@monoes/monobrowse 1.0.26 → 1.0.28

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 (101) hide show
  1. package/dist/src/__tests__/disconnect-session.test.d.ts +13 -0
  2. package/dist/src/__tests__/disconnect-session.test.d.ts.map +1 -0
  3. package/dist/src/__tests__/disconnect-session.test.js +37 -0
  4. package/dist/src/__tests__/disconnect-session.test.js.map +1 -0
  5. package/dist/src/__tests__/profile-cleanup-close.test.d.ts +16 -0
  6. package/dist/src/__tests__/profile-cleanup-close.test.d.ts.map +1 -0
  7. package/dist/src/__tests__/profile-cleanup-close.test.js +250 -0
  8. package/dist/src/__tests__/profile-cleanup-close.test.js.map +1 -0
  9. package/dist/src/__tests__/profile-dir.test.d.ts +10 -0
  10. package/dist/src/__tests__/profile-dir.test.d.ts.map +1 -0
  11. package/dist/src/__tests__/profile-dir.test.js +160 -0
  12. package/dist/src/__tests__/profile-dir.test.js.map +1 -0
  13. package/dist/src/__tests__/setup/isolated-tmpdir.global.d.ts +2 -0
  14. package/dist/src/__tests__/setup/isolated-tmpdir.global.d.ts.map +1 -0
  15. package/dist/src/__tests__/setup/isolated-tmpdir.global.js +30 -0
  16. package/dist/src/__tests__/setup/isolated-tmpdir.global.js.map +1 -0
  17. package/dist/src/browser/actions-eval.d.ts +8 -0
  18. package/dist/src/browser/actions-eval.d.ts.map +1 -0
  19. package/dist/src/browser/actions-eval.js +72 -0
  20. package/dist/src/browser/actions-eval.js.map +1 -0
  21. package/dist/src/browser/actions-form.d.ts +10 -0
  22. package/dist/src/browser/actions-form.d.ts.map +1 -0
  23. package/dist/src/browser/actions-form.js +133 -0
  24. package/dist/src/browser/actions-form.js.map +1 -0
  25. package/dist/src/browser/actions-keyboard.d.ts +7 -0
  26. package/dist/src/browser/actions-keyboard.d.ts.map +1 -0
  27. package/dist/src/browser/actions-keyboard.js +131 -0
  28. package/dist/src/browser/actions-keyboard.js.map +1 -0
  29. package/dist/src/browser/actions-mouse.d.ts +11 -0
  30. package/dist/src/browser/actions-mouse.d.ts.map +1 -0
  31. package/dist/src/browser/actions-mouse.js +105 -0
  32. package/dist/src/browser/actions-mouse.js.map +1 -0
  33. package/dist/src/browser/actions.d.ts +12 -28
  34. package/dist/src/browser/actions.d.ts.map +1 -1
  35. package/dist/src/browser/actions.js +12 -434
  36. package/dist/src/browser/actions.js.map +1 -1
  37. package/dist/src/browser/browser-discovery.d.ts +26 -0
  38. package/dist/src/browser/browser-discovery.d.ts.map +1 -0
  39. package/dist/src/browser/browser-discovery.js +113 -0
  40. package/dist/src/browser/browser-discovery.js.map +1 -0
  41. package/dist/src/browser/browser-launch.d.ts +3 -0
  42. package/dist/src/browser/browser-launch.d.ts.map +1 -0
  43. package/dist/src/browser/browser-launch.js +341 -0
  44. package/dist/src/browser/browser-launch.js.map +1 -0
  45. package/dist/src/browser/browser-lifecycle.d.ts +57 -0
  46. package/dist/src/browser/browser-lifecycle.d.ts.map +1 -0
  47. package/dist/src/browser/browser-lifecycle.js +245 -0
  48. package/dist/src/browser/browser-lifecycle.js.map +1 -0
  49. package/dist/src/browser/browser-page.d.ts +13 -0
  50. package/dist/src/browser/browser-page.d.ts.map +1 -0
  51. package/dist/src/browser/browser-page.js +179 -0
  52. package/dist/src/browser/browser-page.js.map +1 -0
  53. package/dist/src/browser/browser-state.d.ts +11 -0
  54. package/dist/src/browser/browser-state.d.ts.map +1 -0
  55. package/dist/src/browser/browser-state.js +27 -0
  56. package/dist/src/browser/browser-state.js.map +1 -0
  57. package/dist/src/browser/browser.d.ts +5 -68
  58. package/dist/src/browser/browser.d.ts.map +1 -1
  59. package/dist/src/browser/browser.js +9 -849
  60. package/dist/src/browser/browser.js.map +1 -1
  61. package/dist/src/browser/profile-dir.d.ts +88 -0
  62. package/dist/src/browser/profile-dir.d.ts.map +1 -0
  63. package/dist/src/browser/profile-dir.js +242 -0
  64. package/dist/src/browser/profile-dir.js.map +1 -0
  65. package/dist/src/browser/ref-cache.d.ts +4 -0
  66. package/dist/src/browser/ref-cache.d.ts.map +1 -1
  67. package/dist/src/browser/ref-cache.js +2 -0
  68. package/dist/src/browser/ref-cache.js.map +1 -1
  69. package/dist/src/browser/types.d.ts +6 -0
  70. package/dist/src/browser/types.d.ts.map +1 -1
  71. package/dist/src/browser/types.js.map +1 -1
  72. package/dist/src/cli/commands.d.ts +1 -0
  73. package/dist/src/cli/commands.d.ts.map +1 -1
  74. package/dist/src/cli/commands.js +2 -0
  75. package/dist/src/cli/commands.js.map +1 -1
  76. package/dist/src/cli/session.d.ts +9 -0
  77. package/dist/src/cli/session.d.ts.map +1 -1
  78. package/dist/src/cli/session.js +21 -4
  79. package/dist/src/cli/session.js.map +1 -1
  80. package/dist/tsconfig.tsbuildinfo +1 -1
  81. package/package.json +1 -1
  82. package/src/__tests__/disconnect-session.test.ts +42 -0
  83. package/src/__tests__/profile-cleanup-close.test.ts +285 -0
  84. package/src/__tests__/profile-dir.test.ts +196 -0
  85. package/src/__tests__/setup/isolated-tmpdir.global.ts +28 -0
  86. package/src/browser/actions-eval.ts +118 -0
  87. package/src/browser/actions-form.ts +218 -0
  88. package/src/browser/actions-keyboard.ts +171 -0
  89. package/src/browser/actions-mouse.ts +212 -0
  90. package/src/browser/actions.ts +37 -712
  91. package/src/browser/browser-discovery.ts +116 -0
  92. package/src/browser/browser-launch.ts +375 -0
  93. package/src/browser/browser-lifecycle.ts +248 -0
  94. package/src/browser/browser-page.ts +213 -0
  95. package/src/browser/browser-state.ts +30 -0
  96. package/src/browser/browser.ts +21 -917
  97. package/src/browser/profile-dir.ts +249 -0
  98. package/src/browser/ref-cache.ts +7 -0
  99. package/src/browser/types.ts +6 -0
  100. package/src/cli/commands.ts +2 -0
  101. package/src/cli/session.ts +22 -4
