@howaboua/pi-browser 0.0.1

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.
Files changed (115) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/LICENSE +22 -0
  3. package/README.md +47 -0
  4. package/biome.json +31 -0
  5. package/changelog.ts +337 -0
  6. package/dist/index.d.ts +3 -0
  7. package/dist/index.js +82 -0
  8. package/dist/remote-worker.d.ts +2 -0
  9. package/dist/remote-worker.js +3005 -0
  10. package/dist/src/browser/artifacts.d.ts +13 -0
  11. package/dist/src/browser/artifacts.js +133 -0
  12. package/dist/src/browser/bounds.d.ts +4 -0
  13. package/dist/src/browser/bounds.js +129 -0
  14. package/dist/src/browser/config.d.ts +11 -0
  15. package/dist/src/browser/config.js +106 -0
  16. package/dist/src/browser/help.d.ts +1 -0
  17. package/dist/src/browser/help.js +27 -0
  18. package/dist/src/browser/launcher.d.ts +8 -0
  19. package/dist/src/browser/launcher.js +169 -0
  20. package/dist/src/browser/operation-executor.d.ts +9 -0
  21. package/dist/src/browser/operation-executor.js +112 -0
  22. package/dist/src/browser/operation.d.ts +92 -0
  23. package/dist/src/browser/operation.js +20 -0
  24. package/dist/src/browser/parse-operation.d.ts +6 -0
  25. package/dist/src/browser/parse-operation.js +248 -0
  26. package/dist/src/browser/remote-helper.d.ts +3 -0
  27. package/dist/src/browser/remote-helper.js +114 -0
  28. package/dist/src/browser/remote-process.d.ts +7 -0
  29. package/dist/src/browser/remote-process.js +78 -0
  30. package/dist/src/browser/remote.d.ts +4 -0
  31. package/dist/src/browser/remote.js +73 -0
  32. package/dist/src/browser/request.d.ts +8 -0
  33. package/dist/src/browser/request.js +80 -0
  34. package/dist/src/browser/routes.d.ts +16 -0
  35. package/dist/src/browser/routes.js +40 -0
  36. package/dist/src/browser/runtime.d.ts +17 -0
  37. package/dist/src/browser/runtime.js +61 -0
  38. package/dist/src/browser/settings.d.ts +2 -0
  39. package/dist/src/browser/settings.js +164 -0
  40. package/dist/src/browser/worker-server.d.ts +2 -0
  41. package/dist/src/browser/worker-server.js +241 -0
  42. package/dist/src/browser-parameters.d.ts +42 -0
  43. package/dist/src/browser-parameters.js +113 -0
  44. package/dist/src/browser-tool.d.ts +48 -0
  45. package/dist/src/browser-tool.js +71 -0
  46. package/dist/src/cdp/actions/click.d.ts +4 -0
  47. package/dist/src/cdp/actions/click.js +56 -0
  48. package/dist/src/cdp/actions/element.d.ts +22 -0
  49. package/dist/src/cdp/actions/element.js +126 -0
  50. package/dist/src/cdp/actions/page.d.ts +7 -0
  51. package/dist/src/cdp/actions/page.js +127 -0
  52. package/dist/src/cdp/actions/screenshot.d.ts +10 -0
  53. package/dist/src/cdp/actions/screenshot.js +96 -0
  54. package/dist/src/cdp/actions/selector.d.ts +2 -0
  55. package/dist/src/cdp/actions/selector.js +41 -0
  56. package/dist/src/cdp/actions/type.d.ts +3 -0
  57. package/dist/src/cdp/actions/type.js +138 -0
  58. package/dist/src/cdp/client.d.ts +20 -0
  59. package/dist/src/cdp/client.js +248 -0
  60. package/dist/src/cdp/discovery.d.ts +7 -0
  61. package/dist/src/cdp/discovery.js +153 -0
  62. package/dist/src/cdp/evaluate.d.ts +3 -0
  63. package/dist/src/cdp/evaluate.js +31 -0
  64. package/dist/src/cdp/pages.d.ts +3 -0
  65. package/dist/src/cdp/pages.js +40 -0
  66. package/dist/src/cdp/serial.d.ts +1 -0
  67. package/dist/src/cdp/serial.js +18 -0
  68. package/dist/src/cdp/session.d.ts +25 -0
  69. package/dist/src/cdp/session.js +246 -0
  70. package/dist/src/cdp/snapshot-contract.d.ts +32 -0
  71. package/dist/src/cdp/snapshot-contract.js +23 -0
  72. package/dist/src/cdp/snapshot.d.ts +3 -0
  73. package/dist/src/cdp/snapshot.js +205 -0
  74. package/dist/src/cdp/types.d.ts +20 -0
  75. package/dist/src/cdp/types.js +14 -0
  76. package/dist/src/cdp/url.d.ts +1 -0
  77. package/dist/src/cdp/url.js +12 -0
  78. package/index.ts +115 -0
  79. package/package.json +93 -0
  80. package/remote-worker.ts +58 -0
  81. package/src/browser/artifacts.ts +178 -0
  82. package/src/browser/bounds.ts +159 -0
  83. package/src/browser/config.ts +162 -0
  84. package/src/browser/help.ts +30 -0
  85. package/src/browser/launcher.ts +208 -0
  86. package/src/browser/operation-executor.ts +251 -0
  87. package/src/browser/operation.ts +105 -0
  88. package/src/browser/parse-operation.ts +272 -0
  89. package/src/browser/remote-helper.ts +137 -0
  90. package/src/browser/remote-process.ts +85 -0
  91. package/src/browser/remote.ts +120 -0
  92. package/src/browser/request.ts +95 -0
  93. package/src/browser/routes.ts +69 -0
  94. package/src/browser/runtime.ts +84 -0
  95. package/src/browser/settings.ts +219 -0
  96. package/src/browser/worker-server.ts +274 -0
  97. package/src/browser-parameters.ts +118 -0
  98. package/src/browser-tool.ts +88 -0
  99. package/src/cdp/actions/click.ts +126 -0
  100. package/src/cdp/actions/element.ts +234 -0
  101. package/src/cdp/actions/page.ts +219 -0
  102. package/src/cdp/actions/screenshot.ts +176 -0
  103. package/src/cdp/actions/selector.ts +63 -0
  104. package/src/cdp/actions/type.ts +224 -0
  105. package/src/cdp/client.ts +286 -0
  106. package/src/cdp/discovery.ts +198 -0
  107. package/src/cdp/evaluate.ts +55 -0
  108. package/src/cdp/pages.ts +60 -0
  109. package/src/cdp/serial.ts +23 -0
  110. package/src/cdp/session.ts +345 -0
  111. package/src/cdp/snapshot-contract.ts +63 -0
  112. package/src/cdp/snapshot.ts +273 -0
  113. package/src/cdp/types.ts +49 -0
  114. package/src/cdp/url.ts +11 -0
  115. package/tsconfig.json +7 -0
