@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/node/runtime.ts
CHANGED
|
@@ -4,7 +4,10 @@
|
|
|
4
4
|
* entry and resolves `exit` with the code once the process exits — by
|
|
5
5
|
* `process.exit()`, an uncaught exception, being killed, or the loop going idle.
|
|
6
6
|
*/
|
|
7
|
-
import type { ProgramIO, System } from '../system/types.js';
|
|
7
|
+
import type { ProgramIO, System, ThreadInfo } from '../system/types.js';
|
|
8
|
+
import type { IpcEndpoint } from '../system/ipc.js';
|
|
9
|
+
import { attachProcessChannel } from './ipc.js';
|
|
10
|
+
import { threadErrorEnvelope } from './workerThreads.js';
|
|
8
11
|
import { Buffer } from './buffer.js';
|
|
9
12
|
import { createBuiltins } from './builtins.js';
|
|
10
13
|
import { createModuleSystem, type ModuleSystem } from './loader.js';
|
|
@@ -12,6 +15,7 @@ import { EventLoop } from './loop.js';
|
|
|
12
15
|
import { createConsole, createProcess, ProcessExit, type NodeProcess } from './process.js';
|
|
13
16
|
import { esmReady } from './esm.js';
|
|
14
17
|
import { inspect } from './inspect.js';
|
|
18
|
+
import { installGlobalObject } from './globalObject.js';
|
|
15
19
|
|
|
16
20
|
export interface NodeOptions {
|
|
17
21
|
system: System;
|
|
@@ -27,6 +31,10 @@ export interface NodeOptions {
|
|
|
27
31
|
* share one realm.
|
|
28
32
|
*/
|
|
29
33
|
installGlobals?: boolean;
|
|
34
|
+
/** The channel to the parent: `process.send` in a forked child, `parentPort` in a worker thread. */
|
|
35
|
+
ipc?: IpcEndpoint;
|
|
36
|
+
/** Set when this process is a worker thread. */
|
|
37
|
+
thread?: ThreadInfo;
|
|
30
38
|
}
|
|
31
39
|
|
|
32
40
|
export interface NodeInstance {
|
|
@@ -48,7 +56,14 @@ const SIGNAL_CODES: Record<string, number> = { SIGINT: 130, SIGTERM: 143, SIGKIL
|
|
|
48
56
|
|
|
49
57
|
export async function startNode(options: NodeOptions): Promise<NodeInstance> {
|
|
50
58
|
await esmReady;
|
|
51
|
-
const { system
|
|
59
|
+
const { system } = options;
|
|
60
|
+
// Once the process has finished it prints nothing — a host promise settling late
|
|
61
|
+
// must not write past the exit the parent already saw.
|
|
62
|
+
const io: ProgramIO = {
|
|
63
|
+
...options.io,
|
|
64
|
+
stdout: (chunk) => finished || options.io.stdout(chunk),
|
|
65
|
+
stderr: (chunk) => finished || options.io.stderr(chunk),
|
|
66
|
+
};
|
|
52
67
|
let resolveExit!: (code: number) => void;
|
|
53
68
|
const exit = new Promise<number>((resolve) => (resolveExit = resolve));
|
|
54
69
|
let finished = false;
|
|
@@ -57,8 +72,8 @@ export async function startNode(options: NodeOptions): Promise<NodeInstance> {
|
|
|
57
72
|
// Servers die with the process: wrap listen so exit can close what is left open.
|
|
58
73
|
const processSystem: System = {
|
|
59
74
|
...system,
|
|
60
|
-
listen(port, handler) {
|
|
61
|
-
const registration = system.listen(port, handler);
|
|
75
|
+
listen(port, handler, upgrade) {
|
|
76
|
+
const registration = system.listen(port, handler, upgrade);
|
|
62
77
|
const tracked = {
|
|
63
78
|
port: registration.port,
|
|
64
79
|
close() {
|
|
@@ -89,8 +104,12 @@ export async function startNode(options: NodeOptions): Promise<NodeInstance> {
|
|
|
89
104
|
error = nested;
|
|
90
105
|
}
|
|
91
106
|
}
|
|
92
|
-
|
|
93
|
-
|
|
107
|
+
// A worker thread's fatal error is the parent's 'error' event, not output.
|
|
108
|
+
if (options.thread && options.ipc?.connected) options.ipc.send(threadErrorEnvelope(error));
|
|
109
|
+
else {
|
|
110
|
+
const text = error instanceof Error ? error.stack ?? `${error.name}: ${error.message}` : `Uncaught ${inspect(error)}`;
|
|
111
|
+
io.stderr(`${text}\n\nNode.js v${proc.versions.node}\n`);
|
|
112
|
+
}
|
|
94
113
|
exitQuietly(proc.exitCode && proc.exitCode !== 0 ? proc.exitCode : 1);
|
|
95
114
|
};
|
|
96
115
|
|
|
@@ -125,8 +144,9 @@ export async function startNode(options: NodeOptions): Promise<NodeInstance> {
|
|
|
125
144
|
loop,
|
|
126
145
|
onExit: finish,
|
|
127
146
|
});
|
|
147
|
+
if (options.ipc && !options.thread) attachProcessChannel(proc, options.ipc, loop);
|
|
128
148
|
const console = createConsole(proc);
|
|
129
|
-
const builtins = createBuiltins({ fs: system.fs, process: proc, loop, system: processSystem, io, console });
|
|
149
|
+
const builtins = createBuiltins({ fs: system.fs, process: proc, loop, system: processSystem, io, console, thread: options.thread, ipc: options.ipc });
|
|
130
150
|
|
|
131
151
|
const globals: Record<string, unknown> = {
|
|
132
152
|
process: proc,
|
|
@@ -140,17 +160,9 @@ export async function startNode(options: NodeOptions): Promise<NodeInstance> {
|
|
|
140
160
|
clearImmediate: loop.clearImmediate,
|
|
141
161
|
fetch: builtins.fetch,
|
|
142
162
|
};
|
|
143
|
-
|
|
144
|
-
Object.assign(globalThis, globals, { global: globalThis });
|
|
145
|
-
globals.global = globalThis;
|
|
146
|
-
} else {
|
|
147
|
-
// A per-process view of the global object: reads fall through to the real
|
|
148
|
-
// one, Node's own names resolve to this process's.
|
|
149
|
-
globals.global = Object.assign(Object.create(globalThis), globals);
|
|
150
|
-
}
|
|
151
|
-
globals.globalThis = globals.global;
|
|
163
|
+
const scope = installGlobalObject(globals, !!options.installGlobals);
|
|
152
164
|
|
|
153
|
-
const modules = createModuleSystem({ fs: system.fs, isBuiltin: builtins.isBuiltin, builtin: builtins.get, globals });
|
|
165
|
+
const modules = createModuleSystem({ fs: system.fs, isBuiltin: builtins.isBuiltin, builtin: builtins.get, globals, scope });
|
|
154
166
|
(modules.Module as unknown as { builtinModules: string[] }).builtinModules = builtins.names;
|
|
155
167
|
Object.defineProperty(proc, 'mainModule', { get: () => modules.main, configurable: true });
|
|
156
168
|
|
|
@@ -6,8 +6,9 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import { EventEmitterBase } from '../events.js';
|
|
8
8
|
import { Buffer } from '../buffer.js';
|
|
9
|
+
import { queueCallback } from '../processExit.js';
|
|
9
10
|
|
|
10
|
-
export const tick =
|
|
11
|
+
export const tick = queueCallback;
|
|
11
12
|
|
|
12
13
|
export interface ReadableOptions {
|
|
13
14
|
highWaterMark?: number;
|
package/src/node/urlqs.ts
CHANGED
|
@@ -62,7 +62,7 @@ export interface LegacyUrl {
|
|
|
62
62
|
href: string;
|
|
63
63
|
}
|
|
64
64
|
|
|
65
|
-
export function createUrlModule(qs: Record<string, any
|
|
65
|
+
export function createUrlModule(qs: Record<string, any>, resolvePath: (path: string) => string): Record<string, unknown> {
|
|
66
66
|
function parse(input: string, parseQueryString = false, slashesDenoteHost = false): LegacyUrl {
|
|
67
67
|
let rest = input.trim();
|
|
68
68
|
const out: LegacyUrl = { protocol: null, slashes: null, auth: null, host: null, port: null, hostname: null, hash: null, search: null, query: null, pathname: null, path: null, href: '' };
|
|
@@ -153,7 +153,15 @@ export function createUrlModule(qs: Record<string, any>): Record<string, unknown
|
|
|
153
153
|
if (u.protocol !== 'file:') throw Object.assign(new TypeError('The URL must be of scheme file'), { code: 'ERR_INVALID_URL_SCHEME' });
|
|
154
154
|
return decodeURIComponent(u.pathname);
|
|
155
155
|
},
|
|
156
|
-
|
|
156
|
+
// As Node: resolved against the working directory (a relative path never becomes the
|
|
157
|
+
// URL's host), a trailing slash kept, and the characters a pathname would misread escaped.
|
|
158
|
+
pathToFileURL: (path: string) => {
|
|
159
|
+
let resolved = resolvePath(path);
|
|
160
|
+
if (path.endsWith('/') && !resolved.endsWith('/')) resolved += '/';
|
|
161
|
+
const url = new URL('file://');
|
|
162
|
+
url.pathname = resolved.replace(/%/g, '%25').replace(/\\/g, '%5C').replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/\t/g, '%09');
|
|
163
|
+
return url;
|
|
164
|
+
},
|
|
157
165
|
domainToASCII: (d: string) => d,
|
|
158
166
|
domainToUnicode: (d: string) => d,
|
|
159
167
|
urlToHttpOptions: (u: URL) => ({ protocol: u.protocol, hostname: u.hostname, hash: u.hash, search: u.search, pathname: u.pathname, path: u.pathname + u.search, href: u.href, port: u.port ? Number(u.port) : undefined }),
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `worker_threads`, as processes. A `Worker` is a node process started with a
|
|
3
|
+
* message channel and its `workerData` — in the browser runtime, its own Web
|
|
4
|
+
* Worker, so it really runs in parallel. Inside it, `isMainThread` is false and
|
|
5
|
+
* `parentPort` is that channel. There is no shared memory (no SharedArrayBuffer
|
|
6
|
+
* without cross-origin isolation, which this runtime never requires), so
|
|
7
|
+
* messages are copied and `transferList` ports cannot move between threads.
|
|
8
|
+
*
|
|
9
|
+
* On the wire every message is an envelope, so a worker's uncaught error reaches
|
|
10
|
+
* the parent's `'error'` listener as an Error, the way Node reports it.
|
|
11
|
+
*/
|
|
12
|
+
import { EventEmitterBase } from './events.js';
|
|
13
|
+
import { Readable } from './stream/readable.js';
|
|
14
|
+
import type { EventLoop } from './loop.js';
|
|
15
|
+
import type { ChildHandle, StdioChunk, System, ThreadInfo } from '../system/types.js';
|
|
16
|
+
import { Buffer } from './buffer.js';
|
|
17
|
+
import type { IpcEndpoint } from '../system/ipc.js';
|
|
18
|
+
import { join } from '../paths.js';
|
|
19
|
+
import { keepAliveWhileListened, type ChannelKeepAlive } from './ipc.js';
|
|
20
|
+
|
|
21
|
+
type Envelope = { kind: 'message'; value: unknown } | { kind: 'error'; error: { name: string; message: string; stack?: string } };
|
|
22
|
+
|
|
23
|
+
/** The envelope a worker thread sends its parent when it dies of an uncaught error. */
|
|
24
|
+
export function threadErrorEnvelope(error: unknown): Envelope {
|
|
25
|
+
const e = error instanceof Error ? error : new Error(String(error));
|
|
26
|
+
return { kind: 'error', error: { name: e.name, message: e.message, stack: e.stack } };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function errorFrom(envelope: Extract<Envelope, { kind: 'error' }>): Error {
|
|
30
|
+
const error = new Error(envelope.error.message);
|
|
31
|
+
error.name = envelope.error.name;
|
|
32
|
+
if (envelope.error.stack) error.stack = envelope.error.stack;
|
|
33
|
+
return error;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface WorkerThreadsDeps {
|
|
37
|
+
system: System;
|
|
38
|
+
loop: EventLoop;
|
|
39
|
+
cwd(): string;
|
|
40
|
+
env(): Record<string, string | undefined>;
|
|
41
|
+
stdout(chunk: StdioChunk): void;
|
|
42
|
+
stderr(chunk: StdioChunk): void;
|
|
43
|
+
/** Set when this process is itself a worker thread. */
|
|
44
|
+
thread?: ThreadInfo;
|
|
45
|
+
/** Its channel to the parent (the thread's `parentPort`). */
|
|
46
|
+
ipc?: IpcEndpoint;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
interface WorkerOptions {
|
|
50
|
+
workerData?: unknown;
|
|
51
|
+
eval?: boolean;
|
|
52
|
+
argv?: unknown[];
|
|
53
|
+
env?: Record<string, string | undefined> | symbol;
|
|
54
|
+
stdout?: boolean;
|
|
55
|
+
stderr?: boolean;
|
|
56
|
+
name?: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
let nextThreadId = 1;
|
|
60
|
+
|
|
61
|
+
/** The `parentPort` of a worker thread: messages to and from the parent. */
|
|
62
|
+
class ParentPort extends EventEmitterBase {
|
|
63
|
+
private readonly keepAlive: ChannelKeepAlive;
|
|
64
|
+
|
|
65
|
+
constructor(private readonly ipc: IpcEndpoint, loop: EventLoop) {
|
|
66
|
+
super();
|
|
67
|
+
this.keepAlive = keepAliveWhileListened(this, ['message'], loop, () => ipc.connected, () => {
|
|
68
|
+
ipc.onMessage((envelope) => {
|
|
69
|
+
const { kind, value } = envelope as Extract<Envelope, { kind: 'message' }>;
|
|
70
|
+
if (kind === 'message') loop._run(() => this.emit('message', value));
|
|
71
|
+
});
|
|
72
|
+
});
|
|
73
|
+
ipc.onDisconnect(() => {
|
|
74
|
+
loop._run(() => this.emit('close'));
|
|
75
|
+
this.keepAlive.update();
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
postMessage(value: unknown): void {
|
|
80
|
+
this.ipc.send({ kind: 'message', value } satisfies Envelope);
|
|
81
|
+
}
|
|
82
|
+
close(): void {
|
|
83
|
+
this.ipc.disconnect();
|
|
84
|
+
}
|
|
85
|
+
start(): void {}
|
|
86
|
+
ref(): this {
|
|
87
|
+
this.keepAlive.ref();
|
|
88
|
+
return this;
|
|
89
|
+
}
|
|
90
|
+
unref(): this {
|
|
91
|
+
this.keepAlive.unref();
|
|
92
|
+
return this;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function createWorkerThreadsModule(deps: WorkerThreadsDeps): Record<string, unknown> {
|
|
97
|
+
const { loop } = deps;
|
|
98
|
+
const environmentData = new Map<unknown, unknown>();
|
|
99
|
+
|
|
100
|
+
class Worker extends EventEmitterBase {
|
|
101
|
+
readonly threadId = nextThreadId++;
|
|
102
|
+
readonly resourceLimits = {};
|
|
103
|
+
readonly stdin = null;
|
|
104
|
+
readonly stdout: Readable;
|
|
105
|
+
readonly stderr: Readable;
|
|
106
|
+
private readonly handle?: ChildHandle;
|
|
107
|
+
private release?: () => void;
|
|
108
|
+
private terminated = false;
|
|
109
|
+
|
|
110
|
+
constructor(filename: string | URL, options: WorkerOptions = {}) {
|
|
111
|
+
super();
|
|
112
|
+
this.stdout = new Readable({ read() {} });
|
|
113
|
+
this.stderr = new Readable({ read() {} });
|
|
114
|
+
const source = filename instanceof URL ? decodeURIComponent(filename.pathname) : String(filename);
|
|
115
|
+
const script = options.eval ? ['-e', source] : [source.startsWith('/') ? source : join(deps.cwd(), source)];
|
|
116
|
+
const env: Record<string, string> = {};
|
|
117
|
+
const fromParent = typeof options.env === 'object' ? options.env : deps.env();
|
|
118
|
+
for (const [key, value] of Object.entries(fromParent)) if (value !== undefined) env[key] = String(value);
|
|
119
|
+
|
|
120
|
+
this.release = loop.hold();
|
|
121
|
+
try {
|
|
122
|
+
this.handle = deps.system.spawn('node', [...script, ...(options.argv ?? []).map(String)], {
|
|
123
|
+
cwd: deps.cwd(),
|
|
124
|
+
env,
|
|
125
|
+
ipc: true,
|
|
126
|
+
thread: { threadId: this.threadId, workerData: options.workerData ?? null },
|
|
127
|
+
});
|
|
128
|
+
} catch (error) {
|
|
129
|
+
this.releaseLoop();
|
|
130
|
+
queueMicrotask(() => loop._run(() => this.emit('error', error)));
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
const handle = this.handle;
|
|
134
|
+
handle.onStdout((chunk) => (options.stdout ? this.stdout.push(Buffer.from(chunk)) : deps.stdout(chunk)));
|
|
135
|
+
handle.onStderr((chunk) => (options.stderr ? this.stderr.push(Buffer.from(chunk)) : deps.stderr(chunk)));
|
|
136
|
+
handle.ipc?.onMessage((message) => {
|
|
137
|
+
const envelope = message as Envelope;
|
|
138
|
+
loop._run(() => (envelope.kind === 'error' ? this.emit('error', errorFrom(envelope)) : this.emit('message', envelope.value)));
|
|
139
|
+
});
|
|
140
|
+
queueMicrotask(() => loop._run(() => this.emit('online')));
|
|
141
|
+
void handle.exit.then((code) => {
|
|
142
|
+
this.stdout.push(null);
|
|
143
|
+
this.stderr.push(null);
|
|
144
|
+
loop._run(() => this.emit('exit', this.terminated ? 1 : code));
|
|
145
|
+
this.releaseLoop();
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
postMessage(value: unknown): void {
|
|
150
|
+
this.handle?.ipc?.send({ kind: 'message', value } satisfies Envelope);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Stop the thread; resolves with its exit code. */
|
|
154
|
+
terminate(): Promise<number> {
|
|
155
|
+
if (!this.handle) return Promise.resolve(1);
|
|
156
|
+
this.terminated = true;
|
|
157
|
+
this.handle.kill('SIGKILL');
|
|
158
|
+
return this.handle.exit.then(() => 1);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
ref(): this {
|
|
162
|
+
if (!this.release && !this.terminated) this.release = loop.hold();
|
|
163
|
+
return this;
|
|
164
|
+
}
|
|
165
|
+
unref(): this {
|
|
166
|
+
this.releaseLoop();
|
|
167
|
+
return this;
|
|
168
|
+
}
|
|
169
|
+
getHeapSnapshot(): Promise<never> {
|
|
170
|
+
return Promise.reject(Object.assign(new Error('Heap snapshots are not available in the browser runtime'), { code: 'ERR_FEATURE_UNAVAILABLE_ON_PLATFORM' }));
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
private releaseLoop(): void {
|
|
174
|
+
this.release?.();
|
|
175
|
+
this.release = undefined;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const inThread = !!deps.thread && !!deps.ipc;
|
|
180
|
+
return {
|
|
181
|
+
isMainThread: !inThread,
|
|
182
|
+
parentPort: inThread ? new ParentPort(deps.ipc!, loop) : null,
|
|
183
|
+
workerData: deps.thread?.workerData ?? null,
|
|
184
|
+
threadId: deps.thread?.threadId ?? 0,
|
|
185
|
+
resourceLimits: {},
|
|
186
|
+
Worker,
|
|
187
|
+
MessageChannel: globalThis.MessageChannel,
|
|
188
|
+
MessagePort: globalThis.MessagePort,
|
|
189
|
+
BroadcastChannel: globalThis.BroadcastChannel,
|
|
190
|
+
receiveMessageOnPort: () => undefined,
|
|
191
|
+
markAsUntransferable: () => undefined,
|
|
192
|
+
isMarkedAsUntransferable: () => false,
|
|
193
|
+
moveMessagePortToContext: (port: unknown) => port,
|
|
194
|
+
setEnvironmentData: (key: unknown, value: unknown) => void environmentData.set(key, value),
|
|
195
|
+
getEnvironmentData: (key: unknown) => environmentData.get(key),
|
|
196
|
+
SHARE_ENV: Symbol.for('nodejs.worker_threads.SHARE_ENV'),
|
|
197
|
+
};
|
|
198
|
+
}
|
package/src/node/zlib.ts
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
import * as fflate from 'fflate';
|
|
7
7
|
import { Buffer } from './buffer.js';
|
|
8
8
|
import { Transform } from './stream/index.js';
|
|
9
|
+
import { queueCallback } from './processExit.js';
|
|
9
10
|
|
|
10
11
|
type Input = string | ArrayBufferView | ArrayBuffer;
|
|
11
12
|
type Options = { level?: number };
|
|
@@ -36,6 +37,8 @@ const STREAMS: Record<string, (options?: Options) => InstanceType<StreamCtor>> =
|
|
|
36
37
|
Unzip: () => new fflate.Decompress() as unknown as InstanceType<StreamCtor>,
|
|
37
38
|
};
|
|
38
39
|
|
|
40
|
+
const Z_FINISH = 4;
|
|
41
|
+
|
|
39
42
|
function zlibError(error: unknown): Error {
|
|
40
43
|
const message = error instanceof Error ? error.message : String(error);
|
|
41
44
|
return Object.assign(new Error(message || 'invalid compressed data'), { code: 'Z_DATA_ERROR', errno: -3 });
|
|
@@ -72,6 +75,25 @@ class ZlibStream extends Transform {
|
|
|
72
75
|
}
|
|
73
76
|
}
|
|
74
77
|
|
|
78
|
+
/** Node's native handle, which minizlib (tar) briefly patches around `_processChunk`. */
|
|
79
|
+
_handle = { close: () => undefined };
|
|
80
|
+
|
|
81
|
+
/** Node's internal synchronous step: minizlib drives it directly instead of `write`. */
|
|
82
|
+
_processChunk(chunk: Uint8Array, flushFlag: number): Buffer {
|
|
83
|
+
const out: Uint8Array[] = [];
|
|
84
|
+
const ondata = this.engine.ondata;
|
|
85
|
+
this.engine.ondata = (data: Uint8Array) => void (data.length && out.push(data));
|
|
86
|
+
try {
|
|
87
|
+
this.bytesWritten += chunk.length;
|
|
88
|
+
this.engine.push(chunk, flushFlag === Z_FINISH);
|
|
89
|
+
} catch (error) {
|
|
90
|
+
throw zlibError(error);
|
|
91
|
+
} finally {
|
|
92
|
+
this.engine.ondata = ondata;
|
|
93
|
+
}
|
|
94
|
+
return Buffer.concat(out);
|
|
95
|
+
}
|
|
96
|
+
|
|
75
97
|
flush(_kind?: unknown, callback?: () => void): void {
|
|
76
98
|
callback?.();
|
|
77
99
|
}
|
|
@@ -93,7 +115,7 @@ const noBrotli = () => {
|
|
|
93
115
|
export function createZlibModule(): Record<string, unknown> {
|
|
94
116
|
const mod: Record<string, unknown> = {
|
|
95
117
|
constants: {
|
|
96
|
-
Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH
|
|
118
|
+
Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH, Z_BLOCK: 5,
|
|
97
119
|
Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, Z_BUF_ERROR: -5,
|
|
98
120
|
Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9, Z_DEFAULT_COMPRESSION: -1,
|
|
99
121
|
Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4, Z_DEFAULT_STRATEGY: 0,
|
|
@@ -124,7 +146,7 @@ export function createZlibModule(): Record<string, unknown> {
|
|
|
124
146
|
};
|
|
125
147
|
mod[name] = (input: Input, options: Options | ((e: Error | null, r?: Buffer) => void), callback?: (e: Error | null, r?: Buffer) => void) => {
|
|
126
148
|
const cb = (typeof options === 'function' ? options : callback)!;
|
|
127
|
-
|
|
149
|
+
queueCallback(() => {
|
|
128
150
|
try {
|
|
129
151
|
cb(null, Buffer.from(fn(bytes(input), typeof options === 'object' ? options : undefined)));
|
|
130
152
|
} catch (error) {
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Scripts injected into preview pages that let them reach virtual servers the
|
|
3
|
+
* way a page reaches a real one, where a service worker cannot help:
|
|
4
|
+
*
|
|
5
|
+
* • WebSockets. A service worker never sees a WebSocket, so the page's
|
|
6
|
+
* `WebSocket` is replaced by one that, for URLs naming a virtual server
|
|
7
|
+
* (`ws://localhost:3000/…`, `/__bfwc/<id>/__port/3000/…`, or a path on the
|
|
8
|
+
* page's own host from a page that server served), opens a MessageChannel
|
|
9
|
+
* to the runtime's host page (`parent`, else `opener`). The host connects
|
|
10
|
+
* to the server and relays frames both ways. Every other URL gets the real
|
|
11
|
+
* `WebSocket`, untouched.
|
|
12
|
+
* • `document.cookie` on pages a virtual server served. The host keeps those
|
|
13
|
+
* cookies (a service worker cannot set `Set-Cookie`); this mirrors the
|
|
14
|
+
* non-HttpOnly ones into `document.cookie` and sends assignments back.
|
|
15
|
+
*
|
|
16
|
+
* Messages on a socket's channel — page → host: `{ kind: 'send', data }`,
|
|
17
|
+
* `{ kind: 'close', code, reason }`; host → page: `{ kind: 'open', protocol }`,
|
|
18
|
+
* `{ kind: 'message', data }` (string or ArrayBuffer), `{ kind: 'close', code, reason, wasClean }`.
|
|
19
|
+
* On the cookie channel — page → host `{ kind: 'set-cookie', value }`, host → page `{ kind: 'cookies', value }`.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
/** page → host, with a MessagePort: "connect a WebSocket to `port` at `path`". */
|
|
23
|
+
export const SOCKET_MESSAGE_TYPE = 'bfwc:socket';
|
|
24
|
+
/** page → host, with a MessagePort: "keep my `document.cookie` in sync" (pages served by a virtual server). */
|
|
25
|
+
export const COOKIE_MESSAGE_TYPE = 'bfwc:cookies';
|
|
26
|
+
/** How long a page waits for the host to answer a socket before failing it (code 1006). */
|
|
27
|
+
export const SOCKET_CONNECT_TIMEOUT_MS = 15_000;
|
|
28
|
+
|
|
29
|
+
/** The `WebSocket` replacement; runs in every preview page (dev-server documents and virtual-server HTML). */
|
|
30
|
+
export function previewSocketScript(): string {
|
|
31
|
+
return `<script>(function(){
|
|
32
|
+
var Native = window.WebSocket;
|
|
33
|
+
if (!Native || Native.__bfwc) return;
|
|
34
|
+
var runtime = window.parent !== window ? window.parent : window.opener;
|
|
35
|
+
var m = /^(.*\\/__bfwc\\/[A-Za-z0-9_-]+\\/)(?:__port\\/(\\d{1,5})(?:\\/|$))?/.exec(location.pathname);
|
|
36
|
+
if (!runtime || !m || typeof MessageChannel === 'undefined') return;
|
|
37
|
+
var base = m[1], ownPort = m[2] ? Number(m[2]) : 0;
|
|
38
|
+
var LOCAL = /^(localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0|\\[::1\\])$/i;
|
|
39
|
+
function target(url) {
|
|
40
|
+
var u;
|
|
41
|
+
try { u = new URL(String(url), location.href); } catch (_) { return null; }
|
|
42
|
+
if (!/^(wss?|https?):$/.test(u.protocol)) return null;
|
|
43
|
+
if (u.host === location.host) {
|
|
44
|
+
if (u.pathname.indexOf(base) === 0) {
|
|
45
|
+
var p = /^__port\\/(\\d{1,5})(\\/.*)?$/.exec(u.pathname.slice(base.length));
|
|
46
|
+
return p ? { port: Number(p[1]), path: (p[2] || '/') + u.search } : null;
|
|
47
|
+
}
|
|
48
|
+
return ownPort ? { port: ownPort, path: u.pathname + u.search } : null;
|
|
49
|
+
}
|
|
50
|
+
if (LOCAL.test(u.hostname)) return { port: Number(u.port || (/^(wss|https):$/.test(u.protocol) ? 443 : 80)), path: u.pathname + u.search };
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
var CONNECTING = 0, OPEN = 1, CLOSING = 2, CLOSED = 3;
|
|
54
|
+
class VirtualWebSocket extends EventTarget {
|
|
55
|
+
constructor(url, protocols) {
|
|
56
|
+
var t = target(url);
|
|
57
|
+
if (!t) return protocols === undefined ? new Native(url) : new Native(url, protocols);
|
|
58
|
+
super();
|
|
59
|
+
var self = this, channel = new MessageChannel();
|
|
60
|
+
this._url = new URL(String(url), location.href).href.replace(/^http/, 'ws');
|
|
61
|
+
this._state = CONNECTING;
|
|
62
|
+
this._protocol = '';
|
|
63
|
+
this._binaryType = 'blob';
|
|
64
|
+
this._queue = Promise.resolve();
|
|
65
|
+
this._port = channel.port1;
|
|
66
|
+
this._port.onmessage = function (e) { self._receive(e.data); };
|
|
67
|
+
this._timer = setTimeout(function () { self._receive({ kind: 'close', code: 1006, reason: '', wasClean: false }); }, ${SOCKET_CONNECT_TIMEOUT_MS});
|
|
68
|
+
var list = protocols === undefined ? [] : typeof protocols === 'string' ? [protocols] : Array.from(protocols, String);
|
|
69
|
+
runtime.postMessage({ type: ${JSON.stringify(SOCKET_MESSAGE_TYPE)}, href: location.href, port: t.port, path: t.path, protocols: list }, '*', [channel.port2]);
|
|
70
|
+
}
|
|
71
|
+
get url() { return this._url; }
|
|
72
|
+
get readyState() { return this._state; }
|
|
73
|
+
get protocol() { return this._protocol; }
|
|
74
|
+
get extensions() { return ''; }
|
|
75
|
+
get bufferedAmount() { return 0; }
|
|
76
|
+
get binaryType() { return this._binaryType; }
|
|
77
|
+
set binaryType(v) { if (v === 'blob' || v === 'arraybuffer') this._binaryType = v; }
|
|
78
|
+
send(data) {
|
|
79
|
+
if (this._state === CONNECTING) throw new DOMException("Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.", 'InvalidStateError');
|
|
80
|
+
if (this._state !== OPEN) return;
|
|
81
|
+
var port = this._port;
|
|
82
|
+
var value = typeof data === 'string' ? data
|
|
83
|
+
: data instanceof Blob ? data.arrayBuffer()
|
|
84
|
+
: ArrayBuffer.isView(data) ? data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength)
|
|
85
|
+
: data instanceof ArrayBuffer ? data.slice(0) : String(data);
|
|
86
|
+
this._queue = this._queue.then(function () { return value; }).then(function (v) { port.postMessage({ kind: 'send', data: v }); });
|
|
87
|
+
}
|
|
88
|
+
close(code, reason) {
|
|
89
|
+
if (code !== undefined && code !== 1000 && (code < 3000 || code > 4999)) throw new DOMException("Failed to execute 'close' on 'WebSocket': The code must be either 1000, or between 3000 and 4999.", 'InvalidAccessError');
|
|
90
|
+
if (this._state === CLOSING || this._state === CLOSED) return;
|
|
91
|
+
this._state = CLOSING;
|
|
92
|
+
var port = this._port;
|
|
93
|
+
this._queue.then(function () { port.postMessage({ kind: 'close', code: code, reason: reason === undefined ? '' : String(reason) }); });
|
|
94
|
+
}
|
|
95
|
+
_receive(m) {
|
|
96
|
+
if (!m || this._state === CLOSED) return;
|
|
97
|
+
if (m.kind === 'open' && this._state === CONNECTING) {
|
|
98
|
+
clearTimeout(this._timer);
|
|
99
|
+
this._state = OPEN;
|
|
100
|
+
this._protocol = m.protocol || '';
|
|
101
|
+
this._emit(new Event('open'));
|
|
102
|
+
} else if (m.kind === 'message' && this._state !== CONNECTING) {
|
|
103
|
+
var d = m.data;
|
|
104
|
+
if (typeof d !== 'string' && this._binaryType === 'blob') d = new Blob([d]);
|
|
105
|
+
this._emit(new MessageEvent('message', { data: d, origin: new URL(this._url).origin }));
|
|
106
|
+
} else if (m.kind === 'close') {
|
|
107
|
+
clearTimeout(this._timer);
|
|
108
|
+
this._state = CLOSED;
|
|
109
|
+
this._port.close();
|
|
110
|
+
if (!m.wasClean) this._emit(new Event('error'));
|
|
111
|
+
this._emit(new CloseEvent('close', { code: m.code, reason: m.reason || '', wasClean: !!m.wasClean }));
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
_emit(event) {
|
|
115
|
+
var handler = this['on' + event.type];
|
|
116
|
+
if (typeof handler === 'function') handler.call(this, event);
|
|
117
|
+
this.dispatchEvent(event);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
[['CONNECTING', CONNECTING], ['OPEN', OPEN], ['CLOSING', CLOSING], ['CLOSED', CLOSED]].forEach(function (c) {
|
|
121
|
+
Object.defineProperty(VirtualWebSocket, c[0], { value: c[1] });
|
|
122
|
+
Object.defineProperty(VirtualWebSocket.prototype, c[0], { value: c[1] });
|
|
123
|
+
});
|
|
124
|
+
Object.defineProperty(VirtualWebSocket, Symbol.hasInstance, { value: function (o) { return o instanceof Native || Function.prototype[Symbol.hasInstance].call(VirtualWebSocket, o); } });
|
|
125
|
+
VirtualWebSocket.__bfwc = true;
|
|
126
|
+
window.WebSocket = VirtualWebSocket;
|
|
127
|
+
})();</script>`;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** `JSON.stringify`, safe inside an inline script. */
|
|
131
|
+
const scriptLiteral = (value: unknown) => JSON.stringify(value).replace(/</g, '\\u003c');
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* `document.cookie` for a page a virtual server served: starts from the host's
|
|
135
|
+
* jar (`initial`: the non-HttpOnly cookies for this page's path), stays in sync
|
|
136
|
+
* over a channel, and sends assignments to the host's jar.
|
|
137
|
+
*/
|
|
138
|
+
export function previewCookieScript(initial: string): string {
|
|
139
|
+
return `<script>(function(){
|
|
140
|
+
var runtime = window.parent !== window ? window.parent : window.opener;
|
|
141
|
+
var cookies = ${scriptLiteral(initial)};
|
|
142
|
+
var port = null;
|
|
143
|
+
if (runtime && typeof MessageChannel !== 'undefined') {
|
|
144
|
+
var channel = new MessageChannel();
|
|
145
|
+
port = channel.port1;
|
|
146
|
+
port.onmessage = function (e) { if (e.data && e.data.kind === 'cookies') cookies = String(e.data.value); };
|
|
147
|
+
runtime.postMessage({ type: ${JSON.stringify(COOKIE_MESSAGE_TYPE)}, href: location.href }, '*', [channel.port2]);
|
|
148
|
+
}
|
|
149
|
+
function apply(value) {
|
|
150
|
+
var parts = value.split(';'), pair = parts[0], eq = pair.indexOf('=');
|
|
151
|
+
if (eq < 0) return;
|
|
152
|
+
var name = pair.slice(0, eq).trim(), remove = false;
|
|
153
|
+
if (!name) return;
|
|
154
|
+
for (var i = 1; i < parts.length; i++) {
|
|
155
|
+
var a = parts[i].trim(), k = a.split('=')[0].trim().toLowerCase(), v = a.slice(a.indexOf('=') + 1).trim();
|
|
156
|
+
if (k === 'httponly') return;
|
|
157
|
+
if (k === 'max-age' && /^-?\\d+$/.test(v) && Number(v) <= 0) remove = true;
|
|
158
|
+
if (k === 'expires' && Date.parse(v) <= Date.now()) remove = true;
|
|
159
|
+
}
|
|
160
|
+
var list = cookies ? cookies.split('; ').filter(function (c) { return c.slice(0, c.indexOf('=')) !== name; }) : [];
|
|
161
|
+
if (!remove) list.push(name + '=' + pair.slice(eq + 1).trim());
|
|
162
|
+
cookies = list.join('; ');
|
|
163
|
+
}
|
|
164
|
+
try {
|
|
165
|
+
Object.defineProperty(document, 'cookie', {
|
|
166
|
+
configurable: true,
|
|
167
|
+
get: function () { return cookies; },
|
|
168
|
+
set: function (value) { value = String(value); apply(value); if (port) port.postMessage({ kind: 'set-cookie', value: value }); },
|
|
169
|
+
});
|
|
170
|
+
} catch (_) {}
|
|
171
|
+
})();</script>`;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const HEAD_OPEN = /<head(?:\s[^>]*)?>/i;
|
|
175
|
+
const HTML_OPEN = /<html(?:\s[^>]*)?>/i;
|
|
176
|
+
const DOCTYPE = /<!doctype[^>]*>/i;
|
|
177
|
+
/** Content past which `<head>` can no longer appear. */
|
|
178
|
+
const BODY_STARTED = /<(?:body|script|link|meta|style|title|div|p)[\s>/]/i;
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Where to inject the bridge into a streamed document, from its first bytes:
|
|
182
|
+
* just after `<head …>`, else after `<html …>` or the doctype (never before the
|
|
183
|
+
* doctype, which would switch the page to quirks mode), else the start.
|
|
184
|
+
* Undefined while the prefix is too short to tell; pass `complete` at the end of the body.
|
|
185
|
+
*/
|
|
186
|
+
export function bridgeInsertionPoint(prefix: string, complete = false): number | undefined {
|
|
187
|
+
const head = HEAD_OPEN.exec(prefix);
|
|
188
|
+
if (head) return head.index + head[0].length;
|
|
189
|
+
if (!complete && !BODY_STARTED.test(prefix) && prefix.length < 4096) return undefined;
|
|
190
|
+
const html = HTML_OPEN.exec(prefix);
|
|
191
|
+
if (html) return html.index + html[0].length;
|
|
192
|
+
const doctype = DOCTYPE.exec(prefix);
|
|
193
|
+
return doctype ? doctype.index + doctype[0].length : 0;
|
|
194
|
+
}
|
package/src/shell/ast.ts
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The shell's syntax tree. Words keep their quoting as segments, because
|
|
3
|
+
* expansion (variables, `$(…)`, `~`, globs, field splitting) happens at run
|
|
4
|
+
* time and depends on it.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export type Segment =
|
|
8
|
+
| { kind: 'text'; value: string; quoted: boolean }
|
|
9
|
+
| { kind: 'var'; name: string; quoted: boolean; op?: ':-' | '-' | ':=' | ':+'; arg?: Word }
|
|
10
|
+
| { kind: 'cmd'; source: string; quoted: boolean }
|
|
11
|
+
| { kind: 'tilde' };
|
|
12
|
+
export type Word = Segment[];
|
|
13
|
+
|
|
14
|
+
export type RedirectOp = '>' | '>>' | '<' | '2>' | '2>>' | '&>' | '2>&1' | '>&2' | '<<' | '<<-';
|
|
15
|
+
export interface Redirect {
|
|
16
|
+
op: RedirectOp;
|
|
17
|
+
target?: Word;
|
|
18
|
+
/** A here-document's body; expanded like a double-quoted string unless the delimiter was quoted. */
|
|
19
|
+
heredoc?: { body: Word };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface SimpleCommand {
|
|
23
|
+
type: 'simple';
|
|
24
|
+
assignments: Array<{ name: string; value: Word }>;
|
|
25
|
+
words: Word[];
|
|
26
|
+
redirects: Redirect[];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface IfCommand {
|
|
30
|
+
type: 'if';
|
|
31
|
+
clauses: Array<{ condition: Script; body: Script }>;
|
|
32
|
+
otherwise?: Script;
|
|
33
|
+
redirects: Redirect[];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface LoopCommand {
|
|
37
|
+
type: 'while' | 'until';
|
|
38
|
+
condition: Script;
|
|
39
|
+
body: Script;
|
|
40
|
+
redirects: Redirect[];
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface ForCommand {
|
|
44
|
+
type: 'for';
|
|
45
|
+
name: string;
|
|
46
|
+
/** Absent: iterate the positional parameters (`for x; do …`). */
|
|
47
|
+
items?: Word[];
|
|
48
|
+
body: Script;
|
|
49
|
+
redirects: Redirect[];
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface CaseCommand {
|
|
53
|
+
type: 'case';
|
|
54
|
+
subject: Word;
|
|
55
|
+
arms: Array<{ patterns: Word[]; body: Script }>;
|
|
56
|
+
redirects: Redirect[];
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** `{ list; }` runs in this shell; `( list )` in a copy of it. */
|
|
60
|
+
export interface GroupCommand {
|
|
61
|
+
type: 'group' | 'subshell';
|
|
62
|
+
body: Script;
|
|
63
|
+
redirects: Redirect[];
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface FunctionDefinition {
|
|
67
|
+
type: 'function';
|
|
68
|
+
name: string;
|
|
69
|
+
body: CompoundCommand;
|
|
70
|
+
redirects: Redirect[];
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export type CompoundCommand = IfCommand | LoopCommand | ForCommand | CaseCommand | GroupCommand;
|
|
74
|
+
export type Command = SimpleCommand | CompoundCommand | FunctionDefinition;
|
|
75
|
+
|
|
76
|
+
export interface Pipeline {
|
|
77
|
+
negate: boolean;
|
|
78
|
+
commands: Command[];
|
|
79
|
+
}
|
|
80
|
+
export interface AndOrList {
|
|
81
|
+
first: Pipeline;
|
|
82
|
+
rest: Array<{ op: '&&' | '||'; pipeline: Pipeline }>;
|
|
83
|
+
background: boolean;
|
|
84
|
+
}
|
|
85
|
+
export type Script = AndOrList[];
|