wasi_virt_layer-cli 0.2.2

CLI for the wasi_virt_layer crate
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
use std::collections::HashMap;

use camino::Utf8PathBuf;
use clap::{Parser, Subcommand};
use compact_str::CompactString;
use eyre::Context as _;

use crate::{generator::WasmPath, util::ResultUtil as _};

/// Common interface for post-build (transpilation) arguments.
pub trait PostBuildContext {
    /// Returns the output directory path.
    fn out_dir(&self) -> &Utf8PathBuf;
    /// Returns whether to keep intermediate build artifacts.
    fn keep_build_artifacts(&self) -> bool;
    /// Returns whether to adjust the ABI.
    fn adjust_abi(&self) -> bool;
    /// Transpiles the given WebAssembly component into JavaScript source files.
    fn transpile_to_js(
        &self,
        component: &[u8],
        name: impl AsRef<str>,
    ) -> Result<js_component_bindgen::Transpiled, eyre::Error>;
}

/// The main command-line interface for `wasi_virt_layer-cli`.
#[derive(Parser, Debug)]
#[clap(author, version, about, long_about = None)]
#[clap(propagate_version = true)]
pub struct Cli {
    /// The command to execute.
    #[clap(subcommand)]
    pub command: Command,
}

#[derive(Subcommand, Debug)]
/// Supported subcommands for the CLI.
pub enum Command {
    /// Builds a virtualized WASM module (prebuild + postbuild combined).
    Build(BuildArgs),
    /// Generates a Component WASM from VFS and target WASM modules.
    Prebuild(PreBuildArgs),
    /// Transpiles a Component WASM into JavaScript files.
    Postbuild(PostBuildArgs),
    /// Initializes a new WASI Virt Layer project.
    New(NewArgs),
}

#[derive(Parser, Debug)]
/// Arguments for the `new` command.
pub struct NewArgs {
    /// The path where the new project will be created.
    #[arg(value_name = "PATH")]
    pub path: Utf8PathBuf,

    /// Whether to enable multi-threading support in the new project.
    #[arg(long, default_value = "false")]
    pub threads: bool,
}

#[derive(Parser, Debug)]
/// Arguments for the `build` command.
pub struct BuildArgs {
    /// Path to the wasip1 wasm file
    /// This allow 4 patterns:
    /// 1. only manifest path, like `./Cargo.toml` or `./some/dir/Cargo.toml`
    /// 2. only package name, like `my_package`
    /// 3. manifest path and package name, like `./Cargo.toml::my_package` or `./some/dir/Cargo.toml::my_package`
    /// 4. direct path to wasm file, like `./target/wasm32-wasi/release/my_crate.wasm`
    pub wasm: Vec<WasmPath>,

    /// Path to the primary package; used for single-package mode or component translation.
    #[arg(short, long)]
    package: Option<WasmPath>,

    /// Memory hints for the WASM files, used if automatic detection fails.
    #[arg(long)]
    wasm_memory_hint: Vec<isize>,

    /// Output directory for the generated files
    #[arg(long, default_value = "./dist")]
    pub out_dir: Utf8PathBuf,

    /// Target memory type
    /// Change crate feature flags based on the target memory type
    #[arg(short, long)]
    pub target_memory_type: Option<TargetMemoryType>,

    // transpile options
    /// Options for transpiling to JavaScript.
    #[command(flatten)]
    pub transpile_opts: TranspileOpts,

    /// If wasm run on multiple threads, enable thread support
    /// This will change the crate feature flags to enable multi-threading.
    #[arg(long)]
    pub threads: Option<bool>,

    /// Enable dwarf
    /// This is broken currently.
    /// See https://github.com/wasm-bindgen/walrus/issues/258
    #[arg(long)]
    pub dwarf: Option<bool>,

    /// Finally, align the ABI with wasip1-threads.
    /// Only WASM will be generated.
    #[arg(long, default_value = "false")]
    pub adjust_abi: bool,

    /// Keep all intermediate build artifacts instead of deleting them.
    #[arg(long, default_value = "false")]
    pub keep_build_artifacts: bool,
}

impl BuildArgs {
    /// Returns the memory hints for each target module.
    pub fn get_wasm_memory_hints(&self) -> Box<[Option<usize>]> {
        self.wasm_memory_hint
            .iter()
            .map(|&hint| if hint < 0 { None } else { Some(hint as usize) })
            .chain(std::iter::repeat(None))
            .take(self.wasm.len())
            .collect::<Box<_>>()
    }

    /// Resolves and returns the path to the WASM package.
    pub fn get_package(&self) -> eyre::Result<WasmPath> {
        Ok(self.package.clone())
            .transpose()
            .unwrap_or_else(|| WasmPath::with_maybe_none())
    }

    /// Returns the manifest path if specified.
    pub fn get_manifest_path(&self) -> Option<&Utf8PathBuf> {
        self.package.as_ref().and_then(|p| p.manifest_path())
    }

    /// Retrieves the name of the package if available.
    pub fn get_package_name(&self) -> Option<CompactString> {
        self.package.clone().and_then(|p| p.name().ok())
    }
}

