@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.
- package/LICENSE +21 -0
- package/README.md +134 -2
- package/bin/sure-pack.mjs +8 -0
- package/dist/bench-cold.d.ts +29 -0
- package/dist/bench-cold.js +155 -0
- package/dist/loopback-host.d.ts +59 -0
- package/dist/loopback-host.js +320 -0
- package/dist/packager.d.ts +66 -0
- package/dist/packager.js +453 -0
- package/dist/updater.d.ts +109 -0
- package/dist/updater.js +389 -0
- package/dist/wasi-socket.d.ts +77 -0
- package/dist/wasi-socket.js +218 -0
- package/dist/wasm-loader.d.ts +76 -0
- package/dist/wasm-loader.js +271 -0
- package/package.json +78 -4
package/dist/updater.js
ADDED
|
@@ -0,0 +1,389 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// Generic self-update: manifest check, streaming verified download, executable
|
|
3
|
+
// swap by rename. No product manifest URL or path is baked in.
|
|
4
|
+
import { spawn } from "node:child_process";
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
6
|
+
import { createWriteStream } from "node:fs";
|
|
7
|
+
import { chmod, copyFile, mkdir, rename, rm, stat } from "node:fs/promises";
|
|
8
|
+
import { homedir } from "node:os";
|
|
9
|
+
import { basename, join } from "node:path";
|
|
10
|
+
import { Readable, Transform } from "node:stream";
|
|
11
|
+
import { pipeline } from "node:stream/promises";
|
|
12
|
+
import { HelperError } from "./wasm-loader.js";
|
|
13
|
+
function assetKey(platform, arch) {
|
|
14
|
+
return `${platform}-${arch}`;
|
|
15
|
+
}
|
|
16
|
+
function isNodeExecutable(execPath) {
|
|
17
|
+
return /^node(\.exe)?$/i.test(basename(execPath));
|
|
18
|
+
}
|
|
19
|
+
function messageOf(error) {
|
|
20
|
+
return error instanceof Error ? error.message : String(error);
|
|
21
|
+
}
|
|
22
|
+
function storedRelaunchArgs(env, fallback, launchEnv) {
|
|
23
|
+
const candidates = [
|
|
24
|
+
...(launchEnv ? [launchEnv] : []),
|
|
25
|
+
"SURE_APP_LAUNCH_ARGS",
|
|
26
|
+
"SURE_LAUNCH_ARGS",
|
|
27
|
+
];
|
|
28
|
+
for (const name of candidates) {
|
|
29
|
+
const raw = env[name];
|
|
30
|
+
if (typeof raw === "string" && raw.length > 0) {
|
|
31
|
+
try {
|
|
32
|
+
const parsed = JSON.parse(raw);
|
|
33
|
+
if (Array.isArray(parsed) && parsed.every((item) => typeof item === "string")) {
|
|
34
|
+
return parsed;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
// A malformed stash must not block an update; try the next name.
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return fallback;
|
|
43
|
+
}
|
|
44
|
+
function looseFilename(url, appName, build, platform) {
|
|
45
|
+
let name = "";
|
|
46
|
+
try {
|
|
47
|
+
name = basename(new URL(url).pathname);
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
name = "";
|
|
51
|
+
}
|
|
52
|
+
if (name.length === 0 || name === "/") {
|
|
53
|
+
name = `${appName}-${build}${platform === "win32" ? ".exe" : ""}`;
|
|
54
|
+
}
|
|
55
|
+
return name.replace(/[^A-Za-z0-9._-]/g, "-");
|
|
56
|
+
}
|
|
57
|
+
export class SelfUpdater {
|
|
58
|
+
options;
|
|
59
|
+
fetchImpl;
|
|
60
|
+
env;
|
|
61
|
+
platform;
|
|
62
|
+
execPath;
|
|
63
|
+
constructor(options) {
|
|
64
|
+
this.options = options;
|
|
65
|
+
this.fetchImpl = options.fetchImpl ?? fetch;
|
|
66
|
+
this.env = options.env ?? process.env;
|
|
67
|
+
this.platform = options.platform ?? process.platform;
|
|
68
|
+
this.execPath = options.execPath ?? process.execPath;
|
|
69
|
+
}
|
|
70
|
+
/** Fetch the manifest and compare builds (or versions when no build). */
|
|
71
|
+
async check() {
|
|
72
|
+
const current = this.options.currentBuild || this.options.currentVersion;
|
|
73
|
+
try {
|
|
74
|
+
const response = await this.fetchImpl(this.options.manifestUrl, {
|
|
75
|
+
signal: AbortSignal.timeout(8000),
|
|
76
|
+
headers: { "cache-control": "no-cache" },
|
|
77
|
+
});
|
|
78
|
+
if (!response.ok) {
|
|
79
|
+
throw new Error(`manifest HTTP ${response.status}`);
|
|
80
|
+
}
|
|
81
|
+
const manifest = (await response.json());
|
|
82
|
+
if (!manifest || typeof manifest !== "object" || typeof manifest.version !== "string") {
|
|
83
|
+
throw new Error("manifest is missing a string version");
|
|
84
|
+
}
|
|
85
|
+
if (!manifest.assets || typeof manifest.assets !== "object") {
|
|
86
|
+
throw new Error("manifest is missing an assets map");
|
|
87
|
+
}
|
|
88
|
+
const key = assetKey(this.platform, process.arch === "arm64" ? "arm64" : "x64");
|
|
89
|
+
const asset = manifest.assets[key];
|
|
90
|
+
if (!asset) {
|
|
91
|
+
return {
|
|
92
|
+
ok: false,
|
|
93
|
+
current,
|
|
94
|
+
latest: "",
|
|
95
|
+
updateAvailable: false,
|
|
96
|
+
asset: null,
|
|
97
|
+
code: "E_UPDATE_MANIFEST",
|
|
98
|
+
error: `no asset published for ${key}`,
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
const hasBuild = typeof asset.build === "string" && asset.build.length > 0;
|
|
102
|
+
const latest = hasBuild ? String(asset.build) : manifest.version;
|
|
103
|
+
const base = hasBuild ? this.options.currentBuild : this.options.currentVersion;
|
|
104
|
+
const currentBuiltAt = this.options.currentBuiltAt;
|
|
105
|
+
if (currentBuiltAt && asset.builtAt) {
|
|
106
|
+
const currentMs = Date.parse(currentBuiltAt);
|
|
107
|
+
const publishedMs = Date.parse(asset.builtAt);
|
|
108
|
+
if (Number.isFinite(currentMs) && Number.isFinite(publishedMs) && currentMs > publishedMs) {
|
|
109
|
+
return {
|
|
110
|
+
ok: true,
|
|
111
|
+
current,
|
|
112
|
+
latest,
|
|
113
|
+
updateAvailable: false,
|
|
114
|
+
asset,
|
|
115
|
+
reason: "the local build is newer than the published release",
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return {
|
|
120
|
+
ok: true,
|
|
121
|
+
current,
|
|
122
|
+
latest,
|
|
123
|
+
updateAvailable: latest !== base,
|
|
124
|
+
asset,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
catch (error) {
|
|
128
|
+
return {
|
|
129
|
+
ok: false,
|
|
130
|
+
current,
|
|
131
|
+
latest: "",
|
|
132
|
+
updateAvailable: false,
|
|
133
|
+
asset: null,
|
|
134
|
+
code: "E_UPDATE_MANIFEST",
|
|
135
|
+
error: messageOf(error),
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
/** Download and verify this platform's asset while hashing. */
|
|
140
|
+
async download() {
|
|
141
|
+
const info = await this.check();
|
|
142
|
+
if (!info.ok || !info.asset) {
|
|
143
|
+
return {
|
|
144
|
+
ok: false,
|
|
145
|
+
code: info.code ?? "E_UPDATE_MANIFEST",
|
|
146
|
+
error: info.error ?? "no update information",
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
const asset = info.asset;
|
|
150
|
+
const dir = this.options.downloadsDir ?? join(homedir(), "Downloads");
|
|
151
|
+
const name = looseFilename(asset.url, this.options.appName, info.latest, this.platform);
|
|
152
|
+
const path = join(dir, name);
|
|
153
|
+
try {
|
|
154
|
+
await mkdir(dir, { recursive: true });
|
|
155
|
+
}
|
|
156
|
+
catch (error) {
|
|
157
|
+
return { ok: false, code: "E_UPDATE_DOWNLOAD", error: `could not create ${dir}: ${messageOf(error)}` };
|
|
158
|
+
}
|
|
159
|
+
let response;
|
|
160
|
+
try {
|
|
161
|
+
response = await this.fetchImpl(asset.url, { signal: AbortSignal.timeout(600000) });
|
|
162
|
+
}
|
|
163
|
+
catch (error) {
|
|
164
|
+
return { ok: false, code: "E_UPDATE_DOWNLOAD", error: messageOf(error) };
|
|
165
|
+
}
|
|
166
|
+
if (!response.ok || !response.body) {
|
|
167
|
+
return { ok: false, code: "E_UPDATE_DOWNLOAD", error: `download HTTP ${response.status}` };
|
|
168
|
+
}
|
|
169
|
+
const hash = createHash("sha256");
|
|
170
|
+
let bytes = 0;
|
|
171
|
+
const hasher = new Transform({
|
|
172
|
+
transform(chunk, _encoding, done) {
|
|
173
|
+
bytes += chunk.length;
|
|
174
|
+
hash.update(chunk);
|
|
175
|
+
done(null, chunk);
|
|
176
|
+
},
|
|
177
|
+
});
|
|
178
|
+
try {
|
|
179
|
+
await pipeline(Readable.fromWeb(response.body), hasher, createWriteStream(path));
|
|
180
|
+
}
|
|
181
|
+
catch (error) {
|
|
182
|
+
await rm(path, { force: true });
|
|
183
|
+
return { ok: false, code: "E_UPDATE_DOWNLOAD", error: messageOf(error) };
|
|
184
|
+
}
|
|
185
|
+
const digest = hash.digest("hex");
|
|
186
|
+
if (digest !== asset.sha256) {
|
|
187
|
+
await rm(path, { force: true });
|
|
188
|
+
return {
|
|
189
|
+
ok: false,
|
|
190
|
+
code: "E_UPDATE_CHECKSUM",
|
|
191
|
+
error: `checksum mismatch (got ${digest.slice(0, 12)}…, expected ${asset.sha256.slice(0, 12)}…)`,
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
if (bytes === 0) {
|
|
195
|
+
await rm(path, { force: true });
|
|
196
|
+
return { ok: false, code: "E_UPDATE_DOWNLOAD", error: "download was empty" };
|
|
197
|
+
}
|
|
198
|
+
if (this.platform !== "win32") {
|
|
199
|
+
try {
|
|
200
|
+
await chmod(path, 0o755);
|
|
201
|
+
}
|
|
202
|
+
catch (error) {
|
|
203
|
+
return { ok: false, code: "E_UPDATE_DOWNLOAD", error: `chmod failed: ${messageOf(error)}` };
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
let size = bytes;
|
|
207
|
+
try {
|
|
208
|
+
size = (await stat(path)).size;
|
|
209
|
+
}
|
|
210
|
+
catch {
|
|
211
|
+
// bytes is authoritative if stat races with an antivirus lock.
|
|
212
|
+
}
|
|
213
|
+
return {
|
|
214
|
+
ok: true,
|
|
215
|
+
path,
|
|
216
|
+
bytes: size,
|
|
217
|
+
sha256: digest,
|
|
218
|
+
build: info.latest,
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Download, then start the verified helper to swap and relaunch.
|
|
223
|
+
*
|
|
224
|
+
* Refuses when the running executable is Node itself: a source checkout must
|
|
225
|
+
* not replace the interpreter it is running on.
|
|
226
|
+
*/
|
|
227
|
+
async apply() {
|
|
228
|
+
if (isNodeExecutable(this.execPath)) {
|
|
229
|
+
return {
|
|
230
|
+
ok: false,
|
|
231
|
+
code: "E_UPDATE_SOURCE_CHECKOUT",
|
|
232
|
+
error: "This process was started with node, not the packaged application, so it cannot replace itself. " +
|
|
233
|
+
"Stop it and start the new build manually.",
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
const downloaded = await this.download();
|
|
237
|
+
if (!downloaded.ok || !downloaded.path) {
|
|
238
|
+
return {
|
|
239
|
+
ok: false,
|
|
240
|
+
code: downloaded.code ?? "E_UPDATE_DOWNLOAD",
|
|
241
|
+
error: downloaded.error ?? "download failed",
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
const relaunch = this.options.relaunchArgs ?? storedRelaunchArgs(this.env, process.argv.slice(2), this.options.launchEnv);
|
|
245
|
+
try {
|
|
246
|
+
await spawnDetached(downloaded.path, [
|
|
247
|
+
"apply-update",
|
|
248
|
+
String(process.pid),
|
|
249
|
+
this.execPath,
|
|
250
|
+
"--relaunch",
|
|
251
|
+
...relaunch,
|
|
252
|
+
]);
|
|
253
|
+
}
|
|
254
|
+
catch (error) {
|
|
255
|
+
return { ok: false, code: "E_UPDATE_APPLY", error: messageOf(error) };
|
|
256
|
+
}
|
|
257
|
+
return {
|
|
258
|
+
ok: true,
|
|
259
|
+
restarting: true,
|
|
260
|
+
path: downloaded.path,
|
|
261
|
+
target: this.execPath,
|
|
262
|
+
build: downloaded.build,
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
export function createSelfUpdater(options) {
|
|
267
|
+
return new SelfUpdater(options);
|
|
268
|
+
}
|
|
269
|
+
function sleep(ms) {
|
|
270
|
+
return new Promise((done) => setTimeout(done, ms));
|
|
271
|
+
}
|
|
272
|
+
/** Spawn a detached child and wait for the OS to accept it (or fail). */
|
|
273
|
+
function spawnDetached(command, args, cwd) {
|
|
274
|
+
return new Promise((resolve, reject) => {
|
|
275
|
+
const child = spawn(command, args, { detached: true, stdio: "ignore", cwd });
|
|
276
|
+
let settled = false;
|
|
277
|
+
const finish = (error) => {
|
|
278
|
+
if (settled)
|
|
279
|
+
return;
|
|
280
|
+
settled = true;
|
|
281
|
+
clearTimeout(timer);
|
|
282
|
+
child.off("spawn", onSpawn);
|
|
283
|
+
child.off("error", onError);
|
|
284
|
+
if (error)
|
|
285
|
+
reject(error);
|
|
286
|
+
else {
|
|
287
|
+
child.unref();
|
|
288
|
+
resolve();
|
|
289
|
+
}
|
|
290
|
+
};
|
|
291
|
+
const onSpawn = () => finish();
|
|
292
|
+
const onError = (error) => finish(error);
|
|
293
|
+
const timer = setTimeout(() => finish(), 1500);
|
|
294
|
+
child.once("spawn", onSpawn);
|
|
295
|
+
child.once("error", onError);
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
function pidAlive(pid) {
|
|
299
|
+
try {
|
|
300
|
+
process.kill(pid, 0);
|
|
301
|
+
return true;
|
|
302
|
+
}
|
|
303
|
+
catch (error) {
|
|
304
|
+
const code = error.code;
|
|
305
|
+
return code === "EPERM";
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* Wait for `pid`, then replace `target` with the running helper binary.
|
|
310
|
+
*
|
|
311
|
+
* Sequence: copy helper -> `.new`, rename target -> `.old`, rename `.new` ->
|
|
312
|
+
* target, chmod. Any failure after the target moves restores `.old`.
|
|
313
|
+
*/
|
|
314
|
+
export async function applyUpdateSwap(options) {
|
|
315
|
+
const platform = options.platform ?? process.platform;
|
|
316
|
+
const execPath = options.execPath ?? process.execPath;
|
|
317
|
+
const waitMs = options.waitMs ?? 60000;
|
|
318
|
+
const pollMs = options.pollMs ?? 200;
|
|
319
|
+
const target = options.target;
|
|
320
|
+
const backup = `${target}.old`;
|
|
321
|
+
const next = `${target}.new`;
|
|
322
|
+
if (!Number.isInteger(options.pid) || options.pid <= 0) {
|
|
323
|
+
throw new HelperError("E_UPDATE_INVALID_PID", `invalid pid ${String(options.pid)}`);
|
|
324
|
+
}
|
|
325
|
+
const started = Date.now();
|
|
326
|
+
while (pidAlive(options.pid)) {
|
|
327
|
+
if (Date.now() - started >= waitMs) {
|
|
328
|
+
throw new HelperError("E_UPDATE_WAIT_TIMEOUT", `process ${options.pid} did not exit within ${waitMs}ms`);
|
|
329
|
+
}
|
|
330
|
+
await sleep(pollMs);
|
|
331
|
+
}
|
|
332
|
+
let movedOld = false;
|
|
333
|
+
try {
|
|
334
|
+
await copyFile(execPath, next);
|
|
335
|
+
if (platform !== "win32")
|
|
336
|
+
await chmod(next, 0o755);
|
|
337
|
+
await rm(backup, { force: true });
|
|
338
|
+
await rename(target, backup);
|
|
339
|
+
movedOld = true;
|
|
340
|
+
await rename(next, target);
|
|
341
|
+
if (platform !== "win32")
|
|
342
|
+
await chmod(target, 0o755);
|
|
343
|
+
}
|
|
344
|
+
catch (error) {
|
|
345
|
+
if (movedOld) {
|
|
346
|
+
try {
|
|
347
|
+
await rename(backup, target);
|
|
348
|
+
}
|
|
349
|
+
catch {
|
|
350
|
+
// The original remains at `.old`; the error message names it below.
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
await rm(next, { force: true });
|
|
354
|
+
throw new HelperError("E_UPDATE_SWAP", `could not swap ${target} (backup: ${backup}): ${messageOf(error)}`, { cause: error });
|
|
355
|
+
}
|
|
356
|
+
return { ok: true, backup };
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* Entry point for the packaged binary's `apply-update <pid> <target>
|
|
360
|
+
* [--relaunch ...]` verb. Returns a process exit code; never calls exit().
|
|
361
|
+
*/
|
|
362
|
+
export async function runApplyUpdateCli(argv = process.argv.slice(2)) {
|
|
363
|
+
const relaunchAt = argv.indexOf("--relaunch");
|
|
364
|
+
const positional = relaunchAt === -1 ? argv : argv.slice(0, relaunchAt);
|
|
365
|
+
const relaunchArgs = relaunchAt === -1 ? [] : argv.slice(relaunchAt + 1);
|
|
366
|
+
const pid = Number(positional[0]);
|
|
367
|
+
const target = positional[1];
|
|
368
|
+
if (!Number.isInteger(pid) || pid <= 0 || typeof target !== "string" || target.length === 0) {
|
|
369
|
+
console.error("apply-update: usage: apply-update <pid> <target> [--relaunch ...args]");
|
|
370
|
+
return 1;
|
|
371
|
+
}
|
|
372
|
+
try {
|
|
373
|
+
const result = await applyUpdateSwap({ pid, target, relaunchArgs });
|
|
374
|
+
console.error(`apply-update: replaced ${target} (backup ${result.backup})`);
|
|
375
|
+
}
|
|
376
|
+
catch (error) {
|
|
377
|
+
const code = error instanceof HelperError ? error.code : "E_UPDATE_SWAP";
|
|
378
|
+
console.error(`${code}: ${messageOf(error)}`);
|
|
379
|
+
return 1;
|
|
380
|
+
}
|
|
381
|
+
try {
|
|
382
|
+
await spawnDetached(target, relaunchArgs, process.cwd());
|
|
383
|
+
}
|
|
384
|
+
catch (error) {
|
|
385
|
+
console.error(`E_UPDATE_APPLY: could not relaunch ${target}: ${messageOf(error)}`);
|
|
386
|
+
return 1;
|
|
387
|
+
}
|
|
388
|
+
return 0;
|
|
389
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { type ChildProcess } from "node:child_process";
|
|
2
|
+
import type { Readable } from "node:stream";
|
|
3
|
+
export interface WasiSpawnedProcess {
|
|
4
|
+
stdout: Readable | null;
|
|
5
|
+
stderr: Readable | null;
|
|
6
|
+
on(event: "error", listener: (error: Error) => void): unknown;
|
|
7
|
+
on(event: "exit" | "close", listener: (code: number | null) => void): unknown;
|
|
8
|
+
kill(signal?: NodeJS.Signals): boolean;
|
|
9
|
+
}
|
|
10
|
+
export interface WasiSpawnOptions {
|
|
11
|
+
env?: NodeJS.ProcessEnv;
|
|
12
|
+
stdio?: Array<"ignore" | "pipe" | "inherit">;
|
|
13
|
+
windowsHide?: boolean;
|
|
14
|
+
}
|
|
15
|
+
export type WasiSpawnImpl = (command: string, args: string[], options: WasiSpawnOptions) => WasiSpawnedProcess;
|
|
16
|
+
export interface WasiSocketPortOptions {
|
|
17
|
+
/** Path to the compiled WASI 0.2 socket component. */
|
|
18
|
+
componentPath: string;
|
|
19
|
+
/** Runtime binary or absolute path. Defaults to `wasmtime`. */
|
|
20
|
+
runtime?: string;
|
|
21
|
+
/** Extra environment for the child. Merged over process.env. */
|
|
22
|
+
env?: NodeJS.ProcessEnv;
|
|
23
|
+
/** Injectable spawn for tests. Defaults to node:child_process.spawn. */
|
|
24
|
+
spawnImpl?: WasiSpawnImpl;
|
|
25
|
+
}
|
|
26
|
+
export interface WasiConnectOptions {
|
|
27
|
+
address: string;
|
|
28
|
+
message?: string;
|
|
29
|
+
tls?: boolean;
|
|
30
|
+
timeoutMs?: number;
|
|
31
|
+
}
|
|
32
|
+
export interface WasiConnectResult {
|
|
33
|
+
connected: boolean;
|
|
34
|
+
reply: string;
|
|
35
|
+
stderr: string;
|
|
36
|
+
}
|
|
37
|
+
export interface WasiListenOptions {
|
|
38
|
+
address: string;
|
|
39
|
+
onLine: (line: string) => void;
|
|
40
|
+
}
|
|
41
|
+
export interface WasiListenHandle {
|
|
42
|
+
close(): void;
|
|
43
|
+
child: WasiSpawnedProcess;
|
|
44
|
+
}
|
|
45
|
+
export type WasiMode = "connect" | "listen";
|
|
46
|
+
export interface WasiArgsOptions {
|
|
47
|
+
componentPath: string;
|
|
48
|
+
address: string;
|
|
49
|
+
message?: string;
|
|
50
|
+
tls?: boolean;
|
|
51
|
+
}
|
|
52
|
+
/** Build the runtime argv. Exported so tests assert flags without spawning. */
|
|
53
|
+
export declare function argsFor(mode: WasiMode, options: WasiArgsOptions): string[];
|
|
54
|
+
/** Resolve a runtime name against PATH, or accept an explicit path. */
|
|
55
|
+
export declare function resolveRuntime(runtime: string): Promise<string | null>;
|
|
56
|
+
export declare class WasiSocketPort {
|
|
57
|
+
readonly componentPath: string;
|
|
58
|
+
readonly runtime: string;
|
|
59
|
+
private readonly env;
|
|
60
|
+
private readonly spawnImpl;
|
|
61
|
+
constructor(options: WasiSocketPortOptions);
|
|
62
|
+
/** True when both the runtime and the component file are usable. */
|
|
63
|
+
available(): Promise<boolean>;
|
|
64
|
+
private runtimePath;
|
|
65
|
+
/** Open a connection, optionally send one message, and collect the reply. */
|
|
66
|
+
connect(options: WasiConnectOptions): Promise<WasiConnectResult>;
|
|
67
|
+
/**
|
|
68
|
+
* Start a listening child and stream stdout lines.
|
|
69
|
+
*
|
|
70
|
+
* The component owns framing; this adapter only splits on newlines. `close`
|
|
71
|
+
* sends SIGTERM and returns immediately.
|
|
72
|
+
*/
|
|
73
|
+
listen(options: WasiListenOptions): Promise<WasiListenHandle>;
|
|
74
|
+
}
|
|
75
|
+
export declare function createWasiSocketPort(options: WasiSocketPortOptions): WasiSocketPort;
|
|
76
|
+
/** Present so callers can test the child type without importing node types. */
|
|
77
|
+
export type WasiChild = ChildProcess;
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// Portable adapter around a WASI 0.2 `wasi-socket-server` component. Node's
|
|
3
|
+
// WASI has no sockets, so this shells out to a runtime (wasmtime by default).
|
|
4
|
+
// There is no native addon and no network access in this module itself.
|
|
5
|
+
import { spawn } from "node:child_process";
|
|
6
|
+
import { constants } from "node:fs";
|
|
7
|
+
import { access } from "node:fs/promises";
|
|
8
|
+
import { delimiter, join } from "node:path";
|
|
9
|
+
import { HelperError } from "./wasm-loader.js";
|
|
10
|
+
const RUNTIME_FLAGS = [
|
|
11
|
+
"-S",
|
|
12
|
+
"cli=y",
|
|
13
|
+
"-S",
|
|
14
|
+
"tcp=y",
|
|
15
|
+
"-S",
|
|
16
|
+
"allow-ip-name-lookup=y",
|
|
17
|
+
"-S",
|
|
18
|
+
"inherit-network=y",
|
|
19
|
+
];
|
|
20
|
+
const defaultSpawn = (command, args, options) => spawn(command, args, options);
|
|
21
|
+
/** Build the runtime argv. Exported so tests assert flags without spawning. */
|
|
22
|
+
export function argsFor(mode, options) {
|
|
23
|
+
const flags = [...RUNTIME_FLAGS];
|
|
24
|
+
if (mode === "connect" && options.tls)
|
|
25
|
+
flags.push("-S", "tls=y");
|
|
26
|
+
const args = ["run", ...flags, options.componentPath, mode, options.address];
|
|
27
|
+
if (mode === "connect" && options.message !== undefined)
|
|
28
|
+
args.push(options.message);
|
|
29
|
+
return args;
|
|
30
|
+
}
|
|
31
|
+
async function canExecute(path) {
|
|
32
|
+
try {
|
|
33
|
+
await access(path, process.platform === "win32" ? constants.F_OK : constants.X_OK);
|
|
34
|
+
return true;
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/** Resolve a runtime name against PATH, or accept an explicit path. */
|
|
41
|
+
export async function resolveRuntime(runtime) {
|
|
42
|
+
if (runtime.includes("/") || runtime.includes("\\")) {
|
|
43
|
+
return (await canExecute(runtime)) ? runtime : null;
|
|
44
|
+
}
|
|
45
|
+
const path = process.env["PATH"] ?? "";
|
|
46
|
+
const exts = process.platform === "win32"
|
|
47
|
+
? (process.env["PATHEXT"] ?? ".EXE;.CMD;.BAT;.COM").split(";")
|
|
48
|
+
: [""];
|
|
49
|
+
for (const dir of path.split(delimiter)) {
|
|
50
|
+
if (dir.length === 0)
|
|
51
|
+
continue;
|
|
52
|
+
for (const ext of exts) {
|
|
53
|
+
const candidate = join(dir, runtime + ext);
|
|
54
|
+
if (await canExecute(candidate))
|
|
55
|
+
return candidate;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
function failed(message, cause) {
|
|
61
|
+
return new HelperError("E_WASI_SOCKET_FAILED", message, { cause });
|
|
62
|
+
}
|
|
63
|
+
export class WasiSocketPort {
|
|
64
|
+
componentPath;
|
|
65
|
+
runtime;
|
|
66
|
+
env;
|
|
67
|
+
spawnImpl;
|
|
68
|
+
constructor(options) {
|
|
69
|
+
this.componentPath = options.componentPath;
|
|
70
|
+
this.runtime = options.runtime ?? "wasmtime";
|
|
71
|
+
this.env = { ...process.env, ...(options.env ?? {}) };
|
|
72
|
+
this.spawnImpl = options.spawnImpl ?? defaultSpawn;
|
|
73
|
+
}
|
|
74
|
+
/** True when both the runtime and the component file are usable. */
|
|
75
|
+
async available() {
|
|
76
|
+
try {
|
|
77
|
+
await access(this.componentPath, constants.R_OK);
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
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}'`);
|
|
87
|
+
}
|
|
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`);
|
|
91
|
+
}
|
|
92
|
+
return resolved;
|
|
93
|
+
}
|
|
94
|
+
/** Open a connection, optionally send one message, and collect the reply. */
|
|
95
|
+
async connect(options) {
|
|
96
|
+
const runtimePath = await this.runtimePath();
|
|
97
|
+
const timeoutMs = options.timeoutMs ?? 30000;
|
|
98
|
+
const args = argsFor("connect", {
|
|
99
|
+
componentPath: this.componentPath,
|
|
100
|
+
address: options.address,
|
|
101
|
+
message: options.message,
|
|
102
|
+
tls: options.tls === true,
|
|
103
|
+
});
|
|
104
|
+
let child;
|
|
105
|
+
try {
|
|
106
|
+
child = this.spawnImpl(runtimePath, args, {
|
|
107
|
+
env: this.env,
|
|
108
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
109
|
+
windowsHide: true,
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
catch (error) {
|
|
113
|
+
throw failed(`could not spawn '${runtimePath}'`, error);
|
|
114
|
+
}
|
|
115
|
+
return new Promise((resolve, reject) => {
|
|
116
|
+
let stdout = "";
|
|
117
|
+
let stderr = "";
|
|
118
|
+
let settled = false;
|
|
119
|
+
const timer = setTimeout(() => {
|
|
120
|
+
if (settled)
|
|
121
|
+
return;
|
|
122
|
+
settled = true;
|
|
123
|
+
child.kill("SIGKILL");
|
|
124
|
+
reject(new HelperError("E_WASI_SOCKET_TIMEOUT", `connect timed out after ${timeoutMs}ms`));
|
|
125
|
+
}, timeoutMs);
|
|
126
|
+
child.stdout?.setEncoding("utf8");
|
|
127
|
+
child.stderr?.setEncoding("utf8");
|
|
128
|
+
child.stdout?.on("data", (chunk) => {
|
|
129
|
+
stdout += String(chunk);
|
|
130
|
+
});
|
|
131
|
+
child.stderr?.on("data", (chunk) => {
|
|
132
|
+
stderr += String(chunk);
|
|
133
|
+
});
|
|
134
|
+
child.on("error", (error) => {
|
|
135
|
+
if (settled)
|
|
136
|
+
return;
|
|
137
|
+
settled = true;
|
|
138
|
+
clearTimeout(timer);
|
|
139
|
+
reject(failed(`could not run '${runtimePath}'`, error));
|
|
140
|
+
});
|
|
141
|
+
child.on("close", (code) => {
|
|
142
|
+
if (settled)
|
|
143
|
+
return;
|
|
144
|
+
settled = true;
|
|
145
|
+
clearTimeout(timer);
|
|
146
|
+
resolve({ connected: code === 0, reply: stdout, stderr });
|
|
147
|
+
});
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Start a listening child and stream stdout lines.
|
|
152
|
+
*
|
|
153
|
+
* The component owns framing; this adapter only splits on newlines. `close`
|
|
154
|
+
* sends SIGTERM and returns immediately.
|
|
155
|
+
*/
|
|
156
|
+
async listen(options) {
|
|
157
|
+
const runtimePath = await this.runtimePath();
|
|
158
|
+
const args = argsFor("listen", {
|
|
159
|
+
componentPath: this.componentPath,
|
|
160
|
+
address: options.address,
|
|
161
|
+
});
|
|
162
|
+
let child;
|
|
163
|
+
try {
|
|
164
|
+
child = this.spawnImpl(runtimePath, args, {
|
|
165
|
+
env: this.env,
|
|
166
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
167
|
+
windowsHide: true,
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
catch (error) {
|
|
171
|
+
throw failed(`could not spawn '${runtimePath}'`, error);
|
|
172
|
+
}
|
|
173
|
+
let buffer = "";
|
|
174
|
+
const emit = (line) => {
|
|
175
|
+
try {
|
|
176
|
+
options.onLine(line);
|
|
177
|
+
}
|
|
178
|
+
catch {
|
|
179
|
+
// A consumer's callback must not take down the child's stream.
|
|
180
|
+
}
|
|
181
|
+
};
|
|
182
|
+
child.stdout?.setEncoding("utf8");
|
|
183
|
+
child.stdout?.on("data", (chunk) => {
|
|
184
|
+
buffer += String(chunk);
|
|
185
|
+
for (;;) {
|
|
186
|
+
const at = buffer.indexOf("\n");
|
|
187
|
+
if (at === -1)
|
|
188
|
+
break;
|
|
189
|
+
const line = buffer.slice(0, at).replace(/\r$/, "");
|
|
190
|
+
buffer = buffer.slice(at + 1);
|
|
191
|
+
emit(line);
|
|
192
|
+
}
|
|
193
|
+
});
|
|
194
|
+
child.on("error", (error) => {
|
|
195
|
+
emit(`error: ${error.message}`);
|
|
196
|
+
});
|
|
197
|
+
child.on("close", () => {
|
|
198
|
+
if (buffer.length > 0) {
|
|
199
|
+
emit(buffer.replace(/\r$/, ""));
|
|
200
|
+
buffer = "";
|
|
201
|
+
}
|
|
202
|
+
});
|
|
203
|
+
return {
|
|
204
|
+
close() {
|
|
205
|
+
try {
|
|
206
|
+
child.kill("SIGTERM");
|
|
207
|
+
}
|
|
208
|
+
catch {
|
|
209
|
+
// Already gone.
|
|
210
|
+
}
|
|
211
|
+
},
|
|
212
|
+
child,
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
export function createWasiSocketPort(options) {
|
|
217
|
+
return new WasiSocketPort(options);
|
|
218
|
+
}
|