Skip to main content

wasi_virt_layer_cli/
args.rs

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