@monoes/monobrowse 1.0.25 → 1.0.27

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 (67) hide show
  1. package/dist/src/__tests__/browser-launch.test.d.ts +3 -2
  2. package/dist/src/__tests__/browser-launch.test.d.ts.map +1 -1
  3. package/dist/src/__tests__/browser-launch.test.js +71 -6
  4. package/dist/src/__tests__/browser-launch.test.js.map +1 -1
  5. package/dist/src/__tests__/launch-close-settle.test.d.ts +6 -0
  6. package/dist/src/__tests__/launch-close-settle.test.d.ts.map +1 -1
  7. package/dist/src/__tests__/launch-close-settle.test.js +29 -8
  8. package/dist/src/__tests__/launch-close-settle.test.js.map +1 -1
  9. package/dist/src/browser/actions-eval.d.ts +8 -0
  10. package/dist/src/browser/actions-eval.d.ts.map +1 -0
  11. package/dist/src/browser/actions-eval.js +72 -0
  12. package/dist/src/browser/actions-eval.js.map +1 -0
  13. package/dist/src/browser/actions-form.d.ts +10 -0
  14. package/dist/src/browser/actions-form.d.ts.map +1 -0
  15. package/dist/src/browser/actions-form.js +133 -0
  16. package/dist/src/browser/actions-form.js.map +1 -0
  17. package/dist/src/browser/actions-keyboard.d.ts +7 -0
  18. package/dist/src/browser/actions-keyboard.d.ts.map +1 -0
  19. package/dist/src/browser/actions-keyboard.js +131 -0
  20. package/dist/src/browser/actions-keyboard.js.map +1 -0
  21. package/dist/src/browser/actions-mouse.d.ts +11 -0
  22. package/dist/src/browser/actions-mouse.d.ts.map +1 -0
  23. package/dist/src/browser/actions-mouse.js +105 -0
  24. package/dist/src/browser/actions-mouse.js.map +1 -0
  25. package/dist/src/browser/actions.d.ts +12 -28
  26. package/dist/src/browser/actions.d.ts.map +1 -1
  27. package/dist/src/browser/actions.js +12 -434
  28. package/dist/src/browser/actions.js.map +1 -1
  29. package/dist/src/browser/browser-discovery.d.ts +26 -0
  30. package/dist/src/browser/browser-discovery.d.ts.map +1 -0
  31. package/dist/src/browser/browser-discovery.js +113 -0
  32. package/dist/src/browser/browser-discovery.js.map +1 -0
  33. package/dist/src/browser/browser-launch.d.ts +3 -0
  34. package/dist/src/browser/browser-launch.d.ts.map +1 -0
  35. package/dist/src/browser/browser-launch.js +324 -0
  36. package/dist/src/browser/browser-launch.js.map +1 -0
  37. package/dist/src/browser/browser-lifecycle.d.ts +52 -0
  38. package/dist/src/browser/browser-lifecycle.d.ts.map +1 -0
  39. package/dist/src/browser/browser-lifecycle.js +233 -0
  40. package/dist/src/browser/browser-lifecycle.js.map +1 -0
  41. package/dist/src/browser/browser-page.d.ts +13 -0
  42. package/dist/src/browser/browser-page.d.ts.map +1 -0
  43. package/dist/src/browser/browser-page.js +179 -0
  44. package/dist/src/browser/browser-page.js.map +1 -0
  45. package/dist/src/browser/browser-state.d.ts +7 -0
  46. package/dist/src/browser/browser-state.d.ts.map +1 -0
  47. package/dist/src/browser/browser-state.js +19 -0
  48. package/dist/src/browser/browser-state.js.map +1 -0
  49. package/dist/src/browser/browser.d.ts +5 -68
  50. package/dist/src/browser/browser.d.ts.map +1 -1
  51. package/dist/src/browser/browser.js +9 -794
  52. package/dist/src/browser/browser.js.map +1 -1
  53. package/dist/tsconfig.tsbuildinfo +1 -1
  54. package/package.json +1 -1
  55. package/src/__tests__/browser-launch.test.ts +78 -6
  56. package/src/__tests__/launch-close-settle.test.ts +32 -10
  57. package/src/browser/actions-eval.ts +118 -0
  58. package/src/browser/actions-form.ts +218 -0
  59. package/src/browser/actions-keyboard.ts +171 -0
  60. package/src/browser/actions-mouse.ts +212 -0
  61. package/src/browser/actions.ts +37 -712
  62. package/src/browser/browser-discovery.ts +116 -0
  63. package/src/browser/browser-launch.ts +358 -0
  64. package/src/browser/browser-lifecycle.ts +238 -0
  65. package/src/browser/browser-page.ts +213 -0
  66. package/src/browser/browser-state.ts +21 -0
  67. package/src/browser/browser.ts +17 -859
