js-component-bindgen 2.19.1

JS component bindgen for transpiling WebAssembly components into JavaScript
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
use std::collections::HashSet;

use anyhow::{Context as _, Result, anyhow, bail, ensure};
use heck::ToShoutySnakeCase;
use ts_bindgen::ts_bindgen;
use wasmtime_environ::component::{CanonicalOptions, ComponentTypesBuilder, StaticModuleIndex};
use wasmtime_environ::wasmparser::WasmFeatures;
use wasmtime_environ::{PrimaryMap, ScopeVec, Tunables};
use wit_bindgen_core::wit_parser::Function;
use wit_component::DecodedWasm;
use wit_parser::{Package, Resolve, Stability, Type, TypeDefKind, TypeId, WorldId};

mod core;
#[cfg(feature = "embedded-cm-runtime")]
mod embedded_runtime;
mod files;
mod transpile_bindgen;
mod ts_bindgen;

pub mod esm_bindgen;
pub mod function_bindgen;
pub mod names;
pub mod script;
pub mod source;

pub mod intrinsics;
use intrinsics::Intrinsic;

pub use transpile_bindgen::{
    AsyncMode, BindingsMode, ExportKind, InstantiationMode, TranspileOpts,
};
use transpile_bindgen::{TranspileBindgenResult, transpile_bindgen};

fn enum_case_name(name: &str, screaming_snake_case: bool) -> String {
    if screaming_snake_case {
        name.to_shouty_snake_case()
    } else {
        name.to_string()
    }
}

/// Calls [`write!`] with the passed arguments and unwraps the result.
///
/// Useful for writing to things with infallible `Write` implementations like
/// `Source` and `String`.
///
/// [`write!`]: std::write
#[macro_export]
macro_rules! uwrite {
    ($dst:expr, $($arg:tt)*) => {
        write!($dst, $($arg)*).unwrap()
    };
}

/// Calls [`writeln!`] with the passed arguments and unwraps the result.
///
/// Useful for writing to things with infallible `Write` implementations like
/// `Source` and `String`.
///
/// [`writeln!`]: std::writeln
#[macro_export]
macro_rules! uwriteln {
    ($dst:expr, $($arg:tt)*) => {
        writeln!($dst, $($arg)*).unwrap()
    };
}

pub struct Transpiled {
    pub files: Vec<(String, Vec<u8>)>,
    pub imports: Vec<String>,
    pub exports: Vec<(String, transpile_bindgen::ExportKind)>,
}

pub struct ComponentInfo {
    pub imports: Vec<String>,
    pub exports: Vec<(String, transpile_bindgen::ExportKind)>,
}

/// Controls declaration contracts that embedding tools may need to stabilize independently.
/// All fields default to true; the Jco frontend selects its compatibility defaults explicitly.
#[derive(Debug, Clone, Copy, bon::Builder)]
#[non_exhaustive]
pub struct TypeGenerationConfig {
    /// Require nominal identities for resources supplied by the bindings.
    #[builder(default = true)]
    pub nominal_resources: bool,
    /// Allow host async imports to return a value without a Promise.
    #[builder(default = true)]
    pub async_imports_may_return_sync: bool,
    /// Export named error classes for named result error payloads.
    #[builder(default = true)]
    pub typed_error_classes: bool,
    /// Generate separate import-side and export-side interface declarations.
    /// Any of the other enabled contracts also requires separate declarations.
    #[builder(default = true)]
    pub separate_interface_types: bool,
}

impl Default for TypeGenerationConfig {
    fn default() -> Self {
        Self::builder().build()
    }
}

impl TypeGenerationConfig {
    /// Direction-specific contracts require distinct declarations when an interface
    /// is both imported and exported.
    pub(crate) fn separate_interfaces(self) -> bool {
        self.separate_interface_types
            || self.nominal_resources
            || self.async_imports_may_return_sync
            || self.typed_error_classes
    }
}

