Skip to content

Latest commit

 

History

History
1192 lines (969 loc) · 70.5 KB

JS-Reference.md

File metadata and controls

1192 lines (969 loc) · 70.5 KB

WebAssembly Components JS-API Reference

This is the in-depth reference for the WebAssembly Component JS-API. See the component model explainer for an in-depth explanation of WebAssembly Components (hereafter 'components'). See the JS-API explainer for a higher-level introduction to the JS-API.

This is a draft and is not complete. Major details are unresolved, and there are bugs.

Goals

  1. Components can import and use most web and JS APIs
  2. Components can export an API usable by JS
  3. Components interact with the web platform in similar ways to JS:
    1. Components can feature test whether APIs are present
    2. Components work whether they are importing a web API, or a JS polyfill, or a component polyfill
    3. Components are tolerant of web API evolution
    4. Component misuse of a web API results in failure at that call-site, not a link time error
  4. Components have better web API performance than WebAssembly modules today

Non-goals

  1. Components importing every kind of web API
  2. Components exporting any kind of JS API

The gaps ideally will narrow over time after a v1.0 release, but may not ever fully close.

The WebAssembly namespace

We extend the imperative WebAssembly JS-API interfaces to also allow validation, compilation, and instantiation of components in addition to modules.

[LegacyNamespace=WebAssembly, Exposed=*]
interface Component {
    constructor([AllowResizable] AllowSharedBufferSource bytes, optional WebAssemblyCompileOptions options = {});
};

[LegacyNamespace=WebAssembly, Exposed=*]
interface ComponentInstance {
    constructor(Component component, optional object importsObject);
    readonly attribute object exports;
};

typedef (Component or Module) InstantiateSource;

dictionary WebAssemblyInstantiatedComponentSource {
    required Component component;
    required ComponentInstance instance;
};

[Exposed=*]
namespace WebAssembly {
    // Same as before, but now will detect if the bytes are a component or module and dispatch differently.
    boolean validate([AllowResizable] AllowSharedBufferSource bytes, optional WebAssemblyCompileOptions options = {});
    Promise<Module or Component> compile([AllowResizable] AllowSharedBufferSource bytes, optional WebAssemblyCompileOptions options = {});
    Promise<(WebAssemblyInstantiatedSource or WebAssemblyInstantiatedComponentSource)> instantiate(
        [AllowResizable] AllowSharedBufferSource bytes, optional object importObject, optional WebAssemblyCompileOptions options = {});

    // Now takes an InstantiateSource instead of just a Module, and returns a
    // ComponentInstance for a Component.
    Promise<(Instance or ComponentInstance)> instantiate(
        InstantiateSource moduleOrComponentObject, optional object importObject);
};

We also add an error type for component functions that return result<_, E> to JS:

[LegacyNamespace=WebAssembly, Exposed=*]
interface ComponentError : Error {
    constructor(optional DOMString message = "", optional any data);
    readonly attribute any data;
};

data is the converted E value. See Create the exports object.

Validation/compilation

Validation and compilation of components defer to the underlying component embedding interface. This reference adds nothing to it.

Component store

A component store is defined by the canonical ABI and is analogous to the core wasm store. It contains a set of component instances and tasks. A store is also a unit of failure where a trap can trigger a lockdown which prevents further execution within the store.

In contrast with core wasm, every component instantiated by the JS-API or ESM (i.e. 'top level') is partitioned to its own store. This means that all top-level component interaction is mediated by the JS-API. A component export imported by another component is treated the same as any other JS import.

This ensures that whether an ESM is implemented as a component or with JS is an implementation detail that can change over time. This also means that a failure within a top-level component instance that triggers a lockdown affects only that component instance.

Nested components share a common store and directly link following the normal component rules. This should be sufficient for most cases where you want to directly link components. In the future, we could consider an extension to instantiate two components within the same store.

Instance records

Every top-level component instance has an instance record with the following fields:

Field Value
[[Store]] the component store
[[ComponentInstance]] the component instance from the embedding API
[[HostResourceTypes]] map from abstract type key to host resource type
[[GuestResourceClasses]] map from abstract type key to guest resource class

Entry points

A Component JS object has the following slots:

  1. [[Component]] - the compiled component from the embedding API.
  2. [[EnabledBuiltins]] - the enabled builtins.

A ComponentInstance JS object has the following slots:

  1. [[Instance]] - the instance record.
  2. [[Exports]] - the exports object.

To trap given an instance record |instance|:

  1. Invoke |instance|.[[Store]].lock_down().
  2. Throw a WebAssembly.RuntimeError.

A trapped instance is locked down: every later call into it traps again before running any code.

A call has entered the guest once the canonical ABI has, on the call's behalf, invoked any function of the component instance (such as realloc) or modified one of its handle tables. A conversion that throws after that point leaves guest state the guest never sees, so the instance is locked down as if the call had trapped, while the original exception still propagates. A conversion that throws before that point leaves the instance untouched.

To construct a Component given |bytes| and |options|:

  1. Let |stableBytes| be a copy of the bytes held by |bytes|.
  2. Let |enabledBuiltins| be the result of parsing builtins from |options|.
  3. Let |component| be the result of compiling |stableBytes| as a component, per the embedding interface.
  4. If compilation fails:
    1. Throw a WebAssembly.CompileError.
  5. Set this.[[Component]] to |component|.
  6. Set this.[[EnabledBuiltins]] to |enabledBuiltins|.

To construct a ComponentInstance given a Component |component|, and |importsObject|:

  1. Let |enabledBuiltins| be |component|.[[EnabledBuiltins]].
  2. Let |result| be ? instantiate a component from an imports object given |component|.[[Component]], |importsObject|, |enabledBuiltins|.
  3. Set this.[[Instance]] to |result|.[[Instance]].
  4. Set this.[[Exports]] to |result|.[[Exports]].

The exports getter returns this.[[Exports]].

validate is modified to validate the bytes as a component if the layer field of the binary indicates a component. compile/instantiate are modified to asynchronously compile/instantiate the bytes as a component if the layer field indicates a component.

Names

Component import/export plainnames contain labels that must be transformed into an identifier for use with JS.

Fully qualified component import/export interfacenames (such as wasi:http/handler@1.0.0) are used as-is when converted to JS strings or as module specifiers.

We define PascalCase(label) and CamelCase(label) below.

label PascalCase CamelCase
element Element element
query-selector QuerySelector querySelector
inner-HTML InnerHTML innerHTML
XML-http-request XMLHttpRequest xmlHttpRequest
URL URL url
a1-2-3 A123 a123

Every plainname matches exactly one of the four patterns below, and no interfacename matches any of them. The algorithms in this document dispatch on these patterns and read their named captures. <label> stands for the label production.

Pattern Regex Groups Example
Plain ^(<label>)$ 1: name query-selector
Property ^\[(get|set)\](<label>)$ 1: accessor, 2: name [get]inner-HTML
Constructor ^\[constructor\](<label>)$ 1: resource [constructor]element
Member ^\[(method|static)\](\[(get|set)\])?(<label>)\.(<label>)$ 1: scope, 3: accessor, 4: resource, 5: name [method][set]element.inner-HTML

plainname's are restricted by component strong uniqueness. This helps us statically avoid collisions when building high-level export types (such as guest resource classes) and using the name transformations below.

LabelOf(|name|), where |name| is a plainname, returns the label that names the definition in JS:

  1. If |name| matches Constructor:
    1. Return the resource capture.
  2. Return the name capture.

Fragments(|label|):

  1. Return the List of Strings produced by splitting |label| on occurrences of U+002D (-). The hyphens themselves are discarded.

Capitalize(|fragment|):

  1. If |fragment| is an acronym:
    1. Return |fragment|.
  2. Return |fragment| with its first character uppercased.

PascalCase(|label|):

  1. Let |fragments| be Fragments(|label|).
  2. Let |result| be the empty String.
  3. For each |fragment| of |fragments|:
    1. Set |result| to the string-concatenation of |result| and Capitalize(|fragment|).
  4. Return |result|.

