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
17pub use js2rust_bridge_macro::js2rust_bridge;
18
19// Re-export types needed for BuildConfig from js2zig-core so users only
20// need `js2rust-bridge` in their `[build-dependencies]`.
21pub use js2zig_core::{HostConfig, HostFunction, HostType};
22
23use std::path::PathBuf;
24
25/// Simplified build configuration for `build.rs`.
26/// Mirrors `js2zig_core::ProjectConfig` without exposing the full API.
27pub struct BuildConfig {
28    /// Project name (also used as Zig library name).
29    pub name: String,
30    /// Core JS source file path (the entry point; its imports are pulled in transitively).
31    /// Relative to CARGO_MANIFEST_DIR.
32    pub js_file: String,
33    /// Additional core JS files (multi-root: all roots + their transitive deps → one group).
34    pub additional_js_files: Vec<String>,
35    /// Host function declarations (for projects that use `host_*` calls from JS).
36    /// `None` if this project doesn't use host functions.
37    pub host_functions: Option<HostConfig>,
38    /// Force rebuild (ignore incremental cache).
39    pub force_rebuild: bool,
40}
41
42/// Transpile JS → Zig, build the Zig static library, and emit `cargo:rustc-link-*`
43/// directives for the linker.
44///
45/// Call this from your `build.rs`.  On the first build after a clean checkout
46/// this does the heavy lifting (transpile + `zig build`).  On subsequent builds
47/// it detects the up-to-date cache and is a near-no-op.
48///
49/// ```rust,ignore
50/// fn main() {
51///     js2rust_bridge::build(js2rust_bridge::BuildConfig {
52///         name: "main".into(),
53///         js_file: "js_src/main.js".into(),
54///         additional_js_files: vec![],
55///         host_functions: Default::default(),
56///         force_rebuild: false,
57///     });
58/// }
59/// ```
60pub fn build(config: BuildConfig) {
61    let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
62    let cache_dir = PathBuf::from(&manifest_dir).join(".js2zig-cache");
63
64    // Convert BuildConfig → ProjectConfig
65    let js_file_path = PathBuf::from(&manifest_dir).join(&config.js_file);
66    let additional_js_paths: Vec<PathBuf> = config
67        .additional_js_files
68        .iter()
69        .map(|p| PathBuf::from(&manifest_dir).join(p))
70        .collect();
71
72    let project_config = js2zig_core::ProjectConfig {
73        name: config.name,
74        js_file: js_file_path,
75        additional_js_files: additional_js_paths,
76        out_dir: cache_dir.clone(),
77        host_config: config.host_functions,
78        force_rebuild: config.force_rebuild,
79        run_zig_build: true, // build.rs runs zig build
80    };
81
82    // Transpile JS → Zig (generates .js2zig-cache/{name}/)
83    match js2zig_core::transpile_project(&project_config) {
84        Ok(_result) => {
85            // Emit link directives for each group's compiled static library.
86            link_from_cache(&cache_dir);
87        }
88        Err(e) => {
89            // If transpilation fails, still try to link existing cache (e.g. from
90            // a previous successful build).
91            eprintln!("js2rust_bridge::build: transpilation error: {}", e);
92            link_from_cache(&cache_dir);
93        }
94    }
95}
96
97/// Fallback: scan `.js2zig-cache/` and emit link directives without running
98/// transpilation or zig build.  Used when the proc-macro already did the work.
99pub fn link() {
100    let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
101    let cache_dir = PathBuf::from(&manifest_dir).join(".js2zig-cache");
102    link_from_cache(&cache_dir);
103}
104
105/// Scan `.js2zig-cache/` for compiled static libraries and emit link directives.
106fn link_from_cache(cache_dir: &std::path::Path) {
107    if !cache_dir.exists() {
108        println!(
109            "cargo:warning=js2zig: .js2zig-cache not found. \
110             Run `cargo build` twice on a clean checkout."
111        );
112        return;
113    }
114
115    let mut found = false;
116    if let Ok(entries) = std::fs::read_dir(cache_dir) {
117        for entry in entries.flatten() {
118            let group_dir = entry.path();
119            let lib_dir = group_dir.join("zig-out").join("lib");
120
121            if lib_dir.exists()
122                && let Some(group_name) = entry.file_name().to_str() {
123                    if group_name == "host.zig" || group_name == "groups.json" {
124                        continue;
125                    }
126                    println!("cargo:rustc-link-search=native={}", lib_dir.display());
127                    println!("cargo:rustc-link-lib=static={}", group_name);
128                    found = true;
129                }
130        }
131    }
132
133    if !found {
134        println!(
135            "cargo:warning=js2zig: no compiled libraries found in {}. \
136             Run `cargo build` twice on a clean checkout.",
137            cache_dir.display()
138        );
139    }
140}