@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
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// Loopback host: a static UI server with cross-origin isolation plus a
|
|
3
|
+
// WebSocket relay on a second loopback port. No product endpoints live here;
|
|
4
|
+
// callers supply onHttp / onWsUpgrade / onWsMessage.
|
|
5
|
+
import { spawn } from "node:child_process";
|
|
6
|
+
import { createServer } from "node:http";
|
|
7
|
+
import { readFile, stat } from "node:fs/promises";
|
|
8
|
+
import { extname, join, posix, resolve } from "node:path";
|
|
9
|
+
import { WebSocket, WebSocketServer } from "ws";
|
|
10
|
+
const DEFAULT_MAX_FRAME_BYTES = 1024 * 1024;
|
|
11
|
+
/** Slack above maxFrameBytes so an oversized frame reaches our handler first. */
|
|
12
|
+
const FRAME_SLACK_BYTES = 64 * 1024;
|
|
13
|
+
const MEDIA_TYPES = {
|
|
14
|
+
".html": "text/html; charset=utf-8",
|
|
15
|
+
".js": "text/javascript; charset=utf-8",
|
|
16
|
+
".mjs": "text/javascript; charset=utf-8",
|
|
17
|
+
".css": "text/css; charset=utf-8",
|
|
18
|
+
".wasm": "application/wasm",
|
|
19
|
+
".svg": "image/svg+xml",
|
|
20
|
+
".png": "image/png",
|
|
21
|
+
".woff2": "font/woff2",
|
|
22
|
+
".json": "application/json; charset=utf-8",
|
|
23
|
+
".map": "application/json; charset=utf-8",
|
|
24
|
+
};
|
|
25
|
+
function isRecord(value) {
|
|
26
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
27
|
+
}
|
|
28
|
+
function listen(server, port, host) {
|
|
29
|
+
return new Promise((resolvePort, reject) => {
|
|
30
|
+
const onError = (error) => reject(error);
|
|
31
|
+
server.once("error", onError);
|
|
32
|
+
server.listen(port, host, () => {
|
|
33
|
+
server.off("error", onError);
|
|
34
|
+
const address = server.address();
|
|
35
|
+
if (typeof address === "object" && address !== null)
|
|
36
|
+
resolvePort(address.port);
|
|
37
|
+
else
|
|
38
|
+
reject(new Error("server did not bind a TCP port"));
|
|
39
|
+
});
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
function closeServer(server) {
|
|
43
|
+
if (!server || !server.listening)
|
|
44
|
+
return Promise.resolve();
|
|
45
|
+
return new Promise((done) => server.close(() => done()));
|
|
46
|
+
}
|
|
47
|
+
function rejectUpgrade(socket, status, reason) {
|
|
48
|
+
const body = `${reason}\n`;
|
|
49
|
+
const label = status === 400
|
|
50
|
+
? "Bad Request"
|
|
51
|
+
: status === 401
|
|
52
|
+
? "Unauthorized"
|
|
53
|
+
: status === 403
|
|
54
|
+
? "Forbidden"
|
|
55
|
+
: status === 404
|
|
56
|
+
? "Not Found"
|
|
57
|
+
: "Internal Server Error";
|
|
58
|
+
socket.write(`HTTP/1.1 ${status} ${label}\r\n` +
|
|
59
|
+
"Content-Type: text/plain; charset=utf-8\r\n" +
|
|
60
|
+
`Content-Length: ${Buffer.byteLength(body)}\r\n` +
|
|
61
|
+
"Connection: close\r\n\r\n" +
|
|
62
|
+
body);
|
|
63
|
+
socket.destroy();
|
|
64
|
+
}
|
|
65
|
+
function openBrowser(url) {
|
|
66
|
+
const platform = process.platform;
|
|
67
|
+
const command = platform === "darwin" ? "open" : platform === "win32" ? "cmd" : "xdg-open";
|
|
68
|
+
const args = platform === "win32" ? ["/c", "start", "", url] : [url];
|
|
69
|
+
try {
|
|
70
|
+
const child = spawn(command, args, { detached: true, stdio: "ignore" });
|
|
71
|
+
child.on("error", () => {
|
|
72
|
+
// Opening a browser is a courtesy; failing to is not fatal.
|
|
73
|
+
});
|
|
74
|
+
child.unref();
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
// Same: never fail startup because a desktop opener is absent.
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
function frameBytes(raw) {
|
|
81
|
+
if (Array.isArray(raw))
|
|
82
|
+
return raw.reduce((total, part) => total + part.length, 0);
|
|
83
|
+
return raw.byteLength;
|
|
84
|
+
}
|
|
85
|
+
function bufferOf(raw) {
|
|
86
|
+
if (Buffer.isBuffer(raw))
|
|
87
|
+
return raw;
|
|
88
|
+
if (Array.isArray(raw))
|
|
89
|
+
return Buffer.concat(raw);
|
|
90
|
+
return Buffer.from(raw);
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Start the UI and relay servers. Resolves only after both are listening.
|
|
94
|
+
*
|
|
95
|
+
* Binding is loopback by default. If `host` is overridden to a non-loopback
|
|
96
|
+
* address, the caller must add authentication and firewall policy; this helper
|
|
97
|
+
* has none.
|
|
98
|
+
*/
|
|
99
|
+
export async function createLoopbackHost(options) {
|
|
100
|
+
const host = options.host ?? "127.0.0.1";
|
|
101
|
+
const uiDir = resolve(options.uiDir);
|
|
102
|
+
const requestedUiPort = options.port ?? options.defaultUiPort ?? 8788;
|
|
103
|
+
const requestedRelayPort = options.relayPort ?? options.defaultRelayPort ?? 8787;
|
|
104
|
+
const maxFrameBytes = options.maxFrameBytes ?? DEFAULT_MAX_FRAME_BYTES;
|
|
105
|
+
const log = options.log ?? ((message) => console.warn(message));
|
|
106
|
+
let uiDirOk = true;
|
|
107
|
+
try {
|
|
108
|
+
uiDirOk = (await stat(uiDir)).isDirectory();
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
uiDirOk = false;
|
|
112
|
+
}
|
|
113
|
+
if (!uiDirOk) {
|
|
114
|
+
log(`${options.appName}: UI directory not found at ${uiDir}; starting the relay anyway`);
|
|
115
|
+
}
|
|
116
|
+
const uiServer = createServer(async (req, res) => {
|
|
117
|
+
try {
|
|
118
|
+
const url = new URL(req.url ?? "/", `http://${host}`);
|
|
119
|
+
let pathname;
|
|
120
|
+
try {
|
|
121
|
+
pathname = decodeURIComponent(url.pathname);
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
res.writeHead(400, { "content-type": "text/plain; charset=utf-8" });
|
|
125
|
+
res.end("bad path");
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
if (options.onHttp) {
|
|
129
|
+
try {
|
|
130
|
+
if ((await options.onHttp(req, res)) === true)
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
catch (error) {
|
|
134
|
+
log(`${options.appName}: onHttp failed: ${String(error)}`);
|
|
135
|
+
if (!res.headersSent) {
|
|
136
|
+
res.writeHead(500, { "content-type": "text/plain; charset=utf-8" });
|
|
137
|
+
res.end("internal error");
|
|
138
|
+
}
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
143
|
+
res.writeHead(405, { "content-type": "text/plain; charset=utf-8", allow: "GET, HEAD" });
|
|
144
|
+
res.end("method not allowed");
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
// Reject a raw `..` segment before normalize: normalize("/../x") is
|
|
148
|
+
// "/x", which would silently accept a traversal attempt.
|
|
149
|
+
if (pathname.includes("\0") ||
|
|
150
|
+
pathname.includes("\\") ||
|
|
151
|
+
pathname.split("/").includes("..")) {
|
|
152
|
+
res.writeHead(400, { "content-type": "text/plain; charset=utf-8" });
|
|
153
|
+
res.end("bad path");
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
const normalized = posix.normalize(pathname);
|
|
157
|
+
const relative = normalized === "/" ? "index.html" : normalized.replace(/^\/+/, "");
|
|
158
|
+
const file = resolve(join(uiDir, relative));
|
|
159
|
+
if (file !== uiDir && !file.startsWith(`${uiDir}/`)) {
|
|
160
|
+
res.writeHead(400, { "content-type": "text/plain; charset=utf-8" });
|
|
161
|
+
res.end("bad path");
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
let body;
|
|
165
|
+
try {
|
|
166
|
+
body = await readFile(file);
|
|
167
|
+
}
|
|
168
|
+
catch {
|
|
169
|
+
res.writeHead(404, { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" });
|
|
170
|
+
res.end("not found");
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
res.writeHead(200, {
|
|
174
|
+
"content-type": MEDIA_TYPES[extname(file).toLowerCase()] ?? "application/octet-stream",
|
|
175
|
+
// Cross-origin isolation: required for OPFS sync handles and SAB.
|
|
176
|
+
"cross-origin-opener-policy": "same-origin",
|
|
177
|
+
"cross-origin-embedder-policy": "require-corp",
|
|
178
|
+
"cache-control": "no-store",
|
|
179
|
+
});
|
|
180
|
+
if (req.method === "HEAD")
|
|
181
|
+
res.end();
|
|
182
|
+
else
|
|
183
|
+
res.end(body);
|
|
184
|
+
}
|
|
185
|
+
catch (error) {
|
|
186
|
+
log(`${options.appName}: request failed: ${String(error)}`);
|
|
187
|
+
if (!res.headersSent) {
|
|
188
|
+
res.writeHead(500, { "content-type": "text/plain; charset=utf-8" });
|
|
189
|
+
res.end("internal error");
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
});
|
|
193
|
+
const uiPort = await listen(uiServer, requestedUiPort, host);
|
|
194
|
+
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
|
+
});
|
|
208
|
+
let relayPort;
|
|
209
|
+
try {
|
|
210
|
+
relayPort = await listen(relayServer, requestedRelayPort, host);
|
|
211
|
+
}
|
|
212
|
+
catch (error) {
|
|
213
|
+
await closeServer(uiServer);
|
|
214
|
+
throw error;
|
|
215
|
+
}
|
|
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) => {
|
|
220
|
+
void (async () => {
|
|
221
|
+
let decision;
|
|
222
|
+
try {
|
|
223
|
+
decision = options.onWsUpgrade ? await options.onWsUpgrade(req) : undefined;
|
|
224
|
+
}
|
|
225
|
+
catch (error) {
|
|
226
|
+
log(`${options.appName}: onWsUpgrade failed: ${String(error)}`);
|
|
227
|
+
rejectUpgrade(socket, 500, "upgrade handler failed");
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
if (decision === false || (isRecord(decision) && decision["reject"] === true)) {
|
|
231
|
+
const status = isRecord(decision) && typeof decision["status"] === "number" ? decision["status"] : 403;
|
|
232
|
+
const reason = isRecord(decision) && typeof decision["reason"] === "string" ? decision["reason"] : "upgrade rejected";
|
|
233
|
+
rejectUpgrade(socket, status, reason);
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
const context = isRecord(decision) && "context" in decision ? decision["context"] : undefined;
|
|
237
|
+
wss.handleUpgrade(req, socket, head, (ws) => {
|
|
238
|
+
contexts.set(ws, context);
|
|
239
|
+
wss.emit("connection", ws, req);
|
|
240
|
+
});
|
|
241
|
+
})();
|
|
242
|
+
});
|
|
243
|
+
wss.on("connection", (ws, req) => {
|
|
244
|
+
const context = contexts.get(ws);
|
|
245
|
+
ws.on("message", (raw, isBinary) => {
|
|
246
|
+
const bytes = frameBytes(raw);
|
|
247
|
+
if (bytes > maxFrameBytes) {
|
|
248
|
+
ws.send(JSON.stringify({ error: `frame exceeds ${maxFrameBytes} bytes` }));
|
|
249
|
+
ws.close(1009, "frame too large");
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
const buffer = bufferOf(raw);
|
|
253
|
+
let data = buffer;
|
|
254
|
+
if (!isBinary) {
|
|
255
|
+
const text = buffer.toString("utf8");
|
|
256
|
+
try {
|
|
257
|
+
data = JSON.parse(text);
|
|
258
|
+
}
|
|
259
|
+
catch {
|
|
260
|
+
data = text;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
const send = (payload) => {
|
|
264
|
+
if (ws.readyState !== WebSocket.OPEN)
|
|
265
|
+
return;
|
|
266
|
+
if (Buffer.isBuffer(payload) || payload instanceof Uint8Array) {
|
|
267
|
+
ws.send(payload, { binary: true });
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
if (payload instanceof ArrayBuffer) {
|
|
271
|
+
ws.send(Buffer.from(payload), { binary: true });
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
if (typeof payload === "string") {
|
|
275
|
+
ws.send(payload);
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
ws.send(JSON.stringify(payload));
|
|
279
|
+
};
|
|
280
|
+
void Promise.resolve(options.onWsMessage?.({ data, isBinary, context, req, send })).catch((error) => {
|
|
281
|
+
log(`${options.appName}: onWsMessage failed: ${String(error)}`);
|
|
282
|
+
send({ error: String(error instanceof Error ? error.message : error) });
|
|
283
|
+
});
|
|
284
|
+
});
|
|
285
|
+
});
|
|
286
|
+
if (!options.noOpen && options.openBrowser !== false) {
|
|
287
|
+
openBrowser(uiUrl);
|
|
288
|
+
}
|
|
289
|
+
let closed = false;
|
|
290
|
+
return {
|
|
291
|
+
uiPort,
|
|
292
|
+
relayPort,
|
|
293
|
+
uiUrl,
|
|
294
|
+
relayUrl,
|
|
295
|
+
async close() {
|
|
296
|
+
if (closed)
|
|
297
|
+
return;
|
|
298
|
+
closed = true;
|
|
299
|
+
for (const client of wss.clients)
|
|
300
|
+
client.terminate();
|
|
301
|
+
await new Promise((done) => wss.close(() => done()));
|
|
302
|
+
await Promise.all([closeServer(uiServer), closeServer(relayServer)]);
|
|
303
|
+
},
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
/** Exported for tests and for callers that want the same media-type table. */
|
|
307
|
+
export const LOOPBACK_MEDIA_TYPES = MEDIA_TYPES;
|
|
308
|
+
/** Exported for tests: the directory a resolved UI path must stay under. */
|
|
309
|
+
export function resolveUiFile(uiDir, pathname) {
|
|
310
|
+
if (pathname.includes("\0") ||
|
|
311
|
+
pathname.includes("\\") ||
|
|
312
|
+
pathname.split("/").includes("..")) {
|
|
313
|
+
return null;
|
|
314
|
+
}
|
|
315
|
+
const normalized = posix.normalize(pathname);
|
|
316
|
+
const base = resolve(uiDir);
|
|
317
|
+
const relative = normalized === "/" ? "index.html" : normalized.replace(/^\/+/, "");
|
|
318
|
+
const file = resolve(join(base, relative));
|
|
319
|
+
return file === base || file.startsWith(`${base}/`) ? file : null;
|
|
320
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
export interface PackageAsset {
|
|
2
|
+
name: string;
|
|
3
|
+
path: string;
|
|
4
|
+
}
|
|
5
|
+
export interface PackageOptions {
|
|
6
|
+
/** Application name; also the cache directory name. */
|
|
7
|
+
app: string;
|
|
8
|
+
/** Entry file bundled to CJS. */
|
|
9
|
+
entry: string;
|
|
10
|
+
/** UI directory served at runtime. Must contain index.html. */
|
|
11
|
+
uiDir: string;
|
|
12
|
+
/** WASM core embedded as `core/core.wasm`. */
|
|
13
|
+
core: string;
|
|
14
|
+
/** Output executable path. */
|
|
15
|
+
out: string;
|
|
16
|
+
/** Extra embedded assets, `name=path` or objects. */
|
|
17
|
+
assets?: PackageAsset[] | Record<string, string>;
|
|
18
|
+
/** Arguments used when the binary starts with no CLI arguments. */
|
|
19
|
+
noArgsArgs?: string | string[];
|
|
20
|
+
envCore?: string;
|
|
21
|
+
envBuild?: string;
|
|
22
|
+
envUi?: string;
|
|
23
|
+
/** Environment variable that carries the original argv for update relaunch. */
|
|
24
|
+
envLaunch?: string;
|
|
25
|
+
log?: (message: string) => void;
|
|
26
|
+
}
|
|
27
|
+
export interface PackagePlan {
|
|
28
|
+
app: string;
|
|
29
|
+
entry: string;
|
|
30
|
+
uiDir: string;
|
|
31
|
+
core: string;
|
|
32
|
+
out: string;
|
|
33
|
+
uiFiles: string[];
|
|
34
|
+
extraAssets: PackageAsset[];
|
|
35
|
+
assetNames: string[];
|
|
36
|
+
envCore: string;
|
|
37
|
+
envBuild: string;
|
|
38
|
+
envUi: string;
|
|
39
|
+
envLaunch: string;
|
|
40
|
+
noArgsArgs: string[] | null;
|
|
41
|
+
buildDate: string;
|
|
42
|
+
}
|
|
43
|
+
export interface PackageResult {
|
|
44
|
+
ok: true;
|
|
45
|
+
out: string;
|
|
46
|
+
size: number;
|
|
47
|
+
stamp: string;
|
|
48
|
+
uiFiles: number;
|
|
49
|
+
assets: number;
|
|
50
|
+
}
|
|
51
|
+
/** Validate inputs and compute the deterministic asset plan. */
|
|
52
|
+
export declare function resolvePackagePlan(options: PackageOptions): PackagePlan;
|
|
53
|
+
/** Whitespace split with single/double quote support (no shell expansion). */
|
|
54
|
+
export declare function splitArgs(input: string): string[];
|
|
55
|
+
/** Same algorithm the launcher prelude runs: names + bytes, then entry hash. */
|
|
56
|
+
export declare function computeStamp(plan: PackagePlan, contents: Map<string, Buffer>, entryHash: string): string;
|
|
57
|
+
/** Package one executable. Exported for tests; the CLI is a thin wrapper. */
|
|
58
|
+
export declare function packageApp(options: PackageOptions): Promise<PackageResult>;
|
|
59
|
+
/** Parse CLI flags into PackageOptions, optionally seeded by --config JSON. */
|
|
60
|
+
export declare function parsePackageCli(argv: string[]): PackageOptions;
|
|
61
|
+
/** CLI entry point. Returns an exit code; never calls process.exit. */
|
|
62
|
+
export declare function runSurePackCli(argv?: string[]): Promise<number>;
|
|
63
|
+
/** Exported for the packaged binary's own `--version` diagnostics. */
|
|
64
|
+
export declare const packagerVersion = "0.1.0";
|
|
65
|
+
/** Exported for callers that need the default executable suffix. */
|
|
66
|
+
export declare function defaultExecutableName(app: string, platform?: NodeJS.Platform): string;
|