1use camino::Utf8PathBuf;
2use clap::{Parser, Subcommand};
3use compact_str::CompactString;
4use eyre::Context as _;
5
6use crate::{generator::WasmPath, util::ResultUtil as _};
7
8pub trait PostBuildContext {
10 fn out_dir(&self) -> &Utf8PathBuf;
12 fn keep_build_artifacts(&self) -> bool;
14 fn adjust_abi(&self) -> bool;
16 fn transpile_to_js(
18 &self,
19 component: &[u8],
20 name: impl AsRef<str>,
21 ) -> Result<js_component_bindgen::Transpiled, eyre::Error>;
22}
23
24#[derive(Parser, Debug)]
26#[clap(author, version, about, long_about = None)]
27#[clap(propagate_version = true)]
28pub struct Cli {
29 #[clap(subcommand)]
31 pub command: Command,
32}
33
34#[derive(Subcommand, Debug)]
35pub enum Command {
37 Build(BuildArgs),
39 Prebuild(PreBuildArgs),
41 Postbuild(PostBuildArgs),
43 New(NewArgs),
45 PrepareTarget(PrepareTargetArgs),
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 PrepareTargetArgs {
64 #[arg(value_name = "TARGET_WASM")]
66 pub target_wasm: Utf8PathBuf,
67
68 #[arg(short, long, value_name = "OUTPUT")]
70 pub output: Option<Utf8PathBuf>,
71
72 #[arg(long, default_value = "false")]
74 pub keep_artifacts: bool,
75}
76
77#[derive(Parser, Debug)]
78pub struct BuildArgs {
80 pub wasm: Vec<WasmPath>,
87
88 #[arg(short, long)]
90 package: Option<WasmPath>,
91
92 #[arg(long)]
94 wasm_memory_hint: Vec<isize>,
95
96 #[arg(long, default_value = "./dist")]
98 pub out_dir: Utf8PathBuf,
99
100 #[arg(short, long)]
103 pub target_memory_type: Option<TargetMemoryType>,
104
105 #[command(flatten)]
108 pub transpile_opts: TranspileOpts,
109
110 #[arg(long)]
113 pub threads: Option<bool>,
114
115 #[arg(long)]
119 pub dwarf: Option<bool>,
120
121 #[arg(long, default_value = "false")]
124 pub adjust_abi: bool,
125
126 #[arg(long, default_value = "false")]
128 pub keep_build_artifacts: bool,
129}
130
131impl BuildArgs {
132 pub fn get_wasm_memory_hints(&self) -> Box<[Option<usize>]> {
134 self.wasm_memory_hint
135 .iter()
136 .map(|&hint| if hint < 0 { None } else { Some(hint as usize) })
137 .chain(std::iter::repeat(None))
138 .take(self.wasm.len())
139 .collect::<Box<_>>()
140 }
141
142 pub fn get_package(&self) -> eyre::Result<WasmPath> {
144 Ok(self.package.clone())
145 .transpose()
146 .unwrap_or_else(|| WasmPath::with_maybe_none())
147 }
148
149 pub fn get_manifest_path(&self) -> Option<&Utf8PathBuf> {
151 self.package.as_ref().and_then(|p| p.manifest_path())
152 }
153
154 pub fn get_package_name(&self) -> Option<CompactString> {
156 self.package.clone().and_then(|p| p.name().ok())
157 }
158}
159
160impl PostBuildContext for BuildArgs {
161 fn out_dir(&self) -> &Utf8PathBuf {
162 &self.out_dir
163 }
164
165 fn keep_build_artifacts(&self) -> bool {
166 self.keep_build_artifacts
167 }
168
169 fn adjust_abi(&self) -> bool {
170 self.adjust_abi
171 }
172
173 fn transpile_to_js(
174 &self,
175 component: &[u8],
176 name: impl AsRef<str>,
177 ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
178 self.transpile_opts.transpile_to_js(component, name)
179 }
180}
181
182#[derive(Parser, Debug)]
183pub struct PreBuildArgs {
185 pub wasm: Vec<WasmPath>,
192
193 #[arg(short, long)]
195 package: Option<WasmPath>,
196
197 #[arg(long)]
199 wasm_memory_hint: Vec<isize>,
200
201 #[arg(long, default_value = "./dist")]
203 pub out_dir: Utf8PathBuf,
204
205 #[arg(short, long)]
208 pub target_memory_type: Option<TargetMemoryType>,
209
210 #[arg(long)]
213 pub threads: Option<bool>,
214
215 #[arg(long)]
219 pub dwarf: Option<bool>,
220
221 #[arg(long, default_value = "false")]
224 pub adjust_abi: bool,
225
226 #[arg(long, default_value = "false")]
228 pub keep_build_artifacts: bool,
229}
230
231impl PreBuildArgs {
232 pub fn get_wasm_memory_hints(&self) -> Box<[Option<usize>]> {
234 self.wasm_memory_hint
235 .iter()
236 .map(|&hint| if hint < 0 { None } else { Some(hint as usize) })
237 .chain(std::iter::repeat(None))
238 .take(self.wasm.len())
239 .collect::<Box<_>>()
240 }
241
242 pub fn get_package(&self) -> eyre::Result<WasmPath> {
244 Ok(self.package.clone())
245 .transpose()
246 .unwrap_or_else(|| WasmPath::with_maybe_none())
247 }
248}
249
250#[derive(Parser, Debug)]
251pub struct PostBuildArgs {
253 #[arg(short, long)]
255 pub package: WasmPath,
256
257 #[arg(long, default_value = "./dist")]
259 pub out_dir: Utf8PathBuf,
260
261 #[command(flatten)]
263 pub transpile_opts: TranspileOpts,
264
265 #[arg(long)]
267 pub dwarf: Option<bool>,
268
269 #[arg(long, default_value = "false")]
272 pub adjust_abi: bool,
273
274 #[arg(long, default_value = "false")]
276 pub keep_build_artifacts: bool,
277}
278
279impl PostBuildContext for PostBuildArgs {
280 fn out_dir(&self) -> &Utf8PathBuf {
281 &self.out_dir
282 }
283
284 fn keep_build_artifacts(&self) -> bool {
285 self.keep_build_artifacts
286 }
287
288 fn adjust_abi(&self) -> bool {
289 self.adjust_abi
290 }
291
292 fn transpile_to_js(
293 &self,
294 component: &[u8],
295 name: impl AsRef<str>,
296 ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
297 self.transpile_opts.transpile_to_js(component, name)
298 }
299}
300
301#[derive(Parser, Debug)]
303pub struct TranspileOpts {
304 #[arg(long, default_value = "false")]
306 no_typescript: bool,
307
308 #[arg(long, value_parser = analysis::analysis_instantiation, default_value = "CustomInstantiationMode(None)")]
311 instantiation: CustomInstantiationMode,
312
313 #[arg(long, value_parser = analysis::analysis_import_bindings)]
315 import_bindings: Option<js_component_bindgen::BindingsMode>,
316
317 #[arg(long, value_delimiter = ',', value_parser = analysis::parse_mapping, action = clap::ArgAction::Append)]
319 map: Vec<(String, String)>,
320
321 #[arg(long, default_value = "false")]
323 no_nodejs_compat: bool,
324
325 #[arg(long, default_value = "0")]
327 base64_cutoff: usize,
328
329 #[arg(long, default_value = "false")]
331 tla_compat: bool,
332
333 #[arg(long, default_value = "false")]
335 valid_lifting_optimization: bool,
336
337 #[arg(long, default_value = "false")]
339 tracing: bool,
340
341 #[arg(long, default_value = "false")]
343 no_namespaced_exports: bool,
344
345 #[arg(long, default_value = "false")]
347 pub guest: bool,
348}
349
350impl TranspileOpts {
351 pub fn transpile_to_js(
353 &self,
354 component: &[u8],
355 name: impl AsRef<str>,
356 ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
357 js_component_bindgen::transpile(
358 component,
359 js_component_bindgen::TranspileOpts {
360 name: name.as_ref().to_string(),
361 no_typescript: self.no_typescript,
362 instantiation: self.instantiation.clone().0,
363 import_bindings: self.import_bindings.clone(),
364 map: if !self.map.is_empty() {
365 Some(self.map.iter().cloned().collect())
366 } else {
367 None
368 },
369 no_nodejs_compat: self.no_nodejs_compat,
370 base64_cutoff: self.base64_cutoff,
371 tla_compat: self.tla_compat,
372 valid_lifting_optimization: self.valid_lifting_optimization,
373 tracing: self.tracing,
374 no_namespaced_exports: self.no_namespaced_exports,
375 multi_memory: true,
376 guest: self.guest,
377 async_mode: None,
378 strict: false,
379 asmjs: false,
380 },
381 )
382 .to_eyre()
383 .wrap_err("Failed to transpile to JS.")
384 }
385}
386
387#[derive(Clone, Debug)]
389pub struct CustomInstantiationMode(Option<js_component_bindgen::InstantiationMode>);
390
391pub(super) mod analysis {
392 use js_component_bindgen::{BindingsMode, InstantiationMode};
393
394 use super::CustomInstantiationMode;
395
396 pub fn analysis_instantiation(s: &str) -> Result<CustomInstantiationMode, clap::Error> {
397 match s {
398 "Sync" => Ok(CustomInstantiationMode(Some(InstantiationMode::Sync))),
399 "Async" => Ok(CustomInstantiationMode(Some(InstantiationMode::Async))),
400 "Normal" => Ok(CustomInstantiationMode(None)),
401 _ => Ok(CustomInstantiationMode(Some(InstantiationMode::Async))),
402 }
403 }
404
405 pub fn analysis_import_bindings(s: &str) -> Result<Option<BindingsMode>, clap::Error> {
406 match s {
407 "Hybrid" => Ok(Some(BindingsMode::Hybrid)),
408 "Js" => Ok(Some(BindingsMode::Js)),
409 "Optimized" => Ok(Some(BindingsMode::Optimized)),
410 "DirectOptimized" => Ok(Some(BindingsMode::DirectOptimized)),
411 _ => Ok(None),
412 }
413 }
414
415 pub fn parse_mapping(s: &str) -> Result<(String, String), String> {
416 let parts: Vec<&str> = s.splitn(2, '=').collect();
417 if parts.len() != 2 {
418 return Err(format!("Invalid mapping format: '{}'", s));
419 }
420 Ok((parts[0].to_string(), parts[1].to_string()))
421 }
422}
423
424#[derive(Debug, Clone, Copy, PartialEq, strum::EnumString, strum::Display)]
426pub enum TargetMemoryType {
427 #[strum(ascii_case_insensitive)]
429 Single,
430 #[strum(ascii_case_insensitive)]
432 Multi,
433}
434
435impl TargetMemoryType {
436 pub fn is_multi(&self) -> bool {
438 matches!(self, TargetMemoryType::Multi)
439 }
440
441 pub fn is_single(&self) -> bool {
443 matches!(self, TargetMemoryType::Single)
444 }
445}