How does a Wasm module from Rust call a module from Go, when only numbers can cross the border? The Component Model is a standard that wraps a Wasm module into a component: a module that states clearly what it needs and what it provides, with rich data types like list<u8>, string, record and result, not only numbers.
Mrs. Sri once ordered photo editing from different craftsmen: one from a nearby town, one from a big city, one from the other side of the country. Each used to take orders his own way: one wanted a shelf number and a photo count, another wanted the photos left in a particular box. Every pairing needed its own agreement. Now there is a standard order form that says what is handed over and what comes back, plus fixed rules for packing the goods. Any craftsman who can read the form can start working straight away. The form is WIT, the packing rules are the canonical ABI, and the craftsmen are components written in Rust, Go, C or JavaScript.
Core modules and components
Every .wasm in the earlier lessons is a core module. Only numbers cross its boundary: i32, i64, f32, f64, plus references. Text and photos have to be written into linear memory and passed as a pointer and a length, and every pair of languages needs its own glue code (wasm-bindgen for Rust and JS, syscall/js for Go). If a Rust module is to be used by a Go module, both sides have to agree by hand on the memory layout. The idea that solves this used to be called interface types; it is now part of the Component Model.
| Core module | Component | |
|---|---|---|
| What crosses the boundary | i32, i64, f32, f64, references |
also string, list, record, variant, option, result, resource |
| Memory | can be exported and shared | hidden inside the component, not shared |
| Contract | a list of functions with numeric types | WIT: interfaces and worlds |
| Bytes 5 to 8 | 01 00 00 00 |
0d 00 01 00 |
A component is a wrapper: inside it are one or more core modules, plus types written in WIT and the instructions that turn rich types into numbers. Browsers and Node only know core modules. Chromium 147 rejects a component with CompileError: WebAssembly.compile(): expected version 01 00 00 00, found 0d 00 01 00 @+4, WebKit 26.4 with CompileError: WebAssembly.Module doesn't parse at byte 0: unexpected version number 65549 expected 1.
WIT: the contract for Mrs. Sri's photo tool
WIT (Wasm Interface Type) is the language you write the contract in. This is wit/photolab.wit:
package homestay:[email protected];
/// Room photos of Mist Homestay: RGBA, 4 bytes per pixel.
interface photo {
record size {
width: u32,
height: u32,
}
/// gray = (r × 77 + g × 150 + b × 29) >> 8, alpha unchanged.
grayscale: func(pixels: list<u8>) -> list<u8>;
/// Area-average thumbnail. Fails when the byte count does not match the size.
thumbnail: func(pixels: list<u8>, source: size, target: size) -> result<list<u8>, string>;
}
world photolab {
export photo;
}
package homestay:[email protected]gives a name and a version, in the formnamespace:name@version.interface photogroups functions and types.record sizeis like an object with fixed fields:widthandheight.list<u8>is a sequence of bytes.result<list<u8>, string>means: success with bytes, or failure with a text message.world photolabstates what this component exports and imports. This one only exportsphotoand needs nothing from outside.- WIT names use kebab-case (
stay-price). Generators turn them into each language's style:stay_pricein Rust,stayPricein JS. - The other types:
bool,s8tos64,u8tou64,f32,f64,char,string,option<T>,tuple,variant,enum,flagsandresource.
Building the component from Rust
The project is a plain Rust crate (photolab-component) with crate-type = ["cdylib"] and one dependency, wit-bindgen = "0.62". The WIT file sits in the wit/ folder.
wit_bindgen::generate!({ world: "photolab", path: "wit" });
use exports::homestay::mist::photo::{Guest, Size};
struct Photolab;
impl Guest for Photolab {
fn grayscale(mut pixels: Vec<u8>) -> Vec<u8> {
for p in pixels.chunks_exact_mut(4) {
let gray = ((p[0] as u32 * 77 + p[1] as u32 * 150 + p[2] as u32 * 29) >> 8) as u8;
(p[0], p[1], p[2]) = (gray, gray, gray);
}
pixels
}
fn thumbnail(pixels: Vec<u8>, source: Size, target: Size) -> Result<Vec<u8>, String> {
let needed = (source.width * source.height * 4) as usize;
if pixels.len() != needed {
return Err(format!("pixels must be {} bytes, got {}", needed, pixels.len()));
}
if target.width == 0 || target.height == 0 || target.width > source.width || target.height > source.height {
return Err(format!("target size {} × {} cannot come from {} × {}", target.width, target.height, source.width, source.height));
}
Ok(area_average(&pixels, source, target))
}
}
export!(Photolab);
generate!reads the WIT and creates theGuesttrait. You only fill in the functions with ordinary Rust types:list<u8>becomesVec<u8>,stringbecomesString,resultbecomesResult.export!connects your implementation to the component's exports.area_averageholds exactly the same loop asresize_areain the Image Processing lesson, so it is not written out again here.
$ cargo build --release --target wasm32-wasip2
$ wasm-tools component wit target/wasm32-wasip2/release/photolab_component.wasm
world root {
import wasi:io/[email protected];
import wasi:cli/[email protected];
... (14 wasi imports, cut short)
export homestay:mist/[email protected];
}
- The
wasm32-wasip2target (rustc 1.99.0) produces a component directly: 50,511 bytes. Its WASI imports come from Rust's std, which is ready to write to stderr and exit the program. - Without WASI:
cargo build --target wasm32-unknown-unknown, thenwasm-tools component new photolab_component.wasm -o photolab.wasm(wasm-tools 1.261.0). The result is 21,924 bytes and its WIT is onlyexport homestay:mist/[email protected]. Theno_stdversion the Lab uses: 8,374 bytes. cargo componentused to be the recommended way. The Component Model book now says that tool is being deprecated, becausecargo buildwith thewasm32-wasip2target and wit-bindgen is enough.
Canonical ABI: from list to numbers
Inside a component, the function is still a core Wasm function that only knows numbers. The canonical ABI is the fixed set of rules for "lowering" rich values into numbers and bytes in linear memory, and "lifting" the results back: lists and strings become a pointer plus a length, records are split into their fields, a result becomes a tag byte plus its contents. Because the rules are the same for every language, Rust and Go can call each other with no extra agreement. These are the exports of the core module inside photolab.wasm:
memory
homestay:mist/[email protected]#grayscale (i32, i32) -> i32
homestay:mist/[email protected]#thumbnail (i32, i32, i32, i32, i32, i32) -> i32
cabi_realloc (i32, i32, i32, i32) -> i32
cabi_post_homestay:mist/[email protected]#grayscale (i32)
In WIT, grayscale takes a list<u8>, but its core function receives two i32 numbers, a pointer and a length, and the result is one i32: the address of a "return area" holding the result's pointer and length. This is the order of one grayscale([200, 120, 40, 255]) call, with the numbers from the Lab:
| Step | What happens |
|---|---|
| 1 | cabi_realloc(0, 0, 1, 4) gives 1114112: room for 4 bytes in the component's memory |
| 2 | the glue copies the 4 bytes to address 1114112 |
| 3 | homestay:mist/[email protected]#grayscale(1114112, 4) returns 1048912 |
| 4 | read 8 bytes at 1048912: ptr 1114112, len 4 |
| 5 | copy 4 bytes out: [135, 135, 135, 255] |
| 6 | cabi_post_...#grayscale(1048912): the component frees its result |
record sizedoes not go through memory: it is split into twou32s. That is whythumbnailhas 6i32parameters. If the flattened parameters number more than 16, all of them go through memory instead.result<list<u8>, string>in the return area: the first byte is 0 (ok) or 1 (err), then the pointer and length at bytes 4 and 8.wasm-tools print photolab.wasmshows what ties it together:(canon lift (core func ...#grayscale) (memory $memory) (realloc $cabi_realloc) (post-return ...)).- Each component has its own memory, so the data is always copied: 3,840,000 photo bytes in and 3,840,000 bytes out on every call.
Running it: Wasmtime and jco
$ wasmtime run --invoke 'grayscale([200, 120, 40, 255])' photolab.wasm
[135, 135, 135, 255]
$ wasmtime run --invoke 'thumbnail([1, 2, 3, 4], {width: 1200, height: 800}, {width: 400, height: 267})' photolab.wasm
err("pixels must be 3840000 bytes, got 4")
Wasmtime 49.0.2 runs components directly, with no JavaScript. In browsers and Node, use jco (1.37.0) from the Bytecode Alliance. jco transpile photolab.wasm -o photolab turns the no_std component above into a plain core module (photolab.core.wasm, 7,139 bytes) plus a JavaScript ES module (photolab.js, 98.2 KiB before minifying) that holds the canonical ABI described above:
import { photo } from './photolab/photolab.js';
photo.grayscale(new Uint8Array([200, 120, 40, 255])); // Uint8Array [135, 135, 135, 255]
try {
photo.thumbnail(new Uint8Array(16), { width: 1200, height: 800 }, { width: 400, height: 267 });
} catch (e) {
console.log(e.message); // pixels must be 3840000 bytes, got 16
}
- A failed
resultis thrown as aComponentError, with its value ine.payload. - This transpiled output runs in Node 22, Chromium 147 and WebKit 26.4. No browser runs components directly; jco is the bridge.
- If the component imports WASI, jco points those imports at
@bytecodealliance/preview2-shim(0.28.0). In the browser, that shim provides clocks, random numbers, stdout to the console, and outgoing HTTP throughfetch. Files, stdin and sockets need an adapter from your app.
📌 WASI 0.2, 0.3, and runtime support
- WASI 0.2 and 0.3 are built from components.
gray-imgfrom the WASI lesson, built forwasm32-wasip2, imports 17 interfaces (wasi:io,wasi:clocks,wasi:cli,wasi:filesystem, version 0.2.12) and exportswasi:cli/[email protected]. - Key worlds:
wasi:cli/commandfor CLI programs,wasi:http/proxyin WASI 0.2 andwasi:http/service(plusmiddleware) in WASI 0.3 for HTTP servers. - On the W3C WebAssembly CG proposals list the Component Model is still Phase 1, but its WASI releases (0.2.0, 0.3.0, 0.3.1) are kept stable for use outside the browser.
- Wasmtime supports it fully. Spin (now under Akamai) and wasmCloud build their platforms on components. WasmEdge only has the loader and validator so far (0.17.0). WAMR does not yet. Browsers and Node: through jco.
⚠️ Components that get refused, copied, or misnamed
- Loading a component with
WebAssembly.compile. Rejected at byte 4:expected version 01 00 00 00, found 0d 00 01 00. Transpile it with jco first. - Expecting shared memory. Components do not share memory; every call copies its data. For big photos, that cost is real.
- Following old tutorials.
cargo componentis being deprecated, and the wit-bindgen API changes between versions (0.25 against 0.62). Check the version inCargo.toml. - Mixing up names. WIT
stay-price, Ruststay_price, JSstayPrice. The name you type in--invokefollows the WIT.
TL;DR: The Component Model wraps core modules into components with a WIT contract: package, interface, world, and rich types (list, string, record, result, option, variant, resource), so modules from different languages can call each other without laying out memory by hand. The canonical ABI is the fixed rule set: a list<u8> becomes two i32s (pointer and length) copied in through cabi_realloc, the result is read from a return area and then freed with cabi_post_*; records are split into their fields. From Rust: wit-bindgen 0.62 with cargo build --target wasm32-wasip2 (50,511 bytes, WASI imports included), or wasm32-unknown-unknown plus wasm-tools component new (21,924 bytes). Inspect it with wasm-tools component wit. Wasmtime runs it directly (--invoke); browsers and Node don't know components (expected version 01 00 00 00), so jco 1.37.0 turns them into a core module plus JS. WASI 0.2 and 0.3 are built on components: wasi:cli/command, wasi:http/proxy, wasi:http/service.
⚡ Core modules only know numbers
Meaning: Only i32, i64, f32, f64 and references cross a core module's boundary. The Component Model wraps it into a component with a WIT contract and rich types (string, list, record, result), so modules from different languages can call each other without laying out memory by hand.
⚡ WIT: the contract
Write:
interface photo {
record size {
width: u32,
height: u32,
}
grayscale: func(pixels: list<u8>) -> list<u8>;
}
world photolab {
export photo;
}
Meaning: An interface groups functions and types, a record is an object with fixed fields, and a world states what the component exports and imports.
⚡ Canonical ABI: a list becomes two numbers
Guess first: in WIT, grayscale takes one list<u8>. What does its core function take?
Two i32s: a pointer and a length. Its result is one i32, the address of a return area holding the result's pointer and length.
Meaning: The canonical ABI rules are the same for every language: lists and strings are copied in through cabi_realloc, records are split into their fields, and the result is freed with cabi_post_*.
⚡ Browsers don't know components yet
Meaning: WebAssembly.compile rejects a component at byte 4: expected version 01 00 00 00, found 0d 00 01 00. Wasmtime runs it directly, and for browsers and Node, jco turns it into a core module plus JavaScript.