omowright 0.0.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +290 -2
  3. package/TOOLS.md +487 -0
  4. package/bin/omowright-cloak.mjs +112 -0
  5. package/package.json +57 -4
  6. package/presets/agent-events/SKILL.md +75 -0
  7. package/presets/captcha/SKILL.md +129 -0
  8. package/presets/chrome/SKILL.md +88 -0
  9. package/presets/cloak-bridge/SKILL.md +43 -0
  10. package/presets/network/SKILL.md +126 -0
  11. package/presets/visual-browse/SKILL.md +103 -0
  12. package/skills/omowright/SKILL.md +193 -0
  13. package/skills/omowright/references/1password.md +118 -0
  14. package/skills/omowright/references/browserskill.md +195 -0
  15. package/skills/omowright/references/eval-kernel.md +100 -0
  16. package/skills/omowright/references/frames-layers-human.md +123 -0
  17. package/skills/omowright/references/quickstart.md +109 -0
  18. package/skills/omowright/references/stealth.md +174 -0
  19. package/src/agent-tabs.js +179 -0
  20. package/src/aria-hidden.js +47 -0
  21. package/src/bridge-schemas.js +44 -0
  22. package/src/bridge-transport.js +83 -0
  23. package/src/browser-context.js +105 -0
  24. package/src/browser-process.js +127 -0
  25. package/src/bsk/browser-signals.js +90 -0
  26. package/src/bsk/browsers.js +114 -0
  27. package/src/bsk/connect.js +75 -0
  28. package/src/bsk/daemon-info.js +100 -0
  29. package/src/bsk/external-extension.js +110 -0
  30. package/src/bsk/identify-browser.js +88 -0
  31. package/src/bsk/install-cli.js +81 -0
  32. package/src/bsk/ipc-client.js +236 -0
  33. package/src/bsk/onboard.js +140 -0
  34. package/src/bsk/screenshot.js +49 -0
  35. package/src/bsk/session.js +131 -0
  36. package/src/bsk/snapshot.js +56 -0
  37. package/src/bsk/targets.js +25 -0
  38. package/src/captcha-wait.js +79 -0
  39. package/src/captcha.js +142 -0
  40. package/src/cdp-errors.js +23 -0
  41. package/src/cdp-methods.js +69 -0
  42. package/src/chrome-profile.js +176 -0
  43. package/src/chrome.js +194 -0
  44. package/src/cloak-profile.js +266 -0
  45. package/src/connection.js +234 -0
  46. package/src/console-events.js +12 -0
  47. package/src/cookies.js +39 -0
  48. package/src/core.js +1702 -0
  49. package/src/cua.js +74 -0
  50. package/src/dialog-policy.js +80 -0
  51. package/src/emulate.js +127 -0
  52. package/src/events.js +111 -0
  53. package/src/frames-snapshot.js +138 -0
  54. package/src/har.js +103 -0
  55. package/src/human-handoff.js +124 -0
  56. package/src/index.js +89 -0
  57. package/src/injected.js +3 -0
  58. package/src/instance-lock.js +74 -0
  59. package/src/instances.js +490 -0
  60. package/src/internal-capability.js +1 -0
  61. package/src/launch-endpoint.js +185 -0
  62. package/src/layers.js +138 -0
  63. package/src/llm.js +201 -0
  64. package/src/lock-backend-win32.js +54 -0
  65. package/src/lock-backend.js +81 -0
  66. package/src/native-host-win32.js +201 -0
  67. package/src/network-events.js +223 -0
  68. package/src/network-snoop.js +229 -0
  69. package/src/nul-frames.js +28 -0
  70. package/src/open-shadow-query.js +101 -0
  71. package/src/owner-only.js +196 -0
  72. package/src/page-bundle.js +1478 -0
  73. package/src/page-events.js +45 -0
  74. package/src/page-routes.js +94 -0
  75. package/src/page-setup.js +239 -0
  76. package/src/pipe.js +418 -0
  77. package/src/process-start-time.js +64 -0
  78. package/src/routes.js +256 -0
  79. package/src/running-browser.js +85 -0
  80. package/src/scroll-collect.js +73 -0
  81. package/src/serial-emitter.js +17 -0
  82. package/src/shared-connections.js +285 -0
  83. package/src/snapshot-diff.js +75 -0
  84. package/src/text-matching.js +101 -0
  85. package/src/trace.js +183 -0
  86. package/src/url-match.js +148 -0
  87. package/src/viewport.js +12 -0
