@seanhogg/builderforce-webcontainers-core 2026.10.7 → 2026.10.9
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/dist/archive.d.ts +2 -0
- package/dist/archive.d.ts.map +1 -1
- package/dist/archive.js +6 -4
- package/dist/archive.js.map +1 -1
- package/dist/build.d.ts +6 -0
- package/dist/build.d.ts.map +1 -1
- package/dist/build.js +9 -1
- package/dist/build.js.map +1 -1
- package/dist/buildHost.d.ts +3 -0
- package/dist/buildHost.d.ts.map +1 -1
- package/dist/buildHost.js +25 -12
- package/dist/buildHost.js.map +1 -1
- package/dist/compileComponent.d.ts.map +1 -1
- package/dist/compileComponent.js +4 -1
- package/dist/compileComponent.js.map +1 -1
- package/dist/compileScript.d.ts +12 -4
- package/dist/compileScript.d.ts.map +1 -1
- package/dist/compileScript.js +26 -13
- package/dist/compileScript.js.map +1 -1
- package/dist/components.d.ts +5 -0
- package/dist/components.d.ts.map +1 -1
- package/dist/components.js.map +1 -1
- package/dist/detectProject.d.ts +2 -0
- package/dist/detectProject.d.ts.map +1 -1
- package/dist/detectProject.js +13 -7
- package/dist/detectProject.js.map +1 -1
- package/dist/devServer.d.ts +38 -4
- package/dist/devServer.d.ts.map +1 -1
- package/dist/devServer.js +140 -24
- package/dist/devServer.js.map +1 -1
- package/dist/devStyles.d.ts +27 -0
- package/dist/devStyles.d.ts.map +1 -0
- package/dist/devStyles.js +52 -0
- package/dist/devStyles.js.map +1 -0
- package/dist/hot/client.d.ts +33 -0
- package/dist/hot/client.d.ts.map +1 -0
- package/dist/hot/client.js +46 -0
- package/dist/hot/client.js.map +1 -0
- package/dist/hot/moduleGraph.d.ts +39 -0
- package/dist/hot/moduleGraph.d.ts.map +1 -0
- package/dist/hot/moduleGraph.js +69 -0
- package/dist/hot/moduleGraph.js.map +1 -0
- package/dist/hot/planUpdate.d.ts +33 -0
- package/dist/hot/planUpdate.d.ts.map +1 -0
- package/dist/hot/planUpdate.js +43 -0
- package/dist/hot/planUpdate.js.map +1 -0
- package/dist/hot/reactRefresh.d.ts +45 -0
- package/dist/hot/reactRefresh.d.ts.map +1 -0
- package/dist/hot/reactRefresh.js +86 -0
- package/dist/hot/reactRefresh.js.map +1 -0
- package/dist/html.d.ts +4 -8
- package/dist/html.d.ts.map +1 -1
- package/dist/html.js +15 -19
- package/dist/html.js.map +1 -1
- package/dist/index.d.ts +20 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +12 -1
- package/dist/index.js.map +1 -1
- package/dist/installer/tree.d.ts.map +1 -1
- package/dist/installer/tree.js +22 -4
- package/dist/installer/tree.js.map +1 -1
- package/dist/installer/wasmBuilds.d.ts +27 -0
- package/dist/installer/wasmBuilds.d.ts.map +1 -0
- package/dist/installer/wasmBuilds.js +32 -0
- package/dist/installer/wasmBuilds.js.map +1 -0
- package/dist/node/builtins.d.ts +6 -1
- package/dist/node/builtins.d.ts.map +1 -1
- package/dist/node/builtins.js +15 -10
- package/dist/node/builtins.js.map +1 -1
- package/dist/node/childProcess.d.ts +3 -3
- package/dist/node/childProcess.d.ts.map +1 -1
- package/dist/node/childProcess.js +68 -16
- package/dist/node/childProcess.js.map +1 -1
- package/dist/node/crypto.d.ts.map +1 -1
- package/dist/node/crypto.js +5 -4
- package/dist/node/crypto.js.map +1 -1
- package/dist/node/esm.d.ts +7 -0
- package/dist/node/esm.d.ts.map +1 -1
- package/dist/node/esm.js +28 -2
- package/dist/node/esm.js.map +1 -1
- package/dist/node/fs/index.d.ts +3 -0
- package/dist/node/fs/index.d.ts.map +1 -1
- package/dist/node/fs/index.js +22 -106
- package/dist/node/fs/index.js.map +1 -1
- package/dist/node/fs/stdinFd.d.ts +10 -0
- package/dist/node/fs/stdinFd.d.ts.map +1 -0
- package/dist/node/fs/stdinFd.js +40 -0
- package/dist/node/fs/stdinFd.js.map +1 -0
- package/dist/node/fs/streams.d.ts +24 -0
- package/dist/node/fs/streams.d.ts.map +1 -0
- package/dist/node/fs/streams.js +144 -0
- package/dist/node/fs/streams.js.map +1 -0
- package/dist/node/fs/sync.d.ts +2 -0
- package/dist/node/fs/sync.d.ts.map +1 -1
- package/dist/node/fs/sync.js +17 -0
- package/dist/node/fs/sync.js.map +1 -1
- package/dist/node/globalObject.d.ts +25 -0
- package/dist/node/globalObject.d.ts.map +1 -0
- package/dist/node/globalObject.js +83 -0
- package/dist/node/globalObject.js.map +1 -0
- package/dist/node/http/client.d.ts +3 -1
- package/dist/node/http/client.d.ts.map +1 -1
- package/dist/node/http/client.js +74 -5
- package/dist/node/http/client.js.map +1 -1
- package/dist/node/http/index.d.ts.map +1 -1
- package/dist/node/http/index.js +6 -4
- package/dist/node/http/index.js.map +1 -1
- package/dist/node/http/messages.d.ts +87 -0
- package/dist/node/http/messages.d.ts.map +1 -0
- package/dist/node/http/messages.js +146 -0
- package/dist/node/http/messages.js.map +1 -0
- package/dist/node/http/server.d.ts +13 -98
- package/dist/node/http/server.d.ts.map +1 -1
- package/dist/node/http/server.js +41 -206
- package/dist/node/http/server.js.map +1 -1
- package/dist/node/http/serverResponse.d.ts +45 -0
- package/dist/node/http/serverResponse.d.ts.map +1 -0
- package/dist/node/http/serverResponse.js +96 -0
- package/dist/node/http/serverResponse.js.map +1 -0
- package/dist/node/http/upgradeSocket.d.ts +34 -0
- package/dist/node/http/upgradeSocket.d.ts.map +1 -0
- package/dist/node/http/upgradeSocket.js +73 -0
- package/dist/node/http/upgradeSocket.js.map +1 -0
- package/dist/node/ipc.d.ts +26 -0
- package/dist/node/ipc.d.ts.map +1 -0
- package/dist/node/ipc.js +76 -0
- package/dist/node/ipc.js.map +1 -0
- package/dist/node/loader.d.ts +2 -0
- package/dist/node/loader.d.ts.map +1 -1
- package/dist/node/loader.js +79 -14
- package/dist/node/loader.js.map +1 -1
- package/dist/node/misc.d.ts.map +1 -1
- package/dist/node/misc.js +20 -5
- package/dist/node/misc.js.map +1 -1
- package/dist/node/process.d.ts +2 -5
- package/dist/node/process.d.ts.map +1 -1
- package/dist/node/process.js +16 -11
- package/dist/node/process.js.map +1 -1
- package/dist/node/processExit.d.ts +13 -0
- package/dist/node/processExit.d.ts.map +1 -0
- package/dist/node/processExit.js +25 -0
- package/dist/node/processExit.js.map +1 -0
- package/dist/node/program.d.ts.map +1 -1
- package/dist/node/program.js +6 -5
- package/dist/node/program.js.map +1 -1
- package/dist/node/runtime.d.ts +6 -1
- package/dist/node/runtime.d.ts.map +1 -1
- package/dist/node/runtime.js +25 -17
- package/dist/node/runtime.js.map +1 -1
- package/dist/node/stream/readable.d.ts +2 -1
- package/dist/node/stream/readable.d.ts.map +1 -1
- package/dist/node/stream/readable.js +2 -1
- package/dist/node/stream/readable.js.map +1 -1
- package/dist/node/urlqs.d.ts +1 -1
- package/dist/node/urlqs.d.ts.map +1 -1
- package/dist/node/urlqs.js +11 -2
- package/dist/node/urlqs.js.map +1 -1
- package/dist/node/workerThreads.d.ts +31 -0
- package/dist/node/workerThreads.d.ts.map +1 -0
- package/dist/node/workerThreads.js +165 -0
- package/dist/node/workerThreads.js.map +1 -0
- package/dist/node/zlib.d.ts.map +1 -1
- package/dist/node/zlib.js +23 -2
- package/dist/node/zlib.js.map +1 -1
- package/dist/previewBridge.d.ts +42 -0
- package/dist/previewBridge.d.ts.map +1 -0
- package/dist/previewBridge.js +192 -0
- package/dist/previewBridge.js.map +1 -0
- package/dist/shell/ast.d.ts +101 -0
- package/dist/shell/ast.d.ts.map +1 -0
- package/dist/shell/ast.js +7 -0
- package/dist/shell/ast.js.map +1 -0
- package/dist/shell/builtins.d.ts +14 -0
- package/dist/shell/builtins.d.ts.map +1 -1
- package/dist/shell/builtins.js +87 -7
- package/dist/shell/builtins.js.map +1 -1
- package/dist/shell/compound.d.ts +30 -0
- package/dist/shell/compound.d.ts.map +1 -0
- package/dist/shell/compound.js +73 -0
- package/dist/shell/compound.js.map +1 -0
- package/dist/shell/context.d.ts.map +1 -1
- package/dist/shell/context.js +2 -2
- package/dist/shell/context.js.map +1 -1
- package/dist/shell/devHandoff.d.ts +10 -4
- package/dist/shell/devHandoff.d.ts.map +1 -1
- package/dist/shell/devHandoff.js +7 -5
- package/dist/shell/devHandoff.js.map +1 -1
- package/dist/shell/exec.d.ts +27 -6
- package/dist/shell/exec.d.ts.map +1 -1
- package/dist/shell/exec.js +133 -46
- package/dist/shell/exec.js.map +1 -1
- package/dist/shell/expand.d.ts +5 -1
- package/dist/shell/expand.d.ts.map +1 -1
- package/dist/shell/expand.js +7 -5
- package/dist/shell/expand.js.map +1 -1
- package/dist/shell/lineReader.d.ts +9 -0
- package/dist/shell/lineReader.d.ts.map +1 -0
- package/dist/shell/lineReader.js +42 -0
- package/dist/shell/lineReader.js.map +1 -0
- package/dist/shell/npm.js +2 -2
- package/dist/shell/npm.js.map +1 -1
- package/dist/shell/packageManagers.d.ts +20 -0
- package/dist/shell/packageManagers.d.ts.map +1 -0
- package/dist/shell/packageManagers.js +74 -0
- package/dist/shell/packageManagers.js.map +1 -0
- package/dist/shell/parse.d.ts +16 -66
- package/dist/shell/parse.d.ts.map +1 -1
- package/dist/shell/parse.js +244 -243
- package/dist/shell/parse.js.map +1 -1
- package/dist/shell/program.d.ts.map +1 -1
- package/dist/shell/program.js +7 -6
- package/dist/shell/program.js.map +1 -1
- package/dist/shell/testCommand.d.ts +9 -0
- package/dist/shell/testCommand.d.ts.map +1 -0
- package/dist/shell/testCommand.js +105 -0
- package/dist/shell/testCommand.js.map +1 -0
- package/dist/shell/tokenize.d.ts +25 -0
- package/dist/shell/tokenize.d.ts.map +1 -0
- package/dist/shell/tokenize.js +279 -0
- package/dist/shell/tokenize.js.map +1 -0
- package/dist/styleModules.d.ts +2 -5
- package/dist/styleModules.d.ts.map +1 -1
- package/dist/styleModules.js +23 -14
- package/dist/styleModules.js.map +1 -1
- package/dist/styles/compile.d.ts +18 -0
- package/dist/styles/compile.d.ts.map +1 -0
- package/dist/styles/compile.js +34 -0
- package/dist/styles/compile.js.map +1 -0
- package/dist/styles/compilers.d.ts +75 -0
- package/dist/styles/compilers.d.ts.map +1 -0
- package/dist/styles/compilers.js +77 -0
- package/dist/styles/compilers.js.map +1 -0
- package/dist/styles/cssModules.d.ts +40 -0
- package/dist/styles/cssModules.d.ts.map +1 -0
- package/dist/styles/cssModules.js +239 -0
- package/dist/styles/cssModules.js.map +1 -0
- package/dist/styles/imports.d.ts +37 -0
- package/dist/styles/imports.d.ts.map +1 -0
- package/dist/styles/imports.js +88 -0
- package/dist/styles/imports.js.map +1 -0
- package/dist/styles/languages.d.ts +13 -0
- package/dist/styles/languages.d.ts.map +1 -0
- package/dist/styles/languages.js +20 -0
- package/dist/styles/languages.js.map +1 -0
- package/dist/styles/packageStyles.d.ts +19 -0
- package/dist/styles/packageStyles.d.ts.map +1 -0
- package/dist/styles/packageStyles.js +32 -0
- package/dist/styles/packageStyles.js.map +1 -0
- package/dist/svelteCompiler.d.ts.map +1 -1
- package/dist/svelteCompiler.js +19 -2
- package/dist/svelteCompiler.js.map +1 -1
- package/dist/system/commands.d.ts +2 -0
- package/dist/system/commands.d.ts.map +1 -1
- package/dist/system/commands.js +18 -0
- package/dist/system/commands.js.map +1 -1
- package/dist/system/cookieJar.d.ts +59 -0
- package/dist/system/cookieJar.d.ts.map +1 -0
- package/dist/system/cookieJar.js +187 -0
- package/dist/system/cookieJar.js.map +1 -0
- package/dist/system/httpStream.d.ts +40 -0
- package/dist/system/httpStream.d.ts.map +1 -0
- package/dist/system/httpStream.js +156 -0
- package/dist/system/httpStream.js.map +1 -0
- package/dist/system/index.d.ts +11 -1
- package/dist/system/index.d.ts.map +1 -1
- package/dist/system/index.js +5 -0
- package/dist/system/index.js.map +1 -1
- package/dist/system/ipc.d.ts +33 -0
- package/dist/system/ipc.d.ts.map +1 -0
- package/dist/system/ipc.js +65 -0
- package/dist/system/ipc.js.map +1 -0
- package/dist/system/kernel.d.ts +10 -2
- package/dist/system/kernel.d.ts.map +1 -1
- package/dist/system/kernel.js +18 -6
- package/dist/system/kernel.js.map +1 -1
- package/dist/system/ports.d.ts +9 -4
- package/dist/system/ports.d.ts.map +1 -1
- package/dist/system/ports.js +21 -2
- package/dist/system/ports.js.map +1 -1
- package/dist/system/process.d.ts +3 -0
- package/dist/system/process.d.ts.map +1 -1
- package/dist/system/process.js +50 -26
- package/dist/system/process.js.map +1 -1
- package/dist/system/programs.d.ts +1 -1
- package/dist/system/programs.d.ts.map +1 -1
- package/dist/system/programs.js +2 -0
- package/dist/system/programs.js.map +1 -1
- package/dist/system/terminal.d.ts +10 -4
- package/dist/system/terminal.d.ts.map +1 -1
- package/dist/system/terminal.js +21 -13
- package/dist/system/terminal.js.map +1 -1
- package/dist/system/types.d.ts +65 -13
- package/dist/system/types.d.ts.map +1 -1
- package/dist/system/webSocketClient.d.ts +37 -0
- package/dist/system/webSocketClient.d.ts.map +1 -0
- package/dist/system/webSocketClient.js +152 -0
- package/dist/system/webSocketClient.js.map +1 -0
- package/dist/system/webSocketFrames.d.ts +39 -0
- package/dist/system/webSocketFrames.d.ts.map +1 -0
- package/dist/system/webSocketFrames.js +117 -0
- package/dist/system/webSocketFrames.js.map +1 -0
- package/dist/vueCompiler.d.ts.map +1 -1
- package/dist/vueCompiler.js +11 -8
- package/dist/vueCompiler.js.map +1 -1
- package/package.json +4 -1
- package/src/archive.ts +8 -4
- package/src/build.ts +13 -1
- package/src/buildHost.ts +23 -10
- package/src/compileComponent.ts +4 -1
- package/src/compileScript.ts +30 -11
- package/src/components.ts +5 -0
- package/src/detectProject.ts +13 -6
- package/src/devServer.ts +148 -23
- package/src/devStyles.ts +70 -0
- package/src/hot/client.ts +70 -0
- package/src/hot/moduleGraph.ts +90 -0
- package/src/hot/planUpdate.ts +66 -0
- package/src/hot/reactRefresh.ts +93 -0
- package/src/html.ts +17 -21
- package/src/index.ts +20 -1
- package/src/installer/tree.ts +22 -4
- package/src/installer/wasmBuilds.ts +45 -0
- package/src/node/builtins.ts +21 -12
- package/src/node/childProcess.ts +73 -20
- package/src/node/crypto.ts +5 -4
- package/src/node/esm.ts +26 -2
- package/src/node/fs/index.ts +26 -103
- package/src/node/fs/stdinFd.ts +44 -0
- package/src/node/fs/streams.ts +177 -0
- package/src/node/fs/sync.ts +15 -0
- package/src/node/globalObject.ts +82 -0
- package/src/node/http/client.ts +69 -6
- package/src/node/http/index.ts +6 -4
- package/src/node/http/messages.ts +150 -0
- package/src/node/http/server.ts +44 -206
- package/src/node/http/serverResponse.ts +105 -0
- package/src/node/http/upgradeSocket.ts +79 -0
- package/src/node/ipc.ts +91 -0
- package/src/node/loader.ts +78 -14
- package/src/node/misc.ts +19 -5
- package/src/node/process.ts +15 -8
- package/src/node/processExit.ts +21 -0
- package/src/node/program.ts +12 -9
- package/src/node/runtime.ts +29 -17
- package/src/node/stream/readable.ts +2 -1
- package/src/node/urlqs.ts +10 -2
- package/src/node/workerThreads.ts +198 -0
- package/src/node/zlib.ts +24 -2
- package/src/previewBridge.ts +194 -0
- package/src/shell/ast.ts +85 -0
- package/src/shell/builtins.ts +97 -7
- package/src/shell/compound.ts +89 -0
- package/src/shell/context.ts +2 -2
- package/src/shell/devHandoff.ts +16 -9
- package/src/shell/exec.ts +134 -45
- package/src/shell/expand.ts +8 -6
- package/src/shell/lineReader.ts +46 -0
- package/src/shell/npm.ts +2 -2
- package/src/shell/packageManagers.ts +75 -0
- package/src/shell/parse.ts +233 -236
- package/src/shell/program.ts +7 -6
- package/src/shell/testCommand.ts +105 -0
- package/src/shell/tokenize.ts +257 -0
- package/src/styleModules.ts +30 -14
- package/src/styles/compile.ts +43 -0
- package/src/styles/compilers.ts +143 -0
- package/src/styles/cssModules.ts +254 -0
- package/src/styles/imports.ts +125 -0
- package/src/styles/languages.ts +29 -0
- package/src/styles/packageStyles.ts +35 -0
- package/src/svelteCompiler.ts +20 -3
- package/src/system/commands.ts +17 -0
- package/src/system/cookieJar.ts +187 -0
- package/src/system/httpStream.ts +168 -0
- package/src/system/index.ts +28 -1
- package/src/system/ipc.ts +89 -0
- package/src/system/kernel.ts +22 -7
- package/src/system/ports.ts +23 -4
- package/src/system/process.ts +57 -30
- package/src/system/programs.ts +3 -1
- package/src/system/terminal.ts +34 -12
- package/src/system/types.ts +71 -13
- package/src/system/webSocketClient.ts +177 -0
- package/src/system/webSocketFrames.ts +118 -0
- package/src/vueCompiler.ts +11 -8
package/src/system/process.ts
CHANGED
|
@@ -5,8 +5,9 @@
|
|
|
5
5
|
* program it hosts. Also {@link RuntimeProcess}, the stream-based handle the
|
|
6
6
|
* public `run()` returns.
|
|
7
7
|
*/
|
|
8
|
-
import type { ChildHandle, Program, ProgramIO, ProcessOptions, System } from './types.js';
|
|
9
|
-
import { InputQueue, LineDiscipline, toTerminal } from './terminal.js';
|
|
8
|
+
import type { ChildHandle, Program, ProgramIO, ProcessOptions, StdioChunk, System } from './types.js';
|
|
9
|
+
import { InputQueue, LineDiscipline, textChunks, toTerminal } from './terminal.js';
|
|
10
|
+
import type { IpcEndpoint } from './ipc.js';
|
|
10
11
|
|
|
11
12
|
let nextPid = 1000;
|
|
12
13
|
|
|
@@ -21,26 +22,21 @@ export interface RunProgramOptions extends ProcessOptions {
|
|
|
21
22
|
cwd: string;
|
|
22
23
|
env: Record<string, string>;
|
|
23
24
|
pid?: number;
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
/** Decode byte chunks without splitting multi-byte characters across writes. */
|
|
27
|
-
function textSink(emit: (text: string) => void): (chunk: string | Uint8Array) => void {
|
|
28
|
-
const decoder = new TextDecoder();
|
|
29
|
-
return (chunk) => {
|
|
30
|
-
const text = typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true });
|
|
31
|
-
if (text) emit(text);
|
|
32
|
-
};
|
|
25
|
+
/** The child's end of its message channel to the parent (`ipc`); closed when the program exits. */
|
|
26
|
+
channel?: IpcEndpoint;
|
|
33
27
|
}
|
|
34
28
|
|
|
35
29
|
export function runProgram(options: RunProgramOptions): ChildHandle {
|
|
36
30
|
const pid = options.pid ?? allocatePid();
|
|
37
|
-
const stdin = new InputQueue();
|
|
38
|
-
const stdoutListeners = new Set<(chunk:
|
|
39
|
-
const stderrListeners = new Set<(chunk:
|
|
31
|
+
const stdin = new InputQueue<StdioChunk>();
|
|
32
|
+
const stdoutListeners = new Set<(chunk: StdioChunk) => void>();
|
|
33
|
+
const stderrListeners = new Set<(chunk: StdioChunk) => void>();
|
|
40
34
|
const resizeListeners = new Set<(cols: number, rows: number) => void>();
|
|
41
35
|
const controller = new AbortController();
|
|
42
|
-
|
|
43
|
-
|
|
36
|
+
// A dead process prints nothing: a straggling callback that writes after exit is dropped.
|
|
37
|
+
// Chunks pass through as written: bytes stay bytes, so a binary protocol over a child's pipes survives.
|
|
38
|
+
const emitOut = (chunk: StdioChunk) => settled || stdoutListeners.forEach((l) => l(chunk));
|
|
39
|
+
const emitErr = (chunk: StdioChunk) => settled || stderrListeners.forEach((l) => l(chunk));
|
|
44
40
|
let settled = false;
|
|
45
41
|
let forceExit: (code: number) => void = () => undefined;
|
|
46
42
|
|
|
@@ -56,8 +52,8 @@ export function runProgram(options: RunProgramOptions): ChildHandle {
|
|
|
56
52
|
: undefined;
|
|
57
53
|
|
|
58
54
|
const io: ProgramIO = {
|
|
59
|
-
stdout:
|
|
60
|
-
stderr:
|
|
55
|
+
stdout: emitOut,
|
|
56
|
+
stderr: emitErr,
|
|
61
57
|
onStdin: (listener) => stdin.subscribe(listener),
|
|
62
58
|
terminal: size && discipline
|
|
63
59
|
? {
|
|
@@ -78,21 +74,47 @@ export function runProgram(options: RunProgramOptions): ChildHandle {
|
|
|
78
74
|
: undefined,
|
|
79
75
|
};
|
|
80
76
|
|
|
77
|
+
// Children die with their parent unless `detached`: an orphan here would hold its
|
|
78
|
+
// ports and timers with nothing left that can reach it to stop it.
|
|
79
|
+
const children = new Set<ChildHandle>();
|
|
80
|
+
const system: System = {
|
|
81
|
+
...options.system,
|
|
82
|
+
spawn(command, args, spawnOptions) {
|
|
83
|
+
const child = options.system.spawn(command, args, spawnOptions);
|
|
84
|
+
if (!spawnOptions?.detached) {
|
|
85
|
+
children.add(child);
|
|
86
|
+
void child.exit.then(() => children.delete(child));
|
|
87
|
+
}
|
|
88
|
+
return child;
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
const settle = (resolve: (code: number) => void, code: number) => {
|
|
92
|
+
options.channel?.disconnect();
|
|
93
|
+
settled = true;
|
|
94
|
+
for (const child of children) child.kill('SIGTERM');
|
|
95
|
+
resolve(code);
|
|
96
|
+
};
|
|
97
|
+
|
|
81
98
|
const exit = new Promise<number>((resolve) => {
|
|
82
|
-
forceExit = (code) =>
|
|
83
|
-
settled = true;
|
|
84
|
-
resolve(code);
|
|
85
|
-
};
|
|
99
|
+
forceExit = (code) => settle(resolve, code);
|
|
86
100
|
queueMicrotask(async () => {
|
|
87
101
|
let code: number;
|
|
88
102
|
try {
|
|
89
|
-
code = await options.program({
|
|
103
|
+
code = await options.program({
|
|
104
|
+
args: options.args,
|
|
105
|
+
cwd: options.cwd,
|
|
106
|
+
env: options.env,
|
|
107
|
+
io,
|
|
108
|
+
system,
|
|
109
|
+
signal: controller.signal,
|
|
110
|
+
ipc: options.channel,
|
|
111
|
+
thread: options.thread,
|
|
112
|
+
});
|
|
90
113
|
} catch (error) {
|
|
91
114
|
io.stderr(`${error instanceof Error ? error.stack ?? error.message : String(error)}\n`);
|
|
92
115
|
code = 1;
|
|
93
116
|
}
|
|
94
|
-
|
|
95
|
-
resolve(code);
|
|
117
|
+
settle(resolve, code);
|
|
96
118
|
});
|
|
97
119
|
});
|
|
98
120
|
|
|
@@ -107,7 +129,7 @@ export function runProgram(options: RunProgramOptions): ChildHandle {
|
|
|
107
129
|
return () => stderrListeners.delete(listener);
|
|
108
130
|
},
|
|
109
131
|
write(data) {
|
|
110
|
-
if (discipline) discipline.input(data);
|
|
132
|
+
if (discipline) discipline.input(typeof data === 'string' ? data : new TextDecoder().decode(data));
|
|
111
133
|
else stdin.push(data);
|
|
112
134
|
},
|
|
113
135
|
closeStdin: () => stdin.push(null),
|
|
@@ -145,10 +167,15 @@ export function runArguments(args: string[] | ProcessOptions = [], options: Proc
|
|
|
145
167
|
export function toRuntimeProcess(child: ChildHandle, terminal: boolean): RuntimeProcess {
|
|
146
168
|
const combinedOutput = new ReadableStream<string>({
|
|
147
169
|
start(controller) {
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
170
|
+
let open = true;
|
|
171
|
+
const push = (text: string | null) => text !== null && open && controller.enqueue(terminal ? toTerminal(text) : text);
|
|
172
|
+
// One decoder per stream, so a character split across writes on one is not garbled by the other.
|
|
173
|
+
child.onStdout(textChunks(push));
|
|
174
|
+
child.onStderr(textChunks(push));
|
|
175
|
+
void child.exit.then(() => {
|
|
176
|
+
open = false;
|
|
177
|
+
controller.close();
|
|
178
|
+
});
|
|
152
179
|
},
|
|
153
180
|
});
|
|
154
181
|
const stdin = new WritableStream<string>({
|
package/src/system/programs.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* The command table: every program a process can be. Hosts start from
|
|
3
3
|
* `defaultPrograms()` and may add or replace entries (a custom `git`, say).
|
|
4
4
|
*
|
|
5
|
-
* `npm`/`npx` live in the shell (they run scripts through it), so spawning them
|
|
5
|
+
* `npm`/`npx`/`pnpm`/`yarn` live in the shell (they run scripts through it), so spawning them
|
|
6
6
|
* directly runs them through a one-shot shell; coreutils run standalone.
|
|
7
7
|
*/
|
|
8
8
|
import type { Program } from './types.js';
|
|
@@ -25,6 +25,8 @@ export function defaultPrograms(): Record<string, Program> {
|
|
|
25
25
|
bash: shellProgram,
|
|
26
26
|
npm: viaShell('npm'),
|
|
27
27
|
npx: viaShell('npx'),
|
|
28
|
+
pnpm: viaShell('pnpm'),
|
|
29
|
+
yarn: viaShell('yarn'),
|
|
28
30
|
};
|
|
29
31
|
for (const [name, command] of Object.entries(COREUTILS)) programs[name] = asProgram(command, name);
|
|
30
32
|
return programs;
|
package/src/system/terminal.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* What a kernel's TTY layer does between xterm.js and a program:
|
|
3
3
|
*
|
|
4
|
-
* - InputQueue: stdin as a buffered stream of
|
|
4
|
+
* - InputQueue: stdin as a buffered stream of chunks — text, or bytes (data that arrives
|
|
5
5
|
* before the program subscribes is kept, not dropped).
|
|
6
6
|
* - LineDiscipline: "cooked" mode — echo, backspace, Ctrl-U, Enter delivers the
|
|
7
7
|
* line, Ctrl-C raises SIGINT, Ctrl-D is end-of-file. A program that calls
|
|
@@ -9,22 +9,24 @@
|
|
|
9
9
|
* - toTerminal: `\n` → `\r\n` on output (the TTY's ONLCR), since xterm.js
|
|
10
10
|
* only moves to column 0 on `\r`.
|
|
11
11
|
*/
|
|
12
|
+
import type { StdioChunk } from './types.js';
|
|
12
13
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
private readonly
|
|
14
|
+
|
|
15
|
+
export class InputQueue<T extends StdioChunk = string> {
|
|
16
|
+
private readonly buffered: Array<T | null> = [];
|
|
17
|
+
private readonly listeners = new Set<(chunk: T | null) => void>();
|
|
16
18
|
private ended = false;
|
|
17
19
|
|
|
18
20
|
private draining = false;
|
|
19
21
|
|
|
20
|
-
push(chunk:
|
|
22
|
+
push(chunk: T | null): void {
|
|
21
23
|
if (this.ended) return;
|
|
22
24
|
if (chunk === null) this.ended = true;
|
|
23
25
|
this.buffered.push(chunk);
|
|
24
26
|
this.drain();
|
|
25
27
|
}
|
|
26
28
|
|
|
27
|
-
subscribe(listener: (chunk:
|
|
29
|
+
subscribe(listener: (chunk: T | null) => void): () => void {
|
|
28
30
|
this.listeners.add(listener);
|
|
29
31
|
this.drain();
|
|
30
32
|
return () => this.listeners.delete(listener);
|
|
@@ -51,12 +53,14 @@ export class InputQueue {
|
|
|
51
53
|
readAll(): Promise<string> {
|
|
52
54
|
return new Promise((resolve) => {
|
|
53
55
|
let text = '';
|
|
54
|
-
const stop = this.subscribe(
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
56
|
+
const stop = this.subscribe(
|
|
57
|
+
textChunks((chunk) => {
|
|
58
|
+
if (chunk === null) {
|
|
59
|
+
stop();
|
|
60
|
+
resolve(text);
|
|
61
|
+
} else text += chunk;
|
|
62
|
+
}),
|
|
63
|
+
);
|
|
60
64
|
});
|
|
61
65
|
}
|
|
62
66
|
|
|
@@ -65,6 +69,24 @@ export class InputQueue {
|
|
|
65
69
|
}
|
|
66
70
|
}
|
|
67
71
|
|
|
72
|
+
/**
|
|
73
|
+
* A text listener over a bytes-or-text stream: bytes are decoded as UTF-8 with
|
|
74
|
+
* characters split across chunks kept whole; `null` (end) flushes, then passes on.
|
|
75
|
+
*/
|
|
76
|
+
export function textChunks(listener: (text: string | null) => void): (chunk: StdioChunk | null) => void {
|
|
77
|
+
const decoder = new TextDecoder();
|
|
78
|
+
return (chunk) => {
|
|
79
|
+
if (chunk === null) {
|
|
80
|
+
const rest = decoder.decode();
|
|
81
|
+
if (rest) listener(rest);
|
|
82
|
+
listener(null);
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
const text = typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true });
|
|
86
|
+
if (text) listener(text);
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
68
90
|
export function toTerminal(text: string): string {
|
|
69
91
|
return text.replace(/\r?\n/g, '\r\n');
|
|
70
92
|
}
|
package/src/system/types.ts
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import type { VirtualFileSystem } from '../vfs.js';
|
|
8
8
|
import type { PackageCache } from '../installer/registry.js';
|
|
9
|
+
import type { IpcEndpoint } from './ipc.js';
|
|
9
10
|
|
|
10
11
|
export interface TerminalPort {
|
|
11
12
|
cols: number;
|
|
@@ -15,11 +16,14 @@ export interface TerminalPort {
|
|
|
15
16
|
setRawMode(raw: boolean): void;
|
|
16
17
|
}
|
|
17
18
|
|
|
19
|
+
/** What flows through stdio: text, or bytes kept as bytes (binary protocols over a child's pipes). */
|
|
20
|
+
export type StdioChunk = string | Uint8Array;
|
|
21
|
+
|
|
18
22
|
export interface ProgramIO {
|
|
19
|
-
stdout(chunk:
|
|
20
|
-
stderr(chunk:
|
|
21
|
-
/** Stdin chunks as they arrive; `null` is end-of-file. Buffered until the first subscriber. */
|
|
22
|
-
onStdin(listener: (chunk:
|
|
23
|
+
stdout(chunk: StdioChunk): void;
|
|
24
|
+
stderr(chunk: StdioChunk): void;
|
|
25
|
+
/** Stdin chunks as they arrive, bytes or text as written; `null` is end-of-file. Buffered until the first subscriber. Text consumers wrap the listener in `textChunks`. */
|
|
26
|
+
onStdin(listener: (chunk: StdioChunk | null) => void): () => void;
|
|
23
27
|
/** Present when attached to a terminal (xterm.js). */
|
|
24
28
|
terminal?: TerminalPort;
|
|
25
29
|
}
|
|
@@ -29,18 +33,34 @@ export interface ProcessOptions {
|
|
|
29
33
|
env?: Record<string, string>;
|
|
30
34
|
/** Attach to a terminal of this size (`isTTY`, line discipline, `\r\n` output). */
|
|
31
35
|
terminal?: { cols: number; rows: number };
|
|
36
|
+
/** Open a message channel to the child (`child_process.fork`); the handle's `ipc` is the parent's end. */
|
|
37
|
+
ipc?: boolean;
|
|
38
|
+
/** Run as a `worker_threads` Worker: the child's `worker_threads` reports this, over the `ipc` channel. */
|
|
39
|
+
thread?: ThreadInfo;
|
|
40
|
+
/** Outlive the parent (`spawn(…, { detached: true })`). Otherwise a child still running when its parent exits is killed with it. */
|
|
41
|
+
detached?: boolean;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** What a process started as a worker thread sees in `worker_threads`. */
|
|
45
|
+
export interface ThreadInfo {
|
|
46
|
+
threadId: number;
|
|
47
|
+
/** Structured-cloned from the parent's `new Worker(file, { workerData })`. */
|
|
48
|
+
workerData: unknown;
|
|
32
49
|
}
|
|
33
50
|
|
|
34
51
|
/** A child as its parent sees it (separate stdout/stderr listeners, unlike the streams of the public `RuntimeProcess`). */
|
|
35
52
|
export interface ChildHandle {
|
|
36
53
|
readonly pid: number;
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
54
|
+
/** Output as the child wrote it: text, or bytes kept as bytes. */
|
|
55
|
+
onStdout(listener: (chunk: StdioChunk) => void): () => void;
|
|
56
|
+
onStderr(listener: (chunk: StdioChunk) => void): () => void;
|
|
57
|
+
write(data: StdioChunk): void;
|
|
40
58
|
closeStdin(): void;
|
|
41
59
|
kill(signal?: string): void;
|
|
42
60
|
resize?(cols: number, rows: number): void;
|
|
43
61
|
readonly exit: Promise<number>;
|
|
62
|
+
/** The parent's end of the message channel, when spawned with `ipc`. */
|
|
63
|
+
readonly ipc?: IpcEndpoint;
|
|
44
64
|
}
|
|
45
65
|
|
|
46
66
|
export interface HttpRequestData {
|
|
@@ -51,24 +71,58 @@ export interface HttpRequestData {
|
|
|
51
71
|
body: Uint8Array | null;
|
|
52
72
|
}
|
|
53
73
|
|
|
54
|
-
export interface
|
|
74
|
+
export interface HttpResponseHead {
|
|
55
75
|
status: number;
|
|
56
76
|
statusText?: string;
|
|
57
77
|
headers: Record<string, string | string[]>;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** A whole response, body buffered (`Kernel.request`, tests). */
|
|
81
|
+
export interface HttpResponseData extends HttpResponseHead {
|
|
58
82
|
body: Uint8Array;
|
|
59
83
|
}
|
|
60
84
|
|
|
61
|
-
|
|
85
|
+
/**
|
|
86
|
+
* A response as the server produces it: the head as soon as it is written, then
|
|
87
|
+
* the body chunk by chunk (Server-Sent Events, chunked progress). Cancelling the
|
|
88
|
+
* body hangs up, which the server sees as the client closing the connection.
|
|
89
|
+
*/
|
|
90
|
+
export interface HttpStreamResponse extends HttpResponseHead {
|
|
91
|
+
body: ReadableStream<Uint8Array>;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export type HttpHandler = (request: HttpRequestData) => Promise<HttpStreamResponse>;
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* One end of a raw byte pipe — an upgraded connection. The server end carries
|
|
98
|
+
* whatever the server writes (a WebSocket server writes its `101` reply and then
|
|
99
|
+
* frames), so packages like `ws` run their own framing over it unchanged.
|
|
100
|
+
*/
|
|
101
|
+
export interface ByteChannel {
|
|
102
|
+
send(data: Uint8Array): void;
|
|
103
|
+
/** Hang up; the other end hears `onClose`. */
|
|
104
|
+
close(): void;
|
|
105
|
+
onData(listener: (data: Uint8Array) => void): () => void;
|
|
106
|
+
/** The other end hung up. */
|
|
107
|
+
onClose(listener: () => void): () => void;
|
|
108
|
+
readonly closed: boolean;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Take over a connection a client asked to upgrade (`Upgrade: websocket`); `socket` is the server end. */
|
|
112
|
+
export type UpgradeHandler = (request: HttpRequestData, socket: ByteChannel) => void;
|
|
62
113
|
|
|
63
114
|
export interface System {
|
|
64
115
|
fs: VirtualFileSystem;
|
|
65
116
|
/** Outbound network (registry, `http.request`, `fetch`). */
|
|
66
117
|
fetch(input: string, init?: RequestInit): Promise<Response>;
|
|
67
118
|
spawn(command: string, args: string[], options?: ProcessOptions): ChildHandle;
|
|
68
|
-
/**
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
119
|
+
/**
|
|
120
|
+
* Register a virtual server; throws `EADDRINUSE`. Port 0 picks a free one.
|
|
121
|
+
* `upgrade` takes over connections that ask to upgrade (WebSockets). Returns the port and an unlisten.
|
|
122
|
+
*/
|
|
123
|
+
listen(port: number, handler: HttpHandler, upgrade?: UpgradeHandler): { port: number; close(): void };
|
|
124
|
+
/** Send a request to a virtual server in this runtime (`http.get('http://localhost:3000')`); undefined when nothing listens. The body streams. */
|
|
125
|
+
loopback(port: number, request: HttpRequestData): Promise<HttpStreamResponse | undefined>;
|
|
72
126
|
/** Where a browser reaches a server on `port` (the preview URL), if known. */
|
|
73
127
|
serverUrl(port: number): string | undefined;
|
|
74
128
|
/** Tell the host a server is reachable without opening a port; used by the dev-server handoff. */
|
|
@@ -97,6 +151,10 @@ export interface ProgramContext {
|
|
|
97
151
|
system: System;
|
|
98
152
|
/** Aborted by kill(): in-process programs stop at their next await. */
|
|
99
153
|
signal: AbortSignal;
|
|
154
|
+
/** The channel to the parent, when it spawned this process with `ipc` (`process.send`). */
|
|
155
|
+
ipc?: IpcEndpoint;
|
|
156
|
+
/** Set when this process is a worker thread. */
|
|
157
|
+
thread?: ThreadInfo;
|
|
100
158
|
}
|
|
101
159
|
|
|
102
160
|
/** A program resolves with its exit code. */
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The client end of a WebSocket to a virtual server, over an upgraded
|
|
3
|
+
* {@link ByteChannel}: sends the opening handshake as an HTTP request, checks
|
|
4
|
+
* the server's `101` reply (whatever wrote it — `ws`, socket.io's engine, a
|
|
5
|
+
* hand-written `upgrade` handler), then speaks RFC 6455 frames. The host page
|
|
6
|
+
* uses it to carry a preview's `new WebSocket('ws://localhost:3000')`.
|
|
7
|
+
*/
|
|
8
|
+
import type { ByteChannel, HttpRequestData } from './types.js';
|
|
9
|
+
import { FrameDecoder, Opcode, decodeClosePayload, encodeClosePayload, encodeFrame, webSocketAccept, webSocketKey } from './webSocketFrames.js';
|
|
10
|
+
|
|
11
|
+
export interface WebSocketCloseInfo {
|
|
12
|
+
code: number;
|
|
13
|
+
reason: string;
|
|
14
|
+
wasClean: boolean;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface WebSocketConnection {
|
|
18
|
+
/** 0 connecting, 1 open, 2 closing, 3 closed — `WebSocket.readyState`'s values. */
|
|
19
|
+
readonly readyState: number;
|
|
20
|
+
onOpen(listener: (info: { protocol: string }) => void): () => void;
|
|
21
|
+
onMessage(listener: (data: string | Uint8Array) => void): () => void;
|
|
22
|
+
/** Fires once; `wasClean` false and code 1006 when the connection dropped or the handshake failed. */
|
|
23
|
+
onClose(listener: (info: WebSocketCloseInfo) => void): () => void;
|
|
24
|
+
send(data: string | Uint8Array): void;
|
|
25
|
+
close(code?: number, reason?: string): void;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface WebSocketConnectOptions {
|
|
29
|
+
/** Path and query on the server (`/socket?room=1`). */
|
|
30
|
+
path: string;
|
|
31
|
+
protocols?: string[];
|
|
32
|
+
/** Extra request headers (`origin`, `cookie`). */
|
|
33
|
+
headers?: Record<string, string>;
|
|
34
|
+
/** Give up on a close handshake the server never answers. Default 5000ms. */
|
|
35
|
+
closeTimeoutMs?: number;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const HEAD_END = [13, 10, 13, 10];
|
|
39
|
+
|
|
40
|
+
function indexOfHeadEnd(bytes: Uint8Array): number {
|
|
41
|
+
outer: for (let i = 0; i + 3 < bytes.length; i++) {
|
|
42
|
+
for (let j = 0; j < 4; j++) if (bytes[i + j] !== HEAD_END[j]) continue outer;
|
|
43
|
+
return i;
|
|
44
|
+
}
|
|
45
|
+
return -1;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function parseHead(text: string): { status: number; headers: Record<string, string> } {
|
|
49
|
+
const [statusLine = '', ...lines] = text.split('\r\n');
|
|
50
|
+
const headers: Record<string, string> = {};
|
|
51
|
+
for (const line of lines) {
|
|
52
|
+
const colon = line.indexOf(':');
|
|
53
|
+
if (colon > 0) headers[line.slice(0, colon).trim().toLowerCase()] = line.slice(colon + 1).trim();
|
|
54
|
+
}
|
|
55
|
+
return { status: Number(/^HTTP\/\d(?:\.\d)?\s+(\d{3})/.exec(statusLine)?.[1] ?? 0), headers };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Open a WebSocket through `upgrade` (`kernel.upgrade` / `processHost.upgrade` bound to a port). */
|
|
59
|
+
export function connectWebSocket(upgrade: (request: HttpRequestData) => ByteChannel | undefined, options: WebSocketConnectOptions): WebSocketConnection {
|
|
60
|
+
const opens = new Set<(info: { protocol: string }) => void>();
|
|
61
|
+
const messages = new Set<(data: string | Uint8Array) => void>();
|
|
62
|
+
const closes = new Set<(info: WebSocketCloseInfo) => void>();
|
|
63
|
+
const key = webSocketKey();
|
|
64
|
+
const decoder = new FrameDecoder();
|
|
65
|
+
let state = 0;
|
|
66
|
+
let head: Uint8Array = new Uint8Array(0);
|
|
67
|
+
let fragments: Uint8Array[] = [];
|
|
68
|
+
let fragmentOpcode = 0;
|
|
69
|
+
let closeSent = false;
|
|
70
|
+
let closeTimer: ReturnType<typeof setTimeout> | undefined;
|
|
71
|
+
|
|
72
|
+
const headers: Record<string, string> = {
|
|
73
|
+
...options.headers,
|
|
74
|
+
connection: 'Upgrade',
|
|
75
|
+
upgrade: 'websocket',
|
|
76
|
+
'sec-websocket-version': '13',
|
|
77
|
+
'sec-websocket-key': key,
|
|
78
|
+
};
|
|
79
|
+
if (options.protocols?.length) headers['sec-websocket-protocol'] = options.protocols.join(', ');
|
|
80
|
+
const channel = upgrade({ method: 'GET', url: options.path, headers, body: null });
|
|
81
|
+
|
|
82
|
+
const finish = (info: WebSocketCloseInfo) => {
|
|
83
|
+
if (state === 3) return;
|
|
84
|
+
state = 3;
|
|
85
|
+
clearTimeout(closeTimer);
|
|
86
|
+
channel?.close();
|
|
87
|
+
for (const listener of closes) listener(info);
|
|
88
|
+
};
|
|
89
|
+
const fail = () => finish({ code: 1006, reason: '', wasClean: false });
|
|
90
|
+
const sendFrame = (opcode: number, payload: Uint8Array) => channel?.send(encodeFrame(opcode, payload, { mask: true }));
|
|
91
|
+
|
|
92
|
+
const onFrame = (opcode: number, fin: boolean, payload: Uint8Array) => {
|
|
93
|
+
if (opcode === Opcode.ping) return sendFrame(Opcode.pong, payload);
|
|
94
|
+
if (opcode === Opcode.pong) return;
|
|
95
|
+
if (opcode === Opcode.close) {
|
|
96
|
+
const { code, reason } = decodeClosePayload(payload);
|
|
97
|
+
if (!closeSent) {
|
|
98
|
+
closeSent = true;
|
|
99
|
+
sendFrame(Opcode.close, code === 1005 ? new Uint8Array() : encodeClosePayload(code));
|
|
100
|
+
}
|
|
101
|
+
return finish({ code, reason, wasClean: true });
|
|
102
|
+
}
|
|
103
|
+
if (opcode !== Opcode.continuation) {
|
|
104
|
+
fragmentOpcode = opcode;
|
|
105
|
+
fragments = [];
|
|
106
|
+
}
|
|
107
|
+
fragments.push(payload);
|
|
108
|
+
if (!fin) return;
|
|
109
|
+
const whole = fragments.length === 1 ? fragments[0]! : joinChunks(fragments);
|
|
110
|
+
fragments = [];
|
|
111
|
+
const data = fragmentOpcode === Opcode.text ? new TextDecoder().decode(whole) : whole;
|
|
112
|
+
for (const listener of messages) listener(data);
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
const onBytes = (bytes: Uint8Array) => {
|
|
116
|
+
if (state === 3) return;
|
|
117
|
+
let rest = bytes;
|
|
118
|
+
if (state === 0) {
|
|
119
|
+
head = joinChunks([head, bytes]);
|
|
120
|
+
const end = indexOfHeadEnd(head);
|
|
121
|
+
if (end < 0) return;
|
|
122
|
+
const reply = parseHead(new TextDecoder().decode(head.subarray(0, end)));
|
|
123
|
+
rest = head.subarray(end + 4);
|
|
124
|
+
if (reply.status !== 101 || reply.headers['sec-websocket-accept'] !== webSocketAccept(key)) return fail();
|
|
125
|
+
state = 1;
|
|
126
|
+
const protocol = reply.headers['sec-websocket-protocol'] ?? '';
|
|
127
|
+
for (const listener of opens) listener({ protocol });
|
|
128
|
+
}
|
|
129
|
+
for (const frame of decoder.push(rest)) {
|
|
130
|
+
onFrame(frame.opcode, frame.fin, frame.payload);
|
|
131
|
+
if (state === 3) return;
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
if (!channel) queueMicrotask(fail);
|
|
136
|
+
else {
|
|
137
|
+
channel.onData(onBytes);
|
|
138
|
+
channel.onClose(fail);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
return {
|
|
142
|
+
get readyState() {
|
|
143
|
+
return state;
|
|
144
|
+
},
|
|
145
|
+
onOpen: (listener) => subscribe(opens, listener),
|
|
146
|
+
onMessage: (listener) => subscribe(messages, listener),
|
|
147
|
+
onClose: (listener) => subscribe(closes, listener),
|
|
148
|
+
send(data) {
|
|
149
|
+
if (state !== 1) return;
|
|
150
|
+
if (typeof data === 'string') sendFrame(Opcode.text, new TextEncoder().encode(data));
|
|
151
|
+
else sendFrame(Opcode.binary, data);
|
|
152
|
+
},
|
|
153
|
+
close(code, reason) {
|
|
154
|
+
if (state === 0) return fail();
|
|
155
|
+
if (state !== 1) return;
|
|
156
|
+
state = 2;
|
|
157
|
+
closeSent = true;
|
|
158
|
+
sendFrame(Opcode.close, encodeClosePayload(code ?? 1000, reason));
|
|
159
|
+
closeTimer = setTimeout(fail, options.closeTimeoutMs ?? 5000);
|
|
160
|
+
},
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function subscribe<T>(set: Set<T>, listener: T): () => void {
|
|
165
|
+
set.add(listener);
|
|
166
|
+
return () => set.delete(listener);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function joinChunks(chunks: Uint8Array[]): Uint8Array {
|
|
170
|
+
const out = new Uint8Array(chunks.reduce((n, c) => n + c.byteLength, 0));
|
|
171
|
+
let offset = 0;
|
|
172
|
+
for (const chunk of chunks) {
|
|
173
|
+
out.set(chunk, offset);
|
|
174
|
+
offset += chunk.byteLength;
|
|
175
|
+
}
|
|
176
|
+
return out;
|
|
177
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The WebSocket wire format (RFC 6455): the opening handshake's accept key and
|
|
3
|
+
* frame encoding/decoding. Runtime-agnostic, so the same codec drives the
|
|
4
|
+
* client end in the host page (bridging a preview's `WebSocket`) and tests that
|
|
5
|
+
* speak to a server's `upgrade` handler byte for byte.
|
|
6
|
+
*/
|
|
7
|
+
import { hashAlgorithm } from '../node/hashes.js';
|
|
8
|
+
|
|
9
|
+
export const WEBSOCKET_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
|
|
10
|
+
|
|
11
|
+
export const Opcode = { continuation: 0x0, text: 0x1, binary: 0x2, close: 0x8, ping: 0x9, pong: 0xa } as const;
|
|
12
|
+
|
|
13
|
+
export interface WebSocketFrame {
|
|
14
|
+
fin: boolean;
|
|
15
|
+
opcode: number;
|
|
16
|
+
/** Unmasked. */
|
|
17
|
+
payload: Uint8Array;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function bytesToBase64(bytes: Uint8Array): string {
|
|
21
|
+
let binary = '';
|
|
22
|
+
for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]!);
|
|
23
|
+
return btoa(binary);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** `Sec-WebSocket-Accept` for a client's `Sec-WebSocket-Key`. */
|
|
27
|
+
export function webSocketAccept(key: string): string {
|
|
28
|
+
return bytesToBase64(hashAlgorithm('sha1').digest(new TextEncoder().encode(key + WEBSOCKET_GUID)));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** A fresh `Sec-WebSocket-Key` (16 random bytes, base64). */
|
|
32
|
+
export function webSocketKey(): string {
|
|
33
|
+
return bytesToBase64(globalThis.crypto.getRandomValues(new Uint8Array(16)));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** One frame. Clients must mask (`mask: true` picks a random key); servers must not. */
|
|
37
|
+
export function encodeFrame(opcode: number, payload: Uint8Array, options: { mask?: boolean | Uint8Array; fin?: boolean } = {}): Uint8Array {
|
|
38
|
+
const length = payload.byteLength;
|
|
39
|
+
const maskKey = options.mask === true ? globalThis.crypto.getRandomValues(new Uint8Array(4)) : options.mask || undefined;
|
|
40
|
+
const extended = length < 126 ? 0 : length <= 0xffff ? 2 : 8;
|
|
41
|
+
const headerLength = 2 + extended + (maskKey ? 4 : 0);
|
|
42
|
+
const frame = new Uint8Array(headerLength + length);
|
|
43
|
+
const view = new DataView(frame.buffer);
|
|
44
|
+
frame[0] = (options.fin === false ? 0 : 0x80) | (opcode & 0x0f);
|
|
45
|
+
frame[1] = (maskKey ? 0x80 : 0) | (extended === 0 ? length : extended === 2 ? 126 : 127);
|
|
46
|
+
if (extended === 2) view.setUint16(2, length);
|
|
47
|
+
else if (extended === 8) {
|
|
48
|
+
view.setUint32(2, Math.floor(length / 2 ** 32));
|
|
49
|
+
view.setUint32(6, length >>> 0);
|
|
50
|
+
}
|
|
51
|
+
if (maskKey) {
|
|
52
|
+
frame.set(maskKey, 2 + extended);
|
|
53
|
+
for (let i = 0; i < length; i++) frame[headerLength + i] = payload[i]! ^ maskKey[i & 3]!;
|
|
54
|
+
} else frame.set(payload, headerLength);
|
|
55
|
+
return frame;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** A close frame's payload: the status code and a UTF-8 reason. */
|
|
59
|
+
export function encodeClosePayload(code?: number, reason = ''): Uint8Array {
|
|
60
|
+
if (code === undefined) return new Uint8Array();
|
|
61
|
+
const text = new TextEncoder().encode(reason);
|
|
62
|
+
const out = new Uint8Array(2 + text.byteLength);
|
|
63
|
+
new DataView(out.buffer).setUint16(0, code);
|
|
64
|
+
out.set(text, 2);
|
|
65
|
+
return out;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Status 1005 ("no status received") when the payload is empty. */
|
|
69
|
+
export function decodeClosePayload(payload: Uint8Array): { code: number; reason: string } {
|
|
70
|
+
if (payload.byteLength < 2) return { code: 1005, reason: '' };
|
|
71
|
+
return { code: new DataView(payload.buffer, payload.byteOffset, payload.byteLength).getUint16(0), reason: new TextDecoder().decode(payload.subarray(2)) };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Splits a byte stream into frames, whatever the chunking. */
|
|
75
|
+
export class FrameDecoder {
|
|
76
|
+
private buffer = new Uint8Array(0);
|
|
77
|
+
|
|
78
|
+
push(bytes: Uint8Array): WebSocketFrame[] {
|
|
79
|
+
if (bytes.byteLength) {
|
|
80
|
+
const joined = new Uint8Array(this.buffer.byteLength + bytes.byteLength);
|
|
81
|
+
joined.set(this.buffer);
|
|
82
|
+
joined.set(bytes, this.buffer.byteLength);
|
|
83
|
+
this.buffer = joined;
|
|
84
|
+
}
|
|
85
|
+
const frames: WebSocketFrame[] = [];
|
|
86
|
+
for (;;) {
|
|
87
|
+
const frame = this.next();
|
|
88
|
+
if (!frame) return frames;
|
|
89
|
+
frames.push(frame);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
private next(): WebSocketFrame | undefined {
|
|
94
|
+
const b = this.buffer;
|
|
95
|
+
if (b.byteLength < 2) return undefined;
|
|
96
|
+
const masked = (b[1]! & 0x80) !== 0;
|
|
97
|
+
let length = b[1]! & 0x7f;
|
|
98
|
+
let offset = 2;
|
|
99
|
+
const view = new DataView(b.buffer, b.byteOffset, b.byteLength);
|
|
100
|
+
if (length === 126) {
|
|
101
|
+
if (b.byteLength < 4) return undefined;
|
|
102
|
+
length = view.getUint16(2);
|
|
103
|
+
offset = 4;
|
|
104
|
+
} else if (length === 127) {
|
|
105
|
+
if (b.byteLength < 10) return undefined;
|
|
106
|
+
length = view.getUint32(2) * 2 ** 32 + view.getUint32(6);
|
|
107
|
+
offset = 10;
|
|
108
|
+
}
|
|
109
|
+
const maskKey = masked ? b.subarray(offset, offset + 4) : undefined;
|
|
110
|
+
if (masked) offset += 4;
|
|
111
|
+
if (b.byteLength < offset + length) return undefined;
|
|
112
|
+
const payload = b.slice(offset, offset + length);
|
|
113
|
+
if (maskKey) for (let i = 0; i < payload.length; i++) payload[i] = payload[i]! ^ maskKey[i & 3]!;
|
|
114
|
+
const frame = { fin: (b[0]! & 0x80) !== 0, opcode: b[0]! & 0x0f, payload };
|
|
115
|
+
this.buffer = b.slice(offset + length);
|
|
116
|
+
return frame;
|
|
117
|
+
}
|
|
118
|
+
}
|