@ubjs/wasm 0.31.0-5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,267 @@
1
+ /*
2
+ * This Source Code Form is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/
5
+ */
6
+ import { Memory } from "./memory.js";
7
+ import { Scratch } from "./scratch.js";
8
+ import { compileStructLayout, } from "./marshal.js";
9
+ import { specializeFunction, getCapacityHint, canUseFunctionConstructor, } from "./call.js";
10
+ import { CallbackTable } from "./callback.js";
11
+ import { FutureRegistry } from "./future.js";
12
+ const REQUIRED_EXPORTS = ["__ubrn_alloc", "__ubrn_free", "memory"];
13
+ const SCRATCH_BYTES = 64 * 1024;
14
+ async function buildImports(compiled, importObject, resolveModule) {
15
+ const resolved = new Map();
16
+ const seenModules = new Set();
17
+ for (const imp of WebAssembly.Module.imports(compiled)) {
18
+ seenModules.add(imp.module);
19
+ }
20
+ if (resolveModule) {
21
+ for (const moduleName of seenModules) {
22
+ if (moduleName in importObject)
23
+ continue;
24
+ const exports = await resolveModule(moduleName);
25
+ if (exports) {
26
+ resolved.set(moduleName, exports);
27
+ importObject[moduleName] = exports;
28
+ }
29
+ }
30
+ }
31
+ for (const imp of WebAssembly.Module.imports(compiled)) {
32
+ const slotKey = imp.module;
33
+ let slot = importObject[slotKey];
34
+ if (slot && imp.name in slot)
35
+ continue;
36
+ if (!slot) {
37
+ slot = {};
38
+ importObject[slotKey] = slot;
39
+ }
40
+ switch (imp.kind) {
41
+ case "function":
42
+ slot[imp.name] = (..._args) => {
43
+ throw new Error(`wasm import ${imp.module}.${imp.name} is a stub — ` +
44
+ `no resolver provided exports for "${imp.module}".`);
45
+ };
46
+ break;
47
+ case "global":
48
+ slot[imp.name] = new WebAssembly.Global({ value: "i32", mutable: false }, 0);
49
+ break;
50
+ case "memory":
51
+ slot[imp.name] = new WebAssembly.Memory({ initial: 1 });
52
+ break;
53
+ case "table":
54
+ slot[imp.name] = new WebAssembly.Table({
55
+ initial: 0,
56
+ element: "anyfunc",
57
+ });
58
+ break;
59
+ }
60
+ }
61
+ return { resolved };
62
+ }
63
+ /** Install a JS function in `__indirect_function_table` to receive Rust
64
+ * panic messages, and tell the helper crate's panic-log slot to dispatch
65
+ * to it. The helper crate doesn't import an env-namespaced
66
+ * `__ubrn_panic_log` (that would force every linking cdylib to declare an
67
+ * unresolvable env import — see `helper-crate/src/lib.rs`); the player
68
+ * wires it up here via the same trampoline machinery callbacks use. */
69
+ function installPanicLog(callbacks, memory, exports) {
70
+ const setSlot = exports.__ubrn_set_panic_log;
71
+ if (typeof setSlot !== "function")
72
+ return;
73
+ const panicLogDef = {
74
+ args: [{ tag: "UInt32" }, { tag: "UInt32" }],
75
+ ret: { tag: "Void" },
76
+ hasRustCallStatus: false,
77
+ };
78
+ const slot = callbacks.installCallbackFunction((ptr, len) => {
79
+ const bytes = memory.readBytes(ptr, len);
80
+ const msg = new TextDecoder().decode(bytes);
81
+ // eslint-disable-next-line no-console
82
+ console.error("[Rust panic] " + msg + "\n" + new Error().stack);
83
+ }, panicLogDef);
84
+ setSlot(slot);
85
+ }
86
+ export class UniffiNativeModule {
87
+ memory;
88
+ scratch;
89
+ exports;
90
+ instance;
91
+ callbacks;
92
+ futures;
93
+ alloc;
94
+ free;
95
+ constructor(instance) {
96
+ this.instance = instance;
97
+ this.exports = instance.exports;
98
+ for (const name of REQUIRED_EXPORTS) {
99
+ if (!(name in this.exports)) {
100
+ throw new Error(`UniffiNativeModule.open: required export "${name}" not found in wasm module`);
101
+ }
102
+ }
103
+ const wm = this.exports.memory;
104
+ this.memory = new Memory(wm);
105
+ const allocFn = this.exports.__ubrn_alloc;
106
+ const freeFn = this.exports.__ubrn_free;
107
+ this.alloc = allocFn;
108
+ this.free = freeFn;
109
+ const arenaPtr = allocFn(SCRATCH_BYTES, 8);
110
+ if (arenaPtr === 0) {
111
+ throw new Error("UniffiNativeModule.open: __ubrn_alloc returned 0 for scratch arena");
112
+ }
113
+ this.scratch = new Scratch(arenaPtr, SCRATCH_BYTES, (size) => allocFn(size, 8), (ptr, size) => freeFn(ptr, size, 8));
114
+ // Build the callback dispatch infrastructure first — `installPanicLog`
115
+ // emits a trampoline through it, and the `__ubrn_dispatch` import
116
+ // closure forwards to `callbacks.dispatch` so any later panic from
117
+ // inside an FFI call routes correctly.
118
+ this.callbacks = new CallbackTable(this.memory, this.exports, true);
119
+ this.futures = new FutureRegistry(this.callbacks);
120
+ installPanicLog(this.callbacks, this.memory, this.exports);
121
+ if (typeof this.exports.__ubrn_install_panic_hook === "function") {
122
+ this.exports.__ubrn_install_panic_hook();
123
+ }
124
+ }
125
+ static async open(source, options) {
126
+ let compiled;
127
+ if (source instanceof WebAssembly.Module) {
128
+ compiled = source;
129
+ }
130
+ else if (source instanceof ArrayBuffer || source instanceof Uint8Array) {
131
+ compiled = await WebAssembly.compile(source);
132
+ }
133
+ else if (typeof Response !== "undefined" && source instanceof Response) {
134
+ compiled = await WebAssembly.compileStreaming(source);
135
+ }
136
+ else {
137
+ throw new Error("UniffiNativeModule.open: URL/string sources must be resolved by the env-specific entry");
138
+ }
139
+ // Per-instance imports: the closures below close over `created`, which we
140
+ // populate after instantiation. They will reject if invoked during the
141
+ // instantiation start function (start-section panics happen before we have
142
+ // a UniffiNativeModule to dispatch through).
143
+ let created = null;
144
+ const importObject = {
145
+ env: {
146
+ __ubrn_dispatch: (...args) => {
147
+ const mod = created;
148
+ if (!mod) {
149
+ throw new Error("__ubrn_dispatch invoked before module construction completed");
150
+ }
151
+ return mod.callbacks.dispatch(...args);
152
+ },
153
+ },
154
+ };
155
+ const { resolved } = await buildImports(compiled, importObject, options?.resolveModule);
156
+ const instance = await WebAssembly.instantiate(compiled, importObject);
157
+ // wasm-bindgen-bundler glue files expose `__wbg_set_wasm` so JS-side
158
+ // helpers can reach back into the wasm exports. Wire that up before
159
+ // calling any exports, then run `__wbindgen_start` (wasm-bindgen's
160
+ // initializer; it sets up the panic hook the wbg-glued bindings need).
161
+ for (const exports of resolved.values()) {
162
+ const setter = exports["__wbg_set_wasm"];
163
+ if (typeof setter === "function") {
164
+ setter(instance.exports);
165
+ }
166
+ }
167
+ const startFn = instance.exports["__wbindgen_start"];
168
+ if (typeof startFn === "function") {
169
+ startFn();
170
+ }
171
+ created = new UniffiNativeModule(instance);
172
+ return created;
173
+ }
174
+ async register(definitions, opts) {
175
+ return this.registerSync(definitions, opts);
176
+ }
177
+ registerSync(definitions, opts) {
178
+ if (!definitions.symbols.rustbuffer_alloc) {
179
+ throw new Error("register: definitions.symbols.rustbuffer_alloc must be a non-empty string");
180
+ }
181
+ if (!definitions.symbols.rustbuffer_free) {
182
+ throw new Error("register: definitions.symbols.rustbuffer_free must be a non-empty string");
183
+ }
184
+ const structs = new Map();
185
+ for (const [name, fields] of Object.entries(definitions.structs)) {
186
+ structs.set(name, compileStructLayout(fields));
187
+ }
188
+ const callbackDefs = new Map(Object.entries(definitions.callbacks));
189
+ // Hand the resolution context to the CallbackTable so that when a
190
+ // wasm-to-JS dispatch lifts a `Callback`-typed arg (a function-table
191
+ // index Rust passed in), we can wrap it in a JS callable that lowers
192
+ // its args via the registered shape's `args` and the compiled struct
193
+ // layouts.
194
+ this.callbacks.setRegistrationContext({ callbackDefs, structs });
195
+ // Probe once at register time: under strict CSP `new Function` throws,
196
+ // and the caller may explicitly opt out via `disableJit` (used by tests
197
+ // that want to exercise the interpreted path).
198
+ const useJit = !opts?.disableJit && canUseFunctionConstructor();
199
+ const ctx = {
200
+ memory: this.memory,
201
+ scratch: this.scratch,
202
+ structs,
203
+ callbackDefs,
204
+ alloc: this.alloc,
205
+ free: this.free,
206
+ installCallback: (fn, def) => this.callbacks.installCallbackFunction(fn, def),
207
+ useJit,
208
+ };
209
+ const result = Object.create(null);
210
+ for (const [fnName, def] of Object.entries(definitions.functions)) {
211
+ const exportFn = this.exports[fnName];
212
+ if (typeof exportFn !== "function") {
213
+ throw new Error(`register: wasm export "${fnName}" not found`);
214
+ }
215
+ result[fnName] = specializeFunction(ctx, exportFn, def, fnName);
216
+ }
217
+ // JS-callable allocator pair, exposed alongside the per-function entries.
218
+ // A converter handed `rustbuffer_alloc` as its `lower(value, alloc)`
219
+ // writes its payload straight into a view over wasm memory;
220
+ // `writeRustBufferPayload` then spots the wasm-aliased view and forwards
221
+ // `(byteOffset, byteLength)` into the `RustBuffer` struct, so neither
222
+ // side copies.
223
+ //
224
+ // The helper crate's `__ubrn_alloc` / `__ubrn_free` back this rather than
225
+ // `ffi_<crate>_rustbuffer_alloc`. Both reach the same Rust global
226
+ // allocator, so Rust can still take ownership via `Vec::from_raw_parts`,
227
+ // and the path stays crate-agnostic — no per-crate symbol lookup at
228
+ // register time.
229
+ const memory = this.memory;
230
+ const alloc = this.alloc;
231
+ const free = this.free;
232
+ /**
233
+ * Allocate `n` bytes of wasm linear memory and return a Uint8Array view
234
+ * over them. The view aliases wasm memory directly — no copy.
235
+ *
236
+ * Lifetime: the caller MUST call `rustbuffer_free(view)` before any other
237
+ * wasm operation that could trigger `WebAssembly.Memory.grow` (which
238
+ * detaches the underlying ArrayBuffer). Common detaching operations
239
+ * include subsequent `rustbuffer_alloc` calls and FFI calls that allocate
240
+ * Rust-side. After detachment, the view's byteLength becomes 0 and
241
+ * `rustbuffer_free(view)` will leak the original allocation.
242
+ */
243
+ result.rustbuffer_alloc = (n) => {
244
+ if (n === 0)
245
+ return new Uint8Array(0);
246
+ const ptr = alloc(n, 1);
247
+ return new Uint8Array(memory.buffer(), ptr, n);
248
+ };
249
+ result.rustbuffer_free = (view) => {
250
+ const hint = getCapacityHint(view);
251
+ if (view.byteLength === 0 && hint === undefined)
252
+ return;
253
+ if (view.buffer.byteLength === 0) {
254
+ throw new Error("rustbuffer_free: view is detached (held across a wasm memory growth?)");
255
+ }
256
+ // Rust may over-allocate a returned RustBuffer, so its capacity can
257
+ // exceed the view's byteLength. The handoff path stashes the real
258
+ // capacity via `setCapacityHint`. Views from `rustbuffer_alloc` carry no
259
+ // hint because their length already is the allocation size.
260
+ const cap = hint ?? view.byteLength;
261
+ if (cap === 0)
262
+ return;
263
+ free(view.byteOffset, cap, 1);
264
+ };
265
+ return result;
266
+ }
267
+ }
@@ -0,0 +1,40 @@
1
+ type Alloc = (size: number) => number;
2
+ type Free = (ptr: number, size: number) => void;
3
+ /**
4
+ * Stack-discipline bump arena over a region of wasm linear memory.
5
+ *
6
+ * `push(n)` returns a pointer to `n` bytes. If the arena is full, falls
7
+ * back to the supplied allocator. `pop(ptr)` must be called in LIFO order
8
+ * with the value returned by the matching `push`. If the pointer was an
9
+ * overflow allocation, it is freed via the supplied free fn.
10
+ */
11
+ export declare class Scratch {
12
+ private arenaPtr;
13
+ private arenaSize;
14
+ private alloc;
15
+ private free;
16
+ private mark;
17
+ private reservedHigh;
18
+ private hasPushed;
19
+ private overflow;
20
+ private maxArenaSize;
21
+ constructor(arenaPtr: number, arenaSize: number, alloc: Alloc, free: Free, maxArenaSize?: number);
22
+ /**
23
+ * Carve a permanent region from the arena, returning its starting offset
24
+ * within wasm memory. Must be called BEFORE any push(). Survives every
25
+ * push/pop cycle for the arena's lifetime.
26
+ *
27
+ * Note: the returned region is a SINGLE address shared across every caller
28
+ * that holds it. It is suitable only for transient scratch within a single
29
+ * synchronous call frame — callers must not assume its contents survive
30
+ * across re-entry. If the wasm export whose dispatcher owns this region is
31
+ * synchronously re-entered (e.g. via a JS callback that calls the same
32
+ * export), the inner call will overwrite the outer call's scratch (status
33
+ * byte, sret slot, lowered arg buffers). Callers that need re-entrant
34
+ * isolation must use `push`/`pop` per call instead of reserving up front.
35
+ */
36
+ reserve(size: number): number;
37
+ push(size: number): number;
38
+ pop(ptr: number): void;
39
+ }
40
+ export {};
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Stack-discipline bump arena over a region of wasm linear memory.
3
+ *
4
+ * `push(n)` returns a pointer to `n` bytes. If the arena is full, falls
5
+ * back to the supplied allocator. `pop(ptr)` must be called in LIFO order
6
+ * with the value returned by the matching `push`. If the pointer was an
7
+ * overflow allocation, it is freed via the supplied free fn.
8
+ */
9
+ export class Scratch {
10
+ arenaPtr;
11
+ arenaSize;
12
+ alloc;
13
+ free;
14
+ mark = 0; // offset within arena
15
+ reservedHigh = 0; // boundary between reserved (below) and push/pop (above)
16
+ hasPushed = false; // once true, no more reserve() calls allowed
17
+ overflow = new Map(); // ptr -> size
18
+ maxArenaSize;
19
+ constructor(arenaPtr, arenaSize, alloc, free, maxArenaSize) {
20
+ this.arenaPtr = arenaPtr;
21
+ this.arenaSize = arenaSize;
22
+ this.alloc = alloc;
23
+ this.free = free;
24
+ this.maxArenaSize = maxArenaSize ?? arenaSize;
25
+ }
26
+ /**
27
+ * Carve a permanent region from the arena, returning its starting offset
28
+ * within wasm memory. Must be called BEFORE any push(). Survives every
29
+ * push/pop cycle for the arena's lifetime.
30
+ *
31
+ * Note: the returned region is a SINGLE address shared across every caller
32
+ * that holds it. It is suitable only for transient scratch within a single
33
+ * synchronous call frame — callers must not assume its contents survive
34
+ * across re-entry. If the wasm export whose dispatcher owns this region is
35
+ * synchronously re-entered (e.g. via a JS callback that calls the same
36
+ * export), the inner call will overwrite the outer call's scratch (status
37
+ * byte, sret slot, lowered arg buffers). Callers that need re-entrant
38
+ * isolation must use `push`/`pop` per call instead of reserving up front.
39
+ */
40
+ reserve(size) {
41
+ if (this.hasPushed) {
42
+ throw new Error("Scratch.reserve: cannot reserve after the first push()");
43
+ }
44
+ // Callers lay RustCallStatus / RustBuffer structs out relative to the
45
+ // returned base assuming it is 8-byte aligned (both have align 8). The
46
+ // arena base is 8-aligned, so keep every carve-off 8-aligned too.
47
+ const start = (this.reservedHigh + 7) & ~7;
48
+ if (start + size > this.arenaSize) {
49
+ throw new Error(`Scratch.reserve: arena exhausted (need ${size}, have ${this.arenaSize - start})`);
50
+ }
51
+ const p = this.arenaPtr + start;
52
+ this.reservedHigh = start + size;
53
+ this.mark = this.reservedHigh;
54
+ return p;
55
+ }
56
+ push(size) {
57
+ this.hasPushed = true;
58
+ if (this.mark + size > this.maxArenaSize) {
59
+ const p = this.alloc(size);
60
+ this.overflow.set(p, size);
61
+ return p;
62
+ }
63
+ const p = this.arenaPtr + this.mark;
64
+ this.mark += size;
65
+ return p;
66
+ }
67
+ pop(ptr) {
68
+ const overflowSize = this.overflow.get(ptr);
69
+ if (overflowSize !== undefined) {
70
+ this.overflow.delete(ptr);
71
+ this.free(ptr, overflowSize);
72
+ return;
73
+ }
74
+ // Stack discipline: ptr must be the most recent in-arena push.
75
+ const offset = ptr - this.arenaPtr;
76
+ if (offset < this.reservedHigh || offset >= this.arenaSize) {
77
+ throw new Error(`Scratch.pop: pointer ${ptr} not within push region (reserved high=${this.reservedHigh})`);
78
+ }
79
+ this.mark = offset;
80
+ }
81
+ }
@@ -0,0 +1,9 @@
1
+ export declare const TAG_I32 = 0;
2
+ export declare const TAG_I64 = 1;
3
+ export declare const TAG_F32 = 2;
4
+ export declare const TAG_F64 = 3;
5
+ /**
6
+ * Emit a wasm trampoline module. `paramTags` are the trampoline's
7
+ * exposed parameter type tags; `returnTag` is `undefined` for void.
8
+ * `shapeId` is forwarded as the first arg to `__ubrn_dispatch`. */
9
+ export declare function emitTrampoline(shapeId: number, paramTags: number[], returnTag: number | undefined): Uint8Array;
@@ -0,0 +1,153 @@
1
+ /*
2
+ * This Source Code Form is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/
5
+ */
6
+ // Hand-rolled wasm encoder for the *single* shape we emit: a trampoline
7
+ // function that pushes a shape id and forwards its args to a JS-imported
8
+ // `env.__ubrn_dispatch`. Encoding here rather than in the helper crate keeps
9
+ // the wasm-encoder crate — some 4 MB per cdylib — out of every fixture.
10
+ //
11
+ // Output layout:
12
+ //
13
+ // (module
14
+ // (type $trampoline (func (param ...) (result ...)))
15
+ // (type $dispatch (func (param i32 ...) (result ...)))
16
+ // (import "env" "__ubrn_dispatch" (func $dispatch (type 1)))
17
+ // (func $trampoline (type 0)
18
+ // i32.const <shape_id>
19
+ // local.get 0 ... local.get N
20
+ // call $dispatch)
21
+ // (export "trampoline" (func $trampoline)))
22
+ export const TAG_I32 = 0;
23
+ export const TAG_I64 = 1;
24
+ export const TAG_F32 = 2;
25
+ export const TAG_F64 = 3;
26
+ const VALTYPE_I32 = 0x7f;
27
+ const VALTYPE_I64 = 0x7e;
28
+ const VALTYPE_F32 = 0x7d;
29
+ const VALTYPE_F64 = 0x7c;
30
+ function tagToValtype(tag) {
31
+ switch (tag) {
32
+ case TAG_I32:
33
+ return VALTYPE_I32;
34
+ case TAG_I64:
35
+ return VALTYPE_I64;
36
+ case TAG_F32:
37
+ return VALTYPE_F32;
38
+ case TAG_F64:
39
+ return VALTYPE_F64;
40
+ default:
41
+ throw new Error(`emitTrampoline: unknown type tag ${tag}`);
42
+ }
43
+ }
44
+ /** Append unsigned LEB128 of `n` (≥ 0) to `out`. */
45
+ function leb128(out, n) {
46
+ do {
47
+ let byte = n & 0x7f;
48
+ n >>>= 7;
49
+ if (n !== 0)
50
+ byte |= 0x80;
51
+ out.push(byte);
52
+ } while (n !== 0);
53
+ }
54
+ /** Append signed LEB128 of `n` to `out`. */
55
+ function sleb128(out, n) {
56
+ for (;;) {
57
+ let byte = n & 0x7f;
58
+ // Arithmetic shift right preserves sign.
59
+ n >>= 7;
60
+ const sign = byte & 0x40;
61
+ if ((n === 0 && sign === 0) || (n === -1 && sign !== 0)) {
62
+ out.push(byte);
63
+ return;
64
+ }
65
+ out.push(byte | 0x80);
66
+ }
67
+ }
68
+ const ASCII = new TextEncoder();
69
+ function encodeName(out, s) {
70
+ const bytes = ASCII.encode(s);
71
+ leb128(out, bytes.length);
72
+ for (const b of bytes)
73
+ out.push(b);
74
+ }
75
+ function pushSection(out, id, payload) {
76
+ out.push(id);
77
+ leb128(out, payload.length);
78
+ for (const b of payload)
79
+ out.push(b);
80
+ }
81
+ function encodeFuncType(out, params, results) {
82
+ out.push(0x60);
83
+ leb128(out, params.length);
84
+ for (const p of params)
85
+ out.push(p);
86
+ leb128(out, results.length);
87
+ for (const r of results)
88
+ out.push(r);
89
+ }
90
+ /**
91
+ * Emit a wasm trampoline module. `paramTags` are the trampoline's
92
+ * exposed parameter type tags; `returnTag` is `undefined` for void.
93
+ * `shapeId` is forwarded as the first arg to `__ubrn_dispatch`. */
94
+ export function emitTrampoline(shapeId, paramTags, returnTag) {
95
+ const params = paramTags.map(tagToValtype);
96
+ const results = returnTag !== undefined ? [tagToValtype(returnTag)] : [];
97
+ // -- Type section: type 0 = trampoline, type 1 = dispatch (i32, ...params)
98
+ const typeSection = [];
99
+ leb128(typeSection, 2); // 2 type definitions
100
+ encodeFuncType(typeSection, params, results);
101
+ encodeFuncType(typeSection, [VALTYPE_I32, ...params], results);
102
+ // -- Import section: env.__ubrn_dispatch (func type 1) — function index 0
103
+ const importSection = [];
104
+ leb128(importSection, 1);
105
+ encodeName(importSection, "env");
106
+ encodeName(importSection, "__ubrn_dispatch");
107
+ importSection.push(0x00); // import kind: function
108
+ leb128(importSection, 1); // type index 1
109
+ // -- Function section: 1 local function of type 0 (function index 1)
110
+ const funcSection = [];
111
+ leb128(funcSection, 1);
112
+ leb128(funcSection, 0);
113
+ // -- Export section: "trampoline" -> function index 1
114
+ const exportSection = [];
115
+ leb128(exportSection, 1);
116
+ encodeName(exportSection, "trampoline");
117
+ exportSection.push(0x00); // export kind: function
118
+ leb128(exportSection, 1); // function index 1
119
+ // -- Code section: one function body, no locals.
120
+ // Body: i32.const shapeId, local.get 0..N-1, call 0, end.
121
+ const body = [];
122
+ leb128(body, 0); // 0 local declarations
123
+ body.push(0x41); // i32.const
124
+ sleb128(body, shapeId);
125
+ for (let i = 0; i < params.length; i++) {
126
+ body.push(0x20); // local.get
127
+ leb128(body, i);
128
+ }
129
+ body.push(0x10); // call
130
+ leb128(body, 0); // function index 0 (the imported dispatch)
131
+ body.push(0x0b); // end
132
+ const codeSection = [];
133
+ leb128(codeSection, 1); // 1 function body
134
+ leb128(codeSection, body.length); // body length
135
+ for (const b of body)
136
+ codeSection.push(b);
137
+ const out = [
138
+ 0x00,
139
+ 0x61,
140
+ 0x73,
141
+ 0x6d, // magic: \0asm
142
+ 0x01,
143
+ 0x00,
144
+ 0x00,
145
+ 0x00, // version: 1
146
+ ];
147
+ pushSection(out, 1, typeSection);
148
+ pushSection(out, 2, importSection);
149
+ pushSection(out, 3, funcSection);
150
+ pushSection(out, 7, exportSection);
151
+ pushSection(out, 10, codeSection);
152
+ return new Uint8Array(out);
153
+ }
@@ -0,0 +1,19 @@
1
+ import { UniffiNativeModule, type ImportResolver, type WasmSource, type ModuleDefinitions, type NativeModuleInterface } from "../../core/src/module.js";
2
+ export { FfiType } from "../../core/src/ffi-type.js";
3
+ export { UniffiNativeModule };
4
+ export type { WasmSource };
5
+ /**
6
+ * `options.resolveModule` supplies the wasm's own module imports. A cdylib
7
+ * that reached wasm-bindgen through its dependencies imports `./<lib>_bg.js`,
8
+ * and the caller must hand that glue over — generated bindings import it
9
+ * statically and pass it here. Without it, instantiation fails naming the
10
+ * import it could not satisfy.
11
+ */
12
+ export declare function openWasm(source: WasmSource, options?: {
13
+ resolveModule?: ImportResolver;
14
+ }): Promise<UniffiNativeModule>;
15
+ /**
16
+ * Node-only sync registration over an already-instantiated source. The fixture
17
+ * test runner uses this path via wasm-as-ESM imports.
18
+ */
19
+ export declare function registerSync(mod: UniffiNativeModule, defs: ModuleDefinitions): NativeModuleInterface;
@@ -0,0 +1,35 @@
1
+ /*
2
+ * This Source Code Form is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/
5
+ */
6
+ import { readFile } from "node:fs/promises";
7
+ import { fileURLToPath } from "node:url";
8
+ import { UniffiNativeModule, } from "../../core/src/module.js";
9
+ export { FfiType } from "../../core/src/ffi-type.js";
10
+ export { UniffiNativeModule };
11
+ /**
12
+ * `options.resolveModule` supplies the wasm's own module imports. A cdylib
13
+ * that reached wasm-bindgen through its dependencies imports `./<lib>_bg.js`,
14
+ * and the caller must hand that glue over — generated bindings import it
15
+ * statically and pass it here. Without it, instantiation fails naming the
16
+ * import it could not satisfy.
17
+ */
18
+ export async function openWasm(source, options) {
19
+ if (typeof source === "string") {
20
+ const bytes = await readFile(source);
21
+ return UniffiNativeModule.open(bytes, options);
22
+ }
23
+ if (source instanceof URL) {
24
+ const bytes = await readFile(fileURLToPath(source));
25
+ return UniffiNativeModule.open(bytes, options);
26
+ }
27
+ return UniffiNativeModule.open(source, options);
28
+ }
29
+ /**
30
+ * Node-only sync registration over an already-instantiated source. The fixture
31
+ * test runner uses this path via wasm-as-ESM imports.
32
+ */
33
+ export function registerSync(mod, defs) {
34
+ return mod.registerSync(defs);
35
+ }
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@ubjs/wasm",
3
+ "version": "0.31.0-5",
4
+ "description": "WebAssembly player runtime for uniffi-bindgen-react-native generated bindings.",
5
+ "homepage": "https://github.com/jhugman/uniffi-bindgen-react-native",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/jhugman/uniffi-bindgen-react-native.git",
9
+ "directory": "runtimes/wasm"
10
+ },
11
+ "license": "MPL-2.0",
12
+ "author": {
13
+ "name": "James Hugman",
14
+ "email": "james@hugman.tv"
15
+ },
16
+ "bugs": {
17
+ "url": "https://github.com/jhugman/uniffi-bindgen-react-native/issues"
18
+ },
19
+ "keywords": ["uniffi", "ffi", "rust", "wasm", "webassembly", "typescript"],
20
+ "type": "module",
21
+ "exports": {
22
+ ".": {
23
+ "browser": "./dist/browser/src/index.js",
24
+ "node": "./dist/node/src/index.js",
25
+ "default": "./dist/browser/src/index.js"
26
+ },
27
+ "./core": "./dist/core/src/index.js",
28
+ "./browser": "./dist/browser/src/index.js",
29
+ "./node": "./dist/node/src/index.js"
30
+ },
31
+ "files": ["dist/", "!dist/tsconfig.tsbuildinfo", "README.md"],
32
+ "scripts": {
33
+ "build": "tsc -b",
34
+ "prepare": "npm run build",
35
+ "test": "node --test --import tsx './core/tests/*.test.ts'"
36
+ },
37
+ "peerDependencies": {
38
+ "@ubjs/core": "^0.31.0-5"
39
+ },
40
+ "devDependencies": {
41
+ "@ubjs/core": "file:../../typescript",
42
+ "@types/node": "^20",
43
+ "tsx": "^4",
44
+ "typescript": "^5"
45
+ },
46
+ "publishConfig": { "access": "public" }
47
+ }