@@ -1,795 +1,10 @@
1
- import { execSync, spawn } from 'node:child_process';
2
- import { existsSync, readFileSync, rmSync } from 'node:fs';
3
- import { connect } from 'node:net';
4
- import { tmpdir } from 'node:os';
5
- import { join } from 'node:path';
6
- import { CdpClient, fetchNewTarget, fetchTargets } from './cdp.js';
7
- import { enableConsoleCapture, setupConsoleCapture } from './console-log.js';
8
- import { setupDialogAutoHandling } from './dialog.js';
9
- import { listSessionRecords, loadSessionRecord, removeSessionRecord, } from './ref-cache.js';
10
- import { CHROME_EXECUTABLES } from './types.js';
11
- const DEFAULT_PORT = 9222;
12
- const LAUNCH_TIMEOUT = 10_000;
13
- const POLL_INTERVAL = 200;
14
- const BROWSER_CLOSE_TIMEOUT_MS = 3000;
15
- // How long closeBrowser() waits for the process to actually disappear before
16
- // forcing it, and again after forcing. Bounded so a wedged Chrome cannot hang
17
- // a caller indefinitely.
18
- const PROCESS_EXIT_TIMEOUT_MS = 5000;
19
- const PROCESS_EXIT_POLL_MS = 50;
20
- // A cross-process persisted PID older than this is not trusted for the
21
- // SIGKILL fallback in closeBrowser() — see the call site for why.
22
- const PERSISTED_PID_MAX_AGE_MS = 24 * 60 * 60 * 1000;
23
- // A browser WE launched that has had no targets for longer than this is
24
- // reaped at the next launch/attach — see reapIdleLaunchedBrowser().
25
- const IDLE_REAP_AFTER_MS = 30 * 60 * 1000;
26
- const REAP_CONNECT_TIMEOUT_MS = 3000;
27
- // Tracks the PID of Chrome instances *we* spawned, keyed by CDP port, so
28
- // closeBrowser() has a kill fallback when the graceful `Browser.close` CDP
29
- // command fails or times out (e.g. a hung renderer). Ports we merely attached
30
- // to (already-running browser) are never recorded here — we only ever kill
31
- // processes we launched ourselves.
32
- const launchedPids = new Map();
33
- // userDataDir per launched port — informational, persisted alongside the pid
34
- // so a later process could clean up the temp profile dir too if ever needed.
35
- const launchedUserDataDirs = new Map();
36
- /** PID of the Chrome instance *this process* launched on `port`, if any. */
37
- export function getLaunchedPid(port) {
38
- return launchedPids.get(port);
39
- }
40
- /** userDataDir of the Chrome instance *this process* launched on `port`, if any. */
41
- export function getLaunchedUserDataDir(port) {
42
- return launchedUserDataDirs.get(port);
43
- }
44
- function findChrome(executablePath) {
45
- if (executablePath) {
46
- if (existsSync(executablePath))
47
- return executablePath;
48
- throw new Error(`Chrome executable not found: ${executablePath}`);
49
- }
50
- for (const candidate of CHROME_EXECUTABLES) {
51
- if (existsSync(candidate))
52
- return candidate;
53
- }
54
- // Try PATH
55
- try {
56
- const result = execSync('which google-chrome chromium-browser chromium microsoft-edge microsoft-edge-stable 2>/dev/null', { encoding: 'utf8' }).trim();
57
- const first = result.split('\n')[0];
58
- if (first)
59
- return first;
60
- }
61
- catch {
62
- // ignore
63
- }
64
- throw new Error('No supported browser found. Install Google Chrome, Microsoft Edge, or Chromium — or pass executablePath in BrowserConfig.');
65
- }
66
- export async function isPortOpen(port) {
67
- try {
68
- await fetchTargets(port);
69
- return true;
70
- }
71
- catch {
72
- return false;
73
- }
74
- }
75
- /**
76
- * Confirm the CDP endpoint on `port` actually identifies as Chrome/Chromium
77
- * via `/json/version`'s `Browser` field, rather than assuming any CDP-speaking
78
- * responder is "ours". Reduces (does not eliminate) the risk of silently
79
- * attaching to an unrelated real browser that happens to be listening there.
80
- */
81
- async function isChromeIdentity(port) {
82
- return (await chromeIdentity(port)) === 'chrome';
83
- }
84
- /** isChromeIdentity, telling "answered as something else" apart from "did
85
- * not answer in time" ('unknown': a timeout, a refused or reset connection,
86
- * a non-OK status or an unparseable body). */
87
- async function chromeIdentity(port) {
88
- try {
89
- const res = await fetch(`http://127.0.0.1:${port}/json/version`, {
90
- signal: AbortSignal.timeout(1000),
91
- });
92
- if (!res.ok)
93
- return 'unknown';
94
- const info = (await res.json());
95
- // Edge's Browser field is "Edg/<version>" with no "chrome"/"chromium"
96
- // substring, even though it's Chromium-based and CDP-compatible —
97
- // accept it alongside Chrome/Chromium rather than rejecting a valid target.
98
- return typeof info.Browser === 'string' && /chrom(e|ium)|edg/i.test(info.Browser)
99
- ? 'chrome'
100
- : 'other';
101
- }
102
- catch {
103
- return 'unknown';
104
- }
105
- }
106
- /** Raw TCP connect probe — distinguishes "nothing listening" from "something listening that isn't CDP". */
107
- function isTcpPortOpen(port, timeoutMs = 1000) {
108
- return new Promise((resolve) => {
109
- const socket = connect({ host: '127.0.0.1', port, timeout: timeoutMs });
110
- const done = (result) => {
111
- socket.removeAllListeners();
112
- socket.destroy();
113
- resolve(result);
114
- };
115
- socket.once('connect', () => done(true));
116
- socket.once('timeout', () => done(false));
117
- socket.once('error', () => done(false));
118
- });
119
- }
120
- /** Ports scanned when the requested one is occupied by a non-Chrome process
121
- * (e.g. another local tool that happens to reuse Chrome's conventional CDP
122
- * default, 9222 — mirrors the auto-increment convention this monorepo's own
123
- * dashboard server uses in bindServer/server.mjs). Only occupied-by-a-
124
- * DIFFERENT-process is worked around; an already-attachable Chrome on the
125
- * requested port is still returned as-is (existing "attach, don't relaunch"
126
- * behavior). */
127
- const LAUNCH_PORT_SCAN_TRIES = 10;
128
- export async function launchBrowser(config = {}) {
129
- const rawPort = config.port ?? DEFAULT_PORT;
130
- // Port 0 means "let Chrome bind a free port and tell us which" — see
131
- // launchOnFreePort. Otherwise validate port is in a safe range for
132
- // localhost CDP debugging.
133
- if (rawPort === 0) {
134
- if (!config.userDataDir) {
135
- throw new Error('port 0 requires a dedicated userDataDir (Chrome reports the port it bound inside it).');
136
- }
137
- }
138
- else if (!Number.isInteger(rawPort) || rawPort < 1024 || rawPort > 65535) {
139
- throw new Error(`Invalid port: ${rawPort}. Must be 0 or an integer between 1024 and 65535.`);
140
- }
141
- // Every launch/attach is this tool's only chance to notice that a previous
142
- // session abandoned a browser on a CDP port and never gave it back — there
143
- // is no daemon to do it on a timer. Bounded and non-throwing; a stale
144
- // instance on the port we are about to use is freed before we probe it.
145
- await reapIdleLaunchedBrowser();
146
- if (rawPort === 0)
147
- return launchOnFreePort(config, 0);
148
- // strictPort: fail fast on the exact requested port, matching the old
149
- // behavior (Vite has the same escape hatch for the same reason) — for
150
- // callers that treat the error as a signal ("this port is taken by
151
- // something else, bail") rather than consuming the returned port.
152
- if (config.strictPort) {
153
- if (await isTcpPortOpen(rawPort)) {
154
- if (await isChromeIdentity(rawPort))
155
- return rawPort;
156
- throw new Error(`Port ${rawPort} is occupied by a process that does not identify as Chrome/Chromium. ` +
157
- `Refusing to attach — pass a different port or free port ${rawPort}.`);
158
- }
159
- return launchOnFreePort(config, rawPort);
160
- }
161
- const candidates = [];
162
- for (let i = 0; i < LAUNCH_PORT_SCAN_TRIES && rawPort + i <= 65535; i++)
163
- candidates.push(rawPort + i);
164
- for (const candidate of candidates) {
165
- // TCP-level check for "is anything at all listening" — isPortOpen()
166
- // does a full CDP /json fetch, which returns false BOTH for a genuinely
167
- // free port and for one occupied by a non-CDP process (that ambiguity is
168
- // exactly what the post-spawn isTcpPortOpen fallback below exists to
169
- // resolve, the hard way, after a 10s launch timeout). Checking the raw
170
- // socket first tells free and occupied apart up front, so the scan can
171
- // skip an occupied candidate instead of trying to spawn Chrome on top of
172
- // it and only discovering the conflict after a timeout.
173
- if (await isTcpPortOpen(candidate)) {
174
- // Attach-if-already-Chrome only applies to the EXACT requested port —
175
- // the original, deliberate, single-port risk ("don't silently take
176
- // over an unrelated real browser that happens to be on this port").
177
- // Scanning past an occupied default must not let that same shortcut
178
- // attach to a DIFFERENT Chrome instance the caller never named;
179
- // forward candidates are launch-only (skip if anything is there,
180
- // Chrome or not).
181
- if (candidate === rawPort && (await isChromeIdentity(candidate)))
182
- return candidate;
183
- // Occupied (by anything — not just non-Chrome, per the note above) —
184
- // try the next candidate instead of failing outright, same as a
185
- // normal EADDRINUSE retry would.
186
- continue;
187
- }
188
- try {
189
- return await launchOnFreePort(config, candidate);
190
- }
191
- catch (err) {
192
- const isLastCandidate = candidate === candidates[candidates.length - 1];
193
- // isTcpPortOpen() above is a connect() probe, not an atomic claim: two
194
- // concurrent launchBrowser() calls with no explicit --port can both
195
- // observe the same candidate as free and both spawn Chrome on it
196
- // before either binds. One wins; the other's Chrome exits before its
197
- // CDP endpoint opens ("Chrome exited before the CDP endpoint opened
198
- // ... code=21"). Something is listening on the candidate NOW that
199
- // was not a moment ago — a losing race, not a broken Chrome install —
200
- // so try the next candidate exactly like an already-occupied one,
201
- // instead of failing the whole launch outright. A candidate that
202
- // fails with nothing now listening (a real launch failure — bad
203
- // executable, sandbox refusal, etc.) is not a race: retrying the
204
- // next candidate would only fail the same way, so surface it as-is.
205
- if (!isLastCandidate && (await isTcpPortOpen(candidate)))
206
- continue;
207
- throw err;
208
- }
209
- }
210
- throw new Error(`Ports ${candidates[0]}-${candidates[candidates.length - 1]} are all occupied and port ${candidates[0]} ` +
211
- `isn't a Chrome/Chromium instance to attach to. Pass a different --port.`);
212
- }
213
- /** The port Chrome wrote to `<userDataDir>/DevToolsActivePort` once its
214
- * DevTools server was listening, or null if it has not (yet). */
215
- function readDevToolsActivePort(file) {
216
- try {
217
- const port = Number.parseInt(readFileSync(file, 'utf8').split('\n')[0], 10);
218
- return Number.isInteger(port) && port > 0 && port <= 65535 ? port : null;
219
- }
220
- catch {
221
- return null;
222
- }
223
- }
224
- /**
225
- * Spawn Chrome and wait for its CDP endpoint.
226
- *
227
- * With a fixed `port`, "our Chrome is up" is inferred from *some* Chrome
228
- * answering on 127.0.0.1:<port> — which is not necessarily ours. When the port
229
- * is already bound on 127.0.0.1 (a concurrent launch picked the same "free"
230
- * port between its probe and Chrome's bind), Chrome does not fail: it logs
231
- * `bind() failed: Address already in use` and listens on [::1]:<port>
232
- * instead. The poll then accepts the OTHER launcher's browser, both callers
233
- * drive one Chrome, and whichever closes first kills the other's connections
234
- * ("CDP connection closed") while this launch's own Chrome is orphaned.
235
- *
236
- * `port: 0` removes the race instead of narrowing it: Chrome asks the kernel
237
- * for a free port at bind time — atomic, nothing to collide on — and writes
238
- * the port it got to DevToolsActivePort in its own (caller-dedicated) profile
239
- * directory, which is proof the endpoint is the process we spawned.
240
- */
241
- async function launchOnFreePort(config, port) {
242
- const chromePath = findChrome(config.executablePath);
243
- // Suffixed with our own pid: two concurrent launches that both probe the
244
- // same candidate port as free (the race this function exists to survive —
245
- // see the retry-on-collision caller above) briefly run Chrome with
246
- // *identical* --user-data-dir values if it were derived from the port
247
- // alone, sharing a profile directory (lock files, preferences, the
248
- // DevToolsActivePort file itself) between two unrelated Chrome processes
249
- // for as long as the loser stays alive. Different processes always have
250
- // different pids, so this can never collide even when the port does.
251
- const userDataDir = config.userDataDir ?? join(tmpdir(), `monomind-browser-${port}-${process.pid}`);
252
- const activePortFile = join(userDataDir, 'DevToolsActivePort');
253
- // A reused profile dir may hold a previous run's file naming a port some
254
- // other process now owns.
255
- if (port === 0)
256
- rmSync(activePortFile, { force: true });
257
- const defaultArgs = [
258
- `--remote-debugging-port=${port}`,
259
- `--user-data-dir=${userDataDir}`,
260
- '--no-first-run',
261
- '--no-default-browser-check',
262
- '--disable-background-networking',
263
- '--disable-client-side-phishing-detection',
264
- '--disable-default-apps',
265
- '--disable-extensions',
266
- '--disable-hang-monitor',
267
- '--disable-popup-blocking',
268
- '--disable-prompt-on-repost',
269
- '--disable-sync',
270
- '--disable-translate',
271
- '--metrics-recording-only',
272
- '--safebrowsing-disable-auto-update',
273
- '--password-store=basic',
274
- '--use-mock-keychain',
275
- ];
276
- if (config.headless !== false) {
277
- defaultArgs.push('--headless=new');
278
- }
279
- // Chrome's setuid sandbox cannot initialise on most CI runners and
280
- // containers, so the process dies during startup and the CDP endpoint never
281
- // opens. The launch below then burns its whole timeout before reporting a
282
- // generic failure, which reads as a hang rather than "Chrome could not
283
- // start". Disabling the sandbox is the standard remedy and is scoped to CI
284
- // so a real user's browser keeps it. --disable-dev-shm-usage goes with it:
285
- // a container's default /dev/shm is 64MB, which Chrome exhausts and then
286
- // crashes the same way.
287
- if (process.env.CI) {
288
- defaultArgs.push('--no-sandbox', '--disable-dev-shm-usage');
289
- }
290
- // Cap caller-supplied args to prevent memory exhaustion via huge argument arrays
291
- const callerArgs = (config.args ?? []).slice(0, 50);
292
- const args = [...defaultArgs, ...callerArgs];
293
- const child = spawn(chromePath, args, {
294
- detached: true,
295
- stdio: 'ignore',
296
- });
297
- // Without this, a spawn failure (e.g. EACCES/ENOENT — chromePath exists per
298
- // findChrome()'s existsSync check but isn't actually executable, or is
299
- // removed between the check and exec) fires Node's 'error' event on the
300
- // next tick. With no listener, Node throws it as an uncaught exception and
301
- // the whole process goes down — which strands this function's promise
302
- // forever pending rather than rejecting it (issue #314: node:test reports
303
- // that as "cancelledByParent" / "still pending" because nothing here ever
304
- // got the chance to settle it). Recording the failure and having the poll
305
- // loop below notice it turns that crash into a normal rejection. 'exit'
306
- // covers the twin case: Chrome execs fine but the process itself dies
307
- // immediately (missing shared libraries, a container's sandbox refusing
308
- // it, etc.) — that fires 'exit', not 'error', and without this the poll
309
- // loop would just burn its whole timeout probing a port nothing will ever
310
- // open on.
311
- let earlyFailure = null;
312
- child.on('error', (err) => {
313
- earlyFailure ??= new Error(`Chrome failed to start on port ${port}: ${err.message}`);
314
- });
315
- child.on('exit', (code, signal) => {
316
- earlyFailure ??= new Error(`Chrome exited before the CDP endpoint opened on port ${port} ` +
317
- `(code=${code ?? 'null'}, signal=${signal ?? 'null'})`);
318
- });
319
- child.unref();
320
- const track = (boundPort) => {
321
- if (!child.pid)
322
- return;
323
- launchedPids.set(boundPort, child.pid);
324
- launchedUserDataDirs.set(boundPort, userDataDir);
325
- };
326
- // Tracked only once Chrome is CONFIRMED up on `boundPort`, not right after
327
- // spawn(). For port !== 0 this used to track(port) unconditionally the
328
- // moment the child was spawned, before knowing whether it would actually
329
- // win the port — when a racing launchBrowser() call retries a candidate
330
- // that a concurrent process also spawned Chrome on (see the retry loop in
331
- // launchBrowser), BOTH child processes called track() for the SAME
332
- // candidate, and whichever call's spawn happened to run last clobbered the
333
- // map entry with its own pid — including the LOSING, about-to-exit
334
- // process's pid overwriting the real winner's, corrupting the very map
335
- // closeBrowser()'s kill fallback depends on.
336
- // With port 0 a refused or timed-out launch is not tracked under any port,
337
- // so no closeBrowser() could ever reach it — stop it rather than leave it
338
- // running.
339
- const killUntracked = () => {
340
- try {
341
- if (child.pid)
342
- process.kill(child.pid, 'SIGKILL');
343
- }
344
- catch {
345
- /* already gone */
346
- }
347
- };
348
- const launchTimeout = config.launchTimeoutMs ?? LAUNCH_TIMEOUT;
349
- const deadline = Date.now() + launchTimeout;
350
- while (Date.now() < deadline) {
351
- if (earlyFailure)
352
- throw earlyFailure;
353
- await sleep(POLL_INTERVAL);
354
- if (earlyFailure)
355
- throw earlyFailure;
356
- const boundPort = port === 0 ? readDevToolsActivePort(activePortFile) : port;
357
- if (boundPort !== null && (await isPortOpen(boundPort))) {
358
- const identity = await chromeIdentity(boundPort);
359
- if (identity === 'chrome') {
360
- track(boundPort);
361
- return boundPort;
362
- }
363
- // A Chrome that has only just opened its endpoint, on a loaded
364
- // machine, can answer /json/list (no timeout) yet miss the identity
365
- // check's 1 s timeout on /json/version. That says nothing about who is
366
- // listening — keep polling rather than refuse our own Chrome.
367
- if (identity === 'unknown')
368
- continue;
369
- if (port === 0)
370
- killUntracked();
371
- throw new Error(`Port ${boundPort} is occupied by a CDP-speaking process that does not identify as Chrome/Chromium. ` +
372
- `Refusing to attach — pass a different port or free port ${boundPort}.`);
373
- }
374
- }
375
- if (earlyFailure)
376
- throw earlyFailure;
377
- if (port === 0) {
378
- killUntracked();
379
- throw new Error(`Chrome did not report a CDP port in ${activePortFile} within ${launchTimeout}ms`);
380
- }
381
- // Timed out waiting for our Chrome to come up on the port. Distinguish
382
- // "nothing is listening" (real launch failure) from "something non-CDP is
383
- // squatting the port" (confusing generic timeout otherwise) via a raw TCP probe.
384
- if (await isTcpPortOpen(port)) {
385
- throw new Error(`Port ${port} is occupied by a non-Chrome process (TCP connection succeeds but no CDP response within ${launchTimeout}ms). ` +
386
- `Free the port or pass a different one.`);
387
- }
388
- throw new Error(`Chrome failed to start on port ${port} within ${launchTimeout}ms`);
389
- }
390
- export async function enableSessionDomains(client, sessionId) {
391
- await Promise.all([
392
- client.send('Page.enable', {}, sessionId),
393
- client.send('Runtime.enable', {}, sessionId),
394
- client.send('Network.enable', {}, sessionId),
395
- client.send('DOM.enable', {}, sessionId),
396
- client.send('Accessibility.enable', {}, sessionId),
397
- ]);
398
- setupConsoleCapture(client, sessionId);
399
- await enableConsoleCapture(client, sessionId);
400
- setupDialogAutoHandling(client, sessionId);
401
- }
402
- export async function connectToTarget(port, targetId) {
403
- const targets = await fetchTargets(port);
404
- const pageTargets = targets.filter((t) => t.type === 'page');
405
- let target;
406
- if (targetId) {
407
- const found = pageTargets.find((t) => t.id === targetId);
408
- if (!found)
409
- throw new Error(`Target ${targetId} not found`);
410
- target = found;
411
- }
412
- else if (pageTargets.length > 0) {
413
- target = pageTargets[0];
414
- }
415
- else {
416
- target = await fetchNewTarget(port, 'about:blank');
417
- }
418
- const wsUrl = target.webSocketDebuggerUrl ?? `ws://127.0.0.1:${port}/devtools/page/${target.id}`;
419
- const client = new CdpClient();
420
- await client.connect(wsUrl);
421
- const { sessionId } = await client.send('Target.attachToTarget', {
422
- targetId: target.id,
423
- flatten: true,
424
- });
425
- await enableSessionDomains(client, sessionId);
426
- return { client, target, sessionId };
427
- }
428
- /**
429
- * Cleanly terminate a Chrome/Chromium instance we launched on `port`.
430
- * Sends the `Browser.close` CDP command (the correct graceful shutdown —
431
- * closes all tabs and exits the process cleanly) over `client`'s connection.
432
- * If that command fails, times out, or the connection is already gone,
433
- * falls back to killing the tracked PID directly so a headed/interactive
434
- * browser window (e.g. one spawned for a login/CAPTCHA flow) never lingers
435
- * as a visible, authenticated, still-debuggable orphan process.
436
- *
437
- * On the graceful path this resolves only once the process is actually gone,
438
- * or after force-killing it when it outlasts PROCESS_EXIT_TIMEOUT_MS. Chrome
439
- * acknowledges `Browser.close` well before it exits, and this used to return
440
- * on the ack with an unref'd 1s timer as the only force-kill — so it resolved
441
- * while Chrome was still running and holding its port and its profile's
442
- * singleton lock, and if the caller's process exited first the kill never
443
- * happened at all. Callers reasonably read a resolved close() as "that
444
- * browser is gone"; on the graceful path it now means that.
445
- */
446
- export async function closeBrowser(client, port) {
447
- let gracefullyClosed = false;
448
- let closeTimer;
449
- try {
450
- await Promise.race([
451
- client.send('Browser.close', {}),
452
- // Deliberately NOT unref'd, for the same reason waitForProcessExit()'s
453
- // poll below is not. This timer is the only thing that settles the race
454
- // when Chrome's socket dies without ever acknowledging the close, and
455
- // closeBrowser() is actively awaited by callers. An unref'd timer does
456
- // not hold the event loop open, so Node would consider the loop drained
457
- // and exit — status 0, before the caller's verdict was ever printed.
458
- // Cleared in the finally so a close that IS acknowledged does not pin
459
- // the loop for the rest of BROWSER_CLOSE_TIMEOUT_MS.
460
- new Promise((_, reject) => {
461
- closeTimer = setTimeout(() => reject(new Error('Browser.close timed out')), BROWSER_CLOSE_TIMEOUT_MS);
462
- }),
463
- ]);
464
- gracefullyClosed = true;
465
- }
466
- catch {
467
- // fall through to PID-kill fallback below
468
- }
469
- finally {
470
- clearTimeout(closeTimer);
471
- }
472
- let pid = launchedPids.get(port);
473
- if (pid === undefined) {
474
- // Fresh process (each CLI invocation is its own node process — see
475
- // module header) — launchedPids is per-process and empty here even
476
- // though a prior `open` in a DIFFERENT process launched this Chrome.
477
- // Fall back to the PID that process persisted via saveSessionRecord().
478
- try {
479
- const persisted = await loadSessionRecord(port);
480
- if (persisted?.launched && persisted.pid) {
481
- // Bound how far we trust a cross-process PID: if the Chrome we
482
- // launched died outside this flow (OOM-killed, host slept, etc.)
483
- // without its session record ever being cleared, the OS can recycle
484
- // that PID for an unrelated process. There is no cmdline/start-time
485
- // check available portably, so a coarse age bound is the practical
486
- // guard — a PID persisted more than a day ago is far more likely to
487
- // be stale/reused than to still be the same live Chrome.
488
- const age = persisted.savedAt !== undefined ? Date.now() - persisted.savedAt : undefined;
489
- if (age === undefined || age <= PERSISTED_PID_MAX_AGE_MS) {
490
- pid = persisted.pid;
491
- }
492
- }
493
- }
494
- catch {
495
- // best-effort — fall through to "nothing to kill" below
496
- }
497
- }
498
- if (pid === undefined)
499
- return; // not a process we launched, or too stale to trust — nothing to kill
500
- launchedPids.delete(port);
501
- // Liveness-check before every SIGKILL (not just the safety-net path below)
502
- // — process.kill(pid, 0) throws ESRCH if the PID is no longer running,
503
- // which also catches the case where the PID has already been recycled by
504
- // an unrelated process that happens to have exited too.
505
- if (!gracefullyClosed) {
506
- try {
507
- process.kill(pid, 0);
508
- process.kill(pid, 'SIGKILL');
509
- }
510
- catch {
511
- /* already exited, or never was — nothing to do */
512
- }
513
- return;
514
- }
515
- // Browser.close was acknowledged — wait for the process to actually go away,
516
- // then force-kill as a safety net in case it hung.
517
- if (await waitForProcessExit(pid))
518
- return;
519
- try {
520
- process.kill(pid, 'SIGKILL');
521
- }
522
- catch {
523
- /* raced us to exit — expected */
524
- }
525
- }
526
- /** Poll until `pid` is gone or PROCESS_EXIT_TIMEOUT_MS elapses. Returns
527
- * whether it exited. `process.kill(pid, 0)` throws once the process is no
528
- * longer there, on Windows as well as POSIX.
529
- *
530
- * This timer is deliberately NOT unref'd. closeBrowser() awaits this poll
531
- * as part of its own return value — a caller that awaits closeBrowser() is
532
- * actively blocked on it, not doing other work in the background. Once
533
- * Chrome's CDP websocket closes (which happens right around here, as part
534
- * of it shutting down), nothing else may be left holding the event loop
535
- * open; an unref'd timer at that point never fires because Node considers
536
- * the loop drained and exits without running it, leaving this promise (and
537
- * closeBrowser()'s) pending forever — reproduced locally by closing a real
538
- * launched browser with nothing else scheduled. Bounded by
539
- * PROCESS_EXIT_TIMEOUT_MS (5s) either way, so keeping it ref'd only ever
540
- * costs a caller a few seconds, never a hang. */
541
- async function waitForProcessExit(pid) {
542
- const deadline = Date.now() + PROCESS_EXIT_TIMEOUT_MS;
543
- for (;;) {
544
- try {
545
- process.kill(pid, 0);
546
- }
547
- catch {
548
- return true;
549
- }
550
- if (Date.now() >= deadline)
551
- return false;
552
- await new Promise((resolve) => {
553
- setTimeout(resolve, PROCESS_EXIT_POLL_MS);
554
- });
555
- }
556
- }
557
- /**
558
- * Give back the CDP port of a browser we launched that nothing is using any
559
- * more. A launched Chrome is deliberately detached and unref'd so it outlives
560
- * the command that spawned it and later commands can reattach — but nothing
561
- * reaped it afterwards, so an abandoned session kept listening on its port
562
- * (9222 by convention, which other local tools want) indefinitely. A foreign
563
- * CDP server *answers* there rather than refusing the connection, so those
564
- * tools retry the wrong port and report misleading errors instead of moving on.
565
- *
566
- * Nothing long-lived exists to run this on a timer — every CLI command is its
567
- * own short-lived process — so it runs at the next launch/attach instead
568
- * (see launchBrowser). A browser is reaped only when ALL of these hold:
569
- * - the persisted session says WE launched it — `connect` records
570
- * launched:false for a browser that belongs to the user, never touched;
571
- * - that session is older than IDLE_REAP_AFTER_MS;
572
- * - the CDP endpoint still answers and reports ZERO targets. An open tab,
573
- * or a client attached to one (Chrome drops webSocketDebuggerUrl from an
574
- * attached target but still lists it), means the session is live and
575
- * reattach-across-commands must keep working.
576
- *
577
- * Shutdown goes through closeBrowser() on the browser-level websocket — the
578
- * only connection left once every target is gone — so a recycled PID can
579
- * never be signaled by mistake: graceful `Browser.close` reaches whatever is
580
- * actually listening on that port, at any age, and the persisted PID is only
581
- * ever used for closeBrowser's own age-bounded force-kill.
582
- *
583
- * Never throws: a failed reap must not stop a launch. Returns the reaped
584
- * port, or null when there was nothing to reap. Sessions are per-port
585
- * (#318), so every recorded one is considered, not just the newest.
586
- */
587
- export async function reapIdleLaunchedBrowser() {
588
- let reaped = null;
589
- for (const session of await listSessionRecords().catch(() => [])) {
590
- const port = await reapSession(session);
591
- reaped ??= port;
592
- }
593
- return reaped;
594
- }
595
- async function reapSession(session) {
596
- try {
597
- if (!session.launched || session.savedAt === undefined)
598
- return null;
599
- if (Date.now() - session.savedAt < IDLE_REAP_AFTER_MS)
600
- return null;
601
- const wsUrl = await fetchBrowserWebSocketUrl(session.port);
602
- if (!wsUrl)
603
- return null;
604
- if ((await fetchTargets(session.port)).length > 0)
605
- return null;
606
- const client = new CdpClient();
607
- let reapTimer;
608
- try {
609
- // CdpClient.connect() has no timeout of its own — a socket that never
610
- // opens (and never errors) would hang the launch this reap is running
611
- // inside of, which is strictly worse than leaving the port squatted.
612
- // Not unref'd (see closeBrowser): a socket that never opens and never
613
- // errors leaves this timer as the only thing that can settle the race,
614
- // and the reap is awaited inside launch/attach. Cleared in the finally
615
- // below so a connect that succeeds does not pin the event loop.
616
- await Promise.race([
617
- client.connect(wsUrl),
618
- new Promise((_, reject) => {
619
- reapTimer = setTimeout(() => reject(new Error('Reap: CDP connect timed out')), REAP_CONNECT_TIMEOUT_MS);
620
- }),
621
- ]);
622
- await closeBrowser(client, session.port);
623
- }
624
- finally {
625
- clearTimeout(reapTimer);
626
- try {
627
- client.close();
628
- }
629
- catch {
630
- /* already gone */
631
- }
632
- }
633
- launchedPids.delete(session.port);
634
- launchedUserDataDirs.delete(session.port);
635
- await removeSessionRecord(session.port);
636
- return session.port;
637
- }
638
- catch {
639
- return null;
640
- }
641
- }
642
- /** Chrome's browser-level debugger endpoint, from /json/version — the
643
- * connection `Browser.close` belongs on. Null if the port isn't answering as
644
- * a Chrome/Chromium CDP endpoint (same identity check as isChromeIdentity). */
645
- async function fetchBrowserWebSocketUrl(port) {
646
- const res = await fetch(`http://127.0.0.1:${port}/json/version`, {
647
- signal: AbortSignal.timeout(1000),
648
- });
649
- if (!res.ok)
650
- return null;
651
- const info = (await res.json());
652
- if (typeof info.Browser !== 'string' || !/chrom(e|ium)|edg/i.test(info.Browser))
653
- return null;
654
- return typeof info.webSocketDebuggerUrl === 'string' ? info.webSocketDebuggerUrl : null;
655
- }
656
- export async function openUrl(client, sessionId, url) {
657
- // Cap to 2 MB to prevent OOM in CDP message serializer (e.g. data: URI attacks)
658
- if (url.length > 2_097_152)
659
- throw new Error('URL exceeds 2 MB limit');
660
- // Page.navigate reports a protocol-level failure (e.g. a refused connection)
661
- // via errorText in its own response, before Chrome ever settles on the
662
- // chrome-error://chromewebdata/ page — without this check a refused
663
- // connection previously reported success against that error page.
664
- const nav = await client.send('Page.navigate', { url }, sessionId);
665
- if (nav.errorText)
666
- throw new Error(`Navigation to ${url} failed: ${nav.errorText}`);
667
- await waitForNetworkIdle(client, sessionId, 500, 30_000);
668
- }
669
- export async function waitForLoad(client, sessionId, condition = 'load', timeout = 30_000) {
670
- if (condition === 'load' || condition === 'domcontentloaded') {
671
- // Guard against race where the page loads before the listener is registered
672
- const readyExpr = condition === 'load'
673
- ? 'document.readyState === "complete"'
674
- : 'document.readyState !== "loading"';
675
- const readyCheck = await client
676
- .send('Runtime.evaluate', {
677
- expression: readyExpr,
678
- returnByValue: true,
679
- }, sessionId)
680
- .catch(() => ({ result: { value: false } }));
681
- if (readyCheck.result?.value)
682
- return;
683
- const event = condition === 'load' ? 'Page.loadEventFired' : 'Page.domContentEventFired';
684
- const [eventPromise, cancelOnce] = client.onceWithOff(event, sessionId);
685
- let timedOut = false;
686
- let timeoutHandle;
687
- const timeoutPromise = new Promise((resolve) => {
688
- timeoutHandle = setTimeout(() => {
689
- timedOut = true;
690
- resolve();
691
- }, timeout);
692
- });
693
- try {
694
- await Promise.race([eventPromise, timeoutPromise]);
695
- if (timedOut)
696
- throw new Error(`Timeout waiting for ${condition}`);
697
- }
698
- finally {
699
- cancelOnce();
700
- clearTimeout(timeoutHandle);
701
- }
702
- return;
703
- }
704
- // networkidle: no network requests for 500ms
705
- await waitForNetworkIdle(client, sessionId, 500, timeout);
706
- }
707
- async function waitForNetworkIdle(client, sessionId, idleMs, timeout) {
708
- return new Promise((resolve, reject) => {
709
- let pending = 0;
710
- const inflight = new Set();
711
- let idleTimer = null;
712
- const killTimer = setTimeout(() => {
713
- cleanup();
714
- reject(new Error('Timeout waiting for networkidle'));
715
- }, timeout);
716
- const cleanup = () => {
717
- if (idleTimer) {
718
- clearTimeout(idleTimer);
719
- idleTimer = null;
720
- }
721
- clearTimeout(killTimer);
722
- offReq();
723
- offResp();
724
- offFail();
725
- offCache();
726
- offResp2();
727
- };
728
- const settle = () => {
729
- cleanup();
730
- resolve();
731
- };
732
- const check = () => {
733
- if (pending === 0) {
734
- if (idleTimer)
735
- clearTimeout(idleTimer);
736
- idleTimer = setTimeout(settle, idleMs);
737
- }
738
- else {
739
- if (idleTimer) {
740
- clearTimeout(idleTimer);
741
- idleTimer = null;
742
- }
743
- }
744
- };
745
- const offReq = client.on('Network.requestWillBeSent', (params, sid) => {
746
- if (sid !== sessionId)
747
- return;
748
- const id = params.requestId;
749
- if (!inflight.has(id)) {
750
- inflight.add(id);
751
- pending++;
752
- check();
753
- }
754
- });
755
- const decrement = (params, sid) => {
756
- if (sid !== sessionId)
757
- return;
758
- const id = params.requestId;
759
- if (inflight.delete(id)) {
760
- pending = Math.max(0, pending - 1);
761
- check();
762
- }
763
- };
764
- const offResp = client.on('Network.loadingFinished', decrement);
765
- const offFail = client.on('Network.loadingFailed', decrement);
766
- const offCache = client.on('Network.requestServedFromCache', decrement);
767
- // Guard against requests that never fire loadingFinished/loadingFailed (e.g. data: URLs)
768
- // Skip 3xx redirect responses — the request continues under the same requestId
769
- const offResp2 = client.on('Network.responseReceived', (params, sid) => {
770
- const p = params;
771
- if (p.response.status >= 300 && p.response.status < 400)
772
- return;
773
- decrement(params, sid);
774
- });
775
- check();
776
- });
777
- }
778
- export async function getCurrentUrl(client, sessionId) {
779
- const result = await client.send('Runtime.evaluate', {
780
- expression: 'location.href',
781
- returnByValue: true,
782
- }, sessionId);
783
- return result.result?.value ?? '';
784
- }
785
- export async function getCurrentTitle(client, sessionId) {
786
- const result = await client.send('Runtime.evaluate', {
787
- expression: 'document.title',
788
- returnByValue: true,
789
- }, sessionId);
790
- return result.result?.value ?? '';
791
- }
792
- function sleep(ms) {
793
- return new Promise((r) => setTimeout(r, ms));
794
- }
1
+ // File-size sweep: split into sibling modules (browser-state, browser-discovery,
2
+ // browser-launch, browser-lifecycle, browser-page). Pure move — this file now
3
+ // re-exports everything it used to define, so every existing import path
4
+ // keeps working.
5
+ export { isPortOpen } from './browser-discovery.js';
6
+ export { launchBrowser } from './browser-launch.js';
7
+ export { closeBrowser, reapIdleLaunchedBrowser } from './browser-lifecycle.js';
8
+ export { connectToTarget, enableSessionDomains, getCurrentTitle, getCurrentUrl, openUrl, waitForLoad, } from './browser-page.js';
9
+ export { getLaunchedPid, getLaunchedUserDataDir } from './browser-state.js';
795
10
  //# sourceMappingURL=browser.js.map