resuma 1.3.1

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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! Submit HTTP handler + SEO routes (robots, sitemap, OG image).

use std::collections::{BTreeMap, HashMap};

use crate::core::view::View;
use crate::core::ResumaError;
use crate::ssr::escape_text;
use crate::ssr::seo_kit::SeoKit;
use crate::ssr::{render_to_string, PageOptions};
use axum::extract::{ConnectInfo, Form, Path};
use axum::http::{header, HeaderMap, StatusCode, Uri};
use axum::response::{IntoResponse, Response};
use axum::Router;
use std::net::SocketAddr;

use super::middleware::run_middleware;
use super::redirect::{attach_set_cookies, prepare_navigation, redirect_response_with_cookies};
use super::registry::dispatch_submit;
use super::submit::SubmitError;
use crate::server::{
    guard_mutation, http_status, security::config, security::validate_action_name, CSRF_FIELD,
};

#[derive(serde::Serialize, serde::Deserialize, Default)]
pub struct SubmitResponse {
    pub ok: bool,
    pub value: Option<serde_json::Value>,
    pub error: Option<String>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub field_errors: BTreeMap<String, String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub redirect: Option<String>,
}

#[derive(Debug, Clone, Default)]
pub struct FlowSeoConfig {
    pub site_url: String,
    pub paths: Vec<String>,
    /// When set, `/robots.txt` and `/llms.txt` use [`SeoKit`] generators (GEO + AI crawlers).
    pub seo_kit: Option<SeoKit>,
    /// Which auto SEO kit routes to mount (skip paths already registered as pages).
    pub seo_kit_opts: SeoKitRouteOpts,
    /// Static Flow paths omitted from `/sitemap.xml` (aliases, search, noindex URLs).
    pub sitemap_exclude: Vec<String>,
}

/// Which auto-generated SEO text routes to mount (skip paths already registered as pages).
#[derive(Debug, Clone, Copy, Default)]
pub struct SeoKitRouteOpts {
    pub robots: bool,
    pub llms: bool,
}

impl SeoKitRouteOpts {
    pub fn all() -> Self {
        Self {
            robots: true,
            llms: true,
        }
    }
}

const FAVICON_SVG: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" role="img" aria-label="Resuma">
<rect width="32" height="32" rx="6" fill="#712cf9"/>
<text x="16" y="22" text-anchor="middle" fill="#fff" font-family="Segoe UI, system-ui, sans-serif" font-size="18" font-weight="700">R</text>
</svg>"##;

const OG_SVG: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630" role="img" aria-label="Resuma">
<defs>
<linearGradient id="bg" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#712cf9"/>
<stop offset="55%" stop-color="#5a1fd4"/>
<stop offset="100%" stop-color="#0550ae"/>
</linearGradient>
</defs>
<rect width="1200" height="630" fill="url(#bg)"/>
<text x="96" y="250" fill="#ffffff" font-family="Segoe UI, system-ui, sans-serif" font-size="96" font-weight="700">Resuma</text>
<text x="96" y="340" fill="#e9d5ff" font-family="Segoe UI, system-ui, sans-serif" font-size="42">Instantly-interactive Rust — without hydration</text>
<text x="96" y="430" fill="#ddd6fe" font-family="Segoe UI, system-ui, sans-serif" font-size="28">1021 B initial · 9.90 KiB first click · 0 B static pages</text>
</svg>"##;

