1pub mod auth;
2pub mod context_state;
3pub mod share;
4#[cfg(feature = "view")]
5pub mod ssr;
6
7use laravel::http::{IntoResponse, Json, Request, Response, StatusCode};
8use serde::Serialize;
9#[cfg(feature = "view")]
10use serde_json::Value;
11
12pub use auth::{ClientAuthProjection, ClientAuthUser, ClientGuardState};
13pub use context_state::{AppBootConfig, ViewContextState};
14pub use share::{ClientShare, InvalidShareKeyError};
15
16pub const HEADER_ENVELOPE: &str = "x-saola-envelope";
17pub const HEADER_CLIENT: &str = "x-saola-client";
18pub const HEADER_VIEW_REVISION: &str = "x-saola-view-revision";
19pub const HEADER_LANGUAGE: &str = "x-saola-language";
20pub const HEADER_LANGUAGE_REVISION: &str = "x-saola-language-revision";
21pub const HEADER_SAO_RESPONSE: &str = "x-sao-response";
22pub const HEADER_ONE_RESPONSE: &str = "x-one-response";
23
24pub fn wants_saola_json(request: &Request) -> bool {
26 if request.wants_json() {
27 return true;
28 }
29 if header_eq_ignore_ascii_case(request, HEADER_SAO_RESPONSE, "json")
30 || header_eq_ignore_ascii_case(request, HEADER_ONE_RESPONSE, "json")
31 {
32 return true;
33 }
34 request.header(HEADER_CLIENT).is_some()
35}
36
37pub fn is_client_v2(request: &Request) -> bool {
39 request.header(HEADER_CLIENT) == Some("2")
40}
41
42fn header_eq_ignore_ascii_case(request: &Request, name: &str, expected: &str) -> bool {
43 request
44 .header(name)
45 .is_some_and(|value| value.trim().eq_ignore_ascii_case(expected))
46}
47
48#[derive(Debug, Clone, Serialize)]
49struct EnvelopeBody<T> {
50 data: T,
51 #[serde(skip_serializing_if = "Option::is_none")]
52 view: Option<String>,
53 #[serde(skip_serializing_if = "Option::is_none")]
54 auth: Option<ClientAuthProjection>,
55}
56
57#[derive(Debug, Clone)]
59pub struct Envelope<T> {
60 data: T,
61 view: Option<String>,
62 auth: Option<ClientAuthProjection>,
63 status: StatusCode,
64 view_revision: Option<String>,
65 language_revision: Option<String>,
66 headers: Vec<(String, String)>,
67}
68
69impl<T: Serialize> Envelope<T> {
70 pub fn new(data: T) -> Self {
71 Self {
72 data,
73 view: None,
74 auth: None,
75 status: StatusCode::OK,
76 view_revision: None,
77 language_revision: None,
78 headers: Vec::new(),
79 }
80 }
81
82 pub fn ok(data: T) -> Self {
83 Self::new(data)
84 }
85
86 pub fn created(data: T) -> Self {
87 Self::new(data).status(StatusCode::CREATED)
88 }
89
90 pub fn view(mut self, view_key: impl Into<String>) -> Self {
91 self.view = Some(view_key.into());
92 self
93 }
94
95 pub fn auth(mut self, auth: ClientAuthProjection) -> Self {
96 self.auth = Some(auth);
97 self
98 }
99
100 pub fn status(mut self, status: StatusCode) -> Self {
101 self.status = status;
102 self
103 }
104
105 pub fn view_revision(mut self, revision: impl Into<String>) -> Self {
106 self.view_revision = Some(revision.into());
107 self
108 }
109
110 pub fn language_revision(mut self, revision: impl Into<String>) -> Self {
111 self.language_revision = Some(revision.into());
112 self
113 }
114
115 pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
116 self.headers.push((name.into(), value.into()));
117 self
118 }
119}
120
121impl<T: Serialize> IntoResponse for Envelope<T> {
122 fn into_response(self) -> Response {
123 let body = EnvelopeBody {
124 data: self.data,
125 view: self.view,
126 auth: self.auth,
127 };
128
129 let mut response = Json(body)
130 .with_status(self.status)
131 .with_header("content-type", "application/json; charset=utf-8")
132 .with_header(HEADER_ENVELOPE, "1");
133
134 if let Some(rev) = self.view_revision {
135 response = response.with_header(HEADER_VIEW_REVISION, rev);
136 }
137 if let Some(rev) = self.language_revision {
138 response = response.with_header(HEADER_LANGUAGE_REVISION, rev);
139 }
140 for (name, value) in self.headers {
141 response = response.with_header(name, value);
142 }
143
144 response
145 }
146}
147
148#[derive(Debug, Clone)]
151pub struct PageResponse<T> {
152 view_key: String,
153 data: T,
154 shell: String,
155 boot_config: Option<AppBootConfig>,
156 title: Option<String>,
157 locale: String,
158 context: String,
159 auth: Option<ClientAuthProjection>,
160 status: StatusCode,
161 view_revision: Option<String>,
162 language_revision: Option<String>,
163 headers: Vec<(String, String)>,
164 #[cfg(feature = "view")]
165 ssr: Option<SsrSpec>,
166}
167
168#[cfg(feature = "view")]
169#[derive(Debug, Clone)]
170struct SsrSpec {
171 template: String,
172 site: Option<Value>,
173 system: Vec<(String, String)>,
174 container: String,
175}
176
177#[derive(Serialize)]
178struct ShellViewPayload<T> {
179 saola_view: String,
180 saola_data: T,
181 #[serde(skip_serializing_if = "Option::is_none")]
182 saola_auth: Option<ClientAuthProjection>,
183 saola_envelope_json: String,
184 saola_boot_json: String,
185 #[serde(skip_serializing_if = "Option::is_none")]
186 saola_title: Option<String>,
187 saola_locale: String,
188 saola_context: String,
189 #[serde(skip_serializing_if = "Option::is_none")]
191 saola_ssr_boot_json: Option<String>,
192}
193
194impl<T: Serialize> PageResponse<T> {
195 pub fn new(view_key: impl Into<String>, data: T) -> Self {
196 Self {
197 view_key: view_key.into(),
198 data,
199 shell: "app".to_owned(),
200 boot_config: None,
201 title: None,
202 locale: "vi".to_owned(),
203 context: "web".to_owned(),
204 auth: None,
205 status: StatusCode::OK,
206 view_revision: None,
207 language_revision: None,
208 headers: Vec::new(),
209 #[cfg(feature = "view")]
210 ssr: None,
211 }
212 }
213
214 #[cfg(feature = "view")]
218 pub fn ssr(mut self, template: impl Into<String>) -> Self {
219 self.ssr = Some(SsrSpec { template: template.into(), site: None, system: Vec::new(), container: "#app-root".to_owned() });
220 self
221 }
222
223 #[cfg(feature = "view")]
226 pub fn ssr_system(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
227 if let Some(spec) = self.ssr.as_mut() {
228 spec.system.push((name.into(), value.into()));
229 }
230 self
231 }
232
233 #[cfg(feature = "view")]
235 pub fn ssr_container(mut self, selector: impl Into<String>) -> Self {
236 if let Some(spec) = self.ssr.as_mut() {
237 spec.container = selector.into();
238 }
239 self
240 }
241
242 #[cfg(feature = "view")]
244 pub fn ssr_site(mut self, site: Value) -> Self {
245 if let Some(spec) = self.ssr.as_mut() {
246 spec.site = Some(site);
247 }
248 self
249 }
250
251 pub fn shell(mut self, template: impl Into<String>) -> Self {
252 self.shell = template.into();
253 self
254 }
255
256 pub fn boot_config(mut self, boot_config: AppBootConfig) -> Self {
257 self.boot_config = Some(boot_config);
258 self
259 }
260
261 pub fn title(mut self, title: impl Into<String>) -> Self {
262 self.title = Some(title.into());
263 self
264 }
265
266 pub fn locale(mut self, locale: impl Into<String>) -> Self {
267 self.locale = locale.into();
268 self
269 }
270
271 pub fn context(mut self, context: impl Into<String>) -> Self {
272 self.context = context.into();
273 self
274 }
275
276 pub fn auth(mut self, auth: ClientAuthProjection) -> Self {
277 self.auth = Some(auth);
278 self
279 }
280
281 pub fn status(mut self, status: StatusCode) -> Self {
282 self.status = status;
283 self
284 }
285
286 pub fn view_revision(mut self, revision: impl Into<String>) -> Self {
287 self.view_revision = Some(revision.into());
288 self
289 }
290
291 pub fn language_revision(mut self, revision: impl Into<String>) -> Self {
292 self.language_revision = Some(revision.into());
293 self
294 }
295
296 pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
297 self.headers.push((name.into(), value.into()));
298 self
299 }
300
301 pub fn into_envelope(self) -> Envelope<T> {
302 let mut envelope = Envelope::new(self.data)
303 .view(self.view_key)
304 .status(self.status);
305 if let Some(auth) = self.auth {
306 envelope = envelope.auth(auth);
307 }
308 if let Some(rev) = self.view_revision {
309 envelope = envelope.view_revision(rev);
310 }
311 if let Some(rev) = self.language_revision {
312 envelope = envelope.language_revision(rev);
313 }
314 for (k, v) in self.headers {
315 envelope = envelope.header(k, v);
316 }
317 envelope
318 }
319
320 pub fn into_response_for(self, request: &Request) -> Response {
321 if wants_saola_json(request) {
322 return self.into_envelope().into_response();
323 }
324
325 let envelope_json = safe_inline_json(&EnvelopeBody {
326 data: &self.data,
327 view: Some(self.view_key.clone()),
328 auth: self.auth.clone(),
329 });
330
331 let boot_json = match &self.boot_config {
332 Some(boot) => safe_inline_json(boot),
333 None => safe_inline_json(&AppBootConfig::default()),
334 };
335
336 #[cfg(feature = "view")]
338 let ssr_out = self.ssr.as_ref().and_then(|spec| {
339 ssr::render_page(spec.template.as_str(), spec.site.as_ref(), &spec.system, &self.data, &self.view_key, &self.locale, self.auth.as_ref())
340 .map_err(|e| tracing::error!(error = %e, template = %spec.template, "SSR render failed"))
341 .ok()
342 });
343
344 #[cfg(feature = "view")]
345 let ssr_boot_json = match (&self.ssr, &ssr_out) {
346 (Some(spec), Some(_)) => Some(safe_inline_json(&serde_json::json!({
347 "container": spec.container,
348 "view": self.view_key,
349 "viewId": ssr::root_view_id(&self.view_key),
350 }))),
351 _ => None,
352 };
353 #[cfg(not(feature = "view"))]
354 let ssr_boot_json: Option<String> = None;
355
356 let payload = ShellViewPayload {
357 saola_view: self.view_key,
358 saola_data: self.data,
359 saola_auth: self.auth,
360 saola_envelope_json: envelope_json,
361 saola_boot_json: boot_json,
362 saola_title: self.title,
363 saola_locale: self.locale,
364 saola_context: self.context,
365 saola_ssr_boot_json: ssr_boot_json,
366 };
367
368 #[allow(unused_mut)]
369 let mut shell_view = laravel::view::view(self.shell.clone(), payload);
370 #[cfg(feature = "view")]
371 if let Some(out) = ssr_out {
372 shell_view = shell_view.with_html("saola_ssr_html", out.html);
373 for (key, html) in out.meta {
374 shell_view = shell_view.with_html(format!("saola_ssr_meta_{key}"), html);
375 }
376 }
377 let mut response = shell_view.with_status(self.status).into_response();
378
379 if let Some(rev) = self.view_revision {
380 response = response.with_header(HEADER_VIEW_REVISION, rev);
381 }
382 if let Some(rev) = self.language_revision {
383 response = response.with_header(HEADER_LANGUAGE_REVISION, rev);
384 }
385 for (name, value) in self.headers {
386 response = response.with_header(name, value);
387 }
388
389 response
390 }
391}
392
393fn safe_inline_json<T: Serialize>(value: &T) -> String {
394 let raw = serde_json::to_string(value).unwrap_or_else(|_| "{}".to_owned());
395 let mut escaped = String::with_capacity(raw.len());
396 for ch in raw.chars() {
397 match ch {
398 '<' => escaped.push_str("\\u003c"),
399 '>' => escaped.push_str("\\u003e"),
400 '&' => escaped.push_str("\\u0026"),
401 '\u{2028}' => escaped.push_str("\\u2028"),
402 '\u{2029}' => escaped.push_str("\\u2029"),
403 _ => escaped.push(ch),
404 }
405 }
406 escaped
407}
408
409pub fn render<T: Serialize>(view_key: impl Into<String>, data: T) -> PageResponse<T> {
411 PageResponse::new(view_key, data)
412}