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