Skip to main content

js_component_bindgen/
lib.rs

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;
14mod files;
15mod transpile_bindgen;
16mod ts_bindgen;
17
18pub mod esm_bindgen;
19pub mod function_bindgen;
20pub mod names;
21pub mod script;
22pub mod source;
23
24pub mod intrinsics;
25use intrinsics::Intrinsic;
26
27pub use transpile_bindgen::{
28    AsyncMode, BindingsMode, ExportKind, InstantiationMode, TranspileOpts,
29};
30use transpile_bindgen::{TranspileBindgenResult, transpile_bindgen};
31
32fn enum_case_name(name: &str, screaming_snake_case: bool) -> String {
33    if screaming_snake_case {
34        name.to_shouty_snake_case()
35    } else {
36        name.to_string()
37    }
38}
39
40/// Calls [`write!`] with the passed arguments and unwraps the result.
41///
42/// Useful for writing to things with infallible `Write` implementations like
43/// `Source` and `String`.
44///
45/// [`write!`]: std::write
46#[macro_export]
47macro_rules! uwrite {
48    ($dst:expr, $($arg:tt)*) => {
49        write!($dst, $($arg)*).unwrap()
50    };
51}
52
53/// Calls [`writeln!`] with the passed arguments and unwraps the result.
54///
55/// Useful for writing to things with infallible `Write` implementations like
56/// `Source` and `String`.
57///
58/// [`writeln!`]: std::writeln
59#[macro_export]
60macro_rules! uwriteln {
61    ($dst:expr, $($arg:tt)*) => {
62        writeln!($dst, $($arg)*).unwrap()
63    };
64}
65
66pub struct Transpiled {
67    pub files: Vec<(String, Vec<u8>)>,
68    pub imports: Vec<String>,
69    pub exports: Vec<(String, transpile_bindgen::ExportKind)>,
70}
71
72pub struct ComponentInfo {
73    pub imports: Vec<String>,
74    pub exports: Vec<(String, transpile_bindgen::ExportKind)>,
75}
76
77// TODO(breaking): merge TranspileOpts into this non-exhaustive configuration at
78// the next major release, so new options no longer need a separate type.
79/// Extensible configuration for `transpile_with_config`.
80///
81/// `TranspileOpts` keeps its published fields so existing struct literals remain
82/// valid. New options belong here, where fields can be added compatibly.
83#[derive(Debug, Default, Clone, bon::Builder)]
84#[non_exhaustive]
85pub struct TranspileConfig {
86    /// Options shared with `transpile` and [`generate_types`].
87    #[builder(default)]
88    pub opts: TranspileOpts,
89    /// Package or directory base for the experimental Component Model runtime.
90    /// Generated bindings import named exports from runtime and intrinsics/* subpaths.
91    /// Intrinsics are generated inline when this is `None` (the default).
92    /// Requires the `external-runtime` Cargo feature.
93    #[cfg(feature = "external-runtime")]
94    pub cm_runtime_es_module: Option<String>,
95}
96
97pub fn generate_types(
98    name: &str,
99    resolve: Resolve,
100    world_id: WorldId,
101    mut opts: TranspileOpts,
102) -> Result<Vec<(String, Vec<u8>)>> {
103    normalize_namespace_object_options(&mut opts)?;
104    let mut files = files::Files::default();
105
106    ts_bindgen(name, &resolve, world_id, &opts, &mut files)
107        .context("failed to generate Typescript bindings")?;
108
109    let mut files_out: Vec<(String, Vec<u8>)> = Vec::new();
110    for (name, source) in files.iter() {
111        files_out.push((name.to_string(), source.to_vec()));
112    }
113    Ok(files_out)
114}
115
116/// Generate the JS transpilation bindgen for a given Wasm component binary
117/// Outputs the file map and import and export metadata for the Transpilation
118#[cfg(feature = "transpile-bindgen")]
119pub fn transpile(component: &[u8], opts: TranspileOpts) -> Result<Transpiled> {
120    // TODO(breaking): accept the extensible configuration directly in transpile
121    // and remove this compatibility adapter at the next major release.
122    transpile_with_config(component, TranspileConfig::builder().opts(opts).build())
123}
124
125/// Transpile a component with additional configuration, including an optional
126/// external Component Model runtime provider.
127#[cfg(feature = "transpile-bindgen")]
128pub fn transpile_with_config(component: &[u8], mut config: TranspileConfig) -> Result<Transpiled> {
129    use wasmtime_environ::component::{Component, Translator};
130
131    normalize_transpile_config(&mut config)?;
132    let TranspileConfig {
133        mut opts,
134        #[cfg(feature = "external-runtime")]
135        cm_runtime_es_module,
136    } = config;
137    #[cfg(not(feature = "external-runtime"))]
138    let cm_runtime_es_module: Option<String> = None;
139    let name = opts.name.clone();
140    let mut files = files::Files::default();
141
142    // Use the `wit-component` crate here to parse `binary` and discover
143    // the type-level descriptions and `Resolve` corresponding to the
144    // component binary. This will synthesize a `Resolve` which has a top-level
145    // package which has a single document and `world` within it which describes
146    // the state of the component. This is then further used afterwards for
147    // bindings Transpilation as-if a `*.wit` file was input.
148    let decoded = wit_component::decode(component)
149        .context("failed to extract interface information from component")?;
150
151    let (resolve, world_id) = match decoded {
152        DecodedWasm::WitPackage(_, _) => bail!("unexpected wit package as input"),
153        DecodedWasm::Component(resolve, world_id) => (resolve, world_id),
154    };
155
156    // Components are complicated, there's no real way around that. To
157    // handle all the work of parsing a component and figuring out how to
158    // instantiate core wasm modules and such all the work is offloaded to
159    // Wasmtime itself. This crate generator is based on Wasmtime's
160    // low-level `wasmtime-environ` crate which is technically not a public
161    // dependency but the same author who worked on that in Wasmtime wrote
162    // this as well so... "seems fine".
163    //
164    // Note that we're not pulling in the entire Wasmtime engine here,
165    // moreso just the "spine" of validating a component. This enables using
166    // Wasmtime's internal `Component` representation as a much easier to
167    // process version of a component that has decompiled everything
168    // internal to a component to a straight linear list of initializers
169    // that need to be executed to instantiate a component.
170    let scope = ScopeVec::new();
171    let tunables = Tunables::default_u32();
172
173    // The validator that will be used on the component must enable support for all
174    // CM features we expect components to use.
175    //
176    // This does not require the correct execution of the related features post-transpilation,
177    // but without the right features specified, components won't load at all.
178    let mut features = WasmFeatures::WASM3
179        | WasmFeatures::WIDE_ARITHMETIC
180        | WasmFeatures::COMPONENT_MODEL
181        | WasmFeatures::CM_ASYNC
182        | WasmFeatures::CM_MORE_ASYNC_BUILTINS
183        | WasmFeatures::CM_ASYNC_STACKFUL
184        | WasmFeatures::CM_ERROR_CONTEXT
185        | WasmFeatures::CM_FIXED_LENGTH_LISTS
186        | WasmFeatures::CM_MAP
187        | WasmFeatures::CM_IMPLEMENTS
188        | WasmFeatures::CM_THREADING;
189
190    // Unless the target engine is known to support the exception handling
191    // proposal, mask exception handling off: with the feature enabled,
192    // wasmtime-environ's FACT-generated adapters wrap calls in exception
193    // barriers (`try_table`), which only runs behind a flag (e.g.
194    // --experimental-wasm-exnref) in today's JS engines.
195    if !opts.supports_wasm_exnref {
196        features = features.difference(WasmFeatures::EXCEPTIONS);
197    }
198
199    let mut validator = wasmtime_environ::wasmparser::Validator::new_with_features(features);
200
201    let mut types = ComponentTypesBuilder::new(&validator);
202
203    let (component, modules) = Translator::new(&tunables, &mut validator, &mut types, &scope)
204        .translate(component)
205        .map_err(|e| anyhow!(e).context("failed to translate component"))?;
206
207    let modules: PrimaryMap<StaticModuleIndex, core::Translation<'_>> = modules
208        .into_iter()
209        .map(|(_i, module)| core::Translation::new(module, opts.multi_memory))
210        .collect::<Result<_>>()?;
211
212    let num_resource_tables = types.num_resource_tables();
213    let wasmtime_component = Component::default();
214    let types = types.finish(&wasmtime_component);
215
216    // Insert all core wasm modules into the generated `Files` which will
217    // end up getting used in the `generate_instantiate` method.
218    for (i, module) in modules.iter() {
219        files.push(&core_file_name(&name, i.as_u32()), module.wasm());
220    }
221
222    let TranspileBindgenResult {
223        imports,
224        exports,
225        inferred_async_exports,
226    } = transpile_bindgen(
227        &name,
228        &component,
229        &modules,
230        &types.0,
231        num_resource_tables,
232        &resolve,
233        world_id,
234        opts.clone(),
235        cm_runtime_es_module.as_deref(),
236        &mut files,
237    );
238
239    if !opts.no_typescript {
240        if let Some(AsyncMode::JavaScriptPromiseIntegration { exports, .. }) = &mut opts.async_mode
241        {
242            exports.extend(inferred_async_exports);
243        }
244        ts_bindgen(&name, &resolve, world_id, &opts, &mut files)
245            .context("failed to generate Typescript bindings")?;
246    }
247
248    let mut files_out: Vec<(String, Vec<u8>)> = Vec::new();
249    for (name, source) in files.iter() {
250        files_out.push((name.to_string(), source.to_vec()));
251    }
252    Ok(Transpiled {
253        files: files_out,
254        imports,
255        exports,
256    })
257}
258
259fn normalize_namespace_object_options(opts: &mut TranspileOpts) -> Result<()> {
260    ensure!(
261        !(opts.use_namespace_objects && opts.variants_inline_cases),
262        "useNamespaceObjects cannot be combined with variantsInlineCases"
263    );
264    if opts.use_namespace_objects {
265        opts.flags_as_bigint = true;
266    }
267    Ok(())
268}
269
270fn normalize_transpile_config(config: &mut TranspileConfig) -> Result<()> {
271    normalize_namespace_object_options(&mut config.opts)?;
272    #[cfg(feature = "external-runtime")]
273    if let Some(cm_runtime_es_module) = &config.cm_runtime_es_module {
274        intrinsics::ext::module_specifier(cm_runtime_es_module, "runtime")?;
275    }
276    Ok(())
277}
278
279fn core_file_name(name: &str, idx: u32) -> String {
280    let i_str = if idx == 0 {
281        String::from("")
282    } else {
283        (idx + 1).to_string()
284    };
285    format!("{name}.core{i_str}.wasm")
286}
287
288pub fn dealias(resolve: &Resolve, mut id: TypeId) -> TypeId {
289    loop {
290        match &resolve.types[id].kind {
291            TypeDefKind::Type(Type::Id(that_id)) => id = *that_id,
292            _ => break id,
293        }
294    }
295}
296
297/// Check if an item (usually some form of [`WorldItem`]) should be allowed through the feature gate
298/// of a given package.
299fn feature_gate_allowed(
300    resolve: &Resolve,
301    package: &Package,
302    stability: &Stability,
303    item_name: &str,
304) -> Result<bool> {
305    Ok(match stability {
306        Stability::Unknown => true,
307        Stability::Stable { since, .. } => {
308            let Some(package_version) = package.name.version.as_ref() else {
309                // If the package version is missing (we're likely dealing with an unresolved package)
310                // and we can't really check much.
311                return Ok(true);
312            };
313
314            ensure!(
315                package_version >= since,
316                "feature gate on [{item_name}] refers to an unreleased (future) package version [{since}] (current package version is [{package_version}])"
317            );
318
319            // Stabilization (@since annotation) overrides features and deprecation
320            true
321        }
322        Stability::Unstable {
323            feature,
324            deprecated: _,
325        } => {
326            // If a @unstable feature is present but the related feature was not enabled
327            // or all features was not selected, exclude
328            resolve.all_features || resolve.features.contains(feature)
329        }
330    })
331}
332
333/// Utility function for deducing whether a type can throw
334pub fn get_thrown_type(
335    resolve: &Resolve,
336    return_type: Option<Type>,
337) -> Option<(Option<&Type>, Option<&Type>)> {
338    match return_type {
339        None => None,
340        Some(Type::Id(id)) => match &resolve.types[id].kind {
341            TypeDefKind::Result(r) => Some((r.ok.as_ref(), r.err.as_ref())),
342            _ => None,
343        },
344        _ => None,
345    }
346}
347
348/// Check whether a given function is an async fn
349///
350/// Functions that are designated as guest async represent use of
351/// the WASI p3 async feature.
352///
353/// These functions must be called from transpiled javsacript much differently
354/// than they would otherwise be, i.e. in accordance to the Component Model
355/// async feature.
356pub(crate) fn is_async_fn(func: &Function, canon_opts: &CanonicalOptions) -> bool {
357    if canon_opts.async_ {
358        return true;
359    }
360    func.kind.is_async()
361}
362
363/// Identifier for a function used
364enum FunctionIdentifier<'a> {
365    Fn(&'a Function),
366    CanonFnName(&'a str),
367}
368
369/// Check whether a function has been marked or async binding generation
370///
371/// When dealing with imports, functions that are designated to require async porcelain
372/// are usually asynchronous host functions -- they will have code generated
373/// that enables use of techniques like JSPI for exposing asynchronous host/platform
374/// imports to WebAssembly guests.
375///
376/// When dealing with an export, functions that require async porcelain simply provide
377/// an interface in the transpiled codebase that produces a `Promise`, i.e. one that can
378/// be called in an *already* asynchronous context (JS `async` function) or resolved with a`.then()`.
379///
380/// Exports do not indicate a use of JSPI, as JSPI is only for bridging asynchronous *host* behavior
381/// to synchronous WebAssembly modules
382///
383/// This function is *not* for detecting WASI P3 asynchronous behavior -- see [`is_guest_async_lifted_fn`].
384pub(crate) fn requires_async_porcelain(
385    func: FunctionIdentifier<'_>,
386    id: &str,
387    async_funcs: &HashSet<String>,
388) -> bool {
389    if async_funcs.contains("*") {
390        return true;
391    }
392
393    let name = match func {
394        FunctionIdentifier::Fn(func) => func.name.as_str(),
395        FunctionIdentifier::CanonFnName(name) => name,
396    }
397    .trim_start_matches("[async]");
398
399    if async_funcs.contains(name) {
400        return true;
401    }
402
403    let qualified_name = format!("{id}#{name}");
404    if async_funcs.contains(&qualified_name) {
405        return true;
406    }
407
408    if let Some(pos) = id.find('@') {
409        let namespace = &id[..pos];
410        let namespaced_name = format!("{namespace}#{name}");
411
412        if async_funcs.contains(&namespaced_name) {
413            return true;
414        }
415    }
416    false
417}
418
419/// Objects that can control the printing/setup of intrinsics (normally in some final codegen output)
420trait ManagesIntrinsics {
421    /// Add an intrinsic, supplying it's name afterwards
422    fn add_intrinsic(&mut self, intrinsic: Intrinsic);
423}
424
425#[cfg(test)]
426mod tests {
427    use super::*;
428
429    const FLAGS_WIT: &str = r#"
430        package test:flag-values;
431
432        interface api {
433            flags permissions {
434                read,
435                write,
436            }
437            roundtrip: func(value: permissions) -> permissions;
438        }
439
440        world flag-values {
441            export api;
442        }
443    "#;
444
445    fn generated_javascript(transpiled: &Transpiled) -> &str {
446        transpiled
447            .files
448            .iter()
449            .find_map(|(name, contents)| {
450                name.ends_with(".js")
451                    .then(|| std::str::from_utf8(contents).unwrap())
452            })
453            .unwrap()
454    }
455
456    fn flags_interface(flags_as_bigint: bool) -> String {
457        let mut resolve = Resolve::default();
458        let package = resolve.push_str("flags.wit", FLAGS_WIT).unwrap();
459        let world = resolve
460            .select_world(&[package], Some("flag-values"))
461            .unwrap();
462        let files = generate_types(
463            "flags",
464            resolve,
465            world,
466            TranspileOpts::builder()
467                .name("flags".into())
468                .flags_as_bigint(flags_as_bigint)
469                .build(),
470        )
471        .unwrap();
472        let (_, contents) = files
473            .into_iter()
474            .find(|(name, _)| name.ends_with("api.d.ts"))
475            .unwrap();
476        String::from_utf8(contents).unwrap()
477    }
478
479    #[test]
480    fn flags_types_are_objects_by_default() {
481        let source = flags_interface(false);
482        assert!(source.contains("export interface Permissions"));
483        assert!(!source.contains("export const Permissions"));
484    }
485
486    #[test]
487    fn flags_types_can_be_bigints_with_constants() {
488        let source = flags_interface(true);
489        assert!(source.contains("export type Permissions = bigint;"));
490        assert!(source.contains("export const Permissions: {"));
491        assert!(source.contains("readonly Read: bigint"));
492        assert!(source.contains("readonly Write: bigint"));
493    }
494
495    #[test]
496    fn wildcard_marks_every_function_async() {
497        let async_funcs = HashSet::from(["*".to_string()]);
498        assert!(requires_async_porcelain(
499            FunctionIdentifier::CanonFnName("query"),
500            "jco:node/dns@0.1.0",
501            &async_funcs,
502        ));
503        assert!(requires_async_porcelain(
504            FunctionIdentifier::CanonFnName("run"),
505            "example:component/run@1.0.0",
506            &async_funcs,
507        ));
508    }
509
510    #[cfg(feature = "external-runtime")]
511    #[test]
512    fn validates_cm_runtime_es_module_specifiers() {
513        let mut default = TranspileConfig::default();
514        normalize_transpile_config(&mut default).unwrap();
515        assert!(default.cm_runtime_es_module.is_none());
516
517        let mut custom = TranspileConfig::builder()
518            .cm_runtime_es_module("./runtime".into())
519            .build();
520        normalize_transpile_config(&mut custom).unwrap();
521        assert_eq!(custom.cm_runtime_es_module.as_deref(), Some("./runtime"));
522
523        for invalid in ["", "runtime\nmodule"] {
524            let mut config = TranspileConfig::builder()
525                .cm_runtime_es_module(invalid.into())
526                .build();
527            assert!(normalize_transpile_config(&mut config).is_err());
528        }
529    }
530
531    #[cfg(all(feature = "transpile-bindgen", feature = "external-runtime"))]
532    #[test]
533    fn resource_rep_uses_named_runtime_exports() {
534        let component = wat::parse_str(
535            r#"
536                (component
537                    (core module $module
538                        (type $rep-type (func (param i32) (result i32)))
539                        (import "intrinsics" "rep" (func $rep (type $rep-type)))
540                        (func (export "run") (param i32) (result i32)
541                            local.get 0
542                            call $rep
543                        )
544                    )
545                    (type $resource (resource (rep i32)))
546                    (core func $rep (canon resource.rep $resource))
547                    (core instance $intrinsics
548                        (export "rep" (func $rep))
549                    )
550                    (core instance (instantiate $module
551                        (with "intrinsics" (instance $intrinsics))
552                    ))
553                )
554            "#,
555        )
556        .unwrap();
557        let direct = transpile(
558            &component,
559            TranspileOpts::builder()
560                .name("resource-runtime-direct".into())
561                .build(),
562        )
563        .unwrap();
564        let direct_source = generated_javascript(&direct);
565        assert!(direct_source.contains("function rscTableGet(table, handle)"));
566        assert!(!direct_source.contains("_jcoRuntimeProvider"));
567
568        let transpiled = transpile_with_config(
569            &component,
570            TranspileConfig::builder()
571                .opts(
572                    TranspileOpts::builder()
573                        .name("resource-runtime".into())
574                        .instantiation_mode(InstantiationMode::Sync)
575                        .build(),
576                )
577                .cm_runtime_es_module("./custom-runtime".into())
578                .build(),
579        )
580        .unwrap();
581        let source = generated_javascript(&transpiled);
582
583        let import_position = source
584            .find("import { tableGet as rscTableGet } from \"./custom-runtime/intrinsics/resource.js\";")
585            .unwrap();
586        let instantiate_position = source.find("export function instantiate(").unwrap();
587        let realm_position = source.find("const WebAssembly = options?").unwrap();
588        let context_position = source
589            .find("const _jcoResourceTableGetContext = { RuntimeError: WebAssembly.RuntimeError };")
590            .unwrap();
591        assert!(import_position < instantiate_position);
592        assert!(instantiate_position < realm_position);
593        assert!(realm_position < context_position);
594        assert!(
595            source.contains("rscTableGet(_jcoResourceTableGetContext, handleTable0, handle).rep")
596        );
597        assert!(!source.contains("function rscTableGet(table, handle)"));
598        assert!(!source.contains("_jcoRuntimeProvider"));
599        assert!(!source.contains(".bind(receiver)"));
600        assert_eq!(source.matches("tableGet as rscTableGet").count(), 1);
601        assert_eq!(
602            source.matches("const _jcoResourceTableGetContext").count(),
603            1
604        );
605        assert!(source.contains("from \"./custom-runtime/runtime.js\""));
606        assert!(!transpiled.imports.contains(&"./custom-runtime".to_string()));
607    }
608
609    #[cfg(all(feature = "transpile-bindgen", feature = "external-runtime"))]
610    #[test]
611    fn unrelated_component_does_not_import_external_runtime() {
612        let component = wat::parse_str("(component)").unwrap();
613        let transpiled = transpile_with_config(
614            &component,
615            TranspileConfig::builder()
616                .opts(TranspileOpts::builder().name("adder".into()).build())
617                .cm_runtime_es_module("unused-runtime".into())
618                .build(),
619        )
620        .unwrap();
621        let source = generated_javascript(&transpiled);
622
623        assert!(!source.contains("_jcoRuntimeProvider"));
624        assert!(!source.contains("unused-runtime"));
625        assert!(!source.contains("_jcoResourceTableGetContext"));
626    }
627}