@beyondwork/xlsx-substrate-bindings 0.1.0 → 0.3.1

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.
Files changed (47) hide show
  1. package/README.md +189 -0
  2. package/assets/blank-workbook.xlsx +0 -0
  3. package/dist/ai/agent-metadata.d.ts +387 -0
  4. package/dist/ai/agent-metadata.js +227 -0
  5. package/dist/ai/index.d.ts +5 -1
  6. package/dist/ai/index.js +6 -0
  7. package/dist/ai/mutation-bridge.d.ts +82 -0
  8. package/dist/ai/mutation-bridge.js +179 -0
  9. package/dist/ai/types.d.ts +468 -3
  10. package/dist/blank-workbook/index.d.ts +24 -0
  11. package/dist/blank-workbook/index.js +77 -0
  12. package/dist/index.d.ts +8 -3
  13. package/dist/index.js +20 -2
  14. package/dist/runtime/index.d.ts +1 -1
  15. package/dist/runtime/types.d.ts +108 -18
  16. package/dist/wasm/ai-session-bridge.d.ts +97 -0
  17. package/dist/wasm/ai-session-bridge.js +154 -0
  18. package/dist/wasm/bridge-contract.d.ts +108 -6
  19. package/dist/wasm/bridge-contract.js +146 -7
  20. package/dist/wasm/index.d.ts +43 -2
  21. package/dist/wasm/index.js +253 -23
  22. package/dist/wasm/memory-budget.d.ts +77 -0
  23. package/dist/wasm/memory-budget.js +532 -0
  24. package/dist/wasm/runtime-guard.d.ts +141 -0
  25. package/dist/wasm/runtime-guard.js +373 -0
  26. package/dist/wasm/session-router.d.ts +1 -1
  27. package/dist/wasm/session-router.js +4 -1
  28. package/dist/wasm/web.d.ts +18 -3
  29. package/dist/wasm/web.js +99 -9
  30. package/generated/wasm-web/xlsx_substrate_wasm.d.ts +66 -0
  31. package/generated/wasm-web/xlsx_substrate_wasm.js +2488 -2104
  32. package/generated/wasm-web/xlsx_substrate_wasm_bg.wasm +0 -0
  33. package/generated/wasm-web/xlsx_substrate_wasm_bg.wasm.d.ts +15 -0
  34. package/package.json +24 -4
  35. package/dist/wasm/chart-test-fixture.d.ts +0 -19
  36. package/dist/wasm/chart-test-fixture.js +0 -42
  37. package/dist/wasm/media-test-fixture.d.ts +0 -44
  38. package/dist/wasm/media-test-fixture.js +0 -160
  39. package/dist/wasm/volatile-test-fixture.d.ts +0 -7
  40. package/dist/wasm/volatile-test-fixture.js +0 -35
  41. package/generated/wasm/package.json +0 -3
  42. package/generated/wasm/sheet-window-binary.mjs +0 -482
  43. package/generated/wasm/snippets/ironcalc_base-89b4f49381e1e289/inline0.js +0 -45
  44. package/generated/wasm/xlsx_substrate_wasm.d.ts +0 -336
  45. package/generated/wasm/xlsx_substrate_wasm.js +0 -2108
  46. package/generated/wasm/xlsx_substrate_wasm_bg.wasm +0 -0
  47. package/generated/wasm/xlsx_substrate_wasm_bg.wasm.d.ts +0 -105
