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}
22
23#[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 #[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}")]
49pub enum Command {
51 Build(BuildArgs),
53 Prebuild(PreBuildArgs),
55 Postbuild(PostBuildArgs),
57 New(NewArgs),
59 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}")]
72pub struct NewArgs {
74 #[arg(value_name = "PATH")]
76 pub path: Utf8PathBuf,
77
78 #[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}")]
92pub struct PrepareTargetArgs {
94 #[arg(value_name = "TARGET_WASM")]
96 pub target_wasm: Utf8PathBuf,
97
98 #[arg(short, long, value_name = "OUTPUT")]
100 pub output: Option<Utf8PathBuf>,
101
102 #[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}")]
116pub struct BuildArgs {
118 pub wasm: Vec<WasmPath>,
125
126 #[arg(short, long)]
128 package: Option<WasmPath>,
129
130 #[arg(long)]
132 pub manifest_path: Option<Utf8PathBuf>,
133
134 #[arg(long)]
136 wasm_memory_hint: Vec<isize>,
137
138 #[arg(long, default_value = "./dist")]
140 pub out_dir: Utf8PathBuf,
141
142 #[arg(short, long)]
145 pub target_memory_type: Option<TargetMemoryType>,
146
147 #[command(flatten)]
150 pub transpile_opts: TranspileOpts,
151
152 #[arg(long)]
155 pub threads: Option<bool>,
156
157 #[arg(long)]
161 pub dwarf: Option<bool>,
162
163 #[arg(long, default_value = "false")]
166 pub adjust_abi: bool,
167
168 #[arg(long, default_value = "false")]
170 pub keep_build_artifacts: bool,
171
172 #[command(flatten)]
174 pub vfs_build_opts: VfsBuildOptions,
175
176 #[arg(skip)]
178 pub target_vfs_build_opts: Option<Box<[VfsBuildOptions]>>,
179}
180
181impl BuildArgs {
182 pub fn get_wasm_memory_hints(&self) -> Box<[Option<usize>]> {
184 self.wasm_memory_hint
185 .iter()
186 .map(|&hint| if hint < 0 { None } else { Some(hint as usize) })
187 .chain(std::iter::repeat(None))
188 .take(self.wasm.len())
189 .collect::<Box<_>>()
190 }
191
192 pub fn get_package(&self) -> eyre::Result<WasmPath> {
194 let mut p = Ok(self.package.clone()).transpose().unwrap_or_else(|| {
195 if let Some(ref manifest) = self.manifest_path {
196 WasmPath::with_maybe_only_manifest(manifest.clone())
197 } else {
198 WasmPath::with_maybe_none()
199 }
200 })?;
201 if let Some(ref manifest) = self.manifest_path {
202 if let WasmPath::Maybe { manifest_path, .. } = &mut p {
203 *manifest_path = manifest.clone();
204 }
205 }
206 Ok(p)
207 }
208
209 pub fn get_wasm_paths(&self) -> Box<[WasmPath]> {
211 let mut paths = self.wasm.clone();
212 if let Some(ref manifest) = self.manifest_path {
213 for p in &mut paths {
214 if let WasmPath::Maybe { manifest_path, .. } = p {
215 *manifest_path = manifest.clone();
216 }
217 }
218 }
219 paths.into_boxed_slice()
220 }
221}
222
223impl PostBuildContext for BuildArgs {
224 fn out_dir(&self) -> &Utf8PathBuf {
225 &self.out_dir
226 }
227
228 fn keep_build_artifacts(&self) -> bool {
229 self.keep_build_artifacts
230 }
231
232 fn adjust_abi(&self) -> bool {
233 self.adjust_abi
234 }
235
236 fn transpile_to_js(
237 &self,
238 component: &[u8],
239 name: impl AsRef<str>,
240 ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
241 self.transpile_opts.transpile_to_js(component, name)
242 }
243}
244
245#[derive(Parser, Debug)]
246#[clap(author, version, about, long_about = None, help_template = "
247{name} {version}
248{author}
249{about}
250
251{usage-heading} {usage}
252
253{all-args}")]
254pub struct PreBuildArgs {
256 pub wasm: Vec<WasmPath>,
263
264 #[arg(short, long)]
266 package: Option<WasmPath>,
267
268 #[arg(long)]
270 pub manifest_path: Option<Utf8PathBuf>,
271
272 #[arg(long)]
274 wasm_memory_hint: Vec<isize>,
275
276 #[arg(long, default_value = "./dist")]
278 pub out_dir: Utf8PathBuf,
279
280 #[arg(short, long)]
283 pub target_memory_type: Option<TargetMemoryType>,
284
285 #[arg(long)]
288 pub threads: Option<bool>,
289
290 #[arg(long)]
294 pub dwarf: Option<bool>,
295
296 #[arg(long, default_value = "false")]
299 pub adjust_abi: bool,
300
301 #[arg(long, default_value = "false")]
303 pub keep_build_artifacts: bool,
304
305 #[command(flatten)]
307 pub vfs_build_opts: VfsBuildOptions,
308
309 #[arg(skip)]
311 pub target_vfs_build_opts: Option<Box<[VfsBuildOptions]>>,
312}
313
314impl PreBuildArgs {
315 pub fn get_wasm_memory_hints(&self) -> Box<[Option<usize>]> {
317 self.wasm_memory_hint
318 .iter()
319 .map(|&hint| if hint < 0 { None } else { Some(hint as usize) })
320 .chain(std::iter::repeat(None))
321 .take(self.wasm.len())
322 .collect::<Box<_>>()
323 }
324
325 pub fn get_package(&self) -> eyre::Result<WasmPath> {
327 let mut p = Ok(self.package.clone()).transpose().unwrap_or_else(|| {
328 if let Some(ref manifest) = self.manifest_path {
329 WasmPath::with_maybe_only_manifest(manifest.clone())
330 } else {
331 WasmPath::with_maybe_none()
332 }
333 })?;
334 if let Some(ref manifest) = self.manifest_path {
335 if let WasmPath::Maybe { manifest_path, .. } = &mut p {
336 *manifest_path = manifest.clone();
337 }
338 }
339 Ok(p)
340 }
341
342 pub fn get_wasm_paths(&self) -> Box<[WasmPath]> {
344 let mut paths = self.wasm.clone();
345 if let Some(ref manifest) = self.manifest_path {
346 for p in &mut paths {
347 if let WasmPath::Maybe { manifest_path, .. } = p {
348 *manifest_path = manifest.clone();
349 }
350 }
351 }
352 paths.into_boxed_slice()
353 }
354}
355
356#[derive(Parser, Debug)]
357#[clap(author, version, about, long_about = None, help_template = "
358{name} {version}
359{author}
360{about}
361
362{usage-heading} {usage}
363
364{all-args}")]
365pub struct PostBuildArgs {
367 #[arg(short, long)]
369 pub package: WasmPath,
370
371 #[arg(long, default_value = "./dist")]
373 pub out_dir: Utf8PathBuf,
374
375 #[command(flatten)]
377 pub transpile_opts: TranspileOpts,
378
379 #[arg(long)]
381 pub dwarf: Option<bool>,
382
383 #[arg(long, default_value = "false")]
386 pub adjust_abi: bool,
387
388 #[arg(long, default_value = "false")]
390 pub keep_build_artifacts: bool,
391}
392
393impl PostBuildContext for PostBuildArgs {
394 fn out_dir(&self) -> &Utf8PathBuf {
395 &self.out_dir
396 }
397
398 fn keep_build_artifacts(&self) -> bool {
399 self.keep_build_artifacts
400 }
401
402 fn adjust_abi(&self) -> bool {
403 self.adjust_abi
404 }
405
406 fn transpile_to_js(
407 &self,
408 component: &[u8],
409 name: impl AsRef<str>,
410 ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
411 self.transpile_opts.transpile_to_js(component, name)
412 }
413}
414
415#[derive(Parser, Debug)]
417#[clap(author, version, about, long_about = None, help_template = "
418{name} {version}
419{author}
420{about}
421
422{usage-heading} {usage}
423
424{all-args}")]
425pub struct TranspileOpts {
426 #[arg(long, default_value = "false")]
428 no_typescript: bool,
429
430 #[arg(long, value_parser = analysis::analysis_instantiation, default_value = "CustomInstantiationMode(None)")]
433 instantiation: CustomInstantiationMode,
434
435 #[arg(long, value_parser = analysis::analysis_import_bindings)]
437 import_bindings: Option<js_component_bindgen::BindingsMode>,
438
439 #[arg(long, value_delimiter = ',', value_parser = analysis::parse_mapping, action = clap::ArgAction::Append)]
441 map: Vec<(String, String)>,
442
443 #[arg(long, default_value = "false")]
445 no_nodejs_compat: bool,
446
447 #[arg(long, default_value = "0")]
449 base64_cutoff: usize,
450
451 #[arg(long, default_value = "false")]
453 tla_compat: bool,
454
455 #[arg(long, default_value = "false")]
457 valid_lifting_optimization: bool,
458
459 #[arg(long, default_value = "false")]
461 tracing: bool,
462
463 #[arg(long, default_value = "false")]
465 no_namespaced_exports: bool,
466
467 #[arg(long, default_value = "false")]
469 pub guest: bool,
470}
471
472impl TranspileOpts {
473 pub fn transpile_to_js(
475 &self,
476 component: &[u8],
477 name: impl AsRef<str>,
478 ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
479 js_component_bindgen::transpile(
480 component,
481 js_component_bindgen::TranspileOpts {
482 name: name.as_ref().to_string(),
483 no_typescript: self.no_typescript,
484 instantiation: self.instantiation.clone().0,
485 import_bindings: self.import_bindings.clone(),
486 map: if !self.map.is_empty() {
487 Some(self.map.iter().cloned().collect())
488 } else {
489 None
490 },
491 no_nodejs_compat: self.no_nodejs_compat,
492 base64_cutoff: self.base64_cutoff,
493 tla_compat: self.tla_compat,
494 valid_lifting_optimization: self.valid_lifting_optimization,
495 tracing: self.tracing,
496 no_namespaced_exports: self.no_namespaced_exports,
497 multi_memory: true,
498 guest: self.guest,
499 async_mode: None,
500 strict: false,
501 asmjs: false,
502 },
503 )
504 .to_eyre()
505 .wrap_err("Failed to transpile to JS.")
506 }
507}
508
509#[derive(Clone, Debug)]
511pub struct CustomInstantiationMode(Option<js_component_bindgen::InstantiationMode>);
512
513pub(super) mod analysis {
514 use js_component_bindgen::{BindingsMode, InstantiationMode};
515
516 use super::CustomInstantiationMode;
517
518 pub fn analysis_instantiation(s: &str) -> Result<CustomInstantiationMode, clap::Error> {
519 match s {
520 "Sync" => Ok(CustomInstantiationMode(Some(InstantiationMode::Sync))),
521 "Async" => Ok(CustomInstantiationMode(Some(InstantiationMode::Async))),
522 "Normal" => Ok(CustomInstantiationMode(None)),
523 _ => Ok(CustomInstantiationMode(Some(InstantiationMode::Async))),
524 }
525 }
526
527 pub fn analysis_import_bindings(s: &str) -> Result<Option<BindingsMode>, clap::Error> {
528 match s {
529 "Hybrid" => Ok(Some(BindingsMode::Hybrid)),
530 "Js" => Ok(Some(BindingsMode::Js)),
531 "Optimized" => Ok(Some(BindingsMode::Optimized)),
532 "DirectOptimized" => Ok(Some(BindingsMode::DirectOptimized)),
533 _ => Ok(None),
534 }
535 }
536
537 pub fn parse_mapping(s: &str) -> Result<(String, String), String> {
538 let parts: Vec<&str> = s.splitn(2, '=').collect();
539 if parts.len() != 2 {
540 return Err(format!("Invalid mapping format: '{}'", s));
541 }
542 Ok((parts[0].to_string(), parts[1].to_string()))
543 }
544}
545
546#[derive(Debug, Clone, Copy, PartialEq, strum::EnumString, strum::Display)]
548pub enum TargetMemoryType {
549 #[strum(ascii_case_insensitive)]
551 Single,
552 #[strum(ascii_case_insensitive)]
554 Multi,
555}
556
557impl TargetMemoryType {
558 pub fn is_multi(&self) -> bool {
560 matches!(self, TargetMemoryType::Multi)
561 }
562
563 pub fn is_single(&self) -> bool {
565 matches!(self, TargetMemoryType::Single)
566 }
567}
568
569#[derive(Parser, Debug, Clone, Default)]
571pub struct VfsBuildOptions {
572 #[arg(long, action = clap::ArgAction::Append)]
574 pub features: Vec<String>,
575
576 #[arg(long, action = clap::ArgAction::Count)]
578 pub no_default_features: u8,
579}