-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwasm-cli-worker.js
More file actions
677 lines (651 loc) · 27.7 KB
/
Copy pathwasm-cli-worker.js
File metadata and controls
677 lines (651 loc) · 27.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
"use strict";
let stdinControl = null;
let importedFsSnapshot = null;
let stdinData = null;
let debugEnabled = false;
let ttyBrokerUrl = "";
let ttySessionId = "";
function debug(message) {
if (debugEnabled) self.postMessage({ type: "debug", message });
}
function patchLauncherSource(source) {
return String(source)
.replace(/^#!.*(?:\r?\n|$)/, "")
.replace(/^import\s+([A-Za-z_$][\w$]*)\s+from\s+["']([^"']+)["'];\s*/gm, 'const $1 = "$2";\n')
.replace(/^export\s+\{[^}]*\};\s*/gm, "")
.replace(/^export\s+const\s+/gm, "const ")
.replace(/^export\s+function\s+/gm, "function ")
.replace(/\bvar wasmBinary;/, 'var wasmBinary=Module["wasmBinary"];')
.replace(
/var FS_stdin_getChar=\(\)=>\{[\s\S]*?\};var TTY=/,
`var FS_stdin_getChar=()=>{if(!FS_stdin_getChar_buffer.length){var result=null;if(globalThis.__edgetermWorkerReadLine){try{var tty=typeof TTY!="undefined"&&TTY.ttys&&TTY.ttys[1];if(tty&&tty.output&&tty.output.length){out(UTF8ArrayToString(tty.output));tty.output=[]}}catch{}result=globalThis.__edgetermWorkerReadLine();if(result!==null&&result!==undefined){result+="\\n"}}else if(ENVIRONMENT_IS_NODE){var BUFSIZE=256;var buf=Buffer.alloc(BUFSIZE);var bytesRead=0;var fd=process.stdin.fd;try{bytesRead=fs.readSync(fd,buf,0,BUFSIZE)}catch(e){if(e.toString().includes("EOF"))bytesRead=0;else throw e}if(bytesRead>0){result=buf.slice(0,bytesRead).toString("utf-8")}}else{}if(result===null||result===undefined){return null}FS_stdin_getChar_buffer=intArrayFromString(result,true)}return FS_stdin_getChar_buffer.shift()};var TTY=`
)
.replace(
/if\(!result\)\{return null\}/g,
'if(!result&&globalThis.__edgetermWorkerReadLine){result=globalThis.__edgetermWorkerReadLine();if(result!==null){result+="\\n"}}if(!result){return null}'
)
.replace(
/if\(result===null\|\|result===undefined\)break;bytesRead\+\+;buffer\[offset\+i\]=result\}/g,
"if(result===null||result===undefined)break;bytesRead++;buffer[offset+i]=result;if(result===10)break}"
)
.replace(
/ws\.once\(event,listener\)\}\);const cancel=\(\)=>\{ws\.removeListener\(event,listener\);setTimeout\(resolve\)\}/g,
`if(typeof ws.once==="function"){ws.once(event,listener)}else if(typeof ws.addEventListener==="function"){ws.addEventListener(event,listener,{once:true})}else{ws["on"+event]=listener}});const cancel=()=>{if(typeof ws.removeListener==="function"){ws.removeListener(event,listener)}else if(typeof ws.removeEventListener==="function"){ws.removeEventListener(event,listener)}else if(typeof ws.off==="function"){ws.off(event,listener)}else if(ws["on"+event]===listener){ws["on"+event]=null}setTimeout(resolve)}`
)
.replaceAll(
"ws.once(event, listener);",
'if (typeof ws.once === "function") ws.once(event, listener); else if (typeof ws.addEventListener === "function") ws.addEventListener(event, listener, { once: true }); else ws["on" + event] = listener;'
)
.replaceAll(
"ws.removeListener(event, listener);",
'if (typeof ws.removeListener === "function") ws.removeListener(event, listener); else if (typeof ws.removeEventListener === "function") ws.removeEventListener(event, listener); else if (typeof ws.off === "function") ws.off(event, listener); else if (ws["on" + event] === listener) ws["on" + event] = null;'
);
}
function createWasmRuntimeModuleFactory(source) {
const ttyHook = `
if (Module["__edgetermStdinChar"] && Module["__edgetermStdoutChar"] && Module["__edgetermStderrChar"]) {
const __edgetermPreRun = () => {
try {
if (typeof FS !== "undefined" && typeof FS.init === "function") {
FS.init(Module["__edgetermStdinChar"], Module["__edgetermStdoutChar"], Module["__edgetermStderrChar"]);
}
} catch {}
};
if (typeof Module["preRun"] === "function") {
Module["preRun"] = [Module["preRun"]];
} else if (!Array.isArray(Module["preRun"])) {
Module["preRun"] = [];
}
Module["preRun"].push(__edgetermPreRun);
}
`;
const normalizedSource = patchLauncherSource(source)
.replace(/var Module\s*=\s*typeof Module\s*!=\s*['"]undefined['"]\s*\?\s*Module\s*:\s*\{\s*\}\s*;/, (m) => `${m}${ttyHook}`)
.replace(/var Module=typeof Module!=['"]undefined['"]\?Module:\{\};/, (m) => `${m}${ttyHook}`)
.replace(/var Module=typeof PHPLoader!=['"]undefined['"]\?PHPLoader:\{\};/, (m) => `${m}${ttyHook}`);
if (/function init\s*\(\s*RuntimeName\s*,\s*PHPLoader\s*\)/.test(normalizedSource)) {
const patchedSource = normalizedSource.replace(
/Module\["onRuntimeInitialized"\]\?\.\(\);/,
'Module["FS"]=FS;Module["callMain"]=callMain;Module["run"]=run;Module["onRuntimeInitialized"]?.();'
);
return async (moduleArg = {}) => {
const phpRunner = new Function(
"moduleArg",
"globalThis",
`${patchedSource}
return new Promise((resolve, reject) => {
const originalAbort = moduleArg["onAbort"];
moduleArg["noExitRuntime"] = true;
moduleArg["noInitialRun"] = true;
moduleArg["onAbort"] = (what) => {
try {
if (typeof originalAbort === "function") originalAbort(what);
} catch {}
reject(new Error(String(what || "aborted")));
};
moduleArg["onRuntimeInitialized"] = () => resolve(moduleArg);
try {
const runtimeName = typeof WorkerGlobalScope !== "undefined" && globalThis instanceof WorkerGlobalScope ? "WORKER" : "WEB";
init(runtimeName, moduleArg);
} catch (err) {
reject(err);
}
});`
);
const phpModule = await phpRunner(moduleArg, globalThis);
phpModule.__edgetermRunCli = async (args = []) => {
const extensionArgs = [];
const extensions = { ...(moduleArg.extensions || {}) };
try {
if (!extensions.intl && phpModule.FS?.analyzePath?.("/packages/php/intl.so")?.exists) {
extensions.intl = "/packages/php/intl.so";
}
} catch {}
for (const extensionPath of Object.values(extensions)) {
if (extensionPath) extensionArgs.push("-d", `extension=${extensionPath}`);
}
const cliArgs = [phpModule.thisProgram || moduleArg.thisProgram || "php", ...extensionArgs, ...args];
for (const arg of cliArgs) phpModule.ccall("wasm_add_cli_arg", "number", ["string"], [String(arg)]);
try {
const result = phpModule.ccall("run_cli", "number", [], [], { async: true });
return Number((result && typeof result.then === "function" ? await result : result) || 0);
} catch (err) {
if (
err?.name === "ExitStatus" ||
err?.constructor?.name === "ExitStatus" ||
typeof err?.status === "number" ||
typeof err?.code === "number"
) {
return Number(err.status ?? err.code ?? 0);
}
throw err;
}
};
phpModule.__edgetermRunSapiRequest = async (request = {}) => {
if (!phpModule.__edgetermWebSapiInitialized) {
try {
phpModule.ccall("wasm_set_sapi_name", "number", ["string"], ["apache"]);
} catch {}
const initResult = phpModule.ccall("php_wasm_init", "number", [], [], { async: true });
if (initResult && typeof initResult.then === "function") await initResult;
phpModule.__edgetermWebSapiInitialized = true;
}
const callString = (name, value) => phpModule.ccall(name, "number", ["string"], [String(value ?? "")]);
const callNumber = (name, value) => phpModule.ccall(name, "number", ["number"], [Number(value || 0)]);
const addServer = (name, value) => phpModule.ccall("wasm_add_SERVER_entry", "number", ["string", "string"], [String(name), String(value ?? "")]);
const unlinkIfExists = (path) => {
try {
if (phpModule.FS?.analyzePath?.(path)?.exists) phpModule.FS.unlink(path);
} catch {}
};
const collectText = (chunks) => {
const length = chunks.reduce((total, chunk) => total + chunk.length, 0);
const bytes = new Uint8Array(length);
let offset = 0;
for (const chunk of chunks) {
bytes.set(chunk, offset);
offset += chunk.length;
}
return new TextDecoder().decode(bytes);
};
const stdoutChunks = [];
const stderrChunks = [];
const headerChunks = [];
const previousStdout = phpModule.onStdout;
const previousStderr = phpModule.onStderr;
const previousHeaders = phpModule.onHeaders;
phpModule.onStdout = (chunk) => stdoutChunks.push(new Uint8Array(chunk || []));
phpModule.onStderr = (chunk) => stderrChunks.push(new Uint8Array(chunk || []));
phpModule.onHeaders = (chunk) => headerChunks.push(new Uint8Array(chunk || []));
let bodyPtr = 0;
try {
unlinkIfExists("/internal/stdout");
unlinkIfExists("/internal/stderr");
unlinkIfExists("/internal/headers.json");
callString("wasm_set_path_translated", request.scriptFilename || "");
callString("wasm_set_request_uri", request.requestUri || "/");
callString("wasm_set_request_method", request.method || "GET");
callString("wasm_set_request_host", request.serverName || "edgeterm.local");
callString("wasm_set_query_string", request.query || "");
callString("wasm_set_content_type", request.contentType || "");
const bodyBytes = request.bodyBase64
? Uint8Array.from(atob(String(request.bodyBase64 || "")), (char) => char.charCodeAt(0))
: new TextEncoder().encode(String(request.body || ""));
if (bodyBytes.length) {
const malloc = phpModule.malloc || phpModule._malloc;
bodyPtr = malloc(bodyBytes.length || 1);
phpModule.HEAPU8.set(bodyBytes, bodyPtr);
callNumber("wasm_set_request_body", bodyPtr);
}
callNumber("wasm_set_content_length", bodyBytes.length);
callString("wasm_set_cookies", request.cookie || "");
callNumber("wasm_set_request_port", Number(request.serverPort || 443));
addServer("DOCUMENT_ROOT", request.documentRoot || "");
addServer("SCRIPT_FILENAME", request.scriptFilename || "");
addServer("SCRIPT_NAME", request.scriptName || "");
addServer("PHP_SELF", request.scriptName || "");
addServer("PATH_INFO", request.pathInfo || "");
addServer("PATH_TRANSLATED", request.pathInfo ? `${request.documentRoot || ""}${request.pathInfo}` : "");
addServer("REQUEST_URI", request.requestUri || "/");
addServer("REQUEST_METHOD", request.method || "GET");
addServer("QUERY_STRING", request.query || "");
addServer("SERVER_NAME", request.serverName || "edgeterm.local");
addServer("SERVER_PORT", request.serverPort || "443");
addServer("SERVER_PROTOCOL", "HTTP/1.1");
addServer("HTTPS", "on");
addServer("REMOTE_ADDR", "127.0.0.1");
for (const [name, value] of Object.entries(request.headers || {})) {
const lower = String(name).toLowerCase();
const key = ["content-type", "content-length"].includes(lower) ? lower.toUpperCase().replace(/-/g, "_") : "HTTP_" + String(name).toUpperCase().replace(/-/g, "_");
addServer(key, value);
}
let code = 0;
try {
const result = phpModule.ccall("wasm_sapi_handle_request", "number", [], [], { async: true });
code = Number((result && typeof result.then === "function" ? await result : result) || 0);
} catch (requestError) {
const message = String(requestError?.message || requestError || "");
const exitedNormally = requestError === "unwind"
|| requestError?.name === "ExitStatus"
|| requestError?.constructor?.name === "ExitStatus"
|| /null function/i.test(message);
if (!exitedNormally) throw requestError;
code = Number(requestError?.status ?? requestError?.code ?? 0);
}
try {
const shutdownResult = phpModule.ccall("wasm_sapi_request_shutdown", "number", [], [], { async: true });
if (shutdownResult && typeof shutdownResult.then === "function") await shutdownResult;
} catch {}
const headersJson = phpModule.FS?.analyzePath?.("/internal/headers.json")?.exists
? new TextDecoder().decode(phpModule.FS.readFile("/internal/headers.json"))
: "";
const stdoutFile = phpModule.FS?.analyzePath?.("/internal/stdout")?.exists
? new TextDecoder().decode(phpModule.FS.readFile("/internal/stdout"))
: "";
const stderrFile = phpModule.FS?.analyzePath?.("/internal/stderr")?.exists
? new TextDecoder().decode(phpModule.FS.readFile("/internal/stderr"))
: "";
return {
code,
stdout: stdoutFile || collectText(stdoutChunks),
stderr: stderrFile || collectText(stderrChunks),
headers: collectText(headerChunks),
headersJson,
};
} finally {
phpModule.onStdout = previousStdout;
phpModule.onStderr = previousStderr;
phpModule.onHeaders = previousHeaders;
if (bodyPtr) {
try {
(phpModule.free || phpModule._wasm_free || phpModule._free)?.(bodyPtr);
} catch {}
}
}
};
return phpModule;
};
}
if (/var wasmExports;/.test(normalizedSource) && /createWasm\s*\(\s*\)\s*;/.test(normalizedSource) && /run\s*\(\s*\)\s*;/.test(normalizedSource)) {
const patchedSource = normalizedSource
.replace(/var Module\s*=\s*typeof Module\s*!=\s*['"]undefined['"]\s*\?\s*Module\s*:\s*\{\s*\}\s*;/, "var Module = moduleArg || {};")
.replace(/var Module=typeof Module!=['"]undefined['"]\?Module:\{\};/, "var Module = moduleArg || {};")
.replace(
/var wasmExports;[\s\S]*$/,
`var wasmExports;
Module["noExitRuntime"] = true;
Module["noInitialRun"] = true;
return (async () => {
return await new Promise((resolve, reject) => {
const originalAbort = Module["onAbort"];
Module["onAbort"] = (what) => {
try {
if (typeof originalAbort === "function") originalAbort(what);
} catch {}
reject(new Error(String(what || "aborted")));
};
Module["onRuntimeInitialized"] = () => {
Module["FS"] = FS;
Module["callMain"] = callMain;
Module["run"] = run;
resolve(Module);
};
try {
createWasm();
run();
} catch (err) {
reject(err);
}
});
})();`
);
return async (moduleArg = {}) => {
const nonModularRunner = new Function("moduleArg", "globalThis", patchedSource);
return await nonModularRunner(moduleArg, globalThis);
};
}
const module = { exports: {} };
const exports = module.exports;
const runner = new Function(
"module",
"exports",
"globalThis",
`${normalizedSource}\n; return module.exports || exports.default || exports || globalThis.Module || globalThis.createModule || null;`
);
const result = runner(module, exports, globalThis);
if (typeof result === "function") return result;
if (result && typeof result.default === "function") return result.default;
if (result && typeof result.createModule === "function") return result.createModule;
if (typeof globalThis.createModule === "function") return globalThis.createModule;
if (typeof globalThis.Module === "function") return globalThis.Module;
return null;
}
function ensureModuleParentDirs(moduleFs, path) {
const parts = path.split("/").filter(Boolean);
let current = "";
for (let i = 0; i < parts.length - 1; i += 1) {
current += `/${parts[i]}`;
try {
moduleFs.mkdir(current);
} catch {}
}
}
function exportedFsDelta(moduleFs, syncRoots, snapshot) {
const result = [];
const seen = new Set();
const normalizedRoots = syncRoots.map((root) => String(root || "/").replace(/\/+$/, "") || "/");
for (const root of syncRoots) {
deltaWalk(moduleFs, root, snapshot, result, seen);
}
if (snapshot) {
for (const path of snapshot.keys()) {
const synchronized = normalizedRoots.some(
(root) => root === "/" || path === root || path.startsWith(`${root}/`),
);
if (synchronized && !seen.has(path)) {
result.push({ path, dir: false, deleted: true });
}
}
}
return result;
}
function deltaWalk(moduleFs, sourcePath, snapshot, out, seen) {
let stat;
try { stat = moduleFs.stat(sourcePath); } catch { return; }
if (moduleFs.isDir(stat.mode)) {
out.push({ path: sourcePath, dir: true });
seen.add(sourcePath);
try {
for (const name of moduleFs.readdir(sourcePath)) {
if (name === "." || name === "..") continue;
deltaWalk(moduleFs, sourcePath + "/" + name, snapshot, out, seen);
}
} catch {}
return;
}
seen.add(sourcePath);
const oldData = snapshot ? snapshot.get(sourcePath) : undefined;
if (oldData === undefined) {
out.push({ path: sourcePath, dir: false, data: moduleFs.readFile(sourcePath) });
return;
}
const newData = moduleFs.readFile(sourcePath);
if (newData.length !== oldData.length) {
out.push({ path: sourcePath, dir: false, data: newData });
return;
}
for (let j = 0; j < newData.length; j++) {
if (newData[j] !== oldData[j]) {
out.push({ path: sourcePath, dir: false, data: newData });
return;
}
}
}
function importFsEntries(moduleFs, entries) {
for (const entry of entries) {
if (entry.deleted) {
try {
moduleFs.unlink(entry.path);
} catch {}
continue;
}
if (entry.dir) {
try {
moduleFs.mkdir(entry.path);
} catch {}
continue;
}
ensureModuleParentDirs(moduleFs, entry.path);
moduleFs.writeFile(entry.path, new Uint8Array(entry.data));
}
}
function exportFsTree(moduleFs, sourcePath, out) {
let stat;
try {
stat = moduleFs.stat(sourcePath);
} catch {
return;
}
if (moduleFs.isDir(stat.mode)) {
out.push({ path: sourcePath, dir: true });
for (const name of moduleFs.readdir(sourcePath)) {
if (name === "." || name === "..") continue;
exportFsTree(moduleFs, `${sourcePath}/${name}`, out);
}
return;
}
out.push({ path: sourcePath, dir: false, data: moduleFs.readFile(sourcePath) });
}
function wasmRuntimeFriendlyError(err, command) {
let text = `${err?.message || err || "Unknown error"}`;
if (text === "[object Object]") {
try {
text = JSON.stringify(err);
} catch {}
}
if (/socket|network/i.test(text)) return `${command}: this package needs raw networking, which EdgeTerm does not provide in the browser`;
if (/fork|spawn|exec/i.test(text)) return `${command}: this package needs process control that EdgeTerm cannot emulate`;
if (/shared library|dynamic library|dylib|dlopen/i.test(text)) return `${command}: this package needs native dynamic libraries, which are not supported here`;
return `${command}: ${text}`;
}
function readInteractiveLine(display) {
self.postMessage({ type: "stdin_request", display });
if (ttyBrokerUrl && ttySessionId) {
const xhr = new XMLHttpRequest();
xhr.open("GET", `${ttyBrokerUrl}/__edgeterm_tty_read?id=${encodeURIComponent(ttySessionId)}`, false);
xhr.send();
if (xhr.status >= 200 && xhr.status < 300) {
try {
const payload = JSON.parse(xhr.responseText || "{}");
return payload.line === null || payload.line === undefined ? null : String(payload.line);
} catch {
return xhr.responseText || "";
}
}
throw new Error(`TTY broker read failed with HTTP ${xhr.status}`);
}
Atomics.store(stdinControl, 0, 0);
Atomics.wait(stdinControl, 0, 0);
const len = Atomics.load(stdinControl, 1);
if (len < 0) return null;
const bytes = new Uint8Array(stdinData, 0, len);
return new TextDecoder().decode(bytes);
}
self.onmessage = async (event) => {
let data;
try {
data = event.data || {};
if (data.type !== "run") return;
debugEnabled = Boolean(data.debug);
const command = data.command || "wasm";
debug(`${command}: worker start`);
let stdinBuffer = data.stdinText || "";
let interactiveRequested = false;
let pendingDisplay = "";
const stdout = [];
const stderr = [];
let streamOutput = data.streamOutput === true && String(data?.env?.EDGETERM_PHP_STREAM || "") !== "0";
let streamedOutput = false;
let stdinQueue = [];
const streamBuffers = { stdout: "", stderr: "" };
let streamFlushTimer = null;
const flushStream = (stream = "") => {
const names = stream ? [stream] : ["stdout", "stderr"];
for (const name of names) {
const text = streamBuffers[name];
if (!text) continue;
streamBuffers[name] = "";
self.postMessage({ type: "stream", stream: name, text });
}
if (!streamBuffers.stdout && !streamBuffers.stderr && streamFlushTimer !== null) {
clearTimeout(streamFlushTimer);
streamFlushTimer = null;
}
};
const queueStream = (stream, chunk) => {
streamBuffers[stream] += chunk;
if (chunk === "\n" || streamBuffers[stream].length >= 256) {
flushStream(stream);
return;
}
if (streamFlushTimer === null) {
streamFlushTimer = setTimeout(() => flushStream(), 16);
}
};
ttyBrokerUrl = data.ttyBrokerUrl || "";
ttySessionId = data.ttySessionId || "";
try {
if (data.stdinControl && data.stdinData) {
stdinControl = new Int32Array(data.stdinControl);
stdinData = data.stdinData;
} else if (!ttyBrokerUrl || !ttySessionId) {
throw new Error("missing shared memory and TTY broker");
}
} catch (err) {
self.postMessage({
type: "error",
code: 1,
stdout: "",
stderr: `${command}: shared memory bridge unavailable — page may not be cross-origin isolated. Reload from the EdgeTerm server (serve-edgeterm.bat).\n`,
});
return;
}
globalThis.__edgetermWorkerReadLine = () => {
if (stdinBuffer) {
const chunk = stdinBuffer;
stdinBuffer = "";
return chunk;
}
interactiveRequested = true;
const line = readInteractiveLine(pendingDisplay);
pendingDisplay = "";
return line;
};
const stdinInput = () => {
if (stdinQueue.length) return stdinQueue.shift();
const line = globalThis.__edgetermWorkerReadLine();
if (line === null || line === undefined) return null;
const encoded = Array.from(new TextEncoder().encode(`${line}\n`));
stdinQueue = encoded;
return stdinQueue.length ? stdinQueue.shift() : null;
};
const stdoutOutput = (code) => {
if (code === null || code === undefined) return;
const chunk = String.fromCharCode(code);
stdout.push(chunk);
pendingDisplay += chunk;
if (streamOutput) {
streamedOutput = true;
queueStream("stdout", chunk);
}
};
const stderrOutput = (code) => {
if (code === null || code === undefined) return;
const chunk = String.fromCharCode(code);
stderr.push(chunk);
pendingDisplay += chunk;
if (streamOutput) {
streamedOutput = true;
queueStream("stderr", chunk);
}
};
const factory = createWasmRuntimeModuleFactory(data.launcherSource);
if (!factory) throw new Error("package launcher did not expose an Emscripten module factory");
debug(`${command}: factory ready`);
const moduleInstance = await factory({
noInitialRun: true,
arguments: [...(data.args || [])],
thisProgram: data.thisProgram,
extensions: data.extensions || {},
ENV: { ...(data.env || {}), PWD: data.cwd || "/" },
wasmBinary: new Uint8Array(data.wasmBytes),
locateFile: (path) => `${data.packageRoot}/${path}`,
__edgetermStdinChar: stdinInput,
__edgetermStdoutChar: stdoutOutput,
__edgetermStderrChar: stderrOutput,
onStdout: (chunk) => {
for (const code of chunk || []) stdoutOutput(code);
},
onStderr: (chunk) => {
for (const code of chunk || []) stderrOutput(code);
},
print: (text) => {
const chunk = String(text);
stdout.push(chunk);
pendingDisplay += chunk;
},
printErr: (text) => {
const chunk = String(text);
stderr.push(chunk);
pendingDisplay += chunk;
},
});
if (!moduleInstance?.FS) throw new Error("package runtime did not expose FS after initialization");
debug(`${command}: runtime initialized`);
importFsEntries(moduleInstance.FS, data.fsEntries || []);
importedFsSnapshot = new Map();
for (const entry of (data.fsEntries || [])) {
if (entry.deleted && entry.path) {
importedFsSnapshot.delete(entry.path);
} else if (!entry.dir && entry.path) {
importedFsSnapshot.set(entry.path, entry.data);
}
}
try {
ensureModuleParentDirs(moduleInstance.FS, (data.cwd || "/").endsWith("/") ? `${data.cwd}._` : `${data.cwd}/._`);
moduleInstance.FS.chdir(data.cwd || "/");
} catch {
moduleInstance.FS.chdir("/");
}
let code = 0;
try {
debug(`${command}: callMain`);
if (data.phpRequest && typeof moduleInstance.__edgetermRunSapiRequest === "function") {
try {
const response = await moduleInstance.__edgetermRunSapiRequest(data.phpRequest || {});
stdout.length = 0;
stderr.length = 0;
stdout.push(JSON.stringify(response));
code = Number(response.code || 0);
} catch (sapiErr) {
stdout.length = 0;
stderr.length = 0;
stderr.push(`SAPI request failed, falling back to CLI: ${sapiErr?.message || sapiErr}\n`);
code = await moduleInstance.__edgetermRunCli([...(data.args || [])]);
data.phpRequest = null;
}
} else if (typeof moduleInstance.__edgetermRunCli === "function") code = await moduleInstance.__edgetermRunCli([...(data.args || [])]);
else if (typeof moduleInstance.callMain === "function") moduleInstance.callMain([...(data.args || [])]);
else if (typeof moduleInstance.main === "function") code = Number(moduleInstance.main([...(data.args || [])]) || 0);
else throw new Error("package did not expose callMain() or main()");
debug(`${command}: main returned`);
} catch (err) {
if (err === "unwind") {
code = 0;
} else if (
err?.name === "ExitStatus" ||
err?.constructor?.name === "ExitStatus" ||
typeof err?.status === "number" ||
typeof err?.code === "number"
) {
code = Number(err.status ?? err.code ?? 0);
} else {
throw err;
}
}
const fsEntries = data.skipFsExport ? [] : exportedFsDelta(moduleInstance.FS, data.syncRoots || [], importedFsSnapshot);
for (const entry of fsEntries) {
if (!entry?.path) continue;
if (entry.deleted) importedFsSnapshot?.delete(entry.path);
else if (!entry.dir) importedFsSnapshot?.set(entry.path, entry.data);
}
if (interactiveRequested && !stdinBuffer && code === 0) {
code = 1;
stderr.push(
`${command}: interactive terminal input still needs the worker stdin bridge to stay active for the full program lifecycle.\n`
);
}
flushStream();
self.postMessage({
type: "done",
code,
stdout: streamedOutput ? "" : stdout.join(""),
stderr: streamedOutput ? "" : stderr.join(""),
fsEntries,
tailDisplay: streamedOutput ? "" : pendingDisplay,
streamed: interactiveRequested || streamedOutput,
sapi: !!data.phpRequest,
});
} catch (err) {
if (typeof flushStream === "function") flushStream();
self.postMessage({
type: "error",
code: 1,
stdout: "",
tailDisplay: "",
stderr: `${wasmRuntimeFriendlyError(err, data?.command || "wasm")}\n`,
});
} finally {
delete globalThis.__edgetermWorkerReadLine;
}
};