@shing.wong/sure-wasm-helper 0.0.0-stage → 0.1.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.
@@ -0,0 +1,76 @@
1
+ export interface Effect {
2
+ kind: string;
3
+ data: unknown;
4
+ id?: string | number;
5
+ }
6
+ export interface AdapterFeedback {
7
+ kind: string;
8
+ data: unknown;
9
+ id?: string | number;
10
+ }
11
+ /**
12
+ * Translates a domain module's exports into the reactor contract.
13
+ *
14
+ * An adapter performs no I/O and contains no domain logic: it only calls the
15
+ * module and returns plain JSON values. `drain` must return an empty array when
16
+ * the module is idle, and `feed` receives the result of `onEffect`.
17
+ */
18
+ export interface CoreAbiAdapter<TInstance = WebAssembly.Instance> {
19
+ name: string;
20
+ version(instance: TInstance): number | string;
21
+ init(instance: TInstance, config?: unknown): number;
22
+ drain(instance: TInstance): Effect[];
23
+ feed(instance: TInstance, feedback: AdapterFeedback): number;
24
+ /** Called after each drain+execute round; return false to stop drive(). */
25
+ until?(instance: TInstance): boolean;
26
+ }
27
+ export interface MountWasmCoreOptions<TInstance = WebAssembly.Instance> {
28
+ /** Bytes or a compiled module. Omit only when `instance` is supplied. */
29
+ wasmBytes?: BufferSource | WebAssembly.Module;
30
+ /** A pre-instantiated domain wrapper (for example an asc binding object). */
31
+ instance?: TInstance;
32
+ /**
33
+ * Custom instantiation hook. Receives the compiled module and the `sure`
34
+ * import object; use this for bindings that adapt names and strings (asc).
35
+ */
36
+ instantiate?: (module: WebAssembly.Module, imports: WebAssembly.Imports) => Promise<TInstance>;
37
+ /** Optional host imports, passed to the module as the `sure` namespace. */
38
+ ports?: Record<string, unknown>;
39
+ onEffect: (effect: Effect) => unknown | Promise<unknown>;
40
+ /** Expected ABI version. Defaults to 1 for sureAbi; unset for custom adapters. */
41
+ expectedAbi?: number | string;
42
+ /** Domain adapter. Defaults to `sureAbi`. */
43
+ abi?: CoreAbiAdapter<TInstance>;
44
+ /** JSON-serialisable config passed to init. Defaults to `{}`. */
45
+ config?: unknown;
46
+ /** Maximum drain rounds per drive(). Defaults to 1000. */
47
+ maxSteps?: number;
48
+ onLog?: (level: string, message: string) => void;
49
+ }
50
+ export interface CoreHandle<TInstance = WebAssembly.Instance> {
51
+ abiVersion: number | string;
52
+ /** Run the reactor until idle, `until` returns false, or the guard trips. */
53
+ drive(): Promise<number>;
54
+ /** Deliver an external result. Returns the module's raw return code. */
55
+ feed(kind: string, data: unknown, id?: string | number): number;
56
+ close(): void;
57
+ /** The raw instance, for a domain's own exports after the handshake. */
58
+ instance: TInstance;
59
+ }
60
+ /** A public helper error with a stable `.code`. */
61
+ export declare class HelperError extends Error {
62
+ readonly code: string;
63
+ constructor(code: string, message: string, options?: {
64
+ cause?: unknown;
65
+ });
66
+ }
67
+ /** The built-in `sure_*` ABI v1 adapter. */
68
+ export declare const sureAbi: CoreAbiAdapter<WebAssembly.Instance>;
69
+ /**
70
+ * Instantiate a reactor and hand back a drive/feed handle.
71
+ *
72
+ * With no `abi`, the module must implement `sure_*` ABI v1 and `expectedAbi`
73
+ * defaults to 1. With an adapter, the version is checked only when
74
+ * `expectedAbi` is supplied.
75
+ */
76
+ export declare function mountWasmCore<TInstance = WebAssembly.Instance>(options: MountWasmCoreOptions<TInstance>): Promise<CoreHandle<TInstance>>;
@@ -0,0 +1,271 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Generic WebAssembly reactor host: instantiate a module, drain effects, feed
3
+ // results back, repeat. The default ABI is the documented `sure_*` v1 ABI; a
4
+ // domain may supply a CoreAbiAdapter instead.
5
+ const encoder = new TextEncoder();
6
+ const decoder = new TextDecoder("utf-8", { fatal: true });
7
+ /** A public helper error with a stable `.code`. */
8
+ export class HelperError extends Error {
9
+ code;
10
+ constructor(code, message, options) {
11
+ super(message, options);
12
+ this.name = "HelperError";
13
+ this.code = code;
14
+ }
15
+ }
16
+ function fail(code, message, cause) {
17
+ throw new HelperError(code, message, { cause });
18
+ }
19
+ function isRecord(value) {
20
+ return typeof value === "object" && value !== null && !Array.isArray(value);
21
+ }
22
+ function memoryOf(instance) {
23
+ const memory = instance.exports["memory"];
24
+ if (!(memory instanceof WebAssembly.Memory)) {
25
+ fail("E_WASM_MEMORY", "module does not export a WebAssembly.Memory named 'memory'");
26
+ }
27
+ return memory;
28
+ }
29
+ function readMemory(memory, ptr, len) {
30
+ if (!Number.isInteger(ptr) || !Number.isInteger(len) || ptr < 0 || len < 0) {
31
+ fail("E_WASM_MEMORY", `invalid memory range (ptr=${String(ptr)}, len=${String(len)})`);
32
+ }
33
+ if (ptr + len > memory.buffer.byteLength) {
34
+ fail("E_WASM_MEMORY", `memory range out of bounds (ptr=${ptr}, len=${len}, size=${memory.buffer.byteLength})`);
35
+ }
36
+ return new Uint8Array(memory.buffer, ptr, len);
37
+ }
38
+ /**
39
+ * Write bytes at the current end of linear memory and grow for them.
40
+ *
41
+ * The region is scratch: the module may reuse or grow over it after the call
42
+ * returns, so a module that wants to keep a payload must copy it. This avoids
43
+ * assuming an allocator in ABI v1.
44
+ */
45
+ function writeScratch(memory, bytes) {
46
+ if (bytes.length === 0)
47
+ return { ptr: 0, len: 0 };
48
+ const ptr = memory.buffer.byteLength;
49
+ const pages = Math.ceil(bytes.length / 65536);
50
+ let result;
51
+ try {
52
+ result = memory.grow(pages);
53
+ }
54
+ catch (error) {
55
+ fail("E_WASM_MEMORY", `could not grow wasm memory by ${pages} page(s)`, error);
56
+ }
57
+ if (result < 0)
58
+ fail("E_WASM_MEMORY", `could not grow wasm memory by ${pages} page(s)`);
59
+ new Uint8Array(memory.buffer, ptr, bytes.length).set(bytes);
60
+ return { ptr, len: bytes.length };
61
+ }
62
+ function decodeUtf8(bytes) {
63
+ try {
64
+ return decoder.decode(bytes);
65
+ }
66
+ catch (error) {
67
+ fail("E_WASM_EFFECT_INVALID", "module returned invalid UTF-8", error);
68
+ }
69
+ }
70
+ function validateEffects(parsed) {
71
+ if (!Array.isArray(parsed)) {
72
+ fail("E_WASM_EFFECT_INVALID", `effect payload must be a JSON array, got ${typeof parsed}`);
73
+ }
74
+ return parsed.map((entry, index) => {
75
+ if (!isRecord(entry)) {
76
+ fail("E_WASM_EFFECT_INVALID", `effect ${index} is not an object`);
77
+ }
78
+ const kind = entry["kind"];
79
+ if (typeof kind !== "string" || kind.length === 0) {
80
+ fail("E_WASM_EFFECT_INVALID", `effect ${index} needs a non-empty string 'kind'`);
81
+ }
82
+ const id = entry["id"];
83
+ if (id !== undefined && typeof id !== "string" && typeof id !== "number") {
84
+ fail("E_WASM_EFFECT_INVALID", `effect ${index} 'id' must be a string or number`);
85
+ }
86
+ const effect = {
87
+ kind,
88
+ data: Object.prototype.hasOwnProperty.call(entry, "data") ? entry["data"] : null,
89
+ };
90
+ if (id !== undefined)
91
+ effect.id = id;
92
+ return effect;
93
+ });
94
+ }
95
+ function exportFunction(instance, name) {
96
+ const fn = instance.exports[name];
97
+ if (typeof fn !== "function") {
98
+ fail("E_WASM_ABI_MISMATCH", `module does not export '${name}'`);
99
+ }
100
+ return fn;
101
+ }
102
+ function checkFeedCode(code, name) {
103
+ if (typeof code !== "number" || !Number.isInteger(code)) {
104
+ fail("E_WASM_EFFECT_INVALID", `${name} returned a non-integer code`);
105
+ }
106
+ return code;
107
+ }
108
+ /** The built-in `sure_*` ABI v1 adapter. */
109
+ export const sureAbi = {
110
+ name: "sure-v1",
111
+ version(instance) {
112
+ return exportFunction(instance, "sure_abi_version")();
113
+ },
114
+ init(instance, config) {
115
+ const memory = memoryOf(instance);
116
+ const bytes = encoder.encode(JSON.stringify(config ?? {}));
117
+ const scratch = writeScratch(memory, bytes);
118
+ return checkFeedCode(exportFunction(instance, "sure_init")(scratch.ptr, scratch.len), "sure_init");
119
+ },
120
+ drain(instance) {
121
+ const lenFn = exportFunction(instance, "sure_effects_len");
122
+ const ptrFn = exportFunction(instance, "sure_effects");
123
+ const len = checkFeedCode(lenFn(), "sure_effects_len");
124
+ if (len === 0)
125
+ return [];
126
+ if (len < 0)
127
+ fail("E_WASM_EFFECT_INVALID", `sure_effects_len returned ${len}`);
128
+ const ptr = checkFeedCode(ptrFn(), "sure_effects");
129
+ const memory = memoryOf(instance);
130
+ let parsed;
131
+ try {
132
+ parsed = JSON.parse(decodeUtf8(readMemory(memory, ptr, len)));
133
+ }
134
+ catch (error) {
135
+ if (error instanceof HelperError)
136
+ throw error;
137
+ fail("E_WASM_EFFECT_INVALID", `could not parse effect JSON: ${String(error)}`, error);
138
+ }
139
+ return validateEffects(parsed);
140
+ },
141
+ feed(instance, feedback) {
142
+ const memory = memoryOf(instance);
143
+ const kind = encoder.encode(feedback.kind);
144
+ const data = encoder.encode(JSON.stringify(feedback.data === undefined ? {} : feedback.data));
145
+ // Keep both strings in one scratch allocation so a module can read them
146
+ // from a single contiguous region.
147
+ const combined = new Uint8Array(kind.length + data.length);
148
+ combined.set(kind, 0);
149
+ combined.set(data, kind.length);
150
+ const scratch = writeScratch(memory, combined);
151
+ return checkFeedCode(exportFunction(instance, "sure_feed")(scratch.ptr, kind.length, scratch.ptr + kind.length, data.length), "sure_feed");
152
+ },
153
+ };
154
+ async function compile(wasmBytes) {
155
+ if (wasmBytes instanceof WebAssembly.Module)
156
+ return wasmBytes;
157
+ try {
158
+ return await WebAssembly.compile(wasmBytes);
159
+ }
160
+ catch (error) {
161
+ fail("E_WASM_ABI_MISMATCH", `could not compile wasm module: ${String(error)}`, error);
162
+ }
163
+ }
164
+ /**
165
+ * Instantiate a reactor and hand back a drive/feed handle.
166
+ *
167
+ * With no `abi`, the module must implement `sure_*` ABI v1 and `expectedAbi`
168
+ * defaults to 1. With an adapter, the version is checked only when
169
+ * `expectedAbi` is supplied.
170
+ */
171
+ export async function mountWasmCore(options) {
172
+ const abi = (options.abi ?? sureAbi);
173
+ const expectedAbi = options.expectedAbi !== undefined ? options.expectedAbi : options.abi === undefined ? 1 : undefined;
174
+ const maxSteps = options.maxSteps ?? 1000;
175
+ if (!Number.isInteger(maxSteps) || maxSteps < 1) {
176
+ throw new TypeError("maxSteps must be a positive integer");
177
+ }
178
+ if (typeof options.onEffect !== "function") {
179
+ throw new TypeError("onEffect must be a function");
180
+ }
181
+ const log = options.onLog ?? (() => { });
182
+ const imports = { sure: options.ports ?? {} };
183
+ let instance;
184
+ if (options.instance !== undefined) {
185
+ instance = options.instance;
186
+ }
187
+ else if (options.wasmBytes === undefined) {
188
+ throw new TypeError("mountWasmCore needs wasmBytes or instance");
189
+ }
190
+ else {
191
+ const module = await compile(options.wasmBytes);
192
+ try {
193
+ instance =
194
+ options.instantiate !== undefined
195
+ ? await options.instantiate(module, imports)
196
+ : (await WebAssembly.instantiate(module, imports));
197
+ }
198
+ catch (error) {
199
+ fail("E_WASM_ABI_MISMATCH", `could not instantiate wasm module: ${String(error)}`, error);
200
+ }
201
+ }
202
+ let abiVersion;
203
+ try {
204
+ abiVersion = abi.version(instance);
205
+ }
206
+ catch (error) {
207
+ if (error instanceof HelperError && error.code === "E_WASM_ABI_MISMATCH")
208
+ throw error;
209
+ fail("E_WASM_ABI_MISMATCH", `adapter '${abi.name}' could not read the ABI version`, error);
210
+ }
211
+ if (expectedAbi !== undefined && String(abiVersion) !== String(expectedAbi)) {
212
+ fail("E_WASM_ABI_MISMATCH", `expected ABI ${String(expectedAbi)}, module reports ${String(abiVersion)}`);
213
+ }
214
+ const config = options.config ?? {};
215
+ let initCode;
216
+ try {
217
+ initCode = abi.init(instance, config);
218
+ }
219
+ catch (error) {
220
+ if (error instanceof HelperError && error.code === "E_WASM_MEMORY")
221
+ throw error;
222
+ fail("E_WASM_INIT_FAILED", `adapter '${abi.name}' init threw: ${String(error)}`, error);
223
+ }
224
+ if (initCode !== 0) {
225
+ fail("E_WASM_INIT_FAILED", `init returned ${initCode}`);
226
+ }
227
+ let closed = false;
228
+ const feed = (kind, data, id) => {
229
+ if (closed)
230
+ fail("E_WASM_CLOSED", "wasm core is closed");
231
+ if (typeof kind !== "string" || kind.length === 0) {
232
+ throw new TypeError("feed kind must be a non-empty string");
233
+ }
234
+ const feedback = { kind, data: data === undefined ? {} : data };
235
+ if (id !== undefined)
236
+ feedback.id = id;
237
+ return abi.feed(instance, feedback);
238
+ };
239
+ const drive = async () => {
240
+ if (closed)
241
+ fail("E_WASM_CLOSED", "wasm core is closed");
242
+ let processed = 0;
243
+ for (let step = 0; step < maxSteps; step += 1) {
244
+ const effects = abi.drain(instance);
245
+ if (!Array.isArray(effects)) {
246
+ fail("E_WASM_EFFECT_INVALID", `adapter '${abi.name}' drain did not return an array`);
247
+ }
248
+ if (effects.length === 0)
249
+ return processed;
250
+ for (const effect of effects) {
251
+ const normalized = validateEffects([effect])[0];
252
+ const result = await options.onEffect(normalized);
253
+ feed(normalized.kind, result === undefined ? {} : result, normalized.id);
254
+ processed += 1;
255
+ }
256
+ if (abi.until?.(instance) === false)
257
+ return processed;
258
+ }
259
+ fail("E_WASM_DRIVE_LIMIT", `drive exceeded ${maxSteps} steps`);
260
+ };
261
+ log("debug", `wasm: mounted '${abi.name}' ABI ${String(abiVersion)}`);
262
+ return {
263
+ abiVersion,
264
+ drive,
265
+ feed,
266
+ close() {
267
+ closed = true;
268
+ },
269
+ instance,
270
+ };
271
+ }
package/package.json CHANGED
@@ -1,6 +1,80 @@
1
1
  {
2
2
  "name": "@shing.wong/sure-wasm-helper",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Generic WASM reactor host, loopback UI/WebSocket host, WASI socket adapter, SEA packager, self-updater and cold-start bench",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "private": false,
8
+ "engines": {
9
+ "node": ">=22"
10
+ },
11
+ "files": [
12
+ "dist",
13
+ "bin"
14
+ ],
15
+ "exports": {
16
+ "./wasm-loader": {
17
+ "types": "./dist/wasm-loader.d.ts",
18
+ "import": "./dist/wasm-loader.js",
19
+ "default": "./dist/wasm-loader.js"
20
+ },
21
+ "./loopback-host": {
22
+ "types": "./dist/loopback-host.d.ts",
23
+ "import": "./dist/loopback-host.js",
24
+ "default": "./dist/loopback-host.js"
25
+ },
26
+ "./wasi-socket": {
27
+ "types": "./dist/wasi-socket.d.ts",
28
+ "import": "./dist/wasi-socket.js",
29
+ "default": "./dist/wasi-socket.js"
30
+ },
31
+ "./updater": {
32
+ "types": "./dist/updater.d.ts",
33
+ "import": "./dist/updater.js",
34
+ "default": "./dist/updater.js"
35
+ },
36
+ "./packager": {
37
+ "types": "./dist/packager.d.ts",
38
+ "import": "./dist/packager.js",
39
+ "default": "./dist/packager.js"
40
+ },
41
+ "./bench-cold": {
42
+ "types": "./dist/bench-cold.d.ts",
43
+ "import": "./dist/bench-cold.js",
44
+ "default": "./dist/bench-cold.js"
45
+ }
46
+ },
47
+ "bin": {
48
+ "sure-pack": "./bin/sure-pack.mjs"
49
+ },
50
+ "scripts": {
51
+ "prepare": "npm run build",
52
+ "build": "tsc -p tsconfig.json",
53
+ "pretest": "npm run build",
54
+ "test": "node --test test/*.test.mjs",
55
+ "verify:docs": "node scripts/verify-docs.mjs",
56
+ "verify": "npm run build && node --test test/*.test.mjs && npm run verify:docs",
57
+ "build:fixtures": "node scripts/build-synthetic-core.mjs",
58
+ "prepack": "npm run build",
59
+ "prepublishOnly": "npm run verify"
60
+ },
61
+ "dependencies": {
62
+ "ws": "^8.23.1"
63
+ },
64
+ "devDependencies": {
65
+ "@types/node": "^22.20.5",
66
+ "@types/ws": "^8.18.2",
67
+ "esbuild": "^0.28.2",
68
+ "postject": "^1.0.0-alpha.6",
69
+ "typescript": "5.9.3",
70
+ "wabt": "^1.0.39"
71
+ },
72
+ "repository": {
73
+ "type": "git",
74
+ "url": "git+https://github.com/ShingWong/sure-wasm-helper.git"
75
+ },
76
+ "bugs": {
77
+ "url": "https://github.com/ShingWong/sure-wasm-helper/issues"
78
+ },
79
+ "homepage": "https://github.com/ShingWong/sure-wasm-helper#readme"
80
+ }