@@ -0,0 +1,373 @@
1
+ // Runtime 0.2.0 memory contract (R4), the JS side of every bridge call:
2
+ // pre-admission against the memory budget, trap containment with
3
+ // re-instantiation from the cached Module, the session ledger that names the
4
+ // sessions a trap lost, and the memory readbacks (`wasmMemoryBytes`,
5
+ // `highWater`). Browser-safe: no `node:` imports.
6
+ //
7
+ // Why this lives in JS: the wasm module is built with panic=abort and a
8
+ // link-time memory maximum, so an allocation past the maximum aborts and
9
+ // traps as `RuntimeError: unreachable`. Nothing inside wasm can turn that
10
+ // into a typed error, and a trapped instance may hold half-updated state
11
+ // (borrowed RefCells, a torn allocator). So the bridge never reuses it.
12
+ import { estimateXlsxPackageMemory, XLSX_WASM_LINEAR_MEMORY_MAXIMUM_BYTES } from "./memory-budget.js";
13
+ /**
14
+ * The typed errors the bridge throws instead of a raw trap or an
15
+ * out-of-memory abort. Hosts branch on `code` through
16
+ * `isXlsxWasmBridgeError`.
17
+ *
18
+ * Crossing a thread: structured clone (`postMessage`, `structuredClone`)
19
+ * keeps only the standard error names and drops own properties, so a cloned
20
+ * `XlsxWasmBridgeError` arrives as a plain `Error` with no `code` and is not
21
+ * recognised. Post `serializeXlsxWasmBridgeError(error)` instead; the plain
22
+ * object it returns survives the clone, `isXlsxWasmBridgeError` recognises
23
+ * it, and `deserializeXlsxWasmBridgeError` turns it back into an instance.
24
+ */
25
+ export class XlsxWasmBridgeError extends Error {
26
+ code;
27
+ method;
28
+ lostSessions;
29
+ recovered;
30
+ trapped;
31
+ estimatedBytes;
32
+ budgetBytes;
33
+ estimate;
34
+ constructor(details) {
35
+ super(details.message, details.cause === undefined ? undefined : { cause: details.cause });
36
+ this.name = "XlsxWasmBridgeError";
37
+ this.code = details.code;
38
+ this.method = details.method;
39
+ this.lostSessions = Object.freeze([...(details.lostSessions ?? [])]);
40
+ this.recovered = details.recovered ?? false;
41
+ this.trapped = details.trapped ?? false;
42
+ if (details.estimatedBytes !== undefined)
43
+ this.estimatedBytes = details.estimatedBytes;
44
+ if (details.budgetBytes !== undefined)
45
+ this.budgetBytes = details.budgetBytes;
46
+ if (details.estimate !== undefined)
47
+ this.estimate = details.estimate;
48
+ }
49
+ }
50
+ /**
51
+ * True for an `XlsxWasmBridgeError` from any realm, and for the plain object
52
+ * `serializeXlsxWasmBridgeError` returns. A raw structured clone of the error
53
+ * is not recognised: it has lost its name and code (see the class comment).
54
+ */
55
+ export function isXlsxWasmBridgeError(value, code) {
56
+ if (typeof value !== "object" || value === null)
57
+ return false;
58
+ const candidate = value;
59
+ if (candidate.name !== "XlsxWasmBridgeError")
60
+ return false;
61
+ if (candidate.code !== "wasm-instance-lost" && candidate.code !== "out-of-memory-budget")
62
+ return false;
63
+ return code === undefined || candidate.code === code;
64
+ }
65
+ /** A plain object carrying every field of `error` except `cause`, for `postMessage`. */
66
+ export function serializeXlsxWasmBridgeError(error) {
67
+ return {
68
+ name: "XlsxWasmBridgeError",
69
+ code: error.code,
70
+ method: error.method,
71
+ message: error.message,
72
+ lostSessions: [...error.lostSessions],
73
+ recovered: error.recovered,
74
+ trapped: error.trapped,
75
+ ...(error.estimatedBytes !== undefined ? { estimatedBytes: error.estimatedBytes } : {}),
76
+ ...(error.budgetBytes !== undefined ? { budgetBytes: error.budgetBytes } : {}),
77
+ ...(error.estimate !== undefined ? { estimate: { ...error.estimate } } : {})
78
+ };
79
+ }
80
+ /** An `XlsxWasmBridgeError` instance from its serialized form, or undefined when `value` is not one. */
81
+ export function deserializeXlsxWasmBridgeError(value) {
82
+ if (value instanceof XlsxWasmBridgeError)
83
+ return value;
84
+ if (!isXlsxWasmBridgeError(value))
85
+ return undefined;
86
+ const plain = value;
87
+ const lostSessions = Array.isArray(plain.lostSessions)
88
+ ? plain.lostSessions.filter((id) => typeof id === "string")
89
+ : [];
90
+ return new XlsxWasmBridgeError({
91
+ code: value.code,
92
+ method: typeof plain.method === "string" ? plain.method : "unknown",
93
+ message: typeof plain.message === "string" ? plain.message : value.code,
94
+ lostSessions,
95
+ recovered: plain.recovered === true,
96
+ trapped: plain.trapped === true,
97
+ ...(typeof plain.estimatedBytes === "number" ? { estimatedBytes: plain.estimatedBytes } : {}),
98
+ ...(typeof plain.budgetBytes === "number" ? { budgetBytes: plain.budgetBytes } : {}),
99
+ ...(plain.estimate && typeof plain.estimate === "object" ? { estimate: plain.estimate } : {})
100
+ });
101
+ }
102
+ const HANDLE_GENERATION_SEPARATOR = "@";
103
+ /** True for bridge methods whose first argument is a runtime-session handle id. */
104
+ function takesSessionHandle(method) {
105
+ return (method !== "openWorkbookRuntimeSession" &&
106
+ (method.includes("RuntimeSession") || method.endsWith("InSession") || method === "aiSessionCall"));
107
+ }
108
+ function isTrap(error) {
109
+ if (typeof WebAssembly === "object" && WebAssembly !== null && error instanceof WebAssembly.RuntimeError) {
110
+ return true;
111
+ }
112
+ // A wasm stack overflow surfaces as a RangeError and leaves the instance
113
+ // mid-call just like a trap.
114
+ return error instanceof RangeError && /call stack/iu.test(error.message);
115
+ }
116
+ function isPromise(value) {
117
+ return typeof value?.then === "function";
118
+ }
119
+ function admissionOf(options) {
120
+ if (options.memoryBudgetBytes !== undefined && !(options.memoryBudgetBytes >= 0)) {
121
+ throw new RangeError(`memoryBudgetBytes must be a non-negative byte count, got ${String(options.memoryBudgetBytes)}`);
122
+ }
123
+ return {
124
+ ...(options.memoryBudgetBytes !== undefined ? { memoryBudgetBytes: options.memoryBudgetBytes } : {}),
125
+ ...(options.admission !== undefined ? { admission: options.admission } : {})
126
+ };
127
+ }
128
+ export function createXlsxWasmRuntime(options) {
129
+ const maximumBytes = options.maximumMemoryBytes ?? XLSX_WASM_LINEAR_MEMORY_MAXIMUM_BYTES;
130
+ let current = options.instance;
131
+ // The last instance object, kept only so `typeof raw.method` probes still
132
+ // answer while the runtime is lost. It is never called.
133
+ let shape = options.instance.raw;
134
+ let recovering;
135
+ let generation = 0;
136
+ let peakBytes = 0;
137
+ let highWaterBytes;
138
+ /** External handle id -> its estimates, for every session the live instance holds. */
139
+ const liveSessions = new Map();
140
+ /** External handle ids a trap took. */
141
+ const lostSessions = new Set();
142
+ const currentBytes = () => {
143
+ const memory = current?.memory;
144
+ if (!memory)
145
+ return undefined;
146
+ const bytes = memory.buffer.byteLength;
147
+ if (bytes > peakBytes)
148
+ peakBytes = bytes;
149
+ return bytes;
150
+ };
151
+ currentBytes();
152
+ const lost = (method, sessions, message, cause, trapped = false) => new XlsxWasmBridgeError({
153
+ code: "wasm-instance-lost",
154
+ method,
155
+ lostSessions: sessions,
156
+ recovered: current !== undefined,
157
+ trapped,
158
+ message,
159
+ cause
160
+ });
161
+ const adopt = (instance) => {
162
+ current = instance;
163
+ shape = instance.raw;
164
+ currentBytes();
165
+ };
166
+ const recover = () => {
167
+ if (!options.reinstantiate || recovering)
168
+ return;
169
+ let next;
170
+ try {
171
+ next = options.reinstantiate();
172
+ }
173
+ catch {
174
+ return;
175
+ }
176
+ if (isPromise(next)) {
177
+ recovering = next.then((instance) => {
178
+ recovering = undefined;
179
+ adopt(instance);
180
+ }, () => {
181
+ recovering = undefined;
182
+ });
183
+ return;
184
+ }
185
+ adopt(next);
186
+ };
187
+ const externalId = (nativeId) => generation === 0 ? nativeId : `${nativeId}${HANDLE_GENERATION_SEPARATOR}${generation}`;
188
+ /** The native handle id for an external one, or a typed refusal when it is gone. */
189
+ const nativeId = (method, handleId) => {
190
+ if (lostSessions.has(handleId)) {
191
+ throw lost(method, [handleId], `runtime session ${handleId} was lost when the wasm instance trapped; reopen it`);
192
+ }
193
+ if (generation === 0)
194
+ return handleId;
195
+ const suffix = `${HANDLE_GENERATION_SEPARATOR}${generation}`;
196
+ if (handleId.endsWith(suffix))
197
+ return handleId.slice(0, -suffix.length);
198
+ // An id from an earlier instance must never reach this one: its native
199
+ // counter restarted and may have handed the same id to a new session.
200
+ throw lost(method, [handleId], `runtime session ${handleId} belongs to a wasm instance that no longer exists; reopen it`);
201
+ };
202
+ /** The open estimates of the sessions the live instance holds. */
203
+ const committedBytes = () => {
204
+ let total = 0;
205
+ for (const session of liveSessions.values())
206
+ total += session.openBytes;
207
+ return total;
208
+ };
209
+ const admit = (admission, method, estimatedBytes, estimate) => {
210
+ if (admission.admission === "off")
211
+ return;
212
+ // Never `maximum - byteLength`: linear memory does not shrink, so on a
213
+ // long-lived instance that gap only closes, even after the sessions that
214
+ // grew it are disposed and their memory is free for reuse.
215
+ const committed = committedBytes();
216
+ const headroom = maximumBytes - committed;
217
+ const budgetBytes = Math.max(0, Math.min(admission.memoryBudgetBytes ?? Number.POSITIVE_INFINITY, headroom));
218
+ if (estimatedBytes > budgetBytes) {
219
+ throw new XlsxWasmBridgeError({
220
+ code: "out-of-memory-budget",
221
+ method,
222
+ message: `${method} refused before calling into wasm: estimated ${estimatedBytes} bytes of linear memory, ` +
223
+ `budget ${budgetBytes} bytes (maximum ${maximumBytes}, ${committed} estimated for ${liveSessions.size} live session(s)` +
224
+ (admission.memoryBudgetBytes !== undefined ? `, host cap ${admission.memoryBudgetBytes}` : "") +
225
+ ")",
226
+ estimatedBytes,
227
+ budgetBytes,
228
+ ...(estimate ? { estimate } : {})
229
+ });
230
+ }
231
+ };
232
+ const invoke = (admission, method, args) => {
233
+ if (!current) {
234
+ recover();
235
+ if (!current) {
236
+ throw lost(method, [], `the wasm instance trapped and no fresh instance is available yet; ${method} did not run`);
237
+ }
238
+ }
239
+ const live = current;
240
+ let callArgs = args;
241
+ let handleId;
242
+ if (takesSessionHandle(method) && typeof args[0] === "string") {
243
+ handleId = args[0];
244
+ const native = nativeId(method, handleId);
245
+ if (native !== handleId)
246
+ callArgs = [native, ...args.slice(1)];
247
+ }
248
+ let openEstimate;
249
+ if (method === "openWorkbookRuntimeSession" && args[0] instanceof Uint8Array) {
250
+ openEstimate = estimateXlsxPackageMemory(args[0]);
251
+ admit(admission, method, openEstimate.estimatedBytes, openEstimate);
252
+ }
253
+ else if (method === "recalculateFormulas" && args[0] instanceof Uint8Array) {
254
+ const estimate = estimateXlsxPackageMemory(args[0]);
255
+ admit(admission, method, estimate.estimatedBytes + estimate.recalcEstimatedBytes, estimate);
256
+ }
257
+ else if (method === "recalculateInSession" && handleId !== undefined) {
258
+ admit(admission, method, liveSessions.get(handleId)?.recalcBytes ?? 0);
259
+ }
260
+ let result;
261
+ try {
262
+ const fn = live.raw[method];
263
+ if (typeof fn !== "function") {
264
+ throw new TypeError(`wasm bridge method ${method} is not a function`);
265
+ }
266
+ result = fn.apply(live.raw, callArgs);
267
+ }
268
+ catch (error) {
269
+ if (!isTrap(error)) {
270
+ currentBytes();
271
+ throw error;
272
+ }
273
+ currentBytes();
274
+ const taken = [...liveSessions.keys()];
275
+ liveSessions.clear();
276
+ for (const id of taken)
277
+ lostSessions.add(id);
278
+ current = undefined;
279
+ generation += 1;
280
+ recover();
281
+ throw lost(method, taken, `the wasm instance trapped in ${method} (${error instanceof Error ? error.message : String(error)}); ` +
282
+ `it was discarded with ${taken.length} session(s)` +
283
+ (current ? " and a fresh instance is live" : ""), error, true);
284
+ }
285
+ currentBytes();
286
+ return afterCall(method, handleId, callArgs[0], result, openEstimate);
287
+ };
288
+ const afterCall = (method, handleId, nativeHandle, result, openEstimate) => {
289
+ if (method === "openWorkbookRuntimeSession") {
290
+ const opened = result;
291
+ if (opened && typeof opened.handleId === "string") {
292
+ const id = externalId(opened.handleId);
293
+ liveSessions.set(id, {
294
+ openBytes: openEstimate?.estimatedBytes ?? 0,
295
+ recalcBytes: openEstimate?.recalcEstimatedBytes ?? 0
296
+ });
297
+ if (id !== opened.handleId)
298
+ return { ...opened, handleId: id };
299
+ }
300
+ return result;
301
+ }
302
+ if (handleId === undefined)
303
+ return result;
304
+ if (method === "disposeWorkbookRuntimeSession") {
305
+ liveSessions.delete(handleId);
306
+ }
307
+ else if (typeof result === "object" &&
308
+ result !== null &&
309
+ result.sessionDisposed === true) {
310
+ // The runtime disposed the session itself (an AI commit that failed
311
+ // after it ran): it no longer counts against the maximum.
312
+ liveSessions.delete(handleId);
313
+ }
314
+ if (generation === 0 || typeof result !== "object" || result === null)
315
+ return result;
316
+ // After a re-instantiation the native results echo native ids; hand the
317
+ // caller back the id it used.
318
+ let rewritten = result;
319
+ if (rewritten.handleId === nativeHandle)
320
+ rewritten = { ...rewritten, handleId };
321
+ const receipt = rewritten.session;
322
+ if (receipt && typeof receipt === "object" && receipt.handleId === nativeHandle) {
323
+ rewritten = { ...rewritten, session: { ...receipt, handleId } };
324
+ }
325
+ return rewritten;
326
+ };
327
+ const guardedRaw = (admission) => {
328
+ const wrappers = new Map();
329
+ return new Proxy({}, {
330
+ get(_target, property) {
331
+ const value = (current?.raw ?? shape)[property];
332
+ if (typeof value !== "function" || typeof property !== "string")
333
+ return value;
334
+ let wrapper = wrappers.get(property);
335
+ if (!wrapper) {
336
+ wrapper = (...args) => invoke(admission, property, args);
337
+ wrappers.set(property, wrapper);
338
+ }
339
+ return wrapper;
340
+ },
341
+ has(_target, property) {
342
+ return property in (current?.raw ?? shape);
343
+ }
344
+ });
345
+ };
346
+ const readback = () => {
347
+ const bytes = currentBytes();
348
+ return {
349
+ currentBytes: bytes,
350
+ peakBytes,
351
+ maximumBytes,
352
+ highWaterBytes,
353
+ aboveHighWater: highWaterBytes !== undefined && bytes !== undefined && bytes >= highWaterBytes,
354
+ generation
355
+ };
356
+ };
357
+ const highWater = (bytes) => {
358
+ if (bytes !== undefined) {
359
+ if (!Number.isFinite(bytes) || bytes <= 0) {
360
+ throw new RangeError(`highWater expects a positive byte count, got ${String(bytes)}`);
361
+ }
362
+ highWaterBytes = bytes;
363
+ }
364
+ return readback();
365
+ };
366
+ const view = (admission) => ({
367
+ raw: guardedRaw(admission),
368
+ wasmMemoryBytes: currentBytes,
369
+ highWater,
370
+ withAdmission: (next) => view(admissionOf(next))
371
+ });
372
+ return view(admissionOf(options));
373
+ }
@@ -1,7 +1,7 @@
1
1
  import type { XlsxFormulaCommitRequest, XlsxFormulaCommitResult, XlsxFormulaRecalculateResult, XlsxLayoutMetricResizeRequest, XlsxLayoutMetricResizeResult, XlsxLayoutMetricVisibilityRequest, XlsxLayoutMetricVisibilityResult, XlsxFrozenPaneRequest, XlsxFrozenPaneResult, XlsxMergeCellsRequest, XlsxMergeCellsResult, XlsxRangeClearCommitRequest, XlsxRangeClearCommitResult, XlsxRangeFillCommitRequest, XlsxRangeFillCommitResult, XlsxRangeFormatCommitRequest, XlsxRangeFormatCommitResult, XlsxRangePasteCommitRequest, XlsxRangePasteCommitResult, XlsxRangeTransferCommitRequest, XlsxRangeTransferCommitResult, XlsxRuntimeSessionExportRequest, XlsxRuntimeSessionMutationReceipt, XlsxRuntimeWarning, XlsxSessionRecalculateRequest, XlsxSheetStructureMutationRequest, XlsxSheetStructureMutationResult, XlsxSheetTabMutationRequest, XlsxSheetTabMutationResult, XlsxShiftCellsCommitRequest, XlsxShiftCellsCommitResult, XlsxTableAppendRowRequest, XlsxTableAppendRowResult } from "../runtime/index.ts";
