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)]
26#[clap(propagate_version = true)]
27pub struct Cli {
28 #[clap(subcommand)]
30 pub command: Command,
31}
32
33#[derive(Subcommand, Debug)]
34pub enum Command {
36 Build(BuildArgs),
38 Prebuild(PreBuildArgs),
40 Postbuild(PostBuildArgs),
42 New(NewArgs),
44 PrepareTarget(PrepareTargetArgs),
46}
47
48#[derive(Parser, Debug)]
49pub struct NewArgs {
51 #[arg(value_name = "PATH")]
53 pub path: Utf8PathBuf,
54
55 #[arg(long, default_value = "false")]
57 pub threads: bool,
58}
59
60#[derive(Parser, Debug)]
61pub struct PrepareTargetArgs {
63 #[arg(value_name = "TARGET_WASM")]
65 pub target_wasm: Utf8PathBuf,
66
67 #[arg(short, long, value_name = "OUTPUT")]
69 pub output: Option<Utf8PathBuf>,
70
71 #[arg(long, default_value = "false")]
73 pub keep_artifacts: bool,
74}
75
76#[derive(Parser, Debug)]
77pub struct BuildArgs {
79 pub wasm: Vec<WasmPath>,
86
87 #[arg(short, long)]
89 package: Option<WasmPath>,
90
91 #[arg(long)]
93 pub manifest_path: Option<Utf8PathBuf>,
94
95 #[arg(long)]
97 wasm_memory_hint: Vec<isize>,
98
99 #[arg(long, default_value = "./dist")]
101 pub out_dir: Utf8PathBuf,
102
103 #[arg(short, long)]
106 pub target_memory_type: Option<TargetMemoryType>,
107
108 #[command(flatten)]
111 pub transpile_opts: TranspileOpts,
112
113 #[arg(long)]
116 pub threads: Option<bool>,
117
118 #[arg(long)]
122 pub dwarf: Option<bool>,
123
124 #[arg(long, default_value = "false")]
127 pub adjust_abi: bool,
128
129 #[arg(long, default_value = "false")]
131 pub keep_build_artifacts: bool,
132}
133
134impl BuildArgs {
135 pub fn get_wasm_memory_hints(&self) -> Box<[Option<usize>]> {
137 self.wasm_memory_hint
138 .iter()
139 .map(|&hint| if hint < 0 { None } else { Some(hint as usize) })
140 .chain(std::iter::repeat(None))
141 .take(self.wasm.len())
142 .collect::<Box<_>>()
143 }
144
145 pub fn get_package(&self) -> eyre::Result<WasmPath> {
147 let mut p = Ok(self.package.clone()).transpose().unwrap_or_else(|| {
148 if let Some(ref manifest) = self.manifest_path {
149 WasmPath::with_maybe_only_manifest(manifest.clone())
150 } else {
151 WasmPath::with_maybe_none()
152 }
153 })?;
154 if let Some(ref manifest) = self.manifest_path {
155 if let WasmPath::Maybe { manifest_path, .. } = &mut p {
156 *manifest_path = manifest.clone();
157 }
158 }
159 Ok(p)
160 }
161
162 pub fn get_wasm_paths(&self) -> Box<[WasmPath]> {
164 let mut paths = self.wasm.clone();
165 if let Some(ref manifest) = self.manifest_path {
166 for p in &mut paths {
167 if let WasmPath::Maybe { manifest_path, .. } = p {
168 *manifest_path = manifest.clone();
169 }
170 }
171 }
172 paths.into_boxed_slice()
173 }
174}
175
176impl PostBuildContext for BuildArgs {
177 fn out_dir(&self) -> &Utf8PathBuf {
178 &self.out_dir
179 }
180
181 fn keep_build_artifacts(&self) -> bool {
182 self.keep_build_artifacts
183 }
184
185 fn adjust_abi(&self) -> bool {
186 self.adjust_abi
187 }
188
189 fn transpile_to_js(
190 &self,
191 component: &[u8],
192 name: impl AsRef<str>,
193 ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
194 self.transpile_opts.transpile_to_js(component, name)
195 }
196}
197
198#[derive(Parser, Debug)]
199pub struct PreBuildArgs {
201 pub wasm: Vec<WasmPath>,
208
209 #[arg(short, long)]
211 package: Option<WasmPath>,
212
213 #[arg(long)]
215 pub manifest_path: Option<Utf8PathBuf>,
216
217 #[arg(long)]
219 wasm_memory_hint: Vec<isize>,
220
221 #[arg(long, default_value = "./dist")]
223 pub out_dir: Utf8PathBuf,
224
225 #[arg(short, long)]
228 pub target_memory_type: Option<TargetMemoryType>,
229
230 #[arg(long)]
233 pub threads: Option<bool>,
234
235 #[arg(long)]
239 pub dwarf: Option<bool>,
240
241 #[arg(long, default_value = "false")]
244 pub adjust_abi: bool,
245
246 #[arg(long, default_value = "false")]
248 pub keep_build_artifacts: bool,
249}
250
251impl PreBuildArgs {
252 pub fn get_wasm_memory_hints(&self) -> Box<[Option<usize>]> {
254 self.wasm_memory_hint
255 .iter()
256 .map(|&hint| if hint < 0 { None } else { Some(hint as usize) })
257 .chain(std::iter::repeat(None))
258 .take(self.wasm.len())
259 .collect::<Box<_>>()
260 }
261
262 pub fn get_package(&self) -> eyre::Result<WasmPath> {
264 let mut p = Ok(self.package.clone()).transpose().unwrap_or_else(|| {
265 if let Some(ref manifest) = self.manifest_path {
266 WasmPath::with_maybe_only_manifest(manifest.clone())
267 } else {
268 WasmPath::with_maybe_none()
269 }
270 })?;
271 if let Some(ref manifest) = self.manifest_path {
272 if let WasmPath::Maybe { manifest_path, .. } = &mut p {
273 *manifest_path = manifest.clone();
274 }
275 }
276 Ok(p)
277 }
278
279 pub fn get_wasm_paths(&self) -> Box<[WasmPath]> {
281 let mut paths = self.wasm.clone();
282 if let Some(ref manifest) = self.manifest_path {
283 for p in &mut paths {
284 if let WasmPath::Maybe { manifest_path, .. } = p {
285 *manifest_path = manifest.clone();
286 }
287 }
288 }
289 paths.into_boxed_slice()
290 }
291}
292
293#[derive(Parser, Debug)]
294pub struct PostBuildArgs {
296 #[arg(short, long)]
298 pub package: WasmPath,
299
300 #[arg(long, default_value = "./dist")]
302 pub out_dir: Utf8PathBuf,
303
304 #[command(flatten)]
306 pub transpile_opts: TranspileOpts,
307
308 #[arg(long)]
310 pub dwarf: Option<bool>,
311
312 #[arg(long, default_value = "false")]
315 pub adjust_abi: bool,
316
317 #[arg(long, default_value = "false")]
319 pub keep_build_artifacts: bool,
320}
321
322impl PostBuildContext for PostBuildArgs {
323 fn out_dir(&self) -> &Utf8PathBuf {
324 &self.out_dir
325 }
326
327 fn keep_build_artifacts(&self) -> bool {
328 self.keep_build_artifacts
329 }
330
331 fn adjust_abi(&self) -> bool {
332 self.adjust_abi
333 }
334
335 fn transpile_to_js(
336 &self,
337 component: &[u8],
338 name: impl AsRef<str>,
339 ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
340 self.transpile_opts.transpile_to_js(component, name)
341 }
342}
343
344#[derive(Parser, Debug)]
346pub struct TranspileOpts {
347 #[arg(long, default_value = "false")]
349 no_typescript: bool,
350
351 #[arg(long, value_parser = analysis::analysis_instantiation, default_value = "CustomInstantiationMode(None)")]
354 instantiation: CustomInstantiationMode,
355
356 #[arg(long, value_parser = analysis::analysis_import_bindings)]
358 import_bindings: Option<js_component_bindgen::BindingsMode>,
359
360 #[arg(long, value_delimiter = ',', value_parser = analysis::parse_mapping, action = clap::ArgAction::Append)]
362 map: Vec<(String, String)>,
363
364 #[arg(long, default_value = "false")]
366 no_nodejs_compat: bool,
367
368 #[arg(long, default_value = "0")]
370 base64_cutoff: usize,
371
372 #[arg(long, default_value = "false")]
374 tla_compat: bool,
375
376 #[arg(long, default_value = "false")]
378 valid_lifting_optimization: bool,
379
380 #[arg(long, default_value = "false")]
382 tracing: bool,
383
384 #[arg(long, default_value = "false")]
386 no_namespaced_exports: bool,
387
388 #[arg(long, default_value = "false")]
390 pub guest: bool,
391}
392
393impl TranspileOpts {
394 pub fn transpile_to_js(
396 &self,
397 component: &[u8],
398 name: impl AsRef<str>,
399 ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
400 js_component_bindgen::transpile(
401 component,
402 js_component_bindgen::TranspileOpts {
403 name: name.as_ref().to_string(),
404 no_typescript: self.no_typescript,
405 instantiation: self.instantiation.clone().0,
406 import_bindings: self.import_bindings.clone(),
407 map: if !self.map.is_empty() {
408 Some(self.map.iter().cloned().collect())
409 } else {
410 None
411 },
412 no_nodejs_compat: self.no_nodejs_compat,
413 base64_cutoff: self.base64_cutoff,
414 tla_compat: self.tla_compat,
415 valid_lifting_optimization: self.valid_lifting_optimization,
416 tracing: self.tracing,
417 no_namespaced_exports: self.no_namespaced_exports,
418 multi_memory: true,
419 guest: self.guest,
420 async_mode: None,
421 strict: false,
422 asmjs: false,
423 },
424 )
425 .to_eyre()
426 .wrap_err("Failed to transpile to JS.")
427 }
428}
429
430#[derive(Clone, Debug)]
432pub struct CustomInstantiationMode(Option<js_component_bindgen::InstantiationMode>);
433
434pub(super) mod analysis {
435 use js_component_bindgen::{BindingsMode, InstantiationMode};
436
437 use super::CustomInstantiationMode;
438
439 pub fn analysis_instantiation(s: &str) -> Result<CustomInstantiationMode, clap::Error> {
440 match s {
441 "Sync" => Ok(CustomInstantiationMode(Some(InstantiationMode::Sync))),
442 "Async" => Ok(CustomInstantiationMode(Some(InstantiationMode::Async))),
443 "Normal" => Ok(CustomInstantiationMode(None)),
444 _ => Ok(CustomInstantiationMode(Some(InstantiationMode::Async))),
445 }
446 }
447
448 pub fn analysis_import_bindings(s: &str) -> Result<Option<BindingsMode>, clap::Error> {
449 match s {
450 "Hybrid" => Ok(Some(BindingsMode::Hybrid)),
451 "Js" => Ok(Some(BindingsMode::Js)),
452 "Optimized" => Ok(Some(BindingsMode::Optimized)),
453 "DirectOptimized" => Ok(Some(BindingsMode::DirectOptimized)),
454 _ => Ok(None),
455 }
456 }
457
458 pub fn parse_mapping(s: &str) -> Result<(String, String), String> {
459 let parts: Vec<&str> = s.splitn(2, '=').collect();
460 if parts.len() != 2 {
461 return Err(format!("Invalid mapping format: '{}'", s));
462 }
463 Ok((parts[0].to_string(), parts[1].to_string()))
464 }
465}
466
467#[derive(Debug, Clone, Copy, PartialEq, strum::EnumString, strum::Display)]
469pub enum TargetMemoryType {
470 #[strum(ascii_case_insensitive)]
472 Single,
473 #[strum(ascii_case_insensitive)]
475 Multi,
476}
477
478impl TargetMemoryType {
479 pub fn is_multi(&self) -> bool {
481 matches!(self, TargetMemoryType::Multi)
482 }
483
484 pub fn is_single(&self) -> bool {
486 matches!(self, TargetMemoryType::Single)
487 }
488}