@@ -0,0 +1,248 @@
1
+ // Split out of browser.ts (file-size sweep). Pure move: no behaviour change.
2
+
3
+ import { fetchBrowserWebSocketUrl } from './browser-discovery.js';
4
+ import { launchedPids, launchedUserDataDirs, ownedUserDataDirPorts } from './browser-state.js';
5
+ import { CdpClient, fetchTargets } from './cdp.js';
6
+ import { removeOwnedProfileDir } from './profile-dir.js';
7
+ import {
8
+ listSessionRecords,
9
+ loadSessionRecord,
10
+ removeSessionRecord,
11
+ type SessionRecord,
12
+ } from './ref-cache.js';
13
+
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
+
28
+ /**
29
+ * Cleanly terminate a Chrome/Chromium instance we launched on `port`.
30
+ * Sends the `Browser.close` CDP command (the correct graceful shutdown —
31
+ * closes all tabs and exits the process cleanly) over `client`'s connection.
32
+ * If that command fails, times out, or the connection is already gone,
33
+ * falls back to killing the tracked PID directly so a headed/interactive
34
+ * browser window (e.g. one spawned for a login/CAPTCHA flow) never lingers
35
+ * as a visible, authenticated, still-debuggable orphan process.
36
+ *
37
+ * On the graceful path this resolves only once the process is actually gone,
38
+ * or after force-killing it when it outlasts PROCESS_EXIT_TIMEOUT_MS. Chrome
39
+ * acknowledges `Browser.close` well before it exits, and this used to return
40
+ * on the ack with an unref'd 1s timer as the only force-kill — so it resolved
41
+ * while Chrome was still running and holding its port and its profile's
42
+ * singleton lock, and if the caller's process exited first the kill never
43
+ * happened at all. Callers reasonably read a resolved close() as "that
44
+ * browser is gone"; on the graceful path it now means that.
45
+ *
46
+ * A profile directory monobrowse created for that browser (the default temp
47
+ * profile, or a CLI session's — never a caller-supplied one) is deleted once
48
+ * the process is gone, on both paths (#395). In a fresh process the dir and
49
+ * its ownership come from the persisted session record.
50
+ */
51
+ export async function closeBrowser(client: CdpClient, port: number): Promise<void> {
52
+ let gracefullyClosed = false;
53
+ let closeTimer: ReturnType<typeof setTimeout> | undefined;
54
+ try {
55
+ await Promise.race([
56
+ client.send('Browser.close', {}),
57
+ // Deliberately NOT unref'd, for the same reason waitForProcessExit()'s
58
+ // poll below is not. This timer is the only thing that settles the race
59
+ // when Chrome's socket dies without ever acknowledging the close, and
60
+ // closeBrowser() is actively awaited by callers. An unref'd timer does
61
+ // not hold the event loop open, so Node would consider the loop drained
62
+ // and exit — status 0, before the caller's verdict was ever printed.
63
+ // Cleared in the finally so a close that IS acknowledged does not pin
64
+ // the loop for the rest of BROWSER_CLOSE_TIMEOUT_MS.
65
+ new Promise<never>((_, reject) => {
66
+ closeTimer = setTimeout(
67
+ () => reject(new Error('Browser.close timed out')),
68
+ BROWSER_CLOSE_TIMEOUT_MS,
69
+ );
70
+ }),
71
+ ]);
72
+ gracefullyClosed = true;
73
+ } catch {
74
+ // fall through to PID-kill fallback below
75
+ } finally {
76
+ clearTimeout(closeTimer);
77
+ }
78
+
79
+ let pid = launchedPids.get(port);
80
+ let profileDir = ownedUserDataDirPorts.has(port) ? launchedUserDataDirs.get(port) : undefined;
81
+ if (pid === undefined) {
82
+ // Fresh process (each CLI invocation is its own node process — see
83
+ // module header) — launchedPids is per-process and empty here even
84
+ // though a prior `open` in a DIFFERENT process launched this Chrome.
85
+ // Fall back to the PID that process persisted via saveSessionRecord().
86
+ try {
87
+ const persisted = await loadSessionRecord(port);
88
+ if (persisted?.launched && persisted.pid) {
89
+ // Bound how far we trust a cross-process PID: if the Chrome we
90
+ // launched died outside this flow (OOM-killed, host slept, etc.)
91
+ // without its session record ever being cleared, the OS can recycle
92
+ // that PID for an unrelated process. There is no cmdline/start-time
93
+ // check available portably, so a coarse age bound is the practical
94
+ // guard — a PID persisted more than a day ago is far more likely to
95
+ // be stale/reused than to still be the same live Chrome.
96
+ const age = persisted.savedAt !== undefined ? Date.now() - persisted.savedAt : undefined;
97
+ if (age === undefined || age <= PERSISTED_PID_MAX_AGE_MS) {
98
+ pid = persisted.pid;
99
+ if (persisted.ownsUserDataDir) profileDir = persisted.userDataDir;
100
+ }
101
+ }
102
+ } catch {
103
+ // best-effort — fall through to "nothing to kill" below
104
+ }
105
+ }
106
+ if (pid === undefined) return; // not a process we launched, or too stale to trust — nothing to kill
107
+ launchedPids.delete(port);
108
+ ownedUserDataDirPorts.delete(port);
109
+
110
+ // Liveness-check before every SIGKILL (not just the safety-net path below)
111
+ // — process.kill(pid, 0) throws ESRCH if the PID is no longer running,
112
+ // which also catches the case where the PID has already been recycled by
113
+ // an unrelated process that happens to have exited too.
114
+ if (!gracefullyClosed) {
115
+ try {
116
+ process.kill(pid, 0);
117
+ process.kill(pid, 'SIGKILL');
118
+ } catch {
119
+ /* already exited, or never was — nothing to do */
120
+ }
121
+ } else if (!(await waitForProcessExit(pid))) {
122
+ // Browser.close was acknowledged — wait for the process to actually go
123
+ // away, then force-kill as a safety net in case it hung.
124
+ try {
125
+ process.kill(pid, 'SIGKILL');
126
+ } catch {
127
+ /* raced us to exit — expected */
128
+ }
129
+ }
130
+
131
+ // Waits (bounded) for the killed process to be gone before deleting.
132
+ if (profileDir) await removeOwnedProfileDir(profileDir, { pid });
133
+ }
134
+
135
+ /** Poll until `pid` is gone or PROCESS_EXIT_TIMEOUT_MS elapses. Returns
136
+ * whether it exited. `process.kill(pid, 0)` throws once the process is no
137
+ * longer there, on Windows as well as POSIX.
138
+ *
139
+ * This timer is deliberately NOT unref'd. closeBrowser() awaits this poll
140
+ * as part of its own return value — a caller that awaits closeBrowser() is
141
+ * actively blocked on it, not doing other work in the background. Once
142
+ * Chrome's CDP websocket closes (which happens right around here, as part
143
+ * of it shutting down), nothing else may be left holding the event loop
144
+ * open; an unref'd timer at that point never fires because Node considers
145
+ * the loop drained and exits without running it, leaving this promise (and
146
+ * closeBrowser()'s) pending forever — reproduced locally by closing a real
147
+ * launched browser with nothing else scheduled. Bounded by
148
+ * PROCESS_EXIT_TIMEOUT_MS (5s) either way, so keeping it ref'd only ever
149
+ * costs a caller a few seconds, never a hang. */
150
+ async function waitForProcessExit(pid: number): Promise<boolean> {
151
+ const deadline = Date.now() + PROCESS_EXIT_TIMEOUT_MS;
152
+ for (;;) {
153
+ try {
154
+ process.kill(pid, 0);
155
+ } catch {
156
+ return true;
157
+ }
158
+ if (Date.now() >= deadline) return false;
159
+ await new Promise((resolve) => {
160
+ setTimeout(resolve, PROCESS_EXIT_POLL_MS);
161
+ });
162
+ }
163
+ }
164
+
165
+ /**
166
+ * Give back the CDP port of a browser we launched that nothing is using any
167
+ * more. A launched Chrome is deliberately detached and unref'd so it outlives
168
+ * the command that spawned it and later commands can reattach — but nothing
169
+ * reaped it afterwards, so an abandoned session kept listening on its port
170
+ * (9222 by convention, which other local tools want) indefinitely. A foreign
171
+ * CDP server *answers* there rather than refusing the connection, so those
172
+ * tools retry the wrong port and report misleading errors instead of moving on.
173
+ *
174
+ * Nothing long-lived exists to run this on a timer — every CLI command is its
175
+ * own short-lived process — so it runs at the next launch/attach instead
176
+ * (see launchBrowser). A browser is reaped only when ALL of these hold:
177
+ * - the persisted session says WE launched it — `connect` records
178
+ * launched:false for a browser that belongs to the user, never touched;
179
+ * - that session is older than IDLE_REAP_AFTER_MS;
180
+ * - the CDP endpoint still answers and reports ZERO targets. An open tab,
181
+ * or a client attached to one (Chrome drops webSocketDebuggerUrl from an
182
+ * attached target but still lists it), means the session is live and
183
+ * reattach-across-commands must keep working.
184
+ *
185
+ * Shutdown goes through closeBrowser() on the browser-level websocket — the
186
+ * only connection left once every target is gone — so a recycled PID can
187
+ * never be signaled by mistake: graceful `Browser.close` reaches whatever is
188
+ * actually listening on that port, at any age, and the persisted PID is only
189
+ * ever used for closeBrowser's own age-bounded force-kill.
190
+ *
191
+ * Never throws: a failed reap must not stop a launch. Returns the reaped
192
+ * port, or null when there was nothing to reap. Sessions are per-port
193
+ * (#318), so every recorded one is considered, not just the newest.
194
+ */
195
+ export async function reapIdleLaunchedBrowser(): Promise<number | null> {
196
+ let reaped: number | null = null;
197
+ for (const session of await listSessionRecords().catch(() => [])) {
198
+ const port = await reapSession(session);
199
+ reaped ??= port;
200
+ }
201
+ return reaped;
202
+ }
203
+
204
+ async function reapSession(session: SessionRecord): Promise<number | null> {
205
+ try {
206
+ if (!session.launched || session.savedAt === undefined) return null;
207
+ if (Date.now() - session.savedAt < IDLE_REAP_AFTER_MS) return null;
208
+
209
+ const wsUrl = await fetchBrowserWebSocketUrl(session.port);
210
+ if (!wsUrl) return null;
211
+ if ((await fetchTargets(session.port)).length > 0) return null;
212
+
213
+ const client = new CdpClient();
214
+ let reapTimer: ReturnType<typeof setTimeout> | undefined;
215
+ try {
216
+ // CdpClient.connect() has no timeout of its own — a socket that never
217
+ // opens (and never errors) would hang the launch this reap is running
218
+ // inside of, which is strictly worse than leaving the port squatted.
219
+ // Not unref'd (see closeBrowser): a socket that never opens and never
220
+ // errors leaves this timer as the only thing that can settle the race,
221
+ // and the reap is awaited inside launch/attach. Cleared in the finally
222
+ // below so a connect that succeeds does not pin the event loop.
223
+ await Promise.race([
224
+ client.connect(wsUrl),
225
+ new Promise<never>((_, reject) => {
226
+ reapTimer = setTimeout(
227
+ () => reject(new Error('Reap: CDP connect timed out')),
228
+ REAP_CONNECT_TIMEOUT_MS,
229
+ );
230
+ }),
231
+ ]);
232
+ await closeBrowser(client, session.port);
233
+ } finally {
234
+ clearTimeout(reapTimer);
235
+ try {
236
+ client.close();
237
+ } catch {
238
+ /* already gone */
239
+ }
240
+ }
241
+ launchedPids.delete(session.port);
242
+ launchedUserDataDirs.delete(session.port);
243
+ await removeSessionRecord(session.port);
244
+ return session.port;
245
+ } catch {
246
+ return null;
247
+ }
248
+ }
@@ -0,0 +1,213 @@
1
+ // Split out of browser.ts (file-size sweep). Pure move: no behaviour change.
2
+
3
+ import { CdpClient, fetchNewTarget, fetchTargets } from './cdp.js';
4
+ import { enableConsoleCapture, setupConsoleCapture } from './console-log.js';
5
+ import { setupDialogAutoHandling } from './dialog.js';
6
+ import type { CdpTarget } from './types.js';
7
+
8
+ export async function enableSessionDomains(client: CdpClient, sessionId: string): Promise<void> {
9
+ await Promise.all([
10
+ client.send('Page.enable', {}, sessionId),
11
+ client.send('Runtime.enable', {}, sessionId),
12
+ client.send('Network.enable', {}, sessionId),
13
+ client.send('DOM.enable', {}, sessionId),
14
+ client.send('Accessibility.enable', {}, sessionId),
15
+ ]);
16
+ setupConsoleCapture(client, sessionId);
17
+ await enableConsoleCapture(client, sessionId);
18
+ setupDialogAutoHandling(client, sessionId);
19
+ }
20
+
21
+ export async function connectToTarget(
22
+ port: number,
23
+ targetId?: string,
24
+ ): Promise<{ client: CdpClient; target: CdpTarget; sessionId: string }> {
25
+ const targets = await fetchTargets(port);
26
+ const pageTargets = targets.filter((t) => t.type === 'page');
27
+
28
+ let target: CdpTarget;
29
+ if (targetId) {
30
+ const found = pageTargets.find((t) => t.id === targetId);
31
+ if (!found) throw new Error(`Target ${targetId} not found`);
32
+ target = found;
33
+ } else if (pageTargets.length > 0) {
34
+ target = pageTargets[0];
35
+ } else {
36
+ target = await fetchNewTarget(port, 'about:blank');
37
+ }
38
+
39
+ const wsUrl = target.webSocketDebuggerUrl ?? `ws://127.0.0.1:${port}/devtools/page/${target.id}`;
40
+ const client = new CdpClient();
41
+ await client.connect(wsUrl);
42
+
43
+ const { sessionId } = await client.send<{ sessionId: string }>('Target.attachToTarget', {
44
+ targetId: target.id,
45
+ flatten: true,
46
+ });
47
+
48
+ await enableSessionDomains(client, sessionId);
49
+ return { client, target, sessionId };
50
+ }
51
+
52
+ export async function openUrl(client: CdpClient, sessionId: string, url: string): Promise<void> {
53
+ // Cap to 2 MB to prevent OOM in CDP message serializer (e.g. data: URI attacks)
54
+ if (url.length > 2_097_152) throw new Error('URL exceeds 2 MB limit');
55
+ // Page.navigate reports a protocol-level failure (e.g. a refused connection)
56
+ // via errorText in its own response, before Chrome ever settles on the
57
+ // chrome-error://chromewebdata/ page — without this check a refused
58
+ // connection previously reported success against that error page.
59
+ const nav = await client.send<{ errorText?: string }>('Page.navigate', { url }, sessionId);
60
+ if (nav.errorText) throw new Error(`Navigation to ${url} failed: ${nav.errorText}`);
61
+ await waitForNetworkIdle(client, sessionId, 500, 30_000);
62
+ }
63
+
64
+ export async function waitForLoad(
65
+ client: CdpClient,
66
+ sessionId: string,
67
+ condition: 'load' | 'networkidle' | 'domcontentloaded' = 'load',
68
+ timeout = 30_000,
69
+ ): Promise<void> {
70
+ if (condition === 'load' || condition === 'domcontentloaded') {
71
+ // Guard against race where the page loads before the listener is registered
72
+ const readyExpr =
73
+ condition === 'load'
74
+ ? 'document.readyState === "complete"'
75
+ : 'document.readyState !== "loading"';
76
+ const readyCheck = await client
77
+ .send<{ result: { value?: boolean } }>(
78
+ 'Runtime.evaluate',
79
+ {
80
+ expression: readyExpr,
81
+ returnByValue: true,
82
+ },
83
+ sessionId,
84
+ )
85
+ .catch(() => ({ result: { value: false } }));
86
+ if (readyCheck.result?.value) return;
87
+
88
+ const event = condition === 'load' ? 'Page.loadEventFired' : 'Page.domContentEventFired';
89
+ const [eventPromise, cancelOnce] = client.onceWithOff(event, sessionId);
90
+ let timedOut = false;
91
+ let timeoutHandle: ReturnType<typeof setTimeout> | undefined;
92
+ const timeoutPromise = new Promise<void>((resolve) => {
93
+ timeoutHandle = setTimeout(() => {
94
+ timedOut = true;
95
+ resolve();
96
+ }, timeout);
97
+ });
98
+ try {
99
+ await Promise.race([eventPromise, timeoutPromise]);
100
+ if (timedOut) throw new Error(`Timeout waiting for ${condition}`);
101
+ } finally {
102
+ cancelOnce();
103
+ clearTimeout(timeoutHandle);
104
+ }
105
+ return;
106
+ }
107
+
108
+ // networkidle: no network requests for 500ms
109
+ await waitForNetworkIdle(client, sessionId, 500, timeout);
110
+ }
111
+
112
+ async function waitForNetworkIdle(
113
+ client: CdpClient,
114
+ sessionId: string,
115
+ idleMs: number,
116
+ timeout: number,
117
+ ): Promise<void> {
118
+ return new Promise((resolve, reject) => {
119
+ let pending = 0;
120
+ const inflight = new Set<string>();
121
+ let idleTimer: ReturnType<typeof setTimeout> | null = null;
122
+ const killTimer = setTimeout(() => {
123
+ cleanup();
124
+ reject(new Error('Timeout waiting for networkidle'));
125
+ }, timeout);
126
+
127
+ const cleanup = () => {
128
+ if (idleTimer) {
129
+ clearTimeout(idleTimer);
130
+ idleTimer = null;
131
+ }
132
+ clearTimeout(killTimer);
133
+ offReq();
134
+ offResp();
135
+ offFail();
136
+ offCache();
137
+ offResp2();
138
+ };
139
+
140
+ const settle = () => {
141
+ cleanup();
142
+ resolve();
143
+ };
144
+
145
+ const check = () => {
146
+ if (pending === 0) {
147
+ if (idleTimer) clearTimeout(idleTimer);
148
+ idleTimer = setTimeout(settle, idleMs);
149
+ } else {
150
+ if (idleTimer) {
151
+ clearTimeout(idleTimer);
152
+ idleTimer = null;
153
+ }
154
+ }
155
+ };
156
+
157
+ const offReq = client.on('Network.requestWillBeSent', (params, sid) => {
158
+ if (sid !== sessionId) return;
159
+ const id = params.requestId as string;
160
+ if (!inflight.has(id)) {
161
+ inflight.add(id);
162
+ pending++;
163
+ check();
164
+ }
165
+ });
166
+
167
+ const decrement = (params: Record<string, unknown>, sid?: string) => {
168
+ if (sid !== sessionId) return;
169
+ const id = params.requestId as string;
170
+ if (inflight.delete(id)) {
171
+ pending = Math.max(0, pending - 1);
172
+ check();
173
+ }
174
+ };
175
+
176
+ const offResp = client.on('Network.loadingFinished', decrement);
177
+ const offFail = client.on('Network.loadingFailed', decrement);
178
+ const offCache = client.on('Network.requestServedFromCache', decrement);
179
+ // Guard against requests that never fire loadingFinished/loadingFailed (e.g. data: URLs)
180
+ // Skip 3xx redirect responses — the request continues under the same requestId
181
+ const offResp2 = client.on('Network.responseReceived', (params, sid) => {
182
+ const p = params as { requestId: string; response: { status: number } };
183
+ if (p.response.status >= 300 && p.response.status < 400) return;
184
+ decrement(params, sid);
185
+ });
186
+
187
+ check();
188
+ });
189
+ }
190
+
191
+ export async function getCurrentUrl(client: CdpClient, sessionId: string): Promise<string> {
192
+ const result = await client.send<{ result: { value: string } }>(
193
+ 'Runtime.evaluate',
194
+ {
195
+ expression: 'location.href',
196
+ returnByValue: true,
197
+ },
198
+ sessionId,
199
+ );
200
+ return result.result?.value ?? '';
201
+ }
202
+
203
+ export async function getCurrentTitle(client: CdpClient, sessionId: string): Promise<string> {
204
+ const result = await client.send<{ result: { value: string } }>(
205
+ 'Runtime.evaluate',
206
+ {
207
+ expression: 'document.title',
208
+ returnByValue: true,
209
+ },
210
+ sessionId,
211
+ );
212
+ return result.result?.value ?? '';
213
+ }
@@ -0,0 +1,30 @@
1
+ // Split out of browser.ts (file-size sweep). Pure move: no behaviour change.
2
+
3
+ // Tracks the PID of Chrome instances *we* spawned, keyed by CDP port, so
4
+ // closeBrowser() has a kill fallback when the graceful `Browser.close` CDP
5
+ // command fails or times out (e.g. a hung renderer). Ports we merely attached
6
+ // to (already-running browser) are never recorded here — we only ever kill
7
+ // processes we launched ourselves.
8
+ export const launchedPids = new Map<number, number>();
9
+ // userDataDir per launched port, persisted alongside the pid so a later
10
+ // process can clean up the temp profile dir too (#395).
11
+ export const launchedUserDataDirs = new Map<number, string>();
12
+ // Launched ports whose userDataDir monobrowse created itself (not one the
13
+ // caller supplied). Only these profile dirs are ever deleted on close.
14
+ export const ownedUserDataDirPorts = new Set<number>();
15
+
16
+ /** PID of the Chrome instance *this process* launched on `port`, if any. */
17
+ export function getLaunchedPid(port: number): number | undefined {
18
+ return launchedPids.get(port);
19
+ }
20
+
21
+ /** userDataDir of the Chrome instance *this process* launched on `port`, if any. */
22
+ export function getLaunchedUserDataDir(port: number): string | undefined {
23
+ return launchedUserDataDirs.get(port);
24
+ }
25
+
26
+ /** Whether the userDataDir of the Chrome *this process* launched on `port`
27
+ * was created by monobrowse, and so is deleted when that browser closes. */
28
+ export function ownsLaunchedUserDataDir(port: number): boolean {
29
+ return ownedUserDataDirPorts.has(port);
30
+ }