CamelCase(|label|):

  1. Let |fragments| be Fragments(|label|).
  2. Let |result| be |fragments|[0] with every character lowercased.
  3. For each |fragment| of |fragments| after the first:
    1. Set |result| to the string-concatenation of |result| and Capitalize(|fragment|).
  4. Return |result|.

The JS name of an import or export declaration is then:

JSName(|decl|):

  1. If |decl| has an external-id attribute that is the Unicode string |id|:
    1. Return |id|.
  2. If |decl|.Name is an interfacename:
    1. Return |decl|.Name.
  3. If |decl| is a type declaration:
    1. Return PascalCase(LabelOf(|decl|.Name)).
  4. Return CamelCase(LabelOf(|decl|.Name)).

Types and values

Components and JS maintain separate type/value systems, so any value crossing the boundary needs a defined translation in both directions.

This section specifies that translation as two abstract operations:

  1. ToJSValue - convert a component value to a JS value.
  2. ToComponentValue - convert a JS value to a component value of a given type.

Roundtripping from ToJSValue back through ToComponentValue is designed to be strictly the identity function with the following exceptions:

  1. A map with duplicate keys keeps only the last pair per key (see ToJSValueMap)
  2. Float NaNs are canonicalized

Every object a conversion creates, including any error it throws, belongs to the component realm. This is the realm of the WebAssembly namespace the component was instantiated through with the JS-API, or the realm the ESM was instantiated in with ESM-integration.

Conversions run within the current call, a Record with the following fields:

Field Value
[[HostResourceTypes]] map from abstract type key to host resource type
[[GuestResourceClasses]] map from abstract type key to guest resource class
[[Lenders]] an optional List of guest resource objects lent as a borrow back to the defining component

To run within a call given |hostResourceTypes|, |guestResourceClasses| and an Abstract Closure |steps|:

  1. Let |previousCall| be the current call.
  2. Set the current call to Record { [[HostResourceTypes]]: |hostResourceTypes|, [[GuestResourceClasses]]: |guestResourceClasses|, [[Lenders]]: empty }.
  3. Let |result| be Completion(|steps|()).
  4. Set the current call to |previousCall|.
  5. Return ? |result|.

A trap in |steps| also restores the previous call as it unwinds.

ToJSValue

ToJSValue(componentValue, componentValType) converts a component value to a JS value. It is infallible.

Dispatch on componentValType:

  • bool → Boolean.
  • Integer types other than s64/u64 → Number, an exact integer.
  • s64 / u64 → BigInt.
  • f32 / f64 → Number, including NaN and infinities.
  • char → String containing exactly the one Unicode scalar value.
  • string → String (well formed).
  • list<Scalar> → A scalar typed array class over a fresh ArrayBuffer holding the scalars.
  • list<T> → ToJSValueList(the elements, T).
  • list<T, N> → as list<T>; length is N.
  • tuple<T0, T1, ...> → as list, with element i converted as T_i.
  • record { f: T, ... } → ToJSValueRecord(|componentValue|, the fields).
  • flags "L"+ → ToJSValueFlags(|componentValue|, the labels).
  • enum "L"+ → String, the label verbatim.
  • option<T> not nested within another option → undefined for none, else ToJSValue(the payload, T).
  • variant, and nested option, and result outside return position → ToJSValueVariant(|componentValue|, the cases). In return position a result is unwrapped instead, into a return value or a thrown ComponentError (see Read the imports and Create the exports object).
  • map<K, V> → ToJSValueMap(|componentValue|, K, V).
  • own<R> / borrow<R> → See Resource types.
  • future<T> → a Promise (TODO).
  • stream<T> → an AsyncIterator (TODO).
  • error-context → TODO.

The scalar typed array class is given by:

Component type JS class
s8 Int8Array
u8 Uint8Array
s16 Int16Array
u16 Uint16Array
s32 Int32Array
u32 Uint32Array
f32 Float32Array
f64 Float64Array
s64 BigInt64Array
u64 BigUint64Array

ToJSValueList(values, T):

  1. Let |n| be the number of |values|.
  2. Let |array| be ArrayCreate(|n|).
  3. For each i in [0, |n|):
    1. Perform CreateDataPropertyOrThrow(|array|, ToString(𝔽(i)), ToJSValue(|values|[i], T)).
  4. Return |array|.