// TODO(breaking): merge TranspileOpts into this non-exhaustive configuration at
// the next major release, so new options no longer need a separate type.
/// Extensible configuration for `transpile_with_config`.
///
/// `TranspileOpts` keeps its published fields so existing struct literals remain
/// valid. New options belong here, where fields can be added compatibly.
#[derive(Debug, Default, Clone, bon::Builder)]
#[non_exhaustive]
pub struct TranspileConfig {
    /// Options shared with `transpile` and [`generate_types`].
    #[builder(default)]
    pub opts: TranspileOpts,
    /// Emit optional host invocation tracking, independent of the runtime provider.
    #[builder(default)]
    pub call_tracking: bool,
    /// Declare the `val` of a WIT `result` arm that has no payload as optional
    /// in the generated TypeScript, so that `{ tag: 'ok' }` is a complete
    /// `result<_, E>` value.
    #[builder(default)]
    pub optional_result_payloads: bool,
    /// Controls declaration contracts independently of the embedding tool defaults.
    #[builder(default)]
    pub type_generation: TypeGenerationConfig,
    /// Package or directory base for the experimental Component Model runtime.
    /// Generated bindings import named exports from runtime and intrinsics/* subpaths.
    /// Intrinsics are generated inline when this is `None` (the default),
    /// unless the `embedded-cm-runtime` Cargo feature is enabled: the runtime
    /// shipped with this crate is then bundled into the generated bindings.
    /// Requires the `external-runtime` Cargo feature.
    #[cfg(feature = "external-runtime")]
    pub cm_runtime_es_module: Option<String>,
}

pub fn generate_types(
    name: &str,
    resolve: Resolve,
    world_id: WorldId,
    opts: TranspileOpts,
) -> Result<Vec<(String, Vec<u8>)>> {
    generate_types_with_config(
        name,
        resolve,
        world_id,
        TranspileConfig::builder().opts(opts).build(),
    )
}

/// Generate declarations with optional host embedding features.
pub fn generate_types_with_config(
    name: &str,
    resolve: Resolve,
    world_id: WorldId,
    mut config: TranspileConfig,
) -> Result<Vec<(String, Vec<u8>)>> {
    let opts = &mut config.opts;
    normalize_namespace_object_options(opts)?;
    let mut files = files::Files::default();

    ts_bindgen(
        name,
        &resolve,
        world_id,
        opts,
        config.call_tracking,
        config.optional_result_payloads,
        config.type_generation,
        &mut files,
    )
    .context("failed to generate Typescript bindings")?;

    let mut files_out: Vec<(String, Vec<u8>)> = Vec::new();
    for (name, source) in files.iter() {
        files_out.push((name.to_string(), source.to_vec()));
    }
    Ok(files_out)
}

/// Generate the JS transpilation bindgen for a given Wasm component binary
/// Outputs the file map and import and export metadata for the Transpilation
#[cfg(feature = "transpile-bindgen")]
pub fn transpile(component: &[u8], opts: TranspileOpts) -> Result<Transpiled> {
    // TODO(breaking): accept the extensible configuration directly in transpile
    // and remove this compatibility adapter at the next major release.
    transpile_with_config(component, TranspileConfig::builder().opts(opts).build())
}

