@beyondwork/xlsx-substrate-bindings 0.1.0 → 0.2.0
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.
- package/README.md +136 -0
- package/dist/ai/agent-metadata.d.ts +363 -0
- package/dist/ai/agent-metadata.js +227 -0
- package/dist/ai/index.d.ts +5 -1
- package/dist/ai/index.js +6 -0
- package/dist/ai/mutation-bridge.d.ts +82 -0
- package/dist/ai/mutation-bridge.js +179 -0
- package/dist/ai/types.d.ts +448 -3
- package/dist/index.d.ts +7 -3
- package/dist/index.js +20 -2
- package/dist/runtime/index.d.ts +1 -1
- package/dist/runtime/types.d.ts +57 -1
- package/dist/wasm/ai-session-bridge.d.ts +97 -0
- package/dist/wasm/ai-session-bridge.js +154 -0
- package/dist/wasm/bridge-contract.d.ts +108 -6
- package/dist/wasm/bridge-contract.js +146 -7
- package/dist/wasm/index.d.ts +43 -2
- package/dist/wasm/index.js +253 -23
- package/dist/wasm/memory-budget.d.ts +77 -0
- package/dist/wasm/memory-budget.js +532 -0
- package/dist/wasm/runtime-guard.d.ts +141 -0
- package/dist/wasm/runtime-guard.js +373 -0
- package/dist/wasm/web.d.ts +16 -3
- package/dist/wasm/web.js +91 -9
- package/generated/wasm-web/xlsx_substrate_wasm.d.ts +66 -0
- package/generated/wasm-web/xlsx_substrate_wasm.js +2488 -2104
- package/generated/wasm-web/xlsx_substrate_wasm_bg.wasm +0 -0
- package/generated/wasm-web/xlsx_substrate_wasm_bg.wasm.d.ts +15 -0
- package/package.json +18 -4
- package/dist/wasm/chart-test-fixture.d.ts +0 -19
- package/dist/wasm/chart-test-fixture.js +0 -42
- package/dist/wasm/media-test-fixture.d.ts +0 -44
- package/dist/wasm/media-test-fixture.js +0 -160
- package/dist/wasm/volatile-test-fixture.d.ts +0 -7
- package/dist/wasm/volatile-test-fixture.js +0 -35
- package/generated/wasm/package.json +0 -3
- package/generated/wasm/sheet-window-binary.mjs +0 -482
- package/generated/wasm/snippets/ironcalc_base-89b4f49381e1e289/inline0.js +0 -45
- package/generated/wasm/xlsx_substrate_wasm.d.ts +0 -336
- package/generated/wasm/xlsx_substrate_wasm.js +0 -2108
- package/generated/wasm/xlsx_substrate_wasm_bg.wasm +0 -0
- package/generated/wasm/xlsx_substrate_wasm_bg.wasm.d.ts +0 -105
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import type { RawXlsxWasmModule } from "./bridge-contract.ts";
|
|
2
|
+
import { type XlsxPackageMemoryEstimate } from "./memory-budget.ts";
|
|
3
|
+
export type XlsxWasmBridgeErrorCode = "wasm-instance-lost" | "out-of-memory-budget";
|
|
4
|
+
export interface XlsxWasmBridgeErrorDetails {
|
|
5
|
+
readonly code: XlsxWasmBridgeErrorCode;
|
|
6
|
+
/** The bridge method that was refused or trapped. */
|
|
7
|
+
readonly method: string;
|
|
8
|
+
readonly message: string;
|
|
9
|
+
/**
|
|
10
|
+
* wasm-instance-lost: the sessions that no longer exist. On the trap itself
|
|
11
|
+
* this is every session the instance held; afterwards it is the handle the
|
|
12
|
+
* caller used.
|
|
13
|
+
*/
|
|
14
|
+
readonly lostSessions?: readonly string[];
|
|
15
|
+
/** wasm-instance-lost: true when a fresh instance is already live, so the next call runs. */
|
|
16
|
+
readonly recovered?: boolean;
|
|
17
|
+
/**
|
|
18
|
+
* wasm-instance-lost: true on the error the trap itself raised (the call
|
|
19
|
+
* that trapped). False on a later call that used a lost handle or found
|
|
20
|
+
* the runtime still recovering.
|
|
21
|
+
*/
|
|
22
|
+
readonly trapped?: boolean;
|
|
23
|
+
/** out-of-memory-budget: what the refused call was estimated to need. */
|
|
24
|
+
readonly estimatedBytes?: number;
|
|
25
|
+
/** out-of-memory-budget: what the budget allowed at that moment. */
|
|
26
|
+
readonly budgetBytes?: number;
|
|
27
|
+
/** out-of-memory-budget on an open or bytes recalculation: the package estimate. */
|
|
28
|
+
readonly estimate?: XlsxPackageMemoryEstimate;
|
|
29
|
+
readonly cause?: unknown;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* The typed errors the bridge throws instead of a raw trap or an
|
|
33
|
+
* out-of-memory abort. Hosts branch on `code` through
|
|
34
|
+
* `isXlsxWasmBridgeError`.
|
|
35
|
+
*
|
|
36
|
+
* Crossing a thread: structured clone (`postMessage`, `structuredClone`)
|
|
37
|
+
* keeps only the standard error names and drops own properties, so a cloned
|
|
38
|
+
* `XlsxWasmBridgeError` arrives as a plain `Error` with no `code` and is not
|
|
39
|
+
* recognised. Post `serializeXlsxWasmBridgeError(error)` instead; the plain
|
|
40
|
+
* object it returns survives the clone, `isXlsxWasmBridgeError` recognises
|
|
41
|
+
* it, and `deserializeXlsxWasmBridgeError` turns it back into an instance.
|
|
42
|
+
*/
|
|
43
|
+
export declare class XlsxWasmBridgeError extends Error {
|
|
44
|
+
readonly code: XlsxWasmBridgeErrorCode;
|
|
45
|
+
readonly method: string;
|
|
46
|
+
readonly lostSessions: readonly string[];
|
|
47
|
+
readonly recovered: boolean;
|
|
48
|
+
readonly trapped: boolean;
|
|
49
|
+
readonly estimatedBytes?: number;
|
|
50
|
+
readonly budgetBytes?: number;
|
|
51
|
+
readonly estimate?: XlsxPackageMemoryEstimate;
|
|
52
|
+
constructor(details: XlsxWasmBridgeErrorDetails);
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* True for an `XlsxWasmBridgeError` from any realm, and for the plain object
|
|
56
|
+
* `serializeXlsxWasmBridgeError` returns. A raw structured clone of the error
|
|
57
|
+
* is not recognised: it has lost its name and code (see the class comment).
|
|
58
|
+
*/
|
|
59
|
+
export declare function isXlsxWasmBridgeError(value: unknown, code?: XlsxWasmBridgeErrorCode): value is XlsxWasmBridgeError;
|
|
60
|
+
/** The plain-object form of an `XlsxWasmBridgeError`, safe to post to another thread. */
|
|
61
|
+
export interface SerializedXlsxWasmBridgeError {
|
|
62
|
+
readonly name: "XlsxWasmBridgeError";
|
|
63
|
+
readonly code: XlsxWasmBridgeErrorCode;
|
|
64
|
+
readonly method: string;
|
|
65
|
+
readonly message: string;
|
|
66
|
+
readonly lostSessions: readonly string[];
|
|
67
|
+
readonly recovered: boolean;
|
|
68
|
+
readonly trapped: boolean;
|
|
69
|
+
readonly estimatedBytes?: number;
|
|
70
|
+
readonly budgetBytes?: number;
|
|
71
|
+
readonly estimate?: XlsxPackageMemoryEstimate;
|
|
72
|
+
}
|
|
73
|
+
/** A plain object carrying every field of `error` except `cause`, for `postMessage`. */
|
|
74
|
+
export declare function serializeXlsxWasmBridgeError(error: XlsxWasmBridgeError): SerializedXlsxWasmBridgeError;
|
|
75
|
+
/** An `XlsxWasmBridgeError` instance from its serialized form, or undefined when `value` is not one. */
|
|
76
|
+
export declare function deserializeXlsxWasmBridgeError(value: unknown): XlsxWasmBridgeError | undefined;
|
|
77
|
+
/** One live wasm instance as a loader sees it. */
|
|
78
|
+
export interface XlsxWasmInstanceSource {
|
|
79
|
+
/** The raw glue object whose functions call into this instance. */
|
|
80
|
+
readonly raw: RawXlsxWasmModule;
|
|
81
|
+
/** The instance's linear memory, when the loader can see it. */
|
|
82
|
+
readonly memory?: WebAssembly.Memory;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* A fresh instance from the cached Module. Synchronous where the engine
|
|
86
|
+
* allows it; a promise (a browser main thread that refuses synchronous
|
|
87
|
+
* instantiation of a large module) leaves the runtime recovering until it
|
|
88
|
+
* settles, and calls made meanwhile get `wasm-instance-lost`.
|
|
89
|
+
*/
|
|
90
|
+
export type XlsxWasmReinstantiate = () => XlsxWasmInstanceSource | Promise<XlsxWasmInstanceSource>;
|
|
91
|
+
/**
|
|
92
|
+
* How pre-admission treats one bridge's opens and recalculations.
|
|
93
|
+
*
|
|
94
|
+
* The check counts estimates, not `memory.buffer.byteLength`. Linear memory
|
|
95
|
+
* never shrinks: after a large workbook is disposed its pages stay, and the
|
|
96
|
+
* allocator reuses them, but JavaScript cannot see that. So the bridge keeps
|
|
97
|
+
* the open estimate of every live session it opened and admits a call when
|
|
98
|
+
* its own estimate fits beside them under the linear-memory maximum, and
|
|
99
|
+
* under `memoryBudgetBytes` when the host set one.
|
|
100
|
+
*/
|
|
101
|
+
export interface XlsxWasmAdmissionOptions {
|
|
102
|
+
/** A host cap on what one open or recalculation may be estimated to need. */
|
|
103
|
+
readonly memoryBudgetBytes?: number;
|
|
104
|
+
/** "off" skips pre-admission (trap containment stays on). Defaults to "enforce". */
|
|
105
|
+
readonly admission?: "enforce" | "off";
|
|
106
|
+
}
|
|
107
|
+
export interface XlsxWasmRuntimeOptions extends XlsxWasmAdmissionOptions {
|
|
108
|
+
readonly instance: XlsxWasmInstanceSource;
|
|
109
|
+
/** Absent: a trap leaves the runtime lost for good (every call answers wasm-instance-lost). */
|
|
110
|
+
readonly reinstantiate?: XlsxWasmReinstantiate;
|
|
111
|
+
/** The module's link-time linear-memory maximum. Defaults to XLSX_WASM_LINEAR_MEMORY_MAXIMUM_BYTES. */
|
|
112
|
+
readonly maximumMemoryBytes?: number;
|
|
113
|
+
}
|
|
114
|
+
export interface XlsxWasmMemoryReadback {
|
|
115
|
+
/** `memory.buffer.byteLength` of the live instance; undefined when the memory is not visible. */
|
|
116
|
+
readonly currentBytes: number | undefined;
|
|
117
|
+
/** The largest byteLength seen on any instance this runtime has run. */
|
|
118
|
+
readonly peakBytes: number;
|
|
119
|
+
/** The linear-memory maximum the module was linked with. */
|
|
120
|
+
readonly maximumBytes: number;
|
|
121
|
+
/** The mark set with `highWater(bytes)`, if any. */
|
|
122
|
+
readonly highWaterBytes: number | undefined;
|
|
123
|
+
/** True when the live instance's memory is at or above the mark: recycle the instance or worker. */
|
|
124
|
+
readonly aboveHighWater: boolean;
|
|
125
|
+
/** How many times a trap replaced the instance. */
|
|
126
|
+
readonly generation: number;
|
|
127
|
+
}
|
|
128
|
+
export interface XlsxWasmRuntime {
|
|
129
|
+
/** The raw module the bridge calls through: every function is guarded. */
|
|
130
|
+
readonly raw: RawXlsxWasmModule;
|
|
131
|
+
wasmMemoryBytes(): number | undefined;
|
|
132
|
+
highWater(bytes?: number): XlsxWasmMemoryReadback;
|
|
133
|
+
/**
|
|
134
|
+
* A view of the same instance (same sessions, same trap containment, same
|
|
135
|
+
* readbacks) whose calls are admitted under `options` instead of the
|
|
136
|
+
* runtime's own. A shared instance hands each host its own budget this
|
|
137
|
+
* way without changing anyone else's.
|
|
138
|
+
*/
|
|
139
|
+
withAdmission(options: XlsxWasmAdmissionOptions): XlsxWasmRuntime;
|
|
140
|
+
}
|
|
141
|
+
export declare function createXlsxWasmRuntime(options: XlsxWasmRuntimeOptions): XlsxWasmRuntime;
|
|
@@ -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
|
+
}
|
package/dist/wasm/web.d.ts
CHANGED
|
@@ -18,6 +18,13 @@ export interface RawXlsxWasmWebModule extends RawXlsxWasmModule {
|
|
|
18
18
|
readonly initSync?: (init: {
|
|
19
19
|
module: BufferSource | WebAssembly.Module;
|
|
20
20
|
}) => unknown;
|
|
21
|
+
/**
|
|
22
|
+
* Runtime 0.2.0 glue (scripts/build-wasm.mjs): a fresh glue object with its
|
|
23
|
+
* own instance state per call. With it the loader instantiates from one
|
|
24
|
+
* compiled Module and can replace a trapped instance (R4); without it (an
|
|
25
|
+
* older glue) a trap leaves the bridge lost.
|
|
26
|
+
*/
|
|
27
|
+
readonly createXlsxSubstrateGlue?: () => RawXlsxWasmWebModule;
|
|
21
28
|
}
|
|
22
29
|
export interface XlsxWasmWebLoadRequest {
|
|
23
30
|
/**
|
|
@@ -39,6 +46,10 @@ export interface XlsxWasmWebLoadRequest {
|
|
|
39
46
|
* returning a soft result. Defaults to false.
|
|
40
47
|
*/
|
|
41
48
|
readonly required?: boolean;
|
|
49
|
+
/** A host cap on what one open or recalculation may be estimated to need (R4). */
|
|
50
|
+
readonly memoryBudgetBytes?: number;
|
|
51
|
+
/** "off" skips pre-admission; trap containment stays on. */
|
|
52
|
+
readonly admission?: "enforce" | "off";
|
|
42
53
|
}
|
|
43
54
|
/**
|
|
44
55
|
* Instantiate and mount the XLSX wasm bridge from the web-target artifact.
|
|
@@ -49,9 +60,11 @@ export interface XlsxWasmWebLoadRequest {
|
|
|
49
60
|
* with the shared `createXlsxWasmBridge` — the returned `XlsxWasmBridge`
|
|
50
61
|
* surface is identical across both artifacts.
|
|
51
62
|
*
|
|
52
|
-
*
|
|
53
|
-
*
|
|
54
|
-
*
|
|
63
|
+
* With the runtime 0.2.0 glue (`createXlsxSubstrateGlue`), the source is
|
|
64
|
+
* compiled once into a Module and each call mounts a new instance from it;
|
|
65
|
+
* a trapped instance is replaced from the same Module (R4). An older glue
|
|
66
|
+
* holds one module-level instance, so repeated calls reuse it and later
|
|
67
|
+
* `wasmSource` values are ignored. EP3-2 note:
|
|
55
68
|
* Conductor's `/api` responses are no-store; the wasm asset must be served
|
|
56
69
|
* from a cacheable route (or preloaded by the host) before the mirror
|
|
57
70
|
* session ships, or every boot re-downloads the multi-megabyte module.
|
package/dist/wasm/web.js
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
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
11
|
/**
|
|
12
12
|
* Instantiate and mount the XLSX wasm bridge from the web-target artifact.
|
|
13
13
|
*
|
|
@@ -17,9 +17,11 @@ import { createXlsxWasmBridge, validateRawXlsxWasmModule } from "./bridge-contra
|
|
|
17
17
|
* with the shared `createXlsxWasmBridge` — the returned `XlsxWasmBridge`
|
|
18
18
|
* surface is identical across both artifacts.
|
|
19
19
|
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
20
|
+
* With the runtime 0.2.0 glue (`createXlsxSubstrateGlue`), the source is
|
|
21
|
+
* compiled once into a Module and each call mounts a new instance from it;
|
|
22
|
+
* a trapped instance is replaced from the same Module (R4). An older glue
|
|
23
|
+
* holds one module-level instance, so repeated calls reuse it and later
|
|
24
|
+
* `wasmSource` values are ignored. EP3-2 note:
|
|
23
25
|
* Conductor's `/api` responses are no-store; the wasm asset must be served
|
|
24
26
|
* from a cacheable route (or preloaded by the host) before the mirror
|
|
25
27
|
* session ships, or every boot re-downloads the multi-megabyte module.
|
|
@@ -38,15 +40,53 @@ export async function loadXlsxWasmBridgeWeb(request) {
|
|
|
38
40
|
return notMounted("WebAssembly is unavailable in this environment");
|
|
39
41
|
}
|
|
40
42
|
try {
|
|
41
|
-
|
|
42
|
-
const
|
|
43
|
+
const glue = request.glueModule;
|
|
44
|
+
const runtimeOptions = {
|
|
45
|
+
...(request.memoryBudgetBytes !== undefined ? { memoryBudgetBytes: request.memoryBudgetBytes } : {}),
|
|
46
|
+
...(request.admission !== undefined ? { admission: request.admission } : {})
|
|
47
|
+
};
|
|
48
|
+
if (typeof glue.createXlsxSubstrateGlue !== "function") {
|
|
49
|
+
// An older glue: one module-level instance, no re-instantiation.
|
|
50
|
+
const wasmExports = await glue.default({ module_or_path: request.wasmSource });
|
|
51
|
+
const validation = validateRawXlsxWasmModule(glue);
|
|
52
|
+
if (!validation.ok) {
|
|
53
|
+
return notMounted(validation.reason);
|
|
54
|
+
}
|
|
55
|
+
const runtime = createXlsxWasmRuntime({ instance: instanceSource(glue, wasmExports), ...runtimeOptions });
|
|
56
|
+
return { wasmBinding: "mounted", bridge: createXlsxWasmBridge(glue, validation.status, runtime) };
|
|
57
|
+
}
|
|
58
|
+
const compiled = await compileWasmSource(request.wasmSource);
|
|
59
|
+
const first = glue.createXlsxSubstrateGlue();
|
|
60
|
+
const firstExports = await first.default({ module_or_path: compiled.module });
|
|
61
|
+
const holder = { ...first };
|
|
62
|
+
const validation = validateRawXlsxWasmModule(holder);
|
|
43
63
|
if (!validation.ok) {
|
|
44
64
|
return notMounted(validation.reason);
|
|
45
65
|
}
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
66
|
+
const adopt = (fresh, freshExports) => {
|
|
67
|
+
Object.assign(holder, fresh);
|
|
68
|
+
return instanceSource(holder, freshExports);
|
|
49
69
|
};
|
|
70
|
+
const runtime = createXlsxWasmRuntime({
|
|
71
|
+
instance: instanceSource(holder, firstExports),
|
|
72
|
+
maximumMemoryBytes: compiled.maximumBytes,
|
|
73
|
+
...runtimeOptions,
|
|
74
|
+
reinstantiate() {
|
|
75
|
+
const fresh = glue.createXlsxSubstrateGlue();
|
|
76
|
+
try {
|
|
77
|
+
// Synchronous where the engine allows it (workers, Node).
|
|
78
|
+
if (typeof fresh.initSync === "function") {
|
|
79
|
+
return adopt(fresh, fresh.initSync({ module: compiled.module }));
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
// A browser main thread may refuse synchronous instantiation of a
|
|
84
|
+
// large module; fall through to the asynchronous init.
|
|
85
|
+
}
|
|
86
|
+
return fresh.default({ module_or_path: compiled.module }).then((freshExports) => adopt(fresh, freshExports));
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
return { wasmBinding: "mounted", bridge: createXlsxWasmBridge(holder, validation.status, runtime) };
|
|
50
90
|
}
|
|
51
91
|
catch (error) {
|
|
52
92
|
if (required) {
|
|
@@ -58,3 +98,45 @@ export async function loadXlsxWasmBridgeWeb(request) {
|
|
|
58
98
|
};
|
|
59
99
|
}
|
|
60
100
|
}
|
|
101
|
+
function instanceSource(raw, wasmExports) {
|
|
102
|
+
const memory = wasmExports?.memory;
|
|
103
|
+
return memory instanceof WebAssembly.Memory ? { raw, memory } : { raw };
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Compile the host-supplied source into a Module once, so every instance
|
|
107
|
+
* (the first and any replacement after a trap) instantiates from it.
|
|
108
|
+
*/
|
|
109
|
+
async function compileWasmSource(source) {
|
|
110
|
+
if (source instanceof WebAssembly.Module) {
|
|
111
|
+
return { module: source, maximumBytes: XLSX_WASM_LINEAR_MEMORY_MAXIMUM_BYTES };
|
|
112
|
+
}
|
|
113
|
+
if (typeof source === "string" || source instanceof URL || (typeof Request === "function" && source instanceof Request)) {
|
|
114
|
+
return compileWasmSource(await fetch(source));
|
|
115
|
+
}
|
|
116
|
+
if (typeof Response === "function" && source instanceof Response) {
|
|
117
|
+
if (typeof WebAssembly.compileStreaming === "function") {
|
|
118
|
+
try {
|
|
119
|
+
const module = await WebAssembly.compileStreaming(source.clone());
|
|
120
|
+
return { module, maximumBytes: XLSX_WASM_LINEAR_MEMORY_MAXIMUM_BYTES };
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
// Wrong MIME type or no streaming support: compile from the bytes.
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return compileWasmSource(await source.arrayBuffer());
|
|
127
|
+
}
|
|
128
|
+
let view;
|
|
129
|
+
if (source instanceof ArrayBuffer) {
|
|
130
|
+
view = new Uint8Array(source);
|
|
131
|
+
}
|
|
132
|
+
else if (ArrayBuffer.isView(source)) {
|
|
133
|
+
view = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
|
|
134
|
+
}
|
|
135
|
+
else {
|
|
136
|
+
throw new TypeError("unsupported wasm source: expected a URL, Request, Response, BufferSource or WebAssembly.Module");
|
|
137
|
+
}
|
|
138
|
+
return {
|
|
139
|
+
module: await WebAssembly.compile(source),
|
|
140
|
+
maximumBytes: readWasmMemoryLimits(view)?.maximumBytes ?? XLSX_WASM_LINEAR_MEMORY_MAXIMUM_BYTES
|
|
141
|
+
};
|
|
142
|
+
}
|