impl PostBuildContext for BuildArgs {
    fn out_dir(&self) -> &Utf8PathBuf {
        &self.out_dir
    }

    fn keep_build_artifacts(&self) -> bool {
        self.keep_build_artifacts
    }

    fn adjust_abi(&self) -> bool {
        self.adjust_abi
    }

    fn transpile_to_js(
        &self,
        component: &[u8],
        name: impl AsRef<str>,
    ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
        self.transpile_opts.transpile_to_js(component, name)
    }
}

#[derive(Parser, Debug)]
/// Arguments for the `prebuild` command.
pub struct PreBuildArgs {
    /// Path to the wasip1 wasm file
    /// This allow 4 patterns:
    /// 1. only manifest path, like `./Cargo.toml` or `./some/dir/Cargo.toml`
    /// 2. only package name, like `my_package`
    /// 3. manifest path and package name, like `./Cargo.toml::my_package` or `./some/dir/Cargo.toml::my_package`
    /// 4. direct path to wasm file, like `./target/wasm32-wasi/release/my_crate.wasm`
    pub wasm: Vec<WasmPath>,

    /// Path to the primary package.
    #[arg(short, long)]
    package: Option<WasmPath>,

    /// Memory hints for the WASM files, used if automatic detection fails.
    #[arg(long)]
    wasm_memory_hint: Vec<isize>,

    /// Output directory for the generated Component WASM
    #[arg(long, default_value = "./dist")]
    pub out_dir: Utf8PathBuf,

    /// Target memory type
    /// Change crate feature flags based on the target memory type
    #[arg(short, long)]
    pub target_memory_type: Option<TargetMemoryType>,

    /// If wasm run on multiple threads, enable thread support
    /// This will change the crate feature flags to enable multi-threading.
    #[arg(long)]
    pub threads: Option<bool>,

    /// Enable dwarf
    /// This is broken currently.
    /// See https://github.com/wasm-bindgen/walrus/issues/258
    #[arg(long)]
    pub dwarf: Option<bool>,

    /// Finally, align the ABI with wasip1-threads.
    /// Only WASM will be generated.
    #[arg(long, default_value = "false")]
    pub adjust_abi: bool,

    /// Keep all intermediate build artifacts instead of deleting them.
    #[arg(long, default_value = "false")]
    pub keep_build_artifacts: bool,
}

impl PreBuildArgs {
    /// Returns the memory hints for each target module.
    pub fn get_wasm_memory_hints(&self) -> Box<[Option<usize>]> {
        self.wasm_memory_hint
            .iter()
            .map(|&hint| if hint < 0 { None } else { Some(hint as usize) })
            .chain(std::iter::repeat(None))
            .take(self.wasm.len())
            .collect::<Box<_>>()
    }

    /// Resolves and returns the path to the WASM package.
    pub fn get_package(&self) -> eyre::Result<WasmPath> {
        Ok(self.package.clone())
            .transpose()
            .unwrap_or_else(|| WasmPath::with_maybe_none())
    }
}

#[derive(Parser, Debug)]
/// Arguments for the `postbuild` command.
pub struct PostBuildArgs {
    /// Path to the Component WASM file to transpile.
    #[arg(short, long)]
    pub package: WasmPath,

    /// Output directory for the generated files
    #[arg(long, default_value = "./dist")]
    pub out_dir: Utf8PathBuf,

    /// Options for transpiling to JavaScript.
    #[command(flatten)]
    pub transpile_opts: TranspileOpts,

    /// Enable dwarf
    #[arg(long)]
    pub dwarf: Option<bool>,

    /// Finally, align the ABI with wasip1-threads.
    /// Only WASM will be generated.
    #[arg(long, default_value = "false")]
    pub adjust_abi: bool,

    /// Keep all intermediate build artifacts instead of deleting them.
    #[arg(long, default_value = "false")]
    pub keep_build_artifacts: bool,
}

impl PostBuildContext for PostBuildArgs {
    fn out_dir(&self) -> &Utf8PathBuf {
        &self.out_dir
    }

    fn keep_build_artifacts(&self) -> bool {
        self.keep_build_artifacts
    }

    fn adjust_abi(&self) -> bool {
        self.adjust_abi
    }

    fn transpile_to_js(
        &self,
        component: &[u8],
        name: impl AsRef<str>,
    ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
        self.transpile_opts.transpile_to_js(component, name)
    }
}

/// Options for transpiling WebAssembly components into JavaScript.
#[derive(Parser, Debug)]
pub struct TranspileOpts {
    /// Disables generation of *.d.ts files and instead only generates *.js source files.
    #[arg(long, default_value = "false")]
    no_typescript: bool,

    /// Provide a custom JS instantiation API for the component instead of the direct importable native ESM output.
    /// Sync, Async, Normal, Default is Async.
    #[arg(long, value_parser = analysis::analysis_instantiation, default_value = "CustomInstantiationMode(None)")]
    instantiation: CustomInstantiationMode,

    /// Configure how import bindings are provided, as high-level JS bindings, or as hybrid optimized bindings.
    #[arg(long, value_parser = analysis::analysis_import_bindings)]
    import_bindings: Option<js_component_bindgen::BindingsMode>,