ToJSValueRecord(value, fields):

  1. Let |object| be OrdinaryObjectCreate(null).
  2. For each field f: T of |fields|, in declaration order:
    1. Perform CreateDataPropertyOrThrow(|object|, CamelCase(f), ToJSValue(|value|'s f, T)).
  3. Return |object|.

ToJSValueFlags(value, labels):

  1. Let |object| be OrdinaryObjectCreate(null).
  2. For each label L of |labels|:
    1. Perform CreateDataPropertyOrThrow(|object|, CamelCase(L), |value|'s L bit as a Boolean).
  3. Return |object|.

ToJSValueVariant(value, cases):

  1. Let |object| be OrdinaryObjectCreate(null).
  2. Perform CreateDataPropertyOrThrow(|object|, "kind", CaseLabelOf(|value|, |cases|)).
  3. If that case has a payload of type T:
    1. Perform CreateDataPropertyOrThrow(|object|, "value", ToJSValue(PayloadOf(|value|), T)).
  4. Return |object|.

This operation is used for variant, and also cases in the above table where we can't specialize the behavior of option and result.

ToJSValueMap(value, K, V):

  1. Let |map| be a new ordinary Map object with an empty [[MapData]] and the component realm's %Map.prototype%.
  2. For each pair (k, v) of |value|, in order:
    1. Let |key| be ToJSValue(k, K).
    2. Let |mapValue| be ToJSValue(v, V).
    3. If [[MapData]] has an entry whose key is SameValueZero to |key|:
      1. Set that entry's value to |mapValue|.
    4. Else:
      1. Append an entry (|key|, |mapValue|) to [[MapData]].
  3. Return |map|.

A map<K, V> is a specialization of list<tuple<K, V>> where the last pair for a key defines its value. So [(a,1),(a,2)] round-trips from a component value to JS and back as [(a,2)].

ToComponentValue

ToComponentValue(jsValue, targetComponentType) converts a JS value to a component value. It may throw if the JS value doesn't match the component value type.

A component value is a specification device. An implementation lowers the JS value straight into the component's memory and handle tables, so the steps below are interleaved with the canonical ABI's lowering. A final specification would need to be more precise on the ordering of observable actions.

Dispatch on targetComponentType:

  • bool → ToBoolean(|jsValue|).
  • Integer types → ? ToComponentValueInteger(|jsValue|, the type).
  • Float types → ? ToComponentValueFloat(|jsValue|, the type).
  • char → ? ToString(|jsValue|); it must consist of exactly one Unicode scalar value, else throw a TypeError. A lone surrogate is not a scalar value and is therefore a TypeError.
  • string → ? ToString(|jsValue|), then replace each unpaired surrogate with U+FFFD (matching WebIDL USVString).
  • list<Scalar> → ? ToComponentValueScalarList(|scalar|, |jsValue|).
  • list<T> → ? ToComponentValueList(|jsValue|, T, none).
  • list<T, N> → ? ToComponentValueList(|jsValue|, T, N).
  • tuple<Types...> → ? ToComponentValueTuple(|jsValue|, Types...)
  • record { f: T, ... } → ? ToComponentValueRecord(|jsValue|, the fields).
  • flags "L"+ → ? ToComponentValueFlags(|jsValue|, the labels).
  • enum → ? ToString(|jsValue|) must be one of the labels, else throw a TypeError.
  • option<T> not nested within another option → null and undefined both give none; anything else gives some(ToComponentValue(jsValue, T)).
  • variant, and nested option, and result outside return position → ? ToComponentValueVariant(|jsValue|, the cases). In return position a result is unwrapped instead: a JS return value becomes result.ok, and a thrown exception becomes result.error (see Read the imports and Create the exports object).
  • map<K, V> → ? ToComponentValueMap(|jsValue|, K, V).
  • own<R> / borrow<R> → See Resource types.
  • future<T> → TODO.
  • stream<T> → TODO.
  • error-context → TODO.

ToComponentValueInteger(jsValue, t):

  1. Return the result of the matching operation below, applied to |jsValue|:
    • s8 → ToInt8
    • u8 → ToUint8
    • s16 → ToInt16
    • u16 → ToUint16
    • s32 → ToInt32
    • u32 → ToUint32
    • s64 → ToBigInt64
    • u64 → ToBigUint64

Out-of-range values wrap and NaN and infinities become 0, matching the core JS API's ToWebAssemblyValue. The 64-bit types require a BigInt, so a Number throws a TypeError.

ToComponentValueFloat(jsValue, t):

  1. Let |num| be ? ToNumber(|jsValue|).
  2. If |t| is f32:
    1. Set |num| to |num| rounded to the nearest f32 value (ties to even).
  3. Return |num|.

NaN and infinities are accepted (matching WebIDL unrestricted float/unrestricted double).

ToComponentValueScalarList(scalar, jsValue):

  1. If |jsValue| has a [[TypedArrayName]] internal slot whose value is the scalar typed array class for |scalar|:
    1. If |jsValue|'s underlying buffer is detached or |jsValue| is out of bounds:
      1. Throw a TypeError.
    2. Return one |scalar| per element of |jsValue|, in order.
  2. Return ToComponentValueList(|jsValue|, |scalar|, none).

A typed array of the matching class is copied directly, since that is what ToJSValue produces. Anything else goes through the iterable path, so other typed arrays and plain Arrays behave like they do in the new TypedArray(iterable) constructor.

IterableToValues(jsValue):

  1. If |jsValue| is not an Object:
    1. Return not-iterable.
  2. Let |method| be ? GetMethod(|jsValue|, %Symbol.iterator%).
  3. If |method| is undefined:
    1. Return not-iterable.
  4. Return ? IteratorToList(? GetIteratorFromMethod(|jsValue|, |method|)).

%Symbol.iterator% is looked up once, and the iterable is consumed before any element is converted, so that the canonical ABI has the length before calling realloc and converting elements.

ToComponentValueList(jsValue, T, N):

  1. Let |values| be ? IterableToValues(|jsValue|).
  2. If |values| is not-iterable:
    1. Throw a TypeError.
  3. Let |valuesLength| be the length of |values|.
  4. If |N| is not none:
    1. Let |listLength| be |N|.
  5. Else:
    1. Let |listLength| be |valuesLength|.
  6. Let |list| be an empty component list with length |listLength| of type T.
  7. For |i| in 0..|listLength|:
    1. If |i| >= |valuesLength|:
      1. Let |value| be undefined.
    2. Else:
      1. Let |value| be |values|[|i|].
    3. Set |list|[|i|] to ? ToComponentValue(|value|, T).
  8. Return |list|.

For fixed-length lists, any missing values from the iterable are filled in with undefined.

ToComponentValueTuple(jsValue, Types...):

  1. Let |values| be ? IterableToValues(|jsValue|).
  2. If |values| is not-iterable:
    1. Throw a TypeError.
  3. Let |valuesLength| be the length of |values|.
  4. Let |listLength| be the length of |Types|.
  5. Let |list| be an empty component tuple with element types |Types|.
  6. For |i| in 0..|listLength|:
    1. If |i| >= |valuesLength|:
      1. Let |value| be undefined.
    2. Else:
      1. Let |value| be |values|[|i|].
    3. Set |list|[|i|] to ? ToComponentValue(|value|, |Types|[|i|]).
  7. Return |list|.

A tuple is treated like a fixed-length list, except the destination type for conversion changes based on the element index.

ToComponentValueRecord(jsValue, fields):

  1. If |jsValue| is not an Object:
    1. Throw a TypeError.
  2. Let |record| be a new component record value with one field per |fields|.
  3. For each field f: T of |fields|, in declaration order:
    1. Let |m| be ? Get(|jsValue|, CamelCase(f)).
    2. Set |record|'s f field to ? ToComponentValue(|m|, T).
  4. Return |record|.

ToComponentValueFlags(jsValue, labels):

  1. If |jsValue| is not an Object:
    1. Throw a TypeError.
  2. Let |flags| be a new component flags value with every bit initially false.
  3. For each label L of |labels|:
    1. Set |flags|'s L bit to ToBoolean(? Get(|jsValue|, CamelCase(L))).
  4. Return |flags|.

An absent property is therefore false, matching a boolean dictionary member defaulted to false.

ToComponentValueVariant(jsValue, cases):

  1. If |jsValue| is not an Object:
    1. Throw a TypeError.
  2. Let |kind| be ? ToString(? Get(|jsValue|, "kind")).
  3. If there is no case of |cases| whose label L has L equal to |kind|:
    1. Throw a TypeError.
  4. Let |case| be that case.
  5. If |case| has a payload type T:
    1. Let |payload| be ? ToComponentValue(? Get(|jsValue|, "value"), T).
    2. Return a variant value of |case| whose payload is |payload|.
  6. Return a variant value of |case| with no payload.

This operation is used for variant, and also cases in the above table where we can't specialize the behavior of option and result.

ToComponentValueMap(jsValue, K, V):

  1. If |jsValue| is not an Object:
    1. Throw a TypeError.
  2. Let |map| be a new empty component map value.
  3. Let |values| be ? IterableToValues(|jsValue|).
  4. If |values| is a List:
    1. For each |v| of |values|:
      1. Append ? ToComponentValue(|v|, tuple<K, V>) to |map|.
    2. Return |map|.
  5. If K is not string:
    1. Throw a TypeError.
  6. Let |keys| be ? |jsValue|.[OwnPropertyKeys].
  7. For each |key| of |keys|:
    1. Let |desc| be ? |jsValue|.[GetOwnProperty].
    2. If |desc| is not undefined and |desc|.[[Enumerable]] is true:
      1. Let |typedKey| be ? ToComponentValue(|key|, K).
      2. Let |value| be ? Get(|jsValue|, |key|).
      3. Let |typedValue| be ? ToComponentValue(|value|, V).
      4. Append (|typedKey|, |typedValue|) to |map|.
  8. Return |map|.

If the value is not iterable, we fall back to converting the object the way WebIDL's record<USVString, V> would, for compatibility.

Resource types

A component resource type can be defined in a component (i.e. a guest resource), or else as an imported abstract type (i.e. a host resource).

The component JS-API defines:

  1. How a JS value satisfies a resource type import.
  2. A spec representation of host resource types and values.
  3. A JS representation of guest resource types and values.

Embedder extensions

We sketch two operations here that will be formalized more fully in the embedding interface.

To create a resource type for host given a host function |destructor|:

  1. Return a fresh component resource type whose representation is host-defined and whose destructor is |destructor|.

To drop a guest resource given a guest resource class |class| and a guest rep |rep| owned by the host:

  1. Let |resourceType| be |class|.[[ResourceType]].
  2. Let |instance| be |class|.[[Instance]].
  3. If |instance|.[[Store]].is_locked_down():
    1. Perform ? trap given |instance|.
  4. Perform the effect of canon resource.drop on an owning handle holding |resourceType| and |rep|, invoking |resourceType|'s destructor. There is no handle table entry to remove, because the host was holding the rep.
  5. If that traps:
    1. Perform ? trap given |instance|.

Abstract and transparent types

Imported and exported resource types are either abstract or transparently equivalent to a previous abstract import or export.

(type (component
  (import "r1" (type $r1 (sub resource)))
  (import "r2" (type (eq $r1)))
  (import "r3" (type (sub resource)))

  (export "r4" (type $r4 (sub resource)))
  (export "r5" (type (eq $r4)))
  (export "r6" (type (sub resource)))

  (export "r7" (type (eq $r3)))
))

r1, r3, r4, r6 are the abstract types of this component type, while r2, r5, and r7 are transparently equal to one of the abstract types.

Host/guest resource types below are created only for abstract types, and stored in maps on the instance record. The map is keyed by an abstract type key, which is an import/export declaration for an abstract type.

A type import or export declares a resource type if following (eq R) reaches a (sub resource). An abstract type key can be found for any such declaration by following (eq R) until you reach that (sub resource).

Type declarations that do not declare a resource type, such as an exported record, exist only to satisfy external visibility and have no JS representation. The JS-API skips them: a type import is not read from the imports object and a type export is left off the exports object.

Host resource types (i.e. imported)

Host resource types and values

A host resource type is what the JS-API creates to satisfy a resource type import. It is a Record with the following fields:

Field Value
[[ComponentResourceType]] the component resource type produced by create a resource type for host
[[ConstructorObject]] the JS constructor that satisfied the import

A host resource value is the rep of a host resource type. It too is a Record:

Field Value
[[Type]] the host resource type this is a rep of
[[JSValue]] the JS value, held strongly

A host resource value just holds a strong reference to the underlying value. %Symbol.dispose% is captured from the constructor's prototype upon instantiation and is invoked when the resource is dropped. Dropping a resource is infallible, so if the destructor fails this results in a trap and lockdown.

One host resource type is created per imported abstract type. Two abstract type imports satisfied by the same JS constructor become distinct component resource types, and a handle for one cannot be passed where the other is expected.

A map from imported abstract type to host resource type is built by read the imports object and stored on the instance record.

Brand checks

A resource type import is satisfied by a constructor. Each time a JS value needs to be converted to a value of that resource type, it is brand checked against the constructor.

To brand check given a JS value |jsValue| and an Object |constructor|:

  1. If |constructor| is a WebIDL interface object:
    1. Return true if and only if |jsValue| is a platform object that implements the interface |constructor| is the interface object of.
  2. Return ? InstanceofOperator(|jsValue|, |constructor|).

Which case applies is fixed for the lifetime of |constructor|.

The first case is a real brand check. The instanceof fallback only inspects the prototype chain, so a value that was never created by |constructor| can pass it. In the future we may add a way for JS to supply a custom brand check through a Symbol based protocol.

A guest resource class never reaches a brand check, because importing one is a LinkError.

Conversions for host resources

For a resource type R whose abstract type is one of the component's type imports:

  • ToJSValue(rep, own<R> | borrow<R>):
    1. Let |abstractTypeKey| be the abstract type key of |R|.
    2. Let |hostType| be the current call's [[HostResourceTypes]][|abstractTypeKey|].
    3. Assert: |rep| is a host resource value whose [[Type]] is |hostType|.
    4. Return |rep|.[[JSValue]].
  • ToComponentValue(jsValue, own<R> | borrow<R>):
    1. Let |abstractTypeKey| be the abstract type key of |R|.
    2. Let |hostType| be the current call's [[HostResourceTypes]][|abstractTypeKey|].
    3. Let |matches| be ? brand check given |jsValue| and |hostType|.[[ConstructorObject]].
    4. If |matches| is false:
      1. Throw a TypeError.
    5. Return a host resource value whose [[Type]] is |hostType| and whose [[JSValue]] is |jsValue|.

Converting the same JS value to a host resource type yields fresh handle indices. There is no canonicalization of indices.

Guest resource types (i.e. exported)

Re-exported host resource types

A component's type may export a resource type that is transparently equal to one of its imported resource types (see abstract types). This currently throws a LinkError at instantiation, but may be relaxed in the future.

An exported resource type that is only privately a re-export of an imported type, i.e. the component's type declares it as a fresh abstract export, will wrap the original host resource type in a new guest resource class. This keeps callers from observing whether an exported resource type is a re-export or defined in the component.

Re-imported guest resource types

An exported guest resource type may be imported by a separate ComponentInstance through the JS-API. As explained in component store, there is no direct component model linking between top-level instances through the JS-API. However, we do want to ensure that incidental linking of components through the JS-API works well, and there are tricky questions around handling own and borrow. So we temporarily throw a LinkError in this case.

Guest resource classes

A unique JS guest resource class is created for each exported abstract type. A map from abstract type key to guest resource class is stored on the instance record.

A guest resource class is a built-in function object with the following slots:

  1. [[ResourceType]] - the guest resource type.
  2. [[ConstructorFunc]] - the component function that implements new, or empty.
  3. [[Instance]] - the instance record the class belongs to.

To create a guest resource class given an instance record |instance|, a list of export declarations |exportDecls|, resource type |resourceType|, String |name| and an integer |arity|:

  1. Let |prototype| be OrdinaryObjectCreate(%Object.prototype%).
  2. Let |constructor| be a built-in function object with name |name| and length |arity|.
  3. Set |constructor|.[[ResourceType]] to |resourceType|.
  4. Set |constructor|.[[ConstructorFunc]] to empty.
  5. Set |constructor|.[[Instance]] to |instance|.
  6. Set |constructor|'s [[Call]] behaviour to throw a TypeError.
  7. Set |constructor|'s [[Construct]] behaviour, given JS arguments |args| and |newTarget|, to perform:
    1. If |constructor|.[[ConstructorFunc]] is empty:
      1. Throw a TypeError.
    2. Let |proto| be ? Get(|newTarget|, "prototype").
    3. If Type(|proto|) is not Object:
      1. Set |proto| to |prototype|.
    4. Let |rep| be ? run within a call given |instance|.[[HostResourceTypes]], |instance|.[[GuestResourceClasses]], and the following steps:
      1. Return ? invoke a component function given |instance|, |constructor|.[[ConstructorFunc]], false, undefined and |args|.
    5. Return create an own guest resource object given |constructor|, |rep| and |proto|.
  8. Let |disposeFunc| be a built-in function object with name "[Symbol.dispose]" and length 0 that performs dispose a guest resource object given its this value.
  9. Perform DefinePropertyOrThrow(|prototype|, %Symbol.dispose%, PropertyDescriptor { [[Value]]: |disposeFunc|, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).
  10. Perform DefinePropertyOrThrow(|prototype|, %Symbol.toStringTag%, PropertyDescriptor { [[Value]]: |name|, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }).
  11. Perform DefinePropertyOrThrow(|prototype|, "constructor", PropertyDescriptor { [[Value]]: |constructor|, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).
  12. Perform DefinePropertyOrThrow(|constructor|, "prototype", PropertyDescriptor { [[Value]]: |prototype|, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }).
  13. Let |members| be the function exports of |exportDecls| whose names match Constructor or Member with a resource capture naming |resourceType|.
  14. If some |c| of |members| matches Constructor:
    1. Assert: there is only one by validation rules.
    2. Set |constructor|.[[ConstructorFunc]] to |c|.Func.
  15. For each |e| of |members| matching Member, in declaration order:
    1. If JSName(|e|) is in reserved class members:
      1. Continue.
    2. If |e|.Name's scope capture is "method":
      1. Let |target| be |prototype|.
      2. Let |takesSelf| be true.
    3. Else:
      1. Assert: |e|.Name's scope capture is "static".
      2. Let |target| be |constructor|.
      3. Let |takesSelf| be false.
    4. If |e|.Name has an accessor capture:
      1. Perform define an accessor for a component function given |instance|, |target|, |e| and false.
    5. Else:
      1. Let |func| be create a JS function for a component function given |instance|, |e|.Func, JSName(|e|) and |takesSelf|.
      2. Perform DefinePropertyOrThrow(|target|, JSName(|e|), PropertyDescriptor { [[Value]]: |func|, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).
  16. Return |constructor|.

The following names are reserved class members:

  • "proto"
  • "constructor"
  • "prototype"
  • "arguments"
  • "caller"
  • "name"
  • "length"

Defining these on the constructor or prototype may unexpectedly change JS class semantics. They are exported through create the exports object in a generic way alongside all the other exports.

Member exports with an accessor capture become the two halves of one accessor property, on prototype when scope is "method" and on the class itself when it is "static". Validation requires a [set] to be preceded in the same scope by the [get] it pairs with, so the getter is always defined first and the setter only fills in the accessor's [[Set]] field.

Guest resource objects

A guest resource object has the following slots:

  1. [[ResourceClass]] - the resource class this object is an instance of.
  2. [[Rep]] - the rep, or empty once the handle has been detached or dropped.
  3. [[LendCount]] - how many outstanding borrows were lent from this object.

It holds the same state a handle table entry does, plus the class it belongs to. A guest resource object always owns a rep.

To create an own guest resource object given a resource class |class|, |rep|, and an optional Object |proto|:

  1. If |proto| is not present:
    1. Let |proto| be the value of |class|'s "prototype" property.
  2. Let |object| be OrdinaryObjectCreate(|proto|, « [[ResourceClass]], [[Rep]], [[LendCount]] »).
  3. Set |object|.[[ResourceClass]] to |class|.
  4. Set |object|.[[Rep]] to |rep|.
  5. Set |object|.[[LendCount]] to 0.
  6. Register |object| in the guest resource FinalizationRegistry with held value a record { [[ResourceClass]]: |class|, [[Rep]]: |rep| } and unregister token |object|.
  7. Return |object|.

To detach a guest resource object given resource object |resourceObject|:

  1. Assert: |resourceObject|.[[Rep]] is not empty and |resourceObject|.[[LendCount]] is 0.
  2. Set |resourceObject|.[[Rep]] to empty.
  3. Unregister |resourceObject| from the guest resource FinalizationRegistry.

To dispose a guest resource object given |resourceObject|:

  1. If |resourceObject|.[[Rep]] is empty:
    1. Assert |resourceObject|.[[LendCount]] is 0.
    2. Return undefined.
  2. If |resourceObject|.[[LendCount]] is not 0:
    1. Throw a TypeError.
  3. Let |class| be |resourceObject|.[[ResourceClass]].
  4. Let |rep| be |resourceObject|.[[Rep]].
  5. Perform detach a guest resource object with |resourceObject|.
  6. Perform drop a guest resource given |class| and |rep|.
  7. Return undefined.

The [[LendCount]] check can only fail on the %Symbol.dispose% path, because a lent object is kept alive by the [[Lenders]] of the call it was lent to.

To finalize a guest resource object given |resourceClass| and |resourceRep|:

  1. If |resourceClass|.[[Instance]].[[Store]].is_locked_down():
    1. Return.
  2. Perform ? drop a guest resource given |resourceClass| and |resourceRep|.

The current call lender list should keep all guest resource object's alive such that they cannot be finalized.

Conversions for guest resources

Each guest resource object lowered as a borrow while converting the arguments of a JS-to-component call has its [[LendCount]] incremented and is appended to the current call's [[Lenders]], which protects it from being disposed while lent. When the call resolves (and so the callee has dropped all its borrows) invoke a component function decrements every [[LendCount]] in the list.

For a resource type R whose abstract type is one of the component's type exports:

  • ToJSValue(rep, own<R>):
    1. Let |abstractTypeKey| be the abstract type key of |R|.
    2. Let |class| be the current call's [[GuestResourceClasses]][|abstractTypeKey|].
    3. Return create an own guest resource object given |class| and |rep|.
  • ToJSValue(rep, borrow<R>):
    1. Assert: unreachable.
    2. This can only happen if an exported function returns a borrow, which is not allowed.
  • ToComponentValue(jsValue, own<R>):
    1. Let |abstractTypeKey| be the abstract type key of |R|.
    2. Let |class| be the current call's [[GuestResourceClasses]][|abstractTypeKey|].
    3. If |jsValue| does not have a [[ResourceClass]] internal slot, or |jsValue|.[[ResourceClass]] is not |class|:
      1. Throw a TypeError.
    4. If |jsValue|.[[Rep]] is empty, or |jsValue|.[[LendCount]] is not 0:
      1. Throw a TypeError.
    5. Let |rep| be |jsValue|.[[Rep]].
    6. Perform detach a guest resource object with |jsValue|.
    7. Return |rep|.
  • ToComponentValue(jsValue, borrow<R>):
    1. Let |abstractTypeKey| be the abstract type key of |R|.
    2. Let |class| be the current call's [[GuestResourceClasses]][|abstractTypeKey|].
    3. If |jsValue| does not have a [[ResourceClass]] internal slot, or |jsValue|.[[ResourceClass]] is not |class|:
      1. Throw a TypeError.
    4. If |jsValue|.[[Rep]] is empty:
      1. Throw a TypeError.
    5. Let |lenders| be the current call's [[Lenders]].
    6. Assert: |lenders| is not empty.
    7. Increment |jsValue|.[[LendCount]].
    8. Append |jsValue| to |lenders|.
    9. Return |jsValue|.[[Rep]].

Guest resource FinalizationRegistry

There is an unexposed "guest resource FinalizationRegistry" created per-Realm of the WebAssembly namespace object. The callback for it, given a held value |record|, performs finalize a guest resource object given |record|.[[ResourceClass]] and |record|.[[Rep]].

The held value is a record of the objects's class and rep rather than the object itself, because registering an object with itself as the held value would keep it alive forever. The record never goes stale, because the object is unregistered whenever its [[Rep]] is taken.

Instantiation

To instantiate a component given |component|, a list of component definitions |imports|, and |hostResourceTypes|:

  1. If the type of any function import or export of |component|, including those nested in instance imports and exports, is async:
    1. Throw a WebAssembly.LinkError.
  2. If any type export of |component|'s type, including those nested in instance exports, declares a resource type whose abstract type key is an import declaration:
    1. Throw a WebAssembly.LinkError.
  3. Let |store| be a new component store.
  4. Let |componentInstance| be the result of instantiating |component| with |imports| in |store|.
  5. If instantiation traps:
    1. Throw a WebAssembly.RuntimeError.
  6. Let |instance| be a new instance record { [[Store]]: |store|, [[ComponentInstance]]: |componentInstance|, [[HostResourceTypes]]: |hostResourceTypes|, [[GuestResourceClasses]]: a new empty map }.
  7. Perform create guest resource classes given |instance| and |componentInstance|.Exports.
  8. Let |exportsObject| be ? create the exports object given |instance| and |componentInstance|.Exports.
  9. Return a Record { [[Instance]]: |instance|, [[Exports]]: |exportsObject| }.

We temporarily reject async function imports/exports until they are specified, and re-exported host resource types until their semantics are settled.

To instantiate a component from an imports object given |component|, |importsObject|, and |enabledBuiltins|:

  1. Let |imports| and |hostResourceTypes| be ? read the imports object given |component|, |importsObject|, and |enabledBuiltins|.
  2. Return ? instantiate a component given |component|, |imports|, and |hostResourceTypes|.

Read the imports object

The top-level read the imports object algorithm walks the component's imports and resolves each to a JS value via property lookups on the |importsObject|, mirroring the core JS-API's algorithm of the same name.

The resolved JS values are then handed to the per-sort algorithms (read the function import, read the type import, and the rest) to produce the component definitions used during instantiation.

While walking, the algorithm recognizes the pattern of a resource type import accompanied by Constructor and Member function imports naming it. A resource type import is read first and looks for a constructor (see resource types). Those function imports then read from the constructor and its prototype directly. This allows the common case of importing a class to be satisfied by just passing the constructor.

Passing an exported component definition to a component import via the JS-API/ESM-integration is treated as if the import were a JS value. There is no "direct linking" that bypasses going through JS semantics. See component store for more details.

To read the imports object given |component|, |importsObject|, and |enabledBuiltins|:

  1. Let |hostResourceTypes| be an empty map from abstract type key to host resource type record.
  2. If |component| has no imports:
    1. Return an empty list and |hostResourceTypes|.
  3. Let |imports| be ? read a scope of imports given |component|.Imports, |importsObject|, |enabledBuiltins|, and |hostResourceTypes|.
  4. Return |imports| and |hostResourceTypes|.

To read a scope of imports given a list of import declarations |importDecls|, |importsObject|, |enabledBuiltins|, and |hostResourceTypes|:

  1. Let |definitions| be a new empty list.
  2. For each |importDecl| of |importDecls|, in declaration order:
    1. If |importDecl|.Sort is type:
      1. If |importDecl| does not declare a resource type:
        1. Append the type |importDecl| declares to |definitions|.
        2. Continue.
      2. Let |abstractTypeKey| be the abstract type key of |importDecl|.
      3. If |hostResourceTypes|[|abstractTypeKey|] exists:
        1. Append |hostResourceTypes|[|abstractTypeKey|].[[ComponentResourceType]] to |definitions|.
        2. Continue.
    2. Let |name| be JSName(|importDecl|).
    3. Let |builtin| be ? resolve a builtin specifier given |name| and |enabledBuiltins|.
    4. If |builtin| is not empty:
      1. Let |importValue| be |builtin|.
    5. Else:
      1. If |importDecl|.Sort is func and |importDecl|.Name matches Constructor or Member:
        1. Let |abstractTypeKey| be the abstract type key of the type import named by the resource capture.
        2. Assert: |hostResourceTypes|[|abstractTypeKey|] exists. (Validation requires that declaration to precede this one in the same scope)
        3. Let |constructorFunction| be |hostResourceTypes|[|abstractTypeKey|].[[ConstructorObject]].
        4. If |importDecl|.Name matches Constructor:
          1. Let |importValue| be |constructorFunction|.
        5. Else:
          1. If the scope capture is "static":

            1. Let |lookupTarget| be |constructorFunction|.
          2. Else:

            1. Let |lookupTarget| be ? Get(|constructorFunction|, "prototype").
            2. If Type(|lookupTarget|) is not Object:
              1. Throw a WebAssembly.LinkError.
          3. If |importDecl|.Name has an accessor capture:

            1. Let |importValue| be ? find an accessor given |lookupTarget|, |name| and the accessor capture.
          4. Else:

            1. Let |importValue| be ? Get(|lookupTarget|, |name|).
      2. Else:
        1. If Type(|importsObject|) is not Object:

          1. Throw a TypeError.
        2. If |importDecl|.Sort is func and |importDecl|.Name matches Property:

          1. Let |importValue| be ? find an accessor given |importsObject|, |name| and the accessor capture.
        3. Else:

          1. Let |importValue| be ? Get(|importsObject|, |name|).
    6. Let |resolved| be ? read an import given |importDecl|, |importValue| and |hostResourceTypes|.
    7. Append |resolved| to |definitions|.
  3. Return |definitions|.

To read an import given |importDecl|, |importValue| and |hostResourceTypes|:

  1. Match |importDecl|.Sort:
    1. core module: return ? read the core module import given |importDecl|.ModuleType and |importValue|.
    2. func: return ? read the function import given |importDecl|.FuncType, |importValue|, |importDecl|.Name and |hostResourceTypes|.
    3. type: return ? read the type import given |importDecl|, |importValue|, and |hostResourceTypes|.
    4. value: return ? read the value import given |importDecl|.ValType, |importValue| and |hostResourceTypes|.
    5. instance: return ? read the instance import given |importDecl|.InstanceType, |importValue| and |hostResourceTypes|.
    6. component: return ? read the component import given |importDecl|.ComponentType and |importValue|.

To read the core module import given |coreModuleType| and |importValue|:

  1. If |importValue| does not have a [[Module]] internal slot:
    1. Throw a WebAssembly.LinkError.
  2. If the type of |importValue|.[[Module]] is not a subtype of |coreModuleType|:
    1. Throw a WebAssembly.LinkError.
  3. Return |importValue|.[[Module]].

To read the component import given |componentType| and |importValue|:

  1. If |importValue| does not have a [[Component]] internal slot:
    1. Throw a WebAssembly.LinkError.
  2. If the type of |importValue|.[[Component]] is not a subtype of |componentType|:
    1. Throw a WebAssembly.LinkError.
  3. Return |importValue|.[[Component]].

To read the instance import given |instanceType|, |importValue| and |hostResourceTypes|:

  1. If Type(|importValue|) is not Object:
    1. Throw a WebAssembly.LinkError.
  2. Let |definitions| be ? read a scope of imports given |instanceType|.Exports, |importValue|, an empty set of enabled builtins, and |hostResourceTypes|.
  3. Return a component instance whose exports are |definitions|.

To read the type import given |importDecl|, |importValue|, and |hostResourceTypes|:

  1. Let |abstractTypeKey| be the abstract type key of |importDecl|.
  2. Assert: |hostResourceTypes|[|abstractTypeKey|] does not exist. (read a scope of imports handles transparent imports)
  3. If IsCallable(|importValue|) is false:
    1. Throw a WebAssembly.LinkError.
  4. If |importValue| has a [[ConstructorFunc]] internal slot:
    1. Assert: |importValue| is a guest resource class.
    2. Throw a WebAssembly.LinkError.
  5. Let |dispose| be undefined.
  6. Let |prototype| be ? Get(|importValue|, "prototype").
  7. If Type(|prototype|) is Object:
    1. Set |dispose| to ? Get(|prototype|, %Symbol.dispose%).
  8. Let |hasDispose| be IsCallable(|dispose|).
  9. Let |destructor| be a host function that given a host resource value |self|:
    1. Let |selfValue| be |self|.[[JSValue]].
    2. Set |self|.[[JSValue]] to undefined.
    3. If |hasDispose|:
      1. Let |result| be Call(|dispose|, |selfValue|, the empty list).
      2. If |result| is an abrupt completion:
        1. Trap.
  10. Let |resourceType| be create a resource type for host given |destructor|.
  11. Let |hostResourceType| be a new host resource type record whose [[ComponentResourceType]] is |resourceType| and [[ConstructorObject]] is |importValue|.
  12. Set |hostResourceTypes|[|abstractTypeKey|] to |hostResourceType|.
  13. Return |resourceType|.

%Symbol.dispose% is captured from the constructor's prototype, and called when the resource is dropped. Dropping a resource is infallible, so if it throws an exception, this becomes a trap which results in lockdown.

To find an accessor given an object |target|, a property key |key| and |kind|, which is either "get" or "set":

  1. Let |object| be |target|.
  2. Repeat, while |object| is not null:
    1. Let |desc| be ? |object|.[GetOwnProperty].
    2. If |desc| is not undefined:
      1. If IsAccessorDescriptor(|desc|) is false:
        1. Return undefined.
      2. If |kind| is "get", return |desc|.[[Get]].
      3. Return |desc|.[[Set]].
    3. Set |object| to ? |object|.[GetPrototypeOf].
  3. Return undefined.

The walk stops at the first own property it finds, as an ordinary property access does. A data property that shadows an accessor further up the chain therefore resolves to undefined and becomes a LinkError.

To read the function import given |componentFuncType|, |importValue|, |importName| and |hostResourceTypes|:

  1. Let |isConstructor| be true if |importName| matches Constructor, and false otherwise.
  2. If IsCallable(|importValue|) is false or (|isConstructor| is true and IsConstructor(|importValue|) is false):
    1. Return a new Abstract Closure with parameters (|onStart|, |onResolve|) that traps when called.
  3. Let |takesSelf| be true if |importName| matches Member with scope "method", and false otherwise.
  4. Return create a component function for a JS function given |componentFuncType|, |importValue|, |isConstructor|, |takesSelf| and |hostResourceTypes|.

To create a component function for a JS function given |componentFuncType|, |callable|, a Boolean |isConstructor|, a Boolean |takesSelf| and |hostResourceTypes|:

  1. Let |paramTypes| be |componentFuncType|.Params.
  2. Let |resultType| be |componentFuncType|.Result.
  3. Let |paramOffset| be 1 if |takesSelf| is true, else 0.
  4. If |resultType| is a result:
    1. Let |okType| be its ok payload type, or empty if it has none.
    2. Let |errorType| be its error payload type, or empty if it has none.
    3. Let |throwing| be true.
  5. Else:
    1. Let |okType| be |resultType|, or empty if |componentFuncType| has no result.
    2. Let |throwing| be false.
  6. Return a new Abstract Closure with parameters (|onStart|, |onResolve|) that performs the following steps when called:
    1. Let |values| be |onStart|().
    2. Let |results| be run within a call given |hostResourceTypes|, a new empty map, and a new Abstract Closure that performs the following steps when called:
      1. Let |args| be a new empty List.
      2. For each i in [|paramOffset|, |values|.length):
        1. Append ToJSValue(|values|[i], |paramTypes|[i]) to |args|.
      3. If |isConstructor| is true:
        1. Let |completion| be Completion(Construct(|callable|, |args|)).
      4. Else:
        1. If |takesSelf| is true:
          1. Let |thisArg| be ToJSValue(|values|[0], |paramTypes|[0]).
        2. Else:
          1. Let |thisArg| be undefined.
        3. Let |completion| be Completion(Call(|callable|, |thisArg|, |args|)).
      5. If |completion| is an abrupt completion:
        1. If |throwing| is false:
          1. Trap.
        2. If |errorType| is empty:
          1. Return « result.error ».
        3. Let |errorValue| be ToComponentValue(|completion|.[[Value]], |errorType|).
        4. If that throws:
          1. Trap.
        5. Return « result.error(|errorValue|) ».
      6. If |okType| is empty:
        1. If |throwing| is true:
          1. Return « result.ok ».
        2. Return « ».
      7. Let |okValue| be ToComponentValue(|completion|.[[Value]], |okType|).
      8. If that throws:
        1. Trap.
      9. If |throwing| is true:
        1. Return « result.ok(|okValue|) ».
      10. Return « |okValue| ».
    3. Perform |onResolve|(|results|).
    4. Let |onCancel| be a new Abstract Closure with no parameters that performs nothing when called.
    5. Return |onCancel|.

The returned closure is a FuncInst. Since |componentFuncType| is not async, it calls |onStart| and |onResolve| synchronously, and so the caller never needs the returned OnCancel.

To read the value import given |componentValType|, |importValue| and |hostResourceTypes|:

  1. Return ? run within a call given |hostResourceTypes|, a new empty map, and a new Abstract Closure with no parameters that captures |importValue| and |componentValType| and performs the following steps when called:
    1. Return ? ToComponentValue(|importValue|, |componentValType|).

Builtin imports

The component JS-API can provide builtins to imports just as the core JS-API does.

Builtin imports are opt-in via the builtins field of WebAssemblyCompileOptions when used in the JS-API. ESM-integration enables all builtins by default.

This spec defines one builtin specifier:

Builtin Specifiers Resolves to
js/global wasm:js/global, wasm:js/global/* the global object

To resolve a builtin specifier given a String |specifier| and a set of Strings |enabledBuiltins|:

  1. If |specifier| does not start with "wasm:":
    1. Return empty.
  2. Let |name| be the portion of |specifier| after "wasm:".
  3. If |name| is "js/global" or starts with "js/global/":
    1. If |enabledBuiltins| does not contain "js/global":
      1. Return empty.
    2. Return ? resolve a js global builtin with |name|.
  4. Return empty.

The global object

The normal read the imports object rules are designed so that JS classes can be imported by just providing the constructor object. wasm:js/global/* provides a fine-grained way to get access to globally exposed constructors and other functions. This reduces the amount of glue code needed in the common case.

wasm:js/global resolves to the globalThis of the component realm, and nested paths resolve to a chain of property accessors off of the global (e.g. wasm:js/global/console is globalThis.console).

To resolve a js global builtin with String |name|:

  1. Let |result| be the component realm's globalThis.
  2. If |name| is "js/global":
    1. Return |result|.
  3. Assert: |name| starts with "js/global/".
  4. Let |remaining| be the portion of |name| after "js/global/".
  5. Let |projections| be the result of splitting |remaining| on "/".
  6. For each |projection| of |projections|:
    1. Set |result| to ? Get(|result|, |projection|).
  7. Return |result|.

TODO: Handle whitespace? TODO: Within the wasm scheme we're parsing this similar to a general URL, but no using the canonical algorithm. We don't need the general algorithm and it's a nice dependency to avoid. But are there future compatibility or extensibility reasons we should use it?

Create the exports object

The create the exports object algorithm walks the component's exports and builds a fresh JS object whose properties are the exports.

Exported resource types become guest resource classes named JSName(|export|), and function exports matching Constructor or Member are mapped onto the class R named by their resource capture, just as in read the imports object:

  • Constructor: the function becomes R's constructor behaviour. Names are strongly-unique, so there can only be one.
  • Member with scope "method": the function becomes a method named JSName(|export|) on R.prototype.
  • Member with scope "static": the function becomes a static method named JSName(|export|) on R.
  • Member with an accessor capture: the "get" and "set" functions become the getter and setter of one accessor property named JSName(|export|), again on R.prototype or on R.

A Property export becomes an accessor property on the exports object itself. All other exported component definitions are given JS definitions named JSName(|export|) on the exports object.

To create guest resource classes given an instance record |instance| and a list of export declarations |exportDecls|:

  1. Let |guestResourceClasses| be |instance|.[[GuestResourceClasses]].
  2. For each |export| of |exportDecls|, in declaration order:
    1. If |export|.Sort is instance:
      1. Perform create guest resource classes given |instance| and the exports of the exported instance.
      2. Continue.
    2. If |export|.Sort is not type, or |export| does not declare a resource type:
      1. Continue.
    3. Let |abstractTypeKey| be the abstract type key of |export|.
    4. Assert: |abstractTypeKey| is not an import declaration, by instantiation.
    5. If |guestResourceClasses|[|abstractTypeKey|] exists:
      1. Continue.
    6. Let |resourceType| be the component resource type |export| refers to.
    7. Let |arity| be the parameter count of the export of |exportDecls| whose name matches Constructor with a resource capture naming |export|, or 0 if there is none.
    8. Let |class| be create a guest resource class given |instance|, |exportDecls|, |resourceType|, JSName(|export|) and |arity|.
    9. Set |guestResourceClasses|[|abstractTypeKey|] to |class|.

To create the exports object given an instance record |instance| and a list of export declarations |exportDecls|:

  1. Let |exportsObject| be OrdinaryObjectCreate(null).
  2. For each |export| of |exportDecls|, in declaration order:
    1. If |export|.Name matches Constructor:
      1. Continue.
    2. If |export|.Name matches Member and JSName(|export|) is not in reserved class members:
      1. Continue.
    3. If |export|.Name matches Property:
      1. Perform define an accessor for a component function given |instance|, |exportsObject|, |export| and true.
      2. Continue.
    4. Let |key| be JSName(|export|).
    5. Match |export|.Sort:
      1. core module:
        1. Let |value| be a new Module whose [[Module]] is |export|.Module.
      2. type:
        1. If |export| does not declare a resource type:
          1. Continue.
        2. Let |abstractTypeKey| be the abstract type key of |export|.
        3. Let |value| be |instance|.[[GuestResourceClasses]][|abstractTypeKey|].
      3. func:
        1. Let |value| be create a JS function for a component function given |instance|, |export|.Func, |key| and false.
      4. value:
        1. Let |value| be run within a call given |instance|.[[HostResourceTypes]], |instance|.[[GuestResourceClasses]], and a new Abstract Closure that performs the following steps when called:
          1. Return ToJSValue(|export|.Value, |export|.Type).
      5. instance:
        1. Let |value| be ? create the exports object given |instance| and the exports of the exported instance.
      6. component:
        1. Let |value| be a new Component whose [[Component]] is |export|.Component.
    6. Perform CreateDataPropertyOrThrow(|exportsObject|, |key|, |value|).
  3. Perform SetIntegrityLevel(|exportsObject|, "frozen").
  4. Return |exportsObject|.

TODO: We need a JSName for members that hit the reserved class members list. It needs to concatenate the resource name with the method name somehow.

To create a JS function for a component function given an instance record |instance|, |componentFunc|, |name| and |takesSelf|:

  1. Let |paramOffset| be 1 if |takesSelf| is true, else 0.
  2. If |componentFunc|.Result is a result:
    1. Let |okType| be its ok payload type, or empty if it has none.
  3. Else:
    1. Let |okType| be |componentFunc|.Result, or empty if |componentFunc| has no result.
  4. Return a built-in function object with name |name| and length |componentFunc|.Params.length - |paramOffset|, whose behaviour, given a this value |thisValue| and JS arguments |args|, performs:
    1. Return ? run within a call given |instance|.[[HostResourceTypes]], |instance|.[[GuestResourceClasses]], and a new Abstract Closure that performs the following steps when called:
      1. Let |componentResult| be ? invoke a component function given |instance|, |componentFunc|, |takesSelf|, |thisValue| and |args|.
      2. If |okType| is empty:
        1. Return undefined.
      3. Return ToJSValue(|componentResult|, |okType|).

To define an accessor for a component function given an instance record |instance|, an object |target|, a function export |export| and a Boolean |enumerable|:

  1. Let |key| be JSName(|export|).
  2. Let |accessor| be the accessor capture of |export|.Name.
  3. Let |name| be the string-concatenation of |accessor|, " " and |key|.
  4. Let |takesSelf| be true if |export|.Name matches Member with scope "method", and false otherwise.
  5. Let |func| be create a JS function for a component function given |instance|, |export|.Func, |name| and |takesSelf|.
  6. If |accessor| is "get":
    1. Perform DefinePropertyOrThrow(|target|, |key|, PropertyDescriptor { [[Get]]: |func|, [[Set]]: undefined, [[Enumerable]]: |enumerable|, [[Configurable]]: true }).
  7. Else:
    1. Perform DefinePropertyOrThrow(|target|, |key|, PropertyDescriptor { [[Set]]: |func| }).

The "set" case defines a partial descriptor, so it only replaces the [[Set]] field of the accessor property the matching [get] export already defined. The "get "/"set " prefix on the function name follows how JS names accessor functions.

To invoke a component function given an instance record |instance|, |componentFunc|, a Boolean |takesSelf|, |thisValue| and a List of JS values |args|:

  1. Let |paramTypes| be |componentFunc|.Params.
  2. Let |resultType| be |componentFunc|.Result.
  3. Let |formalParamsOffset| be 1 if |takesSelf| is true, else 0.
  4. Let |formalParamsCount| be |paramTypes|.length - |formalParamsOffset|.
  5. If |resultType| is a result:
    1. Let |okType| be its ok payload type, or empty if it has none.
    2. Let |errorType| be its error payload type, or empty if it has none.
    3. Let |throwing| be true.
  6. Else:
    1. Let |okType| be |resultType|, or empty if |componentFunc| has no result.
    2. Let |throwing| be false.
  7. If Length(|args|) is less than |formalParamsCount|:
    1. Let |missingFormalArgCount| be |formalParamsCount| - Length(|args|).
    2. Let |missingFormalArgs| be a List of undefined repeated |missingFormalArgCount| times.
    3. Set |args| to |args| concatenated with |missingFormalArgs|.
  8. If |instance|.[[Store]].is_locked_down():
    1. Perform ? trap given |instance|.
  9. Let |call| be the current call.
  10. Let |lenders| be a new empty List.
  11. Let |onStart| be a new Abstract Closure with no parameters that performs the following steps when called:
    1. Set |call|.[[Lenders]] to |lenders|.
    2. Once the remaining steps complete, either normally or abruptly, set |call|.[[Lenders]] to empty.
    3. Let |values| be a new empty List.
    4. If |formalParamsOffset| is 1:
      1. Append ? ToComponentValue(|thisValue|, |paramTypes|[0]) to |values|.
    5. For each i in [0, |formalParamsCount|): append ? ToComponentValue(|args|[i], |paramTypes|[i + |formalParamsOffset|]) to |values|.
    6. Return |values|.
  12. Let |resolved| be false.
  13. Let |componentResult| be empty.
  14. Let |onResolve| be a new Abstract Closure with parameters (|results|) that performs the following steps when called:
    1. Assert: |results| is not None.
    2. Decrement the [[LendCount]] of every object in |lenders|.
    3. Set |resolved| to true.
    4. If |results| is not empty, set |componentResult| to |results|[0].
  15. Let |completion| be Completion(|instance|.[[Store]].invoke(|componentFunc|, |onStart|, |onResolve|)).
  16. If the call traps:
    1. If |resolved| is false, decrement the [[LendCount]] of every object in |lenders|.
    2. Perform ? trap given |instance|.
  17. If |completion| is an abrupt completion:
    1. Decrement the [[LendCount]] of every object in |lenders|.
    2. If the call has entered the guest:
      1. Invoke |instance|.[[Store]].lock_down().
    3. Return ? |completion|.
  18. Assert: |resolved| is true.
  19. If |throwing| is true and |componentResult| is result.error(|e|):
    1. Throw create a component error for |e| and |errorType|.
  20. If |okType| is empty:
    1. Return empty.
  21. If |throwing| is true:
    1. Return the result.ok payload of |componentResult|.
  22. Else:
    1. Return |componentResult|.

|componentFunc| is not async (see instantiation), so |onStart| and |onResolve| are called by canon_lift synchronously.

To create a component error for an optional component value |e| and component type |errorType|:

  1. If |errorType| is empty:
    1. Let |payload| be undefined.
  2. Else:
    1. Let |payload| be ToJSValue(|e|, |errorType|).
  3. Return a new ComponentError whose data is |payload| and whose message is implementation-defined.

WebAssembly ESM-integration

ESM-integration extends to components. The module loader branches on the layer field of the binary to decide whether the bytes decode as a module or a component, so a component can be loaded anywhere a module can be today.

Each component import has a module specifier given by JSName(|decl|).

Which binding of the resolved module the component receives depends on the import's type:

Import type JS equivalent Value
bare type, function, value import v from "JSName(decl)" the default export
instance import { a, b } from "JSName(decl)" one named import per export of the instance type whose name is an interfacename or matches Plain, named JSName of that export
core module, component import source M from "JSName(decl)" the module source, as a Module or Component

Reading the imports snapshots the resolved values, and so components cannot participate in cycles: a binding that is still uninitialized when the component is evaluated throws a ReferenceError. This matches how core modules work today with ESM-integration.

Each resolved value is handed to read an import and the resulting definitions are passed to instantiate a component.

A component's exports become the bindings of its module namespace object. There is one binding per JSName(|export|), holding what create the exports object puts under that name, and no default binding. Exports matching Property have no binding, since a binding cannot be an accessor.

Follow ups

  1. How to dynamically pass a union value? Statically passing a single case of the union works, but not dynamic choice.
  2. How to import multiple overloads of a function? Can we just use external-id?
  3. How to support class inheritance and casting?
  4. Do we support a reference equality protocol? ToJSValue creates a fresh resource object per lift, so two borrows of one component-defined resource are two JS objects that do not compare equal. Reps are opaque and reusable after a drop, so an identity map would need careful invalidation.
  5. Do we let a JS constructor supply its own brand check?
  6. Should a [get]/[set] import fall back to a Get/Set on the target when the property is not an accessor? That would let data properties, Proxy traps and module namespace bindings satisfy a property import.
  7. How does a component feature test an import?
  8. How does a component pass one of its own functions to a JS callback, e.g. add-event-listener?
  9. Async function types, top-level await, and async start functions.