/// Transpile a component with additional configuration, including an optional
/// external Component Model runtime provider.
#[cfg(feature = "transpile-bindgen")]
pub fn transpile_with_config(component: &[u8], mut config: TranspileConfig) -> Result<Transpiled> {
    use wasmtime_environ::component::{Component, Translator};

    normalize_transpile_config(&mut config)?;
    let TranspileConfig {
        mut opts,
        call_tracking,
        optional_result_payloads,
        type_generation,
        #[cfg(feature = "external-runtime")]
        cm_runtime_es_module,
    } = config;
    #[cfg(not(feature = "external-runtime"))]
    let cm_runtime_es_module: Option<String> = None;
    // TODO(breaking): bundle the runtime unconditionally at the next major release,
    // and remove the inline intrinsics that it stands in for here.
    // Without an external provider, bindings are generated against the runtime
    // shipped with this crate, which is then bundled into them.
    #[cfg(feature = "embedded-cm-runtime")]
    let bundle_runtime = cm_runtime_es_module.is_none();
    #[cfg(feature = "embedded-cm-runtime")]
    let cm_runtime_es_module =
        cm_runtime_es_module.or_else(|| Some(embedded_runtime::PACKAGE.to_string()));
    let name = opts.name.clone();
    let mut files = files::Files::default();

    // Use the `wit-component` crate here to parse `binary` and discover
    // the type-level descriptions and `Resolve` corresponding to the
    // component binary. This will synthesize a `Resolve` which has a top-level
    // package which has a single document and `world` within it which describes
    // the state of the component. This is then further used afterwards for
    // bindings Transpilation as-if a `*.wit` file was input.
    let decoded = wit_component::decode(component)
        .context("failed to extract interface information from component")?;

    let (resolve, world_id) = match decoded {
        DecodedWasm::WitPackage(_, _) => bail!("unexpected wit package as input"),
        DecodedWasm::Component(resolve, world_id) => (resolve, world_id),
    };

    // Components are complicated, there's no real way around that. To
    // handle all the work of parsing a component and figuring out how to
    // instantiate core wasm modules and such all the work is offloaded to
    // Wasmtime itself. This crate generator is based on Wasmtime's
    // low-level `wasmtime-environ` crate which is technically not a public
    // dependency but the same author who worked on that in Wasmtime wrote
    // this as well so... "seems fine".
    //
    // Note that we're not pulling in the entire Wasmtime engine here,
    // moreso just the "spine" of validating a component. This enables using
    // Wasmtime's internal `Component` representation as a much easier to
    // process version of a component that has decompiled everything
    // internal to a component to a straight linear list of initializers
    // that need to be executed to instantiate a component.
    let scope = ScopeVec::new();
    let tunables = Tunables::default_u32();

    // The validator that will be used on the component must enable support for all
    // CM features we expect components to use.
    //
    // This does not require the correct execution of the related features post-transpilation,
    // but without the right features specified, components won't load at all.
    let mut features = WasmFeatures::WASM3
        | WasmFeatures::WIDE_ARITHMETIC
        | WasmFeatures::COMPONENT_MODEL
        | WasmFeatures::CM_ASYNC
        | WasmFeatures::CM_MORE_ASYNC_BUILTINS
        | WasmFeatures::CM_ASYNC_STACKFUL
        | WasmFeatures::CM_ERROR_CONTEXT
        | WasmFeatures::CM_FIXED_LENGTH_LISTS
        | WasmFeatures::CM_MAP
        | WasmFeatures::CM_IMPLEMENTS
        | WasmFeatures::CM_THREADING;

    // Unless the target engine is known to support the exception handling
    // proposal, mask exception handling off: with the feature enabled,
    // wasmtime-environ's FACT-generated adapters wrap calls in exception
    // barriers (`try_table`), which only runs behind a flag (e.g.
    // --experimental-wasm-exnref) in today's JS engines.
    if !opts.supports_wasm_exnref {
        features = features.difference(WasmFeatures::EXCEPTIONS);
    }

    let mut validator = wasmtime_environ::wasmparser::Validator::new_with_features(features);

    let mut types = ComponentTypesBuilder::new(&validator);

    let (component, modules) = Translator::new(&tunables, &mut validator, &mut types, &scope)
        .translate(component)
        .map_err(|e| anyhow!(e).context("failed to translate component"))?;

    let modules: PrimaryMap<StaticModuleIndex, core::Translation<'_>> = modules
        .into_iter()
        .map(|(_i, module)| core::Translation::new(module, opts.multi_memory))
        .collect::<Result<_>>()?;

    let num_resource_tables = types.num_resource_tables();
    let wasmtime_component = Component::default();
    let types = types.finish(&wasmtime_component);

    // Insert all core wasm modules into the generated `Files` which will
    // end up getting used in the `generate_instantiate` method.
    for (i, module) in modules.iter() {
        files.push(&core_file_name(&name, i.as_u32()), module.wasm());
    }

    let TranspileBindgenResult {
        imports,
        exports,
        inferred_async_exports,
    } = transpile_bindgen(
        &name,
        &component,
        &modules,
        &types.0,
        num_resource_tables,
        &resolve,
        world_id,
        opts.clone(),
        cm_runtime_es_module.as_deref(),
        call_tracking,
        type_generation.typed_error_classes,
        &mut files,
    );

    if !opts.no_typescript {
        if let Some(AsyncMode::JavaScriptPromiseIntegration { exports, .. }) = &mut opts.async_mode
        {
            exports.extend(inferred_async_exports);
        }
        ts_bindgen(
            &name,
            &resolve,
            world_id,
            &opts,
            call_tracking,
            optional_result_payloads,
            type_generation,
            &mut files,
        )
        .context("failed to generate Typescript bindings")?;
    }

    let mut files_out: Vec<(String, Vec<u8>)> = Vec::new();
    for (name, source) in files.iter() {
        #[cfg(feature = "embedded-cm-runtime")]
        if bundle_runtime && name.ends_with(".js") {
            let source = std::str::from_utf8(source)
                .with_context(|| format!("generated module {name} is not UTF-8"))?;
            if let Some(linked) = embedded_runtime::link(source)
                .with_context(|| format!("failed to bundle the runtime into {name}"))?
            {
                files_out.push((name.to_string(), linked.into_bytes()));
                continue;
            }
        }
        files_out.push((name.to_string(), source.to_vec()));
    }
    Ok(Transpiled {
        files: files_out,
        imports,
        exports,
    })
}

