wasi_virt_layer_cli/
args.rs

1use std::collections::HashMap;
2
3use camino::Utf8PathBuf;
4use clap::{Parser, command};
5use compact_str::CompactString;
6use eyre::Context as _;
7
8use crate::{generator::WasmPath, util::ResultUtil as _};
9
10#[derive(Parser, Debug)]
11#[command(version, about)]
12pub struct Args {
13    /// Path to the wasip1 wasm file
14    /// This allow 4 patterns:
15    /// 1. only manifest path, like `./Cargo.toml` or `./some/dir/Cargo.toml`
16    /// 2. only package name, like `my_package`
17    /// 3. manifest path and package name, like `./Cargo.toml::my_package` or `./some/dir/Cargo.toml::my_package`
18    /// 4. direct path to wasm file, like `./target/wasm32-wasi/release/my_crate.wasm`
19    pub wasm: Vec<WasmPath>,
20
21    #[arg(short, long)]
22    /// Path to the wasip1 wasm file
23    /// This allow 4 patterns:
24    /// 1. only manifest path, like `./Cargo.toml` or `./some/dir/Cargo.toml`
25    /// 2. only package name, like `my_package`
26    /// 3. manifest path and package name, like `./Cargo.toml::my_package` or `./some/dir/Cargo.toml::my_package`
27    /// 4. direct path to wasm file, like `./target/wasm32-wasi/release/my_crate.wasm`
28    /// 5. direct path to component file, like `./target/wasm32-wasi/release/my_crate.component.wasm`
29    ///      You can translate component to js directly.
30    package: Option<WasmPath>,
31
32    /// Memory hints for the wasm files.
33    /// If the target Wasm file fails to detect the memory used
34    /// when handling the wasip1 instruction, you can use this to specify it.
35    #[arg(long)]
36    wasm_memory_hint: Vec<isize>,
37
38    /// Output directory for the generated files
39    #[arg(long, default_value = "./dist")]
40    pub out_dir: Utf8PathBuf,
41
42    /// Target memory type
43    /// Change crate feature flags based on the target memory type
44    #[arg(short, long)]
45    pub target_memory_type: Option<TargetMemoryType>,
46
47    /// Disable transpile to JS, you can use jco to transpile wasm to js.
48    #[arg(long, default_value = "false")]
49    pub no_transpile: bool,
50
51    // transpile options
52    #[command(flatten)]
53    pub transpile_opts: TranspileOpts,
54
55    /// If wasm run on multiple threads, enable thread support
56    /// This will change the crate feature flags to enable multi-threading.
57    #[arg(long)]
58    pub threads: Option<bool>,
59
60    /// Enable dwarf
61    /// This is broken currently.
62    /// See https://github.com/wasm-bindgen/walrus/issues/258
63    #[arg(long)]
64    pub dwarf: Option<bool>,
65}
66
67impl Args {
68    pub fn new(args: impl IntoIterator<Item = impl Into<String>>) -> Self {
69        let args = args
70            .into_iter()
71            .map(Into::<String>::into)
72            .map(Into::<std::ffi::OsString>::into)
73            .collect::<Vec<_>>();
74        let parsed = Args::parse_from(args);
75        if parsed.wasm.is_empty()
76            && !parsed
77                .package
78                .as_ref()
79                .is_some_and(|p| matches!(p, WasmPath::Component(_)))
80        {
81            unimplemented!("target to only self file is not supported yet");
82        }
83
84        if parsed.dwarf.unwrap_or(false) {
85            log::error!("Warning: dwarf support is experimental and may not work as expected.");
86        }
87
88        parsed
89    }
90
91    pub fn get_wasm_memory_hints(&self) -> Box<[Option<usize>]> {
92        self.wasm_memory_hint
93            .iter()
94            .map(|&hint| if hint < 0 { None } else { Some(hint as usize) })
95            .chain(std::iter::repeat(None))
96            .take(self.wasm.len())
97            .collect::<Box<_>>()
98    }
99
100    pub fn get_package(&self) -> eyre::Result<WasmPath> {
101        Ok(self.package.clone())
102            .transpose()
103            .unwrap_or_else(|| WasmPath::with_maybe_none())
104    }
105
106    pub fn get_manifest_path(&self) -> Option<&Utf8PathBuf> {
107        self.package.as_ref().and_then(|p| p.manifest_path())
108    }
109
110    pub fn get_package_name(&self) -> Option<CompactString> {
111        self.package.clone().and_then(|p| p.name().ok())
112    }
113
114    pub fn transpile_to_js(
115        &self,
116        component: &[u8],
117        name: impl AsRef<str>,
118    ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
119        js_component_bindgen::transpile(
120            component,
121            js_component_bindgen::TranspileOpts {
122                name: name.as_ref().to_string(),
123                no_typescript: self.transpile_opts.no_typescript,
124                instantiation: self.transpile_opts.instantiation.clone().0,
125                import_bindings: self.transpile_opts.import_bindings.clone(),
126                map: {
127                    if let Some(opts_map) = &self.transpile_opts.map {
128                        let mut map = HashMap::new();
129                        for (k, v) in opts_map.iter() {
130                            map.insert(k.clone(), v.clone());
131                        }
132                        Some(map)
133                    } else {
134                        None
135                    }
136                },
137                no_nodejs_compat: self.transpile_opts.no_nodejs_compat,
138                base64_cutoff: self.transpile_opts.base64_cutoff,
139                tla_compat: self.transpile_opts.tla_compat,
140                valid_lifting_optimization: self.transpile_opts.valid_lifting_optimization,
141                tracing: self.transpile_opts.tracing,
142                no_namespaced_exports: self.transpile_opts.no_namespaced_exports,
143                multi_memory: true,
144                guest: self.transpile_opts.guest,
145                async_mode: None,
146            },
147        )
148        .to_eyre()
149        .wrap_err("Failed to transpile to JS. Consider the no_transpile option.")
150    }
151}
152
153#[derive(Parser, Debug)]
154pub struct TranspileOpts {
155    /// Disables generation of *.d.ts files and instead only generates *.js source files.
156    #[arg(long, default_value = "false")]
157    no_typescript: bool,
158
159    /// Provide a custom JS instantiation API for the component instead of the direct importable native ESM output.
160    /// Sync, Async, Normal, Default is Async.
161    #[arg(long, value_parser = analysis::analysis_instantiation, default_value = "CustomInstantiationMode(None)")]
162    instantiation: CustomInstantiationMode,
163
164    /// Configure how import bindings are provided, as high-level JS bindings, or as hybrid optimized bindings.
165    #[arg(long, value_parser = analysis::analysis_import_bindings)]
166    import_bindings: Option<js_component_bindgen::BindingsMode>,
167
168    /// Comma-separated list of “from-specifier=./to-specifier.js” mappings of component import specifiers to JS import specifiers.
169    #[arg(long, value_delimiter = ',', value_parser = analysis::parse_mapping, num_args = 0.., action = clap::ArgAction::Append)]
170    map: Option<HashMap<String, String>>,
171
172    /// Disables compatibility in Node.js without a fetch global.
173    #[arg(long, default_value = "false")]
174    no_nodejs_compat: bool,
175
176    /// Set the cutoff byte size for base64 inlining core Wasm in instantiation mode (set to 0 to disable all base64 inlining)
177    #[arg(long, default_value = "0")]
178    base64_cutoff: usize,
179
180    /// Enables compatibility for JS environments without top-level await support via an async $init promise export to wait for instead.
181    #[arg(long, default_value = "false")]
182    tla_compat: bool,
183
184    /// Disable verification of component Wasm data structures when lifting as a production optimization
185    #[arg(long, default_value = "false")]
186    valid_lifting_optimization: bool,
187
188    /// Whether or not to emit tracing calls on function entry/exit.
189    #[arg(long, default_value = "false")]
190    tracing: bool,
191
192    /// Whether to generate namespaced exports like foo as "local:package/foo ". These exports can break typescript builds.
193    #[arg(long, default_value = "false")]
194    no_namespaced_exports: bool,
195
196    /// Whether to generate types for a guest module using module declarations.
197    #[arg(long, default_value = "false")]
198    guest: bool,
199}
200
201#[derive(Clone, Debug)]
202pub struct CustomInstantiationMode(Option<js_component_bindgen::InstantiationMode>);
203
204pub(super) mod analysis {
205    use js_component_bindgen::{BindingsMode, InstantiationMode};
206
207    use super::CustomInstantiationMode;
208
209    pub fn analysis_instantiation(s: &str) -> Result<CustomInstantiationMode, clap::Error> {
210        match s {
211            "Sync" => Ok(CustomInstantiationMode(Some(InstantiationMode::Sync))),
212            "Async" => Ok(CustomInstantiationMode(Some(InstantiationMode::Async))),
213            "Normal" => Ok(CustomInstantiationMode(None)),
214            _ => Ok(CustomInstantiationMode(Some(InstantiationMode::Async))),
215        }
216    }
217
218    pub fn analysis_import_bindings(s: &str) -> Result<Option<BindingsMode>, clap::Error> {
219        match s {
220            "Hybrid" => Ok(Some(BindingsMode::Hybrid)),
221            "Js" => Ok(Some(BindingsMode::Js)),
222            "Optimized" => Ok(Some(BindingsMode::Optimized)),
223            "DirectOptimized" => Ok(Some(BindingsMode::DirectOptimized)),
224            _ => Ok(None),
225        }
226    }
227
228    pub fn parse_mapping(s: &str) -> Result<(String, String), String> {
229        let parts: Vec<&str> = s.splitn(2, '=').collect();
230        if parts.len() != 2 {
231            return Err(format!("Invalid mapping format: '{}'", s));
232        }
233        Ok((parts[0].to_string(), parts[1].to_string()))
234    }
235}
236
237#[derive(Debug, Clone, Copy, PartialEq, strum::EnumString, strum::Display)]
238pub enum TargetMemoryType {
239    #[strum(ascii_case_insensitive)]
240    Single,
241    #[strum(ascii_case_insensitive)]
242    Multi,
243}
244
245impl TargetMemoryType {
246    pub fn is_multi(&self) -> bool {
247        matches!(self, TargetMemoryType::Multi)
248    }
249
250    pub fn is_single(&self) -> bool {
251        matches!(self, TargetMemoryType::Single)
252    }
253}