Skip to main content

wasi_virt_layer_cli/
args.rs

1use camino::Utf8PathBuf;
2use clap::{Parser, Subcommand};
3use eyre::Context as _;
4
5use crate::{generator::WasmPath, util::ResultUtil as _};
6
7/// Common interface for post-build (transpilation) arguments.
8pub trait PostBuildContext {
9    /// Returns the output directory path.
10    fn out_dir(&self) -> &Utf8PathBuf;
11    /// Returns whether to keep intermediate build artifacts.
12    fn keep_build_artifacts(&self) -> bool;
13    /// Returns whether to adjust the ABI.
14    fn adjust_abi(&self) -> bool;
15    /// Transpiles the given WebAssembly component into JavaScript source files.
16    fn transpile_to_js(
17        &self,
18        component: &[u8],
19        name: impl AsRef<str>,
20    ) -> Result<js_component_bindgen::Transpiled, eyre::Error>;
21}
22
23/// The main command-line interface for `wasi_virt_layer-cli`.
24#[derive(Parser, Debug)]
25#[clap(author, version, about, long_about = None, help_template = "
26{name} {version}
27{author}
28{about}
29
30{usage-heading} {usage}
31
32{all-args}")]
33#[clap(propagate_version = true)]
34pub struct Cli {
35    /// The command to execute.
36    #[clap(subcommand)]
37    pub command: Command,
38}
39
40#[derive(Subcommand, Debug)]
41#[clap(author, version, about, long_about = None, help_template = "
42{name} {version}
43{author}
44{about}
45
46{usage-heading} {usage}
47
48{all-args}")]
49/// Supported subcommands for the CLI.
50pub enum Command {
51    /// Builds a virtualized WASM module (prebuild + postbuild combined).
52    Build(BuildArgs),
53    /// Generates a Component WASM from VFS and target WASM modules.
54    Prebuild(PreBuildArgs),
55    /// Transpiles a Component WASM into JavaScript files.
56    Postbuild(PostBuildArgs),
57    /// Initializes a new WASI Virt Layer project.
58    New(NewArgs),
59    /// Prepares a target WASM module for shared memory operation.
60    PrepareTarget(PrepareTargetArgs),
61}
62
63#[derive(Parser, Debug)]
64#[clap(author, version, about, long_about = None, help_template = "
65{name} {version}
66{author}
67{about}
68
69{usage-heading} {usage}
70
71{all-args}")]
72/// Arguments for the `new` command.
73pub struct NewArgs {
74    /// The path where the new project will be created.
75    #[arg(value_name = "PATH")]
76    pub path: Utf8PathBuf,
77
78    /// Whether to enable multi-threading support in the new project.
79    #[arg(long, default_value = "false")]
80    pub threads: bool,
81}
82
83#[derive(Parser, Debug)]
84#[clap(author, version, about, long_about = None, help_template = "
85{name} {version}
86{author}
87{about}
88
89{usage-heading} {usage}
90
91{all-args}")]
92/// Arguments for the `prepare-target` command.
93pub struct PrepareTargetArgs {
94    /// Path to the target WASM module (wasip1)
95    #[arg(value_name = "TARGET_WASM")]
96    pub target_wasm: Utf8PathBuf,
97
98    /// Output path for the transformed WASM module
99    #[arg(short, long, value_name = "OUTPUT")]
100    pub output: Option<Utf8PathBuf>,
101
102    /// Whether to keep intermediate build artifacts
103    #[arg(long, default_value = "false")]
104    pub keep_artifacts: bool,
105}
106
107#[derive(Parser, Debug)]
108#[clap(author, version, about, long_about = None, help_template = "
109{name} {version}
110{author}
111{about}
112
113{usage-heading} {usage}
114
115{all-args}")]
116/// Arguments for the `build` command.
117pub struct BuildArgs {
118    /// Path to the wasip1 wasm file
119    /// This allow 4 patterns:
120    /// 1. only manifest path, like `./Cargo.toml` or `./some/dir/Cargo.toml`
121    /// 2. only package name, like `my_package`
122    /// 3. manifest path and package name, like `./Cargo.toml::my_package` or `./some/dir/Cargo.toml::my_package`
123    /// 4. direct path to wasm file, like `./target/wasm32-wasi/release/my_crate.wasm`
124    pub wasm: Vec<WasmPath>,
125
126    /// Path to the primary package; used for single-package mode or component translation.
127    #[arg(short, long)]
128    package: Option<WasmPath>,
129
130    /// Path to Cargo.toml
131    #[arg(long)]
132    pub manifest_path: Option<Utf8PathBuf>,
133
134    /// Memory hints for the WASM files, used if automatic detection fails.
135    #[arg(long)]
136    wasm_memory_hint: Vec<isize>,
137
138    /// Output directory for the generated files
139    #[arg(long, default_value = "./dist")]
140    pub out_dir: Utf8PathBuf,
141
142    /// Target memory type
143    /// Change crate feature flags based on the target memory type
144    #[arg(short, long)]
145    pub target_memory_type: Option<TargetMemoryType>,
146
147    // transpile options
148    /// Options for transpiling to JavaScript.
149    #[command(flatten)]
150    pub transpile_opts: TranspileOpts,
151
152    /// If wasm run on multiple threads, enable thread support
153    /// This will change the crate feature flags to enable multi-threading.
154    #[arg(long)]
155    pub threads: Option<bool>,
156
157    /// Enable dwarf
158    /// This is broken currently.
159    /// See https://github.com/wasm-bindgen/walrus/issues/258
160    #[arg(long)]
161    pub dwarf: Option<bool>,
162
163    /// Finally, align the ABI with wasip1-threads.
164    /// Only WASM will be generated.
165    #[arg(long, default_value = "false")]
166    pub adjust_abi: bool,
167
168    /// Keep all intermediate build artifacts instead of deleting them.
169    #[arg(long, default_value = "false")]
170    pub keep_build_artifacts: bool,
171}
172
173impl BuildArgs {
174    /// Returns the memory hints for each target module.
175    pub fn get_wasm_memory_hints(&self) -> Box<[Option<usize>]> {
176        self.wasm_memory_hint
177            .iter()
178            .map(|&hint| if hint < 0 { None } else { Some(hint as usize) })
179            .chain(std::iter::repeat(None))
180            .take(self.wasm.len())
181            .collect::<Box<_>>()
182    }
183
184    /// Resolves and returns the path to the WASM package.
185    pub fn get_package(&self) -> eyre::Result<WasmPath> {
186        let mut p = Ok(self.package.clone()).transpose().unwrap_or_else(|| {
187            if let Some(ref manifest) = self.manifest_path {
188                WasmPath::with_maybe_only_manifest(manifest.clone())
189            } else {
190                WasmPath::with_maybe_none()
191            }
192        })?;
193        if let Some(ref manifest) = self.manifest_path {
194            if let WasmPath::Maybe { manifest_path, .. } = &mut p {
195                *manifest_path = manifest.clone();
196            }
197        }
198        Ok(p)
199    }
200
201    /// Gets the list of wasm targets, applying the manifest path if specified.
202    pub fn get_wasm_paths(&self) -> Box<[WasmPath]> {
203        let mut paths = self.wasm.clone();
204        if let Some(ref manifest) = self.manifest_path {
205            for p in &mut paths {
206                if let WasmPath::Maybe { manifest_path, .. } = p {
207                    *manifest_path = manifest.clone();
208                }
209            }
210        }
211        paths.into_boxed_slice()
212    }
213}
214
215impl PostBuildContext for BuildArgs {
216    fn out_dir(&self) -> &Utf8PathBuf {
217        &self.out_dir
218    }
219
220    fn keep_build_artifacts(&self) -> bool {
221        self.keep_build_artifacts
222    }
223
224    fn adjust_abi(&self) -> bool {
225        self.adjust_abi
226    }
227
228    fn transpile_to_js(
229        &self,
230        component: &[u8],
231        name: impl AsRef<str>,
232    ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
233        self.transpile_opts.transpile_to_js(component, name)
234    }
235}
236
237#[derive(Parser, Debug)]
238#[clap(author, version, about, long_about = None, help_template = "
239{name} {version}
240{author}
241{about}
242
243{usage-heading} {usage}
244
245{all-args}")]
246/// Arguments for the `prebuild` command.
247pub struct PreBuildArgs {
248    /// Path to the wasip1 wasm file
249    /// This allow 4 patterns:
250    /// 1. only manifest path, like `./Cargo.toml` or `./some/dir/Cargo.toml`
251    /// 2. only package name, like `my_package`
252    /// 3. manifest path and package name, like `./Cargo.toml::my_package` or `./some/dir/Cargo.toml::my_package`
253    /// 4. direct path to wasm file, like `./target/wasm32-wasi/release/my_crate.wasm`
254    pub wasm: Vec<WasmPath>,
255
256    /// Path to the primary package.
257    #[arg(short, long)]
258    package: Option<WasmPath>,
259
260    /// Path to Cargo.toml
261    #[arg(long)]
262    pub manifest_path: Option<Utf8PathBuf>,
263
264    /// Memory hints for the WASM files, used if automatic detection fails.
265    #[arg(long)]
266    wasm_memory_hint: Vec<isize>,
267
268    /// Output directory for the generated Component WASM
269    #[arg(long, default_value = "./dist")]
270    pub out_dir: Utf8PathBuf,
271
272    /// Target memory type
273    /// Change crate feature flags based on the target memory type
274    #[arg(short, long)]
275    pub target_memory_type: Option<TargetMemoryType>,
276
277    /// If wasm run on multiple threads, enable thread support
278    /// This will change the crate feature flags to enable multi-threading.
279    #[arg(long)]
280    pub threads: Option<bool>,
281
282    /// Enable dwarf
283    /// This is broken currently.
284    /// See https://github.com/wasm-bindgen/walrus/issues/258
285    #[arg(long)]
286    pub dwarf: Option<bool>,
287
288    /// Finally, align the ABI with wasip1-threads.
289    /// Only WASM will be generated.
290    #[arg(long, default_value = "false")]
291    pub adjust_abi: bool,
292
293    /// Keep all intermediate build artifacts instead of deleting them.
294    #[arg(long, default_value = "false")]
295    pub keep_build_artifacts: bool,
296}
297
298impl PreBuildArgs {
299    /// Returns the memory hints for each target module.
300    pub fn get_wasm_memory_hints(&self) -> Box<[Option<usize>]> {
301        self.wasm_memory_hint
302            .iter()
303            .map(|&hint| if hint < 0 { None } else { Some(hint as usize) })
304            .chain(std::iter::repeat(None))
305            .take(self.wasm.len())
306            .collect::<Box<_>>()
307    }
308
309    /// Resolves and returns the path to the WASM package.
310    pub fn get_package(&self) -> eyre::Result<WasmPath> {
311        let mut p = Ok(self.package.clone()).transpose().unwrap_or_else(|| {
312            if let Some(ref manifest) = self.manifest_path {
313                WasmPath::with_maybe_only_manifest(manifest.clone())
314            } else {
315                WasmPath::with_maybe_none()
316            }
317        })?;
318        if let Some(ref manifest) = self.manifest_path {
319            if let WasmPath::Maybe { manifest_path, .. } = &mut p {
320                *manifest_path = manifest.clone();
321            }
322        }
323        Ok(p)
324    }
325
326    /// Gets the list of wasm targets, applying the manifest path if specified.
327    pub fn get_wasm_paths(&self) -> Box<[WasmPath]> {
328        let mut paths = self.wasm.clone();
329        if let Some(ref manifest) = self.manifest_path {
330            for p in &mut paths {
331                if let WasmPath::Maybe { manifest_path, .. } = p {
332                    *manifest_path = manifest.clone();
333                }
334            }
335        }
336        paths.into_boxed_slice()
337    }
338}
339
340#[derive(Parser, Debug)]
341#[clap(author, version, about, long_about = None, help_template = "
342{name} {version}
343{author}
344{about}
345
346{usage-heading} {usage}
347
348{all-args}")]
349/// Arguments for the `postbuild` command.
350pub struct PostBuildArgs {
351    /// Path to the Component WASM file to transpile.
352    #[arg(short, long)]
353    pub package: WasmPath,
354
355    /// Output directory for the generated files
356    #[arg(long, default_value = "./dist")]
357    pub out_dir: Utf8PathBuf,
358
359    /// Options for transpiling to JavaScript.
360    #[command(flatten)]
361    pub transpile_opts: TranspileOpts,
362
363    /// Enable dwarf
364    #[arg(long)]
365    pub dwarf: Option<bool>,
366
367    /// Finally, align the ABI with wasip1-threads.
368    /// Only WASM will be generated.
369    #[arg(long, default_value = "false")]
370    pub adjust_abi: bool,
371
372    /// Keep all intermediate build artifacts instead of deleting them.
373    #[arg(long, default_value = "false")]
374    pub keep_build_artifacts: bool,
375}
376
377impl PostBuildContext for PostBuildArgs {
378    fn out_dir(&self) -> &Utf8PathBuf {
379        &self.out_dir
380    }
381
382    fn keep_build_artifacts(&self) -> bool {
383        self.keep_build_artifacts
384    }
385
386    fn adjust_abi(&self) -> bool {
387        self.adjust_abi
388    }
389
390    fn transpile_to_js(
391        &self,
392        component: &[u8],
393        name: impl AsRef<str>,
394    ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
395        self.transpile_opts.transpile_to_js(component, name)
396    }
397}
398
399/// Options for transpiling WebAssembly components into JavaScript.
400#[derive(Parser, Debug)]
401#[clap(author, version, about, long_about = None, help_template = "
402{name} {version}
403{author}
404{about}
405
406{usage-heading} {usage}
407
408{all-args}")]
409pub struct TranspileOpts {
410    /// Disables generation of *.d.ts files and instead only generates *.js source files.
411    #[arg(long, default_value = "false")]
412    no_typescript: bool,
413
414    /// Provide a custom JS instantiation API for the component instead of the direct importable native ESM output.
415    /// Sync, Async, Normal, Default is Async.
416    #[arg(long, value_parser = analysis::analysis_instantiation, default_value = "CustomInstantiationMode(None)")]
417    instantiation: CustomInstantiationMode,
418
419    /// Configure how import bindings are provided, as high-level JS bindings, or as hybrid optimized bindings.
420    #[arg(long, value_parser = analysis::analysis_import_bindings)]
421    import_bindings: Option<js_component_bindgen::BindingsMode>,
422
423    /// Comma-separated list of "from-specifier=./to-specifier.js" mappings of component import specifiers to JS import specifiers.
424    #[arg(long, value_delimiter = ',', value_parser = analysis::parse_mapping, action = clap::ArgAction::Append)]
425    map: Vec<(String, String)>,
426
427    /// Disables compatibility in Node.js without a fetch global.
428    #[arg(long, default_value = "false")]
429    no_nodejs_compat: bool,
430
431    /// Set the cutoff byte size for base64 inlining core Wasm in instantiation mode (set to 0 to disable all base64 inlining)
432    #[arg(long, default_value = "0")]
433    base64_cutoff: usize,
434
435    /// Enables compatibility for JS environments without top-level await support via an async $init promise export to wait for instead.
436    #[arg(long, default_value = "false")]
437    tla_compat: bool,
438
439    /// Disable verification of component Wasm data structures when lifting as a production optimization
440    #[arg(long, default_value = "false")]
441    valid_lifting_optimization: bool,
442
443    /// Whether or not to emit tracing calls on function entry/exit.
444    #[arg(long, default_value = "false")]
445    tracing: bool,
446
447    /// Whether to generate namespaced exports like foo as "local:package/foo ". These exports can break typescript builds.
448    #[arg(long, default_value = "false")]
449    no_namespaced_exports: bool,
450
451    /// Whether to generate types for a guest module using module declarations.
452    #[arg(long, default_value = "false")]
453    pub guest: bool,
454}
455
456impl TranspileOpts {
457    /// Transpiles the given WebAssembly component into JavaScript source files.
458    pub fn transpile_to_js(
459        &self,
460        component: &[u8],
461        name: impl AsRef<str>,
462    ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
463        js_component_bindgen::transpile(
464            component,
465            js_component_bindgen::TranspileOpts {
466                name: name.as_ref().to_string(),
467                no_typescript: self.no_typescript,
468                instantiation: self.instantiation.clone().0,
469                import_bindings: self.import_bindings.clone(),
470                map: if !self.map.is_empty() {
471                    Some(self.map.iter().cloned().collect())
472                } else {
473                    None
474                },
475                no_nodejs_compat: self.no_nodejs_compat,
476                base64_cutoff: self.base64_cutoff,
477                tla_compat: self.tla_compat,
478                valid_lifting_optimization: self.valid_lifting_optimization,
479                tracing: self.tracing,
480                no_namespaced_exports: self.no_namespaced_exports,
481                multi_memory: true,
482                guest: self.guest,
483                async_mode: None,
484                strict: false,
485                asmjs: false,
486            },
487        )
488        .to_eyre()
489        .wrap_err("Failed to transpile to JS.")
490    }
491}
492
493/// Represents a custom instantiation mode for the generated JavaScript.
494#[derive(Clone, Debug)]
495pub struct CustomInstantiationMode(Option<js_component_bindgen::InstantiationMode>);
496
497pub(super) mod analysis {
498    use js_component_bindgen::{BindingsMode, InstantiationMode};
499
500    use super::CustomInstantiationMode;
501
502    pub fn analysis_instantiation(s: &str) -> Result<CustomInstantiationMode, clap::Error> {
503        match s {
504            "Sync" => Ok(CustomInstantiationMode(Some(InstantiationMode::Sync))),
505            "Async" => Ok(CustomInstantiationMode(Some(InstantiationMode::Async))),
506            "Normal" => Ok(CustomInstantiationMode(None)),
507            _ => Ok(CustomInstantiationMode(Some(InstantiationMode::Async))),
508        }
509    }
510
511    pub fn analysis_import_bindings(s: &str) -> Result<Option<BindingsMode>, clap::Error> {
512        match s {
513            "Hybrid" => Ok(Some(BindingsMode::Hybrid)),
514            "Js" => Ok(Some(BindingsMode::Js)),
515            "Optimized" => Ok(Some(BindingsMode::Optimized)),
516            "DirectOptimized" => Ok(Some(BindingsMode::DirectOptimized)),
517            _ => Ok(None),
518        }
519    }
520
521    pub fn parse_mapping(s: &str) -> Result<(String, String), String> {
522        let parts: Vec<&str> = s.splitn(2, '=').collect();
523        if parts.len() != 2 {
524            return Err(format!("Invalid mapping format: '{}'", s));
525        }
526        Ok((parts[0].to_string(), parts[1].to_string()))
527    }
528}
529
530/// Specifies the memory architecture of the target WebAssembly module.
531#[derive(Debug, Clone, Copy, PartialEq, strum::EnumString, strum::Display)]
532pub enum TargetMemoryType {
533    /// Traditional single memory environment.
534    #[strum(ascii_case_insensitive)]
535    Single,
536    /// Multi-memory environment where modules have their own address spaces.
537    #[strum(ascii_case_insensitive)]
538    Multi,
539}
540
541impl TargetMemoryType {
542    /// Returns `true` if this memory type is `Multi`.
543    pub fn is_multi(&self) -> bool {
544        matches!(self, TargetMemoryType::Multi)
545    }
546
547    /// Returns `true` if this memory type is `Single`.
548    pub fn is_single(&self) -> bool {
549        matches!(self, TargetMemoryType::Single)
550    }
551}