This explainer describes how WebAssembly Components (hereafter 'components' and not web components) can be used from JS in supported runtimes.
See the reference for an in-depth walkthrough.
This is a draft and is not complete.
The examples below show a component's type, which lists its imports and exports and leaves out the implementation, since that's all JS can observe.
Let's start with a component that imports nothing:
(type (component
(export "greet"
(func (param "who" string) (result string))
)
))Given a component of the above type (compiled to the binary format), you can execute it with:
const { instance } = await WebAssembly.instantiate(bytes);
instance.exports.greet("world"); // "hello, world"The exports object of an instance holds one property per export and greet is an ordinary JS function.
Component names are kebab-case and JS function names are camelCase, so a function export named greet-loudly would be greetLoudly.
Arguments are coerced to their expected type, and if that fails a TypeError is thrown:
instance.exports.greet(42); // "hello, 42"
instance.exports.greet(Symbol("nobody")); // TypeErrorundefined is substituted for missing arguments, and extra arguments are ignored, just as in JS:
instance.exports.greet(); // "hello, undefined"Now a component that imports:
(type (component
(import "log"
(func (param "message" string))
)
(export "run" (func))
))The import log must be a JS callable object, and will be called with a JS String.
We can provide the console.log builtin as here:
const imports = { log: console.log };
const { instance } =
await WebAssembly.instantiate(bytes, imports);
instance.exports.run(); // logs "hello"Or provide a custom implementation:
const lines = [];
const log = (message) => { lines.push(message); };
const imports = { log };
const { instance } =
await WebAssembly.instantiate(bytes, imports);Related functions can be grouped into an instance, which maps to a nested JS object:
(type (component
(import "console"
(instance
(export "log" (func (param "message" string)))
(export "error" (func (param "message" string)))
)
)
(export "math"
(instance
(export "add"
(func (param "a" u32) (param "b" u32) (result u32))
)
)
)
))The console import is read from the imports object, and then log and error are read from it. This means the global console object can be passed directly:
const { instance } =
await WebAssembly.instantiate(bytes, { console });
instance.exports.math.add(1, 2); // 3Instances are often named with an interfacename such as wasi:cli/stdout@0.2.0, which is used as the JS property name verbatim.
Components and JS maintain separate type/value systems, so any value crossing the boundary needs a defined translation in both directions.
The following table describes how a component value is converted into a JS value.
| Component type | JS type | TypeScript |
|---|---|---|
bool |
Boolean | boolean |
s8-s32, u8-u32 |
Number, an exact integer | number |
s64, u64 |
BigInt | bigint |
f32, f64 |
Number, including NaN and infinities | number |
char |
String of exactly one Unicode scalar value | string |
string |
String, well formed | string |
list<sN, N?>, list<uN, N?>, list<fN, N?> |
IntNArray, UintNArray, FloatNArray |
IntNArray, UintNArray, FloatNArray |
list<T>, list<T, N> |
Array | T[] |
tuple<T, U> |
Array | [T, U] |
record { field-name: T, ... } |
null-prototype object | { fieldName: T, ... } |
flags "flag-a" "flag-b" |
null-prototype object of Booleans | { flagA: boolean, flagB: boolean } |
enum "case-a" "case-b" |
String, the case label verbatim | "case-a" | "case-b" |
option<T> (if not nested inside another option) |
undefined, or the payload |
T | undefined |
result<T, E> (if in return position of function) |
if E { thrown as a WebAssembly.ComponentError } else { T } |
T |
variant, option<T>, result<T, E> |
null-prototype object with discriminating kind field and optional value field |
{ kind: "a-b" } | { kind: "c-d", value: T } |
map<K, V> |
Map |
Map<K, V> |
own<R>, borrow<R> |
the original JS value for an imported resource type, an instance of its class for an exported one | R |
future<T>, stream<T>, error-context |
not yet specified | not yet specified |
Converting a JS value to a component value accepts all of the above, but also has additional coercions. See ToJSValue and ToComponentValue for detailed algorithms.
ESM-integration extends to components. The loader branches on the layer field of the binary, so a component loads anywhere a core module does today.
The original greeter example using ESM:
import { greet } from "./component.wasm"
greet("world"); // "hello, world"Each component import becomes a JS import, and its module specifier is the import's external-id.
The following component imports the default value from the "https://esm.unpkg.com/slugify@1.6.6" module.
(type (component
(import "slugify"
(external-id
"https://esm.unpkg.com/slugify@1.6.6")
(func (param "text" string) (result string))
)
;; maps slugify across a list
(export "slugify-list"
(func (param "list" (list string)) (result (list string)))
)
)) // component.wasm is instantiated with slugify=`https://esm.unpkg.com/slugify@1.6.6`.
import { slugifyList } from "./component.wasm";
// And the exported function can be used:
slugifyList(["some string", "another string"]); // ["some-string", "another-string"]If there is no external-id, the specifier is the import's JS name, and an import map can be used to specify the URL to resolve for the import:
<script type="importmap">
{
"imports": {
"slugify": "https://esm.unpkg.com/slugify@1.6.6"
}
}
</script>An instance import takes one named import per export instead of the default export, so (import "console" (instance ...)) behaves like import { log, error } from "console".
Component functions signal failure using a result<T, E> value:
- Exported component functions that return an error
resultthrow JS exceptions. - Imported JS functions that throw JS exceptions are captured as a
result.
An imported JS function that throws where the component asked for a plain return type results in a trap.
(type (component
(import "lookup"
(func (param "key" string) (result (result string (error string))))
)
(export "parse"
(func (param "text" string) (result (result u32 (error string))))
)
))parse tries to parse its text argument as an integer, and if that fails performs a fallible lookup.
const imports = {
lookup: (key) => { throw `no such key: ${key}`; },
};
const { instance } =
await WebAssembly.instantiate(bytes, imports);
instance.exports.parse("42"); // 42
try {
instance.exports.parse("$name");
} catch (e) {
e instanceof WebAssembly.ComponentError; // true
e.data; // "no such key: $name"
}In the second call, parsing fails and leads to a call to lookup which throws a JS exception. This is converted to a result and consumed by the component. The component then propagates it to the original JS caller as a thrown ComponentError carrying the original message.
In the case a component is executing and traps, the trap is surfaced as a WebAssembly.RuntimeError (as in core wasm), and then the component is locked down to prevent future execution. If an exported function from the component is invoked again, it immediately results in another trap.
import { buggyFunction, normalFunction } from "component.wasm"
// normalFunction doesn't trap
normalFunction();
try {
// Calling buggyFunction traps and locks down the component.
buggyFunction()
} catch (err) {
assert(err instanceof WebAssembly.RuntimeError);
try {
// Calling normalFunction again leads to a lockdown trap.
normalFunction();
} catch (err) {
assert(err instanceof WebAssembly.RuntimeError);
}
}Components can also accept JS values as resources. A resource type import is satisfied by passing a constructor function.
Whenever a JS value must be converted to a resource type, an instanceof check is performed against the imported constructor. If the constructor is a WebIDL interface object, a precise brand check is performed. An exported component resource class can't currently be imported.
Any imported function whose name is tagged [constructor], [method], or [static] is looked up on the imported constructor instead of the imports object:
| name | import lookup |
|---|---|
[constructor]R |
R |
[method]R.M |
R.prototype.M |
[static]R.S |
R.S |
The above allows most JS classes to be imported as a resource by just passing the constructor function:
(type (component
(import "element"
(type $element (sub resource))
)
(import "[method]element.query-selector"
(func
(param "self" (borrow $element))
(param "selectors" string)
(result (option (own $element)))
)
)
(import "[method]element.get-attribute"
(func
(param "self" (borrow $element))
(param "name" string)
(result (option string))
)
)
(export "find"
(func
(param "root" (borrow $element))
(param "selectors" string)
(result (option string))
)
)
))const imports = { Element };
const { instance } =
await WebAssembly.instantiate(bytes, imports);
instance.exports.find(document.body, "h1"); // "page-title" or undefinedComponent plainnames as used in imports/exports are converted to idiomatic JS names (rules here). Type names are converted to pascal case, and everything else is converted to camel case. This allows the component imports of element and get-attribute to be satisfied with Element and getAttribute respectively.
The example above still needs someone to write { Element }. A component can skip that and take its imports straight from the global object by importing wasm:js/global:
(type (component
(import "wasm:js/global"
(instance $g
(export "btoa"
(func (param "data" string) (result string))
)
(export "element" (type $element (sub resource)))
(export "[method]element.get-attribute"
(func
(param "self" (borrow $element))
(param "name" string)
(result (option string))
)
)
)
)
(alias export $g "element" (type $el))
(export "encode-id"
(func
(param "el" (borrow $el))
(result (option string))
)
)
))const { instance } =
await WebAssembly.instantiate(bytes, {}, { builtins: ["js/global"] });
instance.exports.encodeId(document.body);Importing from wasm:js/global is equivalent to an imports object with: { "wasm:js/global": globalThis }. The normal rules for reading from the imports object still apply.
ESM-integration defaults to enabling js/global in the compile options (the wasm: prefix is implicit) which allows a component to import and use web APIs without any glue code:
<script type="module">
import { encodeId } from "./component.wasm";
encodeId(document.body);
</script>A resource type exported from a component becomes a JS class:
(type (component
(export "counter" (type $counter (sub resource)))
(export "[constructor]counter"
(func (result (own $counter)))
)
(export "[method]counter.increment-once"
(func
(param "self" (borrow $counter))
(result u32)
)
)
))const { instance } = await WebAssembly.instantiate(bytes);
const { Counter } = instance.exports;
let c = new Counter();
c.incrementOnce(); // 1
c.incrementOnce(); // 2As in the importing a resource case above, component names are converted to JS names. This allows an export of counter to become a JS class named Counter, and increment-once to become incrementOnce.
The following have no binding yet:
- Component model async features such as
asyncfunctions,future,stream. error-context, which would better integrateresultwith JS'sErrorand offer backtrace support.
Everything else we know to be open is collected in the reference's follow ups.