wasm_refgen
This package contains a macro that eases the use of Rust-exported wasm-bindgen types in JS settings. Specifically, it generates boilerplate that upcasts from a duck-typed JS reference to a concrete Rust type implementing that interface. The main caveat is that it assumes that cloning is cheap on the struct in question since you're going to clone to take ownership of the type on the Rust side.
Motivation
wasm-bindgen makes working with Wasm code in JS environments viable, but also comes with a few
sharp edges. Some of these include:
- Consuming Rust-exported types if passed by ownership.
- Not being able to use generics in Rust-exported types.
- No references to Rust-exported types in
extern "C"interfaces. - Disallowing passing references to Rust-exported types in
Vecs.
The most common workaround for these is to pass around JsValues or js_sys::Arrays plus
custom TypeScript strings (which are not checked against the actual types used),
and parse these general types manually rather than bindgen doing the glue for you,
rather than fiddling with unchecked_into or dyn_into yourself.
It would be convenient to have some way to use Rust types on the Rust side, and
have wasm-bindgen automatically generate reasonable types on the TS side.
Dependencies
Add both crates to your Cargo.toml:
[]
= "0.2"
= "0.2"
Example
use ;
use *;
use wasm_refgen;
It is worth noting that the #[wasm_refgen(...)] line MUST be placed above #[wasm_bindgen(...)].
Simple use is straightforward:
// Rust
// JS
const foo = ;
wasm-bindgen only allows generics for types that are JsCast,
which JsFoo is thanks to the glue code generated by this macro.
This is so that it can clone the data safely from JS when going over
the boundary. The JS-representation of WasmFoo is a lightweight
object with a number "pointer" to Wasm memory, so cloning it at
this step is very cheap. Whether you pass a JsFoo by reference
or by value, the cost is the same due to how wasm-bindgen handles
(what it's treating as a) JS-imported type.
Converting from JsValue
When you receive a JsValue and need to convert it to your Rust type,
use FromJsRef::try_from_js_value:
use FromJsRef;
This performs a duck-type check under the hood: it verifies the JS object
has the expected upcast method via Reflect::has, then converts through
the generated reference type.
[!WARNING] Do not use
dyn_into::<JsFoo>()ordyn_ref::<JsFoo>(). These rely oninstanceof, which does not work withwasm_refgen-generated types. Theinstanceofcheck targets the Rust identifier name (e.g.,JsFoo) rather than the JS class name (Foo), so it always fails at runtime. UseFromJsRef::try_from_js_valueinstead.
Collections
This provides both an ergonomic way to get typed Vecs on the Rust side,
but also generates Array<Foo> as the TypeScript type.
Some Lightweight Runtime Safety
This strategy gains a small amount of runtime safety by renaming
.clone to a special method that uses your struct's name. The duck-typed
interface only works if the JS object actually implements this
uniquely named method produced by the glue code. This is not as "safe"
as static type checking, but provides a lightweight way to ensure that
the correct kind of object is passed over the boundary without relying
on direct reflection.
The try_from_js_value method leverages this same mechanism: it checks
for the presence of the upcast method via Reflect::has before attempting
the conversion. If the method is missing, it returns None.
Under The Hood
You do not need to understand how this works under the hood to use the macro, but here's a diagram of how the pieces fit together:
┌───────────────────────────┐
│ │
│ JS Foo instance │
│ Class: Foo │
│ Object { wbg_ptr: 12345 } │
│ │
└─┬──────────────────────┬──┘
│ │
│ │
Implements │
│ │
│ │
┌───────────▼───────────────┐ │
│ │ │
│ TS Interface: Foo │ Pointer
│ only method: │ │
│ __wasm_refgen_to_Foo │ │
│ │ │
└───────────┬───────────────┘ │
JS/TS │ │
─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─│─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┼ ─ ─ ─ ─ ─
Wasm │ │
│ │
┌───────────┼──────────────────────┼───────────┐
│ ▼ ▼ │
│ ┌────────────────┐ ┌────────────────┐ │
│ │ │ │ │ │
│ │ &JsFoo ◀────────▶ WasmFoo │ │
│ │ Opaque Wrapper │ │ Instance #1 │ │
│ │ │ │ │ │
│ └────────────────┘ └────────────────┘ │
└──────────────────────┬───────────────────────┘
│
│
Into::into
(uses `__wasm_refgen_to_Foo`)
(which is a wrapper for `clone`)
│
│
▼
┌────────────────┐
│ │
│ WasmFoo │
│ Instance #2 │
│ │
└────────────────┘
try_from_js_value Flow
When converting from a raw JsValue, the flow is:
JsValue
│
▼
Reflect::has(value, "__wasm_refgen_toWasmFoo")
│
├── false → None
│
└── true
│
▼
unchecked_into::<JsFoo>()
│
▼
from_js_ref(&JsFoo)
│
▼
calls .__wasm_refgen_to_wasm_foo()
│
▼
Some(WasmFoo)