resuma 1.3.0

Resuma — resumable SSR Rust web framework: zero hydration, islands, server actions, Flow (Axum).
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
//! # Resuma
//!
//! **SSR + resumability for Rust** — components run on the server only; the browser
//! resumes serialized signals and lazy handler chunks instead of re-hydrating the tree.
//!
//! ## Quick start
//!
//! ```no_run
//! use resuma::prelude::*;
//!
//! #[component]
//! fn Counter() {
//!     let n = signal(0);
//!     view! {
//!         <button onClick={n.update(|v| *v += 1)}>{n}</button>
//!     }
//! }
//!
//! #[tokio::main]
//! async fn main() -> std::io::Result<()> {
//!     ResumaApp::new()
//!         .component("/", Counter)
//!         .serve(ServeOptions::default())
//!         .await
//! }
//! ```
//!
//! Install the CLI: `cargo install resuma`. Narrative guides live at
//! [resuma-docs.fly.dev](https://resuma-docs.fly.dev/docs).
//!
//! ## Resumability model
//!
//! * Every [`#[component]`](component) is a **resumable boundary** — handlers register
//!   under `/_resuma/handler/{Component}.js` and prefetch when the boundary enters the viewport.
//! * [`computed!`](computed), [`effect!`](effect), and [`debounce!`](debounce) translate Rust
//!   closures to client-replayable JS via rs2js (in `resuma-macros`).
//! * Plain [`use_computed`] / [`use_effect`] run on SSR only;
//!   use the macros when the browser must replay derived state or side effects.
//! * [`#[island]`](island) is **optional** — for heavy lazy bundles, `load = "visible"`, or dev HMR.
//!
//! ## Crate layout
//!
//! | Module | Role |
//! |--------|------|
//! | [`core`] | Signals, `View`, [`RenderContext`], [`ResumePayload`] |
//! | [`ssr`] | HTML rendering + embedded resumability payload |
//! | [`mod@server`] | axum HTTP, `ResumaApp`, `/_resuma/*` assets |
//! | [`flow`] | `FlowApp`, file-based pages, `#[load]`, `#[submit]` |
//! | [`realtime`] | WebSocket room/peer/rate-limit primitives for multiplayer apps |
//! | [`router`] | Page discovery scanner |
//! | [`cli`] | `resuma new` / `dev` / `build` (feature `cli`) |
//!
//! Users depend on **`resuma`** only; [`resuma-macros`](https://docs.rs/resuma-macros) is a separate
//! proc-macro crate required by the build.
//!
//! ## Re-exports
//!
//! Most apps start with [`prelude`] (`use resuma::prelude::*`). Macros (`view!`, `#[component]`,
//! `#[server]`, `#[data]`, Flow attributes) and common types are re-exported at the crate root
//! for convenience.

pub mod client;
pub mod core;
pub mod exec;
pub mod flow;
pub mod realtime;
pub mod router;
pub mod server;
pub mod ssr;

#[cfg(feature = "cli")]
pub mod cli;

pub use resuma_macros::{
    component, computed, data, debounce, effect, island, js, layout, load, middleware, server,
    submit, upload, view, worker, Store,
};

pub use crate::client::{
    client_component, client_script_path, client_script_url, content_digest,
    register_client_asset_digest, ClientComponent, CLIENT_SCRIPT_PREFIX,
};

pub use crate::core::view::AttrValue;
pub use crate::core::{
    combine_js, error_boundary, for_signal, match_signal, nav_link, no_serialize, portal,
    provide_context, provide_theme, push_slots, resolve_slot, show, show_signal, signal,
    stream_chunk, stream_slot, theme_css_vars, try_use_context, use_computed, use_computed_with_js,
    use_context, use_debounce, use_effect, use_signal, use_store, use_task, use_theme,
    use_visible_task, use_visible_task_with_captures, visible_task_js, with_default_slot,
    with_view_transition, Child, Component, Computed, ContextId, Effect, FlowRequest, IntoView,
    NoSerialize, ReadSignal, RenderContext, RenderMode, Result, ResumaError, ResumePayload, Signal,
    SlotGuard, SlottedChild, Store, Theme, View, VisibleTaskSpec, WriteSignal,
};

