use std::collections::HashSet; use std::fs; use std::path::PathBuf; use std::process::Command; use std::time::Instant; use anyhow::{Context, Result, bail}; mod e2e; mod stress; const USAGE: &str = "usage: cargo xtask editor [--dev] | cargo xtask e2e | cargo xtask stress [data|huge|flood|all] [--notes N] [--notebooks N] [--only CASE] [--keep]"; fn main() -> Result<()> { let args: Vec = std::env::args().skip(1).collect(); match args.first().map(String::as_str) { Some("editor") => { let mut dev = false; for arg in &args[1..] { match arg.as_str() { "--dev" => dev = true, other => bail!("unknown argument `{other}`\n{USAGE}"), } } build_editor(!dev) } Some("e2e") => e2e::run(&workspace_root()?, &target_dir()?), Some("stress") => stress::run(&workspace_root()?, &target_dir()?, &args[1..]), _ => bail!("{USAGE}"), } } fn build_editor(release: bool) -> Result<()> { let started = Instant::now(); let root = workspace_root()?; let target = target_dir()?; let cargo = std::env::var("CARGO").unwrap_or_else(|_| "cargo".to_string()); // 1. Build the wasm library. let mut build = Command::new(&cargo); build .args(["build", "-p", "editor", "--lib", "--target", "wasm32-unknown-unknown"]) // SIMD: byte scans (UTF-8 counts, memchr, lz4) on 100 MB notes. Every current browser has it. .env("CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUSTFLAGS", "-C target-feature=+simd128") .current_dir(&root); if release { build.args(["--profile", "editor"]); } let status = build.status().context("failed to spawn cargo build")?; if !status.success() { bail!("cargo build -p editor failed with {status}"); } let profile = if release { "editor" } else { "debug" }; let raw_wasm = target .join("wasm32-unknown-unknown") .join(profile) .join("editor.wasm"); if !raw_wasm.is_file() { bail!("expected wasm at {}", raw_wasm.display()); } // 2. Run wasm-bindgen as a library. let out_dir = target.join("xtask-editor"); fs::create_dir_all(&out_dir)?; wasm_bindgen_cli_support::Bindgen::new() .input_path(&raw_wasm) .web(true)? .typescript(false) .generate(&out_dir) .context("wasm-bindgen generate failed")?; let bg_wasm_path = out_dir.join("editor_bg.wasm"); let glue_path = out_dir.join("editor.js"); // 3. Optimize the wasm in release mode. let mut wasm_bytes = fs::read(&bg_wasm_path) .with_context(|| format!("reading {}", bg_wasm_path.display()))?; if release { let opt_path = out_dir.join("editor_bg.opt.wasm"); // The features rustc's wasm32 target emits by default, plus SIMD. use wasm_opt::Feature; wasm_opt::OptimizationOptions::new_opt_level_3() .enable_feature(Feature::Simd) .enable_feature(Feature::BulkMemory) .enable_feature(Feature::SignExt) .enable_feature(Feature::TruncSat) .enable_feature(Feature::MutableGlobals) .enable_feature(Feature::ReferenceTypes) .enable_feature(Feature::Multivalue) // EDITOR_NAMES=1 (with CARGO_PROFILE_EDITOR_STRIP=false) keeps function names for profiling. .debug_info(std::env::var_os("EDITOR_NAMES").is_some()) .run(&bg_wasm_path, &opt_path) .context("wasm-opt failed")?; wasm_bytes = fs::read(&opt_path)?; } // 4. Content-hash the wasm, then patch and hash the JS glue. let wasm_name = format!("editor-{}.wasm", short_hash(&wasm_bytes)); let glue = fs::read_to_string(&glue_path) .with_context(|| format!("reading {}", glue_path.display()))?; let init_name = default_export_name(&glue)?; let mut js = glue; if !js.ends_with('\n') { js.push('\n'); } js.push_str(&format!( "await {init_name}({{ module_or_path: new URL(\"./{wasm_name}\", import.meta.url) }});\n" )); let js_name = format!("editor-{}.js", short_hash(js.as_bytes())); // 5. Write outputs and manifest into assets/. let assets = root.join("assets"); fs::create_dir_all(&assets)?; let js_path = assets.join(&js_name); let wasm_path = assets.join(&wasm_name); let manifest_path = assets.join("editor.manifest"); fs::write(&js_path, js.as_bytes())?; fs::write(&wasm_path, &wasm_bytes)?; fs::write( &manifest_path, format!("js={js_name}\nwasm={wasm_name}\n"), )?; // 6. Remove older hashed outputs (exact pattern only). let keep: HashSet<&str> = [js_name.as_str(), wasm_name.as_str()].into_iter().collect(); for entry in fs::read_dir(&assets)? { let entry = entry?; let file_name = entry.file_name(); let Some(name) = file_name.to_str() else { continue }; if is_generated_name(name) && !keep.contains(name) && entry.file_type()?.is_file() { fs::remove_file(entry.path()) .with_context(|| format!("removing {}", entry.path().display()))?; println!("removed old output {name}"); } } // 7. Report. println!("init function: {init_name}"); for path in [&js_path, &wasm_path, &manifest_path] { let size = fs::metadata(path)?.len(); println!( "{}\t{} bytes", path.file_name().unwrap_or_default().to_string_lossy(), size ); } println!( "profile: {profile}, elapsed: {:.2}s", started.elapsed().as_secs_f64() ); Ok(()) } fn short_hash(bytes: &[u8]) -> String { let hex = blake3::hash(bytes).to_hex(); hex[..16].to_string() } /// Matches `editor-<16 lowercase hex>.js` or `editor-<16 lowercase hex>.wasm`. fn is_generated_name(name: &str) -> bool { let Some(rest) = name.strip_prefix("editor-") else { return false; }; if rest.len() < 16 { return false; } let (hash, ext) = rest.split_at(16); (ext == ".js" || ext == ".wasm") && hash.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) } /// Finds the name of the default export in the wasm-bindgen glue, e.g. `__wbg_init`. fn default_export_name(glue: &str) -> Result { for line in glue.lines() { // wasm-bindgen web output: `export { initSync, __wbg_init as default };` if let Some(idx) = line.find(" as default") { let name = line[..idx] .rsplit(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '$')) .next() .unwrap_or_default(); if line.trim_start().starts_with("export {") && !name.is_empty() { return Ok(name.to_string()); } } if let Some(rest) = line.strip_prefix("export default ") { let name: String = rest .trim_end_matches(';') .trim() .chars() .take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '$') .collect(); if !name.is_empty() { return Ok(name); } } } bail!("could not find `export default ` in wasm-bindgen output") } fn workspace_root() -> Result { json_field(&cargo_metadata()?, "workspace_root").map(PathBuf::from) } fn target_dir() -> Result { json_field(&cargo_metadata()?, "target_directory").map(PathBuf::from) } fn cargo_metadata() -> Result { let cargo = std::env::var("CARGO").unwrap_or_else(|_| "cargo".to_string()); let output = Command::new(cargo) .args(["metadata", "--format-version", "1", "--no-deps"]) .output() .context("failed to run cargo metadata")?; if !output.status.success() { bail!("cargo metadata failed"); } Ok(String::from_utf8(output.stdout)?) } /// Extracts a top-level string field from cargo metadata JSON without a JSON parser. /// Paths on this machine contain no escape sequences, so a plain scan is enough. fn json_field(json: &str, key: &str) -> Result { let needle = format!("\"{key}\":\""); let start = json .find(&needle) .with_context(|| format!("`{key}` missing from cargo metadata"))? + needle.len(); let end = json[start..] .find('"') .with_context(|| format!("unterminated `{key}`"))?; Ok(json[start..start + end].to_string()) }