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