resuma 0.3.1

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
//! Resuma developer CLI — `resuma new`, `resuma dev`, `resuma build`, `resuma routes`.

use std::path::{Path, PathBuf};
use std::process::Command;

use anyhow::{anyhow, Context, Result};
use clap::{Parser, Subcommand};

mod scaffold;

#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
#[command(name = "resuma")]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand, Debug)]
enum Commands {
    /// Create a new Resuma app from a template.
    #[command(alias = "create")]
    New {
        /// Project directory name.
        name: String,
        /// Template: `basic`, `todo`, or `flow` (file-based pages).
        #[arg(long, default_value = "basic")]
        template: String,
    },
    /// Run the app with hot reload.
    Dev {
        /// Bind address (default: 127.0.0.1:3000).
        #[arg(long, default_value = "127.0.0.1:3000")]
        addr: String,
        /// Skip building the JS runtime (useful when prebuilt).
        #[arg(long)]
        skip_runtime: bool,
    },
    /// Build a production binary + JS bundles.
    Build {
        /// Pre-render static HTML for discovered routes into `--out`.
        #[arg(long)]
        static_export: bool,
        /// Output directory for static export (default: `dist`).
        #[arg(long, default_value = "dist")]
        out: PathBuf,
        /// Pages directory for Flow static export route discovery.
        #[arg(long, default_value = "src/pages")]
        pages: PathBuf,
    },
    /// Print or generate routes from file-based routing.
    Routes {
        /// Path to the pages directory (default: `src/pages`).
        #[arg(long, default_value = "src/pages")]
        path: PathBuf,
        /// Generate `src/pages/_registry.rs` scaffold.
        #[arg(long)]
        generate: bool,
    },
}

/// Entry point for the `resuma` binary (`cargo install resuma`).
pub fn run() -> Result<()> {
    tracing_subscriber::fmt::init();

    let args = Cli::parse();
    match args.command {
        Commands::New { name, template } => scaffold::create_project(&name, &template),
        Commands::Dev { addr, skip_runtime } => dev_command(&addr, skip_runtime),
        Commands::Build {
            static_export,
            out,
            pages,
        } => build_command(static_export, &out, &pages),
        Commands::Routes { path, generate } => routes_command(&path, generate),
    }
}

fn dev_command(addr: &str, skip_runtime: bool) -> Result<()> {
    if !skip_runtime {
        ensure_runtime_built()?;
    }

    println!("[resuma] starting dev server at http://{}", addr);
    std::env::set_var("RESUMA_DEV", "1");

    let has_watch = Command::new("cargo")
        .args(["watch", "--version"])
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false);

    let status = if has_watch {
        Command::new("cargo")
            .args(["watch", "-c", "-q", "-x", "run"])
            .env("RESUMA_ADDR", addr)
            .env("RUST_LOG", "info,resuma=debug")
            .status()
            .context("failed to spawn cargo-watch")?
    } else {
        eprintln!("[resuma] cargo-watch not found — install with `cargo install cargo-watch` for hot reload");
        Command::new("cargo")
            .args(["run"])
            .env("RESUMA_ADDR", addr)
            .env("RUST_LOG", "info,resuma=debug")
            .status()
            .context("failed to spawn cargo run")?
    };

    if !status.success() {
        return Err(anyhow!("dev exited with status {:?}", status.code()));
    }
    Ok(())
}

fn build_command(static_export: bool, out: &Path, pages: &Path) -> Result<()> {
    ensure_runtime_built()?;

    println!("[resuma] cargo build --release");
    let status = Command::new("cargo")
        .args(["build", "--release"])
        .status()
        .context("cargo build failed to start")?;
    if !status.success() {
        return Err(anyhow!("cargo build exited with {:?}", status.code()));
    }

    if static_export {
        static_export_routes(out, pages)?;
    }

    println!("[resuma] build complete — binaries at target/release/");
    Ok(())
}