2
2
  import type { XlsxBlocker } from "../shared.ts";
3
3
  import type { XlsxRuntimeCommandVerdict } from "../runtime/index.ts";
4
- import { type XlsxWasmBridge } from "./index.ts";
4
+ import { type XlsxWasmBridge } from "./bridge-contract.ts";
5
5
  /**
6
6
  * T1 (runtime-session-mutations-v1): host-side routing seam for workbook
7
7
  * mutations.
@@ -1,4 +1,7 @@
1
- import { supportsRuntimeSessionMutations } from "./index.js";
1
+ // X1-D-081: from the target-independent contract, never through the Node
2
+ // loader (./index.ts imports node:crypto, node:fs, node:module, node:path and
3
+ // node:url), so the browser entry (./web.ts) can export the router.
4
+ import { supportsRuntimeSessionMutations } from "./bridge-contract.js";
2
5
  export function createXlsxWorkbookMutationRouter(bridge, init) {
3
6
  let currentBytes = init.bytes;
4
7
  if (init.sessionHandleId !== undefined && supportsRuntimeSessionMutations(bridge)) {
@@ -1,4 +1,6 @@
1
1
  import { type RawXlsxWasmModule, type XlsxWasmBridgeLoadResult } from "./bridge-contract.ts";
2
+ export { BRIDGE_CAPABILITIES, BRIDGE_VERSION, missingXlsxWasmCapabilities, supportsRuntimeSessionMutations, type XlsxRuntimeSessionHandle, type XlsxRuntimeSessionMutationBridge, type XlsxRuntimeSessionOpenRequest, type XlsxSelectionSetRequest, type XlsxWasmBridge, type XlsxWasmBridgeLoadResult, type XlsxWasmBridgeStatus } from "./bridge-contract.ts";
3
+ export { createXlsxWorkbookMutationRouter, type XlsxWorkbookBytesSnapshot, type XlsxWorkbookMutationMode, type XlsxWorkbookMutationRouter, type XlsxWorkbookMutationRouterInit } from "./session-router.ts";
2
4
  /**
3
5
  * Accepted wasm sources for the web glue's init entry point
4
6
  * (wasm-bindgen `--target web`): URL/string/Request/Response stream through
@@ -18,6 +20,13 @@ export interface RawXlsxWasmWebModule extends RawXlsxWasmModule {
18
20
  readonly initSync?: (init: {
19
21
  module: BufferSource | WebAssembly.Module;
20
22
  }) => unknown;
23
+ /**
24
+ * Runtime 0.2.0 glue (scripts/build-wasm.mjs): a fresh glue object with its
25
+ * own instance state per call. With it the loader instantiates from one
26
+ * compiled Module and can replace a trapped instance (R4); without it (an
27
+ * older glue) a trap leaves the bridge lost.
28
+ */
29
+ readonly createXlsxSubstrateGlue?: () => RawXlsxWasmWebModule;
21
30
  }
