Skip to main content

wasi_virt_layer_cli/
args.rs

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