pub mod auth;
pub mod context_state;
pub mod share;
#[cfg(feature = "view")]
pub mod ssr;
use laravel::http::{IntoResponse, Json, Request, Response, StatusCode};
use serde::Serialize;
#[cfg(feature = "view")]
use serde_json::Value;
pub use auth::{ClientAuthProjection, ClientAuthUser, ClientGuardState};
pub use context_state::{AppBootConfig, ViewContextState};
pub use share::{ClientShare, InvalidShareKeyError};
pub const HEADER_ENVELOPE: &str = "x-saola-envelope";
pub const HEADER_CLIENT: &str = "x-saola-client";
pub const HEADER_VIEW_REVISION: &str = "x-saola-view-revision";
pub const HEADER_LANGUAGE: &str = "x-saola-language";
pub const HEADER_LANGUAGE_REVISION: &str = "x-saola-language-revision";
pub const HEADER_SAO_RESPONSE: &str = "x-sao-response";
pub const HEADER_ONE_RESPONSE: &str = "x-one-response";
pub fn wants_saola_json(request: &Request) -> bool {
if request.wants_json() {
return true;
}
if header_eq_ignore_ascii_case(request, HEADER_SAO_RESPONSE, "json")
|| header_eq_ignore_ascii_case(request, HEADER_ONE_RESPONSE, "json")
{
return true;
}
request.header(HEADER_CLIENT).is_some()
}
pub fn is_client_v2(request: &Request) -> bool {
request.header(HEADER_CLIENT) == Some("2")
}
fn header_eq_ignore_ascii_case(request: &Request, name: &str, expected: &str) -> bool {
request
.header(name)
.is_some_and(|value| value.trim().eq_ignore_ascii_case(expected))
}
#[derive(Debug, Clone, Serialize)]
struct EnvelopeBody<T> {
data: T,
#[serde(skip_serializing_if = "Option::is_none")]
view: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
auth: Option<ClientAuthProjection>,
}
#[derive(Debug, Clone)]
pub struct Envelope<T> {
data: T,
view: Option<String>,
auth: Option<ClientAuthProjection>,
status: StatusCode,
view_revision: Option<String>,
language_revision: Option<String>,
headers: Vec<(String, String)>,
}
impl<T: Serialize> Envelope<T> {
pub fn new(data: T) -> Self {
Self {
data,
view: None,
auth: None,
status: StatusCode::OK,
view_revision: None,
language_revision: None,
headers: Vec::new(),
}
}
pub fn ok(data: T) -> Self {
Self::new(data)
}
pub fn created(data: T) -> Self {
Self::new(data).status(StatusCode::CREATED)
}
pub fn view(mut self, view_key: impl Into<String>) -> Self {
self.view = Some(view_key.into());
self
}
pub fn auth(mut self, auth: ClientAuthProjection) -> Self {
self.auth = Some(auth);
self
}
pub fn status(mut self, status: StatusCode) -> Self {
self.status = status;
self
}
pub fn view_revision(mut self, revision: impl Into<String>) -> Self {
self.view_revision = Some(revision.into());
self
}
pub fn language_revision(mut self, revision: impl Into<String>) -> Self {
self.language_revision = Some(revision.into());
self
}
pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.headers.push((name.into(), value.into()));
self
}
}
impl<T: Serialize> IntoResponse for Envelope<T> {
fn into_response(self) -> Response {
let body = EnvelopeBody {
data: self.data,
view: self.view,
auth: self.auth,
};
let mut response = Json(body)
.with_status(self.status)
.with_header("content-type", "application/json; charset=utf-8")
.with_header(HEADER_ENVELOPE, "1");
if let Some(rev) = self.view_revision {
response = response.with_header(HEADER_VIEW_REVISION, rev);
}
if let Some(rev) = self.language_revision {
response = response.with_header(HEADER_LANGUAGE_REVISION, rev);
}
for (name, value) in self.headers {
response = response.with_header(name, value);
}
response
}
}
#[derive(Debug, Clone)]
pub struct PageResponse<T> {
view_key: String,
data: T,
shell: String,
boot_config: Option<AppBootConfig>,
title: Option<String>,
locale: String,
context: String,
auth: Option<ClientAuthProjection>,
status: StatusCode,
view_revision: Option<String>,
language_revision: Option<String>,
headers: Vec<(String, String)>,
#[cfg(feature = "view")]
ssr: Option<SsrSpec>,
}
#[cfg(feature = "view")]
#[derive(Debug, Clone)]
struct SsrSpec {
template: String,
site: Option<Value>,
system: Vec<(String, String)>,
container: String,
}
#[derive(Serialize)]
struct ShellViewPayload<T> {
saola_view: String,
saola_data: T,
#[serde(skip_serializing_if = "Option::is_none")]
saola_auth: Option<ClientAuthProjection>,
saola_envelope_json: String,
saola_boot_json: String,
#[serde(skip_serializing_if = "Option::is_none")]
saola_title: Option<String>,
saola_locale: String,
saola_context: String,
#[serde(skip_serializing_if = "Option::is_none")]
saola_ssr_boot_json: Option<String>,
}
impl<T: Serialize> PageResponse<T> {
pub fn new(view_key: impl Into<String>, data: T) -> Self {
Self {
view_key: view_key.into(),
data,
shell: "app".to_owned(),
boot_config: None,
title: None,
locale: "vi".to_owned(),
context: "web".to_owned(),
auth: None,
status: StatusCode::OK,
view_revision: None,
language_revision: None,
headers: Vec::new(),
#[cfg(feature = "view")]
ssr: None,
}
}
#[cfg(feature = "view")]
pub fn ssr(mut self, template: impl Into<String>) -> Self {
self.ssr = Some(SsrSpec { template: template.into(), site: None, system: Vec::new(), container: "#app-root".to_owned() });
self
}
#[cfg(feature = "view")]
pub fn ssr_system(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
if let Some(spec) = self.ssr.as_mut() {
spec.system.push((name.into(), value.into()));
}
self
}
#[cfg(feature = "view")]
pub fn ssr_container(mut self, selector: impl Into<String>) -> Self {
if let Some(spec) = self.ssr.as_mut() {
spec.container = selector.into();
}
self
}
#[cfg(feature = "view")]
pub fn ssr_site(mut self, site: Value) -> Self {
if let Some(spec) = self.ssr.as_mut() {
spec.site = Some(site);
}
self
}
pub fn shell(mut self, template: impl Into<String>) -> Self {
self.shell = template.into();
self
}
pub fn boot_config(mut self, boot_config: AppBootConfig) -> Self {
self.boot_config = Some(boot_config);
self
}
pub fn title(mut self, title: impl Into<String>) -> Self {
self.title = Some(title.into());
self
}
pub fn locale(mut self, locale: impl Into<String>) -> Self {
self.locale = locale.into();
self
}
pub fn context(mut self, context: impl Into<String>) -> Self {
self.context = context.into();
self
}
pub fn auth(mut self, auth: ClientAuthProjection) -> Self {
self.auth = Some(auth);
self
}
pub fn status(mut self, status: StatusCode) -> Self {
self.status = status;
self
}
pub fn view_revision(mut self, revision: impl Into<String>) -> Self {
self.view_revision = Some(revision.into());
self
}
pub fn language_revision(mut self, revision: impl Into<String>) -> Self {
self.language_revision = Some(revision.into());
self
}
pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.headers.push((name.into(), value.into()));
self
}
pub fn into_envelope(self) -> Envelope<T> {
let mut envelope = Envelope::new(self.data)
.view(self.view_key)
.status(self.status);
if let Some(auth) = self.auth {
envelope = envelope.auth(auth);
}
if let Some(rev) = self.view_revision {
envelope = envelope.view_revision(rev);
}
if let Some(rev) = self.language_revision {
envelope = envelope.language_revision(rev);
}
for (k, v) in self.headers {
envelope = envelope.header(k, v);
}
envelope
}
pub fn into_response_for(self, request: &Request) -> Response {
if wants_saola_json(request) {
return self.into_envelope().into_response();
}
let envelope_json = safe_inline_json(&EnvelopeBody {
data: &self.data,
view: Some(self.view_key.clone()),
auth: self.auth.clone(),
});
let boot_json = match &self.boot_config {
Some(boot) => safe_inline_json(boot),
None => safe_inline_json(&AppBootConfig::default()),
};
#[cfg(feature = "view")]
let ssr_out = self.ssr.as_ref().and_then(|spec| {
ssr::render_page(spec.template.as_str(), spec.site.as_ref(), &spec.system, &self.data, &self.view_key, &self.locale, self.auth.as_ref())
.map_err(|e| tracing::error!(error = %e, template = %spec.template, "SSR render failed"))
.ok()
});
#[cfg(feature = "view")]
let ssr_boot_json = match (&self.ssr, &ssr_out) {
(Some(spec), Some(_)) => Some(safe_inline_json(&serde_json::json!({
"container": spec.container,
"view": self.view_key,
"viewId": ssr::root_view_id(&self.view_key),
}))),
_ => None,
};
#[cfg(not(feature = "view"))]
let ssr_boot_json: Option<String> = None;
let payload = ShellViewPayload {
saola_view: self.view_key,
saola_data: self.data,
saola_auth: self.auth,
saola_envelope_json: envelope_json,
saola_boot_json: boot_json,
saola_title: self.title,
saola_locale: self.locale,
saola_context: self.context,
saola_ssr_boot_json: ssr_boot_json,
};
#[allow(unused_mut)]
let mut shell_view = laravel::view::view(self.shell.clone(), payload);
#[cfg(feature = "view")]
if let Some(out) = ssr_out {
shell_view = shell_view.with_html("saola_ssr_html", out.html);
for (key, html) in out.meta {
shell_view = shell_view.with_html(format!("saola_ssr_meta_{key}"), html);
}
}
let mut response = shell_view.with_status(self.status).into_response();
if let Some(rev) = self.view_revision {
response = response.with_header(HEADER_VIEW_REVISION, rev);
}
if let Some(rev) = self.language_revision {
response = response.with_header(HEADER_LANGUAGE_REVISION, rev);
}
for (name, value) in self.headers {
response = response.with_header(name, value);
}
response
}
}
fn safe_inline_json<T: Serialize>(value: &T) -> String {
let raw = serde_json::to_string(value).unwrap_or_else(|_| "{}".to_owned());
let mut escaped = String::with_capacity(raw.len());
for ch in raw.chars() {
match ch {
'<' => escaped.push_str("\\u003c"),
'>' => escaped.push_str("\\u003e"),
'&' => escaped.push_str("\\u0026"),
'\u{2028}' => escaped.push_str("\\u2028"),
'\u{2029}' => escaped.push_str("\\u2029"),
_ => escaped.push(ch),
}
}
escaped
}
pub fn render<T: Serialize>(view_key: impl Into<String>, data: T) -> PageResponse<T> {
PageResponse::new(view_key, data)
}