@shing.wong/sure-wasm-helper 0.1.1 → 0.1.3

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 CHANGED
@@ -48,6 +48,15 @@ A domain that already exports its own ABI can pass a `CoreAbiAdapter`
48
48
  (`version`, `init`, `drain`, `feed`, optional `until`) instead of renaming its
49
49
  exports; the handle still exposes the raw `instance`. See `docs/abi.md`.
50
50
 
51
+ Host writes use a reusable scratch region at the end of linear memory, so a
52
+ long-lived `feed()` loop does not grow memory once per call. A module that
53
+ grows or allocates its own heap should export
54
+ `sure_alloc(len: i32) -> i32`; the loader then writes only to that returned
55
+ pointer. Without it, a module that grows or allocates races the host for the
56
+ same bytes — exporting `sure_alloc` is the safe opt-in. Concurrent `drive()`
57
+ calls are serialized per handle (effects never run in parallel), and both
58
+ `drive()` and `feed()` after `close()` throw `E_WASM_CLOSED`.
59
+
51
60
  ## Loopback host
52
61
 
53
62
  ```ts
@@ -68,6 +77,10 @@ const host = await createLoopbackHost({
68
77
  onWsMessage: ({ data, isBinary, send }) => {
69
78
  send(isBinary ? data : { echo: data });
70
79
  },
80
+ // Fires once per socket, including after terminate(); async errors are logged.
81
+ onWsClose: ({ context, code, reason }) => {
82
+ console.log("socket closed", code, reason, context);
83
+ },
71
84
  });
72
85
 
73
86
  console.log(host.uiUrl, host.relayUrl);
@@ -78,6 +91,50 @@ The UI server sends `cross-origin-opener-policy: same-origin` and
78
91
  `cross-origin-embedder-policy: require-corp`, which is what cross-origin
79
92
  isolated browser features (OPFS sync handles, `SharedArrayBuffer`) require.
80
93
 
94
+ By default the WebSocket relay lives on a second loopback port and `relayUrl`
95
+ points at it. Pass `relayPort: false` for single-port mode: no second server is
96
+ created, upgrades are handled on the UI port, `host.relayPort` equals
97
+ `host.uiPort`, and `host.relayUrl` is `ws://<host>:<uiPort>/`. A plain HTTP GET
98
+ on that port still serves the UI (with COOP/COEP) rather than a 426 response.
99
+ `onWsClose` is called exactly once per accepted socket with
100
+ `{ context, req, code, reason }`; `reason` is UTF-8 decoded and empty when the
101
+ client sends none, and callback errors are logged without crashing the server.
102
+
103
+ ## WASI sockets
104
+
105
+ ```ts
106
+ import { createWasiSocketPort } from "@shing.wong/sure-wasm-helper/wasi-socket";
107
+
108
+ const port = createWasiSocketPort({
109
+ componentPath: "socket.component.wasm",
110
+ runtime: "wasmtime",
111
+ });
112
+
113
+ const result = await port.connect({
114
+ address: "127.0.0.1:25",
115
+ message: "EHLO example",
116
+ timeoutMs: 30_000,
117
+ maxBytes: 1024 * 1024,
118
+ });
119
+
120
+ const handle = await port.listen({
121
+ address: "127.0.0.1:0",
122
+ onLine: (line) => console.log(line),
123
+ onError: (error) => console.error(error.code, error.message),
124
+ });
125
+ handle.close(); // SIGTERM
126
+ ```
127
+
128
+ `WasiConnectOptions.maxBytes` (default 1 MiB) bounds the combined stdout and
129
+ stderr that `connect()` collects; a chunk that would exceed it kills the child
130
+ and rejects with `E_WASI_SOCKET_OVERFLOW`. `WasiListenOptions.onError` receives
131
+ async child errors as `E_WASI_SOCKET_FAILED`; the adapter always attaches an
132
+ `error` listener, so omitting the callback cannot crash the process.
133
+ `WasiSocketPortOptions.resolveImpl` overrides runtime discovery, primarily for
134
+ tests: combine `runtime: "no-such-runtime"` with
135
+ `resolveImpl: async () => "/mock/wasmtime"` and an injected `spawnImpl` to run
136
+ without wasmtime on the host.
137
+
81
138
  ## Packaging
82
139
 
83
140
  ```bash
@@ -90,12 +147,23 @@ npx sure-pack \
90
147
  --no-args-args "serve --ui --ui-dir {uiDir}"
91
148
  ```
92
149
 
93
- The produced binary is a Node SEA image. On first run it extracts `ui/*` and
94
- `core/core.wasm` to a content-addressed cache (`~/.cache/<app>/ui-<hash>`,
95
- `%LOCALAPPDATA%` on Windows, `XDG_CACHE_HOME` respected) and exposes
96
- `SURE_APP_UI_DIR`, `SURE_APP_CORE_WASM` and `SURE_APP_BUILD` to the entry. The
97
- names are configurable (`--env-ui`, `--env-core`, `--env-build`,
98
- `--env-launch`); the launch-args variable defaults to `SURE_APP_LAUNCH_ARGS`.
150
+ `--core` is optional. A package without a core embeds no `core/core.wasm`,
151
+ excludes it from the asset stamp, does not extract it, and does not set the core
152
+ environment variable. `--external <module>` (repeatable) passes a module to
153
+ esbuild as external, so it stays a runtime `require()` instead of being
154
+ inlined; the JSON config accepts an `external` array.
155
+
156
+ The produced binary is a Node SEA image. On first run it extracts `ui/*` (and
157
+ `core/core.wasm` when present) to a content-addressed cache
158
+ (`~/.cache/<app>/ui-<hash>`, `%LOCALAPPDATA%` on Windows, `XDG_CACHE_HOME`
159
+ respected) and exposes `SURE_APP_UI_DIR`, `SURE_APP_CORE_WASM` (only with a
160
+ core) and `SURE_APP_BUILD` to the entry. Extraction writes a
161
+ `<uiDir>.tmp-<pid>` directory and renames it into place only when complete, so
162
+ concurrent starts and interrupted runs never leave a partial live cache; a
163
+ stray partial `ui-*` directory is replaced, while a complete cache is reused
164
+ untouched. The env names are configurable (`--env-ui`, `--env-core`,
165
+ `--env-build`, `--env-launch`); the launch-args variable defaults to
166
+ `SURE_APP_LAUNCH_ARGS`.
99
167
 
100
168
  ## Self-update
101
169
 
@@ -117,6 +185,16 @@ if (update.updateAvailable) await updater.download();
117
185
  checkout. The swap is performed by the downloaded binary running
118
186
  `apply-update <pid> <target> --relaunch ...`; see `docs/design.md` (ADR-004).
119
187
 