@@ -0,0 +1,69 @@
1
+ import { hostname } from "node:os";
2
+ import {
3
+ type BrowserRouteConfig,
4
+ normalizeBrowserRouteConfig,
5
+ readBrowserRouteConfig,
6
+ } from "./config.js";
7
+
8
+ export interface BrowserRemoteCommand {
9
+ nodePath: string;
10
+ }
11
+
12
+ export interface BrowserRoute {
13
+ local: boolean;
14
+ name: string;
15
+ remote?: BrowserRemoteCommand;
16
+ }
17
+
18
+ export class BrowserRoutes {
19
+ readonly names: readonly string[];
20
+ private readonly routes: ReadonlyMap<string, BrowserRoute>;
21
+
22
+ constructor(routes: ReadonlyMap<string, BrowserRoute> = new Map()) {
23
+ this.routes = routes;
24
+ this.names = [...routes.keys()];
25
+ }
26
+
27
+ resolve(name: string): BrowserRoute {
28
+ const route = this.routes.get(name);
29
+ if (route) return route;
30
+ if (this.names.length === 0) {
31
+ throw new Error("Browser host routing is disabled");
32
+ }
33
+ throw new Error(`browser host must be one of: ${this.names.join(", ")}`);
34
+ }
35
+ }
36
+
37
+ function routesFromConfig(
38
+ config: BrowserRouteConfig,
39
+ currentHostname: string,
40
+ ): BrowserRoutes {
41
+ const shortHostname = currentHostname.split(".")[0] ?? currentHostname;
42
+ const currentName =
43
+ config.aliases[currentHostname] ??
44
+ config.aliases[shortHostname] ??
45
+ shortHostname;
46
+ const remote = {
47
+ nodePath: config.remoteNodePath,
48
+ };
49
+ const routes = new Map<string, BrowserRoute>();
50
+ for (const name of config.hosts) {
51
+ const local = currentName === name;
52
+ routes.set(name, local ? { name, local } : { name, local, remote });
53
+ }
54
+ return new BrowserRoutes(routes);
55
+ }
56
+
57
+ export function parseBrowserRoutes(
58
+ value: unknown,
59
+ currentHostname = hostname(),
60
+ ): BrowserRoutes {
61
+ return routesFromConfig(normalizeBrowserRouteConfig(value), currentHostname);
62
+ }
63
+
64
+ export function loadBrowserRoutes(
65
+ path?: string,
66
+ currentHostname = hostname(),
67
+ ): BrowserRoutes {
68
+ return routesFromConfig(readBrowserRouteConfig(path), currentHostname);
69
+ }
@@ -0,0 +1,84 @@
1
+ import { BrowserCdpSession } from "../cdp/session.js";
2
+ import { pruneArtifacts } from "./artifacts.js";
3
+ import { browserHelp } from "./help.js";
4
+ import type { BrowserOperation } from "./operation.js";
5
+ import { BrowserOperationExecutor } from "./operation-executor.js";
6
+ import { executeRemoteBrowser } from "./remote.js";
7
+ import type { BrowserRequest } from "./request.js";
8
+ import { BrowserRoutes, loadBrowserRoutes } from "./routes.js";
9
+
10
+ export interface BrowserExecutionOptions {
11
+ signal?: AbortSignal | undefined;
12
+ onOperation?(operation: BrowserOperation, index: number, total: number): void;
13
+ }
14
+
15
+ export class BrowserRuntime {
16
+ readonly hosts: readonly string[];
17
+ private readonly cdp = new BrowserCdpSession();
18
+ private readonly operations = new BrowserOperationExecutor(this.cdp);
19
+ private readonly routes: BrowserRoutes;
20
+
21
+ constructor(routes = loadBrowserRoutes()) {
22
+ this.routes = routes;
23
+ this.hosts = routes.names;
24
+ }
25
+
26
+ async execute(
27
+ request: BrowserRequest,
28
+ options: BrowserExecutionOptions = {},
29
+ ): Promise<Record<string, unknown>> {
30
+ options.signal?.throwIfAborted();
31
+ await pruneArtifacts();
32
+ if ("help" in request) return browserHelp(this.hosts);
33
+ if (request.host) {
34
+ const route = this.routes.resolve(request.host);
35
+ if (!route.local) {
36
+ const first = request.operations[0];
37
+ if (first) {
38
+ options.onOperation?.(first, 0, request.operations.length);
39
+ }
40
+ const result = await executeRemoteBrowser(
41
+ route,
42
+ request.operations,
43
+ options.signal,
44
+ );
45
+ return { host: request.host, ...result };
46
+ }
47
+ }
48
+ const result = await this.executeLocal(request.operations, options);
49
+ return request.host ? { host: request.host, ...result } : result;
50
+ }
51
+
52
+ close(): void {
53
+ this.cdp.close();
54
+ }
55
+
56
+ private async executeLocal(
57
+ operations: BrowserOperation[],
58
+ options: BrowserExecutionOptions,
59
+ ): Promise<Record<string, unknown>> {
60
+ const results: Record<string, unknown>[] = [];
61
+ for (const [index, operation] of operations.entries()) {
62
+ try {
63
+ options.signal?.throwIfAborted();
64
+ options.onOperation?.(operation, index, operations.length);
65
+ results.push(await this.operations.execute(operation, options.signal));
66
+ } catch (error) {
67
+ throw new Error(
68
+ `batch failed at ${operation.action}[${index}] after ${results.length} completed operation(s): ${
69
+ error instanceof Error ? error.message : String(error)
70
+ }`,
71
+ );
72
+ }
73
+ }
74
+ const first = results[0];
75
+ if (results.length === 1 && first) return first;
76
+ return {
77
+ results: results.map((result, index) => ({
78
+ operation: operations[index]?.action ?? "unknown",
79
+ index,
80
+ ...result,
81
+ })),
82
+ };
83
+ }
84
+ }
@@ -0,0 +1,219 @@
1
+ import { hostname } from "node:os";
2
+ import type {
3
+ ExtensionAPI,
4
+ ExtensionCommandContext,
5
+ } from "@earendil-works/pi-coding-agent";
6
+ import {
7
+ type BrowserRouteConfig,
8
+ browserConfigPath,
9
+ defaultBrowserRouteConfig,
10
+ normalizeBrowserHostName,
11
+ normalizeBrowserRouteConfig,
12
+ readBrowserRouteConfig,
13
+ writeBrowserRouteConfig,
14
+ } from "./config.js";
15
+
16
+ const BACK = "Back";
17
+ const CANCEL = "Cancel";
18
+ const SAVE = "Save and reload";
19
+
20
+ function currentMachineRoute(config: BrowserRouteConfig): string | undefined {
21
+ const full = hostname();
22
+ const short = full.split(".")[0] ?? full;
23
+ return (
24
+ config.aliases[full] ??
25
+ config.aliases[short] ??
26
+ (config.hosts.includes(short) ? short : undefined)
27
+ );
28
+ }
29
+
30
+ function setCurrentMachineRoute(
31
+ config: BrowserRouteConfig,
32
+ name: string | undefined,
33
+ ): BrowserRouteConfig {
34
+ const full = hostname();
35
+ const short = full.split(".")[0] ?? full;
36
+ const aliases = { ...config.aliases };
37
+ delete aliases[full];
38
+ delete aliases[short];
39
+ if (name && name !== short) aliases[short] = name;
40
+ return { ...config, aliases };
41
+ }
42
+
43
+ function compactPath(value: string): string {
44
+ return value.length <= 48 ? value : `…${value.slice(-47)}`;
45
+ }
46
+
47
+ async function manageHosts(
48
+ ctx: ExtensionCommandContext,
49
+ initial: BrowserRouteConfig,
50
+ ): Promise<BrowserRouteConfig> {
51
+ let config = initial;
52
+ while (true) {
53
+ const removals = new Map(
54
+ config.hosts.map((host) => [`Remove · ${host}`, host]),
55
+ );
56
+ const selected = await ctx.ui.select("Browser hosts", [
57
+ "Add SSH host",
58
+ ...removals.keys(),
59
+ BACK,
60
+ ]);
61
+ if (!selected || selected === BACK) return config;
62
+ if (selected === "Add SSH host") {
63
+ const input = (await ctx.ui.input("SSH host name", "laptop"))?.trim();
64
+ if (!input) continue;
65
+ try {
66
+ const host = normalizeBrowserHostName(input, "SSH host name");
67
+ if (config.hosts.includes(host)) {
68
+ ctx.ui.notify(`Browser host ${host} already exists`, "warning");
69
+ continue;
70
+ }
71
+ config = { ...config, hosts: [...config.hosts, host] };
72
+ } catch (error) {
73
+ ctx.ui.notify(
74
+ error instanceof Error ? error.message : String(error),
75
+ "error",
76
+ );
77
+ }
78
+ continue;
79
+ }
80
+ const host = removals.get(selected);
81
+ if (!host) continue;
82
+ if (
83
+ !(await ctx.ui.confirm(
84
+ "Remove browser host",
85
+ `Remove ${host} from browser routing?`,
86
+ ))
87
+ ) {
88
+ continue;
89
+ }
90
+ const aliases = Object.fromEntries(
91
+ Object.entries(config.aliases).filter(([, target]) => target !== host),
92
+ );
93
+ config = {
94
+ ...config,
95
+ aliases,
96
+ hosts: config.hosts.filter((candidate) => candidate !== host),
97
+ };
98
+ }
99
+ }
100
+
101
+ async function manageAdvanced(
102
+ ctx: ExtensionCommandContext,
103
+ initial: BrowserRouteConfig,
104
+ ): Promise<BrowserRouteConfig> {
105
+ let config = initial;
106
+ while (true) {
107
+ const node = `Remote Node · ${compactPath(config.remoteNodePath)}`;
108
+ const selected = await ctx.ui.select("Advanced browser routing", [
109
+ node,
110
+ BACK,
111
+ ]);
112
+ if (!selected || selected === BACK) return config;
113
+ const value = (
114
+ await ctx.ui.input("Remote Node path", config.remoteNodePath)
115
+ )?.trim();
116
+ if (!value) continue;
117
+ try {
118
+ config = normalizeBrowserRouteConfig({
119
+ ...config,
120
+ remoteNodePath: value,
121
+ });
122
+ } catch (error) {
123
+ ctx.ui.notify(
124
+ error instanceof Error ? error.message : String(error),
125
+ "error",
126
+ );
127
+ }
128
+ }
129
+ }
130
+
131
+ async function initialConfig(
132
+ ctx: ExtensionCommandContext,
133
+ ): Promise<BrowserRouteConfig | undefined> {
134
+ try {
135
+ return readBrowserRouteConfig();
136
+ } catch (error) {
137
+ const message = error instanceof Error ? error.message : String(error);
138
+ const reset = await ctx.ui.confirm(
139
+ "Invalid browser settings",
140
+ `${message}\n\nReset them?`,
141
+ );
142
+ return reset ? defaultBrowserRouteConfig() : undefined;
143
+ }
144
+ }
145
+
146
+ async function openBrowserSettings(
147
+ ctx: ExtensionCommandContext,
148
+ ): Promise<void> {
149
+ let config = await initialConfig(ctx);
150
+ if (!config) return;
151
+ while (true) {
152
+ const hosts = `Hosts · ${config.hosts.length ? config.hosts.join(", ") : "local only"}`;
153
+ const machine = `This machine · ${currentMachineRoute(config) ?? "unnamed local"}`;
154
+ const selected = await ctx.ui.select("Browser settings", [
155
+ hosts,
156
+ machine,
157
+ "Advanced",
158
+ SAVE,
159
+ CANCEL,
160
+ ]);
161
+ if (!selected || selected === CANCEL) return;
162
+ if (selected === hosts) {
163
+ config = await manageHosts(ctx, config);
164
+ continue;
165
+ }
166
+ if (selected === machine) {
167
+ const route = await ctx.ui.select("This machine", [
168
+ "Unnamed local browser",
169
+ ...config.hosts,
170
+ ]);
171
+ if (route) {
172
+ config = setCurrentMachineRoute(
173
+ config,
174
+ route === "Unnamed local browser" ? undefined : route,
175
+ );
176
+ }
177
+ continue;
178
+ }
179
+ if (selected === "Advanced") {
180
+ config = await manageAdvanced(ctx, config);
181
+ continue;
182
+ }
183
+ try {
184
+ writeBrowserRouteConfig(config);
185
+ ctx.ui.notify("Browser settings saved; reloading Pi", "info");
186
+ await ctx.reload();
187
+ return;
188
+ } catch (error) {
189
+ ctx.ui.notify(
190
+ `Could not save browser settings: ${error instanceof Error ? error.message : String(error)}`,
191
+ "error",
192
+ );
193
+ }
194
+ }
195
+ }
196
+
197
+ export function registerBrowserCommand(pi: ExtensionAPI): void {
198
+ pi.registerCommand("browser", {
199
+ description: "Configure browser host routing",
200
+ handler: async (_args, ctx) => {
201
+ if (!ctx.hasUI || ctx.mode !== "tui") {
202
+ try {
203
+ const config = readBrowserRouteConfig();
204
+ ctx.ui.notify(
205
+ `Browser: ${config.hosts.length ? config.hosts.join(", ") : "local only"}\nConfig: ${browserConfigPath()}`,
206
+ "info",
207
+ );
208
+ } catch (error) {
209
+ ctx.ui.notify(
210
+ error instanceof Error ? error.message : String(error),
211
+ "error",
212
+ );
213
+ }
214
+ return;
215
+ }
216
+ await openBrowserSettings(ctx);
217
+ },
218
+ });
219
+ }
@@ -0,0 +1,274 @@
1
+ import { spawn } from "node:child_process";
2
+ import { chmod, lstat, mkdir, rm } from "node:fs/promises";
3
+ import { createConnection, createServer, type Socket } from "node:net";
4
+ import { tmpdir } from "node:os";
5
+ import { dirname, join } from "node:path";
6
+ import { StringDecoder } from "node:string_decoder";
7
+ import type { BrowserOperation } from "./operation.js";
8
+ import { isRecordValue, parseActionRequest } from "./parse-operation.js";
9
+ import { BrowserRoutes } from "./routes.js";
10
+ import { BrowserRuntime } from "./runtime.js";
11
+
12
+ const INPUT_LIMIT_BYTES = 8 * 1_024 * 1_024;
13
+ const START_TIMEOUT_MS = 5_000;
14
+ const IDLE_TIMEOUT_MS = 20 * 60 * 1_000;
15
+ const IS_WINDOWS = process.platform === "win32";
16
+
17
+ interface WorkerResponse {
18
+ error?: string;
19
+ ok: boolean;
20
+ result?: Record<string, unknown>;
21
+ }
22
+
23
+ function workerSocketPath(workerId: string): string {
24
+ if (IS_WINDOWS) return `\\\\.\\pipe\\pi-browser-worker-${workerId}`;
25
+ const directory = process.env["XDG_RUNTIME_DIR"]
26
+ ? join(process.env["XDG_RUNTIME_DIR"], "browser-tool")
27
+ : join(tmpdir(), `browser-tool-${process.getuid?.() ?? "user"}`);
28
+ return join(directory, `worker-${workerId}.sock`);
29
+ }
30
+
31
+ async function ensureWorkerSocketDirectory(workerId: string): Promise<void> {
32
+ if (IS_WINDOWS) return;
33
+ const directory = dirname(workerSocketPath(workerId));
34
+ await mkdir(directory, { recursive: true, mode: 0o700 });
35
+ const info = await lstat(directory);
36
+ const uid = process.getuid?.();
37
+ if (info.isSymbolicLink() || !info.isDirectory()) {
38
+ throw new Error(
39
+ `Browser worker socket directory is not a directory: ${directory}`,
40
+ );
41
+ }
42
+ if (uid === undefined || info.uid !== uid) {
43
+ throw new Error(
44
+ `Browser worker socket directory is not owned by this user: ${directory}`,
45
+ );
46
+ }
47
+ if ((info.mode & 0o077) !== 0) await chmod(directory, 0o700);
48
+ }
49
+
50
+ function parseWorkerOperations(input: string): BrowserOperation[] {
51
+ let value: unknown;
52
+ try {
53
+ value = JSON.parse(input);
54
+ } catch (error) {
55
+ throw new Error(
56
+ `worker input must be valid JSON: ${error instanceof Error ? error.message : String(error)}`,
57
+ );
58
+ }
59
+ if (!isRecordValue(value)) throw new Error("worker input must be an object");
60
+ const unknown = Object.keys(value).filter((key) => key !== "operations");
61
+ if (unknown.length > 0) {
62
+ throw new Error(`unknown worker field(s): ${unknown.join(", ")}`);
63
+ }
64
+ if (!Array.isArray(value["operations"]) || value["operations"].length === 0) {
65
+ throw new Error("worker operations must be a non-empty array");
66
+ }
67
+ return value["operations"].map((operation, index) => {
68
+ if (!isRecordValue(operation)) {
69
+ throw new Error(`worker operations[${index}] must be an object`);
70
+ }
71
+ const parsed = parseActionRequest(operation);
72
+ if (parsed.action === "help") {
73
+ throw new Error("help is not a worker operation");
74
+ }
75
+ return parsed;
76
+ });
77
+ }
78
+
79
+ function readLine(socket: Socket): Promise<string> {
80
+ return new Promise((resolveValue, reject) => {
81
+ let input = "";
82
+ let bytes = 0;
83
+ const decoder = new StringDecoder("utf8");
84
+ const cleanup = () => {
85
+ socket.off("data", onData);
86
+ socket.off("end", onEnd);
87
+ socket.off("error", onError);
88
+ };
89
+ const onError = (error: Error) => {
90
+ cleanup();
91
+ reject(error);
92
+ };
93
+ const onEnd = () => onError(new Error("Browser worker closed early"));
94
+ const onData = (chunk: Buffer) => {
95
+ bytes += chunk.length;
96
+ if (bytes > INPUT_LIMIT_BYTES) {
97
+ cleanup();
98
+ reject(new Error("Browser worker input exceeded 8 MiB"));
99
+ return;
100
+ }
101
+ input += decoder.write(chunk);
102
+ const newline = input.indexOf("\n");
103
+ if (newline < 0) return;
104
+ cleanup();
105
+ resolveValue(input.slice(0, newline));
106
+ };
107
+ socket.on("data", onData);
108
+ socket.once("end", onEnd);
109
+ socket.once("error", onError);
110
+ });
111
+ }
112
+
113
+ async function handleConnection(
114
+ socket: Socket,
115
+ runtime: BrowserRuntime,
116
+ ): Promise<void> {
117
+ const controller = new AbortController();
118
+ const abort = () =>
119
+ controller.abort(new Error("Browser worker requester disconnected"));
120
+ socket.once("close", abort);
121
+ socket.once("error", abort);
122
+ let response: WorkerResponse;
123
+ try {
124
+ const operations = parseWorkerOperations(await readLine(socket));
125
+ response = {
126
+ ok: true,
127
+ result: await runtime.execute(
128
+ { operations },
129
+ { signal: controller.signal },
130
+ ),
131
+ };
132
+ } catch (error) {
133
+ response = {
134
+ ok: false,
135
+ error: error instanceof Error ? error.message : String(error),
136
+ };
137
+ }
138
+ socket.off("close", abort);
139
+ socket.off("error", abort);
140
+ if (!socket.destroyed) socket.end(`${JSON.stringify(response)}\n`);
141
+ }
142
+
143
+ export async function serveBrowserWorker(workerId: string): Promise<void> {
144
+ const path = workerSocketPath(workerId);
145
+ await ensureWorkerSocketDirectory(workerId);
146
+ const runtime = new BrowserRuntime(new BrowserRoutes());
147
+ let ownsSocket = false;
148
+ const server = createServer((socket) => {
149
+ resetIdle();
150
+ void handleConnection(socket, runtime).finally(resetIdle);
151
+ });
152
+ let idleTimer: ReturnType<typeof setTimeout> | undefined;
153
+ const close = () => server.close();
154
+ const resetIdle = () => {
155
+ if (idleTimer) clearTimeout(idleTimer);
156
+ idleTimer = setTimeout(close, IDLE_TIMEOUT_MS);
157
+ idleTimer.unref?.();
158
+ };
159
+ process.once("SIGINT", close);
160
+ process.once("SIGTERM", close);
161
+ try {
162
+ await new Promise<void>((resolveValue, reject) => {
163
+ server.once("error", reject);
164
+ server.listen(path, () => {
165
+ ownsSocket = true;
166
+ server.off("error", reject);
167
+ resetIdle();
168
+ });
169
+ server.once("close", resolveValue);
170
+ });
171
+ } finally {
172
+ if (idleTimer) clearTimeout(idleTimer);
173
+ process.removeListener("SIGINT", close);
174
+ process.removeListener("SIGTERM", close);
175
+ runtime.close();
176
+ if (!IS_WINDOWS && ownsSocket) await rm(path, { force: true });
177
+ }
178
+ }
179
+
180
+ async function requestOnce(
181
+ input: string,
182
+ workerId: string,
183
+ signal?: AbortSignal,
184
+ ): Promise<WorkerResponse> {
185
+ if (signal?.aborted) {
186
+ return Promise.reject(
187
+ signal.reason ?? new Error("Browser worker request aborted"),
188
+ );
189
+ }
190
+ await ensureWorkerSocketDirectory(workerId);
191
+ if (signal?.aborted) {
192
+ throw signal.reason ?? new Error("Browser worker request aborted");
193
+ }
194
+ return new Promise((resolveValue, reject) => {
195
+ const socket = createConnection(workerSocketPath(workerId));
196
+ const abort = () => {
197
+ socket.destroy();
198
+ reject(signal?.reason ?? new Error("Browser worker request aborted"));
199
+ };
200
+ signal?.addEventListener("abort", abort, { once: true });
201
+ socket.once("connect", () => socket.write(`${input}\n`));
202
+ void readLine(socket).then(
203
+ (line) => {
204
+ signal?.removeEventListener("abort", abort);
205
+ socket.destroy();
206
+ try {
207
+ const response: unknown = JSON.parse(line);
208
+ if (!isRecordValue(response) || typeof response["ok"] !== "boolean") {
209
+ throw new Error("Browser worker returned an invalid response");
210
+ }
211
+ resolveValue(response as unknown as WorkerResponse);
212
+ } catch (error) {
213
+ reject(error);
214
+ }
215
+ },
216
+ (error) => {
217
+ signal?.removeEventListener("abort", abort);
218
+ socket.destroy();
219
+ reject(error);
220
+ },
221
+ );
222
+ });
223
+ }
224
+
225
+ function canStartWorker(error: unknown): boolean {
226
+ return (
227
+ error instanceof Error &&
228
+ "code" in error &&
229
+ (error.code === "ENOENT" || error.code === "ECONNREFUSED")
230
+ );
231
+ }
232
+
233
+ export async function requestBrowserWorker(
234
+ input: string,
235
+ entryPath: string,
236
+ workerId: string,
237
+ signal?: AbortSignal,
238
+ ): Promise<Record<string, unknown>> {
239
+ try {
240
+ const response = await requestOnce(input, workerId, signal);
241
+ if (!response.ok)
242
+ throw new Error(response.error ?? "Browser worker failed");
243
+ if (!response.result) throw new Error("Browser worker returned no result");
244
+ return response.result;
245
+ } catch (error) {
246
+ if (!canStartWorker(error)) throw error;
247
+ }
248
+ if (!IS_WINDOWS) await rm(workerSocketPath(workerId), { force: true });
249
+ const child = spawn(
250
+ process.execPath,
251
+ ["--preserve-symlinks-main", entryPath, "--daemon"],
252
+ { detached: true, stdio: "ignore" },
253
+ );
254
+ child.unref();
255
+ const deadline = Date.now() + START_TIMEOUT_MS;
256
+ let lastError: unknown;
257
+ while (Date.now() < deadline) {
258
+ try {
259
+ const response = await requestOnce(input, workerId, signal);
260
+ if (!response.ok)
261
+ throw new Error(response.error ?? "Browser worker failed");
262
+ if (!response.result)
263
+ throw new Error("Browser worker returned no result");
264
+ return response.result;
265
+ } catch (error) {
266
+ if (!canStartWorker(error)) throw error;
267
+ lastError = error;
268
+ await new Promise((resolveValue) => setTimeout(resolveValue, 50));
269
+ }
270
+ }
271
+ throw new Error(
272
+ `Browser worker did not start within ${START_TIMEOUT_MS}ms${lastError instanceof Error ? `: ${lastError.message}` : ""}`,
273
+ );
274
+ }