Skip to main content

wabot_ui_bundler/
lib.rs

1//! # wabot-ui-bundler
2//!
3//! Build-time bundler for **Preact (or any JSX) islands**, for apps
4//! that want real components in the browser while Rust keeps rendering
5//! every page. Port of the discovery + entry-generation half of
6//! wabot-ts's `UiBundler`, delegating the actual bundling to esbuild.
7//!
8//! This is a **build dependency**, not a runtime one — nothing here
9//! ends up in your binary.
10//!
11//! ```ignore
12//! // build.rs
13//! fn main() {
14//!     wabot_ui_bundler::IslandBundler::new("islands", "static/islands")
15//!         .public_base("/static/islands")
16//!         .run_or_warn();
17//! }
18//! ```
19//!
20//! ```ignore
21//! // src/main.rs — ids and module URLs, checked by the compiler
22//! include!(concat!(env!("OUT_DIR"), "/islands.rs"));
23//!
24//! island_module(islands::CLICKS_ID, islands::CLICKS_MODULE, &props, html! { … })
25//! ```
26//!
27//! ## What it does
28//!
29//! 1. Finds `*.island.tsx` / `*.island.jsx` under the source directory.
30//! 2. Derives a stable id from the filename: `NotesForm.island.tsx` →
31//!    `notes-form`. That id is what the Rust view passes to `island()`
32//!    and what the generated entry registers, so the two always agree.
33//! 3. Writes one entry per island that hydrates the default export into
34//!    its `<wabot-island>` host and returns a teardown.
35//! 4. Runs esbuild over all entries with code splitting, so Preact
36//!    itself lands in one shared chunk instead of being copied into
37//!    every island.
38//! 5. Emits `islands.rs` with an id + module-URL constant per island,
39//!    so renaming a `.tsx` file breaks the Rust build instead of
40//!    silently producing a dead island.
41//!
42//! ## Degrading without Node
43//!
44//! [`IslandBundler::run_or_warn`] turns a missing toolchain into a
45//! `cargo:warning` rather than a failed build, so a checkout without
46//! Node still compiles — you just need the previously-built bundles
47//! present (committing them is reasonable for an example or a
48//! deploy artifact).
49
50use std::fmt::Write as _;
51use std::fs;
52use std::path::{Path, PathBuf};
53use std::process::Command;
54
55use sha2::Digest;
56use thiserror::Error;
57
58pub mod css;
59pub use css::{CssModule, CssModuleBundler};
60
61#[derive(Debug, Error)]
62pub enum BundleError {
63    #[error("island source directory {0} does not exist")]
64    MissingSourceDir(PathBuf),
65    #[error("io error: {0}")]
66    Io(#[from] std::io::Error),
67    #[error("could not run esbuild ({command}): {source}")]
68    EsbuildSpawn {
69        command: String,
70        source: std::io::Error,
71    },
72    #[error("esbuild failed:\n{0}")]
73    Esbuild(String),
74    #[error("css error: {0}")]
75    Css(String),
76    #[error("{0}")]
77    Other(String),
78    #[error("two island files map to the same id `{id}`: {first} and {second}")]
79    DuplicateId {
80        id: String,
81        first: PathBuf,
82        second: PathBuf,
83    },
84}
85
86/// One discovered island source file.
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub struct Island {
89    /// Stable id — what `island("…")` takes in Rust and what the
90    /// generated entry registers with `wabot.island`.
91    pub id: String,
92    /// Absolute path to the `.island.tsx` file.
93    pub source: PathBuf,
94    /// Rust constant stem, e.g. `NOTES_FORM`.
95    pub const_stem: String,
96}
97
98/// What a successful run produced.
99#[derive(Debug, Clone)]
100pub struct BundleReport {
101    pub islands: Vec<Island>,
102    /// Where the generated Rust constants were written, if requested.
103    pub constants_path: Option<PathBuf>,
104}
105
106pub struct IslandBundler {
107    source_dir: PathBuf,
108    out_dir: PathBuf,
109    public_base: String,
110    jsx_import_source: String,
111    minify: bool,
112    sourcemap: bool,
113    constants_file: Option<PathBuf>,
114    esbuild: Vec<String>,
115    work_dir: Option<PathBuf>,
116}
117
118impl IslandBundler {
119    /// `source_dir` holds the `*.island.tsx` files; `out_dir` receives
120    /// the bundles. Both are relative to the crate root when relative.
121    pub fn new(source_dir: impl Into<PathBuf>, out_dir: impl Into<PathBuf>) -> Self {
122        Self {
123            source_dir: source_dir.into(),
124            out_dir: out_dir.into(),
125            public_base: "/islands".to_string(),
126            jsx_import_source: "preact".to_string(),
127            minify: true,
128            sourcemap: false,
129            constants_file: Some(PathBuf::from("islands.rs")),
130            // `npx esbuild` works whether esbuild is a local devDependency
131            // or not installed at all (npx fetches it).
132            esbuild: vec!["npx".into(), "--yes".into(), "esbuild".into()],
133            work_dir: None,
134        }
135    }
136
137    /// Where generated entries and constants are written. Defaults to
138    /// `OUT_DIR`, which is what a build script wants; set it explicitly
139    /// when driving the bundler outside cargo (tests, a CLI).
140    pub fn work_dir(mut self, dir: impl Into<PathBuf>) -> Self {
141        self.work_dir = Some(dir.into());
142        self
143    }
144
145    /// URL prefix the bundles are served from, used for the generated
146    /// `*_MODULE` constants. Default `/islands`.
147    pub fn public_base(mut self, base: impl Into<String>) -> Self {
148        self.public_base = base.into();
149        self
150    }
151
152    /// JSX runtime to compile against. Default `preact`; use `react`
153    /// for React components.
154    pub fn jsx_import_source(mut self, source: impl Into<String>) -> Self {
155        self.jsx_import_source = source.into();
156        self
157    }
158
159    pub fn minify(mut self, minify: bool) -> Self {
160        self.minify = minify;
161        self
162    }
163
164    pub fn sourcemap(mut self, sourcemap: bool) -> Self {
165        self.sourcemap = sourcemap;
166        self
167    }
168
169    /// Filename for the generated constants, written into `OUT_DIR`.
170    /// `None` skips generation.
171    pub fn constants_file(mut self, name: Option<impl Into<PathBuf>>) -> Self {
172        self.constants_file = name.map(Into::into);
173        self
174    }
175
176    /// Override how esbuild is invoked — e.g.
177    /// `["./node_modules/.bin/esbuild"]` to pin the local install.
178    pub fn esbuild_command(mut self, command: Vec<String>) -> Self {
179        self.esbuild = command;
180        self
181    }
182
183    /// Discover, generate entries, bundle, and emit constants.
184    pub fn run(&self) -> Result<BundleReport, BundleError> {
185        let islands = self.discover()?;
186        self.emit_rerun_directives(&islands);
187
188        let constants_path = match &self.constants_file {
189            Some(name) => Some(self.write_constants(&islands, name)?),
190            None => None,
191        };
192
193        if islands.is_empty() {
194            return Ok(BundleReport {
195                islands,
196                constants_path,
197            });
198        }
199
200        let entries = self.write_entries(&islands)?;
201        self.run_esbuild(&entries)?;
202
203        Ok(BundleReport {
204            islands,
205            constants_path,
206        })
207    }
208
209    /// [`IslandBundler::run`], but a missing or failing toolchain
210    /// becomes a `cargo:warning` instead of a build failure. Constants
211    /// are still emitted, so the Rust side compiles either way.
212    pub fn run_or_warn(&self) -> Option<BundleReport> {
213        match self.run() {
214            Ok(report) => Some(report),
215            Err(e) => {
216                // `cargo:warning=` is one line each, and esbuild's
217                // diagnostics are multi-line — split them so a failure
218                // is actually readable in the build output.
219                for line in format!("island bundling skipped: {e}").lines() {
220                    println!("cargo:warning={line}");
221                }
222                println!(
223                    "cargo:warning=the previously-built bundles in {} will be used",
224                    self.out_dir.display()
225                );
226                // Still emit constants so `include!` doesn't break.
227                if let Some(name) = &self.constants_file {
228                    if let Ok(islands) = self.discover() {
229                        let _ = self.write_constants(&islands, name);
230                    }
231                }
232                None
233            }
234        }
235    }
236
237    // ---------- steps ---------------------------------------------------
238
239    fn discover(&self) -> Result<Vec<Island>, BundleError> {
240        let dir = self.abs(&self.source_dir);
241        if !dir.is_dir() {
242            return Err(BundleError::MissingSourceDir(dir));
243        }
244        let mut found: Vec<Island> = Vec::new();
245        collect(&dir, &mut found)?;
246        found.sort_by(|a, b| a.id.cmp(&b.id));
247
248        // Ids come from filenames, so two directories can collide.
249        // Fail loudly: a silent collision would mean one island never
250        // hydrates.
251        for pair in found.windows(2) {
252            if pair[0].id == pair[1].id {
253                return Err(BundleError::DuplicateId {
254                    id: pair[0].id.clone(),
255                    first: pair[0].source.clone(),
256                    second: pair[1].source.clone(),
257                });
258            }
259        }
260        Ok(found)
261    }
262
263    fn write_entries(&self, islands: &[Island]) -> Result<Vec<PathBuf>, BundleError> {
264        let entry_dir = self.resolved_work_dir().join("entries");
265        fs::create_dir_all(&entry_dir)?;
266        let mut entries = Vec::with_capacity(islands.len());
267
268        for island in islands {
269            let entry = entry_dir.join(format!("{}.js", island.id));
270            let import_path = island.source.to_string_lossy().replace('\\', "/");
271            // The mount signature is wabot's: return a teardown so the
272            // nav runtime can unmount the island when its host leaves
273            // the DOM.
274            let contents = format!(
275                "// generated by wabot-ui-bundler — do not edit\n\
276                 import {{ h, hydrate, render }} from 'preact';\n\
277                 import Component from '{import_path}';\n\
278                 \n\
279                 window.wabot.island('{id}', (el, props) => {{\n\
280                 \x20 hydrate(h(Component, props), el);\n\
281                 \x20 return () => render(null, el);\n\
282                 }});\n",
283                id = island.id
284            );
285            fs::write(&entry, contents)?;
286            entries.push(entry);
287        }
288        Ok(entries)
289    }
290
291    fn run_esbuild(&self, entries: &[PathBuf]) -> Result<(), BundleError> {
292        let out = self.abs(&self.out_dir);
293        fs::create_dir_all(&out)?;
294
295        let (program, leading) = self
296            .esbuild
297            .split_first()
298            .expect("esbuild command must not be empty");
299
300        let mut command = Command::new(program);
301        command.args(leading);
302        for entry in entries {
303            command.arg(entry);
304        }
305        command
306            .arg("--bundle")
307            // Splitting keeps Preact in one shared chunk rather than
308            // copying it into every island bundle.
309            .arg("--splitting")
310            .arg("--format=esm")
311            .arg(format!("--outdir={}", out.display()))
312            .arg("--jsx=automatic")
313            .arg(format!("--jsx-import-source={}", self.jsx_import_source))
314            .arg("--target=es2020")
315            .arg("--log-level=warning");
316        if self.minify {
317            command.arg("--minify");
318        }
319        if self.sourcemap {
320            command.arg("--sourcemap");
321        }
322        // The generated entries live in OUT_DIR, so Node's walk-up
323        // resolution never reaches the crate's node_modules. NODE_PATH
324        // points esbuild at it explicitly (esbuild honours it; its
325        // `--node-paths` flag doesn't exist).
326        command.current_dir(self.crate_root());
327        command.env("NODE_PATH", self.crate_root().join("node_modules"));
328
329        let output = command
330            .output()
331            .map_err(|source| BundleError::EsbuildSpawn {
332                command: self.esbuild.join(" "),
333                source,
334            })?;
335
336        if !output.status.success() {
337            let mut message = String::from_utf8_lossy(&output.stderr).to_string();
338            if message.trim().is_empty() {
339                message = String::from_utf8_lossy(&output.stdout).to_string();
340            }
341            return Err(BundleError::Esbuild(message));
342        }
343        Ok(())
344    }
345
346    fn write_constants(&self, islands: &[Island], name: &Path) -> Result<PathBuf, BundleError> {
347        let path = self.resolved_work_dir().join(name);
348        if let Some(parent) = path.parent() {
349            fs::create_dir_all(parent)?;
350        }
351
352        let mut out = String::new();
353        out.push_str(
354            "// generated by wabot-ui-bundler — do not edit\n\
355             /// Island ids and module URLs, one pair per `*.island.tsx`\n\
356             /// file. Referencing a renamed or deleted island is a\n\
357             /// compile error rather than a silently dead element.\n\
358             #[allow(dead_code)]\n\
359             pub mod islands {\n",
360        );
361        for island in islands {
362            let base = self.public_base.trim_end_matches('/');
363            let _ = writeln!(
364                out,
365                "    /// `{}`\n    pub const {}_ID: &str = \"{}\";\n    \
366                 pub const {}_MODULE: &str = \"{}/{}.js\";",
367                island
368                    .source
369                    .file_name()
370                    .map(|n| n.to_string_lossy().to_string())
371                    .unwrap_or_default(),
372                island.const_stem,
373                island.id,
374                island.const_stem,
375                base,
376                island.id
377            );
378        }
379        out.push_str("}\n");
380
381        fs::write(&path, out)?;
382        Ok(path)
383    }
384
385    fn emit_rerun_directives(&self, islands: &[Island]) {
386        println!(
387            "cargo:rerun-if-changed={}",
388            self.abs(&self.source_dir).display()
389        );
390        for island in islands {
391            println!("cargo:rerun-if-changed={}", island.source.display());
392        }
393    }
394
395    // ---------- paths -----------------------------------------------------
396
397    fn crate_root(&self) -> PathBuf {
398        std::env::var("CARGO_MANIFEST_DIR")
399            .map(PathBuf::from)
400            .unwrap_or_else(|_| PathBuf::from("."))
401    }
402
403    /// Where generated files go: the explicit override, else `OUT_DIR`
404    /// under cargo, else a temp dir.
405    fn resolved_work_dir(&self) -> PathBuf {
406        if let Some(dir) = &self.work_dir {
407            return dir.clone();
408        }
409        std::env::var("OUT_DIR")
410            .map(PathBuf::from)
411            .unwrap_or_else(|_| std::env::temp_dir().join("wabot-ui-bundler"))
412    }
413
414    fn abs(&self, path: &Path) -> PathBuf {
415        if path.is_absolute() {
416            path.to_path_buf()
417        } else {
418            self.crate_root().join(path)
419        }
420    }
421}
422
423fn collect(dir: &Path, found: &mut Vec<Island>) -> Result<(), BundleError> {
424    collect_kind(dir, found, "island")
425}
426
427fn collect_kind(dir: &Path, found: &mut Vec<Island>, kind: &str) -> Result<(), BundleError> {
428    for entry in fs::read_dir(dir)? {
429        let path = entry?.path();
430        if path.is_dir() {
431            collect_kind(&path, found, kind)?;
432            continue;
433        }
434        let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
435            continue;
436        };
437        if let Some(stem) = stem_for(name, kind) {
438            found.push(Island {
439                id: kebab_case(stem),
440                const_stem: screaming_case(stem),
441                source: path,
442            });
443        }
444    }
445    Ok(())
446}
447
448/// `Counter.island.tsx` → `Some("Counter")`; anything else → `None`.
449pub fn island_stem(file_name: &str) -> Option<&str> {
450    stem_for(file_name, "island")
451}
452
453/// `Dashboard.view.tsx` → `Some("Dashboard")`. Server-rendered views,
454/// as opposed to client islands.
455pub fn view_stem(file_name: &str) -> Option<&str> {
456    stem_for(file_name, "view")
457}
458
459fn stem_for<'a>(file_name: &'a str, kind: &str) -> Option<&'a str> {
460    for ext in ["tsx", "jsx", "ts", "js"] {
461        let suffix = format!(".{kind}.{ext}");
462        if let Some(stem) = file_name.strip_suffix(&suffix) {
463            return (!stem.is_empty()).then_some(stem);
464        }
465    }
466    None
467}
468
469/// `NotesForm` → `notes-form`, `HTTPStatus` → `http-status`.
470pub fn kebab_case(name: &str) -> String {
471    separated(name, '-').to_lowercase()
472}
473
474/// `NotesForm` → `NOTES_FORM`.
475pub fn screaming_case(name: &str) -> String {
476    separated(name, '_').to_uppercase()
477}
478
479fn separated(name: &str, sep: char) -> String {
480    let chars: Vec<char> = name.chars().collect();
481    let mut out = String::with_capacity(name.len() + 4);
482    for (i, &c) in chars.iter().enumerate() {
483        if c == '-' || c == '_' || c == ' ' {
484            if !out.ends_with(sep) && !out.is_empty() {
485                out.push(sep);
486            }
487            continue;
488        }
489        let starts_word = i > 0
490            && c.is_uppercase()
491            // `notesForm` -> notes-form, and `HTTPStatus` -> http-status
492            // (uppercase run followed by a lowercase starts a new word).
493            && (!chars[i - 1].is_uppercase()
494                || chars.get(i + 1).is_some_and(|n| n.is_lowercase()));
495        if starts_word && !out.ends_with(sep) {
496            out.push(sep);
497        }
498        out.push(c);
499    }
500    out
501}
502
503#[cfg(test)]
504mod tests {
505    use super::*;
506
507    #[test]
508    fn recognizes_island_files_only() {
509        assert_eq!(island_stem("Counter.island.tsx"), Some("Counter"));
510        assert_eq!(island_stem("NotesForm.island.jsx"), Some("NotesForm"));
511        assert_eq!(island_stem("helper.ts"), None);
512        assert_eq!(island_stem("Counter.tsx"), None);
513        assert_eq!(
514            island_stem(".island.tsx"),
515            None,
516            "empty stem is not an island"
517        );
518    }
519
520    #[test]
521    fn ids_are_kebab_case() {
522        assert_eq!(kebab_case("Counter"), "counter");
523        assert_eq!(kebab_case("NotesForm"), "notes-form");
524        assert_eq!(kebab_case("notesForm"), "notes-form");
525        assert_eq!(kebab_case("notes_form"), "notes-form");
526        assert_eq!(kebab_case("HTTPStatus"), "http-status");
527        assert_eq!(kebab_case("clock"), "clock");
528    }
529
530    #[test]
531    fn constants_are_screaming_snake() {
532        assert_eq!(screaming_case("Counter"), "COUNTER");
533        assert_eq!(screaming_case("NotesForm"), "NOTES_FORM");
534        assert_eq!(screaming_case("HTTPStatus"), "HTTP_STATUS");
535    }
536
537    #[test]
538    fn a_missing_source_directory_is_an_error_not_a_panic() {
539        let bundler = IslandBundler::new("/definitely/not/here", "/tmp/out");
540        assert!(matches!(
541            bundler.run(),
542            Err(BundleError::MissingSourceDir(_))
543        ));
544    }
545}
546
547// ---------- server-side views ------------------------------------------
548
549/// Bundles `*.view.tsx` into **one** JavaScript file that QuickJS
550/// evaluates at startup, exposing `__wabot_render(view, propsJson)`.
551///
552/// This is the server-rendering half of the TSX story: a view written
553/// as a Preact component renders to HTML inside the binary, with no
554/// Node at run time and no WASM. Islands (`*.island.tsx`) are the
555/// client half and use [`IslandBundler`] instead.
556///
557/// ```ignore
558/// // build.rs
559/// wabot_ui_bundler::ViewBundler::new("views")
560///     .run_or_warn();
561/// ```
562///
563/// ```ignore
564/// // main.rs
565/// wabot::ui::tsx::install(include_str!(concat!(env!("OUT_DIR"), "/views.js")));
566/// include!(concat!(env!("OUT_DIR"), "/views.rs"));   // view-name constants
567/// ```
568///
569/// The output goes to `OUT_DIR` and is `include_str!`'d into the
570/// binary, so a release build is one self-contained executable.
571pub struct ViewBundler {
572    source_dir: PathBuf,
573    bundle_name: PathBuf,
574    constants_file: Option<PathBuf>,
575    jsx_import_source: String,
576    minify: bool,
577    esbuild: Vec<String>,
578    work_dir: Option<PathBuf>,
579    dev_entry: Option<PathBuf>,
580}
581
582impl ViewBundler {
583    pub fn new(source_dir: impl Into<PathBuf>) -> Self {
584        Self {
585            source_dir: source_dir.into(),
586            bundle_name: PathBuf::from("views.js"),
587            constants_file: Some(PathBuf::from("views.rs")),
588            jsx_import_source: "preact".to_string(),
589            minify: true,
590            esbuild: vec!["npx".into(), "--yes".into(), "esbuild".into()],
591            work_dir: None,
592            dev_entry: None,
593        }
594    }
595
596    /// Filename of the bundle inside `OUT_DIR`. Default `views.js`.
597    pub fn bundle_name(mut self, name: impl Into<PathBuf>) -> Self {
598        self.bundle_name = name.into();
599        self
600    }
601
602    pub fn constants_file(mut self, name: Option<impl Into<PathBuf>>) -> Self {
603        self.constants_file = name.map(Into::into);
604        self
605    }
606
607    pub fn jsx_import_source(mut self, source: impl Into<String>) -> Self {
608        self.jsx_import_source = source.into();
609        self
610    }
611
612    pub fn minify(mut self, minify: bool) -> Self {
613        self.minify = minify;
614        self
615    }
616
617    pub fn esbuild_command(mut self, command: Vec<String>) -> Self {
618        self.esbuild = command;
619        self
620    }
621
622    pub fn work_dir(mut self, dir: impl Into<PathBuf>) -> Self {
623        self.work_dir = Some(dir.into());
624        self
625    }
626
627    /// Also write the generated entry to a stable path, so
628    /// `esbuild --watch` can be pointed at it for development.
629    ///
630    /// The entry imports every view by absolute path, so esbuild
631    /// watches the `.tsx` files through it and rewrites the bundle on
632    /// each save — which is what `tsx::install_watched` reloads.
633    ///
634    /// ```sh
635    /// npx esbuild dev/entry.js --bundle --format=iife --target=es2020 \
636    ///   --jsx=automatic --jsx-import-source=preact \
637    ///   --outfile=dev/views.js --watch
638    /// ```
639    pub fn dev_entry(mut self, path: impl Into<PathBuf>) -> Self {
640        self.dev_entry = Some(path.into());
641        self
642    }
643
644    pub fn run(&self) -> Result<BundleReport, BundleError> {
645        let views = self.discover()?;
646        println!(
647            "cargo:rerun-if-changed={}",
648            self.abs(&self.source_dir).display()
649        );
650        for view in &views {
651            println!("cargo:rerun-if-changed={}", view.source.display());
652        }
653
654        let constants_path = match &self.constants_file {
655            Some(name) => Some(self.write_constants(&views, name)?),
656            None => None,
657        };
658
659        // Always emit a bundle, even with no views: `install` +
660        // `include_str!` shouldn't fail to compile on an empty project.
661        let entry = self.write_entry(&views)?;
662        if let Some(dev_entry) = &self.dev_entry {
663            let target = self.abs(dev_entry);
664            if let Some(parent) = target.parent() {
665                fs::create_dir_all(parent)?;
666            }
667            fs::copy(&entry, &target)?;
668        }
669        self.run_esbuild(&entry)?;
670
671        Ok(BundleReport {
672            islands: views,
673            constants_path,
674        })
675    }
676
677    /// [`ViewBundler::run`], downgrading a missing toolchain to a
678    /// `cargo:warning`. The bundle from a previous build is reused.
679    pub fn run_or_warn(&self) -> Option<BundleReport> {
680        match self.run() {
681            Ok(report) => Some(report),
682            Err(e) => {
683                for line in format!("TSX view bundling skipped: {e}").lines() {
684                    println!("cargo:warning={line}");
685                }
686                if let Some(name) = &self.constants_file {
687                    if let Ok(views) = self.discover() {
688                        let _ = self.write_constants(&views, name);
689                    }
690                }
691                // An empty stub keeps `include_str!` compiling.
692                let bundle = self.resolved_work_dir().join(&self.bundle_name);
693                if !bundle.exists() {
694                    let _ = fs::create_dir_all(self.resolved_work_dir());
695                    let _ = fs::write(
696                        &bundle,
697                        "globalThis.__wabot_render = function () {\n  \
698                         throw new Error('TSX views were not bundled: no Node toolchain at build time');\n\
699                         };\n",
700                    );
701                }
702                None
703            }
704        }
705    }
706
707    fn discover(&self) -> Result<Vec<Island>, BundleError> {
708        let dir = self.abs(&self.source_dir);
709        if !dir.is_dir() {
710            return Err(BundleError::MissingSourceDir(dir));
711        }
712        let mut found = Vec::new();
713        collect_kind(&dir, &mut found, "view")?;
714        found.sort_by(|a, b| a.id.cmp(&b.id));
715        for pair in found.windows(2) {
716            if pair[0].id == pair[1].id {
717                return Err(BundleError::DuplicateId {
718                    id: pair[0].id.clone(),
719                    first: pair[0].source.clone(),
720                    second: pair[1].source.clone(),
721                });
722            }
723        }
724        Ok(found)
725    }
726
727    /// One entry importing every view and exposing the render function
728    /// QuickJS calls.
729    fn write_entry(&self, views: &[Island]) -> Result<PathBuf, BundleError> {
730        let dir = self.resolved_work_dir().join("view-entry");
731        fs::create_dir_all(&dir)?;
732        let entry = dir.join("entry.js");
733
734        let mut imports = String::new();
735        let mut registry = String::new();
736        for (index, view) in views.iter().enumerate() {
737            let path = view.source.to_string_lossy().replace('\\', "/");
738            let _ = writeln!(imports, "import __v{index} from '{path}';");
739            let _ = writeln!(registry, "  {:?}: __v{index},", view.id);
740        }
741
742        let contents = format!(
743            "// generated by wabot-ui-bundler — do not edit\n\
744             import {{ h }} from 'preact';\n\
745             import {{ render }} from 'preact-render-to-string';\n\
746             {imports}\n\
747             const views = {{\n{registry}}};\n\
748             \n\
749             // The single entry point the Rust side calls. Props arrive\n\
750             // as JSON because that is the cheapest thing to pass across\n\
751             // the QuickJS boundary.\n\
752             globalThis.{RENDER_ENTRY} = function (name, propsJson) {{\n\
753             \x20 const View = views[name];\n\
754             \x20 if (!View) {{\n\
755             \x20   throw new Error('unknown view: ' + name + ' (known: ' + Object.keys(views).join(', ') + ')');\n\
756             \x20 }}\n\
757             \x20 return render(h(View, propsJson ? JSON.parse(propsJson) : {{}}));\n\
758             }};\n"
759        );
760        fs::write(&entry, contents)?;
761        Ok(entry)
762    }
763
764    fn run_esbuild(&self, entry: &Path) -> Result<(), BundleError> {
765        let out = self.resolved_work_dir().join(&self.bundle_name);
766        if let Some(parent) = out.parent() {
767            fs::create_dir_all(parent)?;
768        }
769
770        let (program, leading) = self
771            .esbuild
772            .split_first()
773            .expect("esbuild command must not be empty");
774        let mut command = Command::new(program);
775        command.args(leading);
776        command
777            .arg(entry)
778            .arg("--bundle")
779            // IIFE, not ESM: QuickJS evaluates this as a plain script,
780            // and the bundle's only export is the global it assigns.
781            .arg("--format=iife")
782            .arg(format!("--outfile={}", out.display()))
783            .arg("--jsx=automatic")
784            .arg(format!("--jsx-import-source={}", self.jsx_import_source))
785            // QuickJS implements ES2020; newer syntax would fail to parse.
786            .arg("--target=es2020")
787            // No DOM in QuickJS — fail loudly at build time if a view
788            // reaches for browser globals rather than at render time.
789            .arg("--platform=neutral")
790            .arg("--log-level=warning");
791        if self.minify {
792            command.arg("--minify");
793        }
794        command.current_dir(self.crate_root());
795        command.env("NODE_PATH", self.crate_root().join("node_modules"));
796
797        let output = command
798            .output()
799            .map_err(|source| BundleError::EsbuildSpawn {
800                command: self.esbuild.join(" "),
801                source,
802            })?;
803        if !output.status.success() {
804            let mut message = String::from_utf8_lossy(&output.stderr).to_string();
805            if message.trim().is_empty() {
806                message = String::from_utf8_lossy(&output.stdout).to_string();
807            }
808            return Err(BundleError::Esbuild(message));
809        }
810        Ok(())
811    }
812
813    fn write_constants(&self, views: &[Island], name: &Path) -> Result<PathBuf, BundleError> {
814        let path = self.resolved_work_dir().join(name);
815        if let Some(parent) = path.parent() {
816            fs::create_dir_all(parent)?;
817        }
818        let mut out = String::new();
819        out.push_str(
820            "// generated by wabot-ui-bundler — do not edit\n\
821             /// Names of the server-rendered TSX views, one per\n\
822             /// `*.view.tsx`. Renaming a file breaks the Rust build\n\
823             /// instead of failing at render time with `unknown view`.\n\
824             #[allow(dead_code)]\n\
825             pub mod views {\n",
826        );
827        for view in views {
828            let _ = writeln!(
829                out,
830                "    /// `{}`\n    pub const {}: &str = \"{}\";",
831                view.source
832                    .file_name()
833                    .map(|n| n.to_string_lossy().to_string())
834                    .unwrap_or_default(),
835                view.const_stem,
836                view.id
837            );
838        }
839        out.push_str("}\n");
840        fs::write(&path, out)?;
841        Ok(path)
842    }
843
844    fn crate_root(&self) -> PathBuf {
845        std::env::var("CARGO_MANIFEST_DIR")
846            .map(PathBuf::from)
847            .unwrap_or_else(|_| PathBuf::from("."))
848    }
849
850    fn resolved_work_dir(&self) -> PathBuf {
851        if let Some(dir) = &self.work_dir {
852            return dir.clone();
853        }
854        std::env::var("OUT_DIR")
855            .map(PathBuf::from)
856            .unwrap_or_else(|_| std::env::temp_dir().join("wabot-ui-bundler"))
857    }
858
859    fn abs(&self, path: &Path) -> PathBuf {
860        if path.is_absolute() {
861            path.to_path_buf()
862        } else {
863            self.crate_root().join(path)
864        }
865    }
866}
867
868/// Must match `wabot_feature_ui_controller::tsx::RENDER_ENTRY`.
869const RENDER_ENTRY: &str = "__wabot_render";
870
871/// Default path to the asset type in generated manifests.
872const DEFAULT_ASSET_TYPE: &str = "::wabot_feature_ui_controller::assets::EmbeddedAsset";
873
874// ---------- embedding assets in the binary ------------------------------
875
876/// Walks a directory at build time and generates a Rust manifest that
877/// `include_bytes!`s every file, so the binary carries its own assets.
878///
879/// That is what makes a wabot app a **single executable**: no
880/// `static/` next to the binary, nothing to copy at deploy time.
881///
882/// ```ignore
883/// // build.rs — bundle islands into OUT_DIR, then embed everything
884/// let out = std::path::PathBuf::from(std::env::var("OUT_DIR").unwrap());
885/// IslandBundler::new("islands", out.join("islands"))
886///     .public_base("/static/islands")
887///     .run_or_warn();
888/// AssetEmbedder::new("static")           // hand-written css, images…
889///     .also(out.join("islands"), "islands")   // …plus the built bundles
890///     .run()
891///     .expect("embed assets");
892/// ```
893///
894/// ```ignore
895/// // main.rs
896/// include!(concat!(env!("OUT_DIR"), "/assets.rs"));
897/// let router = ui_router().merge(embedded_assets("/static", ASSETS));
898/// ```
899pub struct AssetEmbedder {
900    roots: Vec<(PathBuf, String)>,
901    output: PathBuf,
902    constant: String,
903    asset_type: String,
904    work_dir: Option<PathBuf>,
905}
906
907impl AssetEmbedder {
908    /// Embed everything under `dir`, mounted at the manifest's root.
909    pub fn new(dir: impl Into<PathBuf>) -> Self {
910        Self {
911            roots: vec![(dir.into(), String::new())],
912            output: PathBuf::from("assets.rs"),
913            constant: "ASSETS".to_string(),
914            asset_type: DEFAULT_ASSET_TYPE.to_string(),
915            work_dir: None,
916        }
917    }
918
919    /// Start with no directories — add them all with [`Self::also`].
920    pub fn empty() -> Self {
921        Self {
922            roots: Vec::new(),
923            output: PathBuf::from("assets.rs"),
924            constant: "ASSETS".to_string(),
925            asset_type: DEFAULT_ASSET_TYPE.to_string(),
926            work_dir: None,
927        }
928    }
929
930    /// Add another directory, served under `prefix`.
931    pub fn also(mut self, dir: impl Into<PathBuf>, prefix: impl Into<String>) -> Self {
932        self.roots.push((dir.into(), prefix.into()));
933        self
934    }
935
936    /// Filename of the generated manifest inside `OUT_DIR`.
937    pub fn output(mut self, name: impl Into<PathBuf>) -> Self {
938        self.output = name.into();
939        self
940    }
941
942    /// Name of the generated constant. Default `ASSETS`.
943    pub fn constant(mut self, name: impl Into<String>) -> Self {
944        self.constant = name.into();
945        self
946    }
947
948    /// Path the generated manifest uses for the asset type. Defaults
949    /// to the feature crate; an app depending on the `wabot` umbrella
950    /// wants `"::wabot::ui::assets::EmbeddedAsset"` instead, since it
951    /// doesn't name the inner crate in its Cargo.toml.
952    pub fn asset_type(mut self, path: impl Into<String>) -> Self {
953        self.asset_type = path.into();
954        self
955    }
956
957    pub fn work_dir(mut self, dir: impl Into<PathBuf>) -> Self {
958        self.work_dir = Some(dir.into());
959        self
960    }
961
962    /// Generate the manifest. Missing directories are skipped with a
963    /// warning rather than failing the build — an app may legitimately
964    /// have no hand-written assets.
965    pub fn run(&self) -> Result<PathBuf, BundleError> {
966        let mut entries: Vec<(String, PathBuf)> = Vec::new();
967
968        for (dir, prefix) in &self.roots {
969            let dir = self.abs(dir);
970            if !dir.is_dir() {
971                println!(
972                    "cargo:warning=asset directory {} does not exist; skipping",
973                    dir.display()
974                );
975                continue;
976            }
977            println!("cargo:rerun-if-changed={}", dir.display());
978            collect_files(&dir, &dir, prefix, &mut entries)?;
979        }
980        entries.sort_by(|a, b| a.0.cmp(&b.0));
981
982        let mut out = String::new();
983        out.push_str(&format!(
984            "// generated by wabot-ui-bundler — do not edit\n\
985             /// Every static asset, compiled into the binary. Serve with\n\
986             /// `embedded_assets(\"/static\", {name})`.\n\
987             #[allow(dead_code)]\n\
988             pub static {name}: &[{ty}] = &[\n",
989            name = self.constant,
990            ty = self.asset_type
991        ));
992
993        for (path, file) in &entries {
994            println!("cargo:rerun-if-changed={}", file.display());
995            let bytes = fs::read(file)?;
996            let etag = format!("\"{}\"", &hex::encode(sha2::Sha256::digest(&bytes))[..32]);
997            let _ = writeln!(
998                out,
999                "    {ty} {{\n\
1000                 \x20       path: {path:?},\n\
1001                 \x20       bytes: include_bytes!({file:?}),\n\
1002                 \x20       content_type: {ct:?},\n\
1003                 \x20       etag: {etag:?},\n\
1004                 \x20   }},",
1005                ty = self.asset_type,
1006                path = path,
1007                file = file.to_string_lossy(),
1008                ct = content_type_for(path),
1009                etag = etag,
1010            );
1011        }
1012        out.push_str("];\n");
1013
1014        let target = self.resolved_work_dir().join(&self.output);
1015        if let Some(parent) = target.parent() {
1016            fs::create_dir_all(parent)?;
1017        }
1018        fs::write(&target, out)?;
1019        Ok(target)
1020    }
1021
1022    fn crate_root(&self) -> PathBuf {
1023        std::env::var("CARGO_MANIFEST_DIR")
1024            .map(PathBuf::from)
1025            .unwrap_or_else(|_| PathBuf::from("."))
1026    }
1027
1028    fn resolved_work_dir(&self) -> PathBuf {
1029        if let Some(dir) = &self.work_dir {
1030            return dir.clone();
1031        }
1032        std::env::var("OUT_DIR")
1033            .map(PathBuf::from)
1034            .unwrap_or_else(|_| std::env::temp_dir().join("wabot-ui-bundler"))
1035    }
1036
1037    fn abs(&self, path: &Path) -> PathBuf {
1038        if path.is_absolute() {
1039            path.to_path_buf()
1040        } else {
1041            self.crate_root().join(path)
1042        }
1043    }
1044}
1045
1046fn collect_files(
1047    root: &Path,
1048    dir: &Path,
1049    prefix: &str,
1050    out: &mut Vec<(String, PathBuf)>,
1051) -> Result<(), BundleError> {
1052    for entry in fs::read_dir(dir)? {
1053        let path = entry?.path();
1054        if path.is_dir() {
1055            collect_files(root, &path, prefix, out)?;
1056            continue;
1057        }
1058        // Editor and OS droppings have no business in the binary.
1059        let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
1060        if name.starts_with('.') || name.ends_with('~') {
1061            continue;
1062        }
1063        let relative = path
1064            .strip_prefix(root)
1065            .unwrap_or(&path)
1066            .to_string_lossy()
1067            .replace('\\', "/");
1068        let served = if prefix.is_empty() {
1069            relative
1070        } else {
1071            format!("{}/{relative}", prefix.trim_matches('/'))
1072        };
1073        out.push((served, path));
1074    }
1075    Ok(())
1076}
1077
1078/// MIME type for an asset path. Mirrors
1079/// `wabot_feature_ui_controller::assets::content_type_for` — kept here
1080/// so the build script needs no runtime dependency on that crate.
1081fn content_type_for(path: &str) -> &'static str {
1082    let ext = path.rsplit('.').next().unwrap_or("").to_ascii_lowercase();
1083    match ext.as_str() {
1084        "html" | "htm" => "text/html; charset=utf-8",
1085        "css" => "text/css; charset=utf-8",
1086        "js" | "mjs" => "text/javascript; charset=utf-8",
1087        "json" | "map" => "application/json",
1088        "svg" => "image/svg+xml",
1089        "png" => "image/png",
1090        "jpg" | "jpeg" => "image/jpeg",
1091        "gif" => "image/gif",
1092        "webp" => "image/webp",
1093        "avif" => "image/avif",
1094        "ico" => "image/x-icon",
1095        "woff" => "font/woff",
1096        "woff2" => "font/woff2",
1097        "ttf" => "font/ttf",
1098        "otf" => "font/otf",
1099        "txt" => "text/plain; charset=utf-8",
1100        "xml" => "application/xml",
1101        "pdf" => "application/pdf",
1102        "wasm" => "application/wasm",
1103        _ => "application/octet-stream",
1104    }
1105}