resuma 0.4.6

Resuma - SSR + Resumability + Islands + Server Actions + JS Bridge for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
//! Server-Side Rendering for Resuma.
//!
//! Two flavours of renderer live here:
//!
//!  * [`render_to_string`] — full page render. Wraps the view in a `<!doctype html>`
//!    document, embeds the resumability payload as a `<script type="resuma/state">…</script>`
//!    block, and injects the bootstrap loader for the tiny client runtime.
//!
//!  * [`render_view`] — partial render. Returns just the HTML for a `View` tree.
//!    Used by the dev server for island-only re-renders.
//!
//! The renderer never executes JavaScript itself. It only walks the tree
//! and writes characters. Everything needed for resumability lives inside
//! the HTML payload it produces.

use std::fmt::Write;
use std::rc::Rc;

use crate::core::{
    context::{page_needs_client, RenderContext, RenderMode, ResumePayload},
    handler::HandlerRef,
    serialize::encode_payload,
    view::{Attr, AttrValue, Child, Element, Fragment, Island, View},
    with_context,
};

mod escape;
pub mod pwa;
pub mod seo;
pub mod stream;
use escape::{escape_attr, escape_text};

pub use stream::{
    build_page_stream, render_stream_parts, render_to_stream, stream_head, stream_placeholder,
    stream_tail, StreamChunk,
};

/// PWA install / theming options injected into `<head>`.
#[derive(Debug, Clone, Default)]
pub struct PwaOptions {
    pub enabled: bool,
    pub name: String,
    pub short_name: String,
    pub description: String,
    pub theme_color: String,
    pub background_color: String,
}

/// Configuration for full-page rendering.
#[derive(Debug, Clone, Default)]
pub struct PageOptions {
    pub title: String,
    pub description: String,
    pub head: String,
    pub lang: String,
    /// Public site origin, e.g. `https://resuma-docs.fly.dev` (no trailing slash).
    pub site_url: String,
    /// Open Graph image path or absolute URL.
    pub og_image: String,
    pub og_type: String,
    /// Optional JSON-LD `<script>` inner JSON (not HTML-escaped).
    pub json_ld: String,
    /// Override canonical URL (absolute). Defaults to `site_url + path`.
    pub canonical: Option<String>,
    /// Progressive Web App options (`manifest`, service worker registration).
    pub pwa: Option<PwaOptions>,
    /// Client bootstrap script. Defaults to `/_resuma/loader.js`.
    pub loader_src: String,
    /// Legacy alias for `loader_src` when set explicitly.
    pub runtime_src: String,
    pub stylesheet: Option<String>,
    /// Per-request CSP nonce for inline resumability script.
    #[doc(hidden)]
    pub csp_nonce: String,
    /// Per-request CSRF token embedded in the state payload.
    #[doc(hidden)]
    pub csrf_token: String,
}

/// Render a complete HTML document for an already-built view (merges payload handlers server-side).
pub fn render_document(opts: &PageOptions, path: &str, view: &View) -> (String, ResumePayload) {
    let (body, payload) = render_body_and_payload(view);
    (wrap_document(opts, &body, &payload, path), payload)
}

/// Render a view that was already built inside an external [`RenderContext`].
pub fn render_prebuilt_document(
    opts: &PageOptions,
    path: &str,
    view: &View,
    payload: &ResumePayload,
) -> String {
    let body = render_view(view);
    wrap_document(opts, &body, payload, path)
}

/// Render a `View` produced by a component to a complete HTML document.
pub fn render_to_string<F>(opts: &PageOptions, build_view: F) -> String
where
    F: FnOnce() -> View,
{
    render_to_string_at_path(opts, "/", build_view)
}

