@ewe-studios/foundation-wasm-ui 0.0.0-stage → 0.1.13

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,2449 @@
1
+ // foundation-wasm.js — core WASM↔JS ABI runtime (clean rewrite of megatron.js).
2
+ //
3
+ // WHY: megatron.js is one 7000-line IIFE that tangles the pure ABI (memory,
4
+ // messaging, callbacks, timers) with DOM concerns. This file is the ABI half only —
5
+ // no DOM, no window — matching the `foundation_wasm` crate split (decision 015).
6
+ //
7
+ // WHAT — ONE self-contained file (no internal imports, browser-loadable without a
8
+ // bundler: `<script type="module">` for the ESM exports, or the
9
+ // `globalThis.FoundationWasmRuntime` mirror for classic scripts), in three sections:
10
+ // 1. Function-call ABI codec: ParameterParser (flat/V1), ReturnHintParser,
11
+ // ReplyEncoder, FunctionRegistry, ExternalHeap
12
+ // 2. V2 quantized batch codec: Operations, TypeOptimization, BatchParameterParser,
13
+ // BatchInstructions (the custom protocol backbone)
14
+ // 3. Core runtime: WasmEnvelope (14-byte [protocol][version][memory_id][length]),
15
+ // ProtocolDispatcher, MemoryAllocations, TimerRegistry, CallbackRegistry,
16
+ // StringCache, AnimationDriver, FoundationWasm (bridge + `web_abi` + `init()`)
17
+ //
18
+ // HOW: bootstrap mirrors the proven integration pattern —
19
+ // const rt = new FoundationWasm();
20
+ // const mod = await WebAssembly.instantiate(bytes, { abi: rt.web_abi });
21
+ // rt.init(mod); // memory comes from instance.exports.memory
22
+ // The WASM module EXPORTS its own linear memory; the host imports close over a
23
+ // lazily-populated `bridge`, so they work even though the instance doesn't exist at
24
+ // the time the import object is built.
25
+ //
26
+ // Protocol bytes (decision 014/022, F27): 0 = Custom Binary, 1 = Arrow, 2 = JSON,
27
+ // 3 = Capability Trigger (host→wasm), 4 = IPC Trigger (host→wasm).
28
+
29
+
30
+ // ════════════════════════════════════════════════════════════════════════════════
31
+ // SECTION 1: function-call ABI codec (formerly function-registry.js)
32
+ // ════════════════════════════════════════════════════════════════════════════════
33
+
34
+ // Function-call ABI codec — WASM↔JS function-call ABI codec (ported from megatron's
35
+ // ParameterParserV1 + ReturnHintParser + Reply, per feature 17 research docs).
36
+ //
37
+ // FAITHFULNESS: this is the FLAT invoke encoding — `[ParamTypeId:u8][value]` per param,
38
+ // concatenated (Rust `Params::to_binary` ↔ this `ParameterParser`). The marker/quantized
39
+ // batch encoding (V2) is a SEPARATE codec. Discriminants and byte layouts mirror
40
+ // `foundation_wasm/src/{base.rs, ops.rs, protocol.rs}` exactly — see research-core-types.md.
41
+
42
+ // Move-by widths (megatron's MOVE_BY_N_BYTES counts BITS for 16/32/64): bytes consumed.
43
+ const B1 = 1, B2 = 2, B4 = 4, B8 = 8;
44
+
45
+ // ─── Reference wrappers (RefPointer family) ─────────────────────────────────────
46
+ export class RefPointer {
47
+ constructor(id) { this.id = id; }
48
+ get value() { return this.id; }
49
+ }
50
+ export class ExternalPointer extends RefPointer {}
51
+ export class InternalPointer extends RefPointer {}
52
+ export class CachePointer extends RefPointer {}
53
+ export class ErrorCodeValue { constructor(code) { this.code = code; } }
54
+ export class TypedArraySliceValue {
55
+ constructor(sliceType, content) { this.sliceType = sliceType; this.content = content; }
56
+ }
57
+
58
+ /**
59
+ * A pre-typed return slot: `{type: ReturnType, value}`. Registered functions build
60
+ * these via the context `as*` helpers; the encoder passes them through untouched
61
+ * instead of inferring the type from the hint (megatron ReplyContainer parity).
62
+ */
63
+ export class ReplyContainer {
64
+ constructor(type, value) { this.type = type; this.value = value; }
65
+ }
66
+
67
+ /** Minimal DOM-node stand-in for non-DOM hosts (megatron FakeNode parity). */
68
+ export class FakeNode {
69
+ constructor(tag) { this.tag = tag; }
70
+ }
71
+
72
+ /** A failure a registered fn raises to reach the WASM callback as an ErrorCode. */
73
+ export class ReplyError extends Error {
74
+ constructor(code, options) {
75
+ if (!Number.isInteger(code)) {
76
+ throw new Error("Only numbers allowed to represent the code to be sent");
77
+ }
78
+ super(`Reply failed with error code: ${code}`, options);
79
+ this.code = code;
80
+ }
81
+ }
82
+
83
+ // ─── Shared discriminants (the cross-language contract) ─────────────────────────
84
+ export const ParamType = Object.freeze({
85
+ Null: 0, Undefined: 1, Bool: 2, Text8: 3, Text16: 4, Int8: 5, Int16: 6, Int32: 7,
86
+ Int64: 8, Uint8: 9, Uint16: 10, Uint32: 11, Uint64: 12, Float32: 13, Float64: 14,
87
+ ExternalReference: 15, Uint8Array: 16, Uint16Array: 17, Uint32Array: 18, Uint64Array: 19,
88
+ Int8Array: 20, Int16Array: 21, Int32Array: 22, Int64Array: 23, Float32Array: 24,
89
+ Float64Array: 25, InternalReference: 26, Int128: 27, Uint128: 28, CachedText: 29,
90
+ TypedArraySlice: 30, ErrorCode: 31,
91
+ });
92
+
93
+ export const ReturnType = Object.freeze({
94
+ Bool: 1, Text8: 2, Int8: 3, Int16: 4, Int32: 5, Int64: 6, Uint8: 7, Uint16: 8, Uint32: 9,
95
+ Uint64: 10, Float32: 11, Float64: 12, Int128: 13, Uint128: 14, MemorySlice: 15,
96
+ ExternalReference: 16, InternalReference: 17, Object: 28, DOMObject: 29, None: 30,
97
+ ErrorCode: 31, TypedArraySlice: 32,
98
+ });
99
+
100
+ const RETURN_NAKED = new Set([
101
+ ReturnType.Bool, ReturnType.Uint8, ReturnType.Uint16, ReturnType.Uint32, ReturnType.Uint64,
102
+ ReturnType.Int8, ReturnType.Int16, ReturnType.Int32, ReturnType.Int64, ReturnType.Float32,
103
+ ReturnType.Float64, ReturnType.Object, ReturnType.DOMObject, ReturnType.ErrorCode,
104
+ ReturnType.MemorySlice, ReturnType.InternalReference, ReturnType.ExternalReference,
105
+ ]);
106
+
107
+ export const ReturnIds = Object.freeze({ None: 0, One: 1, Multi: 2, List: 3 });
108
+ export const ThreeStateId = Object.freeze({ One: 70, Two: 80, Three: 90 });
109
+ export const ReturnHintMarker = Object.freeze({ Start: 200, Stop: 201 });
110
+ // The reply ReturnValues binary is framed Begin..End (Rust `FromBinary for ReturnTypeHints`).
111
+ export const ReturnValueMarker = Object.freeze({ Begin: 100, End: 101 });
112
+ export const TypedSliceArray = {
113
+ 1: Int8Array, 2: Int16Array, 3: Int32Array, 4: BigInt64Array, 5: Uint8Array,
114
+ 6: Uint16Array, 7: Uint32Array, 8: BigUint64Array, 9: Float32Array, 10: Float64Array,
115
+ };
116
+
117
+ // ─── ExternalHeap (generation-based arena, = megatron ArenaAllocator) ───────────
118
+
119
+ /**
120
+ * Host-side heap for objects referenced across the ABI by `ExternalPointer` ids.
121
+ * Ids pack `(index << 32) | generation` (bigint) — same scheme as the Rust arena —
122
+ * so stale ids fail the generation check instead of resolving to a reused slot.
123
+ * `create(null)` pre-allocates a handle (the `*_allocate_external_pointer` imports);
124
+ * `update` fills it later (e.g. batch MakeFunction).
125
+ */
126
+ export class ExternalHeap {
127
+ constructor() {
128
+ this.items = []; // { item, generation, active }
129
+ this.free = [];
130
+ }
131
+
132
+ #unpack(uid) {
133
+ const v = BigInt(uid);
134
+ return { index: Number(v >> 32n), generation: v & 0xffffffffn };
135
+ }
136
+
137
+ /** Allocate a slot for `item` (may be null) → packed uid (bigint). */
138
+ create(item) {
139
+ let index;
140
+ if (this.free.length > 0) {
141
+ index = this.free.pop();
142
+ const slot = this.items[index];
143
+ slot.generation += 1n;
144
+ slot.active = true;
145
+ slot.item = item;
146
+ } else {
147
+ index = this.items.length;
148
+ this.items.push({ item, generation: 0n, active: true });
149
+ }
150
+ return (BigInt(index) << 32n) | this.items[index].generation;
151
+ }
152
+
153
+ /** Resolve a uid → item (undefined when stale/missing). */
154
+ get(uid) {
155
+ const { index, generation } = this.#unpack(uid);
156
+ const slot = this.items[index];
157
+ if (!slot || !slot.active || slot.generation !== generation) return undefined;
158
+ return slot.item;
159
+ }
160
+
161
+ /** Replace the item at a live uid (pre-allocated handles). False when stale. */
162
+ update(uid, item) {
163
+ const { index, generation } = this.#unpack(uid);
164
+ const slot = this.items[index];
165
+ if (!slot || slot.generation !== generation) return false;
166
+ slot.item = item;
167
+ slot.active = true;
168
+ return true;
169
+ }
170
+
171
+ /** Retire a uid; its slot is recycled with a bumped generation. */
172
+ destroy(uid) {
173
+ const { index, generation } = this.#unpack(uid);
174
+ const slot = this.items[index];
175
+ if (!slot || !slot.active || slot.generation !== generation) return false;
176
+ slot.item = null;
177
+ slot.active = false;
178
+ this.free.push(index);
179
+ return true;
180
+ }
181
+ }
182
+
183
+ /**
184
+ * Normalize a typed-slice return value: a `TypedArraySliceValue` keeps its declared
185
+ * slice type; a bare TypedArray maps to its `TypedSlice` id (megatron check_for_type
186
+ * accepted both). Returns the slice id + a byte view over the content.
187
+ */
188
+ function asTypedSlice(value) {
189
+ if (value instanceof TypedArraySliceValue) {
190
+ const content = value.content;
191
+ return {
192
+ sliceType: value.sliceType,
193
+ u8: new Uint8Array(content.buffer, content.byteOffset, content.byteLength),
194
+ };
195
+ }
196
+ for (const [id, Ctor] of Object.entries(TypedSliceArray)) {
197
+ if (value instanceof Ctor && value.constructor === Ctor) {
198
+ return {
199
+ sliceType: Number(id),
200
+ u8: new Uint8Array(value.buffer, value.byteOffset, value.byteLength),
201
+ };
202
+ }
203
+ }
204
+ throw new Error("TypedArraySlice return: expected a TypedArray or TypedArraySliceValue");
205
+ }
206
+
207
+ /**
208
+ * The u16 code behind any error representation: an `ErrorCodeValue` (echoed param),
209
+ * a `ReplyError`/Error carrying `.code`, or a bare integer. Unknown shapes → 1.
210
+ */
211
+ function errorCodeOf(value) {
212
+ if (value instanceof ErrorCodeValue) return value.code;
213
+ if (value && Number.isInteger(value.code)) return value.code;
214
+ if (Number.isInteger(value)) return value;
215
+ if (typeof value === "bigint") return Number(value);
216
+ return 1;
217
+ }
218
+
219
+ /**
220
+ * Does `value`'s JS runtime type satisfy the candidate `ReturnType`? Used to resolve
221
+ * a union ThreeState (Two/Three): candidates are tried IN DECLARED ORDER and the
222
+ * first match wins (megatron `Reply.check_for_type` parity — e.g. `1` against
223
+ * `Three(Bool, Int8, Uint8)` picks Int8, not Bool). Non-union states never consult
224
+ * this; the Rust `ReturnValueParserIter` validates the final choice.
225
+ */
226
+ function matchesReturnType(value, type) {
227
+ switch (type) {
228
+ case ReturnType.None: return value === undefined || value === null;
229
+ case ReturnType.Bool: return typeof value === "boolean";
230
+ case ReturnType.Text8: return typeof value === "string";
231
+ case ReturnType.Int8:
232
+ case ReturnType.Int16:
233
+ case ReturnType.Int32:
234
+ case ReturnType.Uint8:
235
+ case ReturnType.Uint16:
236
+ case ReturnType.Uint32:
237
+ return typeof value === "number" && Number.isInteger(value);
238
+ case ReturnType.Int64:
239
+ case ReturnType.Uint64:
240
+ case ReturnType.Int128:
241
+ case ReturnType.Uint128:
242
+ return typeof value === "bigint" || (typeof value === "number" && Number.isInteger(value));
243
+ case ReturnType.Float32:
244
+ case ReturnType.Float64:
245
+ return typeof value === "number";
246
+ case ReturnType.ErrorCode:
247
+ return value instanceof ErrorCodeValue || value instanceof ReplyError ||
248
+ (typeof value === "number" && Number.isInteger(value));
249
+ case ReturnType.ExternalReference: return value instanceof ExternalPointer;
250
+ case ReturnType.InternalReference: return value instanceof InternalPointer;
251
+ case ReturnType.TypedArraySlice:
252
+ return value instanceof TypedArraySliceValue || ArrayBuffer.isView(value);
253
+ case ReturnType.MemorySlice:
254
+ return typeof value === "bigint" || typeof value === "number" || ArrayBuffer.isView(value);
255
+ case ReturnType.DOMObject:
256
+ return value instanceof FakeNode ||
257
+ (typeof Node !== "undefined" && value instanceof Node) ||
258
+ (typeof value === "object" && value !== null);
259
+ case ReturnType.Object: return typeof value === "object" && value !== null;
260
+ default: return false;
261
+ }
262
+ }
263
+
264
+ // ─── ParameterParser (FLAT, = ParameterParserV1) ────────────────────────────────
265
+
266
+ /**
267
+ * Decode `host_invoke_function` params: `[ParamType:u8][value]` repeated until the
268
+ * buffer is consumed. Text/arrays carry `[ptr:u64][len:u64]` into WASM memory.
269
+ */
270
+ export class ParameterParser {
271
+ /** @param {{memory:WebAssembly.Memory}} bridge @param {StringCache} strings */
272
+ constructor(bridge, strings) {
273
+ this.bridge = bridge;
274
+ this.strings = strings;
275
+ }
276
+
277
+ /** @returns {any[]} decoded positional args */
278
+ parse(ptr, len) {
279
+ const start = Number(ptr);
280
+ const total = Number(len);
281
+ const view = new DataView(this.bridge.memory.buffer, start, total);
282
+ const args = [];
283
+ let i = 0;
284
+ while (i < total) {
285
+ const type = view.getUint8(i);
286
+ i += B1;
287
+ i = this.#one(type, i, view, args);
288
+ }
289
+ return args;
290
+ }
291
+
292
+ #slice(view, i) {
293
+ // [ptr:u64 LE][len:u64 LE] → (byteStart, byteLen) into WASM memory
294
+ const ptr = Number(view.getBigUint64(i, true));
295
+ i += B8;
296
+ const len = Number(view.getBigUint64(i, true));
297
+ i += B8;
298
+ return [i, ptr, len];
299
+ }
300
+
301
+ #one(type, i, view, args) {
302
+ const mem = this.bridge.memory.buffer;
303
+ switch (type) {
304
+ case ParamType.Null: args.push(null); return i;
305
+ case ParamType.Undefined: args.push(undefined); return i;
306
+ case ParamType.Bool: args.push(view.getUint8(i) === 1); return i + B1;
307
+ case ParamType.Int8: args.push(view.getInt8(i)); return i + B1;
308
+ case ParamType.Uint8: args.push(view.getUint8(i)); return i + B1;
309
+ case ParamType.Int16: args.push(view.getInt16(i, true)); return i + B2;
310
+ case ParamType.Uint16: args.push(view.getUint16(i, true)); return i + B2;
311
+ case ParamType.ErrorCode: args.push(new ErrorCodeValue(view.getUint16(i, true))); return i + B2;
312
+ case ParamType.Int32: args.push(view.getInt32(i, true)); return i + B4;
313
+ case ParamType.Uint32: args.push(view.getUint32(i, true)); return i + B4;
314
+ case ParamType.Float32: args.push(view.getFloat32(i, true)); return i + B4;
315
+ case ParamType.Float64: args.push(view.getFloat64(i, true)); return i + B8;
316
+ case ParamType.Int64: args.push(view.getBigInt64(i, true)); return i + B8;
317
+ case ParamType.Uint64: args.push(view.getBigUint64(i, true)); return i + B8;
318
+ case ParamType.ExternalReference: args.push(new ExternalPointer(view.getBigUint64(i, true))); return i + B8;
319
+ case ParamType.InternalReference: args.push(new InternalPointer(view.getBigUint64(i, true))); return i + B8;
320
+ case ParamType.CachedText: {
321
+ const handle = view.getBigUint64(i, true);
322
+ const text = this.strings.get(handle);
323
+ if (text === undefined) throw new Error(`CachedText: no string for handle ${handle}`);
324
+ args.push(text);
325
+ return i + B8;
326
+ }
327
+ case ParamType.Int128: {
328
+ const msb = view.getBigInt64(i, true), lsb = view.getBigUint64(i + B8, true);
329
+ args.push((msb << 64n) | lsb);
330
+ return i + B8 + B8;
331
+ }
332
+ case ParamType.Uint128: {
333
+ const msb = view.getBigUint64(i, true), lsb = view.getBigUint64(i + B8, true);
334
+ args.push((msb << 64n) | lsb);
335
+ return i + B8 + B8;
336
+ }
337
+ case ParamType.Text8: {
338
+ const [ni, p, l] = this.#slice(view, i);
339
+ args.push(new TextDecoder().decode(new Uint8Array(mem, p, l)));
340
+ return ni;
341
+ }
342
+ case ParamType.Text16: {
343
+ const [ni, p, l] = this.#slice(view, i);
344
+ args.push(new TextDecoder("utf-16le").decode(new Uint8Array(mem, p, l)));
345
+ return ni;
346
+ }
347
+ case ParamType.TypedArraySlice: {
348
+ const sliceType = view.getUint8(i);
349
+ const [ni, p, l] = this.#slice(view, i + B1);
350
+ const Ctor = TypedSliceArray[sliceType] ?? Uint8Array;
351
+ args.push(new TypedArraySliceValue(sliceType, new Ctor(mem.slice(p, p + l * Ctor.BYTES_PER_ELEMENT))));
352
+ return ni;
353
+ }
354
+ default: {
355
+ // *ArrayBuffer (16–25): [ptr][len] → a copy in the matching typed array.
356
+ const Ctor = ARRAY_BUFFER_CTORS[type];
357
+ if (!Ctor) throw new Error(`ParameterParser: unknown ParamType ${type}`);
358
+ const [ni, p, l] = this.#slice(view, i);
359
+ args.push(new Ctor(mem.slice(p, p + l * Ctor.BYTES_PER_ELEMENT)));
360
+ return ni;
361
+ }
362
+ }
363
+ }
364
+ }
365
+
366
+ const ARRAY_BUFFER_CTORS = {
367
+ [ParamType.Uint8Array]: Uint8Array, [ParamType.Uint16Array]: Uint16Array,
368
+ [ParamType.Uint32Array]: Uint32Array, [ParamType.Uint64Array]: BigUint64Array,
369
+ [ParamType.Int8Array]: Int8Array, [ParamType.Int16Array]: Int16Array,
370
+ [ParamType.Int32Array]: Int32Array, [ParamType.Int64Array]: BigInt64Array,
371
+ [ParamType.Float32Array]: Float32Array, [ParamType.Float64Array]: Float64Array,
372
+ };
373
+
374
+ // ─── ReturnHintParser ────────────────────────────────────────────────────────────
375
+
376
+ /** Decode `[Start][ReturnIds][ThreeState…][Stop]` → { id, states:[{ stateId, types:[] }] }. */
377
+ export class ReturnHintParser {
378
+ constructor(bridge) { this.bridge = bridge; }
379
+
380
+ parse(ptr, len) {
381
+ const view = new DataView(this.bridge.memory.buffer, Number(ptr), Number(len));
382
+ const [, hint] = ReturnHintParser.parseFrom(view, 0);
383
+ return hint;
384
+ }
385
+
386
+ /**
387
+ * Offset-based variant shared with the batch codec (hints are embedded mid-stream
388
+ * there). Returns `[indexAfterStop, hint]`.
389
+ */
390
+ static parseFrom(view, i) {
391
+ if (view.getUint8(i) !== ReturnHintMarker.Start) throw new Error("hint: missing Start");
392
+ i += B1;
393
+ const id = view.getUint8(i);
394
+ i += B1;
395
+ const states = [];
396
+ if (id !== ReturnIds.None) {
397
+ // One/List carry exactly one ThreeState; Multi carries several, concatenated.
398
+ // Each ThreeState is [ThreeStateId][ReturnType×n]; read until the Stop marker.
399
+ while (view.getUint8(i) !== ReturnHintMarker.Stop) {
400
+ const stateId = view.getUint8(i);
401
+ i += B1;
402
+ const n = stateId === ThreeStateId.One ? 1 : stateId === ThreeStateId.Two ? 2 : 3;
403
+ const types = [];
404
+ for (let k = 0; k < n; k++) { types.push(view.getUint8(i)); i += B1; }
405
+ states.push({ stateId, types });
406
+ }
407
+ }
408
+ if (view.getUint8(i) !== ReturnHintMarker.Stop) throw new Error("hint: missing Stop");
409
+ i += B1;
410
+ return [i, { id, states }];
411
+ }
412
+ }
413
+
414
+ // ─── ReplyEncoder (= Reply) ─────────────────────────────────────────────────────
415
+
416
+ /** Encodes a JS return value as `[ReturnType:u8][value]` and (when needed) into an arena slot. */
417
+ export class ReplyEncoder {
418
+ /** @param {MemoryAllocations} memory */
419
+ constructor(memory) {
420
+ this.memory = memory;
421
+ // Heaps for reference-returning types; the runtime wires `objects`, the DOM layer
422
+ // wires `dom` (megatron threaded object_heap/dom_heap into Reply.transform).
423
+ this.objects = null; // ExternalHeap | null
424
+ this.dom = null; // ExternalHeap | null
425
+ }
426
+
427
+ /**
428
+ * Mirror of megatron `Reply.immediate`. `hint` is the parsed return-hint
429
+ * ({id, states}); returns either a naked scalar (typed fast-paths, !alwaysEncoded)
430
+ * or a MemoryId (bigint) for an encoded slot, or -1n for None+undefined.
431
+ */
432
+ immediate(hint, value, alwaysEncoded) {
433
+ if (hint.id === ReturnIds.None) {
434
+ if (value === undefined || value === null) return -1n;
435
+ throw new Error(`Expected NoReturn but got ${value}`);
436
+ }
437
+ const containers = this.#containers(hint, value);
438
+ if (
439
+ hint.id === ReturnIds.One && containers.length === 1 &&
440
+ RETURN_NAKED.has(containers[0].type) && !alwaysEncoded
441
+ ) {
442
+ return this.#naked(containers[0]); // typed fast-path — value crosses raw
443
+ }
444
+ return this.encodeIntoMemory(containers);
445
+ }
446
+
447
+ /**
448
+ * The naked form of one container (megatron transforms BEFORE the naked check):
449
+ * Object/DOMObject intern into their heap and the HANDLE crosses; reference
450
+ * pointers cross as their raw id; scalars cross as-is.
451
+ */
452
+ #naked({ type, value }) {
453
+ switch (type) {
454
+ case ReturnType.Object: {
455
+ if (!this.objects) throw new Error("ReplyEncoder: no object heap wired");
456
+ return value instanceof RefPointer ? value.value : this.objects.create(value);
457
+ }
458
+ case ReturnType.DOMObject: {
459
+ if (!this.dom) throw new Error("ReplyEncoder: no DOM heap wired");
460
+ return value instanceof RefPointer ? value.value : this.dom.create(value);
461
+ }
462
+ case ReturnType.ExternalReference:
463
+ case ReturnType.InternalReference:
464
+ return value instanceof RefPointer ? value.value : value;
465
+ case ReturnType.ErrorCode:
466
+ return errorCodeOf(value);
467
+ default:
468
+ return value;
469
+ }
470
+ }
471
+
472
+ /**
473
+ * Build the `{type, value}` containers for a return hint, mirroring the Rust
474
+ * `ReturnValueParserIter` shape:
475
+ * One → exactly 1 value typed by the single ThreeState;
476
+ * List → N homogeneous values, each typed by the same ThreeState;
477
+ * Multi → one value per ThreeState (value `k` ↔ `states[k]`).
478
+ * A union ThreeState (Two/Three) is resolved per concrete value (see #pickType).
479
+ */
480
+ #containers(hint, value) {
481
+ // A ReplyContainer is already typed (context as* helpers) — pass it through
482
+ // untouched (megatron transform_from_hint checks this before any inference).
483
+ const resolve = (state, v) =>
484
+ v instanceof ReplyContainer
485
+ ? { type: v.type, value: v.value }
486
+ : { type: this.#pickType(state, v), value: v };
487
+ switch (hint.id) {
488
+ case ReturnIds.One:
489
+ return [resolve(hint.states[0], value)];
490
+ case ReturnIds.List: {
491
+ const state = hint.states[0];
492
+ return Array.from(value).map((v) => resolve(state, v));
493
+ }
494
+ case ReturnIds.Multi: {
495
+ const arr = Array.from(value);
496
+ return hint.states.map((state, k) => resolve(state, arr[k]));
497
+ }
498
+ default:
499
+ return [];
500
+ }
501
+ }
502
+
503
+ /**
504
+ * Resolve a single declared ThreeState to the concrete ReturnType for `value`.
505
+ * Non-union (`One(t)`) states use their one type directly; union states try each
506
+ * candidate IN DECLARED ORDER and take the first whose runtime type matches
507
+ * (megatron check_for_type order — Rust validates the final choice).
508
+ */
509
+ #pickType(state, value) {
510
+ const { types } = state;
511
+ if (types.length === 1) return types[0];
512
+ for (const candidate of types) {
513
+ if (matchesReturnType(value, candidate)) return candidate;
514
+ }
515
+ throw new Error(`return value ${value} matches none of the hinted types [${types}]`);
516
+ }
517
+
518
+ /** Encode containers `{type, value}` as `[type][value]…` into one arena slot → MemoryId. */
519
+ encodeIntoMemory(containers) {
520
+ const bytes = this.encode(containers);
521
+ const id = this.memory.create(bytes.length);
522
+ this.memory.write(id, bytes);
523
+ return id;
524
+ }
525
+
526
+ /**
527
+ * Mirror of megatron `Reply.callback_success`: an async JS result resolved — encode it
528
+ * (always framed Begin..End) and deliver it to WASM callback `callbackId` via the
529
+ * `CallbackRegistry` (which writes a slot + calls `invoke_callback`). `None`-hinted
530
+ * async calls are fire-and-forget and never reach here.
531
+ * @param {CallbackRegistry} callbacks
532
+ * @param {bigint} callbackId the WASM `InternalPointer` value
533
+ * @param {{id:number, states:Array<{types:number[]}>}} hint
534
+ */
535
+ callbackSuccess(callbacks, callbackId, hint, value) {
536
+ const bytes = this.encode(this.#containers(hint, value));
537
+ callbacks.invoke(callbackId, bytes);
538
+ }
539
+
540
+ /**
541
+ * Mirror of megatron `Reply.callback_failure`: a rejected async result — frame it as an
542
+ * `ErrorCode` ReturnValue and deliver it (Rust decodes `ReturnValues::ErrorCode`).
543
+ * @param {CallbackRegistry} callbacks
544
+ * @param {bigint} callbackId
545
+ */
546
+ callbackFailure(callbacks, callbackId, error) {
547
+ const bytes = this.encode([{ type: ReturnType.ErrorCode, value: errorCodeOf(error) }]);
548
+ callbacks.invoke(callbackId, bytes);
549
+ }
550
+
551
+ /** Encode containers as `[Begin][ReturnType][value]…[End]` (Rust FromBinary expects the frame). */
552
+ encode(containers) {
553
+ const out = [ReturnValueMarker.Begin];
554
+ const push = (n, bytes) => { for (let k = 0; k < bytes; k++) out.push(Number((BigInt(n) >> BigInt(8 * k)) & 0xffn)); };
555
+ for (const { type, value } of containers) {
556
+ out.push(type);
557
+ switch (type) {
558
+ case ReturnType.None: break;
559
+ case ReturnType.Bool: out.push(value ? 1 : 0); break;
560
+ case ReturnType.Uint8: case ReturnType.Int8: push(value, 1); break;
561
+ case ReturnType.Uint16: case ReturnType.Int16: push(value, 2); break;
562
+ // ErrorCode values may arrive wrapped (an echoed ErrorCodeValue param or a
563
+ // ReplyError) — the u16 code is what crosses.
564
+ case ReturnType.ErrorCode: push(errorCodeOf(value), 2); break;
565
+ case ReturnType.Uint32: case ReturnType.Int32: push(value, 4); break;
566
+ case ReturnType.Uint64: case ReturnType.Int64: push(BigInt(value), 8); break;
567
+ case ReturnType.Float32: { const b = new Uint8Array(4); new DataView(b.buffer).setFloat32(0, value, true); out.push(...b); break; }
568
+ case ReturnType.Float64: { const b = new Uint8Array(8); new DataView(b.buffer).setFloat64(0, value, true); out.push(...b); break; }
569
+ case ReturnType.Int128: case ReturnType.Uint128: { const v = BigInt(value); push((v >> 64n) & 0xffffffffffffffffn, 8); push(v & 0xffffffffffffffffn, 8); break; }
570
+ // Reference returns: the id is sent inline (Rust resolves it host-side).
571
+ case ReturnType.ExternalReference:
572
+ case ReturnType.InternalReference:
573
+ push(BigInt(value instanceof RefPointer ? value.value : value), 8);
574
+ break;
575
+ // Text8: write the UTF-8 bytes into a fresh slot, send [type][slot_id:u64].
576
+ // Rust's ReturnValueParserIter Text8 arm takes + frees that slot.
577
+ case ReturnType.Text8: {
578
+ const bytes = new TextEncoder().encode(String(value));
579
+ const slot = this.memory.create(bytes.length);
580
+ this.memory.write(slot, bytes);
581
+ push(slot, 8);
582
+ break;
583
+ }
584
+ // MemorySlice / array buffers: a numeric value IS an existing slot id (the
585
+ // asMemorySlice contract); raw bytes get written into a fresh slot first.
586
+ case ReturnType.MemorySlice: {
587
+ if (typeof value === "bigint" || typeof value === "number") {
588
+ push(BigInt(value), 8);
589
+ break;
590
+ }
591
+ const u8 = value instanceof Uint8Array ? value : new Uint8Array(value.buffer ?? value);
592
+ const slot = this.memory.create(u8.length);
593
+ this.memory.write(slot, u8);
594
+ push(slot, 8);
595
+ break;
596
+ }
597
+ // Object/DOMObject: intern in the matching host heap, send [type][heap_handle:u64]
598
+ // (megatron Reply.asObject/asDOMObject). A RefPointer passes its existing id through.
599
+ case ReturnType.Object: {
600
+ if (!this.objects) throw new Error("ReplyEncoder: no object heap wired");
601
+ push(value instanceof RefPointer ? value.value : this.objects.create(value), 8);
602
+ break;
603
+ }
604
+ case ReturnType.DOMObject: {
605
+ if (!this.dom) throw new Error("ReplyEncoder: no DOM heap wired");
606
+ push(value instanceof RefPointer ? value.value : this.dom.create(value), 8);
607
+ break;
608
+ }
609
+ // TypedArraySlice: stage the bytes in a slot and send the slot's LIVE address —
610
+ // [type][slice_type:u8][ptr:u64][len:u64] (Rust ReturnValues::TypedArraySlice
611
+ // carries a raw MemoryLocation; consume it before the next allocation).
612
+ case ReturnType.TypedArraySlice: {
613
+ const { sliceType, u8 } = asTypedSlice(value);
614
+ const slot = this.memory.create(u8.length);
615
+ this.memory.write(slot, u8);
616
+ out.push(sliceType);
617
+ push(this.memory.get(slot).ptr, 8);
618
+ push(u8.length, 8);
619
+ break;
620
+ }
621
+ default: throw new Error(`ReplyEncoder: unsupported return type ${type}`);
622
+ }
623
+ }
624
+ out.push(ReturnValueMarker.End);
625
+ return Uint8Array.from(out);
626
+ }
627
+ }
628
+
629
+ // ─── FunctionRegistry ────────────────────────────────────────────────────────────
630
+
631
+ /**
632
+ * Implements `host_register_function` + `host_invoke_function(+_as_*)`. Registered JS
633
+ * functions are stored by handle and called with `this` = `context` (so they can use
634
+ * runtime helpers), args spread positionally (mirrors megatron).
635
+ */
636
+ export class FunctionRegistry {
637
+ /**
638
+ * @param {{exports:object, memory:WebAssembly.Memory}} bridge
639
+ * @param {MemoryAllocations} memory
640
+ * @param {StringCache} strings
641
+ * @param {CallbackRegistry} callbacks delivers async replies
642
+ */
643
+ constructor(bridge, memory, strings, callbacks) {
644
+ this.bridge = bridge;
645
+ this.params = new ParameterParser(bridge, strings);
646
+ this.hints = new ReturnHintParser(bridge);
647
+ this.reply = new ReplyEncoder(memory);
648
+ this.callbacks = callbacks;
649
+ // Generation-arena heap shared by ALL function-handle paths: host_register_function,
650
+ // function_allocate_external_pointer pre-allocation, and batch MakeFunction (megatron
651
+ // used one function_heap for all three — handles must be interchangeable).
652
+ this.heap = new ExternalHeap();
653
+ this.context = this; // `this` for registered fns; override to expose helpers
654
+ }
655
+
656
+ /** Compile a registered-function source string into a callable. */
657
+ static compile(source) {
658
+ return Function(`"use strict"; return(${source})`)();
659
+ }
660
+
661
+ /** host_register_function(start, len, utf) → handle. Evals the source string. */
662
+ register(start, len, utf) {
663
+ const enc = Number(utf) === 16 ? "utf-16le" : "utf-8";
664
+ const bytes = new Uint8Array(this.bridge.memory.buffer, Number(start), Number(len));
665
+ const source = new TextDecoder(enc).decode(bytes);
666
+ return this.heap.create(FunctionRegistry.compile(source));
667
+ }
668
+
669
+ /** function_allocate_external_pointer → an empty handle MakeFunction fills later. */
670
+ allocate() {
671
+ return this.heap.create(null);
672
+ }
673
+
674
+ /** host_unregister_function. */
675
+ unregister(handle) {
676
+ this.heap.destroy(BigInt(handle));
677
+ }
678
+
679
+ #call(handle, pPtr, pLen) {
680
+ const fn = this.heap.get(BigInt(handle));
681
+ if (!fn) throw new Error(`invoke: no function for handle ${handle}`);
682
+ return fn.apply(this.context, this.params.parse(pPtr, pLen));
683
+ }
684
+
685
+ /** Generic host_invoke_function → MemoryId of the encoded ReturnValues (or -1n). */
686
+ invoke(handle, pPtr, pLen, rPtr, rLen) {
687
+ const hint = this.hints.parse(rPtr, rLen);
688
+ const result = this.#call(handle, pPtr, pLen);
689
+ // immediate() owns the no-value convention: only a None HINT yields -1n. An
690
+ // undefined result under a One(None) hint still encodes a framed None reply —
691
+ // the module dereferences the returned slot id (megatron with_return parity).
692
+ const reply = this.reply.immediate(hint, result, true);
693
+ return typeof reply === "bigint" ? reply : BigInt(reply);
694
+ }
695
+
696
+ /**
697
+ * Naked typed invoke: call the fn and return the value raw per `returnTypeId`
698
+ * (Object/DOMObject intern into their heap and the handle crosses). Public so the
699
+ * DOM layer can wire `host_invoke_function_as_dom` (ReturnType.DOMObject).
700
+ */
701
+ invokeNakedAs(handle, pPtr, pLen, returnTypeId) {
702
+ const hint = { id: ReturnIds.One, states: [{ stateId: ThreeStateId.One, types: [returnTypeId] }] };
703
+ return this.reply.immediate(hint, this.#call(handle, pPtr, pLen), false);
704
+ }
705
+
706
+ /**
707
+ * `host_invoke_async_function`: call a fn that returns a Promise. Params + return hint
708
+ * are read from WASM memory SYNCHRONOUSLY (before any await); when the promise settles
709
+ * the framed reply is delivered to WASM via `invoke_callback`. A `None` hint is
710
+ * fire-and-forget (mirror of megatron — the promise result is discarded).
711
+ */
712
+ invokeAsync(handle, callbackHandle, pPtr, pLen, rPtr, rLen) {
713
+ const hint = this.hints.parse(rPtr, rLen);
714
+ const result = this.#call(handle, pPtr, pLen);
715
+ if (hint.id === ReturnIds.None) return; // fire-and-forget
716
+ const callbackId = BigInt(callbackHandle);
717
+ const settled = Promise.resolve(result).then(
718
+ (value) => this.reply.callbackSuccess(this.callbacks, callbackId, hint, value),
719
+ (error) => this.reply.callbackFailure(this.callbacks, callbackId, error),
720
+ );
721
+ if (this.tasks) this.tasks.add(settled);
722
+ }
723
+
724
+ invokeAsBool(handle, pPtr, pLen) { return this.invokeNakedAs(handle, pPtr, pLen, ReturnType.Bool) ? 1 : 0; }
725
+ invokeAsFloat(handle, pPtr, pLen) { return Number(this.invokeNakedAs(handle, pPtr, pLen, ReturnType.Float64)); }
726
+ invokeAsInt(handle, pPtr, pLen) { const v = this.invokeNakedAs(handle, pPtr, pLen, ReturnType.Int64); return typeof v === "bigint" ? Number(v) : v; }
727
+ invokeAsBigInt(handle, pPtr, pLen) { const v = this.invokeNakedAs(handle, pPtr, pLen, ReturnType.Uint64); return typeof v === "bigint" ? v : BigInt(v); }
728
+ /** Object fast-path: the result interns into the object heap; its handle crosses naked. */
729
+ invokeAsObject(handle, pPtr, pLen) { const v = this.invokeNakedAs(handle, pPtr, pLen, ReturnType.Object); return typeof v === "bigint" ? v : BigInt(v); }
730
+
731
+ /**
732
+ * String fast-path (megatron `as_str`): the result string's RAW UTF-8 bytes go into
733
+ * a fresh arena slot (no reply framing) and the slot id crosses.
734
+ */
735
+ invokeAsString(handle, pPtr, pLen) {
736
+ const bytes = new TextEncoder().encode(String(this.#call(handle, pPtr, pLen)));
737
+ const slot = this.reply.memory.create(bytes.length);
738
+ this.reply.memory.write(slot, bytes);
739
+ return slot;
740
+ }
741
+
742
+ // ── Context `as*` helpers (megatron middleware parity) ──────────────────────────
743
+ // Registered functions run with `this` = the context (this registry by default) and
744
+ // build PRE-TYPED return slots with these, e.g. `return this.asUint8(10)`. Each
745
+ // yields a ReplyContainer the encoder passes through without hint inference.
746
+
747
+ asNone() { return new ReplyContainer(ReturnType.None, undefined); }
748
+ asBool(v) { return new ReplyContainer(ReturnType.Bool, Boolean(v)); }
749
+ asText8(v) { return new ReplyContainer(ReturnType.Text8, String(v)); }
750
+ asInt8(v) { return new ReplyContainer(ReturnType.Int8, v); }
751
+ asInt16(v) { return new ReplyContainer(ReturnType.Int16, v); }
752
+ asInt32(v) { return new ReplyContainer(ReturnType.Int32, v); }
753
+ asInt64(v) { return new ReplyContainer(ReturnType.Int64, BigInt(v)); }
754
+ asUint8(v) { return new ReplyContainer(ReturnType.Uint8, v); }
755
+ asUint16(v) { return new ReplyContainer(ReturnType.Uint16, v); }
756
+ asUint32(v) { return new ReplyContainer(ReturnType.Uint32, v); }
757
+ asUint64(v) { return new ReplyContainer(ReturnType.Uint64, BigInt(v)); }
758
+ asFloat32(v) { return new ReplyContainer(ReturnType.Float32, v); }
759
+ asFloat64(v) { return new ReplyContainer(ReturnType.Float64, v); }
760
+ asInt128(lsb, msb = 0) {
761
+ return new ReplyContainer(
762
+ ReturnType.Int128,
763
+ (BigInt(msb) << 64n) | (BigInt(lsb) & 0xffffffffffffffffn),
764
+ );
765
+ }
766
+ asUint128(lsb, msb = 0) {
767
+ return new ReplyContainer(
768
+ ReturnType.Uint128,
769
+ (BigInt(msb) << 64n) | (BigInt(lsb) & 0xffffffffffffffffn),
770
+ );
771
+ }
772
+ asErrorCode(v) {
773
+ return new ReplyContainer(ReturnType.ErrorCode, v instanceof ErrorCodeValue ? v.code : v);
774
+ }
775
+ asReplyError(code) { return new ReplyError(code); }
776
+
777
+ /** Intern a JS object in the host object heap → pre-typed Object container. */
778
+ asObject(value) {
779
+ if (typeof value !== "object" || value === null) {
780
+ throw new Error("Value must be a JS Object/object");
781
+ }
782
+ if (!this.reply.objects) throw new Error("asObject: no object heap wired");
783
+ return new ReplyContainer(ReturnType.Object, new ExternalPointer(this.reply.objects.create(value)));
784
+ }
785
+
786
+ /** Intern a DOM node in the host DOM heap → pre-typed DOMObject container. */
787
+ asDOMObject(value) {
788
+ if (!this.reply.dom) throw new Error("asDOMObject: no DOM heap wired");
789
+ return new ReplyContainer(ReturnType.DOMObject, new InternalPointer(this.reply.dom.create(value)));
790
+ }
791
+
792
+ /** A FakeNode (non-DOM host stand-in) interned as a DOMObject. */
793
+ asFakeNode(tag) {
794
+ if (typeof tag !== "string") throw new Error("Value must be a JS string");
795
+ return this.asDOMObject(new FakeNode(tag));
796
+ }
797
+
798
+ /** An existing arena-slot id (or raw bytes) as a MemorySlice return. */
799
+ asMemorySlice(value) {
800
+ const id = typeof value === "bigint" || typeof value === "number" ? BigInt(value) : value;
801
+ return new ReplyContainer(ReturnType.MemorySlice, id);
802
+ }
803
+
804
+ asTypedArraySlice(sliceType, content) {
805
+ return new ReplyContainer(ReturnType.TypedArraySlice, new TypedArraySliceValue(sliceType, content));
806
+ }
807
+
808
+ asInternalReference(v) {
809
+ return new ReplyContainer(
810
+ ReturnType.InternalReference,
811
+ v instanceof RefPointer ? v : new InternalPointer(BigInt(v)),
812
+ );
813
+ }
814
+
815
+ asExternalReference(v) {
816
+ return new ReplyContainer(
817
+ ReturnType.ExternalReference,
818
+ v instanceof RefPointer ? v : new ExternalPointer(BigInt(v)),
819
+ );
820
+ }
821
+
822
+ // Typed-array returns ride MemorySlice (raw bytes) under the current contract.
823
+ #asArray(Ctor, v) {
824
+ if (!(v instanceof Ctor)) throw new Error(`Value must be a ${Ctor.name}`);
825
+ return new ReplyContainer(ReturnType.MemorySlice, new Uint8Array(v.buffer, v.byteOffset, v.byteLength));
826
+ }
827
+ asUint8Array(v) { return this.#asArray(Uint8Array, v); }
828
+ asUint16Array(v) { return this.#asArray(Uint16Array, v); }
829
+ asUint32Array(v) { return this.#asArray(Uint32Array, v); }
830
+ asUint64Array(v) { return this.#asArray(BigUint64Array, v); }
831
+ asInt8Array(v) { return this.#asArray(Int8Array, v); }
832
+ asInt16Array(v) { return this.#asArray(Int16Array, v); }
833
+ asInt32Array(v) { return this.#asArray(Int32Array, v); }
834
+ asInt64Array(v) { return this.#asArray(BigInt64Array, v); }
835
+ asFloat32Array(v) { return this.#asArray(Float32Array, v); }
836
+ asFloat64Array(v) { return this.#asArray(Float64Array, v); }
837
+ }
838
+
839
+ // ════════════════════════════════════════════════════════════════════════════════
840
+ // SECTION 2: V2 quantized batch codec (formerly batch-instructions.js)
841
+ // ════════════════════════════════════════════════════════════════════════════════
842
+
843
+ // V2 batch codec — the V2 quantized batch codec (ported from megatron's
844
+ // ParameterParserV2 + BatchInstructions + BatchOperation, per feature 17 research docs).
845
+ //
846
+ // This is the backbone of the custom binary protocol: WASM builds an instruction batch
847
+ // (Rust `Instructions`, ops.rs) in TWO arena slots — an OPS buffer of opcodes/markers
848
+ // and a TEXTS buffer of raw UTF-8 — and ships both via `host_batch_apply` (no results)
849
+ // or `host_batch_returning_apply` (group-return slot id). DISTINCT from the flat invoke
850
+ // codec (V1, section 1): batch params are marker-framed AND quantized.
851
+ //
852
+ // Wire layout (Rust `Batchable` impls are the source of truth):
853
+ // ops = [Operations.Begin=0] (op…)* [Operations.Stop=255]
854
+ // op = [opId:u8] [payload…] [Operations.End=254]
855
+ // MakeFunction payload = [ParamType.ExternalReference=15][TQ][handle]
856
+ // [ParamType.Text8=3][index:u64 raw][len:u64 raw] (into TEXTS)
857
+ // Invoke payload = [15][TQ][handle] [return-hint frame 200..201] [args]
858
+ // InvokeAsync payload = [15][TQ][handle] [26][TQ][callback] [hint] [args]
859
+ // args = [ArgStart=1] ([ArgBegin=2][ParamType][TQ?][value][ArgEnd=3])* [ArgStop=4]
860
+ // Quantized values carry a TypeOptimization byte; Bool/Int8/Uint8/Float32 never do.
861
+
862
+
863
+
864
+ // ─── Shared discriminants (cross-language contract, base.rs) ────────────────────
865
+ export const Operations = Object.freeze({
866
+ Begin: 0, MakeFunction: 1, Invoke: 2, InvokeAsync: 3, End: 254, Stop: 255,
867
+ });
868
+
869
+ export const ArgumentOperations = Object.freeze({ Start: 1, Begin: 2, End: 3, Stop: 4 });
870
+
871
+ export const TypeOptimization = Object.freeze({
872
+ None: 0,
873
+ QuantizedInt16AsI8: 1, QuantizedInt32AsI8: 2, QuantizedInt32AsI16: 3,
874
+ QuantizedInt64AsI8: 4, QuantizedInt64AsI16: 5, QuantizedInt64AsI32: 6,
875
+ QuantizedUint16AsU8: 7, QuantizedUint32AsU8: 8, QuantizedUint32AsU16: 9,
876
+ QuantizedUint64AsU8: 10, QuantizedUint64AsU16: 11, QuantizedUint64AsU32: 12,
877
+ QuantizedF64AsF32: 13, QuantizedF128AsF32: 14, QuantizedF128AsF64: 15,
878
+ QuantizedInt128AsI8: 16, QuantizedInt128AsI16: 17, QuantizedInt128AsI32: 18,
879
+ QuantizedInt128AsI64: 19, QuantizedUint128AsU8: 20, QuantizedUint128AsU16: 21,
880
+ QuantizedUint128AsU32: 22, QuantizedUint128AsU64: 23,
881
+ QuantizedPtrAsU8: 24, QuantizedPtrAsU16: 25, QuantizedPtrAsU32: 26, QuantizedPtrAsU64: 27,
882
+ });
883
+
884
+ // Group-return frame (Rust GroupReturnHintMarker; protocol.rs GroupReturnTypeHints).
885
+ const GroupReturnHintMarker = Object.freeze({ Start: 111, Stop: 222 });
886
+
887
+ /**
888
+ * Read one TQ-prefixed value: `[TypeOptimization:u8][bytes…]`. `none` reads the value
889
+ * at full width when no quantization was applied; every Quantized* case reads the
890
+ * narrowed width (the Rust `value_quantitization::q*` inverse). → `[newIndex, value]`.
891
+ */
892
+ function readQuantized(view, i, none) {
893
+ const tq = view.getUint8(i);
894
+ i += B1;
895
+ switch (tq) {
896
+ case TypeOptimization.None:
897
+ return none(view, i);
898
+ case TypeOptimization.QuantizedInt16AsI8:
899
+ case TypeOptimization.QuantizedInt32AsI8:
900
+ case TypeOptimization.QuantizedInt64AsI8:
901
+ case TypeOptimization.QuantizedInt128AsI8:
902
+ return [i + B1, view.getInt8(i)];
903
+ case TypeOptimization.QuantizedInt32AsI16:
904
+ case TypeOptimization.QuantizedInt64AsI16:
905
+ case TypeOptimization.QuantizedInt128AsI16:
906
+ return [i + B2, view.getInt16(i, true)];
907
+ case TypeOptimization.QuantizedInt64AsI32:
908
+ case TypeOptimization.QuantizedInt128AsI32:
909
+ return [i + B4, view.getInt32(i, true)];
910
+ case TypeOptimization.QuantizedInt128AsI64:
911
+ return [i + B8, view.getBigInt64(i, true)];
912
+ case TypeOptimization.QuantizedUint16AsU8:
913
+ case TypeOptimization.QuantizedUint32AsU8:
914
+ case TypeOptimization.QuantizedUint64AsU8:
915
+ case TypeOptimization.QuantizedUint128AsU8:
916
+ case TypeOptimization.QuantizedPtrAsU8:
917
+ return [i + B1, view.getUint8(i)];
918
+ case TypeOptimization.QuantizedUint32AsU16:
919
+ case TypeOptimization.QuantizedUint64AsU16:
920
+ case TypeOptimization.QuantizedUint128AsU16:
921
+ case TypeOptimization.QuantizedPtrAsU16:
922
+ return [i + B2, view.getUint16(i, true)];
923
+ case TypeOptimization.QuantizedUint64AsU32:
924
+ case TypeOptimization.QuantizedUint128AsU32:
925
+ case TypeOptimization.QuantizedPtrAsU32:
926
+ return [i + B4, view.getUint32(i, true)];
927
+ case TypeOptimization.QuantizedUint128AsU64:
928
+ case TypeOptimization.QuantizedPtrAsU64:
929
+ return [i + B8, view.getBigUint64(i, true)];
930
+ case TypeOptimization.QuantizedF64AsF32:
931
+ case TypeOptimization.QuantizedF128AsF32:
932
+ return [i + B4, view.getFloat32(i, true)];
933
+ case TypeOptimization.QuantizedF128AsF64:
934
+ return [i + B8, view.getFloat64(i, true)];
935
+ default:
936
+ throw new Error(`readQuantized: unknown TypeOptimization ${tq}`);
937
+ }
938
+ }
939
+
940
+ // Full-width readers for the TypeOptimization.None case, one per declared type.
941
+ const noneI16 = (v, i) => [i + B2, v.getInt16(i, true)];
942
+ const noneU16 = (v, i) => [i + B2, v.getUint16(i, true)];
943
+ const noneI32 = (v, i) => [i + B4, v.getInt32(i, true)];
944
+ const noneU32 = (v, i) => [i + B4, v.getUint32(i, true)];
945
+ const noneI64 = (v, i) => [i + B8, v.getBigInt64(i, true)];
946
+ const noneU64 = (v, i) => [i + B8, v.getBigUint64(i, true)];
947
+ const noneF64 = (v, i) => [i + B8, v.getFloat64(i, true)];
948
+ // 128-bit: [msb:8][lsb:8] little-endian halves, msb first (ops.rs Int128/Uint128 arms).
949
+ const noneI128 = (v, i) => [i + 16, (v.getBigInt64(i, true) << 64n) | v.getBigUint64(i + B8, true)];
950
+ const noneU128 = (v, i) => [i + 16, (v.getBigUint64(i, true) << 64n) | v.getBigUint64(i + B8, true)];
951
+
952
+ // ─── BatchParameterParser (= ParameterParserV2) ─────────────────────────────────
953
+
954
+ /**
955
+ * Decode the marker-framed, quantized argument list of a batch Invoke/InvokeAsync.
956
+ * Reads from the OPS view; Text8 indexes the TEXTS string; pointer-carrying params
957
+ * (Text16 / TypedArraySlice / *ArrayBuffer) dereference WASM linear memory.
958
+ */
959
+ export class BatchParameterParser {
960
+ /** @param {{memory:WebAssembly.Memory}} bridge @param {StringCache} strings */
961
+ constructor(bridge, strings) {
962
+ this.bridge = bridge;
963
+ this.strings = strings;
964
+ }
965
+
966
+ /**
967
+ * Parse `[ArgBegin][param][ArgEnd]…[ArgStop]` starting AFTER ArgStart.
968
+ * @returns {[number, any[]]} `[indexAfterStop, args]`
969
+ */
970
+ parseParams(view, i, texts) {
971
+ const args = [];
972
+ while (view.getUint8(i) !== ArgumentOperations.Stop) {
973
+ if (view.getUint8(i) !== ArgumentOperations.Begin) {
974
+ throw new Error(`batch args: expected Begin marker, got ${view.getUint8(i)}`);
975
+ }
976
+ i += B1;
977
+ let value;
978
+ [i, value] = this.parseParam(view, i, texts);
979
+ args.push(value);
980
+ if (view.getUint8(i) !== ArgumentOperations.End) {
981
+ throw new Error(`batch args: expected End marker, got ${view.getUint8(i)}`);
982
+ }
983
+ i += B1;
984
+ }
985
+ i += B1; // consume ArgStop
986
+ return [i, args];
987
+ }
988
+
989
+ /** Parse one `[ParamType][TQ?][value]` (after the Begin marker). */
990
+ parseParam(view, i, texts) {
991
+ const type = view.getUint8(i);
992
+ i += B1;
993
+ switch (type) {
994
+ case ParamType.Null: return [i, null];
995
+ case ParamType.Undefined: return [i, undefined];
996
+ case ParamType.Bool: return [i + B1, view.getUint8(i) === 1];
997
+ case ParamType.Int8: return [i + B1, view.getInt8(i)];
998
+ case ParamType.Uint8: return [i + B1, view.getUint8(i)];
999
+ case ParamType.Float32: return [i + B4, view.getFloat32(i, true)];
1000
+ case ParamType.Int16: return readQuantized(view, i, noneI16);
1001
+ case ParamType.Uint16: return readQuantized(view, i, noneU16);
1002
+ case ParamType.Int32: return readQuantized(view, i, noneI32);
1003
+ case ParamType.Uint32: return readQuantized(view, i, noneU32);
1004
+ case ParamType.Int64: return readQuantized(view, i, noneI64);
1005
+ case ParamType.Uint64: return readQuantized(view, i, noneU64);
1006
+ case ParamType.Float64: return readQuantized(view, i, noneF64);
1007
+ case ParamType.Int128: return readQuantized(view, i, noneI128);
1008
+ case ParamType.Uint128: return readQuantized(view, i, noneU128);
1009
+ case ParamType.ErrorCode: {
1010
+ // Rust encodes via qu16 ([TQ][u8|u16]); megatron's parseErrorCode misread this
1011
+ // as a u64 — we decode per the Rust encoder (see LEARNINGS).
1012
+ const [ni, code] = readQuantized(view, i, noneU16);
1013
+ return [ni, new ErrorCodeValue(Number(code))];
1014
+ }
1015
+ case ParamType.CachedText: {
1016
+ const [ni, handle] = readQuantized(view, i, noneU64);
1017
+ const text = this.strings.get(BigInt(handle));
1018
+ if (text === undefined) throw new Error(`batch CachedText: no string for handle ${handle}`);
1019
+ return [ni, text];
1020
+ }
1021
+ case ParamType.ExternalReference: {
1022
+ const [ni, id] = readQuantized(view, i, noneU64);
1023
+ return [ni, new ExternalPointer(BigInt(id))];
1024
+ }
1025
+ case ParamType.InternalReference: {
1026
+ const [ni, id] = readQuantized(view, i, noneU64);
1027
+ return [ni, new InternalPointer(BigInt(id))];
1028
+ }
1029
+ case ParamType.Text8: {
1030
+ // Two TQ'd u64s: (index, length) into the TEXTS string (NOT WASM memory).
1031
+ let index, length;
1032
+ [i, index] = readQuantized(view, i, noneU64);
1033
+ [i, length] = readQuantized(view, i, noneU64);
1034
+ return [i, texts.substr(Number(index), Number(length))];
1035
+ }
1036
+ case ParamType.Text16: {
1037
+ // TQ'd pointer into WASM memory + TQ'd u16-unit count (megatron ×2 multiplier).
1038
+ let ptr, length;
1039
+ [i, ptr] = readQuantized(view, i, noneU64);
1040
+ [i, length] = readQuantized(view, i, noneU64);
1041
+ const bytes = new Uint8Array(this.bridge.memory.buffer, Number(ptr), Number(length) * 2);
1042
+ return [i, new TextDecoder("utf-16le").decode(bytes)];
1043
+ }
1044
+ case ParamType.TypedArraySlice: {
1045
+ const sliceType = view.getUint8(i);
1046
+ i += B1;
1047
+ let ptr, length; // length is in BYTES (Rust passes a byte slice)
1048
+ [i, ptr] = readQuantized(view, i, noneU64);
1049
+ [i, length] = readQuantized(view, i, noneU64);
1050
+ const copy = this.bridge.memory.buffer.slice(Number(ptr), Number(ptr) + Number(length));
1051
+ const Ctor = TypedSliceArray[sliceType] ?? Uint8Array;
1052
+ return [i, new TypedArraySliceValue(sliceType, new Ctor(copy))];
1053
+ }
1054
+ default: {
1055
+ // *ArrayBuffer (16–25): TQ'd pointer + TQ'd ELEMENT count into WASM memory.
1056
+ const Ctor = BATCH_ARRAY_CTORS[type];
1057
+ if (!Ctor) throw new Error(`batch param: unknown ParamType ${type}`);
1058
+ let ptr, length;
1059
+ [i, ptr] = readQuantized(view, i, noneU64);
1060
+ [i, length] = readQuantized(view, i, noneU64);
1061
+ const start = Number(ptr);
1062
+ const copy = this.bridge.memory.buffer.slice(start, start + Number(length) * Ctor.BYTES_PER_ELEMENT);
1063
+ return [i, new Ctor(copy)];
1064
+ }
1065
+ }
1066
+ }
1067
+ }
1068
+
1069
+ const BATCH_ARRAY_CTORS = {
1070
+ [ParamType.Uint8Array]: Uint8Array, [ParamType.Uint16Array]: Uint16Array,
1071
+ [ParamType.Uint32Array]: Uint32Array, [ParamType.Uint64Array]: BigUint64Array,
1072
+ [ParamType.Int8Array]: Int8Array, [ParamType.Int16Array]: Int16Array,
1073
+ [ParamType.Int32Array]: Int32Array, [ParamType.Int64Array]: BigInt64Array,
1074
+ [ParamType.Float32Array]: Float32Array, [ParamType.Float64Array]: Float64Array,
1075
+ };
1076
+
1077
+ // ─── BatchInstructions ───────────────────────────────────────────────────────────
1078
+
1079
+ const MAKE_FUNCTION_HINT = Object.freeze({
1080
+ id: ReturnIds.One,
1081
+ states: [{ stateId: ThreeStateId.One, types: [ReturnType.ExternalReference] }],
1082
+ });
1083
+
1084
+ /**
1085
+ * Parses + executes instruction batches (the `host_batch_apply` /
1086
+ * `host_batch_returning_apply` imports). Mirrors megatron's two-phase design:
1087
+ * a parse pass turns each op into a thunk, then the thunks run in order — so a
1088
+ * MakeFunction earlier in the batch is visible to an Invoke later in it.
1089
+ *
1090
+ * Extension point: `registerOperation(opId, handler)` adds custom opcodes (the DOM
1091
+ * layer registers its own). A handler is `(batch, opId, i, view, texts) => [newIndex,
1092
+ * thunk|null]`; a thunk is `(batch) => ({hint, value} | null)`.
1093
+ */
1094
+ export class BatchInstructions {
1095
+ /**
1096
+ * @param {{exports:object, memory:WebAssembly.Memory}} bridge
1097
+ * @param {MemoryAllocations} memory
1098
+ * @param {StringCache} strings
1099
+ * @param {FunctionRegistry} functions
1100
+ * @param {CallbackRegistry} callbacks
1101
+ */
1102
+ constructor(bridge, memory, strings, functions, callbacks) {
1103
+ this.bridge = bridge;
1104
+ this.memory = memory;
1105
+ this.functions = functions;
1106
+ this.callbacks = callbacks;
1107
+ this.reply = functions.reply; // share the ReturnValues encoder (one contract)
1108
+ this.params = new BatchParameterParser(bridge, strings);
1109
+ this.operations = new Map([
1110
+ [Operations.MakeFunction, BatchInstructions.makeFunction],
1111
+ [Operations.Invoke, BatchInstructions.invoke],
1112
+ [Operations.InvokeAsync, BatchInstructions.invokeAsync],
1113
+ ]);
1114
+ }
1115
+
1116
+ registerOperation(opId, handler) {
1117
+ this.operations.set(opId, handler);
1118
+ return this;
1119
+ }
1120
+
1121
+ /** host_batch_apply: parse + run every op; results are discarded. */
1122
+ applyNoReturn(opsPtr, opsLen, textPtr, textLen) {
1123
+ for (const thunk of this.#parse(opsPtr, opsLen, textPtr, textLen)) {
1124
+ thunk(this);
1125
+ }
1126
+ }
1127
+
1128
+ /**
1129
+ * host_batch_returning_apply: run every op, encode each non-null result into its own
1130
+ * framed ReturnValues slot, then write the group-return frame
1131
+ * `[Start=111]([ReturnIds][Multi: count:u16][ThreeStates…][slot_id:u64])*[Stop=222]`
1132
+ * into a fresh slot → its id (or -1n when nothing returned). Decoded by Rust
1133
+ * `GroupReturnTypeHints::from_binary`.
1134
+ */
1135
+ applyReturning(opsPtr, opsLen, textPtr, textLen) {
1136
+ const results = [];
1137
+ for (const thunk of this.#parse(opsPtr, opsLen, textPtr, textLen)) {
1138
+ const result = thunk(this);
1139
+ if (result === null || result === undefined) continue;
1140
+ const memId = this.reply.immediate(result.hint, result.value, true);
1141
+ results.push({ hint: result.hint, memId: BigInt(memId) });
1142
+ }
1143
+ if (results.length === 0) return -1n;
1144
+
1145
+ const out = [GroupReturnHintMarker.Start];
1146
+ for (const { hint, memId } of results) {
1147
+ out.push(hint.id);
1148
+ if (hint.id === ReturnIds.Multi) {
1149
+ out.push(Number(hint.states.length & 0xff), Number((hint.states.length >> 8) & 0xff));
1150
+ }
1151
+ for (const state of hint.states) {
1152
+ out.push(state.stateId, ...state.types);
1153
+ }
1154
+ for (let k = 0; k < 8; k++) out.push(Number((memId >> BigInt(8 * k)) & 0xffn));
1155
+ }
1156
+ out.push(GroupReturnHintMarker.Stop);
1157
+
1158
+ const bytes = Uint8Array.from(out);
1159
+ const slot = this.memory.create(bytes.length);
1160
+ this.memory.write(slot, bytes);
1161
+ return slot;
1162
+ }
1163
+
1164
+ /** Read both buffers (ops as a detached copy — thunks may grow WASM memory), parse all ops. */
1165
+ #parse(opsPtr, opsLen, textPtr, textLen) {
1166
+ const opsStart = Number(opsPtr);
1167
+ const ops = this.bridge.memory.buffer.slice(opsStart, opsStart + Number(opsLen));
1168
+ const textStart = Number(textPtr);
1169
+ const textBytes = new Uint8Array(this.bridge.memory.buffer, textStart, Number(textLen));
1170
+ const texts = new TextDecoder().decode(textBytes);
1171
+
1172
+ const view = new DataView(ops);
1173
+ let i = 0;
1174
+ if (view.getUint8(i) !== Operations.Begin) {
1175
+ throw new Error(`batch: expected Operations.Begin, got ${view.getUint8(i)}`);
1176
+ }
1177
+ i += B1;
1178
+
1179
+ const thunks = [];
1180
+ while (i < view.byteLength && view.getUint8(i) !== Operations.Stop) {
1181
+ const opId = view.getUint8(i);
1182
+ i += B1;
1183
+ const handler = this.operations.get(opId);
1184
+ if (!handler) throw new Error(`batch: unhandled operation ${opId}`);
1185
+ let thunk;
1186
+ [i, thunk] = handler(this, opId, i, view, texts);
1187
+ if (thunk) thunks.push(thunk);
1188
+ }
1189
+ return thunks;
1190
+ }
1191
+
1192
+ /** Read `[ParamType.ExternalReference][TQ][handle]` → bigint handle. */
1193
+ static readExternalHandle(view, i) {
1194
+ const vt = view.getUint8(i);
1195
+ if (vt !== ParamType.ExternalReference) {
1196
+ throw new Error(`batch: expected ExternalReference param, got ${vt}`);
1197
+ }
1198
+ const [ni, raw] = readQuantized(view, i + B1, noneU64);
1199
+ return [ni, BigInt(raw)];
1200
+ }
1201
+
1202
+ /** MakeFunction: compile TEXTS[index..len] and bind it at the pre-allocated handle. */
1203
+ static makeFunction(batch, _opId, i, view, texts) {
1204
+ let handle;
1205
+ [i, handle] = BatchInstructions.readExternalHandle(view, i);
1206
+
1207
+ if (view.getUint8(i) !== ParamType.Text8) {
1208
+ throw new Error(`batch MakeFunction: expected Text8, got ${view.getUint8(i)}`);
1209
+ }
1210
+ i += B1;
1211
+ // Raw (unquantized) u64 pair — register_function writes plain to_le_bytes.
1212
+ const index = Number(view.getBigUint64(i, true));
1213
+ i += B8;
1214
+ const length = Number(view.getBigUint64(i, true));
1215
+ i += B8;
1216
+
1217
+ if (view.getUint8(i) !== Operations.End) {
1218
+ throw new Error(`batch MakeFunction: expected Operations.End, got ${view.getUint8(i)}`);
1219
+ }
1220
+ i += B1;
1221
+
1222
+ const source = texts.substr(index, length);
1223
+ const thunk = (b) => {
1224
+ const fn = b.functions.constructor.compile(source);
1225
+ b.functions.heap.update(handle, fn);
1226
+ return { hint: MAKE_FUNCTION_HINT, value: new ExternalPointer(handle) };
1227
+ };
1228
+ return [i, thunk];
1229
+ }
1230
+
1231
+ /** Shared head of Invoke/InvokeAsync: handle, (callback), hint, args, End. */
1232
+ static parseCallParts(batch, i, view, texts, hasCallback) {
1233
+ let handle;
1234
+ [i, handle] = BatchInstructions.readExternalHandle(view, i);
1235
+
1236
+ let callbackId = null;
1237
+ if (hasCallback) {
1238
+ const vt = view.getUint8(i);
1239
+ if (vt !== ParamType.InternalReference) {
1240
+ throw new Error(`batch: expected InternalReference param, got ${vt}`);
1241
+ }
1242
+ let raw;
1243
+ [i, raw] = readQuantized(view, i + B1, noneU64);
1244
+ callbackId = BigInt(raw);
1245
+ }
1246
+
1247
+ let hint;
1248
+ [i, hint] = ReturnHintParser.parseFrom(view, i);
1249
+
1250
+ if (view.getUint8(i) !== ArgumentOperations.Start) {
1251
+ throw new Error(`batch args: expected Start marker, got ${view.getUint8(i)}`);
1252
+ }
1253
+ i += B1;
1254
+ let args;
1255
+ [i, args] = batch.params.parseParams(view, i, texts);
1256
+
1257
+ if (view.getUint8(i) !== Operations.End) {
1258
+ throw new Error(`batch: expected Operations.End, got ${view.getUint8(i)}`);
1259
+ }
1260
+ i += B1;
1261
+
1262
+ return [i, handle, callbackId, hint, args];
1263
+ }
1264
+
1265
+ static invoke(batch, _opId, i, view, texts) {
1266
+ let handle, hint, args;
1267
+ [i, handle, , hint, args] = BatchInstructions.parseCallParts(batch, i, view, texts, false);
1268
+
1269
+ const thunk = (b) => {
1270
+ const fn = b.functions.heap.get(handle);
1271
+ if (!fn) throw new Error(`batch invoke: no function for handle ${handle}`);
1272
+ const result = fn.apply(b.functions.context, args);
1273
+ if (hint.id === ReturnIds.None) return null;
1274
+ return { hint, value: result };
1275
+ };
1276
+ return [i, thunk];
1277
+ }
1278
+
1279
+ static invokeAsync(batch, _opId, i, view, texts) {
1280
+ let handle, callbackId, hint, args;
1281
+ [i, handle, callbackId, hint, args] = BatchInstructions.parseCallParts(batch, i, view, texts, true);
1282
+
1283
+ const thunk = (b) => {
1284
+ const fn = b.functions.heap.get(handle);
1285
+ if (!fn) throw new Error(`batch invokeAsync: no function for handle ${handle}`);
1286
+ const result = fn.apply(b.functions.context, args);
1287
+ if (hint.id === ReturnIds.None) return null; // fire-and-forget
1288
+ const settled = Promise.resolve(result).then(
1289
+ (value) => b.reply.callbackSuccess(b.callbacks, callbackId, hint, value),
1290
+ (error) => b.reply.callbackFailure(b.callbacks, callbackId, error),
1291
+ );
1292
+ if (b.functions.tasks) b.functions.tasks.add(settled);
1293
+ return null; // delivery happens via invoke_callback, never inline
1294
+ };
1295
+ return [i, thunk];
1296
+ }
1297
+ }
1298
+
1299
+ // ════════════════════════════════════════════════════════════════════════════════
1300
+ // SECTION 3: core runtime
1301
+ // ════════════════════════════════════════════════════════════════════════════════
1302
+
1303
+ // ─── WasmEnvelope ──────────────────────────────────────────────────────────────
1304
+
1305
+ /**
1306
+ * The 14-byte WASM message header — mirror of `foundation_wasm::WasmEnvelope`.
1307
+ * Layout (little-endian): [protocol:1][version:1][memory_id:8][length:4][payload...]
1308
+ */
1309
+ export class WasmEnvelope {
1310
+ static HEADER_LEN = 14;
1311
+
1312
+ /**
1313
+ * Frame a payload into a fresh Uint8Array.
1314
+ * @param {number} protocol protocol byte (0/1/2)
1315
+ * @param {number} version protocol version
1316
+ * @param {bigint|number} memoryId arena slot id (u64)
1317
+ * @param {Uint8Array} payload
1318
+ * @returns {Uint8Array}
1319
+ */
1320
+ static write(protocol, version, memoryId, payload) {
1321
+ const buf = new Uint8Array(WasmEnvelope.HEADER_LEN + payload.length);
1322
+ const view = new DataView(buf.buffer);
1323
+ view.setUint8(0, protocol);
1324
+ view.setUint8(1, version);
1325
+ view.setBigUint64(2, BigInt(memoryId), true);
1326
+ view.setUint32(10, payload.length, true);
1327
+ buf.set(payload, WasmEnvelope.HEADER_LEN);
1328
+ return buf;
1329
+ }
1330
+
1331
+ /**
1332
+ * Parse the header (zero-copy payload view).
1333
+ * @param {ArrayBuffer|Uint8Array} bytes
1334
+ * @param {number} [byteOffset] offset when `bytes` is an ArrayBuffer
1335
+ * @returns {{ protocol:number, version:number, memoryId:bigint, length:number, payload:Uint8Array }}
1336
+ */
1337
+ static parse(bytes, byteOffset = 0) {
1338
+ const u8 = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes, byteOffset);
1339
+ if (u8.length < WasmEnvelope.HEADER_LEN) {
1340
+ throw new RangeError("WasmEnvelope: buffer shorter than 14-byte header");
1341
+ }
1342
+ const view = new DataView(u8.buffer, u8.byteOffset, u8.byteLength);
1343
+ const protocol = view.getUint8(0);
1344
+ const version = view.getUint8(1);
1345
+ const memoryId = view.getBigUint64(2, true);
1346
+ const length = view.getUint32(10, true);
1347
+ const end = WasmEnvelope.HEADER_LEN + length;
1348
+ if (u8.length < end) {
1349
+ throw new RangeError("WasmEnvelope: payload length exceeds buffer");
1350
+ }
1351
+ return { protocol, version, memoryId, length, payload: u8.subarray(WasmEnvelope.HEADER_LEN, end) };
1352
+ }
1353
+ }
1354
+
1355
+ // ─── ProtocolDispatcher ──────────────────────────────────────────────────────────
1356
+
1357
+ /**
1358
+ * Reads the protocol byte from an incoming message and routes it to the matching
1359
+ * handler `{ apply(memoryId: bigint, payload: Uint8Array) }`.
1360
+ *
1361
+ * Mirror of `foundation_wasm::dispatch_message` — same demux, same throw-on-unknown.
1362
+ */
1363
+ export class ProtocolDispatcher {
1364
+ /** @param {Record<number, {apply:Function}>} handlers keyed by protocol byte */
1365
+ constructor(handlers = {}) {
1366
+ this.handlers = handlers;
1367
+ }
1368
+
1369
+ setHandler(protocol, handler) {
1370
+ this.handlers[protocol] = handler;
1371
+ return this;
1372
+ }
1373
+
1374
+ /** Install a reader for a self-identifying binary format. Other messages use the envelope. */
1375
+ setRawHandler(matches, apply) {
1376
+ this.rawHandler = { matches, apply };
1377
+ }
1378
+
1379
+ /** @param {ArrayBuffer|Uint8Array} buffer */
1380
+ dispatch(buffer) {
1381
+ if (this.rawHandler?.matches(buffer)) return this.rawHandler.apply(buffer);
1382
+ const { protocol, memoryId, payload } = WasmEnvelope.parse(buffer);
1383
+ const handler = this.handlers[protocol];
1384
+ if (!handler) {
1385
+ throw new Error(`unknown protocol: ${protocol}`);
1386
+ }
1387
+ return handler.apply(memoryId, payload);
1388
+ }
1389
+ }
1390
+
1391
+ // ─── MemoryAllocations ───────────────────────────────────────────────────────────
1392
+
1393
+ /**
1394
+ * JS view over the WASM arena. Reads the bridge lazily so it keeps working after the
1395
+ * instance is wired in `FoundationWasm.init`. Slot ids are u64 (`bigint`);
1396
+ * generation-based ids in the Rust arena make stale access fail safely (decision 028).
1397
+ */
1398
+ export class MemoryAllocations {
1399
+ /** @param {{exports:object, memory:WebAssembly.Memory}} bridge shared, late-populated */
1400
+ constructor(bridge) {
1401
+ this.bridge = bridge;
1402
+ }
1403
+
1404
+ /** Allocate a slot of `size` bytes; returns its id (bigint). */
1405
+ create(size) {
1406
+ return this.bridge.exports.create_allocation(BigInt(size));
1407
+ }
1408
+
1409
+ /**
1410
+ * Resolve a slot id to a live byte view into WASM linear memory (zero-copy).
1411
+ * Valid only until the memory grows or the slot is disposed.
1412
+ * @returns {{ ptr:number, len:number, bytes:Uint8Array }}
1413
+ */
1414
+ get(id) {
1415
+ const ptr = Number(this.bridge.exports.allocation_start_pointer(BigInt(id)));
1416
+ const len = Number(this.bridge.exports.allocation_length(BigInt(id)));
1417
+ return { ptr, len, bytes: new Uint8Array(this.bridge.memory.buffer, ptr, len) };
1418
+ }
1419
+
1420
+ /** Copy `data` into the slot's memory (slot must be ≥ data.length). */
1421
+ write(id, data) {
1422
+ this.get(id).bytes.set(data);
1423
+ }
1424
+
1425
+ /** ACK/free a slot back to the arena. MUST be called after processing a message. */
1426
+ dispose(id) {
1427
+ this.bridge.exports.dispose_allocation(BigInt(id));
1428
+ }
1429
+
1430
+ /** Reset a slot's contents without freeing it. */
1431
+ clear(id) {
1432
+ this.bridge.exports.clear_allocation(BigInt(id));
1433
+ }
1434
+ }
1435
+
1436
+ // ─── TimerRegistry ───────────────────────────────────────────────────────────────
1437
+
1438
+ /**
1439
+ * Implements the `schedule_timeout` / `schedule_interval` host imports using the
1440
+ * platform timers, firing the matching WASM export when they elapse. WASM owns the
1441
+ * callback ids; JS just maps id → live handle so it can cancel.
1442
+ */
1443
+ export class TimerRegistry {
1444
+ /**
1445
+ * @param {{exports:object}} bridge
1446
+ * @param {{setTimeout:Function,clearTimeout:Function,setInterval:Function,clearInterval:Function}} [host]
1447
+ */
1448
+ constructor(bridge, host = globalThis) {
1449
+ this.bridge = bridge;
1450
+ this.host = host;
1451
+ this.timeouts = new Map();
1452
+ this.intervals = new Map();
1453
+ // Set by cancelAll(): nothing scheduled for this instance may call into it
1454
+ // afterwards (queued microtasks cannot be cancelled, so they check this).
1455
+ this.disposed = false;
1456
+ }
1457
+
1458
+ scheduleTimeout(callbackId, delayMs) {
1459
+ if (this.disposed) return;
1460
+ const key = String(callbackId);
1461
+ const handle = this.host.setTimeout(() => {
1462
+ this.timeouts.delete(key);
1463
+ if (this.disposed) return;
1464
+ this.bridge.exports.run_scheduled_callback(BigInt(callbackId));
1465
+ }, delayMs);
1466
+ this.timeouts.set(key, handle);
1467
+ }
1468
+
1469
+ /**
1470
+ * Run the scheduled callback once as a microtask (`schedule_microtask`): right
1471
+ * after the current task, before timers and I/O. Used by the guest to resume
1472
+ * itself from an event-driven wake without the latency of a 0 ms timer.
1473
+ */
1474
+ scheduleMicrotask(callbackId) {
1475
+ if (this.disposed) return;
1476
+ const queue = this.host.queueMicrotask
1477
+ ? this.host.queueMicrotask.bind(this.host)
1478
+ : (fn) => Promise.resolve().then(fn);
1479
+ queue(() => {
1480
+ if (this.disposed) return;
1481
+ this.bridge.exports.run_scheduled_callback(BigInt(callbackId));
1482
+ });
1483
+ }
1484
+
1485
+ cancelTimeout(callbackId) {
1486
+ const key = String(callbackId);
1487
+ const handle = this.timeouts.get(key);
1488
+ if (handle !== undefined) {
1489
+ this.host.clearTimeout(handle);
1490
+ this.timeouts.delete(key);
1491
+ }
1492
+ }
1493
+
1494
+ scheduleInterval(callbackId, intervalMs) {
1495
+ if (this.disposed) return;
1496
+ const key = String(callbackId);
1497
+ const handle = this.host.setInterval(() => {
1498
+ // run_interval_callback returns 0 (STOP) when the callback asked to stop.
1499
+ if (Number(this.bridge.exports.run_interval_callback(BigInt(callbackId))) === 0) {
1500
+ this.cancelInterval(callbackId);
1501
+ }
1502
+ }, intervalMs);
1503
+ this.intervals.set(key, handle);
1504
+ }
1505
+
1506
+ cancelInterval(callbackId) {
1507
+ const key = String(callbackId);
1508
+ const handle = this.intervals.get(key);
1509
+ if (handle !== undefined) {
1510
+ this.host.clearInterval(handle);
1511
+ this.intervals.delete(key);
1512
+ }
1513
+ }
1514
+
1515
+ /**
1516
+ * Cancel every pending timeout and interval and refuse new ones: the instance
1517
+ * these callbacks would run in is being discarded. Without this, a timer the
1518
+ * guest scheduled keeps the old instance alive and calls into it later — after
1519
+ * its owner has moved on (e.g. the `#[wasm_test]` runner's next case).
1520
+ */
1521
+ cancelAll() {
1522
+ this.disposed = true;
1523
+ for (const handle of this.timeouts.values()) this.host.clearTimeout(handle);
1524
+ for (const handle of this.intervals.values()) this.host.clearInterval(handle);
1525
+ this.timeouts.clear();
1526
+ this.intervals.clear();
1527
+ }
1528
+ }
1529
+
1530
+ // ─── CallbackRegistry ────────────────────────────────────────────────────────────
1531
+
1532
+ /**
1533
+ * Delivers async JS→WASM responses. WASM hands JS a callback id (its
1534
+ * `InternalPointer`); when the JS-side work resolves, JS writes the (already
1535
+ * protocol-encoded) result into a fresh arena slot and calls `invoke_callback`.
1536
+ * Monotonic ids in the Rust registry make stale invocations drop silently.
1537
+ */
1538
+ export class CallbackRegistry {
1539
+ /** @param {{exports:object}} bridge @param {MemoryAllocations} memory */
1540
+ constructor(bridge, memory) {
1541
+ this.bridge = bridge;
1542
+ this.memory = memory;
1543
+ }
1544
+
1545
+ /** Deliver `data` (Uint8Array) to WASM callback `id`. */
1546
+ invoke(id, data) {
1547
+ const slot = this.memory.create(data.length);
1548
+ this.memory.write(slot, data);
1549
+ this.bridge.exports.invoke_callback(BigInt(id), BigInt(slot));
1550
+ }
1551
+
1552
+ /** Permanently retire a WASM callback id (never reused). */
1553
+ unregister(id) {
1554
+ this.bridge.exports.unregister_callback(BigInt(id));
1555
+ }
1556
+ }
1557
+
1558
+ // ─── StringCache ─────────────────────────────────────────────────────────────────
1559
+
1560
+ /**
1561
+ * Interns UTF-8/UTF-16 strings that WASM caches via the `host_cache_string` import,
1562
+ * returning a stable `bigint` handle reused for identical strings. The handle is how
1563
+ * `CachedText` params later refer to the string without re-sending the bytes.
1564
+ */
1565
+ export class StringCache {
1566
+ /** @param {{memory:WebAssembly.Memory}} bridge */
1567
+ constructor(bridge) {
1568
+ this.bridge = bridge;
1569
+ this.byString = new Map(); // string -> handle (bigint)
1570
+ this.byHandle = new Map(); // handle (bigint) -> string
1571
+ this.next = 1n;
1572
+ }
1573
+
1574
+ /**
1575
+ * Read a string from WASM memory at `(ptr, len)` and intern it.
1576
+ * @param {bigint|number} ptr
1577
+ * @param {bigint|number} len
1578
+ * @param {number} encoding 0 = UTF-8, 1 = UTF-16LE (JSEncoding)
1579
+ * @returns {bigint} stable handle
1580
+ */
1581
+ cache(ptr, len, encoding = 0) {
1582
+ const bytes = new Uint8Array(this.bridge.memory.buffer, Number(ptr), Number(len));
1583
+ const decoder = encoding === 1 ? new TextDecoder("utf-16le") : new TextDecoder();
1584
+ const str = decoder.decode(bytes);
1585
+ let handle = this.byString.get(str);
1586
+ if (handle === undefined) {
1587
+ handle = this.next;
1588
+ this.next += 1n;
1589
+ this.byString.set(str, handle);
1590
+ this.byHandle.set(handle, str);
1591
+ }
1592
+ return handle;
1593
+ }
1594
+
1595
+ /** Resolve a handle back to its string (or `undefined`). */
1596
+ get(handle) {
1597
+ return this.byHandle.get(BigInt(handle));
1598
+ }
1599
+
1600
+ /** Evict an interned string (host_string_cache_drop_external_pointer). */
1601
+ drop(handle) {
1602
+ const key = BigInt(handle);
1603
+ const str = this.byHandle.get(key);
1604
+ if (str === undefined) return false;
1605
+ this.byHandle.delete(key);
1606
+ this.byString.delete(str);
1607
+ return true;
1608
+ }
1609
+ }
1610
+
1611
+ // ─── AnimationDriver ─────────────────────────────────────────────────────────────
1612
+
1613
+ /**
1614
+ * Drives the WASM animation-frame loop. WASM calls the `hook_up_animation_frames`
1615
+ * import when it registers a frame callback; this driver runs a rAF loop that calls
1616
+ * the `trigger_animation_callbacks(timestamp)` export each frame and stops once
1617
+ * `get_total_animation_callbacks()` returns 0 (decision: exposed_runtime semantics).
1618
+ */
1619
+ export class AnimationDriver {
1620
+ /**
1621
+ * @param {{exports:object}} bridge
1622
+ * @param {{request:(cb:(ts:number)=>void)=>any, cancel:(handle:any)=>void}} [raf]
1623
+ */
1624
+ constructor(bridge, raf) {
1625
+ this.bridge = bridge;
1626
+ this.raf = raf ?? defaultRaf();
1627
+ this.running = false;
1628
+ this.handle = null;
1629
+ }
1630
+
1631
+ /** Start the loop. Idempotent — repeated `hook_up` calls keep a single loop. */
1632
+ start() {
1633
+ if (this.running) return;
1634
+ this.running = true;
1635
+ this.#schedule();
1636
+ }
1637
+
1638
+ #schedule() {
1639
+ this.handle = this.raf.request((ts) => this.#frame(ts));
1640
+ }
1641
+
1642
+ #frame(ts) {
1643
+ this.bridge.exports.trigger_animation_callbacks(ts);
1644
+ if (Number(this.bridge.exports.get_total_animation_callbacks()) > 0) {
1645
+ this.#schedule(); // more callbacks pending — next frame
1646
+ } else {
1647
+ this.running = false; // 0 callbacks left — WASM tells JS to stop the loop
1648
+ this.handle = null;
1649
+ }
1650
+ }
1651
+
1652
+ /** Stop the loop early (e.g. teardown). */
1653
+ stop() {
1654
+ if (this.handle !== null) this.raf.cancel(this.handle);
1655
+ this.running = false;
1656
+ this.handle = null;
1657
+ }
1658
+ }
1659
+
1660
+ /** Browser `requestAnimationFrame` when available; a ~16ms timer fallback otherwise. */
1661
+ function defaultRaf() {
1662
+ if (typeof globalThis.requestAnimationFrame === "function") {
1663
+ return {
1664
+ request: (cb) => globalThis.requestAnimationFrame(cb),
1665
+ cancel: (h) => globalThis.cancelAnimationFrame?.(h),
1666
+ };
1667
+ }
1668
+ const now = () => (globalThis.performance?.now?.() ?? Date.now());
1669
+ return {
1670
+ request: (cb) => setTimeout(() => cb(now()), 16),
1671
+ cancel: (h) => clearTimeout(h),
1672
+ };
1673
+ }
1674
+
1675
+ // ─── TestReports (feature 13 — owned #[wasm_test] result protocol) ─────────────────
1676
+
1677
+ /**
1678
+ * Collects `#[wasm_test]` case outcomes delivered by the `host_report` import:
1679
+ * `{ status, message }` with status 0 = pass, 1 = fail, 2 = ignored. A runner
1680
+ * resolves async cases by awaiting `next()` — one report per executed case.
1681
+ */
1682
+ export class TestReports {
1683
+ static PASS = 0;
1684
+ static FAIL = 1;
1685
+ static IGNORED = 2;
1686
+
1687
+ constructor() {
1688
+ this.reports = [];
1689
+ this.waiters = [];
1690
+ // The last report delivered to a waiter. A wasm trap can end the event loop
1691
+ // between the delivery and the awaiting continuation, so this copy keeps the
1692
+ // message readable after the trap (issue #587).
1693
+ this.last = null;
1694
+ }
1695
+
1696
+ /** Record a report (called by the host_report import). */
1697
+ push(status, message) {
1698
+ const report = { status, message };
1699
+ const waiter = this.waiters.shift();
1700
+ if (waiter) {
1701
+ this.last = report;
1702
+ waiter(report);
1703
+ } else this.reports.push(report);
1704
+ }
1705
+
1706
+ /** Resolve with the next report — already-buffered or yet to arrive. */
1707
+ next() {
1708
+ const buffered = this.reports.shift();
1709
+ if (buffered) return Promise.resolve(buffered);
1710
+ // A new case starts here: a report it does not deliver must not show the
1711
+ // previous case's message in a post-trap diagnostic.
1712
+ this.last = null;
1713
+ return new Promise((resolve) => this.waiters.push(resolve));
1714
+ }
1715
+
1716
+ /**
1717
+ * Every report not yet consumed, plus the last one delivered to a waiter.
1718
+ * The runner's post-trap diagnostic reads this (issue #587).
1719
+ */
1720
+ snapshot() {
1721
+ return this.last ? [...this.reports, this.last] : [...this.reports];
1722
+ }
1723
+
1724
+ /** Number of buffered (unconsumed) reports. */
1725
+ get pending() {
1726
+ return this.reports.length;
1727
+ }
1728
+ }
1729
+
1730
+ // ─── Batch protocol handler (protocol byte 0 = Custom Binary) ──────────────────────
1731
+
1732
+ /**
1733
+ * Build a ProtocolDispatcher handler for protocol byte 0 — the batch-instructions
1734
+ * format (decision 022). The envelope payload is
1735
+ * `[texts_off:u32 LE][texts_len:u32 LE][ops stream][texts pool]`; since the payload
1736
+ * is a LIVE view over WASM memory, the handler just computes absolute pointers and
1737
+ * feeds the existing BatchInstructions machinery (no re-parse, no copy).
1738
+ *
1739
+ * @param {BatchInstructions} batches
1740
+ */
1741
+ export function batchProtocolHandler(batches) {
1742
+ return {
1743
+ apply(_memoryId, payload) {
1744
+ if (payload.byteLength < 8) throw new Error("batch payload: missing header");
1745
+ const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
1746
+ const textsOff = view.getUint32(0, true);
1747
+ const textsLen = view.getUint32(4, true);
1748
+ if (textsOff < 8 || textsOff + textsLen > payload.byteLength) {
1749
+ throw new Error("batch payload: header out of range");
1750
+ }
1751
+ const base = payload.byteOffset; // absolute position in WASM linear memory
1752
+ batches.applyNoReturn(base + 8, textsOff - 8, base + textsOff, textsLen);
1753
+ },
1754
+ };
1755
+ }
1756
+
1757
+ // ─── AsyncTaskCollector ────────────────────────────────────────────────────────────
1758
+
1759
+ /**
1760
+ * Tracks the Promises behind async invocations so tests/hosts can await settlement
1761
+ * (`rt.awaitTasks()`). Collection is OFF by default (megatron parity) — long-running
1762
+ * apps shouldn't accumulate promise refs; enable around the window you care about.
1763
+ */
1764
+ export class AsyncTaskCollector {
1765
+ constructor(collect = false) {
1766
+ this.tasks = [];
1767
+ this.collect = collect;
1768
+ }
1769
+
1770
+ enable() { this.collect = true; }
1771
+ disable() { this.collect = false; }
1772
+
1773
+ add(task) {
1774
+ if (!(task instanceof Promise)) throw new Error("Item must be a Promise");
1775
+ if (this.collect) this.tasks.push(task);
1776
+ }
1777
+
1778
+ clear() { this.tasks.length = 0; }
1779
+
1780
+ awaitAll() { return Promise.all(this.tasks); }
1781
+ }
1782
+
1783
+ // ─── WasmStreamReceiver / WasmStreamSender (F28) ─────────────────────────────────
1784
+
1785
+ /**
1786
+ * Host→WASM incoming stream. The WASM side writes data; JS receives it.
1787
+ *
1788
+ * Usage:
1789
+ * var stream = new WasmStreamReceiver({
1790
+ * onData: function(chunk) { ... }, // { data: Uint8Array, sequence: number }
1791
+ * onEnd: function() { ... },
1792
+ * onError: function(err) { ... }
1793
+ * });
1794
+ *
1795
+ * The WASM side calls the internal `_push(id, data, seq, isLast)` to deliver
1796
+ * chunks. IDs are assigned by the JS side (monotonic counter).
1797
+ */
1798
+ let _receiverIdCounter = 0;
1799
+ const _receivers = {};
1800
+
1801
+ export class WasmStreamReceiver {
1802
+ constructor(opts) {
1803
+ this._id = ++_receiverIdCounter;
1804
+ this._onData = (opts && opts.onData) || function () {};
1805
+ this._onEnd = (opts && opts.onEnd) || function () {};
1806
+ this._onError = (opts && opts.onError) || function () {};
1807
+ _receivers[this._id] = this;
1808
+ }
1809
+
1810
+ /** Called by WASM (through host_apply or direct FFI) when data arrives. */
1811
+ static _push(id, data, sequence, isLast) {
1812
+ var r = _receivers[id];
1813
+ if (!r) return;
1814
+ try {
1815
+ if (isLast) {
1816
+ r._onEnd();
1817
+ delete _receivers[id];
1818
+ } else {
1819
+ r._onData({ data: data, sequence: sequence });
1820
+ }
1821
+ } catch (e) {
1822
+ r._onError(e);
1823
+ }
1824
+ }
1825
+
1826
+ /** The global ID used by WASM to reference this receiver. */
1827
+ get receiverId() { return this._id; }
1828
+ }
1829
+
1830
+ /**
1831
+ * WASM→host outgoing stream. The WASM side creates a stream and sends chunks;
1832
+ * the host receives them through callbacks.
1833
+ *
1834
+ * Usage:
1835
+ * var stream = new WasmStreamSender(function(chunk) {
1836
+ * // chunk = { data: Uint8Array, sequence: number } — deliver to host
1837
+ * }, function() {
1838
+ * // stream complete
1839
+ * });
1840
+ * // Pass stream.senderId to WASM so it can call host_sender_send / host_sender_end.
1841
+ */
1842
+ let _senderIdCounter = 0;
1843
+ const _senders = {};
1844
+
1845
+ export class WasmStreamSender {
1846
+ constructor(onChunk, onEnd) {
1847
+ this._id = ++_senderIdCounter;
1848
+ this._onChunk = onChunk || function () {};
1849
+ this._onEnd = onEnd || function () {};
1850
+ _senders[this._id] = this;
1851
+ }
1852
+
1853
+ /** Called by WASM when it has a chunk to send. */
1854
+ static _send(id, data, sequence) {
1855
+ var s = _senders[id];
1856
+ if (s) s._onChunk({ data: data, sequence: sequence });
1857
+ }
1858
+
1859
+ /** Called by WASM when the stream is complete. */
1860
+ static _end(id) {
1861
+ var s = _senders[id];
1862
+ if (s) { s._onEnd(); delete _senders[id]; }
1863
+ }
1864
+
1865
+ /** The global ID used by WASM to reference this sender. */
1866
+ get senderId() { return this._id; }
1867
+ }
1868
+
1869
+ // ─── FoundationWasm runtime ──────────────────────────────────────────────────────
1870
+
1871
+ /**
1872
+ * Ties the core ABI together. Build it, instantiate with its `web_abi` import object,
1873
+ * then call `init(module)` to bind the instance.
1874
+ */
1875
+ export class FoundationWasm {
1876
+ /** @param {{timerHost?:object}} [opts] */
1877
+ constructor(opts = {}) {
1878
+ // Shared, late-populated bridge — import closures and registries read it lazily.
1879
+ this.bridge = { exports: null, memory: null };
1880
+ this.memory = new MemoryAllocations(this.bridge);
1881
+ this.timers = new TimerRegistry(this.bridge, opts.timerHost);
1882
+ this.callbacks = new CallbackRegistry(this.bridge, this.memory);
1883
+ this.animation = new AnimationDriver(this.bridge, opts.rafHost);
1884
+ this.strings = new StringCache(this.bridge);
1885
+ this.functions = new FunctionRegistry(this.bridge, this.memory, this.strings, this.callbacks);
1886
+ // Host-side object heap (object returns + object_allocate_external_pointer).
1887
+ this.objects = new ExternalHeap();
1888
+ this.functions.reply.objects = this.objects;
1889
+ // Pending async-invocation promises (off by default; rt.tasks.enable() to track).
1890
+ this.tasks = new AsyncTaskCollector(false);
1891
+ this.functions.tasks = this.tasks;
1892
+ // #[wasm_test] case outcomes (host_report import — feature 13).
1893
+ this.testReports = new TestReports();
1894
+ // V2 quantized batch codec (host_batch_apply / host_batch_returning_apply).
1895
+ this.batches = new BatchInstructions(
1896
+ this.bridge, this.memory, this.strings, this.functions, this.callbacks,
1897
+ );
1898
+ this.dispatcher = new ProtocolDispatcher();
1899
+ // Protocol byte 0 (Custom Binary) IS the batch-instructions format (decision
1900
+ // 022) — pre-wire its handler so batch messages route without extra setup.
1901
+ this.dispatcher.setHandler(0, batchProtocolHandler(this.batches));
1902
+ // F27: Protocol bytes 3 = capability trigger, 4 = IPC trigger.
1903
+ // Handlers are set lazily via registerTriggerHandlers() so the WASM app
1904
+ // can register callbacks before the dispatcher routes to them.
1905
+ this._capTriggerHandler = null;
1906
+ this._ipcTriggerHandler = null;
1907
+ this.dispatcher.setHandler(3, { apply: (mid, payload) => this._dispatchCapTrigger(mid, payload) });
1908
+ this.dispatcher.setHandler(4, { apply: (mid, payload) => this._dispatchIpcTrigger(mid, payload) });
1909
+ // F28: Stream registry placeholder — WASM exports register streams here.
1910
+ this._streamRegistry = null;
1911
+ // F28: Host-side stream registry. Streams are created by WASM via
1912
+ // host_stream_create() → returns an ID. Chunks are buffered until
1913
+ // callbacks are bound via host_stream_bind(). This decouples creation
1914
+ // (WASM gets an ID it can pass as a return value) from consumption
1915
+ // (JS binds callbacks later).
1916
+ this._streamRegistry = {};
1917
+ this._nextStreamId = 1;
1918
+ }
1919
+
1920
+ /**
1921
+ * F27: Deliver a capability trigger FROM the host INTO the WASM module.
1922
+ * The host (browser, Tauri, Deno) calls this to invoke a capability handler
1923
+ * registered on the WASM side via TriggerRegistry.
1924
+ *
1925
+ * @param {{ capability: string, action: string, payload: Uint8Array }} request
1926
+ * @returns {Promise<object>} capability response
1927
+ */
1928
+ triggerCapability(request) {
1929
+ if (!this._capTriggerHandler) {
1930
+ return Promise.reject(new Error('triggerCapability: no handler registered'));
1931
+ }
1932
+ return this._capTriggerHandler(request);
1933
+ }
1934
+
1935
+ /**
1936
+ * F27: Deliver an IPC trigger FROM the host INTO the WASM module.
1937
+ *
1938
+ * @param {{ ipc: string, action: string, payload: Uint8Array }} request
1939
+ * @returns {Promise<object>} IPC response
1940
+ */
1941
+ triggerIpc(request) {
1942
+ if (!this._ipcTriggerHandler) {
1943
+ return Promise.reject(new Error('triggerIpc: no handler registered'));
1944
+ }
1945
+ return this._ipcTriggerHandler(request);
1946
+ }
1947
+
1948
+ /**
1949
+ * F27: Register trigger handlers for capability and IPC dispatch.
1950
+ * Called by foundation_wasm_ui once the WASM app has set up its
1951
+ * TriggerRegistry.
1952
+ *
1953
+ * @param {{ onCapability: Function, onIpc: Function }} handlers
1954
+ */
1955
+ registerTriggerHandlers(handlers) {
1956
+ if (handlers.onCapability) this._capTriggerHandler = handlers.onCapability;
1957
+ if (handlers.onIpc) this._ipcTriggerHandler = handlers.onIpc;
1958
+ }
1959
+
1960
+ /** @private */
1961
+ _dispatchCapTrigger(memoryId, payload) {
1962
+ if (!this._capTriggerHandler) return;
1963
+ try {
1964
+ var req = JSON.parse(new TextDecoder().decode(payload));
1965
+ this._capTriggerHandler(req);
1966
+ } catch (_) { /* best-effort */ }
1967
+ this.memory.dispose(memoryId);
1968
+ }
1969
+
1970
+ /** @private */
1971
+ _dispatchIpcTrigger(memoryId, payload) {
1972
+ if (!this._ipcTriggerHandler) return;
1973
+ try {
1974
+ var req = JSON.parse(new TextDecoder().decode(payload));
1975
+ this._ipcTriggerHandler(req);
1976
+ } catch (_) { /* best-effort */ }
1977
+ this.memory.dispose(memoryId);
1978
+ }
1979
+
1980
+ /**
1981
+ * The `{ ...abi imports }` object — pass as `{ abi: rt.web_abi }` to instantiate.
1982
+ * The DOM-specific imports (rAF, function invocation, dom_* refs) are layered on by
1983
+ * foundation-wasm-ui.js, which can extend this object.
1984
+ */
1985
+ get web_abi() {
1986
+ const self = this;
1987
+ const { bridge, memory, dispatcher, timers, animation, strings, functions, objects, batches } = this;
1988
+ return {
1989
+ // Uniform protocol transport: WASM shipped a message in slot `memId`.
1990
+ host_apply(memId, ptr, len) {
1991
+ try {
1992
+ dispatcher.dispatch(memory.get(memId).bytes);
1993
+ } finally {
1994
+ memory.dispose(memId); // ACK: always free, even if the handler threw.
1995
+ }
1996
+ },
1997
+ schedule_timeout(timing, callbackId) {
1998
+ timers.scheduleTimeout(callbackId, Number(timing));
1999
+ },
2000
+ unschedule_timeout(callbackId) {
2001
+ timers.cancelTimeout(callbackId);
2002
+ },
2003
+ schedule_microtask(callbackId) {
2004
+ timers.scheduleMicrotask(callbackId);
2005
+ },
2006
+ schedule_interval(timing, callbackId) {
2007
+ timers.scheduleInterval(callbackId, Number(timing));
2008
+ },
2009
+ unschedule_interval(callbackId) {
2010
+ timers.cancelInterval(callbackId);
2011
+ },
2012
+ // WASM registered a frame callback — start (or keep) the rAF loop.
2013
+ hook_up_animation_frames() {
2014
+ animation.start();
2015
+ },
2016
+ // Intern a UTF-8/UTF-16 string from WASM memory; returns a stable handle.
2017
+ host_cache_string(ptr, len, encoding) {
2018
+ return strings.cache(ptr, len, Number(encoding));
2019
+ },
2020
+ // #[wasm_test] outcome (feature 13): status 0/1/2 + optional UTF-8 message.
2021
+ host_report: (status, ptr, len) => {
2022
+ const length = Number(len);
2023
+ const message = length
2024
+ ? new TextDecoder().decode(
2025
+ new Uint8Array(this.bridge.memory.buffer, Number(ptr), length),
2026
+ )
2027
+ : "";
2028
+ this.testReports.push(Number(status), message);
2029
+ },
2030
+
2031
+ // Clock + entropy for foundation_compact's `host-abi` backend (the owned
2032
+ // path's `Instant`, `SystemTime` and RNG seeding, no wasm-bindgen glue).
2033
+ // Monotonic ms since the time origin; Date.now() where there is no
2034
+ // `performance` (e.g. some worklets), like the rAF fallback above.
2035
+ host_monotonic_now_ms() {
2036
+ return globalThis.performance?.now?.() ?? Date.now();
2037
+ },
2038
+ // The time origin in ms since the Unix epoch (threaded builds only).
2039
+ host_time_origin_ms() {
2040
+ return globalThis.performance?.timeOrigin ?? 0;
2041
+ },
2042
+ // Wall-clock ms since the Unix epoch.
2043
+ host_wall_clock_ms() {
2044
+ return Date.now();
2045
+ },
2046
+ // Fill `len` bytes at `ptr` from crypto.getRandomValues: 0 = ok, 1 = no
2047
+ // secure source. Web Crypto takes at most 65536 bytes per call, and
2048
+ // refuses views over shared memory, which go through a scratch buffer.
2049
+ host_fill_random: (ptr, len) => {
2050
+ const crypto = globalThis.crypto;
2051
+ if (typeof crypto?.getRandomValues !== "function") return 1;
2052
+ const MAX_PER_CALL = 65536; // Web Crypto's per-call limit (spec).
2053
+ const start = Number(ptr);
2054
+ const total = Number(len);
2055
+ try {
2056
+ for (let done = 0; done < total; done += MAX_PER_CALL) {
2057
+ const n = Math.min(MAX_PER_CALL, total - done);
2058
+ const buffer = this.bridge.memory.buffer;
2059
+ const dest = new Uint8Array(buffer, start + done, n);
2060
+ if (typeof SharedArrayBuffer !== "undefined" && buffer instanceof SharedArrayBuffer) {
2061
+ const scratch = new Uint8Array(n);
2062
+ crypto.getRandomValues(scratch);
2063
+ dest.set(scratch);
2064
+ } else {
2065
+ crypto.getRandomValues(dest);
2066
+ }
2067
+ }
2068
+ } catch (_) {
2069
+ return 1;
2070
+ }
2071
+ return 0;
2072
+ },
2073
+ // Console log for foundation_compact's `host-abi` trace backend: read a
2074
+ // UTF-8 line from WASM memory and print it with console.log (no wasm-bindgen).
2075
+ host_console_log(ptr, len) {
2076
+ const length = Number(len);
2077
+ const message = length
2078
+ ? new TextDecoder().decode(
2079
+ new Uint8Array(this.bridge.memory.buffer, Number(ptr), length),
2080
+ )
2081
+ : "";
2082
+ console.log(message);
2083
+ },
2084
+
2085
+ // Function registry: register a JS fn (source string) → handle; invoke it.
2086
+ host_register_function(start, len, utf) {
2087
+ return functions.register(start, len, utf);
2088
+ },
2089
+ host_invoke_function(handle, pPtr, pLen, rPtr, rLen) {
2090
+ return functions.invoke(handle, pPtr, pLen, rPtr, rLen);
2091
+ },
2092
+ // Async fn: result Promise → framed reply delivered later via invoke_callback.
2093
+ host_invoke_async_function(handle, callbackHandle, pPtr, pLen, rPtr, rLen) {
2094
+ functions.invokeAsync(handle, callbackHandle, pPtr, pLen, rPtr, rLen);
2095
+ },
2096
+ // Typed fast-paths: return the naked scalar directly.
2097
+ host_invoke_function_as_bool: (h, p, l) => functions.invokeAsBool(h, p, l),
2098
+ host_invoke_function_as_f32: (h, p, l) => functions.invokeAsFloat(h, p, l),
2099
+ host_invoke_function_as_f64: (h, p, l) => functions.invokeAsFloat(h, p, l),
2100
+ host_invoke_function_as_u8: (h, p, l) => functions.invokeAsInt(h, p, l),
2101
+ host_invoke_function_as_u16: (h, p, l) => functions.invokeAsInt(h, p, l),
2102
+ host_invoke_function_as_u32: (h, p, l) => functions.invokeAsInt(h, p, l),
2103
+ host_invoke_function_as_i8: (h, p, l) => functions.invokeAsInt(h, p, l),
2104
+ host_invoke_function_as_i16: (h, p, l) => functions.invokeAsInt(h, p, l),
2105
+ host_invoke_function_as_i32: (h, p, l) => functions.invokeAsInt(h, p, l),
2106
+ host_invoke_function_as_u64: (h, p, l) => functions.invokeAsBigInt(h, p, l),
2107
+ // Object fast-path: interned in the object heap, handle crosses naked.
2108
+ host_invoke_function_as_object: (h, p, l) => functions.invokeAsObject(h, p, l),
2109
+ host_invoke_function_as_i64: (h, p, l) => functions.invokeAsBigInt(h, p, l),
2110
+ host_unregister_function(handle) {
2111
+ functions.unregister(handle);
2112
+ },
2113
+ // megatron-era aliases/extras, kept so megatron-built modules instantiate:
2114
+ host_function_drop_external_pointer(handle) {
2115
+ functions.unregister(handle);
2116
+ },
2117
+ // String fast-path: raw UTF-8 into a fresh slot, slot id crosses.
2118
+ host_invoke_function_as_str: (h, p, l) => functions.invokeAsString(h, p, l),
2119
+ // WASM-side fatal: surface it as a JS exception (megatron parity).
2120
+ host_abort() {
2121
+ throw new Error("WasmInstance called abort");
2122
+ },
2123
+
2124
+ // Pre-allocate empty heap handles for later binding (batch MakeFunction / objects).
2125
+ function_allocate_external_pointer: () => functions.allocate(),
2126
+ object_allocate_external_pointer: () => objects.create(null),
2127
+
2128
+ // Retire host-heap handles (generation-checked; stale ids no-op).
2129
+ host_object_drop_external_pointer(handle) {
2130
+ objects.destroy(BigInt(handle));
2131
+ },
2132
+ host_string_cache_drop_external_pointer(handle) {
2133
+ strings.drop(handle);
2134
+ },
2135
+
2136
+ // V2 quantized batch transport: ops + texts buffers in WASM memory.
2137
+ host_batch_apply(opsPtr, opsLen, textPtr, textLen) {
2138
+ batches.applyNoReturn(opsPtr, opsLen, textPtr, textLen);
2139
+ },
2140
+ host_batch_returning_apply(opsPtr, opsLen, textPtr, textLen) {
2141
+ return batches.applyReturning(opsPtr, opsLen, textPtr, textLen);
2142
+ },
2143
+
2144
+ // F28: Stream FFI — WASM pushes data through buffered host-side streams.
2145
+ //
2146
+ // host_stream_create() → returns stream ID (u64). WASM can pass this
2147
+ // as a return value. Chunks are buffered until
2148
+ // callbacks are bound.
2149
+ // host_stream_bind(id, onChunk, onEnd) → bind callbacks, drain buffer.
2150
+ // host_sender_send(id, ptr, len, seq) → push chunk (buffer or deliver).
2151
+ // host_sender_end(id) → signal end (or mark ended).
2152
+ //
2153
+ // This decouples stream creation from consumption:
2154
+ // 1. WASM calls host_stream_create() → gets ID
2155
+ // 2. WASM passes ID as return value to JS
2156
+ // 3. JS binds callbacks via host_stream_bind(id, onChunk, onEnd)
2157
+ // 4. WASM pushes chunks → delivered to onChunk
2158
+ // 5. WASM calls host_sender_end → delivered to onEnd
2159
+ host_stream_create() {
2160
+ var id = self._nextStreamId++;
2161
+ self._streamRegistry[id] = {
2162
+ chunks: [],
2163
+ onChunk: null,
2164
+ onEnd: null,
2165
+ ended: false,
2166
+ bind: function (chunkFn, endFn) {
2167
+ this.onChunk = chunkFn || null;
2168
+ this.onEnd = endFn || null;
2169
+ // Drain buffered chunks
2170
+ if (this.onChunk) {
2171
+ for (var i = 0; i < this.chunks.length; i++) {
2172
+ this.onChunk(this.chunks[i]);
2173
+ }
2174
+ this.chunks.length = 0;
2175
+ }
2176
+ if (this.ended && this.onEnd) {
2177
+ this.onEnd();
2178
+ }
2179
+ },
2180
+ };
2181
+ return BigInt(id);
2182
+ },
2183
+ host_stream_bind(streamId, cbOnChunk, cbOnEnd) {
2184
+ var s = self._streamRegistry[Number(streamId)];
2185
+ if (!s) return;
2186
+ s.onChunk = typeof cbOnChunk === "function" ? cbOnChunk : null;
2187
+ s.onEnd = typeof cbOnEnd === "function" ? cbOnEnd : null;
2188
+ // Drain buffered chunks
2189
+ if (s.onChunk) {
2190
+ for (var i = 0; i < s.chunks.length; i++) {
2191
+ s.onChunk(s.chunks[i]);
2192
+ }
2193
+ s.chunks.length = 0;
2194
+ }
2195
+ // If already ended, fire onEnd immediately
2196
+ if (s.ended && s.onEnd) {
2197
+ s.onEnd();
2198
+ }
2199
+ },
2200
+ host_sender_send(streamId, dataPtr, dataLen, seq) {
2201
+ var id = Number(streamId);
2202
+ var data = new Uint8Array(bridge.memory.buffer, Number(dataPtr), Number(dataLen));
2203
+ var s = self._streamRegistry[id];
2204
+ if (s) {
2205
+ var chunk = { data: data, sequence: Number(seq) };
2206
+ if (s.onChunk) {
2207
+ s.onChunk(chunk);
2208
+ } else {
2209
+ s.chunks.push(chunk);
2210
+ }
2211
+ } else {
2212
+ // Fallback: direct WasmStreamSender (pre-F28 API)
2213
+ WasmStreamSender._send(id, data, Number(seq));
2214
+ }
2215
+ },
2216
+ host_sender_end(streamId) {
2217
+ var id = Number(streamId);
2218
+ var s = self._streamRegistry[id];
2219
+ if (s) {
2220
+ s.ended = true;
2221
+ if (s.onEnd) s.onEnd();
2222
+ delete self._streamRegistry[id];
2223
+ } else {
2224
+ // Fallback: direct WasmStreamSender (pre-F28 API)
2225
+ WasmStreamSender._end(id);
2226
+ }
2227
+ },
2228
+ // Host → WASM (incoming): call host_receiver_push to deliver chunks.
2229
+ host_receiver_push(receiverId, dataPtr, dataLen, seq, isLast) {
2230
+ var data = new Uint8Array(bridge.memory.buffer, Number(dataPtr), Number(dataLen));
2231
+ WasmStreamReceiver._push(Number(receiverId), data, Number(seq), isLast !== 0);
2232
+ },
2233
+ };
2234
+ }
2235
+
2236
+ /**
2237
+ * Bind the instantiated module. Accepts the `{ instance }` result of
2238
+ * `WebAssembly.instantiate` (or a bare instance). Memory is taken from the
2239
+ * instance's exported `memory`.
2240
+ */
2241
+ init(moduleOrInstance) {
2242
+ const instance = moduleOrInstance.instance ?? moduleOrInstance;
2243
+ this.bridge.exports = instance.exports;
2244
+ this.bridge.memory = instance.exports.memory;
2245
+ return this;
2246
+ }
2247
+
2248
+ /**
2249
+ * Tear down this runtime's host-side scheduling before discarding the
2250
+ * instance: pending timeouts, intervals, queued microtasks and the animation
2251
+ * loop are cancelled, so no guest code runs after this call.
2252
+ */
2253
+ dispose() {
2254
+ this.timers.cancelAll();
2255
+ this.animation.stop();
2256
+ }
2257
+
2258
+ /** Register a protocol handler `{ apply(memoryId, payload) }` for a protocol byte. */
2259
+ setProtocolHandler(protocol, handler) {
2260
+ this.dispatcher.setHandler(protocol, handler);
2261
+ return this;
2262
+ }
2263
+
2264
+ /** Await every tracked async invocation (requires `rt.tasks.enable()` beforehand). */
2265
+ awaitTasks() {
2266
+ return this.tasks.awaitAll();
2267
+ }
2268
+ }
2269
+
2270
+ // ─── WasmLoader / WasmWebScripts (megatron WASMLoader parity) ──────────────────────
2271
+
2272
+ /** Reports the stage and address of a module load failure. */
2273
+ export class WasmLoadError extends Error {
2274
+ constructor(code, url, detail, options) {
2275
+ super(`Cannot load WebAssembly from ${url}: ${detail}`, options);
2276
+ this.name = "WasmLoadError";
2277
+ this.code = code;
2278
+ this.url = String(url);
2279
+ }
2280
+ }
2281
+
2282
+ /**
2283
+ * Convenience loader: owns a FoundationWasm runtime, instantiates a module from a
2284
+ * URL (streaming) or raw bytes with the `abi` imports + a `js.mem` memory, and binds
2285
+ * the bridge. Mirrors megatron WASMLoader incl. the JS-string-builtins compile
2286
+ * options (`builtins: ["js-strings"]`, `importedStringConstants`).
2287
+ */
2288
+ export class WasmLoader {
2289
+ #options;
2290
+
2291
+ /**
2292
+ * @param {{initialMemory?:number, maximumMemory?:number, environment?:object,
2293
+ * compileOptions?:object}} [opts] memory sizes are in WASM pages
2294
+ */
2295
+ constructor(opts = {}) {
2296
+ this.#options = {...opts};
2297
+ this.environment = opts.environment ?? {};
2298
+ this.compileOptions = WasmLoader.compileOptionsOf(opts.compileOptions);
2299
+ this.#prepareRuntime();
2300
+ }
2301
+
2302
+ /** Allocate a new host after disposal. Old callbacks keep their disabled registry. */
2303
+ #prepareRuntime() {
2304
+ if (!this.runtime || this.runtime.timers.disposed) {
2305
+ this.runtime = new FoundationWasm(this.#options);
2306
+ this.memory = new WebAssembly.Memory({
2307
+ initial: this.#options.initialMemory ?? 10,
2308
+ maximum: this.#options.maximumMemory ?? 200,
2309
+ });
2310
+ this.module = null;
2311
+ }
2312
+ }
2313
+
2314
+ static compileOptionsOf(compileOptions) {
2315
+ return {
2316
+ builtins: compileOptions?.builtins ?? ["js-strings"],
2317
+ importedStringConstants: compileOptions?.importedStringConstants ?? "imported_strings",
2318
+ };
2319
+ }
2320
+
2321
+ /** The full import object: the ABI, a host memory under `js.mem`, plus extras. */
2322
+ get imports() {
2323
+ return { abi: this.runtime.web_abi, js: { mem: this.memory }, ...this.environment };
2324
+ }
2325
+
2326
+ /** Check the response before streaming the module into the compiler. */
2327
+ async loadURL(url, fetchModule = globalThis.fetch) {
2328
+ this.#prepareRuntime();
2329
+ let response;
2330
+ try {
2331
+ response = await fetchModule(url);
2332
+ } catch (cause) {
2333
+ throw new WasmLoadError("Network", url, cause.message, { cause });
2334
+ }
2335
+ if (!response.ok) {
2336
+ const error = new WasmLoadError("HttpStatus", url, `HTTP ${response.status}`);
2337
+ error.status = response.status;
2338
+ await response.body?.cancel().catch(() => {});
2339
+ throw error;
2340
+ }
2341
+ try {
2342
+ this.#bind(await WebAssembly.instantiateStreaming(response, this.imports, this.compileOptions));
2343
+ } catch (cause) {
2344
+ const code = cause instanceof WebAssembly.LinkError ? "Imports"
2345
+ : cause instanceof WebAssembly.CompileError ? "Compile" : "Instantiate";
2346
+ throw new WasmLoadError(code, url, cause.message, { cause });
2347
+ }
2348
+ return this;
2349
+ }
2350
+
2351
+ /** Instantiate from raw bytes (ArrayBuffer/TypedArray). */
2352
+ async loadBytes(bytes) {
2353
+ this.#prepareRuntime();
2354
+ const module = await WebAssembly.instantiate(bytes, this.imports, this.compileOptions);
2355
+ this.#bind(module);
2356
+ return this;
2357
+ }
2358
+
2359
+ #bind(module) {
2360
+ this.module = module;
2361
+ this.runtime.init(module);
2362
+ }
2363
+
2364
+ /** Call the module's exported `main()`. */
2365
+ run() {
2366
+ if (!this.module) throw new Error("No wasm module loaded");
2367
+ const main = this.module.instance.exports.main;
2368
+ if (!main) throw new Error("wasm module has no exported main function");
2369
+ return main();
2370
+ }
2371
+
2372
+ /** Load every `<script type="application/wasm" src=…>` on the page → loaders. */
2373
+ static async fromScripts(opts = {}) {
2374
+ const scripts = document.querySelectorAll('script[type="application/wasm"]');
2375
+ const loading = [];
2376
+ for (const script of scripts) {
2377
+ if (!script.src) continue;
2378
+ loading.push(new WasmLoader(opts).loadURL(script.src));
2379
+ }
2380
+ return Promise.all(loading);
2381
+ }
2382
+ }
2383
+
2384
+ /**
2385
+ * Page bootstrap: loads every `application/wasm` script tag and runs each module's
2386
+ * `main()` (megatron WasmWebScripts parity).
2387
+ */
2388
+ export class WasmWebScripts {
2389
+ constructor(opts = {}) {
2390
+ this.modules = WasmLoader.fromScripts(opts);
2391
+ }
2392
+
2393
+ static default(environment) {
2394
+ return new WasmWebScripts({ environment });
2395
+ }
2396
+
2397
+ async runAll() {
2398
+ const loaders = await this.modules;
2399
+ for (const loader of loaders) loader.run();
2400
+ return loaders;
2401
+ }
2402
+ }
2403
+
2404
+ // ─── Global registration ──────────────────────────────────────────────────────────
2405
+ //
2406
+ // The ESM exports above are canonical (`<script type="module">` / import). This
2407
+ // mirror lets classic (non-module) scripts on the same page reach the runtime as
2408
+ // `globalThis.FoundationWasmRuntime` once the module has loaded.
2409
+ globalThis.FoundationWasmRuntime = Object.freeze({
2410
+ FoundationWasm,
2411
+ batchProtocolHandler,
2412
+ WasmLoader,
2413
+ WasmLoadError,
2414
+ WasmWebScripts,
2415
+ AsyncTaskCollector,
2416
+ TestReports,
2417
+ WasmEnvelope,
2418
+ ProtocolDispatcher,
2419
+ MemoryAllocations,
2420
+ TimerRegistry,
2421
+ CallbackRegistry,
2422
+ StringCache,
2423
+ AnimationDriver,
2424
+ FunctionRegistry,
2425
+ ParameterParser,
2426
+ ReturnHintParser,
2427
+ ReplyEncoder,
2428
+ ExternalHeap,
2429
+ BatchInstructions,
2430
+ BatchParameterParser,
2431
+ Operations,
2432
+ ArgumentOperations,
2433
+ TypeOptimization,
2434
+ ParamType,
2435
+ ReturnType,
2436
+ ReturnIds,
2437
+ ThreeStateId,
2438
+ ExternalPointer,
2439
+ InternalPointer,
2440
+ CachePointer,
2441
+ ErrorCodeValue,
2442
+ TypedArraySliceValue,
2443
+ TypedSliceArray,
2444
+ ReplyContainer,
2445
+ FakeNode,
2446
+ ReplyError,
2447
+ WasmStreamReceiver,
2448
+ WasmStreamSender,
2449
+ });