fn static_export_routes(out: &Path, pages: &Path) -> Result<()> {
    use crate::router::discover;
    use crate::ssr::{render_to_string_at_path, PageOptions};

    std::fs::create_dir_all(out).with_context(|| format!("create {}", out.display()))?;

    let routes = discover(pages);
    if routes.is_empty() {
        println!(
            "[resuma] static export: no routes under {}",
            pages.display()
        );
        return Ok(());
    }

    let opts = PageOptions {
        title: "Static Export".into(),
        ..Default::default()
    };

    for route in routes.iter().filter(|r| !r.is_layout) {
        let file_path = if route.pattern == "/" {
            out.join("index.html")
        } else {
            out.join(route.pattern.trim_start_matches('/'))
                .join("index.html")
        };
        if let Some(parent) = file_path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        let pattern = route.pattern.clone();
        let label = pattern.clone();
        let html = render_to_string_at_path(&opts, &pattern, move || {
            crate::core::View::Text(format!(
                "Static export shell for {label} — customize `resuma build --static` with your page factories."
            ))
        });
        std::fs::write(&file_path, html)
            .with_context(|| format!("write {}", file_path.display()))?;
        println!("[resuma] exported {}", route.pattern);
    }

    Ok(())
}

fn ensure_runtime_built() -> Result<()> {
    let runtime_dir = Path::new("runtime");
    if !runtime_dir.exists() {
        return Ok(());
    }

    let pkg_lock = runtime_dir.join("node_modules");
    if !pkg_lock.exists() {
        println!("[resuma] installing runtime dependencies (npm install)");
        let status = Command::new(npm_bin())
            .args(["install"])
            .current_dir(runtime_dir)
            .status();
        if let Ok(s) = status {
            if !s.success() {
                eprintln!("[resuma] npm install failed — continuing with fallback runtime");
                return Ok(());
            }
        }
    }

    println!("[resuma] building JS runtime");
    let status = Command::new(npm_bin())
        .args(["run", "build"])
        .current_dir(runtime_dir)
        .status();
    if let Ok(s) = status {
        if s.success() {
            let assets = [
                ("runtime.js", runtime_dir.join("dist/runtime.js")),
                ("loader.js", runtime_dir.join("dist/loader.js")),
                ("core.js", runtime_dir.join("dist/core.js")),
            ];
            for (name, from) in assets {
                let to = runtime_assets_dir().join(name);
                if from.exists() {
                    if let Some(parent) = to.parent() {
                        std::fs::create_dir_all(parent).ok();
                    }
                    std::fs::copy(&from, &to)
                        .with_context(|| format!("failed to copy {name} to {}", to.display()))?;
                    println!("[resuma] {name} copied to {}", to.display());
                }
            }
        }
    }
    Ok(())
}

fn npm_bin() -> &'static str {
    if cfg!(windows) {
        "npm.cmd"
    } else {
        "npm"
    }
}

/// Where to copy rebuilt JS when developing the Resuma monorepo vs a standalone app.
fn runtime_assets_dir() -> PathBuf {
    let monorepo = Path::new("crates/resuma/assets");
    if monorepo.is_dir() {
        monorepo.to_path_buf()
    } else {
        PathBuf::from(".resuma/assets")
    }
}