/// Like [`render_to_string`] but sets canonical/OG tags from the request path.
pub fn render_to_string_at_path<F>(opts: &PageOptions, path: &str, build_view: F) -> String
where
    F: FnOnce() -> View,
{
    let ctx = RenderContext::new(RenderMode::Ssr);
    let (body, payload) = with_context(ctx.clone(), || {
        let view = build_view();
        let mut buf = String::new();
        write_view(&mut buf, &view);
        (buf, ctx.snapshot())
    });

    wrap_document(opts, &body, &payload, path)
}

fn loader_src(opts: &PageOptions) -> &str {
    if !opts.runtime_src.is_empty() {
        &opts.runtime_src
    } else if !opts.loader_src.is_empty() {
        &opts.loader_src
    } else {
        "/_resuma/loader.js"
    }
}

pub(crate) fn client_scripts(
    opts: &PageOptions,
    body_html: &str,
    payload: &ResumePayload,
) -> String {
    if !page_needs_client(payload, body_html) {
        return String::new();
    }
    let mut payload = payload.for_client();
    if !opts.csrf_token.is_empty() {
        payload.csrf_token = Some(opts.csrf_token.clone());
    }
    let payload_json = encode_payload(&payload);
    let nonce_attr = if opts.csp_nonce.is_empty() {
        String::new()
    } else {
        format!(r#" nonce="{}""#, escape_attr(&opts.csp_nonce))
    };
    format!(
        r#"<script type="resuma/state" id="resuma-state"{nonce_attr}>{payload}</script>
<script type="module" src="{loader}"{nonce_attr}></script>"#,
        payload = payload_json,
        loader = loader_src(opts),
        nonce_attr = nonce_attr,
    )
}

/// Render a `View` body and capture the resumability payload in one pass.
pub fn render_body_and_payload(view: &View) -> (String, ResumePayload) {
    let ctx = RenderContext::new(RenderMode::Ssr);
    let body = with_context(ctx.clone(), || {
        let mut buf = String::new();
        write_view(&mut buf, view);
        buf
    });
    (body, ctx.snapshot_full())
}

/// Render only the body of a `View`, no document scaffolding.
pub fn render_view(view: &View) -> String {
    let mut buf = String::new();
    write_view(&mut buf, view);
    buf
}

/// Render a view in a context — used by the server when it has its own ctx.
pub fn render_with_context(ctx: Rc<RenderContext>, view: &View) -> String {
    with_context(ctx, || {
        let mut buf = String::new();
        write_view(&mut buf, view);
        buf
    })
}

pub(crate) fn apply_head_csp_nonce(head: &str, nonce: &str) -> String {
    if nonce.is_empty() {
        return head.to_string();
    }
    let nonce_attr = format!(r#" nonce="{}""#, escape_attr(nonce));
    inject_csp_nonce_into_head(head, &nonce_attr)
}

fn inject_csp_nonce_into_head(head: &str, nonce_attr: &str) -> String {
    let mut out = String::with_capacity(head.len() + 64);
    let mut rest = head;
    while let Some(start) = rest.find('<') {
        out.push_str(&rest[..start]);
        rest = &rest[start..];
        let Some(end) = rest.find('>') else {
            out.push_str(rest);
            break;
        };
        let tag = &rest[..=end];
        out.push_str(&inject_nonce_on_tag(tag, nonce_attr));
        rest = &rest[end + 1..];
    }
    out.push_str(rest);
    out
}

fn inject_nonce_on_tag(tag: &str, nonce_attr: &str) -> String {
    let lower = tag.to_ascii_lowercase();
    if !(lower.starts_with("<style") || lower.starts_with("<script")) {
        return tag.to_string();
    }
    if lower.contains("nonce=") {
        return tag.to_string();
    }
    if lower.starts_with("<script") && lower.contains("src=") {
        return tag.to_string();
    }
    if let Some(gt) = tag.rfind('>') {
        format!("{}{}{}", &tag[..gt], nonce_attr, &tag[gt..])
    } else {
        tag.to_string()
    }
}

fn wrap_document(
    opts: &PageOptions,
    body_html: &str,
    payload: &ResumePayload,
    path: &str,
) -> String {
    let lang = if opts.lang.is_empty() {
        "en"
    } else {
        &opts.lang
    };
    let title = seo::page_title(opts, path);
    let description = seo::page_description(opts, path);
    let seo_tags = seo::seo_head_tags(opts, path);
    let json_ld = seo::json_ld_script(&opts.json_ld);
    let stylesheet = opts
        .stylesheet
        .as_ref()
        .map(|s| format!(r#"<link rel="stylesheet" href="{}" />"#, escape_attr(s)))
        .unwrap_or_default();
    let scripts = client_scripts(opts, body_html, payload);
    let dev_script = crate::server::dev::dev_reload_script(&opts.csp_nonce);
    let head = apply_head_csp_nonce(&opts.head, &opts.csp_nonce);

    format!(
        r#"<!doctype html>
<html lang="{lang}">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="description" content="{description}" />
<title>{title}</title>
{json_ld}{seo_tags}
{stylesheet}
{head}
</head>
<body>
<div id="resuma-root">{body}</div>
{scripts}
{dev_script}
</body>
</html>"#,
        lang = lang,
        title = escape_text(&title),
        description = escape_text(&description),
        seo_tags = seo_tags,
        json_ld = json_ld,
        head = head,
        stylesheet = stylesheet,
        body = body_html,
        scripts = scripts,
        dev_script = dev_script,
    )
}

fn write_view(buf: &mut String, view: &View) {
    match view {
        View::Empty => {}
        View::Text(t) => buf.push_str(&escape_text(t)),
        View::Raw(html) => buf.push_str(html),
        View::Dynamic(d) => {
            // SSR-time we render the snapshot value. Wrap in a marker so the
            // runtime knows where to bind reactivity.
            let value = match &d.snapshot {
                serde_json::Value::String(s) => s.clone(),
                other => other.to_string(),
            };
            let formatted = match &d.format {
                Some(fmt) => fmt.replace("{}", &value),
                None => value,
            };
            let _ = write!(
                buf,
                r#"<resuma-dyn data-r-signal="{}">{}</resuma-dyn>"#,
                d.signal,
                escape_text(&formatted)
            );
        }
        View::Element(el) => write_element(buf, el),
        View::Fragment(Fragment { children }) => {
            for c in children {
                write_child(buf, c);
            }
        }
        View::Component(c) => write_view(buf, &c.view),
        View::Island(island) => write_island(buf, island),
        View::Boundary(boundary) => write_boundary(buf, boundary),
        View::Slot(slot) => {
            let resolved = crate::core::resolve_slot(slot.name.as_deref());
            write_view(buf, &resolved);
        }
    }
}

fn write_child(buf: &mut String, child: &Child) {
    match child {
        Child::Text(t) => buf.push_str(&escape_text(t)),
        Child::View(v) => write_view(buf, v),
    }
}

fn write_element(buf: &mut String, el: &Element) {
    let _ = write!(buf, "<{}", el.tag);

    if let Some(id) = &el.dom_id {
        let _ = write!(buf, r#" id="{}""#, escape_attr(id));
    }

    for attr in &el.attrs {
        write_attr(buf, attr);
    }

    if is_void_element(&el.tag) && el.children.is_empty() {
        let _ = write!(buf, " />");
        return;
    }

    let _ = write!(buf, ">");
    for c in &el.children {
        write_child(buf, c);
    }
    let _ = write!(buf, "</{}>", el.tag);
}

fn write_attr(buf: &mut String, attr: &Attr) {
    let name = &attr.name;
    match &attr.value {
        AttrValue::Static(s) => {
            let _ = write!(buf, r#" {}="{}""#, name, escape_attr(s));
        }
        AttrValue::Bool(true) => {
            let _ = write!(buf, " {}", name);
        }
        AttrValue::Bool(false) => {}
        AttrValue::Dynamic { signal, format } => {
            let f = format.as_deref().unwrap_or("{}");
            let _ = write!(
                buf,
                r#" {}="" data-r-bind:{}="{}|{}""#,
                name,
                name,
                signal,
                escape_attr(f)
            );
        }
        AttrValue::Handler(h) => write_handler_attr(buf, h),
        AttrValue::PreventDefault(ev) => {
            let _ = write!(buf, r#" data-r-prevent:{ev}="" "#, ev = ev);
        }
        AttrValue::StopPropagation(ev) => {
            let _ = write!(buf, r#" data-r-stop:{ev}="" "#, ev = ev);
        }
    }
}

fn write_handler_attr(buf: &mut String, h: &HandlerRef) {
    // data-r-on:click="<chunk>#<symbol>" — runtime resolves this lazily.
    let _ = write!(
        buf,
        r#" data-r-on:{ev}="{chunk}#{sym}""#,
        ev = h.event,
        chunk = h.chunk,
        sym = h.symbol,
    );

    if !h.captures.is_empty() {
        // Format: `name:s1,other:s5` — the runtime parses each pair to map
        // the Rust identifier to its stable signal id.
        let captures = h
            .captures
            .iter()
            .map(|c| format!("{}:{}", c.name, c.id))
            .collect::<Vec<_>>()
            .join(",");
        let _ = write!(
            buf,
            r#" data-r-cap:{ev}="{cap}""#,
            ev = h.event,
            cap = captures
        );
    }

    // Handler source lives only in the resumability JSON payload — not duplicated
    // in `data-r-inline:*` attributes. The runtime lazy-compiles on first interaction.
}

fn write_island(buf: &mut String, island: &Island) {
    let signals = island
        .signal_ids
        .iter()
        .map(|s| s.to_string())
        .collect::<Vec<_>>()
        .join(",");
    let props = serde_json::to_string(&island.props).unwrap_or_else(|_| "{}".into());
    let load = match island.load {
        crate::core::view::IslandLoad::Visible => "visible",
        crate::core::view::IslandLoad::Eager => "eager",
    };
    let mut inner = String::new();
    write_view(&mut inner, &island.view);
    crate::server::island_cache::cache_island_html(
        &island.instance_id,
        &inner,
        &island.chunk_id,
        load,
    );
    let _ = write!(
        buf,
        r#"<resuma-island data-r-chunk="{chunk}" data-r-instance="{inst}" data-r-signals="{signals}" data-r-props="{props}" data-r-load="{load}">"#,
        chunk = island.chunk_id,
        inst = island.instance_id,
        signals = signals,
        props = escape_attr(&props),
        load = load,
    );
    buf.push_str(&inner);
    let _ = write!(buf, "</resuma-island>");
}

fn write_boundary(buf: &mut String, boundary: &crate::core::view::Boundary) {
    let _ = write!(
        buf,
        r#"<resuma-boundary data-r-chunk="{chunk}" hidden aria-hidden="true"></resuma-boundary>"#,
        chunk = escape_attr(&boundary.chunk_id),
    );
    write_view(buf, &boundary.view);
}

fn is_void_element(tag: &str) -> bool {
    matches!(
        tag,
        "area"
            | "base"
            | "br"
            | "col"
            | "embed"
            | "hr"
            | "img"
            | "input"
            | "link"
            | "meta"
            | "source"
            | "track"
            | "wbr"
    )
}

#[cfg(test)]
mod head_nonce_tests {
    use super::apply_head_csp_nonce;

    #[test]
    fn injects_nonce_on_inline_style_and_script() {
        let head = r#"<style>.x{color:red}</style><script>console.log(1)</script>"#;
        let out = apply_head_csp_nonce(head, "abc123");
        assert!(out.contains(r#"<style nonce="abc123">"#));
        assert!(out.contains(r#"<script nonce="abc123">"#));
    }

    #[test]
    fn skips_external_script_with_src() {
        let head = r#"<script type="module" src="/static/app.js"></script>"#;
        let out = apply_head_csp_nonce(head, "abc123");
        assert!(!out.contains("nonce="));
    }
}