22
31
  export interface XlsxWasmWebLoadRequest {
23
32
  /**
@@ -39,6 +48,10 @@ export interface XlsxWasmWebLoadRequest {
39
48
  * returning a soft result. Defaults to false.
40
49
  */
41
50
  readonly required?: boolean;
51
+ /** A host cap on what one open or recalculation may be estimated to need (R4). */
52
+ readonly memoryBudgetBytes?: number;
53
+ /** "off" skips pre-admission; trap containment stays on. */
54
+ readonly admission?: "enforce" | "off";
42
55
  }
43
56
  /**
44
57
  * Instantiate and mount the XLSX wasm bridge from the web-target artifact.
@@ -49,9 +62,11 @@ export interface XlsxWasmWebLoadRequest {
49
62
  * with the shared `createXlsxWasmBridge` — the returned `XlsxWasmBridge`
50
63
  * surface is identical across both artifacts.
51
64
  *
52
- * Init is once-per-document: the wasm-bindgen web glue holds module-level
53
- * instance state, so repeated calls reuse the already-initialized module
54
- * (subsequent `wasmSource` values are ignored by the glue). EP3-2 note:
65
+ * With the runtime 0.2.0 glue (`createXlsxSubstrateGlue`), the source is
66
+ * compiled once into a Module and each call mounts a new instance from it;
67
+ * a trapped instance is replaced from the same Module (R4). An older glue
68
+ * holds one module-level instance, so repeated calls reuse it and later
69
+ * `wasmSource` values are ignored. EP3-2 note:
55
70
  * Conductor's `/api` responses are no-store; the wasm asset must be served
56
71
  * from a cacheable route (or preloaded by the host) before the mirror
57
72
  * session ships, or every boot re-downloads the multi-megabyte module.
package/dist/wasm/web.js CHANGED
@@ -7,7 +7,15 @@
7
7
  // Response, or preloaded bytes). This keeps the bindings package free of
8
8
  // dynamic remote imports — self-contained for Beyond Work iframe
9
9
  // deployments where the wasm bytes are host-supplied, never CDN-fetched.
10
- import { createXlsxWasmBridge, validateRawXlsxWasmModule } from "./bridge-contract.js";
10
+ import { createXlsxWasmBridge, createXlsxWasmRuntime, readWasmMemoryLimits, validateRawXlsxWasmModule, XLSX_WASM_LINEAR_MEMORY_MAXIMUM_BYTES } from "./bridge-contract.js";
11
+ // X1-D-081: the browser entry carries what a host needs to gate and drive a
12
+ // mounted bridge without reaching the Node loader (./index.ts): the
13
+ // capability helpers, the BRIDGE_* constants and the mutation router. Each
14
+ // comes from a module with no `node:` import; the bundling guard
15
+ // test/xlsx/browser-entry-node-free.test.ts holds that for every browser
16
+ // entry of the package.
17
+ export { BRIDGE_CAPABILITIES, BRIDGE_VERSION, missingXlsxWasmCapabilities, supportsRuntimeSessionMutations } from "./bridge-contract.js";
18
+ export { createXlsxWorkbookMutationRouter } from "./session-router.js";
11
19
  /**
12
20
  * Instantiate and mount the XLSX wasm bridge from the web-target artifact.
13
21
  *
@@ -17,9 +25,11 @@ import { createXlsxWasmBridge, validateRawXlsxWasmModule } from "./bridge-contra
17
25
  * with the shared `createXlsxWasmBridge` — the returned `XlsxWasmBridge`
18
26
  * surface is identical across both artifacts.
19
27
  *
20
- * Init is once-per-document: the wasm-bindgen web glue holds module-level
21
- * instance state, so repeated calls reuse the already-initialized module
22
- * (subsequent `wasmSource` values are ignored by the glue). EP3-2 note:
28
+ * With the runtime 0.2.0 glue (`createXlsxSubstrateGlue`), the source is
29
+ * compiled once into a Module and each call mounts a new instance from it;
30
+ * a trapped instance is replaced from the same Module (R4). An older glue
31
+ * holds one module-level instance, so repeated calls reuse it and later
32
+ * `wasmSource` values are ignored. EP3-2 note:
23
33
  * Conductor's `/api` responses are no-store; the wasm asset must be served
24
34
  * from a cacheable route (or preloaded by the host) before the mirror
25
35
  * session ships, or every boot re-downloads the multi-megabyte module.
@@ -38,15 +48,53 @@ export async function loadXlsxWasmBridgeWeb(request) {
38
48
  return notMounted("WebAssembly is unavailable in this environment");
39
49
  }
40
50
  try {
41
- await request.glueModule.default({ module_or_path: request.wasmSource });
42
- const validation = validateRawXlsxWasmModule(request.glueModule);
51
+ const glue = request.glueModule;
52
+ const runtimeOptions = {
53
+ ...(request.memoryBudgetBytes !== undefined ? { memoryBudgetBytes: request.memoryBudgetBytes } : {}),
54
+ ...(request.admission !== undefined ? { admission: request.admission } : {})
55
+ };
56
+ if (typeof glue.createXlsxSubstrateGlue !== "function") {
57
+ // An older glue: one module-level instance, no re-instantiation.
58
+ const wasmExports = await glue.default({ module_or_path: request.wasmSource });
59
+ const validation = validateRawXlsxWasmModule(glue);
60
+ if (!validation.ok) {
61
+ return notMounted(validation.reason);
62
+ }
63
+ const runtime = createXlsxWasmRuntime({ instance: instanceSource(glue, wasmExports), ...runtimeOptions });
64
+ return { wasmBinding: "mounted", bridge: createXlsxWasmBridge(glue, validation.status, runtime) };
65
+ }
66
+ const compiled = await compileWasmSource(request.wasmSource);
67
+ const first = glue.createXlsxSubstrateGlue();
68
+ const firstExports = await first.default({ module_or_path: compiled.module });
69
+ const holder = { ...first };
70
+ const validation = validateRawXlsxWasmModule(holder);
43
71
  if (!validation.ok) {
44
72
  return notMounted(validation.reason);
45
73
  }
46
- return {
47
- wasmBinding: "mounted",
48
- bridge: createXlsxWasmBridge(request.glueModule, validation.status)
74
+ const adopt = (fresh, freshExports) => {
75
+ Object.assign(holder, fresh);
76
+ return instanceSource(holder, freshExports);
49
77
  };
78
+ const runtime = createXlsxWasmRuntime({
79
+ instance: instanceSource(holder, firstExports),
80
+ maximumMemoryBytes: compiled.maximumBytes,
81
+ ...runtimeOptions,
82
+ reinstantiate() {
83
+ const fresh = glue.createXlsxSubstrateGlue();
84
+ try {
85
+ // Synchronous where the engine allows it (workers, Node).
86
+ if (typeof fresh.initSync === "function") {
87
+ return adopt(fresh, fresh.initSync({ module: compiled.module }));
88
+ }
89
+ }
90
+ catch {
91
+ // A browser main thread may refuse synchronous instantiation of a
92
+ // large module; fall through to the asynchronous init.
93
+ }
94
+ return fresh.default({ module_or_path: compiled.module }).then((freshExports) => adopt(fresh, freshExports));
95
+ }
96
+ });
97
+ return { wasmBinding: "mounted", bridge: createXlsxWasmBridge(holder, validation.status, runtime) };
50
98
  }
51
99
  catch (error) {
52
100
  if (required) {
@@ -58,3 +106,45 @@ export async function loadXlsxWasmBridgeWeb(request) {
58
106
  };
59
107
  }
60
108
  }
109
+ function instanceSource(raw, wasmExports) {
110
+ const memory = wasmExports?.memory;
111
+ return memory instanceof WebAssembly.Memory ? { raw, memory } : { raw };
112
+ }
113
+ /**
114
+ * Compile the host-supplied source into a Module once, so every instance
115
+ * (the first and any replacement after a trap) instantiates from it.
116
+ */
117
+ async function compileWasmSource(source) {
118
+ if (source instanceof WebAssembly.Module) {
119
+ return { module: source, maximumBytes: XLSX_WASM_LINEAR_MEMORY_MAXIMUM_BYTES };
120
+ }
121
+ if (typeof source === "string" || source instanceof URL || (typeof Request === "function" && source instanceof Request)) {
122
+ return compileWasmSource(await fetch(source));
123
+ }
124
+ if (typeof Response === "function" && source instanceof Response) {
125
+ if (typeof WebAssembly.compileStreaming === "function") {
126
+ try {
127
+ const module = await WebAssembly.compileStreaming(source.clone());
128
+ return { module, maximumBytes: XLSX_WASM_LINEAR_MEMORY_MAXIMUM_BYTES };
129
+ }
130
+ catch {
131
+ // Wrong MIME type or no streaming support: compile from the bytes.
132
+ }
133
+ }
134
+ return compileWasmSource(await source.arrayBuffer());
135
+ }
136
+ let view;
137
+ if (source instanceof ArrayBuffer) {
138
+ view = new Uint8Array(source);
139
+ }
140
+ else if (ArrayBuffer.isView(source)) {
141
+ view = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
142
+ }
143
+ else {
144
+ throw new TypeError("unsupported wasm source: expected a URL, Request, Response, BufferSource or WebAssembly.Module");
145
+ }
146
+ return {
147
+ module: await WebAssembly.compile(source),
148
+ maximumBytes: readWasmMemoryLimits(view)?.maximumBytes ?? XLSX_WASM_LINEAR_MEMORY_MAXIMUM_BYTES
149
+ };
150
+ }