1use std::collections::HashMap;
2
3use camino::Utf8PathBuf;
4use clap::{Parser, Subcommand};
5use compact_str::CompactString;
6use eyre::Context as _;
7
8use crate::{generator::WasmPath, util::ResultUtil as _};
9
10pub trait PostBuildContext {
12 fn out_dir(&self) -> &Utf8PathBuf;
14 fn keep_build_artifacts(&self) -> bool;
16 fn adjust_abi(&self) -> bool;
18 fn transpile_to_js(
20 &self,
21 component: &[u8],
22 name: impl AsRef<str>,
23 ) -> Result<js_component_bindgen::Transpiled, eyre::Error>;
24}
25
26#[derive(Parser, Debug)]
28#[clap(author, version, about, long_about = None)]
29#[clap(propagate_version = true)]
30pub struct Cli {
31 #[clap(subcommand)]
33 pub command: Command,
34}
35
36#[derive(Subcommand, Debug)]
37pub enum Command {
39 Build(BuildArgs),
41 Prebuild(PreBuildArgs),
43 Postbuild(PostBuildArgs),
45 New(NewArgs),
47}
48
49#[derive(Parser, Debug)]
50pub struct NewArgs {
52 #[arg(value_name = "PATH")]
54 pub path: Utf8PathBuf,
55
56 #[arg(long, default_value = "false")]
58 pub threads: bool,
59}
60
61#[derive(Parser, Debug)]
62pub struct BuildArgs {
64 pub wasm: Vec<WasmPath>,
71
72 #[arg(short, long)]
74 package: Option<WasmPath>,
75
76 #[arg(long)]
78 wasm_memory_hint: Vec<isize>,
79
80 #[arg(long, default_value = "./dist")]
82 pub out_dir: Utf8PathBuf,
83
84 #[arg(short, long)]
87 pub target_memory_type: Option<TargetMemoryType>,
88
89 #[command(flatten)]
92 pub transpile_opts: TranspileOpts,
93
94 #[arg(long)]
97 pub threads: Option<bool>,
98
99 #[arg(long)]
103 pub dwarf: Option<bool>,
104
105 #[arg(long, default_value = "false")]
108 pub adjust_abi: bool,
109
110 #[arg(long, default_value = "false")]
112 pub keep_build_artifacts: bool,
113}
114
115impl BuildArgs {
116 pub fn get_wasm_memory_hints(&self) -> Box<[Option<usize>]> {
118 self.wasm_memory_hint
119 .iter()
120 .map(|&hint| if hint < 0 { None } else { Some(hint as usize) })
121 .chain(std::iter::repeat(None))
122 .take(self.wasm.len())
123 .collect::<Box<_>>()
124 }
125
126 pub fn get_package(&self) -> eyre::Result<WasmPath> {
128 Ok(self.package.clone())
129 .transpose()
130 .unwrap_or_else(|| WasmPath::with_maybe_none())
131 }
132
133 pub fn get_manifest_path(&self) -> Option<&Utf8PathBuf> {
135 self.package.as_ref().and_then(|p| p.manifest_path())
136 }
137
138 pub fn get_package_name(&self) -> Option<CompactString> {
140 self.package.clone().and_then(|p| p.name().ok())
141 }
142}
143
144impl PostBuildContext for BuildArgs {
145 fn out_dir(&self) -> &Utf8PathBuf {
146 &self.out_dir
147 }
148
149 fn keep_build_artifacts(&self) -> bool {
150 self.keep_build_artifacts
151 }
152
153 fn adjust_abi(&self) -> bool {
154 self.adjust_abi
155 }
156
157 fn transpile_to_js(
158 &self,
159 component: &[u8],
160 name: impl AsRef<str>,
161 ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
162 self.transpile_opts.transpile_to_js(component, name)
163 }
164}
165
166#[derive(Parser, Debug)]
167pub struct PreBuildArgs {
169 pub wasm: Vec<WasmPath>,
176
177 #[arg(short, long)]
179 package: Option<WasmPath>,
180
181 #[arg(long)]
183 wasm_memory_hint: Vec<isize>,
184
185 #[arg(long, default_value = "./dist")]
187 pub out_dir: Utf8PathBuf,
188
189 #[arg(short, long)]
192 pub target_memory_type: Option<TargetMemoryType>,
193
194 #[arg(long)]
197 pub threads: Option<bool>,
198
199 #[arg(long)]
203 pub dwarf: Option<bool>,
204
205 #[arg(long, default_value = "false")]
208 pub adjust_abi: bool,
209
210 #[arg(long, default_value = "false")]
212 pub keep_build_artifacts: bool,
213}
214
215impl PreBuildArgs {
216 pub fn get_wasm_memory_hints(&self) -> Box<[Option<usize>]> {
218 self.wasm_memory_hint
219 .iter()
220 .map(|&hint| if hint < 0 { None } else { Some(hint as usize) })
221 .chain(std::iter::repeat(None))
222 .take(self.wasm.len())
223 .collect::<Box<_>>()
224 }
225
226 pub fn get_package(&self) -> eyre::Result<WasmPath> {
228 Ok(self.package.clone())
229 .transpose()
230 .unwrap_or_else(|| WasmPath::with_maybe_none())
231 }
232}
233
234#[derive(Parser, Debug)]
235pub struct PostBuildArgs {
237 #[arg(short, long)]
239 pub package: WasmPath,
240
241 #[arg(long, default_value = "./dist")]
243 pub out_dir: Utf8PathBuf,
244
245 #[command(flatten)]
247 pub transpile_opts: TranspileOpts,
248
249 #[arg(long)]
251 pub dwarf: Option<bool>,
252
253 #[arg(long, default_value = "false")]
256 pub adjust_abi: bool,
257
258 #[arg(long, default_value = "false")]
260 pub keep_build_artifacts: bool,
261}
262
263impl PostBuildContext for PostBuildArgs {
264 fn out_dir(&self) -> &Utf8PathBuf {
265 &self.out_dir
266 }
267
268 fn keep_build_artifacts(&self) -> bool {
269 self.keep_build_artifacts
270 }
271
272 fn adjust_abi(&self) -> bool {
273 self.adjust_abi
274 }
275
276 fn transpile_to_js(
277 &self,
278 component: &[u8],
279 name: impl AsRef<str>,
280 ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
281 self.transpile_opts.transpile_to_js(component, name)
282 }
283}
284
285#[derive(Parser, Debug)]
287pub struct TranspileOpts {
288 #[arg(long, default_value = "false")]
290 no_typescript: bool,
291
292 #[arg(long, value_parser = analysis::analysis_instantiation, default_value = "CustomInstantiationMode(None)")]
295 instantiation: CustomInstantiationMode,
296
297 #[arg(long, value_parser = analysis::analysis_import_bindings)]
299 import_bindings: Option<js_component_bindgen::BindingsMode>,
300
301 #[arg(long, value_delimiter = ',', value_parser = analysis::parse_mapping, num_args = 0.., action = clap::ArgAction::Append)]
303 map: Option<HashMap<String, String>>,
304
305 #[arg(long, default_value = "false")]
307 no_nodejs_compat: bool,
308
309 #[arg(long, default_value = "0")]
311 base64_cutoff: usize,
312
313 #[arg(long, default_value = "false")]
315 tla_compat: bool,
316
317 #[arg(long, default_value = "false")]
319 valid_lifting_optimization: bool,
320
321 #[arg(long, default_value = "false")]
323 tracing: bool,
324
325 #[arg(long, default_value = "false")]
327 no_namespaced_exports: bool,
328
329 #[arg(long, default_value = "false")]
331 pub guest: bool,
332}
333
334impl TranspileOpts {
335 pub fn transpile_to_js(
337 &self,
338 component: &[u8],
339 name: impl AsRef<str>,
340 ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
341 js_component_bindgen::transpile(
342 component,
343 js_component_bindgen::TranspileOpts {
344 name: name.as_ref().to_string(),
345 no_typescript: self.no_typescript,
346 instantiation: self.instantiation.clone().0,
347 import_bindings: self.import_bindings.clone(),
348 map: {
349 if let Some(opts_map) = &self.map {
350 let mut map = HashMap::new();
351 for (k, v) in opts_map.iter() {
352 map.insert(k.clone(), v.clone());
353 }
354 Some(map)
355 } else {
356 None
357 }
358 },
359 no_nodejs_compat: self.no_nodejs_compat,
360 base64_cutoff: self.base64_cutoff,
361 tla_compat: self.tla_compat,
362 valid_lifting_optimization: self.valid_lifting_optimization,
363 tracing: self.tracing,
364 no_namespaced_exports: self.no_namespaced_exports,
365 multi_memory: true,
366 guest: self.guest,
367 async_mode: None,
368 strict: false,
369 asmjs: false,
370 },
371 )
372 .to_eyre()
373 .wrap_err("Failed to transpile to JS.")
374 }
375}
376
377#[derive(Clone, Debug)]
379pub struct CustomInstantiationMode(Option<js_component_bindgen::InstantiationMode>);
380
381pub(super) mod analysis {
382 use js_component_bindgen::{BindingsMode, InstantiationMode};
383
384 use super::CustomInstantiationMode;
385
386 pub fn analysis_instantiation(s: &str) -> Result<CustomInstantiationMode, clap::Error> {
387 match s {
388 "Sync" => Ok(CustomInstantiationMode(Some(InstantiationMode::Sync))),
389 "Async" => Ok(CustomInstantiationMode(Some(InstantiationMode::Async))),
390 "Normal" => Ok(CustomInstantiationMode(None)),
391 _ => Ok(CustomInstantiationMode(Some(InstantiationMode::Async))),
392 }
393 }
394
395 pub fn analysis_import_bindings(s: &str) -> Result<Option<BindingsMode>, clap::Error> {
396 match s {
397 "Hybrid" => Ok(Some(BindingsMode::Hybrid)),
398 "Js" => Ok(Some(BindingsMode::Js)),
399 "Optimized" => Ok(Some(BindingsMode::Optimized)),
400 "DirectOptimized" => Ok(Some(BindingsMode::DirectOptimized)),
401 _ => Ok(None),
402 }
403 }
404
405 pub fn parse_mapping(s: &str) -> Result<(String, String), String> {
406 let parts: Vec<&str> = s.splitn(2, '=').collect();
407 if parts.len() != 2 {
408 return Err(format!("Invalid mapping format: '{}'", s));
409 }
410 Ok((parts[0].to_string(), parts[1].to_string()))
411 }
412}
413
414#[derive(Debug, Clone, Copy, PartialEq, strum::EnumString, strum::Display)]
416pub enum TargetMemoryType {
417 #[strum(ascii_case_insensitive)]
419 Single,
420 #[strum(ascii_case_insensitive)]
422 Multi,
423}
424
425impl TargetMemoryType {
426 pub fn is_multi(&self) -> bool {
428 matches!(self, TargetMemoryType::Multi)
429 }
430
431 pub fn is_single(&self) -> bool {
433 matches!(self, TargetMemoryType::Single)
434 }
435}