fn normalize_namespace_object_options(opts: &mut TranspileOpts) -> Result<()> {
    ensure!(
        !(opts.use_namespace_objects && opts.variants_inline_cases),
        "useNamespaceObjects cannot be combined with variantsInlineCases"
    );
    if opts.use_namespace_objects {
        opts.flags_as_bigint = true;
    }
    Ok(())
}

fn normalize_transpile_config(config: &mut TranspileConfig) -> Result<()> {
    normalize_namespace_object_options(&mut config.opts)?;
    #[cfg(feature = "external-runtime")]
    if let Some(cm_runtime_es_module) = &config.cm_runtime_es_module {
        intrinsics::ext::module_specifier(cm_runtime_es_module, "runtime")?;
    }
    Ok(())
}

fn core_file_name(name: &str, idx: u32) -> String {
    let i_str = if idx == 0 {
        String::from("")
    } else {
        (idx + 1).to_string()
    };
    format!("{name}.core{i_str}.wasm")
}

pub fn dealias(resolve: &Resolve, mut id: TypeId) -> TypeId {
    loop {
        match &resolve.types[id].kind {
            TypeDefKind::Type(Type::Id(that_id)) => id = *that_id,
            _ => break id,
        }
    }
}

/// Check if an item (usually some form of [`WorldItem`]) should be allowed through the feature gate
/// of a given package.
fn feature_gate_allowed(
    resolve: &Resolve,
    package: &Package,
    stability: &Stability,
    item_name: &str,
) -> Result<bool> {
    Ok(match stability {
        Stability::Unknown => true,
        Stability::Stable { since, .. } => {
            let Some(package_version) = package.name.version.as_ref() else {
                // If the package version is missing (we're likely dealing with an unresolved package)
                // and we can't really check much.
                return Ok(true);
            };

            ensure!(
                package_version >= since,
                "feature gate on [{item_name}] refers to an unreleased (future) package version [{since}] (current package version is [{package_version}])"
            );

            // Stabilization (@since annotation) overrides features and deprecation
            true
        }
        Stability::Unstable {
            feature,
            deprecated: _,
        } => {
            // If a @unstable feature is present but the related feature was not enabled
            // or all features was not selected, exclude
            resolve.all_features || resolve.features.contains(feature)
        }
    })
}

/// Utility function for deducing whether a type can throw
pub fn get_thrown_type(
    resolve: &Resolve,
    return_type: Option<Type>,
) -> Option<(Option<&Type>, Option<&Type>)> {
    match return_type {
        None => None,
        Some(Type::Id(id)) => match &resolve.types[id].kind {
            TypeDefKind::Result(r) => Some((r.ok.as_ref(), r.err.as_ref())),
            _ => None,
        },
        _ => None,
    }
}

