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