fn routes_command(path: &Path, generate: bool) -> Result<()> {
    let routes = crate::router::discover(path);
    if routes.is_empty() {
        println!("[resuma] no routes found under {}", path.display());
        return Ok(());
    }

    let layouts_index: Vec<_> = routes
        .iter()
        .filter(|x| x.is_layout)
        .map(|x| (x.pattern.clone(), x.file.clone()))
        .collect();

    if generate {
        let mod_rs = path.join("mod.rs");
        let registry = path.join("_registry.rs");
        let mod_code = generate_pages_mod(&routes);
        let registry_code = generate_pages_registry(&routes);

        std::fs::write(&mod_rs, mod_code)
            .with_context(|| format!("failed to write {}", mod_rs.display()))?;
        std::fs::write(&registry, registry_code)
            .with_context(|| format!("failed to write {}", registry.display()))?;
        println!(
            "[resuma] generated {} and {}",
            mod_rs.display(),
            registry.display()
        );
    }

    println!("[resuma] discovered routes:");
    for r in &routes {
        let layouts = if r.is_layout {
            Vec::new()
        } else {
            crate::router::layout_chain_for(&r.pattern, &layouts_index)
        };
        println!(
            "  {:<32} → {} ({}{}) layouts={:?}",
            r.pattern,
            r.module,
            r.file.display(),
            if r.is_layout { " layout" } else { "" },
            if r.is_layout {
                Vec::<String>::new()
            } else {
                layouts
            },
        );
    }
    Ok(())
}

use std::collections::BTreeMap;

#[derive(Default)]
struct ModTree {
    children: BTreeMap<String, ModTree>,
    is_module: bool,
}

fn insert_mod_path(tree: &mut ModTree, parts: &[&str]) {
    if parts.is_empty() {
        return;
    }
    let node = tree.children.entry(parts[0].to_string()).or_default();
    if parts.len() == 1 {
        node.is_module = true;
    } else {
        insert_mod_path(node, &parts[1..]);
    }
}

fn emit_mod_tree(tree: &ModTree, depth: usize) -> String {
    let indent = "    ".repeat(depth);
    let mut out = String::new();
    for (name, child) in &tree.children {
        if child.children.is_empty() {
            out.push_str(&format!("{indent}pub mod {name};\n"));
        } else {
            out.push_str(&format!("{indent}pub mod {name} {{\n"));
            out.push_str(&emit_mod_tree(child, depth + 1));
            out.push_str(&format!("{indent}}}\n"));
        }
    }
    out
}

fn generate_pages_mod(routes: &[crate::router::DiscoveredRoute]) -> String {
    let mut tree = ModTree::default();
    for r in routes {
        if r.is_layout || r.module == "_registry" {
            continue;
        }
        let mut mod_path = r.module.clone();
        if r.file
            .file_stem()
            .and_then(|s| s.to_str())
            .is_some_and(|s| s == "index")
            && r.module != "index"
        {
            mod_path = format!("{}::index", r.module);
        }
        let parts: Vec<&str> = mod_path.split("::").collect();
        insert_mod_path(&mut tree, &parts);
    }

    format!(
        "// Auto-generated by `resuma routes --generate`. Do not edit by hand.\n\n\
         {}\n\
         mod _registry;\n\
         pub use _registry::PagesRegistry;\n",
        emit_mod_tree(&tree, 0),
    )
}

fn module_rust_path(route: &crate::router::DiscoveredRoute) -> String {
    let stem = route
        .file
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("");
    if stem == "index" && route.module != "index" {
        format!("super::{}::index", route.module)
    } else {
        format!("super::{}", route.module)
    }
}

fn generate_pages_registry(routes: &[crate::router::DiscoveredRoute]) -> String {
    let mut code = String::from(
        "// Auto-generated by `resuma routes --generate`. Do not edit by hand.\n\
         use resuma::prelude::*;\n\
         use resuma::FlowPageRegistry;\n\n\
         pub struct PagesRegistry;\n\n\
         impl FlowPageRegistry for PagesRegistry {\n\
             fn render(&self, module: &str, req: FlowRequest) -> Option<View> {\n\
                 match module {\n",
    );

    for r in routes {
        if r.is_layout {
            continue;
        }
        let path = module_rust_path(r);
        code.push_str(&format!(
            "            \"{}\" => Some({path}::page(req)),\n",
            r.module,
            path = path,
        ));
    }

    code.push_str(
        "            _ => None,\n\
             }\n\
             }\n\
             }\n",
    );
    code
}