/// The class of the errors that the bindings throw when a function that an
/// interface exports returns the error of its `result`.
///
/// The bindings export one class per named error type from the interface, so
/// that a host can tell the errors of the interface apart with `instanceof`.
/// There is none for an error type without a name, and none where the name of
/// the class would be that of another declaration of the interface.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ResultErrorClass {
    /// The name that the interface exports the class under.
    pub name: String,
    /// The name of the error type, as declared in WIT.
    pub payload_type_name: String,
}

/// Find the [`ResultErrorClass`] of a function of an interface.
pub(crate) fn result_error_class(
    resolve: &Resolve,
    interface: wit_parser::InterfaceId,
    func: &Function,
) -> Option<ResultErrorClass> {
    use heck::ToUpperCamelCase as _;

    let (_, Some(Type::Id(err))) = get_thrown_type(resolve, func.result)? else {
        return None;
    };
    let payload_type_name = resolve.types[*err].name.clone()?;
    let name = format!("{}Error", payload_type_name.to_upper_camel_case());

    // The declarations of the interface name its types, and name the cases of
    // its variants after the variant and the case.
    let is_declared = resolve.interfaces[interface]
        .types
        .iter()
        .any(|(type_name, type_id)| {
            if type_name.to_upper_camel_case() == name {
                return true;
            }
            let TypeDefKind::Variant(variant) = &resolve.types[*type_id].kind else {
                return false;
            };
            variant
                .cases
                .iter()
                .any(|case| format!("{type_name}_{}", case.name).to_upper_camel_case() == name)
        });
    (!is_declared).then_some(ResultErrorClass {
        name,
        payload_type_name,
    })
}

/// Check whether a given function is an async fn
///
/// Functions that are designated as guest async represent use of
/// the WASI p3 async feature.
///
/// These functions must be called from transpiled javsacript much differently
/// than they would otherwise be, i.e. in accordance to the Component Model
/// async feature.
pub(crate) fn is_async_fn(func: &Function, canon_opts: &CanonicalOptions) -> bool {
    if canon_opts.async_ {
        return true;
    }
    func.kind.is_async()
}