pub async fn handle_submit(
    Path(name): Path<String>,
    uri: Uri,
    headers: HeaderMap,
    connect: ConnectInfo<SocketAddr>,
    Form(mut form): Form<HashMap<String, String>>,
) -> Response {
    let wants_json = headers
        .get("accept")
        .and_then(|v| v.to_str().ok())
        .map(|s| s.contains("application/json"))
        .unwrap_or(false);

    let cfg = config();
    let host = headers
        .get(header::HOST)
        .and_then(|v| v.to_str().ok())
        .unwrap_or("localhost")
        .to_string();
    let form_csrf = form.remove(CSRF_FIELD);
    let ip = client_ip_from_connect(&headers, &connect);

    if let Err(err) = guard_mutation(
        &headers,
        &host,
        &ip,
        "submit",
        cfg.submits_per_minute,
        form_csrf.as_deref(),
    ) {
        return submit_error(err, wants_json);
    }

    if let Err(err) = validate_action_name(&name) {
        return submit_error(err, wants_json);
    }

    let data = serde_json::to_value(&form).unwrap_or(serde_json::Value::Null);
    // Same input bounds as server actions (payload size / nesting depth) —
    // see `serve_action` in server/app.rs.
    if let Err(err) = crate::exec::security::validate_input(&data) {
        return submit_error(err, wants_json);
    }
    let mut req = super::request::from_http(
        "POST",
        uri.path(),
        &headers,
        BTreeMap::new(),
        BTreeMap::new(),
    );
    super::extensions::global_extensions().merge_into(&mut req);

    match run_middleware(req.clone()).await {
        Ok(r) => req = r,
        Err(e) => return submit_error(e, wants_json),
    }

    match dispatch_submit(&name, data, req).await {
        Ok(mut value) => {
            let (redirect, cookies) = prepare_navigation(&mut value);
            if wants_json {
                let mut res = axum::Json(SubmitResponse {
                    ok: true,
                    value: Some(value),
                    error: None,
                    field_errors: BTreeMap::new(),
                    redirect,
                })
                .into_response();
                attach_set_cookies(&mut res, &cookies);
                res
            } else if let Some(loc) = redirect {
                let referer = headers.get(header::REFERER).and_then(|v| v.to_str().ok());
                let loc = super::redirect::resolve_redirect_location(&loc, referer);
                redirect_response_with_cookies(&loc, &cookies)
            } else {
                let html = render_to_string(
                    &PageOptions {
                        title: "Submitted".into(),
                        ..Default::default()
                    },
                    || View::text("Submitted successfully."),
                );
                let mut res = axum::response::Html(html).into_response();
                attach_set_cookies(&mut res, &cookies);
                res
            }
        }
        Err(err) => {
            let (message, field_errors) = parse_submit_error(&err);
            let status = if field_errors.is_empty() {
                http_status(&err)
            } else {
                StatusCode::UNPROCESSABLE_ENTITY
            };
            if wants_json {
                (
                    status,
                    axum::Json(SubmitResponse {
                        ok: false,
                        value: None,
                        error: Some(message),
                        field_errors,
                        redirect: None,
                    }),
                )
                    .into_response()
            } else {
                let mut body = format!("<p>{}</p>", escape_text(&message));
                if !field_errors.is_empty() {
                    body.push_str("<ul>");
                    for (field, msg) in &field_errors {
                        body.push_str(&format!(
                            "<li><strong>{}</strong>: {}</li>",
                            escape_text(field),
                            escape_text(msg)
                        ));
                    }
                    body.push_str("</ul>");
                }
                let html = render_to_string(
                    &PageOptions {
                        title: "Submission failed".into(),
                        ..Default::default()
                    },
                    || View::raw(body),
                );
                (status, axum::response::Html(html)).into_response()
            }
        }
    }
}

fn parse_submit_error(err: &crate::core::ResumaError) -> (String, BTreeMap<String, String>) {
    if let crate::core::ResumaError::Other(msg) = err {
        if let Ok(se) = serde_json::from_str::<SubmitError>(msg) {
            return (se.message, se.field_errors);
        }
    }
    let cfg = config();
    (err.client_message(cfg.production), BTreeMap::new())
}

fn submit_error(err: ResumaError, wants_json: bool) -> Response {
    let status = http_status(&err);
    let cfg = config();
    let message = err.client_message(cfg.production);
    if wants_json {
        (
            status,
            axum::Json(SubmitResponse {
                ok: false,
                value: None,
                error: Some(message),
                field_errors: BTreeMap::new(),
                redirect: None,
            }),
        )
            .into_response()
    } else {
        (status, message).into_response()
    }
}

fn client_ip_from_connect(headers: &HeaderMap, connect: &ConnectInfo<SocketAddr>) -> String {
    crate::server::client_ip_from_parts(headers, Some(connect.0))
}

fn robots_body(seo: &FlowSeoConfig) -> String {
    if let Some(kit) = &seo.seo_kit {
        return kit.robots_txt();
    }
    let mut body = String::from("User-agent: *\nAllow: /\n");
    let base = seo.site_url.trim_end_matches('/');
    if !base.is_empty() {
        body.push_str("\nSitemap: ");
        body.push_str(base);
        body.push_str("/sitemap.xml\n");
    }
    body
}

/// Mount `/robots.txt` and `/llms.txt` from a [`SeoKit`].
pub fn attach_seo_kit_routes<S>(
    mut router: Router<S>,
    kit: SeoKit,
    opts: SeoKitRouteOpts,
) -> Router<S>
where
    S: Clone + Send + Sync + 'static,
{
    if opts.robots {
        let robots_kit = kit.clone();
        router = router.route(
            "/robots.txt",
            axum::routing::get(move || {
                let body = robots_kit.robots_txt();
                async move { ([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], body) }
            }),
        );
    }
    if opts.llms {
        router = router.route(
            "/llms.txt",
            axum::routing::get(move || {
                let body = kit.llms_txt();
                async move { ([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], body) }
            }),
        );
    }
    router
}

