1use std::collections::HashSet;
2
3use anyhow::{Context as _, Result, anyhow, bail, ensure};
4use heck::ToShoutySnakeCase;
5use ts_bindgen::ts_bindgen;
6use wasmtime_environ::component::{CanonicalOptions, ComponentTypesBuilder, StaticModuleIndex};
7use wasmtime_environ::wasmparser::WasmFeatures;
8use wasmtime_environ::{PrimaryMap, ScopeVec, Tunables};
9use wit_bindgen_core::wit_parser::Function;
10use wit_component::DecodedWasm;
11use wit_parser::{Package, Resolve, Stability, Type, TypeDefKind, TypeId, WorldId};
12
13mod core;
14#[cfg(feature = "embedded-cm-runtime")]
15mod embedded_runtime;
16mod files;
17mod transpile_bindgen;
18mod ts_bindgen;
19
20pub mod esm_bindgen;
21pub mod function_bindgen;
22pub mod names;
23pub mod script;
24pub mod source;
25
26pub mod intrinsics;
27use intrinsics::Intrinsic;
28
29pub use transpile_bindgen::{
30 AsyncMode, BindingsMode, ExportKind, InstantiationMode, TranspileOpts,
31};
32use transpile_bindgen::{TranspileBindgenResult, transpile_bindgen};
33
34fn enum_case_name(name: &str, screaming_snake_case: bool) -> String {
35 if screaming_snake_case {
36 name.to_shouty_snake_case()
37 } else {
38 name.to_string()
39 }
40}
41
42#[macro_export]
49macro_rules! uwrite {
50 ($dst:expr, $($arg:tt)*) => {
51 write!($dst, $($arg)*).unwrap()
52 };
53}
54
55#[macro_export]
62macro_rules! uwriteln {
63 ($dst:expr, $($arg:tt)*) => {
64 writeln!($dst, $($arg)*).unwrap()
65 };
66}
67
68pub struct Transpiled {
69 pub files: Vec<(String, Vec<u8>)>,
70 pub imports: Vec<String>,
71 pub exports: Vec<(String, transpile_bindgen::ExportKind)>,
72}
73
74pub struct ComponentInfo {
75 pub imports: Vec<String>,
76 pub exports: Vec<(String, transpile_bindgen::ExportKind)>,
77}
78
79#[derive(Debug, Clone, Copy, bon::Builder)]
82#[non_exhaustive]
83pub struct TypeGenerationConfig {
84 #[builder(default = true)]
86 pub nominal_resources: bool,
87 #[builder(default = true)]
89 pub async_imports_may_return_sync: bool,
90 #[builder(default = true)]
92 pub typed_error_classes: bool,
93 #[builder(default = true)]
96 pub separate_interface_types: bool,
97}
98
99impl Default for TypeGenerationConfig {
100 fn default() -> Self {
101 Self::builder().build()
102 }
103}
104
105impl TypeGenerationConfig {
106 pub(crate) fn separate_interfaces(self) -> bool {
109 self.separate_interface_types
110 || self.nominal_resources
111 || self.async_imports_may_return_sync
112 || self.typed_error_classes
113 }
114}
115
116#[derive(Debug, Default, Clone, bon::Builder)]
123#[non_exhaustive]
124pub struct TranspileConfig {
125 #[builder(default)]
127 pub opts: TranspileOpts,
128 #[builder(default)]
130 pub call_tracking: bool,
131 #[builder(default)]
135 pub optional_result_payloads: bool,
136 #[builder(default)]
138 pub type_generation: TypeGenerationConfig,
139 #[cfg(feature = "external-runtime")]
146 pub cm_runtime_es_module: Option<String>,
147}
148
149pub fn generate_types(
150 name: &str,
151 resolve: Resolve,
152 world_id: WorldId,
153 opts: TranspileOpts,
154) -> Result<Vec<(String, Vec<u8>)>> {
155 generate_types_with_config(
156 name,
157 resolve,
158 world_id,
159 TranspileConfig::builder().opts(opts).build(),
160 )
161}
162
163pub fn generate_types_with_config(
165 name: &str,
166 resolve: Resolve,
167 world_id: WorldId,
168 mut config: TranspileConfig,
169) -> Result<Vec<(String, Vec<u8>)>> {
170 let opts = &mut config.opts;
171 normalize_namespace_object_options(opts)?;
172 let mut files = files::Files::default();
173
174 ts_bindgen(
175 name,
176 &resolve,
177 world_id,
178 opts,
179 config.call_tracking,
180 config.optional_result_payloads,
181 config.type_generation,
182 &mut files,
183 )
184 .context("failed to generate Typescript bindings")?;
185
186 let mut files_out: Vec<(String, Vec<u8>)> = Vec::new();
187 for (name, source) in files.iter() {
188 files_out.push((name.to_string(), source.to_vec()));
189 }
190 Ok(files_out)
191}
192
193#[cfg(feature = "transpile-bindgen")]
196pub fn transpile(component: &[u8], opts: TranspileOpts) -> Result<Transpiled> {
197 transpile_with_config(component, TranspileConfig::builder().opts(opts).build())
200}
201
202#[cfg(feature = "transpile-bindgen")]
205pub fn transpile_with_config(component: &[u8], mut config: TranspileConfig) -> Result<Transpiled> {
206 use wasmtime_environ::component::{Component, Translator};
207
208 normalize_transpile_config(&mut config)?;
209 let TranspileConfig {
210 mut opts,
211 call_tracking,
212 optional_result_payloads,
213 type_generation,
214 #[cfg(feature = "external-runtime")]
215 cm_runtime_es_module,
216 } = config;
217 #[cfg(not(feature = "external-runtime"))]
218 let cm_runtime_es_module: Option<String> = None;
219 #[cfg(feature = "embedded-cm-runtime")]
224 let bundle_runtime = cm_runtime_es_module.is_none();
225 #[cfg(feature = "embedded-cm-runtime")]
226 let cm_runtime_es_module =
227 cm_runtime_es_module.or_else(|| Some(embedded_runtime::PACKAGE.to_string()));
228 let name = opts.name.clone();
229 let mut files = files::Files::default();
230
231 let decoded = wit_component::decode(component)
238 .context("failed to extract interface information from component")?;
239
240 let (resolve, world_id) = match decoded {
241 DecodedWasm::WitPackage(_, _) => bail!("unexpected wit package as input"),
242 DecodedWasm::Component(resolve, world_id) => (resolve, world_id),
243 };
244
245 let scope = ScopeVec::new();
260 let tunables = Tunables::default_u32();
261
262 let mut features = WasmFeatures::WASM3
268 | WasmFeatures::WIDE_ARITHMETIC
269 | WasmFeatures::COMPONENT_MODEL
270 | WasmFeatures::CM_ASYNC
271 | WasmFeatures::CM_MORE_ASYNC_BUILTINS
272 | WasmFeatures::CM_ASYNC_STACKFUL
273 | WasmFeatures::CM_ERROR_CONTEXT
274 | WasmFeatures::CM_FIXED_LENGTH_LISTS
275 | WasmFeatures::CM_MAP
276 | WasmFeatures::CM_IMPLEMENTS
277 | WasmFeatures::CM_THREADING;
278
279 if !opts.supports_wasm_exnref {
285 features = features.difference(WasmFeatures::EXCEPTIONS);
286 }
287
288 let mut validator = wasmtime_environ::wasmparser::Validator::new_with_features(features);
289
290 let mut types = ComponentTypesBuilder::new(&validator);
291
292 let (component, modules) = Translator::new(&tunables, &mut validator, &mut types, &scope)
293 .translate(component)
294 .map_err(|e| anyhow!(e).context("failed to translate component"))?;
295
296 let modules: PrimaryMap<StaticModuleIndex, core::Translation<'_>> = modules
297 .into_iter()
298 .map(|(_i, module)| core::Translation::new(module, opts.multi_memory))
299 .collect::<Result<_>>()?;
300
301 let num_resource_tables = types.num_resource_tables();
302 let wasmtime_component = Component::default();
303 let types = types.finish(&wasmtime_component);
304
305 for (i, module) in modules.iter() {
308 files.push(&core_file_name(&name, i.as_u32()), module.wasm());
309 }
310
311 let TranspileBindgenResult {
312 imports,
313 exports,
314 inferred_async_exports,
315 } = transpile_bindgen(
316 &name,
317 &component,
318 &modules,
319 &types.0,
320 num_resource_tables,
321 &resolve,
322 world_id,
323 opts.clone(),
324 cm_runtime_es_module.as_deref(),
325 call_tracking,
326 type_generation.typed_error_classes,
327 &mut files,
328 );
329
330 if !opts.no_typescript {
331 if let Some(AsyncMode::JavaScriptPromiseIntegration { exports, .. }) = &mut opts.async_mode
332 {
333 exports.extend(inferred_async_exports);
334 }
335 ts_bindgen(
336 &name,
337 &resolve,
338 world_id,
339 &opts,
340 call_tracking,
341 optional_result_payloads,
342 type_generation,
343 &mut files,
344 )
345 .context("failed to generate Typescript bindings")?;
346 }
347
348 let mut files_out: Vec<(String, Vec<u8>)> = Vec::new();
349 for (name, source) in files.iter() {
350 #[cfg(feature = "embedded-cm-runtime")]
351 if bundle_runtime && name.ends_with(".js") {
352 let source = std::str::from_utf8(source)
353 .with_context(|| format!("generated module {name} is not UTF-8"))?;
354 if let Some(linked) = embedded_runtime::link(source)
355 .with_context(|| format!("failed to bundle the runtime into {name}"))?
356 {
357 files_out.push((name.to_string(), linked.into_bytes()));
358 continue;
359 }
360 }
361 files_out.push((name.to_string(), source.to_vec()));
362 }
363 Ok(Transpiled {
364 files: files_out,
365 imports,
366 exports,
367 })
368}
369
370fn normalize_namespace_object_options(opts: &mut TranspileOpts) -> Result<()> {
371 ensure!(
372 !(opts.use_namespace_objects && opts.variants_inline_cases),
373 "useNamespaceObjects cannot be combined with variantsInlineCases"
374 );
375 if opts.use_namespace_objects {
376 opts.flags_as_bigint = true;
377 }
378 Ok(())
379}
380
381fn normalize_transpile_config(config: &mut TranspileConfig) -> Result<()> {
382 normalize_namespace_object_options(&mut config.opts)?;
383 #[cfg(feature = "external-runtime")]
384 if let Some(cm_runtime_es_module) = &config.cm_runtime_es_module {
385 intrinsics::ext::module_specifier(cm_runtime_es_module, "runtime")?;
386 }
387 Ok(())
388}
389
390fn core_file_name(name: &str, idx: u32) -> String {
391 let i_str = if idx == 0 {
392 String::from("")
393 } else {
394 (idx + 1).to_string()
395 };
396 format!("{name}.core{i_str}.wasm")
397}
398
399pub fn dealias(resolve: &Resolve, mut id: TypeId) -> TypeId {
400 loop {
401 match &resolve.types[id].kind {
402 TypeDefKind::Type(Type::Id(that_id)) => id = *that_id,
403 _ => break id,
404 }
405 }
406}
407
408fn feature_gate_allowed(
411 resolve: &Resolve,
412 package: &Package,
413 stability: &Stability,
414 item_name: &str,
415) -> Result<bool> {
416 Ok(match stability {
417 Stability::Unknown => true,
418 Stability::Stable { since, .. } => {
419 let Some(package_version) = package.name.version.as_ref() else {
420 return Ok(true);
423 };
424
425 ensure!(
426 package_version >= since,
427 "feature gate on [{item_name}] refers to an unreleased (future) package version [{since}] (current package version is [{package_version}])"
428 );
429
430 true
432 }
433 Stability::Unstable {
434 feature,
435 deprecated: _,
436 } => {
437 resolve.all_features || resolve.features.contains(feature)
440 }
441 })
442}
443
444pub fn get_thrown_type(
446 resolve: &Resolve,
447 return_type: Option<Type>,
448) -> Option<(Option<&Type>, Option<&Type>)> {
449 match return_type {
450 None => None,
451 Some(Type::Id(id)) => match &resolve.types[id].kind {
452 TypeDefKind::Result(r) => Some((r.ok.as_ref(), r.err.as_ref())),
453 _ => None,
454 },
455 _ => None,
456 }
457}
458
459#[derive(Debug, Clone, PartialEq, Eq)]
467pub(crate) struct ResultErrorClass {
468 pub name: String,
470 pub payload_type_name: String,
472}
473
474pub(crate) fn result_error_class(
476 resolve: &Resolve,
477 interface: wit_parser::InterfaceId,
478 func: &Function,
479) -> Option<ResultErrorClass> {
480 use heck::ToUpperCamelCase as _;
481
482 let (_, Some(Type::Id(err))) = get_thrown_type(resolve, func.result)? else {
483 return None;
484 };
485 let payload_type_name = resolve.types[*err].name.clone()?;
486 let name = format!("{}Error", payload_type_name.to_upper_camel_case());
487
488 let is_declared = resolve.interfaces[interface]
491 .types
492 .iter()
493 .any(|(type_name, type_id)| {
494 if type_name.to_upper_camel_case() == name {
495 return true;
496 }
497 let TypeDefKind::Variant(variant) = &resolve.types[*type_id].kind else {
498 return false;
499 };
500 variant
501 .cases
502 .iter()
503 .any(|case| format!("{type_name}_{}", case.name).to_upper_camel_case() == name)
504 });
505 (!is_declared).then_some(ResultErrorClass {
506 name,
507 payload_type_name,
508 })
509}
510
511pub(crate) fn is_async_fn(func: &Function, canon_opts: &CanonicalOptions) -> bool {
520 if canon_opts.async_ {
521 return true;
522 }
523 func.kind.is_async()
524}
525
526enum FunctionIdentifier<'a> {
528 Fn(&'a Function),
529 CanonFnName(&'a str),
530}
531
532pub(crate) fn requires_async_porcelain(
548 func: FunctionIdentifier<'_>,
549 id: &str,
550 async_funcs: &HashSet<String>,
551) -> bool {
552 if async_funcs.contains("*") {
553 return true;
554 }
555
556 let name = match func {
557 FunctionIdentifier::Fn(func) => func.name.as_str(),
558 FunctionIdentifier::CanonFnName(name) => name,
559 }
560 .trim_start_matches("[async]");
561
562 if async_funcs.contains(name) {
563 return true;
564 }
565
566 let qualified_name = format!("{id}#{name}");
567 if async_funcs.contains(&qualified_name) {
568 return true;
569 }
570
571 if let Some(pos) = id.find('@') {
572 let namespace = &id[..pos];
573 let namespaced_name = format!("{namespace}#{name}");
574
575 if async_funcs.contains(&namespaced_name) {
576 return true;
577 }
578 }
579 false
580}
581
582trait ManagesIntrinsics {
584 fn add_intrinsic(&mut self, intrinsic: Intrinsic);
586}
587
588#[cfg(test)]
589mod tests {
590 use super::*;
591
592 const FLAGS_WIT: &str = r#"
593 package test:flag-values;
594
595 interface api {
596 flags permissions {
597 read,
598 write,
599 }
600 roundtrip: func(value: permissions) -> permissions;
601 }
602
603 world flag-values {
604 export api;
605 }
606 "#;
607
608 fn generated_javascript(transpiled: &Transpiled) -> &str {
609 transpiled
610 .files
611 .iter()
612 .find_map(|(name, contents)| {
613 name.ends_with(".js")
614 .then(|| std::str::from_utf8(contents).unwrap())
615 })
616 .unwrap()
617 }
618
619 #[cfg(feature = "transpile-bindgen")]
620 #[test]
621 fn async_export_returns_imported_resource_without_imported_functions() {
622 let component = wat::parse_str(
623 r#"
624 (component
625 (import "test:data/blob" (instance $data
626 (export "blob" (type (sub resource)))
627 ))
628 (alias export $data "blob" (type $blob))
629 (core func $task_return (canon task.return (result (own $blob))))
630 (core module $m
631 (import "" "task.return" (func $ret (param i32)))
632 (func (export "pass") (param i32) (result i32)
633 local.get 0 call $ret i32.const 0)
634 (func (export "cb") (param i32 i32 i32) (result i32)
635 i32.const 0)
636 )
637 (core instance $i (instantiate $m
638 (with "" (instance (export "task.return" (func $task_return))))))
639 (type $ft (func async (param "b" (own $blob)) (result (own $blob))))
640 (func (export "pass") (type $ft)
641 (canon lift (core func $i "pass") async (callback (core func $i "cb"))))
642 )
643 "#,
644 )
645 .unwrap();
646 for instantiation_mode in [
647 None,
648 Some(InstantiationMode::Async),
649 Some(InstantiationMode::Sync),
650 ] {
651 transpile(
652 &component,
653 TranspileOpts::builder()
654 .name("async-pass-imported-resource".into())
655 .maybe_instantiation_mode(instantiation_mode)
656 .build(),
657 )
658 .unwrap();
659 }
660 }
661
662 fn flags_interface(flags_as_bigint: bool) -> String {
663 let mut resolve = Resolve::default();
664 let package = resolve.push_str("flags.wit", FLAGS_WIT).unwrap();
665 let world = resolve
666 .select_world(&[package], Some("flag-values"))
667 .unwrap();
668 let files = generate_types(
669 "flags",
670 resolve,
671 world,
672 TranspileOpts::builder()
673 .name("flags".into())
674 .flags_as_bigint(flags_as_bigint)
675 .build(),
676 )
677 .unwrap();
678 let (_, contents) = files
679 .into_iter()
680 .find(|(name, _)| name.ends_with("api.d.ts"))
681 .unwrap();
682 String::from_utf8(contents).unwrap()
683 }
684
685 #[test]
686 fn flags_types_are_objects_by_default() {
687 let source = flags_interface(false);
688 assert!(source.contains("export interface Permissions"));
689 assert!(!source.contains("export const Permissions"));
690 }
691
692 #[test]
693 fn flags_types_can_be_bigints_with_constants() {
694 let source = flags_interface(true);
695 assert!(source.contains("export type Permissions = bigint;"));
696 assert!(source.contains("export const Permissions: {"));
697 assert!(source.contains("readonly Read: bigint"));
698 assert!(source.contains("readonly Write: bigint"));
699 }
700
701 #[test]
702 fn wildcard_marks_every_function_async() {
703 let async_funcs = HashSet::from(["*".to_string()]);
704 assert!(requires_async_porcelain(
705 FunctionIdentifier::CanonFnName("query"),
706 "jco:node/dns@0.1.0",
707 &async_funcs,
708 ));
709 assert!(requires_async_porcelain(
710 FunctionIdentifier::CanonFnName("run"),
711 "example:component/run@1.0.0",
712 &async_funcs,
713 ));
714 }
715
716 #[cfg(feature = "external-runtime")]
717 #[test]
718 fn validates_cm_runtime_es_module_specifiers() {
719 let mut default = TranspileConfig::default();
720 normalize_transpile_config(&mut default).unwrap();
721 assert!(default.cm_runtime_es_module.is_none());
722
723 let mut custom = TranspileConfig::builder()
724 .cm_runtime_es_module("./runtime".into())
725 .build();
726 normalize_transpile_config(&mut custom).unwrap();
727 assert_eq!(custom.cm_runtime_es_module.as_deref(), Some("./runtime"));
728
729 for invalid in ["", "runtime\nmodule"] {
730 let mut config = TranspileConfig::builder()
731 .cm_runtime_es_module(invalid.into())
732 .build();
733 assert!(normalize_transpile_config(&mut config).is_err());
734 }
735 }
736
737 #[cfg(all(feature = "transpile-bindgen", feature = "external-runtime"))]
738 #[test]
739 fn resource_rep_uses_named_runtime_exports() {
740 let component = wat::parse_str(
741 r#"
742 (component
743 (core module $module
744 (type $rep-type (func (param i32) (result i32)))
745 (import "intrinsics" "rep" (func $rep (type $rep-type)))
746 (func (export "run") (param i32) (result i32)
747 local.get 0
748 call $rep
749 )
750 )
751 (type $resource (resource (rep i32)))
752 (core func $rep (canon resource.rep $resource))
753 (core instance $intrinsics
754 (export "rep" (func $rep))
755 )
756 (core instance (instantiate $module
757 (with "intrinsics" (instance $intrinsics))
758 ))
759 )
760 "#,
761 )
762 .unwrap();
763 let direct = transpile(
764 &component,
765 TranspileOpts::builder()
766 .name("resource-runtime-direct".into())
767 .build(),
768 )
769 .unwrap();
770 let direct_source = generated_javascript(&direct);
771 #[cfg(feature = "embedded-cm-runtime")]
774 {
775 assert!(direct_source.contains("__jcoEmbeddedRuntime$tableGet"));
776 assert!(!direct_source.contains(crate::embedded_runtime::PACKAGE));
777 assert!(!direct_source.contains("\nimport "));
778 }
779 #[cfg(not(feature = "embedded-cm-runtime"))]
780 assert!(direct_source.contains("function rscTableGet(table, handle)"));
781 assert!(!direct_source.contains("_jcoRuntimeProvider"));
782
783 let transpiled = transpile_with_config(
784 &component,
785 TranspileConfig::builder()
786 .opts(
787 TranspileOpts::builder()
788 .name("resource-runtime".into())
789 .instantiation_mode(InstantiationMode::Sync)
790 .build(),
791 )
792 .cm_runtime_es_module("./custom-runtime".into())
793 .build(),
794 )
795 .unwrap();
796 let source = generated_javascript(&transpiled);
797
798 let import_position = source.find("tableGet as rscTableGet").unwrap();
799 let instantiate_position = source.find("export function instantiate(").unwrap();
800 let realm_position = source.find("const WebAssembly = options?").unwrap();
801 let context_position = source
802 .find("const _jcoResourceTableGetContext = { RuntimeError: WebAssembly.RuntimeError };")
803 .unwrap();
804 assert!(import_position < instantiate_position);
805 assert!(instantiate_position < realm_position);
806 assert!(realm_position < context_position);
807 assert!(
808 source.contains("rscTableGet(_jcoResourceTableGetContext, handleTable0, handle).rep")
809 );
810 assert!(!source.contains("function rscTableGet(table, handle)"));
811 assert!(!source.contains("_jcoRuntimeProvider"));
812 assert!(!source.contains(".bind(receiver)"));
813 assert_eq!(source.matches("tableGet as rscTableGet").count(), 1);
814 assert_eq!(
815 source.matches("const _jcoResourceTableGetContext").count(),
816 1
817 );
818 assert!(source.contains("from \"./custom-runtime/runtime.js\""));
819 assert!(!transpiled.imports.contains(&"./custom-runtime".to_string()));
820 }
821
822 #[cfg(all(feature = "transpile-bindgen", feature = "external-runtime"))]
823 #[test]
824 fn unrelated_component_does_not_import_external_runtime() {
825 let component = wat::parse_str("(component)").unwrap();
826 let transpiled = transpile_with_config(
827 &component,
828 TranspileConfig::builder()
829 .opts(TranspileOpts::builder().name("adder".into()).build())
830 .cm_runtime_es_module("unused-runtime".into())
831 .build(),
832 )
833 .unwrap();
834 let source = generated_javascript(&transpiled);
835
836 assert!(!source.contains("_jcoRuntimeProvider"));
837 assert!(!source.contains("unused-runtime"));
838 assert!(!source.contains("_jcoResourceTableGetContext"));
839 }
840}