/// Identifier for a function used
enum FunctionIdentifier<'a> {
    Fn(&'a Function),
    CanonFnName(&'a str),
}

/// Check whether a function has been marked or async binding generation
///
/// When dealing with imports, functions that are designated to require async porcelain
/// are usually asynchronous host functions -- they will have code generated
/// that enables use of techniques like JSPI for exposing asynchronous host/platform
/// imports to WebAssembly guests.
///
/// When dealing with an export, functions that require async porcelain simply provide
/// an interface in the transpiled codebase that produces a `Promise`, i.e. one that can
/// be called in an *already* asynchronous context (JS `async` function) or resolved with a`.then()`.
///
/// Exports do not indicate a use of JSPI, as JSPI is only for bridging asynchronous *host* behavior
/// to synchronous WebAssembly modules
///
/// This function is *not* for detecting WASI P3 asynchronous behavior -- see [`is_guest_async_lifted_fn`].
pub(crate) fn requires_async_porcelain(
    func: FunctionIdentifier<'_>,
    id: &str,
    async_funcs: &HashSet<String>,
) -> bool {
    if async_funcs.contains("*") {
        return true;
    }

    let name = match func {
        FunctionIdentifier::Fn(func) => func.name.as_str(),
        FunctionIdentifier::CanonFnName(name) => name,
    }
    .trim_start_matches("[async]");

    if async_funcs.contains(name) {
        return true;
    }

    let qualified_name = format!("{id}#{name}");
    if async_funcs.contains(&qualified_name) {
        return true;
    }

    if let Some(pos) = id.find('@') {
        let namespace = &id[..pos];
        let namespaced_name = format!("{namespace}#{name}");

        if async_funcs.contains(&namespaced_name) {
            return true;
        }
    }
    false
}

/// Objects that can control the printing/setup of intrinsics (normally in some final codegen output)
trait ManagesIntrinsics {
    /// Add an intrinsic, supplying it's name afterwards
    fn add_intrinsic(&mut self, intrinsic: Intrinsic);
}

#[cfg(test)]
mod tests {
    use super::*;

    const FLAGS_WIT: &str = r#"
        package test:flag-values;

        interface api {
            flags permissions {
                read,
                write,
            }
            roundtrip: func(value: permissions) -> permissions;
        }

        world flag-values {
            export api;
        }
    "#;

    fn generated_javascript(transpiled: &Transpiled) -> &str {
        transpiled
            .files
            .iter()
            .find_map(|(name, contents)| {
                name.ends_with(".js")
                    .then(|| std::str::from_utf8(contents).unwrap())
            })
            .unwrap()
    }

    #[cfg(feature = "transpile-bindgen")]
    #[test]
    fn async_export_returns_imported_resource_without_imported_functions() {
        let component = wat::parse_str(
            r#"
                (component
                    (import "test:data/blob" (instance $data
                        (export "blob" (type (sub resource)))
                    ))
                    (alias export $data "blob" (type $blob))
                    (core func $task_return (canon task.return (result (own $blob))))
                    (core module $m
                        (import "" "task.return" (func $ret (param i32)))
                        (func (export "pass") (param i32) (result i32)
                            local.get 0 call $ret i32.const 0)
                        (func (export "cb") (param i32 i32 i32) (result i32)
                            i32.const 0)
                    )
                    (core instance $i (instantiate $m
                        (with "" (instance (export "task.return" (func $task_return))))))
                    (type $ft (func async (param "b" (own $blob)) (result (own $blob))))
                    (func (export "pass") (type $ft)
                        (canon lift (core func $i "pass") async (callback (core func $i "cb"))))
                )
            "#,
        )
        .unwrap();
        for instantiation_mode in [
            None,
            Some(InstantiationMode::Async),
            Some(InstantiationMode::Sync),
        ] {
            transpile(
                &component,
                TranspileOpts::builder()
                    .name("async-pass-imported-resource".into())
                    .maybe_instantiation_mode(instantiation_mode)
                    .build(),
            )
            .unwrap();
        }
    }

    fn flags_interface(flags_as_bigint: bool) -> String {
        let mut resolve = Resolve::default();
        let package = resolve.push_str("flags.wit", FLAGS_WIT).unwrap();
        let world = resolve
            .select_world(&[package], Some("flag-values"))
            .unwrap();
        let files = generate_types(
            "flags",
            resolve,
            world,
            TranspileOpts::builder()
                .name("flags".into())
                .flags_as_bigint(flags_as_bigint)
                .build(),
        )
        .unwrap();
        let (_, contents) = files
            .into_iter()
            .find(|(name, _)| name.ends_with("api.d.ts"))
            .unwrap();
        String::from_utf8(contents).unwrap()
    }

    #[test]
    fn flags_types_are_objects_by_default() {
        let source = flags_interface(false);
        assert!(source.contains("export interface Permissions"));
        assert!(!source.contains("export const Permissions"));
    }

    #[test]
    fn flags_types_can_be_bigints_with_constants() {
        let source = flags_interface(true);
        assert!(source.contains("export type Permissions = bigint;"));
        assert!(source.contains("export const Permissions: {"));
        assert!(source.contains("readonly Read: bigint"));
        assert!(source.contains("readonly Write: bigint"));
    }

    #[test]
    fn wildcard_marks_every_function_async() {
        let async_funcs = HashSet::from(["*".to_string()]);
        assert!(requires_async_porcelain(
            FunctionIdentifier::CanonFnName("query"),
            "jco:node/dns@0.1.0",
            &async_funcs,
        ));
        assert!(requires_async_porcelain(
            FunctionIdentifier::CanonFnName("run"),
            "example:component/run@1.0.0",
            &async_funcs,
        ));
    }

    #[cfg(feature = "external-runtime")]
    #[test]
    fn validates_cm_runtime_es_module_specifiers() {
        let mut default = TranspileConfig::default();
        normalize_transpile_config(&mut default).unwrap();
        assert!(default.cm_runtime_es_module.is_none());

        let mut custom = TranspileConfig::builder()
            .cm_runtime_es_module("./runtime".into())
            .build();
        normalize_transpile_config(&mut custom).unwrap();
        assert_eq!(custom.cm_runtime_es_module.as_deref(), Some("./runtime"));

        for invalid in ["", "runtime\nmodule"] {
            let mut config = TranspileConfig::builder()
                .cm_runtime_es_module(invalid.into())
                .build();
            assert!(normalize_transpile_config(&mut config).is_err());
        }
    }

    #[cfg(all(feature = "transpile-bindgen", feature = "external-runtime"))]
    #[test]
    fn resource_rep_uses_named_runtime_exports() {
        let component = wat::parse_str(
            r#"
                (component
                    (core module $module
                        (type $rep-type (func (param i32) (result i32)))
                        (import "intrinsics" "rep" (func $rep (type $rep-type)))
                        (func (export "run") (param i32) (result i32)
                            local.get 0
                            call $rep
                        )
                    )
                    (type $resource (resource (rep i32)))
                    (core func $rep (canon resource.rep $resource))
                    (core instance $intrinsics
                        (export "rep" (func $rep))
                    )
                    (core instance (instantiate $module
                        (with "intrinsics" (instance $intrinsics))
                    ))
                )
            "#,
        )
        .unwrap();
        let direct = transpile(
            &component,
            TranspileOpts::builder()
                .name("resource-runtime-direct".into())
                .build(),
        )
        .unwrap();
        let direct_source = generated_javascript(&direct);
        // Without a selected provider the intrinsics are self-contained: bundled from
        // the shipped runtime when that feature is enabled, and rendered inline otherwise.
        #[cfg(feature = "embedded-cm-runtime")]
        {
            assert!(direct_source.contains("__jcoEmbeddedRuntime$tableGet"));
            assert!(!direct_source.contains(crate::embedded_runtime::PACKAGE));
            assert!(!direct_source.contains("\nimport "));
        }
        #[cfg(not(feature = "embedded-cm-runtime"))]
        assert!(direct_source.contains("function rscTableGet(table, handle)"));
        assert!(!direct_source.contains("_jcoRuntimeProvider"));

        let transpiled = transpile_with_config(
            &component,
            TranspileConfig::builder()
                .opts(
                    TranspileOpts::builder()
                        .name("resource-runtime".into())
                        .instantiation_mode(InstantiationMode::Sync)
                        .build(),
                )
                .cm_runtime_es_module("./custom-runtime".into())
                .build(),
        )
        .unwrap();
        let source = generated_javascript(&transpiled);

        let import_position = source.find("tableGet as rscTableGet").unwrap();
        let instantiate_position = source.find("export function instantiate(").unwrap();
        let realm_position = source.find("const WebAssembly = options?").unwrap();
        let context_position = source
            .find("const _jcoResourceTableGetContext = { RuntimeError: WebAssembly.RuntimeError };")
            .unwrap();
        assert!(import_position < instantiate_position);
        assert!(instantiate_position < realm_position);
        assert!(realm_position < context_position);
        assert!(
            source.contains("rscTableGet(_jcoResourceTableGetContext, handleTable0, handle).rep")
        );
        assert!(!source.contains("function rscTableGet(table, handle)"));
        assert!(!source.contains("_jcoRuntimeProvider"));
        assert!(!source.contains(".bind(receiver)"));
        assert_eq!(source.matches("tableGet as rscTableGet").count(), 1);
        assert_eq!(
            source.matches("const _jcoResourceTableGetContext").count(),
            1
        );
        assert!(source.contains("from \"./custom-runtime/runtime.js\""));
        assert!(!transpiled.imports.contains(&"./custom-runtime".to_string()));
    }

    #[cfg(all(feature = "transpile-bindgen", feature = "external-runtime"))]
    #[test]
    fn unrelated_component_does_not_import_external_runtime() {
        let component = wat::parse_str("(component)").unwrap();
        let transpiled = transpile_with_config(
            &component,
            TranspileConfig::builder()
                .opts(TranspileOpts::builder().name("adder".into()).build())
                .cm_runtime_es_module("unused-runtime".into())
                .build(),
        )
        .unwrap();
        let source = generated_javascript(&transpiled);

        assert!(!source.contains("_jcoRuntimeProvider"));
        assert!(!source.contains("unused-runtime"));
        assert!(!source.contains("_jcoResourceTableGetContext"));
    }
}