Skip to main content

js2rust_bridge/
lib.rs

1// js2rust-bridge: Facade crate for the js2rust_bridge! proc-macro.
2//
3// Users only need to depend on this single crate:
4//
5// ```toml
6// [dependencies]
7// js2rust-bridge = "0.3"
8// [build-dependencies]
9// js2rust-bridge = "0.3"
10// ```
11//
12// The macro transpiles JS to Zig and generates Rust FFI bindings in one step.
13// Call `js2rust_bridge::build()` from your `build.rs` to transpile, compile,
14// and link the Zig static libraries.  The proc-macro detects an up-to-date cache
15// and skips re-transpilation automatically.
16//
17// Both `js2rust_bridge!()` and `build()` read from a single `js2rust.toml`
18// in the crate root — no duplicated configuration.
19//
20// `build()` emits `cargo:rerun-if-changed` directives for every JS source
21// file, the `js2rust.toml` config, and the build cache, so Cargo automatically
22// re-runs the build script when any input changes.
23
24mod config;
25#[cfg(feature = "icu")]
26pub mod native_icu;
27#[cfg(feature = "regex")]
28pub mod native_regex;
29pub mod sdk;
30
31pub use js2rust_bridge_macro::{host_fn, js2rust_bridge};
32
33// Re-export types needed for host function configuration from js2zig-core
34// so users only need `js2rust-bridge` in their `[build-dependencies]`.
35pub use js2zig_core::{HostConfig, HostFunction, HostType};
36
37// Re-export config types for programmatic use.
38pub use config::{BuildSection, HostFnToml, Js2rustConfig, ProjectSection};
39
40use std::path::PathBuf;
41
42/// Build: transpile JS → Zig, compile Zig static library, and emit linker directives.
43///
44/// Reads configuration from `js2rust.toml` in the crate root.  Call this from
45/// your `build.rs` with zero arguments:
46///
47/// ```rust,ignore
48/// fn main() {
49///     js2rust_bridge::build();
50/// }
51/// ```
52///
53/// The project name is derived automatically from the file stem of the first
54/// entry in `project.js_files`. Build behavior (force_rebuild, run_zig_build)
55/// is read from the `[build]` section of `js2rust.toml`.
56pub fn build() {
57    let config = Js2rustConfig::from_manifest_dir();
58    let manifest_dir =
59        std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR must be set by Cargo");
60    let cache_dir = PathBuf::from(&manifest_dir).join(".js2zig-cache");
61
62    // All JS files are resolved from config (entry + additional roots)
63    let js_dir: PathBuf = PathBuf::from(&manifest_dir).join(&config.project.js_dir);
64    let js_files = &config.project.js_files;
65
66    // Emit cargo:rerun-if-changed for explicitly listed JS files and config.
67    // Note: js2zig-core::transpile_project() additionally emits rerun-if-changed
68    // for every JS file it discovers via import analysis (including transitive
69    // dependencies like helpers.js).  Those directives take effect in subsequent
70    // builds because Cargo stores all rerun-if-changed paths from the previous
71    // build script run.
72    for f in js_files {
73        let p = js_dir.join(f);
74        println!("cargo:rerun-if-changed={}", p.display());
75    }
76    let config_toml = PathBuf::from(&manifest_dir).join("js2rust.toml");
77    println!("cargo:rerun-if-changed={}", config_toml.display());
78    // Watch the diagnostics tracking file so Cargo re-runs the build script
79    // when it is first created or changes.  This ensures the build script
80    // produces a CLEAN output (no cargo:warning) on the next run after the
81    // initial diagnostic emission, preventing Cargo from replaying stale
82    // warnings on cached builds.
83    let diagnostics_file = cache_dir.join(".last_emitted_diagnostics.json");
84    println!("cargo:rerun-if-changed={}", diagnostics_file.display());
85
86    // Derive js_dir and js_files for ProjectConfig from TOML fields.
87    // js_dir is an absolute path (manifest_dir + config.project.js_dir);
88    // js_files are plain filenames from TOML.
89    let js_dir_abs = js_dir.clone();
90    let js_files_vec: Vec<String> = js_files.clone();
91
92    let host_config = config.to_host_config();
93
94    // Determine Zig optimization level: TOML override > Cargo PROFILE auto-detect.
95    let zig_optimize = config.build.zig_optimize.clone().unwrap_or_else(|| {
96        let profile = std::env::var("PROFILE").unwrap_or_else(|_| "debug".into());
97        if profile == "release" {
98            "ReleaseSafe".into()
99        } else {
100            "Debug".into()
101        }
102    });
103
104    let project_config = js2zig_core::ProjectConfig {
105        js_dir: js_dir_abs,
106        js_files: js_files_vec,
107        out_dir: cache_dir.clone(),
108        host_config,
109        build: js2zig_core::BuildConfig {
110            force_rebuild: config.build.force_rebuild,
111            run_zig_build: config.build.run_zig_build,
112            zig_optimize: Some(zig_optimize),
113            is_build_script: true, // build.rs context — show progress + emit rerun-if-changed
114        },
115    };
116    match js2zig_core::transpile_project(&project_config) {
117        Ok(result) => {
118            // Emit compile errors as cargo:warning — but only when they CHANGE.
119            // Cargo replays cargo:warning from the previous build script run,
120            // so if we always emit them the user sees the same warnings on every
121            // build.  By tracking the last-emitted set and only emitting new/
122            // changed diagnostics, we produce a clean build script output once
123            // the diagnostics stabilize, and Cargo will replay that clean output
124            // on subsequent cached builds.
125            let compile_errors: Vec<&str> = result
126                .diagnostics
127                .iter()
128                .filter(|d| d.contains("COMPILE_ERROR"))
129                .map(|s| s.as_str())
130                .collect();
131
132            let last_emitted_path = cache_dir.join(".last_emitted_diagnostics.json");
133            let last_emitted: Vec<String> = std::fs::read_to_string(&last_emitted_path)
134                .ok()
135                .and_then(|s| serde_json::from_str(&s).ok())
136                .unwrap_or_default();
137
138            // Only emit warnings for diagnostics that differ from the last emission
139            if !compile_errors.iter().eq(last_emitted.iter()) {
140                for diag in &compile_errors {
141                    println!("cargo:warning=js2zig: {diag}");
142                }
143                // Persist current set so the next build can compare
144                if let Ok(json) = serde_json::to_string_pretty(&compile_errors) {
145                    let _ = std::fs::write(&last_emitted_path, json);
146                }
147            }
148
149            link_from_cache(&cache_dir);
150        }
151        Err(e) => {
152            panic!("js2rust_bridge::build: transpilation/zig build failed: {e}");
153        }
154    }
155}
156
157/// Fallback: scan `.js2zig-cache/` and emit link directives without running
158/// transpilation or zig build.  Used when the proc-macro already did the work.
159///
160/// Emits `cargo:rerun-if-changed` for the cache directory so Cargo re-runs
161/// the build script when the compiled libraries change.
162pub fn link() {
163    let manifest_dir =
164        std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR must be set by Cargo");
165    let cache_dir = PathBuf::from(&manifest_dir).join(".js2zig-cache");
166
167    // Re-run when compiled libraries appear or change.
168    if cache_dir.exists() {
169        println!("cargo:rerun-if-changed={}", cache_dir.display());
170    }
171
172    link_from_cache(&cache_dir);
173}
174
175/// Scan `.js2zig-cache/` for compiled static libraries and emit link directives.
176fn link_from_cache(cache_dir: &std::path::Path) {
177    if !cache_dir.exists() {
178        println!(
179            "cargo:warning=js2zig: .js2zig-cache not found. \
180             Run `cargo build` twice on a clean checkout."
181        );
182        return;
183    }
184
185    let mut found = false;
186    if let Ok(entries) = std::fs::read_dir(cache_dir) {
187        for entry in entries.flatten() {
188            let project_dir = entry.path();
189            let lib_dir = project_dir.join("zig-out").join("lib");
190
191            if lib_dir.exists()
192                && let Some(dir_name) = entry.file_name().to_str()
193            {
194                if dir_name == "host_regex.zig"
195                    || dir_name == "host_icu.zig"
196                    || dir_name == "host_regex_stubs.zig"
197                    || dir_name == "host_icu_stubs.zig"
198                {
199                    continue;
200                }
201                println!("cargo:rustc-link-search=native={}", lib_dir.display());
202                println!("cargo:rustc-link-lib=static={}", dir_name);
203                found = true;
204            }
205        }
206    }
207
208    if !found {
209        println!(
210            "cargo:warning=js2zig: no compiled libraries found in {}. \
211             Run `cargo build` twice on a clean checkout.",
212            cache_dir.display()
213        );
214    }
215}