    /// Comma-separated list of "from-specifier=./to-specifier.js" mappings of component import specifiers to JS import specifiers.
    #[arg(long, value_delimiter = ',', value_parser = analysis::parse_mapping, num_args = 0.., action = clap::ArgAction::Append)]
    map: Option<HashMap<String, String>>,

    /// Disables compatibility in Node.js without a fetch global.
    #[arg(long, default_value = "false")]
    no_nodejs_compat: bool,

    /// Set the cutoff byte size for base64 inlining core Wasm in instantiation mode (set to 0 to disable all base64 inlining)
    #[arg(long, default_value = "0")]
    base64_cutoff: usize,

    /// Enables compatibility for JS environments without top-level await support via an async $init promise export to wait for instead.
    #[arg(long, default_value = "false")]
    tla_compat: bool,

    /// Disable verification of component Wasm data structures when lifting as a production optimization
    #[arg(long, default_value = "false")]
    valid_lifting_optimization: bool,

    /// Whether or not to emit tracing calls on function entry/exit.
    #[arg(long, default_value = "false")]
    tracing: bool,

    /// Whether to generate namespaced exports like foo as "local:package/foo ". These exports can break typescript builds.
    #[arg(long, default_value = "false")]
    no_namespaced_exports: bool,

    /// Whether to generate types for a guest module using module declarations.
    #[arg(long, default_value = "false")]
    pub guest: bool,
}

impl TranspileOpts {
    /// Transpiles the given WebAssembly component into JavaScript source files.
    pub fn transpile_to_js(
        &self,
        component: &[u8],
        name: impl AsRef<str>,
    ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
        js_component_bindgen::transpile(
            component,
            js_component_bindgen::TranspileOpts {
                name: name.as_ref().to_string(),
                no_typescript: self.no_typescript,
                instantiation: self.instantiation.clone().0,
                import_bindings: self.import_bindings.clone(),
                map: {
                    if let Some(opts_map) = &self.map {
                        let mut map = HashMap::new();
                        for (k, v) in opts_map.iter() {
                            map.insert(k.clone(), v.clone());
                        }
                        Some(map)
                    } else {
                        None
                    }
                },
                no_nodejs_compat: self.no_nodejs_compat,
                base64_cutoff: self.base64_cutoff,
                tla_compat: self.tla_compat,
                valid_lifting_optimization: self.valid_lifting_optimization,
                tracing: self.tracing,
                no_namespaced_exports: self.no_namespaced_exports,
                multi_memory: true,
                guest: self.guest,
                async_mode: None,
                strict: false,
                asmjs: false,
            },
        )
        .to_eyre()
        .wrap_err("Failed to transpile to JS.")
    }
}

/// Represents a custom instantiation mode for the generated JavaScript.
#[derive(Clone, Debug)]
pub struct CustomInstantiationMode(Option<js_component_bindgen::InstantiationMode>);

pub(super) mod analysis {
    use js_component_bindgen::{BindingsMode, InstantiationMode};

    use super::CustomInstantiationMode;

    pub fn analysis_instantiation(s: &str) -> Result<CustomInstantiationMode, clap::Error> {
        match s {
            "Sync" => Ok(CustomInstantiationMode(Some(InstantiationMode::Sync))),
            "Async" => Ok(CustomInstantiationMode(Some(InstantiationMode::Async))),
            "Normal" => Ok(CustomInstantiationMode(None)),
            _ => Ok(CustomInstantiationMode(Some(InstantiationMode::Async))),
        }
    }

    pub fn analysis_import_bindings(s: &str) -> Result<Option<BindingsMode>, clap::Error> {
        match s {
            "Hybrid" => Ok(Some(BindingsMode::Hybrid)),
            "Js" => Ok(Some(BindingsMode::Js)),
            "Optimized" => Ok(Some(BindingsMode::Optimized)),
            "DirectOptimized" => Ok(Some(BindingsMode::DirectOptimized)),
            _ => Ok(None),
        }
    }

    pub fn parse_mapping(s: &str) -> Result<(String, String), String> {
        let parts: Vec<&str> = s.splitn(2, '=').collect();
        if parts.len() != 2 {
            return Err(format!("Invalid mapping format: '{}'", s));
        }
        Ok((parts[0].to_string(), parts[1].to_string()))
    }
}

/// Specifies the memory architecture of the target WebAssembly module.
#[derive(Debug, Clone, Copy, PartialEq, strum::EnumString, strum::Display)]
pub enum TargetMemoryType {
    /// Traditional single memory environment.
    #[strum(ascii_case_insensitive)]
    Single,
    /// Multi-memory environment where modules have their own address spaces.
    #[strum(ascii_case_insensitive)]
    Multi,
}

impl TargetMemoryType {
    /// Returns `true` if this memory type is `Multi`.
    pub fn is_multi(&self) -> bool {
        matches!(self, TargetMemoryType::Multi)
    }

    /// Returns `true` if this memory type is `Single`.
    pub fn is_single(&self) -> bool {
        matches!(self, TargetMemoryType::Single)
    }
}