188
+ Downloads stream to `<file>.part`, are hashed and counted while writing, and
189
+ are renamed into place only after SHA-256 and the manifest's optional `size`
190
+ match. A bad hash, wrong size or network error removes `.part` and leaves no
191
+ partial executable. `manifestUrl` and every `asset.url` must be `https:`;
192
+ plain `http:` is accepted only for loopback hosts (`127.0.0.1`, `localhost`,
193
+ `[::1]`, `::1`) and any other insecure URL fails with
194
+ `E_UPDATE_INSECURE_URL` before a fetch. If the helper and target live on
195
+ different filesystems (`EXDEV`), the swap falls back to copy + chmod + remove
196
+ of the source, then the same `.old` rollback sequence.
197
+
120
198
  ## Development
121
199
 
122
200
  ```bash
@@ -11,7 +11,12 @@ export interface LoopbackHostOptions {
11
11
  /** Bind address. Defaults to loopback; overriding it exposes the host. */
12
12
  host?: string;
13
13
  port?: number;
14
- relayPort?: number;
14
+ /**
15
+ * Relay port. Pass `false` for single-port mode: no second server is
16
+ * started, WebSocket upgrades are handled on the UI server, and the handle
17
+ * reports `relayPort === uiPort` plus `relayUrl = ws://<host>:<uiPort>/`.
18
+ */
19
+ relayPort?: number | false;
15
20
  noOpen?: boolean;
16
21
  /** Return true when the request is fully handled. */
17
22
  onHttp?: (req: IncomingMessage, res: ServerResponse) => boolean | void | Promise<boolean | void>;
@@ -24,6 +29,12 @@ export interface LoopbackHostOptions {
24
29
  reason?: string;
25
30
  } | boolean | void | Promise<unknown>;
26
31
  onWsMessage?: (info: WsMessageInfo) => void | Promise<void>;
32
+ /**
33
+ * Called once when an accepted WebSocket closes, including after
34
+ * `terminate()`. `reason` is decoded UTF-8 (empty when absent). Errors are
35
+ * logged and never crash the server.
36
+ */
37
+ onWsClose?: (info: WsCloseInfo) => void | Promise<void>;
27
38
  maxFrameBytes?: number;
28
39
  openBrowser?: boolean;
29
40
  log?: (message: string) => void;
@@ -38,13 +49,29 @@ export interface WsMessageInfo {
38
49
  /** Buffer/Uint8Array/ArrayBuffer -> binary frame; string -> text; else JSON. */
39
50
  send: (payload: unknown) => void;
40
51
  }
52
+ export interface WsCloseInfo {
53
+ /** Whatever onWsUpgrade returned in `{ context }`. */
54
+ context: unknown;
55
+ req: IncomingMessage;
56
+ code: number;
57
+ /** Close reason decoded as UTF-8; empty when the client sent none. */
58
+ reason: string;
59
+ }
41
60
  export interface LoopbackHostHandle {
42
61
  uiPort: number;
62
+ /** Relay port; equal to `uiPort` in single-port (`relayPort: false`) mode. */
43
63
  relayPort: number;
44
64
  uiUrl: string;
65
+ /** Relay WebSocket URL; on the UI port in single-port mode. */
45
66
  relayUrl: string;
46
67
  close(): Promise<void>;
47
68
  }
69
+ /**
70
+ * True when `file` is `root` itself or lives below it on the given separator.
71
+ * `separator` defaults to the platform separator; pass `"/"` or `"\\"`
72
+ * explicitly when checking paths that came from another platform.
73
+ */
74
+ export declare function isPathWithin(root: string, file: string, separator?: string): boolean;
48
75
  /**
49
76
  * Start the UI and relay servers. Resolves only after both are listening.
50
77
  *
@@ -5,7 +5,7 @@
5
5
  import { spawn } from "node:child_process";
6
6
  import { createServer } from "node:http";
7
7
  import { readFile, stat } from "node:fs/promises";
8
- import { extname, join, posix, resolve } from "node:path";
8
+ import { extname, join, posix, resolve, sep } from "node:path";
9
9
  import { WebSocket, WebSocketServer } from "ws";
10
10
  const DEFAULT_MAX_FRAME_BYTES = 1024 * 1024;
11
11
  /** Slack above maxFrameBytes so an oversized frame reaches our handler first. */