/// Escape text placed inside XML element content (`<loc>` in the sitemap).
fn escape_xml_text(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
}

fn sitemap_xml(seo: &FlowSeoConfig) -> String {
    let base = seo.site_url.trim_end_matches('/');
    let mut paths: Vec<String> = seo
        .paths
        .iter()
        .filter(|p| {
            !p.contains(':')
                && !p.contains('*')
                && !seo.sitemap_exclude.iter().any(|skip| skip == *p)
        })
        .cloned()
        .collect();
    if !paths.iter().any(|p| p == "/") {
        paths.push("/".into());
    }
    paths.sort();
    paths.dedup();

    let mut xml = String::from(r#"<?xml version="1.0" encoding="UTF-8"?>"#);
    xml.push_str(r#"<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">"#);
    for path in paths {
        let priority = if path == "/" { "1.0" } else { "0.8" };
        let changefreq = if path == "/" { "weekly" } else { "monthly" };
        xml.push_str("<url><loc>");
        xml.push_str(&escape_xml_text(base));
        if path == "/" {
            xml.push('/');
        } else {
            xml.push_str(&escape_xml_text(&path));
        }
        xml.push_str("</loc><changefreq>");
        xml.push_str(changefreq);
        xml.push_str("</changefreq><priority>");
        xml.push_str(priority);
        xml.push_str("</priority></url>");
    }
    xml.push_str("</urlset>");
    xml
}

async fn serve_og_image() -> impl IntoResponse {
    (
        [(header::CONTENT_TYPE, "image/svg+xml; charset=utf-8")],
        OG_SVG,
    )
}

async fn serve_favicon() -> impl IntoResponse {
    (
        [(header::CONTENT_TYPE, "image/svg+xml; charset=utf-8")],
        FAVICON_SVG,
    )
}

pub fn attach_flow_routes(router: Router, seo: FlowSeoConfig) -> Router {
    // `ResumaApp::into_router` already mounts SeoKit `/robots.txt` + `/llms.txt`.
    // Mounting them again panics (`Overlapping method route`).
    let router = if seo.seo_kit.is_some() {
        router
    } else {
        let robots_seo = seo.clone();
        router.route(
            "/robots.txt",
            axum::routing::get(move || {
                let body = robots_body(&robots_seo);
                async move { ([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], body) }
            }),
        )
    };
    let sitemap_seo = seo;

    router
        .route(
            "/sitemap.xml",
            axum::routing::get(move || {
                let body = sitemap_xml(&sitemap_seo);
                async move {
                    (
                        [(header::CONTENT_TYPE, "application/xml; charset=utf-8")],
                        body,
                    )
                }
            }),
        )
        .route("/og.svg", axum::routing::get(serve_og_image))
        .route("/favicon.svg", axum::routing::get(serve_favicon))
        .route("/favicon.ico", axum::routing::get(serve_favicon))
        .route("/_resuma/submit/{name}", axum::routing::post(handle_submit))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn sitemap_omits_excluded_and_dynamic_paths() {
        let xml = sitemap_xml(&FlowSeoConfig {
            site_url: "https://example.com".into(),
            paths: vec![
                "/".into(),
                "/docs".into(),
                "/docs/search".into(),
                "/docs/:slug".into(),
            ],
            sitemap_exclude: vec!["/docs/search".into()],
            ..Default::default()
        });
        assert!(xml.contains("https://example.com/</loc>"));
        assert!(xml.contains("https://example.com/docs</loc>"));
        assert!(!xml.contains("/docs/search"));
        assert!(!xml.contains("/docs/:slug"));
    }

    #[test]
    fn seo_kit_flow_routes_do_not_double_mount_robots() {
        let kit = SeoKit::new("Demo", "https://example.com");
        let router = attach_seo_kit_routes(Router::new(), kit.clone(), SeoKitRouteOpts::all());
        let _ = attach_flow_routes(
            router,
            FlowSeoConfig {
                site_url: "https://example.com".into(),
                paths: vec!["/".into()],
                seo_kit: Some(kit),
                seo_kit_opts: SeoKitRouteOpts::all(),
                sitemap_exclude: vec![],
            },
        );
    }
}