1use camino::Utf8PathBuf;
2use clap::{Parser, Subcommand};
3use eyre::Context as _;
4
5use crate::{generator::WasmPath, util::ResultUtil as _};
6
7pub trait PostBuildContext {
9 fn out_dir(&self) -> &Utf8PathBuf;
11 fn keep_build_artifacts(&self) -> bool;
13 fn adjust_abi(&self) -> bool;
15 fn transpile_to_js(
17 &self,
18 component: &[u8],
19 name: impl AsRef<str>,
20 ) -> Result<js_component_bindgen::Transpiled, eyre::Error>;
21 fn dev(&self) -> bool;
23}
24
25#[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 #[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}")]
51pub enum Command {
53 Build(BuildArgs),
55 Prebuild(PreBuildArgs),
57 Postbuild(PostBuildArgs),
59 New(NewArgs),
61 PrepareTarget(PrepareTargetArgs),
63}
64
65#[derive(Parser, Debug)]
66#[clap(author, version, about, long_about = None, help_template = "
67{name} {version}
68{author}
69{about}
70
71{usage-heading} {usage}
72
73{all-args}")]
74pub struct NewArgs {
76 #[arg(value_name = "PATH")]
78 pub path: Utf8PathBuf,
79
80 #[arg(long, default_value = "false")]
82 pub threads: bool,
83}
84
85#[derive(Parser, Debug)]
86#[clap(author, version, about, long_about = None, help_template = "
87{name} {version}
88{author}
89{about}
90
91{usage-heading} {usage}
92
93{all-args}")]
94pub struct PrepareTargetArgs {
96 #[arg(value_name = "TARGET_WASM")]
98 pub target_wasm: Utf8PathBuf,
99
100 #[arg(short, long, value_name = "OUTPUT")]
102 pub output: Option<Utf8PathBuf>,
103
104 #[arg(long, default_value = "false")]
106 pub keep_artifacts: bool,
107}
108
109#[derive(Parser, Debug)]
110#[clap(author, version, about, long_about = None, help_template = "
111{name} {version}
112{author}
113{about}
114
115{usage-heading} {usage}
116
117{all-args}")]
118pub struct BuildArgs {
120 pub wasm: Vec<WasmPath>,
127
128 #[arg(short, long)]
130 package: Option<WasmPath>,
131
132 #[arg(long)]
134 pub manifest_path: Option<Utf8PathBuf>,
135
136 #[arg(long)]
138 wasm_memory_hint: Vec<isize>,
139
140 #[arg(long, default_value = "./dist")]
142 pub out_dir: Utf8PathBuf,
143
144 #[arg(short, long)]
147 pub target_memory_type: Option<TargetMemoryType>,
148
149 #[command(flatten)]
152 pub transpile_opts: TranspileOpts,
153
154 #[arg(long)]
157 pub threads: Option<bool>,
158
159 #[arg(long)]
163 pub dwarf: Option<bool>,
164
165 #[arg(long, default_value = "false")]
168 pub adjust_abi: bool,
169
170 #[arg(long, default_value = "false")]
172 pub keep_build_artifacts: bool,
173
174 #[arg(long, default_value = "false")]
176 pub dev: bool,
177
178 #[command(flatten)]
180 pub vfs_build_opts: VfsBuildOptions,
181
182 #[arg(skip)]
184 pub target_vfs_build_opts: Option<Box<[VfsBuildOptions]>>,
185}
186
187impl BuildArgs {
188 pub fn get_wasm_memory_hints(&self) -> Box<[Option<usize>]> {
190 self.wasm_memory_hint
191 .iter()
192 .map(|&hint| if hint < 0 { None } else { Some(hint as usize) })
193 .chain(std::iter::repeat(None))
194 .take(self.wasm.len())
195 .collect::<Box<_>>()
196 }
197
198 pub fn get_package(&self) -> eyre::Result<WasmPath> {
200 let mut p = Ok(self.package.clone()).transpose().unwrap_or_else(|| {
201 if let Some(ref manifest) = self.manifest_path {
202 WasmPath::with_maybe_only_manifest(manifest.clone())
203 } else {
204 WasmPath::with_maybe_none()
205 }
206 })?;
207 if let Some(ref manifest) = self.manifest_path {
208 if let WasmPath::Maybe { manifest_path, .. } = &mut p {
209 *manifest_path = manifest.clone();
210 }
211 }
212 Ok(p)
213 }
214
215 pub fn get_wasm_paths(&self) -> Box<[WasmPath]> {
217 let mut paths = self.wasm.clone();
218 if let Some(ref manifest) = self.manifest_path {
219 for p in &mut paths {
220 if let WasmPath::Maybe { manifest_path, .. } = p {
221 *manifest_path = manifest.clone();
222 }
223 }
224 }
225 paths.into_boxed_slice()
226 }
227}
228
229impl PostBuildContext for BuildArgs {
230 fn out_dir(&self) -> &Utf8PathBuf {
231 &self.out_dir
232 }
233
234 fn keep_build_artifacts(&self) -> bool {
235 self.keep_build_artifacts
236 }
237
238 fn adjust_abi(&self) -> bool {
239 self.adjust_abi
240 }
241
242 fn transpile_to_js(
243 &self,
244 component: &[u8],
245 name: impl AsRef<str>,
246 ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
247 self.transpile_opts.transpile_to_js(component, name)
248 }
249
250 fn dev(&self) -> bool {
251 self.dev
252 }
253}
254
255#[derive(Parser, Debug)]
256#[clap(author, version, about, long_about = None, help_template = "
257{name} {version}
258{author}
259{about}
260
261{usage-heading} {usage}
262
263{all-args}")]
264pub struct PreBuildArgs {
266 pub wasm: Vec<WasmPath>,
273
274 #[arg(short, long)]
276 package: Option<WasmPath>,
277
278 #[arg(long)]
280 pub manifest_path: Option<Utf8PathBuf>,
281
282 #[arg(long)]
284 wasm_memory_hint: Vec<isize>,
285
286 #[arg(long, default_value = "./dist")]
288 pub out_dir: Utf8PathBuf,
289
290 #[arg(short, long)]
293 pub target_memory_type: Option<TargetMemoryType>,
294
295 #[arg(long)]
298 pub threads: Option<bool>,
299
300 #[arg(long)]
304 pub dwarf: Option<bool>,
305
306 #[arg(long, default_value = "false")]
309 pub adjust_abi: bool,
310
311 #[arg(long, default_value = "false")]
313 pub keep_build_artifacts: bool,
314
315 #[arg(long, default_value = "false")]
317 pub dev: bool,
318
319 #[command(flatten)]
321 pub vfs_build_opts: VfsBuildOptions,
322
323 #[arg(skip)]
325 pub target_vfs_build_opts: Option<Box<[VfsBuildOptions]>>,
326}
327
328impl PreBuildArgs {
329 pub fn get_wasm_memory_hints(&self) -> Box<[Option<usize>]> {
331 self.wasm_memory_hint
332 .iter()
333 .map(|&hint| if hint < 0 { None } else { Some(hint as usize) })
334 .chain(std::iter::repeat(None))
335 .take(self.wasm.len())
336 .collect::<Box<_>>()
337 }
338
339 pub fn get_package(&self) -> eyre::Result<WasmPath> {
341 let mut p = Ok(self.package.clone()).transpose().unwrap_or_else(|| {
342 if let Some(ref manifest) = self.manifest_path {
343 WasmPath::with_maybe_only_manifest(manifest.clone())
344 } else {
345 WasmPath::with_maybe_none()
346 }
347 })?;
348 if let Some(ref manifest) = self.manifest_path {
349 if let WasmPath::Maybe { manifest_path, .. } = &mut p {
350 *manifest_path = manifest.clone();
351 }
352 }
353 Ok(p)
354 }
355
356 pub fn get_wasm_paths(&self) -> Box<[WasmPath]> {
358 let mut paths = self.wasm.clone();
359 if let Some(ref manifest) = self.manifest_path {
360 for p in &mut paths {
361 if let WasmPath::Maybe { manifest_path, .. } = p {
362 *manifest_path = manifest.clone();
363 }
364 }
365 }
366 paths.into_boxed_slice()
367 }
368}
369
370#[derive(Parser, Debug)]
371#[clap(author, version, about, long_about = None, help_template = "
372{name} {version}
373{author}
374{about}
375
376{usage-heading} {usage}
377
378{all-args}")]
379pub struct PostBuildArgs {
381 #[arg(short, long)]
383 pub package: WasmPath,
384
385 #[arg(long, default_value = "./dist")]
387 pub out_dir: Utf8PathBuf,
388
389 #[command(flatten)]
391 pub transpile_opts: TranspileOpts,
392
393 #[arg(long)]
395 pub dwarf: Option<bool>,
396
397 #[arg(long, default_value = "false")]
400 pub adjust_abi: bool,
401
402 #[arg(long, default_value = "false")]
404 pub keep_build_artifacts: bool,
405
406 #[arg(long, default_value = "false")]
408 pub dev: bool,
409}
410
411impl PostBuildContext for PostBuildArgs {
412 fn out_dir(&self) -> &Utf8PathBuf {
413 &self.out_dir
414 }
415
416 fn keep_build_artifacts(&self) -> bool {
417 self.keep_build_artifacts
418 }
419
420 fn adjust_abi(&self) -> bool {
421 self.adjust_abi
422 }
423
424 fn transpile_to_js(
425 &self,
426 component: &[u8],
427 name: impl AsRef<str>,
428 ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
429 self.transpile_opts.transpile_to_js(component, name)
430 }
431
432 fn dev(&self) -> bool {
433 self.dev
434 }
435}
436
437#[derive(Parser, Debug)]
439#[clap(author, version, about, long_about = None, help_template = "
440{name} {version}
441{author}
442{about}
443
444{usage-heading} {usage}
445
446{all-args}")]
447pub struct TranspileOpts {
448 #[arg(long, default_value = "false")]
450 no_typescript: bool,
451
452 #[arg(long, value_parser = analysis::analysis_instantiation, default_value = "CustomInstantiationMode(None)")]
455 instantiation: CustomInstantiationMode,
456
457 #[arg(long, value_parser = analysis::analysis_import_bindings)]
459 import_bindings: Option<js_component_bindgen::BindingsMode>,
460
461 #[arg(long, value_delimiter = ',', value_parser = analysis::parse_mapping, action = clap::ArgAction::Append)]
463 map: Vec<(String, String)>,
464
465 #[arg(long, default_value = "false")]
467 no_nodejs_compat: bool,
468
469 #[arg(long, default_value = "0")]
471 base64_cutoff: usize,
472
473 #[arg(long, default_value = "false")]
475 tla_compat: bool,
476
477 #[arg(long, default_value = "false")]
479 valid_lifting_optimization: bool,
480
481 #[arg(long, default_value = "false")]
483 tracing: bool,
484
485 #[arg(long, default_value = "false")]
487 no_namespaced_exports: bool,
488
489 #[arg(long, default_value = "false")]
491 pub guest: bool,
492}
493
494impl TranspileOpts {
495 pub fn transpile_to_js(
497 &self,
498 component: &[u8],
499 name: impl AsRef<str>,
500 ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
501 js_component_bindgen::transpile(
502 component,
503 js_component_bindgen::TranspileOpts {
504 name: name.as_ref().to_string(),
505 no_typescript: self.no_typescript,
506 instantiation_mode: self.instantiation.clone().0,
507 import_bindings: self.import_bindings.clone(),
508 map: if !self.map.is_empty() {
509 Some(self.map.iter().cloned().collect())
510 } else {
511 None
512 },
513 nodejs_compat_disabled: self.no_nodejs_compat,
514 base64_cutoff: self.base64_cutoff,
515 tla_compat: self.tla_compat,
516 valid_lifting_optimization: self.valid_lifting_optimization,
517 tracing: self.tracing,
518 no_namespaced_exports: self.no_namespaced_exports,
519 multi_memory: true,
520 guest: self.guest,
521 async_mode: None,
522 strict: false,
523 asmjs: false,
524 },
525 )
526 .to_eyre()
527 .wrap_err("Failed to transpile to JS.")
528 }
529}
530
531#[derive(Clone, Debug)]
533pub struct CustomInstantiationMode(Option<js_component_bindgen::InstantiationMode>);
534
535pub(super) mod analysis {
536 use js_component_bindgen::{BindingsMode, InstantiationMode};
537
538 use super::CustomInstantiationMode;
539
540 pub fn analysis_instantiation(s: &str) -> Result<CustomInstantiationMode, clap::Error> {
541 match s {
542 "Sync" => Ok(CustomInstantiationMode(Some(InstantiationMode::Sync))),
543 "Async" => Ok(CustomInstantiationMode(Some(InstantiationMode::Async))),
544 "Normal" => Ok(CustomInstantiationMode(None)),
545 _ => Ok(CustomInstantiationMode(Some(InstantiationMode::Async))),
546 }
547 }
548
549 pub fn analysis_import_bindings(s: &str) -> Result<Option<BindingsMode>, clap::Error> {
550 match s {
551 "Hybrid" => Ok(Some(BindingsMode::Hybrid)),
552 "Js" => Ok(Some(BindingsMode::Js)),
553 "Optimized" => Ok(Some(BindingsMode::Optimized)),
554 "DirectOptimized" => Ok(Some(BindingsMode::DirectOptimized)),
555 _ => Ok(None),
556 }
557 }
558
559 pub fn parse_mapping(s: &str) -> Result<(String, String), String> {
560 let parts: Vec<&str> = s.splitn(2, '=').collect();
561 if parts.len() != 2 {
562 return Err(format!("Invalid mapping format: '{}'", s));
563 }
564 Ok((parts[0].to_string(), parts[1].to_string()))
565 }
566}
567
568#[derive(Debug, Clone, Copy, PartialEq, strum::EnumString, strum::Display)]
570pub enum TargetMemoryType {
571 #[strum(ascii_case_insensitive)]
573 Single,
574 #[strum(ascii_case_insensitive)]
576 Multi,
577}
578
579impl TargetMemoryType {
580 pub fn is_multi(&self) -> bool {
582 matches!(self, TargetMemoryType::Multi)
583 }
584
585 pub fn is_single(&self) -> bool {
587 matches!(self, TargetMemoryType::Single)
588 }
589}
590
591#[derive(Parser, Debug, Clone, Default)]
593pub struct VfsBuildOptions {
594 #[arg(long, action = clap::ArgAction::Append)]
596 pub features: Vec<String>,
597
598 #[arg(long, action = clap::ArgAction::Count)]
600 pub no_default_features: u8,
601
602 #[arg(long, action = clap::ArgAction::Count)]
604 pub no_opt: u8,
605
606 #[arg(long, action = clap::ArgAction::Count)]
608 pub no_opt_all: u8,
609}