pub use crate::server::{
    build_content_security_policy, configure_security, register_server_action,
    set_action_middleware, CspConfig, ResumaApp, SecurityConfig, ServeOptions, CSRF_FIELD,
    CSRF_HEADER,
};

pub use crate::ssr::seo_kit::{AiCrawlerPolicy, MetaTag, SeoKit};
pub use crate::ssr::{render_to_stream, render_to_string, render_view, PageOptions};

pub use crate::flow::{
    apply_layouts, build_query_href, clear_cookie, collect_public_dir, cookie_value,
    current_location_href, current_request, discover_pages, encode_submit_result, error_page,
    extract_redirect, flash_message, form, invalidate_href, invalidate_href_now, invalidate_link,
    load_boundary, loader_refresh_form, loader_refresh_input, not_found_page, query_nav_link,
    redirect, redirect_with_flash, register_layout, register_loader, register_loader_cache,
    register_middleware, register_stream_chunk, register_stream_loader, register_submit,
    set_cookie, set_current_request, theme_into_pwa, try_use_load, try_use_load_value, use_load,
    with_request,
    CookieOptions, DiscoveredPage, FlowApp, FlowError, FlowExtensions, FlowPageRegistry,
    FlowPwaConfig, FlowServeOptions, FromFlowRequest, LoadValue, LoaderError, Path, PublicAsset,
    PwaShortcut, Query, Redirect, SameSite, SubmitError, SubmitValue,
};

pub use crate::realtime::{
    classify_frame, spawn_ws_writer, InboundFrame, Peer, PeerId, Room, RoomFull, RoomRegistry,
    WsWriter,
};

pub use crate::exec::{
    artifact_get, artifact_put, artifact_put_json, attach_exec_routes, dispatch_tool, durable_get,
    durable_set, enqueue, init_exec, plan as plan_execution, queue_stats, register_tool,
    register_upload, register_worker, resolve_resources, store_upload, take_upload, ArtifactRef,
    ExecutionRecord, FlowEngine, GraphId, GraphSnapshot, PlannerHints, QueueMessage, QueueStats,
    ResourceProfile, Resources, RuntimeChoice, RuntimeTarget, StartWorkerResponse, UploadMeta,
    UploadReceipt, UploadedFile, WorkerContext, WorkerEvent, WorkerMeta, WorkerRegistry,
};

/// CLI entry point (`cargo install resuma`).
#[cfg(feature = "cli")]
pub fn run() -> anyhow::Result<()> {
    crate::cli::run()
}

pub mod prelude {
    //! Convenient re-exports for application code.
    //!
    //! ```rust,ignore
    //! use resuma::prelude::*;
    //! ```
    //!
    //! Includes:
    //!
    //! * **Macros** — [`view!`](crate::view), [`#[component]`](crate::component),
    //!   [`#[server]`](macro@crate::server), [`#[data]`](macro@crate::data), [`computed!`](crate::computed),
    //!   [`effect!`](crate::effect), [`debounce!`](crate::debounce), Flow (`#[load]`, `#[submit]`, …)
    //! * **Components** — [`View`], [`Signal`], [`Component`]
    //! * **Apps** — [`ResumaApp`], [`FlowApp`],
    //!   [`ServeOptions`], [`FlowServeOptions`]
    //! * **SSR** — [`render_to_string`], [`render_view`]
    //! * **Flow runtime** — [`FlowRequest`], [`current_request`],
    //!   [`use_load`], [`form`](crate::form())
    //! * **Client components** — [`ClientComponent`], [`client_component`]
    //!
    //! For low-level types ([`RenderContext`](crate::RenderContext), [`ResumePayload`](crate::ResumePayload)),
    //! import from [`crate::core`].
    pub use super::{
        build_query_href, clear_cookie, client_component, client_script_url, combine_js, component,
        computed, configure_security, cookie_value, current_request, data, debounce, effect,
        error_boundary, error_page, extract_redirect, flash_message, for_signal, form,
        invalidate_href, invalidate_href_now, invalidate_link, island, js, layout, load,
        load_boundary, loader_refresh_form, loader_refresh_input, match_signal, middleware,
        nav_link, not_found_page, portal, provide_context, provide_theme, push_slots,
        query_nav_link, redirect, redirect_with_flash, render_to_string, render_view, resolve_slot,
        server, set_action_middleware, set_cookie, show, signal, stream_slot, submit,
        theme_css_vars, try_use_context, try_use_load, try_use_load_value, upload, use_computed,
        use_computed_with_js, use_context, use_debounce, use_effect, use_load, use_signal,
        use_store, use_task, use_theme, use_visible_task, use_visible_task_with_captures, view,
        visible_task, with_view_transition, worker, AttrValue, Child, ClientComponent, Component,
        Computed, CookieOptions, CspConfig, Effect, FlowApp, FlowError, FlowPageRegistry,
        FlowPwaConfig, FlowRequest, FlowServeOptions, FromFlowRequest, IntoView, LoadValue,
        LoaderError, PageOptions, Path, PublicAsset, PwaShortcut, Query, ReadSignal, Redirect,
        Result, ResumaApp, ResumaError, SameSite, SecurityConfig, ServeOptions, Signal,
        SlottedChild, Store, SubmitError, Theme, View, WriteSignal, CLIENT_SCRIPT_PREFIX,
        CSRF_FIELD, CSRF_HEADER,
    };
}

