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 source;
22
23pub mod intrinsics;
24use intrinsics::Intrinsic;
25
26pub use transpile_bindgen::{
27    AsyncMode, BindingsMode, ExportKind, InstantiationMode, TranspileOpts,
28};
29use transpile_bindgen::{TranspileBindgenResult, transpile_bindgen};
30
31fn enum_case_name(name: &str, screaming_snake_case: bool) -> String {
32    if screaming_snake_case {
33        name.to_shouty_snake_case()
34    } else {
35        name.to_string()
36    }
37}
38
39/// Calls [`write!`] with the passed arguments and unwraps the result.
40///
41/// Useful for writing to things with infallible `Write` implementations like
42/// `Source` and `String`.
43///
44/// [`write!`]: std::write
45#[macro_export]
46macro_rules! uwrite {
47    ($dst:expr, $($arg:tt)*) => {
48        write!($dst, $($arg)*).unwrap()
49    };
50}
51
52/// Calls [`writeln!`] with the passed arguments and unwraps the result.
53///
54/// Useful for writing to things with infallible `Write` implementations like
55/// `Source` and `String`.
56///
57/// [`writeln!`]: std::writeln
58#[macro_export]
59macro_rules! uwriteln {
60    ($dst:expr, $($arg:tt)*) => {
61        writeln!($dst, $($arg)*).unwrap()
62    };
63}
64
65pub struct Transpiled {
66    pub files: Vec<(String, Vec<u8>)>,
67    pub imports: Vec<String>,
68    pub exports: Vec<(String, transpile_bindgen::ExportKind)>,
69}
70
71pub struct ComponentInfo {
72    pub imports: Vec<String>,
73    pub exports: Vec<(String, transpile_bindgen::ExportKind)>,
74}
75
76pub fn generate_types(
77    name: &str,
78    resolve: Resolve,
79    world_id: WorldId,
80    mut opts: TranspileOpts,
81) -> Result<Vec<(String, Vec<u8>)>> {
82    normalize_namespace_object_options(&mut opts)?;
83    let mut files = files::Files::default();
84
85    ts_bindgen(name, &resolve, world_id, &opts, &mut files)
86        .context("failed to generate Typescript bindings")?;
87
88    let mut files_out: Vec<(String, Vec<u8>)> = Vec::new();
89    for (name, source) in files.iter() {
90        files_out.push((name.to_string(), source.to_vec()));
91    }
92    Ok(files_out)
93}
94
95/// Generate the JS transpilation bindgen for a given Wasm component binary
96/// Outputs the file map and import and export metadata for the Transpilation
97#[cfg(feature = "transpile-bindgen")]
98pub fn transpile(component: &[u8], mut opts: TranspileOpts) -> Result<Transpiled> {
99    use wasmtime_environ::component::{Component, Translator};
100
101    normalize_namespace_object_options(&mut opts)?;
102    let name = opts.name.clone();
103    let mut files = files::Files::default();
104
105    // Use the `wit-component` crate here to parse `binary` and discover
106    // the type-level descriptions and `Resolve` corresponding to the
107    // component binary. This will synthesize a `Resolve` which has a top-level
108    // package which has a single document and `world` within it which describes
109    // the state of the component. This is then further used afterwards for
110    // bindings Transpilation as-if a `*.wit` file was input.
111    let decoded = wit_component::decode(component)
112        .context("failed to extract interface information from component")?;
113
114    let (resolve, world_id) = match decoded {
115        DecodedWasm::WitPackage(_, _) => bail!("unexpected wit package as input"),
116        DecodedWasm::Component(resolve, world_id) => (resolve, world_id),
117    };
118
119    // Components are complicated, there's no real way around that. To
120    // handle all the work of parsing a component and figuring out how to
121    // instantiate core wasm modules and such all the work is offloaded to
122    // Wasmtime itself. This crate generator is based on Wasmtime's
123    // low-level `wasmtime-environ` crate which is technically not a public
124    // dependency but the same author who worked on that in Wasmtime wrote
125    // this as well so... "seems fine".
126    //
127    // Note that we're not pulling in the entire Wasmtime engine here,
128    // moreso just the "spine" of validating a component. This enables using
129    // Wasmtime's internal `Component` representation as a much easier to
130    // process version of a component that has decompiled everything
131    // internal to a component to a straight linear list of initializers
132    // that need to be executed to instantiate a component.
133    let scope = ScopeVec::new();
134    let tunables = Tunables::default_u32();
135
136    // The validator that will be used on the component must enable support for all
137    // CM features we expect components to use.
138    //
139    // This does not require the correct execution of the related features post-transpilation,
140    // but without the right features specified, components won't load at all.
141    let mut features = WasmFeatures::WASM3
142        | WasmFeatures::WIDE_ARITHMETIC
143        | WasmFeatures::COMPONENT_MODEL
144        | WasmFeatures::CM_ASYNC
145        | WasmFeatures::CM_MORE_ASYNC_BUILTINS
146        | WasmFeatures::CM_ASYNC_STACKFUL
147        | WasmFeatures::CM_ERROR_CONTEXT
148        | WasmFeatures::CM_FIXED_LENGTH_LISTS
149        | WasmFeatures::CM_MAP
150        | WasmFeatures::CM_IMPLEMENTS;
151
152    // Unless the target engine is known to support the exception handling
153    // proposal, mask exception handling off: with the feature enabled,
154    // wasmtime-environ's FACT-generated adapters wrap calls in exception
155    // barriers (`try_table`), which only runs behind a flag (e.g.
156    // --experimental-wasm-exnref) in today's JS engines.
157    if !opts.supports_wasm_exnref {
158        features = features.difference(WasmFeatures::EXCEPTIONS);
159    }
160
161    let mut validator = wasmtime_environ::wasmparser::Validator::new_with_features(features);
162
163    let mut types = ComponentTypesBuilder::new(&validator);
164
165    let (component, modules) = Translator::new(&tunables, &mut validator, &mut types, &scope)
166        .translate(component)
167        .map_err(|e| anyhow!(e).context("failed to translate component"))?;
168
169    let modules: PrimaryMap<StaticModuleIndex, core::Translation<'_>> = modules
170        .into_iter()
171        .map(|(_i, module)| core::Translation::new(module, opts.multi_memory))
172        .collect::<Result<_>>()?;
173
174    let wasmtime_component = Component::default();
175    let types = types.finish(&wasmtime_component);
176
177    // Insert all core wasm modules into the generated `Files` which will
178    // end up getting used in the `generate_instantiate` method.
179    for (i, module) in modules.iter() {
180        files.push(&core_file_name(&name, i.as_u32()), module.wasm());
181    }
182
183    let TranspileBindgenResult {
184        imports,
185        exports,
186        inferred_async_exports,
187    } = transpile_bindgen(
188        &name,
189        &component,
190        &modules,
191        &types.0,
192        &resolve,
193        world_id,
194        opts.clone(),
195        &mut files,
196    );
197
198    if !opts.no_typescript {
199        if let Some(AsyncMode::JavaScriptPromiseIntegration { exports, .. }) = &mut opts.async_mode
200        {
201            exports.extend(inferred_async_exports);
202        }
203        ts_bindgen(&name, &resolve, world_id, &opts, &mut files)
204            .context("failed to generate Typescript bindings")?;
205    }
206
207    let mut files_out: Vec<(String, Vec<u8>)> = Vec::new();
208    for (name, source) in files.iter() {
209        files_out.push((name.to_string(), source.to_vec()));
210    }
211    Ok(Transpiled {
212        files: files_out,
213        imports,
214        exports,
215    })
216}
217
218fn normalize_namespace_object_options(opts: &mut TranspileOpts) -> Result<()> {
219    ensure!(
220        !(opts.use_namespace_objects && opts.variants_inline_cases),
221        "useNamespaceObjects cannot be combined with variantsInlineCases"
222    );
223    if opts.use_namespace_objects {
224        opts.flags_as_bigint = true;
225    }
226    Ok(())
227}
228
229fn core_file_name(name: &str, idx: u32) -> String {
230    let i_str = if idx == 0 {
231        String::from("")
232    } else {
233        (idx + 1).to_string()
234    };
235    format!("{name}.core{i_str}.wasm")
236}
237
238pub fn dealias(resolve: &Resolve, mut id: TypeId) -> TypeId {
239    loop {
240        match &resolve.types[id].kind {
241            TypeDefKind::Type(Type::Id(that_id)) => id = *that_id,
242            _ => break id,
243        }
244    }
245}
246
247/// Check if an item (usually some form of [`WorldItem`]) should be allowed through the feature gate
248/// of a given package.
249fn feature_gate_allowed(
250    resolve: &Resolve,
251    package: &Package,
252    stability: &Stability,
253    item_name: &str,
254) -> Result<bool> {
255    Ok(match stability {
256        Stability::Unknown => true,
257        Stability::Stable { since, .. } => {
258            let Some(package_version) = package.name.version.as_ref() else {
259                // If the package version is missing (we're likely dealing with an unresolved package)
260                // and we can't really check much.
261                return Ok(true);
262            };
263
264            ensure!(
265                package_version >= since,
266                "feature gate on [{item_name}] refers to an unreleased (future) package version [{since}] (current package version is [{package_version}])"
267            );
268
269            // Stabilization (@since annotation) overrides features and deprecation
270            true
271        }
272        Stability::Unstable {
273            feature,
274            deprecated: _,
275        } => {
276            // If a @unstable feature is present but the related feature was not enabled
277            // or all features was not selected, exclude
278            resolve.all_features || resolve.features.contains(feature)
279        }
280    })
281}
282
283/// Utility function for deducing whether a type can throw
284pub fn get_thrown_type(
285    resolve: &Resolve,
286    return_type: Option<Type>,
287) -> Option<(Option<&Type>, Option<&Type>)> {
288    match return_type {
289        None => None,
290        Some(Type::Id(id)) => match &resolve.types[id].kind {
291            TypeDefKind::Result(r) => Some((r.ok.as_ref(), r.err.as_ref())),
292            _ => None,
293        },
294        _ => None,
295    }
296}
297
298/// Check whether a given function is an async fn
299///
300/// Functions that are designated as guest async represent use of
301/// the WASI p3 async feature.
302///
303/// These functions must be called from transpiled javsacript much differently
304/// than they would otherwise be, i.e. in accordance to the Component Model
305/// async feature.
306pub(crate) fn is_async_fn(func: &Function, canon_opts: &CanonicalOptions) -> bool {
307    if canon_opts.async_ {
308        return true;
309    }
310    func.kind.is_async()
311}
312
313/// Identifier for a function used
314enum FunctionIdentifier<'a> {
315    Fn(&'a Function),
316    CanonFnName(&'a str),
317}
318
319/// Check whether a function has been marked or async binding generation
320///
321/// When dealing with imports, functions that are designated to require async porcelain
322/// are usually asynchronous host functions -- they will have code generated
323/// that enables use of techniques like JSPI for exposing asynchronous host/platform
324/// imports to WebAssembly guests.
325///
326/// When dealing with an export, functions that require async porcelain simply provide
327/// an interface in the transpiled codebase that produces a `Promise`, i.e. one that can
328/// be called in an *already* asynchronous context (JS `async` function) or resolved with a`.then()`.
329///
330/// Exports do not indicate a use of JSPI, as JSPI is only for bridging asynchronous *host* behavior
331/// to synchronous WebAssembly modules
332///
333/// This function is *not* for detecting WASI P3 asynchronous behavior -- see [`is_guest_async_lifted_fn`].
334pub(crate) fn requires_async_porcelain(
335    func: FunctionIdentifier<'_>,
336    id: &str,
337    async_funcs: &HashSet<String>,
338) -> bool {
339    if async_funcs.contains("*") {
340        return true;
341    }
342
343    let name = match func {
344        FunctionIdentifier::Fn(func) => func.name.as_str(),
345        FunctionIdentifier::CanonFnName(name) => name,
346    }
347    .trim_start_matches("[async]");
348
349    if async_funcs.contains(name) {
350        return true;
351    }
352
353    let qualified_name = format!("{id}#{name}");
354    if async_funcs.contains(&qualified_name) {
355        return true;
356    }
357
358    if let Some(pos) = id.find('@') {
359        let namespace = &id[..pos];
360        let namespaced_name = format!("{namespace}#{name}");
361
362        if async_funcs.contains(&namespaced_name) {
363            return true;
364        }
365    }
366    false
367}
368
369/// Objects that can control the printing/setup of intrinsics (normally in some final codegen output)
370trait ManagesIntrinsics {
371    /// Add an intrinsic, supplying it's name afterwards
372    fn add_intrinsic(&mut self, intrinsic: Intrinsic);
373}
374
375#[cfg(test)]
376mod tests {
377    use super::*;
378
379    const FLAGS_WIT: &str = r#"
380        package test:flag-values;
381
382        interface api {
383            flags permissions {
384                read,
385                write,
386            }
387            roundtrip: func(value: permissions) -> permissions;
388        }
389
390        world flag-values {
391            export api;
392        }
393    "#;
394
395    fn flags_interface(flags_as_bigint: bool) -> String {
396        let mut resolve = Resolve::default();
397        let package = resolve.push_str("flags.wit", FLAGS_WIT).unwrap();
398        let world = resolve
399            .select_world(&[package], Some("flag-values"))
400            .unwrap();
401        let files = generate_types(
402            "flags",
403            resolve,
404            world,
405            TranspileOpts::builder()
406                .name("flags".into())
407                .flags_as_bigint(flags_as_bigint)
408                .build(),
409        )
410        .unwrap();
411        let (_, contents) = files
412            .into_iter()
413            .find(|(name, _)| name.ends_with("api.d.ts"))
414            .unwrap();
415        String::from_utf8(contents).unwrap()
416    }
417
418    #[test]
419    fn flags_types_are_objects_by_default() {
420        let source = flags_interface(false);
421        assert!(source.contains("export interface Permissions"));
422        assert!(!source.contains("export const Permissions"));
423    }
424
425    #[test]
426    fn flags_types_can_be_bigints_with_constants() {
427        let source = flags_interface(true);
428        assert!(source.contains("export type Permissions = bigint;"));
429        assert!(source.contains("export const Permissions: {"));
430        assert!(source.contains("readonly Read: bigint"));
431        assert!(source.contains("readonly Write: bigint"));
432    }
433
434    #[test]
435    fn wildcard_marks_every_function_async() {
436        let async_funcs = HashSet::from(["*".to_string()]);
437        assert!(requires_async_porcelain(
438            FunctionIdentifier::CanonFnName("query"),
439            "jco:node/dns@0.1.0",
440            &async_funcs,
441        ));
442        assert!(requires_async_porcelain(
443            FunctionIdentifier::CanonFnName("run"),
444            "example:component/run@1.0.0",
445            &async_funcs,
446        ));
447    }
448}