@@ -0,0 +1,490 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import {
4
+ mkdir,
5
+ open,
6
+ readFile,
7
+ readdir,
8
+ rename,
9
+ unlink,
10
+ } from "node:fs/promises";
11
+ import os from "node:os";
12
+ import path from "node:path";
13
+ import { profileDirFromArgs, terminateChild } from "./browser-process.js";
14
+ import { openConnection } from "./connection.js";
15
+ import { isPidAlive, unlinkIfPresent, withLock } from "./instance-lock.js";
16
+ import {
17
+ assertLaunchedBrowser,
18
+ discoverLaunchedEndpoint,
19
+ snapshotActivePort,
20
+ } from "./launch-endpoint.js";
21
+ import { restrictToOwner } from "./owner-only.js";
22
+ import { acquireSharedConnection } from "./shared-connections.js";
23
+
24
+ const RECORD_VERSION = 2;
25
+ const DEFAULT_REGISTRY_ROOT = path.join(
26
+ os.homedir(),
27
+ ".local",
28
+ "share",
29
+ "omowright",
30
+ "instances",
31
+ );
32
+ const DEFAULT_PROBE_TIMEOUT_MS = 1_000;
33
+ const DEFAULT_LAUNCH_TIMEOUT_MS = 10_000;
34
+ const DEFAULT_CONNECT_TIMEOUT_MS = 10_000;
35
+ const BROWSER_CLOSE_TIMEOUT_MS = 2_000;
36
+ // Waiting for the lock has to outlast the slowest honest critical section
37
+ // (probe + launch + CDP attach); a shorter budget makes a second caller give up
38
+ // at the exact moment the first one is about to publish its record.
39
+ const LOCK_TIMEOUT_MARGIN_MS = 5_000;
40
+ // Same sum the per-call resolver below computes, for callers with no overrides.
41
+ const DEFAULT_LOCK_TIMEOUT_MS = resolveLockTimeoutMs({});
42
+
43
+ function normalizeName(name) {
44
+ if (
45
+ typeof name !== "string" ||
46
+ !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name)
47
+ ) {
48
+ throw new TypeError(
49
+ "instance name must start with a letter or number and contain only letters, numbers, dots, dashes, or underscores",
50
+ );
51
+ }
52
+ return name;
53
+ }
54
+
55
+ function registryPaths(registryRoot, name) {
56
+ const root = path.resolve(registryRoot ?? DEFAULT_REGISTRY_ROOT);
57
+ return {
58
+ root,
59
+ recordPath: path.join(root, `${name}.json`),
60
+ lockPath: path.join(root, `${name}.flock`),
61
+ };
62
+ }
63
+
64
+ async function ensureRegistryRoot(root) {
65
+ await mkdir(root, { recursive: true, mode: 0o700 });
66
+ await restrictToOwner(root, "directory");
67
+ }
68
+
69
+ function isRecord(value, expectedName) {
70
+ return (
71
+ value !== null &&
72
+ typeof value === "object" &&
73
+ value.version === RECORD_VERSION &&
74
+ value.name === expectedName &&
75
+ Number.isInteger(value.pid) &&
76
+ value.pid > 0 &&
77
+ typeof value.endpoint === "string" &&
78
+ value.endpoint.length > 0 &&
79
+ typeof value.webSocketDebuggerUrl === "string" &&
80
+ value.webSocketDebuggerUrl.length > 0 &&
81
+ (typeof value.profileDir === "string" || value.profileDir === null) &&
82
+ typeof value.browserPath === "string" &&
83
+ value.browserPath.length > 0 &&
84
+ typeof value.startedAt === "string" &&
85
+ !Number.isNaN(Date.parse(value.startedAt))
86
+ );
87
+ }
88
+
89
+ async function readRecord(recordPath, expectedName) {
90
+ let text;
91
+ try {
92
+ text = await readFile(recordPath, "utf8");
93
+ } catch (error) {
94
+ if (error?.code === "ENOENT") return { exists: false, record: null };
95
+ throw error;
96
+ }
97
+
98
+ try {
99
+ const record = JSON.parse(text);
100
+ return {
101
+ exists: true,
102
+ record: isRecord(record, expectedName) ? record : null,
103
+ };
104
+ } catch {
105
+ return { exists: true, record: null };
106
+ }
107
+ }
108
+
109
+ async function writeRecordAtomic(root, recordPath, record) {
110
+ const tempPath = path.join(
111
+ root,
112
+ `.${record.name}.${process.pid}.${randomUUID()}.tmp`,
113
+ );
114
+ let handle;
115
+ try {
116
+ handle = await open(tempPath, "wx", 0o600);
117
+ await handle.writeFile(`${JSON.stringify(record, null, 2)}\n`, "utf8");
118
+ await handle.close();
119
+ handle = null;
120
+ await restrictToOwner(tempPath, "file");
121
+ await rename(tempPath, recordPath);
122
+ await restrictToOwner(recordPath, "file");
123
+ } catch (error) {
124
+ await handle?.close().catch(() => {});
125
+ await unlink(tempPath).catch(() => {});
126
+ throw error;
127
+ }
128
+ }
129
+
130
+ function isConnectionRefused(error) {
131
+ for (let cause = error; cause; cause = cause?.cause) {
132
+ if (
133
+ cause.code === "ECONNREFUSED" ||
134
+ cause.code === "ENOTFOUND" ||
135
+ // Bun's fetch reports refused connections with this code.
136
+ cause.code === "ConnectionRefused"
137
+ ) {
138
+ return true;
139
+ }
140
+ }
141
+ return false;
142
+ }
143
+
144
+ async function probeEndpoint(endpoint, timeoutMs) {
145
+ const versionUrl = new URL("/json/version", endpoint);
146
+ const response = await fetch(versionUrl, {
147
+ signal: AbortSignal.timeout(timeoutMs),
148
+ });
149
+ if (!response.ok) {
150
+ throw new Error(
151
+ `CDP discovery request failed (${response.status} ${response.statusText})`,
152
+ );
153
+ }
154
+ const version = await response.json();
155
+ if (
156
+ typeof version?.webSocketDebuggerUrl !== "string" ||
157
+ version.webSocketDebuggerUrl.length === 0
158
+ ) {
159
+ throw new Error("CDP discovery response lacks webSocketDebuggerUrl");
160
+ }
161
+ return version;
162
+ }
163
+
164
+ function resolveConnectTimeoutMs(options) {
165
+ return options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
166
+ }
167
+
168
+ function resolveLockTimeoutMs(options) {
169
+ if (options.lockTimeoutMs !== undefined) return options.lockTimeoutMs;
170
+ return (
171
+ (options.launchTimeoutMs ?? DEFAULT_LAUNCH_TIMEOUT_MS) +
172
+ (options.probeTimeoutMs ?? resolveConnectTimeoutMs(options)) +
173
+ resolveConnectTimeoutMs(options) +
174
+ LOCK_TIMEOUT_MARGIN_MS
175
+ );
176
+ }
177
+
178
+ function nameLockOptions(options) {
179
+ return {
180
+ timeoutMs: resolveLockTimeoutMs(options),
181
+ };
182
+ }
183
+
184
+ // `/json/version` answering proves nothing about the WebSocket upgrade behind
185
+ // it, so the session handshake carries its own bound.
186
+ async function connectWithin(endpoint, options, timeoutMs) {
187
+ const pending = openConnection(endpoint, options);
188
+ let timer;
189
+ try {
190
+ return await Promise.race([
191
+ pending,
192
+ new Promise((_, reject) => {
193
+ timer = setTimeout(
194
+ () =>
195
+ reject(
196
+ new Error(
197
+ `timed out after ${timeoutMs}ms opening a CDP session on ${endpoint}`,
198
+ ),
199
+ ),
200
+ timeoutMs,
201
+ );
202
+ }),
203
+ ]);
204
+ } catch (error) {
205
+ // A session that lands after the bound would otherwise hold a live socket.
206
+ pending.then(
207
+ (connection) => connection.close().catch(() => {}),
208
+ () => {},
209
+ );
210
+ throw error;
211
+ } finally {
212
+ clearTimeout(timer);
213
+ }
214
+ }
215
+
216
+ async function removeOwnedRecord(recordPath, name, pid) {
217
+ const loaded = await readRecord(recordPath, name);
218
+ if (loaded.record?.pid !== pid) return;
219
+ await unlinkIfPresent(recordPath);
220
+ }
221
+
222
+ function connectionOptions(options, profileDir) {
223
+ const result = { ...(options.connectionOptions ?? {}) };
224
+ if (options.storageRoot !== undefined) result.storageRoot = options.storageRoot;
225
+ else if (result.storageRoot === undefined && profileDir) {
226
+ result.storageRoot = profileDir;
227
+ }
228
+ if (options.client !== undefined) {
229
+ result.client = {
230
+ ...(result.client ?? {}),
231
+ ...options.client,
232
+ };
233
+ }
234
+ // Part of the sharing key too: callers asking for different dialog policies
235
+ // never share one connection.
236
+ if (options.dialogPolicy !== undefined) result.dialogPolicy = options.dialogPolicy;
237
+ return result;
238
+ }
239
+
240
+ // Asked over CDP first, as the pipe transport does: on Windows no signal can
241
+ // ask a browser to quit, and Chrome cleans up only on a clean quit. Only a live
242
+ // browser on a live socket is asked: CdpClient.send would otherwise reconnect
243
+ // through the recorded port, which is not an identity (another process may
244
+ // hold it by now). The connection is closed as soon as the request is answered,
245
+ // before the quitting browser drops its socket: a drop on an open client starts
246
+ // its auto-reconnect loop, which would keep the caller's process alive. Then,
247
+ // like the pipe transport, the browser gets a bounded wait to exit before
248
+ // terminateChild steps in.
249
+ async function askBrowserToQuit(connection, child, disconnect) {
250
+ if (child.exitCode !== null || child.signalCode !== null || !connection.cdp.isConnected) {
251
+ await disconnect();
252
+ return false;
253
+ }
254
+ const exited = new Promise((resolve) => child.once("exit", resolve));
255
+ const quitRequested = await Promise.race([
256
+ connection.cdp
257
+ .send("Browser.close", undefined, undefined, { timeoutMs: BROWSER_CLOSE_TIMEOUT_MS })
258
+ .then(() => true, () => false),
259
+ exited.then(() => true),
260
+ ]);
261
+ await disconnect();
262
+ if (child.exitCode === null && child.signalCode === null) {
263
+ let timer;
264
+ await Promise.race([
265
+ exited,
266
+ new Promise((resolve) => { timer = setTimeout(resolve, BROWSER_CLOSE_TIMEOUT_MS); }),
267
+ ]);
268
+ clearTimeout(timer);
269
+ }
270
+ return quitRequested;
271
+ }
272
+
273
+ async function launchNamed(
274
+ name,
275
+ { root, recordPath, lockPath },
276
+ options,
277
+ ) {
278
+ if (typeof options.browserPath !== "string" || options.browserPath.length === 0) {
279
+ throw new TypeError(
280
+ `connectNamed("${name}") requires browserPath when no healthy instance is registered`,
281
+ );
282
+ }
283
+ const browserArgs = [...(options.browserArgs ?? [])];
284
+ const profileDir = options.profileDir
285
+ ? path.resolve(options.profileDir)
286
+ : profileDirFromArgs(browserArgs);
287
+ const previousActivePort = await snapshotActivePort(profileDir);
288
+ const child = spawn(
289
+ options.browserPath,
290
+ [
291
+ ...browserArgs,
292
+ "--remote-debugging-address=127.0.0.1",
293
+ "--remote-debugging-port=0",
294
+ ],
295
+ {
296
+ // A named browser is shared through the registry, so it has to outlive
297
+ // the process that launched it. On Windows libuv puts every non-detached
298
+ // child in a kill-on-close job object, which kills the browser the
299
+ // moment its launcher exits (#90); detached keeps it out of that job
300
+ // (DETACHED_PROCESS also gives a console-subsystem browser no console).
301
+ // No windowsHide: it would start a headful browser's window hidden.
302
+ ...(process.platform === "win32" ? { detached: true } : {}),
303
+ ...(options.spawnOptions ?? {}),
304
+ stdio: ["ignore", "ignore", "pipe"],
305
+ },
306
+ );
307
+
308
+ let connection;
309
+ try {
310
+ const launchTimeoutMs = options.launchTimeoutMs ?? DEFAULT_LAUNCH_TIMEOUT_MS;
311
+ const report = await discoverLaunchedEndpoint(child, {
312
+ profileDir,
313
+ timeoutMs: launchTimeoutMs,
314
+ previousActivePort,
315
+ });
316
+ const { endpoint } = report;
317
+ // The browser's own WebSocket URL carries its GUID: recording it makes a
318
+ // later attach prove it reached this browser and not whatever else ends up
319
+ // on the port once this pid is gone.
320
+ const { webSocketDebuggerUrl } = await probeEndpoint(
321
+ endpoint,
322
+ launchTimeoutMs,
323
+ );
324
+ assertLaunchedBrowser(child, report, webSocketDebuggerUrl);
325
+ connection = await connectWithin(
326
+ endpoint,
327
+ connectionOptions(options, profileDir),
328
+ resolveConnectTimeoutMs(options),
329
+ );
330
+ const record = {
331
+ version: RECORD_VERSION,
332
+ name,
333
+ pid: child.pid,
334
+ endpoint,
335
+ webSocketDebuggerUrl,
336
+ profileDir,
337
+ browserPath: path.resolve(options.browserPath),
338
+ startedAt: new Date().toISOString(),
339
+ };
340
+ await writeRecordAtomic(root, recordPath, record);
341
+ connection.browserProcess = child;
342
+ const disconnect = connection.close.bind(connection);
343
+ connection.close = async () => {
344
+ let failure;
345
+ const quitRequested = await askBrowserToQuit(connection, child, async () => {
346
+ try {
347
+ await disconnect();
348
+ } catch (error) {
349
+ failure = error;
350
+ }
351
+ });
352
+ await terminateChild(child, { quitRequested });
353
+ // The browser this record points at is gone, so the record goes with it
354
+ // instead of waiting for the next caller to clean it up.
355
+ try {
356
+ await withLock(lockPath, nameLockOptions(options), () =>
357
+ removeOwnedRecord(recordPath, name, child.pid),
358
+ );
359
+ } catch (error) {
360
+ failure ??= error;
361
+ }
362
+ if (failure) throw failure;
363
+ };
364
+ return connection;
365
+ } catch (error) {
366
+ await connection?.close().catch(() => {});
367
+ await terminateChild(child);
368
+ throw error;
369
+ }
370
+ }
371
+
372
+ export async function withEngineLock(registryRoot, engineKey, run) {
373
+ const root = path.resolve(registryRoot ?? DEFAULT_REGISTRY_ROOT);
374
+ await ensureRegistryRoot(root);
375
+ const digest = createHash("sha256")
376
+ .update(path.resolve(engineKey))
377
+ .digest("hex")
378
+ .slice(0, 16);
379
+ const lockPath = path.join(root, `_engine-${digest}.flock`);
380
+ return withLock(
381
+ lockPath,
382
+ { timeoutMs: DEFAULT_LOCK_TIMEOUT_MS },
383
+ run,
384
+ );
385
+ }
386
+
387
+ export async function connectNamed(name, options = {}) {
388
+ const normalizedName = normalizeName(name);
389
+ const paths = registryPaths(options.registryRoot, normalizedName);
390
+ await ensureRegistryRoot(paths.root);
391
+ return withLock(paths.lockPath, nameLockOptions(options), () =>
392
+ attachOrLaunch(normalizedName, paths, options),
393
+ );
394
+ }
395
+
396
+ async function attachOrLaunch(normalizedName, paths, options) {
397
+ const loaded = await readRecord(paths.recordPath, normalizedName);
398
+ if (loaded.record) {
399
+ await restrictToOwner(paths.recordPath, "file");
400
+ if (isPidAlive(loaded.record.pid)) {
401
+ let version = null;
402
+ try {
403
+ version = await probeEndpoint(
404
+ loaded.record.endpoint,
405
+ // Attaching is not a one-second listInstances health check. A
406
+ // healthy holder may still be busy finishing startup under load.
407
+ options.probeTimeoutMs ?? resolveConnectTimeoutMs(options),
408
+ );
409
+ } catch (error) {
410
+ if (!isConnectionRefused(error)) {
411
+ throw new Error(
412
+ `unresponsive holder "${normalizedName}" pid ${loaded.record.pid} endpoint ${loaded.record.endpoint}: ${error.message}`,
413
+ { cause: error },
414
+ );
415
+ }
416
+ // A live pid whose recorded debug port refuses connections is a
417
+ // reused pid, not a holder: the record is stale and the launch
418
+ // below reclaims it.
419
+ }
420
+ // A pid that came back and a port any local process can rebind are
421
+ // not an identity. Only the recorded WebSocket URL (it carries the
422
+ // browser GUID) says this is our browser; anything else answering
423
+ // there is a stranger, so the record is stale, not a holder.
424
+ if (
425
+ version?.webSocketDebuggerUrl === loaded.record.webSocketDebuggerUrl
426
+ ) {
427
+ // Connecting to the recorded GUID URL, not the port, keeps the shared
428
+ // connection's auto-reconnect from landing on a different browser.
429
+ const { webSocketDebuggerUrl } = loaded.record;
430
+ const timeoutMs = resolveConnectTimeoutMs(options);
431
+ try {
432
+ return await acquireSharedConnection(
433
+ webSocketDebuggerUrl,
434
+ connectionOptions(options, loaded.record.profileDir),
435
+ {
436
+ open: (shared) =>
437
+ connectWithin(webSocketDebuggerUrl, shared, timeoutMs),
438
+ timeoutMs,
439
+ },
440
+ );
441
+ } catch (error) {
442
+ throw new Error(
443
+ `unresponsive holder "${normalizedName}" pid ${loaded.record.pid} endpoint ${loaded.record.endpoint}: ${error.message}`,
444
+ { cause: error },
445
+ );
446
+ }
447
+ }
448
+ }
449
+ }
450
+
451
+ if (loaded.exists) {
452
+ await unlink(paths.recordPath).catch((error) => {
453
+ if (error?.code !== "ENOENT") throw error;
454
+ });
455
+ }
456
+ return await launchNamed(normalizedName, paths, options);
457
+ }
458
+
459
+ export async function listInstances(options = {}) {
460
+ const root = path.resolve(options.registryRoot ?? DEFAULT_REGISTRY_ROOT);
461
+ await ensureRegistryRoot(root);
462
+ const entries = await readdir(root, { withFileTypes: true });
463
+ const records = await Promise.all(
464
+ entries
465
+ .filter((entry) => entry.isFile() && entry.name.endsWith(".json"))
466
+ .map(async (entry) => {
467
+ const expectedName = entry.name.slice(0, -".json".length);
468
+ const recordPath = path.join(root, entry.name);
469
+ const loaded = await readRecord(recordPath, expectedName);
470
+ if (!loaded.record) return null;
471
+ await restrictToOwner(recordPath, "file");
472
+ const alive = isPidAlive(loaded.record.pid);
473
+ let responsive = false;
474
+ if (alive) {
475
+ responsive = await probeEndpoint(
476
+ loaded.record.endpoint,
477
+ options.probeTimeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS,
478
+ ).then(
479
+ (version) =>
480
+ version.webSocketDebuggerUrl === loaded.record.webSocketDebuggerUrl,
481
+ () => false,
482
+ );
483
+ }
484
+ return { ...loaded.record, alive, responsive };
485
+ }),
486
+ );
487
+ return records
488
+ .filter((record) => record !== null)
489
+ .sort((left, right) => left.name.localeCompare(right.name));
490
+ }
@@ -0,0 +1 @@
1
+ export const targetCreationCapability = Symbol("omowright.targetCreationCapability");
@@ -0,0 +1,185 @@
1
+ import { watch } from "node:fs";
2
+ import { readFile, stat } from "node:fs/promises";
3
+ import path from "node:path";
4
+
5
+ // fs.watch can drop or delay directory events on a loaded host (seconds, or
6
+ // never), so the file is also re-read on this interval until the launch settles.
7
+ const ACTIVE_PORT_POLL_MS = 100;
8
+
9
+ function httpEndpointFromWebSocket(webSocketUrl) {
10
+ const endpoint = new URL(webSocketUrl);
11
+ endpoint.protocol = endpoint.protocol === "wss:" ? "https:" : "http:";
12
+ endpoint.pathname = "/";
13
+ endpoint.search = "";
14
+ endpoint.hash = "";
15
+ return endpoint.toString().replace(/\/$/, "");
16
+ }
17
+
18
+ // Chromium writes `<port>\n/devtools/browser/<guid>`; the second line names the browser.
19
+ function parseActivePort(text) {
20
+ const [portLine, browserPath] = text.trim().split(/\r?\n/);
21
+ const port = Number(portLine);
22
+ if (!Number.isInteger(port) || port < 1 || port > 65_535) return null;
23
+ return {
24
+ endpoint: `http://127.0.0.1:${port}`,
25
+ browserPath: browserPath?.trim() || null,
26
+ };
27
+ }
28
+
29
+ function activePortIdentity(info) {
30
+ return { ino: info.ino, mtimeMs: info.mtimeMs, size: info.size };
31
+ }
32
+
33
+ // A DevToolsActivePort that is already there before the spawn was written by
34
+ // an earlier run or by another browser on the same profile (#74). Taken before
35
+ // the spawn, so discovery can tell it from the file the new browser writes.
36
+ // The bytes are kept as well as the identity: an identity change does not prove
37
+ // the bytes changed (Linux updates mtime before it copies a write's data, and a
38
+ // touch or an in-place rewrite moves it too), and stale bytes name another
39
+ // browser whose id the launch check would then compare against itself (#107).
40
+ export async function snapshotActivePort(profileDir) {
41
+ if (!profileDir) return null;
42
+ const activePortPath = path.join(profileDir, "DevToolsActivePort");
43
+ try {
44
+ const identity = activePortIdentity(await stat(activePortPath));
45
+ return { ...identity, text: await readFile(activePortPath, "utf8") };
46
+ } catch (error) {
47
+ if (error?.code === "ENOENT") return null;
48
+ throw error;
49
+ }
50
+ }
51
+
52
+ function isSameFile(info, previous) {
53
+ return (
54
+ previous !== null &&
55
+ info.ino === previous.ino &&
56
+ info.mtimeMs === previous.mtimeMs &&
57
+ info.size === previous.size
58
+ );
59
+ }
60
+
61
+ // The endpoint is the launched browser's only if it answers with the browser id
62
+ // that browser reported, and the browser is still the one we spawned.
63
+ export function assertLaunchedBrowser(child, report, webSocketDebuggerUrl) {
64
+ if (child.exitCode !== null || child.signalCode !== null) {
65
+ throw new Error(
66
+ `browser exited before its DevTools endpoint ${report.endpoint} could be verified`,
67
+ );
68
+ }
69
+ const answered = new URL(webSocketDebuggerUrl).pathname;
70
+ if (report.browserPath === null || answered !== report.browserPath) {
71
+ throw new Error(
72
+ `DevTools endpoint ${report.endpoint} answers as ${answered}, not as the launched browser (${report.browserPath ?? "no browser id reported"})`,
73
+ );
74
+ }
75
+ }
76
+
77
+ export async function discoverLaunchedEndpoint(
78
+ child,
79
+ { profileDir, timeoutMs, previousActivePort = null } = {},
80
+ ) {
81
+ const activePortPath = profileDir
82
+ ? path.join(profileDir, "DevToolsActivePort")
83
+ : null;
84
+
85
+ return new Promise((resolve, reject) => {
86
+ let settled = false;
87
+ let stderr = "";
88
+ let activePortWatcher;
89
+ let activePortReading = false;
90
+ let activePortChangedWhileReading = false;
91
+ const cleanups = [];
92
+
93
+ const finish = (error, endpoint) => {
94
+ if (settled) return;
95
+ settled = true;
96
+ for (const cleanup of cleanups.splice(0)) cleanup();
97
+ activePortWatcher?.close();
98
+ if (error) reject(error);
99
+ else resolve(endpoint);
100
+ };
101
+
102
+ const readActivePort = async () => {
103
+ const info = await stat(activePortPath);
104
+ if (isSameFile(activePortIdentity(info), previousActivePort)) return;
105
+ const text = await readFile(activePortPath, "utf8");
106
+ if (previousActivePort !== null && text === previousActivePort.text) return;
107
+ const report = parseActivePort(text);
108
+ if (report) finish(null, report);
109
+ };
110
+
111
+ const tryActivePort = async () => {
112
+ if (!activePortPath || settled) return;
113
+ if (activePortReading) {
114
+ activePortChangedWhileReading = true;
115
+ return;
116
+ }
117
+ activePortReading = true;
118
+ try {
119
+ do {
120
+ activePortChangedWhileReading = false;
121
+ await readActivePort();
122
+ } while (activePortChangedWhileReading && !settled);
123
+ } catch (error) {
124
+ if (error?.code !== "ENOENT") finish(error);
125
+ } finally {
126
+ activePortReading = false;
127
+ }
128
+ };
129
+
130
+ const onStderr = (chunk) => {
131
+ stderr = `${stderr}${chunk}`.slice(-16_384);
132
+ const match = /DevTools listening on (ws:\/\/\S+)/.exec(stderr);
133
+ if (match) {
134
+ finish(null, {
135
+ endpoint: httpEndpointFromWebSocket(match[1]),
136
+ browserPath: new URL(match[1]).pathname,
137
+ });
138
+ }
139
+ else void tryActivePort();
140
+ };
141
+ const onError = (error) => finish(error);
142
+ const onExit = (code, signal) => {
143
+ finish(
144
+ new Error(
145
+ `browser exited before exposing DevTools (code ${code}, signal ${signal ?? "none"})${stderr ? `\n${stderr}` : ""}`,
146
+ ),
147
+ );
148
+ };
149
+ child.stderr.setEncoding("utf8");
150
+ child.stderr.on("data", onStderr);
151
+ child.once("error", onError);
152
+ child.once("exit", onExit);
153
+ cleanups.push(() => child.stderr.off("data", onStderr));
154
+ cleanups.push(() => child.off("error", onError));
155
+ cleanups.push(() => child.off("exit", onExit));
156
+
157
+ if (activePortPath) {
158
+ try {
159
+ activePortWatcher = watch(profileDir, (event, filename) => {
160
+ if (
161
+ (event === "rename" || event === "change") &&
162
+ (!filename ||
163
+ filename.toString() === path.basename(activePortPath))
164
+ ) {
165
+ void tryActivePort();
166
+ }
167
+ });
168
+ } catch (error) {
169
+ if (error?.code !== "ENOENT") finish(error);
170
+ }
171
+ void tryActivePort();
172
+ const poll = setInterval(() => void tryActivePort(), ACTIVE_PORT_POLL_MS);
173
+ cleanups.push(() => clearInterval(poll));
174
+ }
175
+
176
+ const timeout = setTimeout(() => {
177
+ finish(
178
+ new Error(
179
+ `browser did not expose a DevTools endpoint within ${timeoutMs}ms${stderr ? `\n${stderr}` : ""}`,
180
+ ),
181
+ );
182
+ }, timeoutMs);
183
+ cleanups.push(() => clearTimeout(timeout));
184
+ });
185
+ }