/// Register a client-only visible task with automatic signal capture wiring.
///
/// ```rust,ignore
/// visible_task!(r#"
///     (async (state, __resuma) => {
///         const next = await __resuma.action("list_todos", []);
///         state.todos.set(next);
///     })
/// "#, todos, ui);
/// ```
#[macro_export]
macro_rules! visible_task {
    ($js:expr $(, $($cap:ident),+ $(,)?)?) => {{
        let mut __caps = ::std::collections::BTreeMap::new();
        $( $(
            __caps.insert(::std::stringify!($cap).to_string(), $cap.id());
        )+ )?
        $crate::use_visible_task_with_captures($js, __caps)
    }};
}

#[doc(hidden)]
pub mod __private {
    //! Re-exports used by the macro-generated code.
    pub use crate::core::effect::{attach_client_effect, use_computed_with_js, use_effect};
    pub use crate::core::task::{register_debounce_effect, use_debounce};
    pub use crate::core::{
        combine_js, for_signal, match_signal, match_static, nav_link, show, show_signal,
    };
    pub use crate::core::{
        context::{current_context, with_handler_chunk, RenderContext, RenderMode},
        handler::{HandlerCapture, HandlerRef},
        signal::SignalId,
        slot::{push_slots, resolve_slot, with_default_slot, SlottedChild},
        view::{AttrValue, Element, Fragment, Island as IslandView},
        Child, Component, IntoView, ReadSignal, Result, ResumaError, Signal, View, WriteSignal,
    };
    pub use crate::flow::form as flow_form;
    pub use crate::server::register_server_action;
    pub use ctor;
    pub use serde;
    pub use serde_json;

    #[derive(Debug, Clone)]
    pub enum HandlerSource {
        Inline(String),
        Chunk {
            chunk: String,
            symbol: String,
            source: String,
        },
    }

    #[derive(Debug, Clone)]
    pub enum ResumeCapture {
        Signal { name: String, id: SignalId },
        Action(String),
    }

    pub use crate::core::view::Element as ElementType;

    pub fn register_handler(
        event: &str,
        _chunk: &str,
        symbol: &str,
        js_source: &str,
        captures: Vec<ResumeCapture>,
        actions: Vec<String>,
    ) -> AttrValue {
        let chunk = current_context()
            .map(|c| c.current_handler_chunk())
            .unwrap_or_else(|| "__page__".to_string());

        if let Some(ctx) = current_context() {
            ctx.register_handler(&chunk, symbol, js_source);
            for a in &actions {
                ctx.register_action(a);
            }
        }

        let signal_captures: Vec<HandlerCapture> = captures
            .into_iter()
            .filter_map(|c| match c {
                ResumeCapture::Signal { name, id } => Some(HandlerCapture { name, id }),
                _ => None,
            })
            .collect();

        let inline = if chunk == "__page__"
            && js_source.len() <= crate::core::context::INLINE_HANDLER_MAX_BYTES
        {
            Some(js_source.to_string())
        } else {
            None
        };

        AttrValue::Handler(HandlerRef {
            event: event.to_string(),
            chunk,
            symbol: symbol.to_string(),
            captures: signal_captures,
            inline,
        })
    }