@@ -25,6 +25,14 @@ const MEDIA_TYPES = {
25
25
  function isRecord(value) {
26
26
  return typeof value === "object" && value !== null && !Array.isArray(value);
27
27
  }
28
+ /**
29
+ * True when `file` is `root` itself or lives below it on the given separator.
30
+ * `separator` defaults to the platform separator; pass `"/"` or `"\\"`
31
+ * explicitly when checking paths that came from another platform.
32
+ */
33
+ export function isPathWithin(root, file, separator = sep) {
34
+ return file === root || file.startsWith(`${root}${separator}`);
35
+ }
28
36
  function listen(server, port, host) {
29
37
  return new Promise((resolvePort, reject) => {
30
38
  const onError = (error) => reject(error);
@@ -100,7 +108,6 @@ export async function createLoopbackHost(options) {
100
108
  const host = options.host ?? "127.0.0.1";
101
109
  const uiDir = resolve(options.uiDir);
102
110
  const requestedUiPort = options.port ?? options.defaultUiPort ?? 8788;
103
- const requestedRelayPort = options.relayPort ?? options.defaultRelayPort ?? 8787;
104
111
  const maxFrameBytes = options.maxFrameBytes ?? DEFAULT_MAX_FRAME_BYTES;
105
112
  const log = options.log ?? ((message) => console.warn(message));
106
113
  let uiDirOk = true;
@@ -156,7 +163,7 @@ export async function createLoopbackHost(options) {
156
163
  const normalized = posix.normalize(pathname);
157
164
  const relative = normalized === "/" ? "index.html" : normalized.replace(/^\/+/, "");
158
165
  const file = resolve(join(uiDir, relative));
159
- if (file !== uiDir && !file.startsWith(`${uiDir}/`)) {
166
+ if (!isPathWithin(uiDir, file)) {
160
167
  res.writeHead(400, { "content-type": "text/plain; charset=utf-8" });
161
168
  res.end("bad path");
162
169
  return;
@@ -192,31 +199,43 @@ export async function createLoopbackHost(options) {
192
199
  });
193
200
  const uiPort = await listen(uiServer, requestedUiPort, host);
194
201
  const uiUrl = `http://${host}:${uiPort}/`;
195
- const relayServer = createServer((_req, res) => {
196
- const body = JSON.stringify({
197
- error: "upgrade required",
198
- message: `${options.appName}: this port speaks WebSocket only. Open the UI at ${uiUrl}`,
199
- uiUrl,
200
- });
201
- res.writeHead(426, {
202
- "content-type": "application/json; charset=utf-8",
203
- "cache-control": "no-store",
204
- connection: "close",
205
- });
206
- res.end(body);
207
- });
202
+ const wss = new WebSocketServer({ noServer: true, maxPayload: maxFrameBytes + FRAME_SLACK_BYTES });
203
+ const contexts = new WeakMap();
204
+ let relayServer = null;
208
205
  let relayPort;
209
- try {
210
- relayPort = await listen(relayServer, requestedRelayPort, host);
206
+ let relayUrl;
207
+ if (options.relayPort === false) {
208
+ // Single-port mode: WebSocket upgrades share the UI origin. There is no
209
+ // second server and therefore no relay-only 426 response.
210
+ relayPort = uiPort;
211
+ relayUrl = `ws://${host}:${uiPort}/`;
211
212
  }
212
- catch (error) {
213
- await closeServer(uiServer);
214
- throw error;
213
+ else {
214
+ const requestedRelayPort = options.relayPort ?? options.defaultRelayPort ?? 8787;
215
+ relayServer = createServer((_req, res) => {
216
+ const body = JSON.stringify({
217
+ error: "upgrade required",
218
+ message: `${options.appName}: this port speaks WebSocket only. Open the UI at ${uiUrl}`,
219
+ uiUrl,
220
+ });
221
+ res.writeHead(426, {
222
+ "content-type": "application/json; charset=utf-8",
223
+ "cache-control": "no-store",
224
+ connection: "close",
225
+ });
226
+ res.end(body);
227
+ });
228
+ try {
229
+ relayPort = await listen(relayServer, requestedRelayPort, host);
230
+ }
231
+ catch (error) {
232
+ await closeServer(uiServer);
233
+ throw error;
234
+ }
235
+ relayUrl = `ws://${host}:${relayPort}/`;
215
236
  }
216
- const relayUrl = `ws://${host}:${relayPort}/`;
217
- const wss = new WebSocketServer({ noServer: true, maxPayload: maxFrameBytes + FRAME_SLACK_BYTES });
218
- const contexts = new WeakMap();
219
- relayServer.on("upgrade", (req, socket, head) => {
237
+ const upgradeServer = relayServer ?? uiServer;
238
+ upgradeServer.on("upgrade", (req, socket, head) => {
220
239
  void (async () => {
221
240
  let decision;
222
241
  try {
@@ -242,6 +261,27 @@ export async function createLoopbackHost(options) {
242
261
  });
243
262
  wss.on("connection", (ws, req) => {
244
263
  const context = contexts.get(ws);
264
+ let closeNotified = false;
265
+ ws.on("close", (code, reason) => {
266
+ // `terminate()` also emits `close`; guard so cleanup runs exactly once.
267
+ if (closeNotified)
268
+ return;
269
+ closeNotified = true;
270
+ const info = {
271
+ context,
272
+ req,
273
+ code,
274
+ reason: reason && reason.length > 0 ? reason.toString("utf8") : "",
275
+ };
276
+ try {
277
+ void Promise.resolve(options.onWsClose?.(info)).catch((error) => {
278
+ log(`${options.appName}: onWsClose failed: ${String(error)}`);
279
+ });
280
+ }
281
+ catch (error) {
282
+ log(`${options.appName}: onWsClose failed: ${String(error)}`);
283
+ }
284
+ });
245
285
  ws.on("message", (raw, isBinary) => {
246
286
  const bytes = frameBytes(raw);
247
287
  if (bytes > maxFrameBytes) {
@@ -316,5 +356,5 @@ export function resolveUiFile(uiDir, pathname) {
316
356
  const base = resolve(uiDir);
317
357
  const relative = normalized === "/" ? "index.html" : normalized.replace(/^\/+/, "");
318
358
  const file = resolve(join(base, relative));
319
- return file === base || file.startsWith(`${base}/`) ? file : null;
359
+ return isPathWithin(base, file) ? file : null;
320
360
  }
@@ -9,14 +9,16 @@ export interface PackageOptions {
9
9
  entry: string;
10
10
  /** UI directory served at runtime. Must contain index.html. */
11
11
  uiDir: string;
12
- /** WASM core embedded as `core/core.wasm`. */
13
- core: string;
12
+ /** Optional WASM core embedded as `core/core.wasm`. */
13
+ core?: string;
14
14
  /** Output executable path. */
15
15
  out: string;
16
16
  /** Extra embedded assets, `name=path` or objects. */
17
17
  assets?: PackageAsset[] | Record<string, string>;
18
18
  /** Arguments used when the binary starts with no CLI arguments. */
19
19
  noArgsArgs?: string | string[];
20
+ /** Modules esbuild must leave as runtime `require()` calls. */
21
+ external?: string[];
20
22
  envCore?: string;
21
23
  envBuild?: string;
22
24
  envUi?: string;
@@ -28,11 +30,12 @@ export interface PackagePlan {
28
30
  app: string;
29
31
  entry: string;
30
32
  uiDir: string;
31
- core: string;
33
+ core: string | null;
32
34
  out: string;
33
35
  uiFiles: string[];
34
36
  extraAssets: PackageAsset[];
35
37
  assetNames: string[];
38
+ external: string[];
36
39
  envCore: string;
37
40
  envBuild: string;
38
41
  envUi: string;
@@ -61,6 +64,6 @@ export declare function parsePackageCli(argv: string[]): PackageOptions;
61
64
  /** CLI entry point. Returns an exit code; never calls process.exit. */
62
65
  export declare function runSurePackCli(argv?: string[]): Promise<number>;
63
66
  /** Exported for the packaged binary's own `--version` diagnostics. */
64
- export declare const packagerVersion = "0.1.0";
67
+ export declare const packagerVersion = "0.1.3";
65
68
  /** Exported for callers that need the default executable suffix. */
66
69
  export declare function defaultExecutableName(app: string, platform?: NodeJS.Platform): string;
package/dist/packager.js CHANGED
@@ -67,7 +67,7 @@ export function resolvePackagePlan(options) {
67
67
  fail(`ui directory not found: ${uiDir}`);
68
68
  if (!existsSync(join(uiDir, "index.html")))
69
69
  fail(`ui directory has no index.html: ${uiDir}`);
70
- const core = requireFile("core", options.core);
70
+ const core = options.core === undefined ? null : requireFile("core", options.core);
71
71
  const out = resolve(options.out);
72
72
  const uiFiles = walkUi(uiDir);
73
73
  if (uiFiles.length === 0)
@@ -82,7 +82,7 @@ export function resolvePackagePlan(options) {
82
82
  }
83
83
  const assetNames = [
84
84
  ...uiFiles.map((file) => `ui/${file}`),
85
- "core/core.wasm",
85
+ ...(core === null ? [] : ["core/core.wasm"]),
86
86
  ...extraAssets.map((a) => a.name),
87
87
  ].sort();
88
88
  const noArgsArgs = options.noArgsArgs === undefined
@@ -99,6 +99,7 @@ export function resolvePackagePlan(options) {
99
99
  uiFiles,
100
100
  extraAssets,
101
101
  assetNames,
102
+ external: options.external ? [...options.external] : [],
102
103
  envCore: options.envCore ?? "SURE_APP_CORE_WASM",
103
104
  envBuild: options.envBuild ?? "SURE_APP_BUILD",
104
105
  envUi: options.envUi ?? "SURE_APP_UI_DIR",
@@ -143,7 +144,8 @@ function assetContents(plan) {
143
144
  for (const file of plan.uiFiles) {
144
145
  contents.set(`ui/${file}`, readFileSync(join(plan.uiDir, file)));
145
146
  }
146
- contents.set("core/core.wasm", readFileSync(plan.core));
147
+ if (plan.core !== null)
148
+ contents.set("core/core.wasm", readFileSync(plan.core));
147
149
  for (const asset of plan.extraAssets) {
148
150
  contents.set(asset.name, readFileSync(asset.path));
149
151
  }
@@ -172,6 +174,7 @@ function prelude(plan, entryHash) {
172
174
  envBuild: plan.envBuild,
173
175
  envUi: plan.envUi,
174
176
  envLaunch: plan.envLaunch,
177
+ hasCore: plan.core !== null,
175
178
  assetNames: plan.assetNames,
176
179
  entryHash,
177
180
  noArgsArgs: plan.noArgsArgs,
@@ -200,25 +203,50 @@ if (require("node:sea").isSea()) {
200
203
  : (process.env.XDG_CACHE_HOME || path.join(os.homedir(), ".cache"));
201
204
  const uiDir = path.join(base, CONFIG.app, "ui-" + stamp);
202
205
  const corePath = path.join(uiDir, "core.wasm");
206
+ const required = CONFIG.hasCore ? ["index.html", "core.wasm"] : ["index.html"];
207
+ const complete = (dir) => required.every((name) => fs.existsSync(path.join(dir, name)));
203
208
  const relativeOf = (name) =>
204
209
  name === "core/core.wasm" ? "core.wasm" : name.startsWith("ui/") ? name.slice(3) : name;
205
210
 
206
- if (!fs.existsSync(path.join(uiDir, "index.html")) || !fs.existsSync(corePath)) {
211
+ if (!complete(uiDir)) {
207
212
  const tmp = uiDir + ".tmp-" + process.pid;
208
213
  fs.rmSync(tmp, { recursive: true, force: true });
209
- fs.mkdirSync(tmp, { recursive: true });
210
- for (const name of CONFIG.assetNames) {
211
- const target = path.join(tmp, relativeOf(name));
212
- fs.mkdirSync(path.dirname(target), { recursive: true });
213
- fs.writeFileSync(target, Buffer.from(sea.getAsset(name)));
214
+ try {
215
+ fs.mkdirSync(tmp, { recursive: true });
216
+ for (const name of CONFIG.assetNames) {
217
+ const target = path.join(tmp, relativeOf(name));
218
+ fs.mkdirSync(path.dirname(target), { recursive: true });
219
+ fs.writeFileSync(target, Buffer.from(sea.getAsset(name)));
220
+ }
221
+ fs.mkdirSync(path.dirname(uiDir), { recursive: true });
222
+ try {
223
+ fs.renameSync(tmp, uiDir);
224
+ } catch (error) {
225
+ // Another process may have completed the same content-addressed cache
226
+ // first. Accept it only when it is complete; never leave the temp dir.
227
+ if (complete(uiDir)) {
228
+ fs.rmSync(tmp, { recursive: true, force: true });
229
+ } else {
230
+ // A stale partial cache from an interrupted older run: remove it and
231
+ // retry the swap. The new directory is already fully written.
232
+ fs.rmSync(uiDir, { recursive: true, force: true });
233
+ try {
234
+ fs.renameSync(tmp, uiDir);
235
+ } catch (second) {
236
+ fs.rmSync(tmp, { recursive: true, force: true });
237
+ if (!complete(uiDir)) throw second;
238
+ }
239
+ }
240
+ }
241
+ } catch (error) {
242
+ fs.rmSync(tmp, { recursive: true, force: true });
243
+ if (!complete(uiDir)) fs.rmSync(uiDir, { recursive: true, force: true });
244
+ throw error;
214
245
  }
215
- fs.rmSync(uiDir, { recursive: true, force: true });
216
- fs.mkdirSync(path.dirname(uiDir), { recursive: true });
217
- fs.renameSync(tmp, uiDir);
218
246
  }
219
247
 
220
248
  process.env[CONFIG.envUi] = uiDir;
221
- process.env[CONFIG.envCore] = corePath;
249
+ if (CONFIG.hasCore) process.env[CONFIG.envCore] = corePath;
222
250
 
223
251
  const args = process.argv.slice(2);
224
252
  process.env[CONFIG.envLaunch] = JSON.stringify(args);
@@ -262,6 +290,7 @@ export async function packageApp(options) {
262
290
  format: "cjs",
263
291
  target: "node22",
264
292
  logLevel: "warning",
293
+ external: plan.external,
265
294
  define: { "import.meta.url": "__seaImportMetaUrl" },
266
295
  banner: {
267
296
  js: `const __seaImportMetaUrl = require("node:url").pathToFileURL(process.execPath).href;`,
@@ -278,7 +307,8 @@ export async function packageApp(options) {
278
307
  const assets = {};
279
308
  for (const file of plan.uiFiles)
280
309
  assets[`ui/${file}`] = join(plan.uiDir, file);
281
- assets["core/core.wasm"] = plan.core;
310
+ if (plan.core !== null)
311
+ assets["core/core.wasm"] = plan.core;
282
312
  for (const asset of plan.extraAssets)
283
313
  assets[asset.name] = asset.path;
284
314
  const config = seaConfigPath(work);
@@ -352,6 +382,7 @@ export function parsePackageCli(argv) {
352
382
  for (const [name, path] of Object.entries(options.assets))
353
383
  assets.push({ name, path });
354
384
  }
385
+ const external = Array.isArray(options.external) ? [...options.external] : [];
355
386
  for (let index = 0; index < argv.length; index += 1) {
356
387
  const flag = argv[index];
357
388
  switch (flag) {
@@ -407,23 +438,29 @@ export function parsePackageCli(argv) {
407
438
  index += 1;
408
439
  break;
409
440
  }
441
+ case "--external":
442
+ external.push(takeValue(argv, index, flag));
443
+ index += 1;
444
+ break;
410
445
  default:
411
446
  fail(`unknown argument '${flag}'`);
412
447
  }
413
448
  }
414
449
  if (assets.length > 0)
415
450
  options.assets = assets;
451
+ if (external.length > 0)
452
+ options.external = external;
416
453
  if (typeof options.app !== "string" ||
417
454
  typeof options.entry !== "string" ||
418
455
  typeof options.uiDir !== "string" ||
419
- typeof options.core !== "string" ||
420
456
  typeof options.out !== "string") {
421
- fail("need --app, --entry, --ui-dir, --core and --out (or --config)");
457
+ fail("need --app, --entry, --ui-dir and --out (or --config)");
422
458
  }
423
459
  return options;
424
460
  }
425
- const USAGE = `usage: sure-pack --app <name> --entry <file> --ui-dir <dir> --core <wasm> --out <file>
426
- [--asset name=path]... [--no-args-args "serve --ui"]
461
+ const USAGE = `usage: sure-pack --app <name> --entry <file> --ui-dir <dir> --out <file>
462
+ [--core <wasm>] [--asset name=path]... [--external <module>]...
463
+ [--no-args-args "serve --ui"]
427
464
  [--env-core NAME] [--env-build NAME] [--env-ui NAME] [--env-launch NAME]
428
465
  [--config sure-pack.json]`;
429
466
  /** CLI entry point. Returns an exit code; never calls process.exit. */
@@ -446,7 +483,7 @@ export async function runSurePackCli(argv = process.argv.slice(2)) {
446
483
  }
447
484
  }
448
485
  /** Exported for the packaged binary's own `--version` diagnostics. */
449
- export const packagerVersion = "0.1.0";
486
+ export const packagerVersion = "0.1.3";
450
487
  /** Exported for callers that need the default executable suffix. */
451
488
  export function defaultExecutableName(app, platform = process.platform) {
452
489
  return `${basename(app)}${platform === "win32" ? ".exe" : ""}`;
package/dist/updater.d.ts CHANGED
@@ -70,6 +70,12 @@ export interface ApplyUpdateSwapOptions {
70
70
  /** The verified helper binary to copy into place. */
71
71
  execPath?: string;
72
72
  platform?: string;
73
+ /**
74
+ * Override the rename used to move the verified helper to `<target>.new`.
75
+ * Defaults to `fs/promises.rename`; an `EXDEV` result falls back to
76
+ * copy + chmod + remove.
77
+ */
78
+ renameImpl?: (from: string, to: string) => Promise<void>;
73
79
  }
74
80
  export interface ApplyUpdateSwapResult {
75
81
  ok: true;
@@ -98,8 +104,9 @@ export declare function createSelfUpdater(options: SelfUpdaterOptions): SelfUpda
98
104
  /**
99
105
  * Wait for `pid`, then replace `target` with the running helper binary.
100
106
  *
101
- * Sequence: copy helper -> `.new`, rename target -> `.old`, rename `.new` ->
102
- * target, chmod. Any failure after the target moves restores `.old`.
107
+ * Sequence: move the verified helper to `.new` (rename, or copy + chmod + rm on
108
+ * `EXDEV`), rename target -> `.old`, rename `.new` -> target, chmod. Any failure
109
+ * after the target moves restores `.old`.
103
110
  */
104
111
  export declare function applyUpdateSwap(options: ApplyUpdateSwapOptions): Promise<ApplyUpdateSwapResult>;
105
112
  /**
package/dist/updater.js CHANGED
@@ -19,6 +19,30 @@ function isNodeExecutable(execPath) {
19
19
  function messageOf(error) {
20
20
  return error instanceof Error ? error.message : String(error);
21
21
  }
22
+ /** Loopback hosts for which plain HTTP is accepted (tests and local releases). */
23
+ const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "[::1]", "::1"]);
24
+ /**
25
+ * Refuse anything that is not HTTPS, except explicit loopback HTTP.
26
+ *
27
+ * Update payloads are executable, so a plain-HTTP URL anywhere other than the
28
+ * local machine is a remote-code-execution path; reject before fetching.
29
+ */
30
+ function assertSecureUrl(raw) {
31
+ let url;
32
+ try {
33
+ url = new URL(raw);
34
+ }
35
+ catch (error) {
36
+ throw new HelperError("E_UPDATE_INSECURE_URL", `invalid update URL '${String(raw)}'`, {
37
+ cause: error,
38
+ });
39
+ }
40
+ if (url.protocol === "https:")
41
+ return;
42
+ if (url.protocol === "http:" && LOOPBACK_HOSTS.has(url.hostname.toLowerCase()))
43
+ return;
44
+ throw new HelperError("E_UPDATE_INSECURE_URL", `refusing insecure update URL '${String(raw)}' (https required; http is loopback-only)`);
45
+ }
22
46
  function storedRelaunchArgs(env, fallback, launchEnv) {
23
47
  const candidates = [
24
48
  ...(launchEnv ? [launchEnv] : []),
@@ -71,6 +95,7 @@ export class SelfUpdater {
71
95
  async check() {
72
96
  const current = this.options.currentBuild || this.options.currentVersion;
73
97
  try {
98
+ assertSecureUrl(this.options.manifestUrl);
74
99
  const response = await this.fetchImpl(this.options.manifestUrl, {
75
100
  signal: AbortSignal.timeout(8000),
76
101
  headers: { "cache-control": "no-cache" },
@@ -131,7 +156,7 @@ export class SelfUpdater {
131
156
  latest: "",
132
157
  updateAvailable: false,
133
158
  asset: null,
134
- code: "E_UPDATE_MANIFEST",
159
+ code: error instanceof HelperError ? error.code : "E_UPDATE_MANIFEST",
135
160
  error: messageOf(error),
136
161
  };
137
162
  }
@@ -147,9 +172,16 @@ export class SelfUpdater {
147
172
  };
148
173
  }
149
174
  const asset = info.asset;
175
+ try {
176
+ assertSecureUrl(asset.url);
177
+ }
178
+ catch (error) {
179
+ return { ok: false, code: "E_UPDATE_INSECURE_URL", error: messageOf(error) };
180
+ }
150
181
  const dir = this.options.downloadsDir ?? join(homedir(), "Downloads");
151
182
  const name = looseFilename(asset.url, this.options.appName, info.latest, this.platform);
152
183
  const path = join(dir, name);
184
+ const part = `${path}.part`;
153
185
  try {
154
186
  await mkdir(dir, { recursive: true });
155
187
  }
@@ -176,30 +208,51 @@ export class SelfUpdater {
176
208
  },
177
209
  });
178
210
  try {
179
- await pipeline(Readable.fromWeb(response.body), hasher, createWriteStream(path));
211
+ await pipeline(Readable.fromWeb(response.body), hasher, createWriteStream(part));
180
212
  }
181
213
  catch (error) {
182
- await rm(path, { force: true });
214
+ await rm(part, { force: true });
183
215
  return { ok: false, code: "E_UPDATE_DOWNLOAD", error: messageOf(error) };
184
216
  }
217
+ // Verify before the bytes are visible under the final name. A failed
218
+ // download must leave neither `.part` nor a partial executable in place.
185
219
  const digest = hash.digest("hex");
186
220
  if (digest !== asset.sha256) {
187
- await rm(path, { force: true });
221
+ await rm(part, { force: true });
188
222
  return {
189
223
  ok: false,
190
224
  code: "E_UPDATE_CHECKSUM",
191
225
  error: `checksum mismatch (got ${digest.slice(0, 12)}…, expected ${asset.sha256.slice(0, 12)}…)`,
192
226
  };
193
227
  }
228
+ if (typeof asset.size === "number" && bytes !== asset.size) {
229
+ await rm(part, { force: true });
230
+ return {
231
+ ok: false,
232
+ code: "E_UPDATE_CHECKSUM",
233
+ error: `size mismatch (got ${bytes} bytes, expected ${asset.size})`,
234
+ };
235
+ }
194
236
  if (bytes === 0) {
195
- await rm(path, { force: true });
237
+ await rm(part, { force: true });
196
238
  return { ok: false, code: "E_UPDATE_DOWNLOAD", error: "download was empty" };
197
239
  }
240
+ try {
241
+ // Windows rename does not replace an existing file atomically.
242
+ if (this.platform === "win32")
243
+ await rm(path, { force: true });
244
+ await rename(part, path);
245
+ }
246
+ catch (error) {
247
+ await rm(part, { force: true });
248
+ return { ok: false, code: "E_UPDATE_DOWNLOAD", error: messageOf(error) };
249
+ }
198
250
  if (this.platform !== "win32") {
199
251
  try {
200
252
  await chmod(path, 0o755);
201
253
  }
202
254
  catch (error) {
255
+ await rm(path, { force: true });
203
256
  return { ok: false, code: "E_UPDATE_DOWNLOAD", error: `chmod failed: ${messageOf(error)}` };
204
257
  }
205
258
  }
@@ -308,14 +361,16 @@ function pidAlive(pid) {
308
361
  /**
309
362
  * Wait for `pid`, then replace `target` with the running helper binary.
310
363
  *
311
- * Sequence: copy helper -> `.new`, rename target -> `.old`, rename `.new` ->
312
- * target, chmod. Any failure after the target moves restores `.old`.
364
+ * Sequence: move the verified helper to `.new` (rename, or copy + chmod + rm on
365
+ * `EXDEV`), rename target -> `.old`, rename `.new` -> target, chmod. Any failure
366
+ * after the target moves restores `.old`.
313
367
  */
314
368
  export async function applyUpdateSwap(options) {
315
369
  const platform = options.platform ?? process.platform;
316
370
  const execPath = options.execPath ?? process.execPath;
317
371
  const waitMs = options.waitMs ?? 60000;
318
372
  const pollMs = options.pollMs ?? 200;
373
+ const renameImpl = options.renameImpl ?? rename;
319
374
  const target = options.target;
320
375
  const backup = `${target}.old`;
321
376
  const next = `${target}.new`;
@@ -331,9 +386,18 @@ export async function applyUpdateSwap(options) {
331
386
  }
332
387
  let movedOld = false;
333
388
  try {
334
- await copyFile(execPath, next);
335
- if (platform !== "win32")
336
- await chmod(next, 0o755);
389
+ try {
390
+ await renameImpl(execPath, next);
391
+ }
392
+ catch (error) {
393
+ if (error?.code !== "EXDEV")
394
+ throw error;
395
+ // The downloaded helper and the target live on different filesystems.
396
+ await copyFile(execPath, next);
397
+ if (platform !== "win32")
398
+ await chmod(next, 0o755);
399
+ await rm(execPath, { force: true });
400
+ }
337
401
  await rm(backup, { force: true });
338
402
  await rename(target, backup);
339
403
  movedOld = true;
@@ -1,5 +1,6 @@
1
1
  import { type ChildProcess } from "node:child_process";
2
2
  import type { Readable } from "node:stream";
3
+ import { HelperError } from "./wasm-loader.js";
3
4
  export interface WasiSpawnedProcess {
4
5
  stdout: Readable | null;
5
6
  stderr: Readable | null;
@@ -22,12 +23,16 @@ export interface WasiSocketPortOptions {
22
23
  env?: NodeJS.ProcessEnv;
23
24
  /** Injectable spawn for tests. Defaults to node:child_process.spawn. */
24
25
  spawnImpl?: WasiSpawnImpl;
26
+ /** Injectable runtime resolver for tests. Defaults to `resolveRuntime`. */
27
+ resolveImpl?: (runtime: string) => Promise<string | null>;
25
28
  }
26
29
  export interface WasiConnectOptions {
27
30
  address: string;
28
31
  message?: string;
29
32
  tls?: boolean;
30
33
  timeoutMs?: number;
34
+ /** Cap on combined stdout+stderr bytes. Defaults to 1 MiB. */
35
+ maxBytes?: number;
31
36
  }
32
37
  export interface WasiConnectResult {
33
38
  connected: boolean;
@@ -37,6 +42,8 @@ export interface WasiConnectResult {
37
42
  export interface WasiListenOptions {
38
43
  address: string;
39
44
  onLine: (line: string) => void;
45
+ /** Receives async child errors instead of an unhandled EventEmitter error. */
46
+ onError?: (err: HelperError) => void;
40
47
  }
41
48
  export interface WasiListenHandle {
42
49
  close(): void;
@@ -58,10 +65,16 @@ export declare class WasiSocketPort {
58
65
  readonly runtime: string;
59
66
  private readonly env;
60
67
  private readonly spawnImpl;
68
+ private readonly resolveImpl;
61
69
  constructor(options: WasiSocketPortOptions);
70
+ /**
71
+ * Check the component once and resolve the runtime once. Both `available()`
72
+ * and the launch paths go through this, so a connect/listen never re-checks
73
+ * prerequisites independently.
74
+ */
75
+ private resolvePrerequisites;
62
76
  /** True when both the runtime and the component file are usable. */
63
77
  available(): Promise<boolean>;
64
- private runtimePath;
65
78
  /** Open a connection, optionally send one message, and collect the reply. */
66
79
  connect(options: WasiConnectOptions): Promise<WasiConnectResult>;
67
80
  /**
@@ -73,5 +86,8 @@ export declare class WasiSocketPort {
73
86
  listen(options: WasiListenOptions): Promise<WasiListenHandle>;
74
87
  }
75
88
  export declare function createWasiSocketPort(options: WasiSocketPortOptions): WasiSocketPort;
76
- /** Present so callers can test the child type without importing node types. */
89
+ /**
90
+ * Present so callers can test the child type without importing node types.
91
+ * The `spawn` import above stays live because `defaultSpawn` uses it.
92
+ */
77
93
  export type WasiChild = ChildProcess;
@@ -65,36 +65,50 @@ export class WasiSocketPort {
65
65
  runtime;
66
66
  env;
67
67
  spawnImpl;
68
+ resolveImpl;
68
69
  constructor(options) {
69
70
  this.componentPath = options.componentPath;
70
71
  this.runtime = options.runtime ?? "wasmtime";
71
72
  this.env = { ...process.env, ...(options.env ?? {}) };
72
73
  this.spawnImpl = options.spawnImpl ?? defaultSpawn;
74
+ this.resolveImpl = options.resolveImpl ?? resolveRuntime;
73
75
  }
74
- /** True when both the runtime and the component file are usable. */
75
- async available() {
76
+ /**
77
+ * Check the component once and resolve the runtime once. Both `available()`
78
+ * and the launch paths go through this, so a connect/listen never re-checks
79
+ * prerequisites independently.
80
+ */
81
+ async resolvePrerequisites() {
76
82
  try {
77
83
  await access(this.componentPath, constants.R_OK);
78
84
  }
79
85
  catch {
80
- return false;
86
+ return null;
81
87
  }
82
- return (await resolveRuntime(this.runtime)) !== null;
83
- }
84
- async runtimePath() {
85
- if (!(await this.available())) {
86
- throw new HelperError("E_WASI_SOCKET_UNAVAILABLE", `WASI socket prerequisites missing: runtime '${this.runtime}' or component '${this.componentPath}'`);
88
+ let runtimePath;
89
+ try {
90
+ runtimePath = await this.resolveImpl(this.runtime);
87
91
  }
88
- const resolved = await resolveRuntime(this.runtime);
89
- if (!resolved) {
90
- throw new HelperError("E_WASI_SOCKET_UNAVAILABLE", `runtime '${this.runtime}' not found on PATH`);
92
+ catch {
93
+ return null;
91
94
  }
92
- return resolved;
95
+ if (!runtimePath)
96
+ return null;
97
+ return { runtimePath, componentPath: this.componentPath };
98
+ }
99
+ /** True when both the runtime and the component file are usable. */
100
+ async available() {
101
+ return (await this.resolvePrerequisites()) !== null;
93
102
  }
94
103
  /** Open a connection, optionally send one message, and collect the reply. */
95
104
  async connect(options) {
96
- const runtimePath = await this.runtimePath();
105
+ const prerequisites = await this.resolvePrerequisites();
106
+ if (!prerequisites) {
107
+ throw new HelperError("E_WASI_SOCKET_UNAVAILABLE", `WASI socket prerequisites missing: runtime '${this.runtime}' or component '${this.componentPath}'`);
108
+ }
109
+ const runtimePath = prerequisites.runtimePath;
97
110
  const timeoutMs = options.timeoutMs ?? 30000;
111
+ const maxBytes = options.maxBytes ?? 1024 * 1024;
98
112
  const args = argsFor("connect", {
99
113
  componentPath: this.componentPath,
100
114
  address: options.address,
@@ -115,6 +129,7 @@ export class WasiSocketPort {
115
129
  return new Promise((resolve, reject) => {
116
130
  let stdout = "";
117
131
  let stderr = "";
132
+ let totalBytes = 0;
118
133
  let settled = false;
119
134
  const timer = setTimeout(() => {
120
135
  if (settled)
@@ -123,12 +138,35 @@ export class WasiSocketPort {
123
138
  child.kill("SIGKILL");
124
139
  reject(new HelperError("E_WASI_SOCKET_TIMEOUT", `connect timed out after ${timeoutMs}ms`));
125
140
  }, timeoutMs);
141
+ /**
142
+ * Account for one chunk before it is appended. A chunk that would push
143
+ * the combined output past `maxBytes` kills the child and settles once;
144
+ * later data/close/error events are ignored.
145
+ */
146
+ const account = (chunk, stream) => {
147
+ if (settled)
148
+ return false;
149
+ const size = typeof chunk === "string" ? Buffer.byteLength(chunk, "utf8") : chunk.byteLength;
150
+ if (totalBytes + size > maxBytes) {
151
+ settled = true;
152
+ clearTimeout(timer);
153
+ child.kill("SIGKILL");
154
+ reject(new HelperError("E_WASI_SOCKET_OVERFLOW", `connect ${stream} exceeded the ${maxBytes}-byte maxBytes cap`));
155
+ return false;
156
+ }
157
+ totalBytes += size;
158
+ return true;
159
+ };
126
160
  child.stdout?.setEncoding("utf8");
127
161
  child.stderr?.setEncoding("utf8");
128
162
  child.stdout?.on("data", (chunk) => {
163
+ if (!account(chunk, "stdout"))
164
+ return;
129
165
  stdout += String(chunk);
130
166
  });
131
167
  child.stderr?.on("data", (chunk) => {
168
+ if (!account(chunk, "stderr"))
169
+ return;
132
170
  stderr += String(chunk);
133
171
  });
134
172
  child.on("error", (error) => {
@@ -154,7 +192,11 @@ export class WasiSocketPort {
154
192
  * sends SIGTERM and returns immediately.
155
193
  */
156
194
  async listen(options) {
157
- const runtimePath = await this.runtimePath();
195
+ const prerequisites = await this.resolvePrerequisites();
196
+ if (!prerequisites) {
197
+ throw new HelperError("E_WASI_SOCKET_UNAVAILABLE", `WASI socket prerequisites missing: runtime '${this.runtime}' or component '${this.componentPath}'`);
198
+ }
199
+ const runtimePath = prerequisites.runtimePath;
158
200
  const args = argsFor("listen", {
159
201
  componentPath: this.componentPath,
160
202
  address: options.address,
@@ -192,13 +234,22 @@ export class WasiSocketPort {
192
234
  }
193
235
  });
194
236
  child.on("error", (error) => {
195
- emit(`error: ${error.message}`);
237
+ // Keep a listener attached even without a callback so an async spawn
238
+ // failure can never become an unhandled EventEmitter error.
239
+ if (!options.onError)
240
+ return;
241
+ try {
242
+ options.onError(failed(`listen child failed: ${error.message}`, error));
243
+ }
244
+ catch {
245
+ // A consumer's callback must not take down the child's stream.
246
+ }
196
247
  });
197
248
  child.on("close", () => {
198
- if (buffer.length > 0) {
199
- emit(buffer.replace(/\r$/, ""));
200
- buffer = "";
201
- }
249
+ const trailing = buffer.replace(/\r$/, "");
250
+ buffer = "";
251
+ if (trailing.length > 0)
252
+ emit(trailing);
202
253
  });
203
254
  return {
204
255
  close() {
@@ -36,28 +36,70 @@ function readMemory(memory, ptr, len) {
36
36
  return new Uint8Array(memory.buffer, ptr, len);
37
37
  }
38
38
  /**
39
- * Write bytes at the current end of linear memory and grow for them.
39
+ * Host-owned scratch at the end of linear memory, keyed by the memory itself.
40
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.
41
+ * Reusing the region avoids growing one page per write. It is only reused while
42
+ * linear memory has not changed size: if the module grew (or will grow) its own
43
+ * heap, the host reserves a fresh region at the new end instead of writing over
44
+ * bytes the module may have claimed.
44
45
  */
45
- function writeScratch(memory, bytes) {
46
+ const scratchRegions = new WeakMap();
47
+ /**
48
+ * Write a host payload into the module's linear memory.
49
+ *
50
+ * Safety contract:
51
+ * - A module that can grow or allocate its heap must export
52
+ * `sure_alloc(len: i32) -> i32` and return a non-zero pointer for a non-empty
53
+ * request. The host then writes only to that allocation.
54
+ * - Without `sure_alloc`, the host uses a cached scratch region at the end of
55
+ * linear memory. The region is host-owned only until the module grows memory;
56
+ * a module that calls `memory.grow` between writes gets a fresh region at the
57
+ * new end. A module that grows or allocates without exporting `sure_alloc`
58
+ * races the host for the same bytes, so exporting `sure_alloc` is the safe
59
+ * opt-in.
60
+ * - The region is valid only for the duration of the call. A module must copy
61
+ * anything it wants to keep.
62
+ */
63
+ function writeHostBytes(instance, memory, bytes) {
46
64
  if (bytes.length === 0)
47
65
  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);
66
+ const alloc = instance.exports["sure_alloc"];
67
+ if (typeof alloc === "function") {
68
+ let ptr;
69
+ try {
70
+ ptr = alloc(bytes.length);
71
+ }
72
+ catch (error) {
73
+ fail("E_WASM_MEMORY", `sure_alloc(${bytes.length}) threw`, error);
74
+ }
75
+ if (typeof ptr !== "number" ||
76
+ !Number.isInteger(ptr) ||
77
+ ptr <= 0 ||
78
+ ptr + bytes.length > memory.buffer.byteLength) {
79
+ fail("E_WASM_MEMORY", `sure_alloc(${bytes.length}) returned an unusable pointer (${String(ptr)})`);
80
+ }
81
+ new Uint8Array(memory.buffer, ptr, bytes.length).set(bytes);
82
+ return { ptr, len: bytes.length };
53
83
  }
54
- catch (error) {
55
- fail("E_WASM_MEMORY", `could not grow wasm memory by ${pages} page(s)`, error);
84
+ const memorySize = memory.buffer.byteLength;
85
+ let region = scratchRegions.get(memory);
86
+ if (!region || region.memorySize !== memorySize || bytes.length > region.cap) {
87
+ const ptr = memorySize;
88
+ const pages = Math.max(1, Math.ceil(bytes.length / 65536));
89
+ let result;
90
+ try {
91
+ result = memory.grow(pages);
92
+ }
93
+ catch (error) {
94
+ fail("E_WASM_MEMORY", `could not grow wasm memory by ${pages} page(s)`, error);
95
+ }
96
+ if (result < 0)
97
+ fail("E_WASM_MEMORY", `could not grow wasm memory by ${pages} page(s)`);
98
+ region = { ptr, cap: pages * 65536, memorySize: memory.buffer.byteLength };
99
+ scratchRegions.set(memory, region);
56
100
  }
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 };
101
+ new Uint8Array(memory.buffer, region.ptr, bytes.length).set(bytes);
102
+ return { ptr: region.ptr, len: bytes.length };
61
103
  }
62
104
  function decodeUtf8(bytes) {
63
105
  try {
@@ -114,7 +156,7 @@ export const sureAbi = {
114
156
  init(instance, config) {
115
157
  const memory = memoryOf(instance);
116
158
  const bytes = encoder.encode(JSON.stringify(config ?? {}));
117
- const scratch = writeScratch(memory, bytes);
159
+ const scratch = writeHostBytes(instance, memory, bytes);
118
160
  return checkFeedCode(exportFunction(instance, "sure_init")(scratch.ptr, scratch.len), "sure_init");
119
161
  },
120
162
  drain(instance) {
@@ -147,7 +189,7 @@ export const sureAbi = {
147
189
  const combined = new Uint8Array(kind.length + data.length);
148
190
  combined.set(kind, 0);
149
191
  combined.set(data, kind.length);
150
- const scratch = writeScratch(memory, combined);
192
+ const scratch = writeHostBytes(instance, memory, combined);
151
193
  return checkFeedCode(exportFunction(instance, "sure_feed")(scratch.ptr, kind.length, scratch.ptr + kind.length, data.length), "sure_feed");
152
194
  },
153
195
  };
@@ -225,6 +267,10 @@ export async function mountWasmCore(options) {
225
267
  fail("E_WASM_INIT_FAILED", `init returned ${initCode}`);
226
268
  }
227
269
  let closed = false;
270
+ // Serializes drive() calls: each waits for the previous one, then checks
271
+ // `closed` and runs. The queue swallows rejections so one failed drive does
272
+ // not poison later calls.
273
+ let queue = Promise.resolve();
228
274
  const feed = (kind, data, id) => {
229
275
  if (closed)
230
276
  fail("E_WASM_CLOSED", "wasm core is closed");
@@ -236,7 +282,7 @@ export async function mountWasmCore(options) {
236
282
  feedback.id = id;
237
283
  return abi.feed(instance, feedback);
238
284
  };
239
- const drive = async () => {
285
+ const drain = async () => {
240
286
  if (closed)
241
287
  fail("E_WASM_CLOSED", "wasm core is closed");
242
288
  let processed = 0;
@@ -258,6 +304,11 @@ export async function mountWasmCore(options) {
258
304
  }
259
305
  fail("E_WASM_DRIVE_LIMIT", `drive exceeded ${maxSteps} steps`);
260
306
  };
307
+ const drive = () => {
308
+ const run = queue.then(drain);
309
+ queue = run.catch(() => undefined);
310
+ return run;
311
+ };
261
312
  log("debug", `wasm: mounted '${abi.name}' ABI ${String(abiVersion)}`);
262
313
  return {
263
314
  abiVersion,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shing.wong/sure-wasm-helper",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Generic WASM reactor host, loopback UI/WebSocket host, WASI socket adapter, SEA packager, self-updater and cold-start bench",
5
5
  "type": "module",
6
6
  "license": "MIT",