@shing.wong/sure-wasm-helper 0.1.2 → 0.1.4
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 +36 -6
- package/dist/packager.d.ts +10 -4
- package/dist/packager.js +68 -20
- package/dist/updater.d.ts +9 -2
- package/dist/updater.js +74 -10
- package/dist/wasm-loader.js +70 -19
- package/package.json +1 -1
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
|
|
@@ -138,12 +147,23 @@ npx sure-pack \
|
|
|
138
147
|
--no-args-args "serve --ui --ui-dir {uiDir}"
|
|
139
148
|
```
|
|
140
149
|
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
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`.
|
|
147
167
|
|
|
148
168
|
## Self-update
|
|
149
169
|
|
|
@@ -165,6 +185,16 @@ if (update.updateAvailable) await updater.download();
|
|
|
165
185
|
checkout. The swap is performed by the downloaded binary running
|
|
166
186
|
`apply-update <pid> <target> --relaunch ...`; see `docs/design.md` (ADR-004).
|
|
167
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
|
+
|
|
168
198
|
## Development
|
|
169
199
|
|
|
170
200
|
```bash
|
package/dist/packager.d.ts
CHANGED
|
@@ -9,14 +9,18 @@ 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
|
|
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
|
+
/** Browser-opener port when noArgsArgs omits --port. */
|
|
21
|
+
defaultUiPort?: number;
|
|
22
|
+
/** Modules esbuild must leave as runtime `require()` calls. */
|
|
23
|
+
external?: string[];
|
|
20
24
|
envCore?: string;
|
|
21
25
|
envBuild?: string;
|
|
22
26
|
envUi?: string;
|
|
@@ -28,16 +32,18 @@ export interface PackagePlan {
|
|
|
28
32
|
app: string;
|
|
29
33
|
entry: string;
|
|
30
34
|
uiDir: string;
|
|
31
|
-
core: string;
|
|
35
|
+
core: string | null;
|
|
32
36
|
out: string;
|
|
33
37
|
uiFiles: string[];
|
|
34
38
|
extraAssets: PackageAsset[];
|
|
35
39
|
assetNames: string[];
|
|
40
|
+
external: string[];
|
|
36
41
|
envCore: string;
|
|
37
42
|
envBuild: string;
|
|
38
43
|
envUi: string;
|
|
39
44
|
envLaunch: string;
|
|
40
45
|
noArgsArgs: string[] | null;
|
|
46
|
+
defaultUiPort: number;
|
|
41
47
|
buildDate: string;
|
|
42
48
|
}
|
|
43
49
|
export interface PackageResult {
|
|
@@ -61,6 +67,6 @@ export declare function parsePackageCli(argv: string[]): PackageOptions;
|
|
|
61
67
|
/** CLI entry point. Returns an exit code; never calls process.exit. */
|
|
62
68
|
export declare function runSurePackCli(argv?: string[]): Promise<number>;
|
|
63
69
|
/** Exported for the packaged binary's own `--version` diagnostics. */
|
|
64
|
-
export declare const packagerVersion = "0.1.
|
|
70
|
+
export declare const packagerVersion = "0.1.4";
|
|
65
71
|
/** Exported for callers that need the default executable suffix. */
|
|
66
72
|
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,11 +99,13 @@ 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",
|
|
105
106
|
envLaunch: options.envLaunch ?? "SURE_APP_LAUNCH_ARGS",
|
|
106
107
|
noArgsArgs,
|
|
108
|
+
defaultUiPort: options.defaultUiPort ?? 8788,
|
|
107
109
|
buildDate: new Date().toISOString(),
|
|
108
110
|
};
|
|
109
111
|
}
|
|
@@ -143,7 +145,8 @@ function assetContents(plan) {
|
|
|
143
145
|
for (const file of plan.uiFiles) {
|
|
144
146
|
contents.set(`ui/${file}`, readFileSync(join(plan.uiDir, file)));
|
|
145
147
|
}
|
|
146
|
-
|
|
148
|
+
if (plan.core !== null)
|
|
149
|
+
contents.set("core/core.wasm", readFileSync(plan.core));
|
|
147
150
|
for (const asset of plan.extraAssets) {
|
|
148
151
|
contents.set(asset.name, readFileSync(asset.path));
|
|
149
152
|
}
|
|
@@ -172,6 +175,7 @@ function prelude(plan, entryHash) {
|
|
|
172
175
|
envBuild: plan.envBuild,
|
|
173
176
|
envUi: plan.envUi,
|
|
174
177
|
envLaunch: plan.envLaunch,
|
|
178
|
+
hasCore: plan.core !== null,
|
|
175
179
|
assetNames: plan.assetNames,
|
|
176
180
|
entryHash,
|
|
177
181
|
noArgsArgs: plan.noArgsArgs,
|
|
@@ -200,25 +204,50 @@ if (require("node:sea").isSea()) {
|
|
|
200
204
|
: (process.env.XDG_CACHE_HOME || path.join(os.homedir(), ".cache"));
|
|
201
205
|
const uiDir = path.join(base, CONFIG.app, "ui-" + stamp);
|
|
202
206
|
const corePath = path.join(uiDir, "core.wasm");
|
|
207
|
+
const required = CONFIG.hasCore ? ["index.html", "core.wasm"] : ["index.html"];
|
|
208
|
+
const complete = (dir) => required.every((name) => fs.existsSync(path.join(dir, name)));
|
|
203
209
|
const relativeOf = (name) =>
|
|
204
210
|
name === "core/core.wasm" ? "core.wasm" : name.startsWith("ui/") ? name.slice(3) : name;
|
|
205
211
|
|
|
206
|
-
if (!
|
|
212
|
+
if (!complete(uiDir)) {
|
|
207
213
|
const tmp = uiDir + ".tmp-" + process.pid;
|
|
208
214
|
fs.rmSync(tmp, { recursive: true, force: true });
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
const
|
|
212
|
-
|
|
213
|
-
|
|
215
|
+
try {
|
|
216
|
+
fs.mkdirSync(tmp, { recursive: true });
|
|
217
|
+
for (const name of CONFIG.assetNames) {
|
|
218
|
+
const target = path.join(tmp, relativeOf(name));
|
|
219
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
220
|
+
fs.writeFileSync(target, Buffer.from(sea.getAsset(name)));
|
|
221
|
+
}
|
|
222
|
+
fs.mkdirSync(path.dirname(uiDir), { recursive: true });
|
|
223
|
+
try {
|
|
224
|
+
fs.renameSync(tmp, uiDir);
|
|
225
|
+
} catch (error) {
|
|
226
|
+
// Another process may have completed the same content-addressed cache
|
|
227
|
+
// first. Accept it only when it is complete; never leave the temp dir.
|
|
228
|
+
if (complete(uiDir)) {
|
|
229
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
230
|
+
} else {
|
|
231
|
+
// A stale partial cache from an interrupted older run: remove it and
|
|
232
|
+
// retry the swap. The new directory is already fully written.
|
|
233
|
+
fs.rmSync(uiDir, { recursive: true, force: true });
|
|
234
|
+
try {
|
|
235
|
+
fs.renameSync(tmp, uiDir);
|
|
236
|
+
} catch (second) {
|
|
237
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
238
|
+
if (!complete(uiDir)) throw second;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
} catch (error) {
|
|
243
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
244
|
+
if (!complete(uiDir)) fs.rmSync(uiDir, { recursive: true, force: true });
|
|
245
|
+
throw error;
|
|
214
246
|
}
|
|
215
|
-
fs.rmSync(uiDir, { recursive: true, force: true });
|
|
216
|
-
fs.mkdirSync(path.dirname(uiDir), { recursive: true });
|
|
217
|
-
fs.renameSync(tmp, uiDir);
|
|
218
247
|
}
|
|
219
248
|
|
|
220
249
|
process.env[CONFIG.envUi] = uiDir;
|
|
221
|
-
process.env[CONFIG.envCore] = corePath;
|
|
250
|
+
if (CONFIG.hasCore) process.env[CONFIG.envCore] = corePath;
|
|
222
251
|
|
|
223
252
|
const args = process.argv.slice(2);
|
|
224
253
|
process.env[CONFIG.envLaunch] = JSON.stringify(args);
|
|
@@ -227,7 +256,7 @@ if (require("node:sea").isSea()) {
|
|
|
227
256
|
process.argv = [process.argv[0], process.argv[1], ...rewritten];
|
|
228
257
|
if (!rewritten.includes("--no-open")) {
|
|
229
258
|
setTimeout(() => {
|
|
230
|
-
const url = "http://127.0.0.1:" + (rewritten.includes("--port") ? rewritten[rewritten.indexOf("--port") + 1] :
|
|
259
|
+
const url = "http://127.0.0.1:" + (rewritten.includes("--port") ? rewritten[rewritten.indexOf("--port") + 1] : String(CONFIG.defaultUiPort)) + "/";
|
|
231
260
|
const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
|
|
232
261
|
const argv = process.platform === "win32" ? ["/c", "start", "", url] : [url];
|
|
233
262
|
try {
|
|
@@ -262,6 +291,7 @@ export async function packageApp(options) {
|
|
|
262
291
|
format: "cjs",
|
|
263
292
|
target: "node22",
|
|
264
293
|
logLevel: "warning",
|
|
294
|
+
external: plan.external,
|
|
265
295
|
define: { "import.meta.url": "__seaImportMetaUrl" },
|
|
266
296
|
banner: {
|
|
267
297
|
js: `const __seaImportMetaUrl = require("node:url").pathToFileURL(process.execPath).href;`,
|
|
@@ -278,7 +308,8 @@ export async function packageApp(options) {
|
|
|
278
308
|
const assets = {};
|
|
279
309
|
for (const file of plan.uiFiles)
|
|
280
310
|
assets[`ui/${file}`] = join(plan.uiDir, file);
|
|
281
|
-
|
|
311
|
+
if (plan.core !== null)
|
|
312
|
+
assets["core/core.wasm"] = plan.core;
|
|
282
313
|
for (const asset of plan.extraAssets)
|
|
283
314
|
assets[asset.name] = asset.path;
|
|
284
315
|
const config = seaConfigPath(work);
|
|
@@ -352,6 +383,7 @@ export function parsePackageCli(argv) {
|
|
|
352
383
|
for (const [name, path] of Object.entries(options.assets))
|
|
353
384
|
assets.push({ name, path });
|
|
354
385
|
}
|
|
386
|
+
const external = Array.isArray(options.external) ? [...options.external] : [];
|
|
355
387
|
for (let index = 0; index < argv.length; index += 1) {
|
|
356
388
|
const flag = argv[index];
|
|
357
389
|
switch (flag) {
|
|
@@ -407,23 +439,39 @@ export function parsePackageCli(argv) {
|
|
|
407
439
|
index += 1;
|
|
408
440
|
break;
|
|
409
441
|
}
|
|
442
|
+
case "--external":
|
|
443
|
+
external.push(takeValue(argv, index, flag));
|
|
444
|
+
index += 1;
|
|
445
|
+
break;
|
|
446
|
+
case "--default-ui-port": {
|
|
447
|
+
const port = Number(takeValue(argv, index, flag));
|
|
448
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
449
|
+
fail("--default-ui-port must be 1-65535");
|
|
450
|
+
}
|
|
451
|
+
options.defaultUiPort = port;
|
|
452
|
+
index += 1;
|
|
453
|
+
break;
|
|
454
|
+
}
|
|
410
455
|
default:
|
|
411
456
|
fail(`unknown argument '${flag}'`);
|
|
412
457
|
}
|
|
413
458
|
}
|
|
414
459
|
if (assets.length > 0)
|
|
415
460
|
options.assets = assets;
|
|
461
|
+
if (external.length > 0)
|
|
462
|
+
options.external = external;
|
|
416
463
|
if (typeof options.app !== "string" ||
|
|
417
464
|
typeof options.entry !== "string" ||
|
|
418
465
|
typeof options.uiDir !== "string" ||
|
|
419
|
-
typeof options.core !== "string" ||
|
|
420
466
|
typeof options.out !== "string") {
|
|
421
|
-
fail("need --app, --entry, --ui-dir
|
|
467
|
+
fail("need --app, --entry, --ui-dir and --out (or --config)");
|
|
422
468
|
}
|
|
423
469
|
return options;
|
|
424
470
|
}
|
|
425
|
-
const USAGE = `usage: sure-pack --app <name> --entry <file> --ui-dir <dir> --
|
|
426
|
-
[--asset name=path]... [--
|
|
471
|
+
const USAGE = `usage: sure-pack --app <name> --entry <file> --ui-dir <dir> --out <file>
|
|
472
|
+
[--core <wasm>] [--asset name=path]... [--external <module>]...
|
|
473
|
+
[--default-ui-port <n>]
|
|
474
|
+
[--no-args-args "serve --ui"]
|
|
427
475
|
[--env-core NAME] [--env-build NAME] [--env-ui NAME] [--env-launch NAME]
|
|
428
476
|
[--config sure-pack.json]`;
|
|
429
477
|
/** CLI entry point. Returns an exit code; never calls process.exit. */
|
|
@@ -446,7 +494,7 @@ export async function runSurePackCli(argv = process.argv.slice(2)) {
|
|
|
446
494
|
}
|
|
447
495
|
}
|
|
448
496
|
/** Exported for the packaged binary's own `--version` diagnostics. */
|
|
449
|
-
export const packagerVersion = "0.1.
|
|
497
|
+
export const packagerVersion = "0.1.4";
|
|
450
498
|
/** Exported for callers that need the default executable suffix. */
|
|
451
499
|
export function defaultExecutableName(app, platform = process.platform) {
|
|
452
500
|
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:
|
|
102
|
-
*
|
|
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(
|
|
211
|
+
await pipeline(Readable.fromWeb(response.body), hasher, createWriteStream(part));
|
|
180
212
|
}
|
|
181
213
|
catch (error) {
|
|
182
|
-
await rm(
|
|
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(
|
|
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(
|
|
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:
|
|
312
|
-
*
|
|
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
|
-
|
|
335
|
-
|
|
336
|
-
|
|
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;
|
package/dist/wasm-loader.js
CHANGED
|
@@ -36,28 +36,70 @@ function readMemory(memory, ptr, len) {
|
|
|
36
36
|
return new Uint8Array(memory.buffer, ptr, len);
|
|
37
37
|
}
|
|
38
38
|
/**
|
|
39
|
-
*
|
|
39
|
+
* Host-owned scratch at the end of linear memory, keyed by the memory itself.
|
|
40
40
|
*
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
*
|
|
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
|
-
|
|
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
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
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
|
-
|
|
55
|
-
|
|
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
|
-
|
|
58
|
-
|
|
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 =
|
|
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 =
|
|
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
|
|
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.
|
|
3
|
+
"version": "0.1.4",
|
|
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",
|