    pub trait ElementBuilderExt {
        fn attr_runtime(self, kv: (String, AttrValue)) -> Self;
    }

    impl ElementBuilderExt for crate::core::view::ElementBuilder {
        fn attr_runtime(self, (name, value): (String, AttrValue)) -> Self {
            self.attr(name, value)
        }
    }

    pub fn render_component<C: Component>(props: C::Props) -> View {
        C::render(props)
    }

    pub fn resolve_attr_value<T: Into<AttrValueAuto>>(value: T) -> AttrValue {
        value.into().into_attr_value()
    }

    pub struct AttrValueAuto(AttrValue);

    impl AttrValueAuto {
        fn into_attr_value(self) -> AttrValue {
            self.0
        }
    }

    impl From<&str> for AttrValueAuto {
        fn from(s: &str) -> Self {
            Self(AttrValue::Static(s.to_string()))
        }
    }
    impl From<String> for AttrValueAuto {
        fn from(s: String) -> Self {
            Self(AttrValue::Static(s))
        }
    }
    impl From<bool> for AttrValueAuto {
        fn from(b: bool) -> Self {
            Self(AttrValue::Static(b.to_string()))
        }
    }
    impl From<i32> for AttrValueAuto {
        fn from(n: i32) -> Self {
            Self(AttrValue::Static(n.to_string()))
        }
    }
    impl From<i64> for AttrValueAuto {
        fn from(n: i64) -> Self {
            Self(AttrValue::Static(n.to_string()))
        }
    }
    impl From<u32> for AttrValueAuto {
        fn from(n: u32) -> Self {
            Self(AttrValue::Static(n.to_string()))
        }
    }
    impl From<u64> for AttrValueAuto {
        fn from(n: u64) -> Self {
            Self(AttrValue::Static(n.to_string()))
        }
    }
    impl From<f64> for AttrValueAuto {
        fn from(n: f64) -> Self {
            Self(AttrValue::Static(n.to_string()))
        }
    }

    impl<T: Clone + serde::Serialize + 'static> From<&Signal<T>> for AttrValueAuto {
        fn from(s: &Signal<T>) -> Self {
            Self(AttrValue::Dynamic {
                signal: s.id(),
                format: None,
            })
        }
    }
    impl<T: Clone + serde::Serialize + 'static> From<Signal<T>> for AttrValueAuto {
        fn from(s: Signal<T>) -> Self {
            Self(AttrValue::Dynamic {
                signal: s.id(),
                format: None,
            })
        }
    }
    impl<T: Clone + serde::Serialize + Send + Sync + 'static> From<&crate::Computed<T>>
        for AttrValueAuto
    {
        fn from(c: &crate::Computed<T>) -> Self {
            Self(AttrValue::Dynamic {
                signal: c.id(),
                format: None,
            })
        }
    }

    pub fn wrap_in_island(
        name: &str,
        instance: u32,
        build: impl FnOnce() -> View,
        load: &str,
    ) -> View {
        if let Some(ctx) = current_context() {
            ctx.register_island(name);
        }
        let load = match load {
            "visible" | "Visible" => view_mod::IslandLoad::Visible,
            _ => view_mod::IslandLoad::Eager,
        };
        let inner = crate::core::context::with_handler_chunk(name, build);
        View::Island(IslandView {
            chunk_id: name.to_string(),
            instance_id: format!("{}-{}", name, instance),
            signal_ids: Vec::new(),
            view: Box::new(inner),
            props: serde_json::Value::Null,
            load,
        })
    }

    pub use crate::core::view as view_mod;
    pub use crate::core::view::ElementBuilder;

    pub fn fragment(children: Vec<Child>) -> View {
        View::fragment(children)
    }

    pub fn element(tag: &str) -> ElementBuilder {
        View::element(tag)
    }
}