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