A public API declared once, in Rust, written as every binding its users need: an idiomatic TypeScript facade over
the crate's wasm-bindgen exports, React hooks, a web component's attributes and React Native's names over it, a Python
API, their references in Markdown, and any other binding a plugin adds. Change the Rust, run wasm-facade generate, and
every binding follows; wasm-facade check in CI fails on any drift.
Site, with a live demo: https://ignf.github.io/wasm-facade/
orval reads an OpenAPI document and writes a typed client and TanStack Query hooks: the server's contract is written once and the client never drifts. wasm-facade does the same for a library compiled to WebAssembly:
| orval | wasm-facade | |
|---|---|---|
| Source of truth | openapi.json |
the Rust crate, annotated |
| Intermediate | the OpenAPI document | api.json (data/api.schema.json, versioned) |
| Generated | typed client, React Query hooks, mocks | TypeScript facade over wasm-bindgen, React hooks, web component, React Native, Python, references, plugins |
| Transport | HTTP | wasm-bindgen's exports, typed arrays passed as they are |
wasm-bindgen already writes .d.ts for what it exports. That surface is the engine's, not the user's: numeric enums,
positional arguments, Function, free() to remember. wasm-facade writes the layer on top that a user calls (unions of
strings, options objects with defaults, on(event, listener), promises, converters from the user's types) without
anyone maintaining it by hand.
npm install -D wasm-facade@0.3.0 # `npx wasm-facade generate` (or bun, pnpm, yarn)The generator runs on Node 20+ and on Bun. The package brings the extractor of its own version: prebuilt for macOS,
Linux (x64, arm64) and Windows (x64) in the package itself (bin/<os>-<cpu>), else installed once by
cargo install wasm-facade --version <its version> in ~/.cache/wasm-facade (WASM_FACADE_CACHE) and reused. Nothing
else to install, here or in CI: extracting reads the workspace with cargo metadata, --no-extract needs no Rust.
-
Declare the public API in Rust with an inert attribute,
#[cfg_attr(wasm_facade, api(…))].wasm_facadeis a cfg never set: nothing is compiled, no proc-macro, no dependency, no build time. Tell rustc the cfg is known:[lints.rust] unexpected_cfgs = { level = "warn", check-cfg = ["cfg(wasm_facade)"] }
-
Add
wasm-facade.tomlat the repository's root. An empty file works; a conventional one:wasm = "../pkg/my_crate.js" # the wasm-bindgen module, as the facade imports it converters = "src/converters.ts" # the project's converters, if any [targets.typescript] # out = "src/api.ts" [targets.react] # out = "src/hooks.ts", facade = "src/api.ts" [targets.reference] # out = "docs/api.md", title = "API" [targets.python] # out = "python/_api.py"
The declarations may live in any member of the Cargo workspace: every member is read (or
[extract] members), so moving code between crates or folders changes nothing generated. -
Register converters (optional): a module whose named exports take what the facade's user gives and return what the wasm module takes (
pixels(image: ImageData): Uint8Array). A declaration names one by its name. -
Run
wasm-facade generatein the build (below), or after changing the declarations andwasm-facade checkin the lint and CI when the outputs are committed.
api.json is the contract: committed, its diff shows an API change in review. What is generated from it need not be:
# What wasm-facade.toml's targets write (here the defaults)
src/api.ts
src/hooks.ts
docs/api.md{
"scripts": {
"postinstall": "wasm-facade generate --no-extract",
"build": "wasm-facade generate && tsc",
"dev": "wasm-facade generate --watch"
}
}generateis incremental: when the API,wasm-facade.toml, the plugins (and the local modules they import), itsinputsand wasm-facade's version are those of its last run, and the files it wrote are still as written, it writes nothing and runs no formatter. Its stamp is kept incache(node_modules/.cache/wasm-facade).--no-extractreads the committedapi.jsonas it is, without the extractor: after an install, the editor sees the types without Rust being built.--watchgenerates again whenever a Rust file, the configuration or a plugin changes.--forceruns every target though nothing changed.
check is then needed only by a repository that commits its outputs, and in CI after the build, where it fails if
the committed api.json is not what the Rust declares.
#[cfg_attr(wasm_facade, api(key = "text", key = 3, flag))] on a struct, an enum, an exported pub fn or an exported
impl block (and on their fields and methods). Keys are free: the generic patterns read those below, a project's
own patterns read theirs.
| Rust | Keys | TypeScript |
|---|---|---|
#[wasm_bindgen] enum Edge { Clamp, Wrap } |
union (rename_all = "none" keeps the names) |
type Edge = 'clamp' | 'wrap', mapped to the wasm enum |
struct BlurOptions { radius: f64 } |
options; on a field default = "2" (a TypeScript literal) |
interface BlurOptions, BlurOptionsInit, defaultBlurOptions |
| an options struct or one of its fields | emits = "change" |
the class's setter of that option emits change once the value is kept and the call made: { radius: 3 }, typed in BlurEvents, heard by on |
#[wasm_bindgen] pub fn histogram(…) |
function |
histogram(…) |
#[wasm_bindgen] impl Blur { … } |
class, options = "BlurOptions" |
class Blur: new Blur({ radius }) (the constructor's parameters taken from the options by name), its methods, free(); the options kept by the facade, each a property read from that copy (never from wasm; objects and arrays frozen, typed arrays copied), its wasm-bindgen setter keeping the value then making the call |
the impl block of a class |
deps = "map: GeoMap, engine: Engine" (names and the project's TypeScript types, in order) |
new Layer(map, engine, options): its dependencies taken first, typed and required, kept in protected readonly fields (below) |
#[wasm_bindgen(getter)] / (setter) |
(wasm-bindgen's) | get radius() / set radius(v), or getRadius() / setRadius(v) with accessors = "methods" (below) |
pub async fn |
returns Promise<…> |
|
a js_sys::Function parameter |
callback = "(row: number) => boolean" |
that parameter typed so |
| a method taking a listener | event = "progress", payload = "number" |
on('progress', listener), returning what stops it |
a method (key, name, value) |
keyed = "Levels" (an options struct, its defaults; or a record), emits |
setLevelsProperty(key, name, value), returning the class, and getLevelsProperty(key, name): each key's properties held by the facade (the value kept, then the call made), typed by the struct's fields; emits gives { key, name, value } |
| a function or a method of many parameters | takes = "Planes, …" (records) |
the parameters named as the record's fields taken as one object of it, interleave(planes); a record of typed arrays also gets planesBuffers(planes), its buffers once each, to transfer it |
a function or a method returning a JsValue |
returns = "Stats" (a record) |
typed as the record and checked as it comes back: checkedStats(value), a TypeError naming the field that is not as declared (Stats.mean is string, number expected) |
| a parameter given through a converter | convert = "image=pixels, …" |
the parameter typed as the converter's parameter |
| a result through a converter | result = "toImage" |
typed as the converter's result |
#[cfg(wasm_facade)] trait PreviewHost { … } |
host = "Preview"; on a method animation, export, ts, py; on a parameter ts, py |
abstract class PreviewApi: the methods of a class written by hand (below) |
struct Snapshot { radius: f64 }, struct Size(u32, u32) |
record; on a field ts, py, a tuple's label |
interface Snapshot { readonly radius: number }, type Size = [width: number, height: number]; a TypedDict, a tuple in Python |
enum PreviewEvent { Shown(Snapshot), Cleared } |
events, host = "Preview"; on a variant name, ts, py |
interface PreviewEvents { shown: Snapshot; cleared: undefined }, the host's on and emit |
struct ViewSettings { min_zoom: f64 } |
settings; on a field call = "setZoomRange", getter, store, spread, convert, default, emits (or on the struct) |
each field a setting of a host class (setMinZoom, getMinZoom): read by the web-component, react-native and python targets and by plugins |
Names: snake_case becomes camelCase; exported names are wasm-bindgen's js_name. A class's documentation is its
impl block's doc comment; every doc comment becomes TSDoc and reference text. Types: numbers, bool, String,
slices and Vecs of numbers (typed arrays), Option, Result<_, JsValue>, the declared enums, and the project's
own types in [types].
| Key | Default | |
|---|---|---|
extractor |
the package's own | the command running the extractor, to override it (["cargo", "run", "-q", "-p", "wasm-facade", "--"] from sources) |
api |
wasm-facade/api.json |
where the API is written ([extract] out wins) |
wasm |
./pkg/index.js |
the wasm-bindgen module, as the facade imports it |
converters |
none | the converters' module, from the root |
[extract] cfg, attribute |
wasm_facade, api |
the attribute's names |
[extract] exported, call_keys |
none, ["call"] |
the classes whose exported methods declarations may name as calls, and the keys naming them (resolved and checked: a call missing or exported twice is an error) |
[extract] export_attribute, export_name |
wasm_bindgen, js_name |
how an export is recognized and named |
[extract] members |
"all" |
the members read, their folders |
[types] |
the project's Rust types in TypeScript (Rgba = "[number, number, number, number]") |
|
accessors |
"properties" |
how a class's properties are written: get radius() / set radius(v), or "methods": getRadius() / setRadius(v) |
[imports] |
the project's TypeScript types the generated code names (a class's deps), by name: their module, a file from the root with its extension (GeoMap = "src/map.ts") or a package as written (Engine = "@my/engine"); imported as types where used |
|
inputs |
none | files the plugins read besides their modules, in generate's stamp |
cache |
node_modules/.cache/wasm-facade |
where generate keeps its stamp |
[format] |
none | a formatter per extension, the text on its stdin (".ts" = ["biome", "format", "--stdin-file-path={name}"]) |
[targets.<name>] |
a target to run: built in (below) or plugin = "path.ts" (or a package); enabled = false turns one off; the other keys are its options |
The TypeScript facade is the one binding that calls the wasm module: React's hooks import it, and the web component's
attributes and React Native's names are for the hand-written element and bridge over it. Python is a sibling, read
from the same api.json:
| Target | Writes (default out) |
|
|---|---|---|
typescript |
the facade (src/api.ts) |
unions, options with defaults, functions, classes, events, converters, records, hosts' abstract classes and their events |
react |
hooks over the facade (src/hooks.ts; facade) |
useBlur(options), useBlurEvent(blur, type, listener) |
web-component |
a custom element's attributes and events (src/element.api.ts; from, the structs, default the settings; host, prefix) |
ATTRIBUTES ('max-pitch' → maxPitch, a number, a flag or text), attributeValue(name, text), EVENTS (shown → 'preview-shown') |
react-native |
the names a bridge exposes (src/native.api.ts) |
each class's methods, properties and events, the functions, the settings' setters and getters |
python |
the Python API (python/_api.py; title, types, functions) |
Literal unions, TypedDict options with their defaults and keyword functions, a mixin per class, settings struct and the functions |
reference |
the reference (docs/api.md; title) |
|
python-reference |
the Python reference (docs/python.md; title, types) |
The targets reading settings take call_key, the key naming their call (call by default).
A class's properties (its options kept by the facade, wasm-bindgen's getters and setters) are accessors by default.
A project whose style is a pair of methods says so once, in wasm-facade.toml:
accessors = "methods"// accessors = "properties" (the default) // accessors = "methods"
blur.radius = 3; blur.setRadius(3);
blur.radius; // 3 blur.getRadius(); // 3The behaviour is the same: read from the facade's copy, the setter keeping the value, making the wasm call, then
emitting its event. Properties by key stay setXProperty / getXProperty. React Native lists the pairs among the
methods (BLUR_PROPERTIES empty); the reference names them; Python keeps properties (blur.radius = 3, its idiom),
its transport called by the facade's names (_call("setRadius", 3) in place of _set("radius", 3)). The web
component's attributes do not change. A method already named as an accessor would be (getRadius) is an error.
A class that needs objects of the project (a map, an engine) declares them on its impl block, the types those the
TypeScript side names, and where they come from in [imports]:
#[cfg_attr(wasm_facade, api(class, options = "LayerOptions", deps = "map: GeoMap, engine: Engine"))]
#[wasm_bindgen]
impl Layer {
#[wasm_bindgen(constructor)]
pub fn new(engine: &Engine, opacity: f64) -> Layer { … } // a parameter named as a dependency is given it
}[imports]
GeoMap = "src/map.ts"
Engine = "@my/engine"// api.ts, generated
import type { GeoMap } from './map.ts';
import type { Engine } from '@my/engine';
export class Layer {
protected readonly map: GeoMap;
protected readonly engine: Engine;
constructor(map: GeoMap, engine: Engine, options: LayerOptionsInit = {}) { this.map = map; this.engine = engine; … }
}
// labels.ts, by hand: a subclass uses them
export class Labels extends Layer { redraw() { this.map.requestRender(); } }Dependencies arrive in the constructor, typed and required, never set afterwards; protected readonly and not
#private, so that a hand-written subclass reads them. The extractor reads deps into the class's deps in
api.json (a name and a type each, in their order; a text that is not name: Type, … an error); React's
useLayer(map, engine, options) takes them first and makes the instance again when one changes; the references list
them. Python's mixins and React Native's names construct nothing: they do not change.
Some methods are written by hand in TypeScript, and stay so: what loads (fetch, workers), what animates
(requestAnimationFrame), what waits for the GPU. Their surface (names, parameters, results, documentation) is still
declared once, in Rust, in a trait that is never compiled: its types need not exist in Rust, its attributes are bare.
/// A blur's preview: an image on a canvas, blurred as it is shown
#[cfg(wasm_facade)]
#[api(host = "Preview")]
pub trait PreviewHost {
/// Shows an image, blurred by the options given
async fn show(#[api(ts = "ImageData", py = "Any")] image: Image, options: Option<BlurOptions>);
/// Moves the blur's radius over `duration` milliseconds
#[api(animation)]
fn fade_to(radius: f64, duration: Option<f64>);
}The facade declares them in an abstract class, and the hand-written class extends it: tsc fails where it does not follow the declarations.
// api.ts, generated
export abstract class PreviewApi {
abstract show(image: ImageData, options?: BlurOptionsInit): Promise<void>;
/** … Resolved once the animation ends */
abstract fadeTo(radius: number, duration?: number): Promise<void>;
}
// preview.ts, by hand
export class Preview extends PreviewApi { … }Every other binding takes them as it takes the rest: Python's PreviewApi mixin, React Native's PREVIEW_METHODS, the
references. Trailing Option parameters may be left out; animation returns a promise resolved once it ends.
What the methods return and what the host tells are declared beside it, in Rust never compiled too:
- Records, the structured values a method returns (
api(record)): an interface of read-only fields, anOptionone optional; a tuple struct a labelled tuple (Size(#[api(label = "width")] u32, …)). ATypedDictor atuplein Python. - Events (
api(events, host = "Preview")on an enum): each variant an event, named by the variant in lowercase (orname), its payload its one field. The host's base class gets a typedon(type, listener)and a protectedemit(type, event)(a listener that throws is reported, the others still called); Python anon, React Native itsPREVIEW_EVENTS, the web component the DOM names it dispatches (EVENTS:preview-shown).
The python target writes the API in Python's terms (snake_case, typed keywords, docstrings), and no runtime: each
method hands its call, by the facade's name, to the class inheriting the mixin. That class gives the transport
(_call, _get, _set, _on):
class Blur(Widget, BlurApi): # Widget: the project's, carrying each call to the TypeScript facade in a notebook
...A library drawing in a browser (a map in Jupyter) carries the calls to its TypeScript facade through a widget; a library computing could carry them to native code. The API generated is the same.
A target is a module whose default export is a Target:
import { classes, type Target } from 'wasm-facade';
const target: Target = {
name: 'my-binding',
outputs: ({ api, config, options }) => [
{ path: 'src/names.api.ts', text: classes(api).map((c) => `export const ${c.name}Name = '${c.name}';`).join('\n') },
],
command: (context, check) => ({ run: ['my-script', ...(check ? ['--check'] : [])] }), // optional, after the writes
};
export default target;plugin names a module of the repository ("scripts/my-binding.ts", from the root) or a package it depends on
("wasm-facade-plugin-foo", or one of its exports), resolved from the root as an import is: a plugin is written in the
repository that uses it, or published and shared.
A plugin may be written in TypeScript: Bun and Node 23.6+ load it as it is; on Node 20 to 23.5, run the CLI with
node --experimental-strip-types (22.6+) or through a loader (npx tsx node_modules/wasm-facade/dist/cli.js generate),
or write the plugin in JavaScript.
outputs returns whole files. A target reads the API through the patterns (classes, functions, options,
unions, converters, settings from wasm-facade) or its own; no target imports another. The file it reads,
api.json, is described by data/api.schema.json.
A generated file is never edited, so a repository can leave it out of git (*.api.ts in .gitignore) and a reader
knows which lines are whose. Where generated code meets hand-written code, the hand-written side extends it:
-
Class members: the generated methods go in a base class the hand-written class extends. In TypeScript an abstract class, declaring the protected members its methods need; in Python a mixin.
// map.api.ts, generated export abstract class MapApi { protected abstract readonly engine: Engine; protected abstract requestRender(): void; /** The map's lowest zoom */ setMinZoom(zoom: number): this { this.engine.set_min_zoom(zoom); this.requestRender(); return this; } } // map.ts, by hand export class Map extends MapApi { protected readonly engine = new Engine(); protected requestRender() { … } }
-
Option fields: the generated fields go in an interface the hand-written one extends (
interface MapOptions extends MapSettings { container: HTMLElement }). -
Table entries: the generated entries are exported constants the hand-written table spreads (
{ ...LIVE_SETTINGS, container: … },[...SETTING_ATTRIBUTES, 'src']).
A region of a hand-written file is still supported, for a file that cannot be split: an output with region: 'name'
replaces the lines between // <api:name> and // </api:name> (# in Python). Such a file mixes both and stays in
git.
examples/filters is a repository of its own using wasm-facade: an image-filters crate (filters/src/lib.rs, every
pattern above but the settings), its wasm-facade.toml (every built-in target), its converters, its hand-written
Preview (src/preview.ts, extending the generated PreviewApi: its methods, its Snapshot record, its events), and
what wasm-facade writes from them, committed so
that check shows any drift:
src/api.ts(the facade),src/hooks.ts(useBlur,useBlurEvent),src/element.api.ts,src/native.api.ts;python/filters/_api.py, over a recording transport inpython/filters/__init__.py, run and typed strictly (pyright) in CI;docs/api.md,docs/python.md.
pkg/filters.d.ts stands in for wasm-bindgen's output, so that the facade is type-checked without building the wasm
module.
wasm-facade: what it writes is the facade over a wasm-bindgen module. The crate (the extractor) and the npm package
(the generator, the extractor's binaries in it) share their version.
MIT, see LICENSE.