cdp-toolkit 3.1.0 → 3.3.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.
@@ -0,0 +1,366 @@
1
+ /**
2
+ * bidi-browser-tools.ts: Firefox (WebDriver BiDi) implementations of the two BROWSER-scoped tools,
3
+ * `wait_for_download` (capability "browser.downloads") and `grant_permissions` ("browser.permissions").
4
+ * Same argument schema, same validation (imported from the Chrome modules, never re-derived) and the
5
+ * same result shapes as src/tools/downloads.ts and src/tools/permissions.ts. Both need Firefox 160+
6
+ * (BIDI_CAPABILITY_MIN_FIREFOX in ./bidi/driver.ts); an older Firefox gets "unsupported" naming the
7
+ * version before any browser state is touched.
8
+ *
9
+ * HOW THEY REACH THE CONNECTION. Both tools first acquire `driver.page(target)` — that is the
10
+ * Firefox lease choke point (resolveContext) and the source of the `target` field — then do the
11
+ * browser-wide work through BidiBrowserDriver.withBrowserConnection, and register a dispose hook
12
+ * (BidiBrowserDriver.setDisposeHook) for state that must not outlive this process.
13
+ *
14
+ * MEASURED on headless Firefox 160.0 (probes /tmp/ffpar/dlperm/probe.ts, probe3.ts):
15
+ * - browser.setDownloadBehavior {type:"allowed", destinationFolder} redirects every download;
16
+ * `downloadBehavior: null` restores the profile's own behavior (a later download landed in the
17
+ * profile's browser.download.dir, not the capture folder). The override does NOT survive
18
+ * session.end — but in attach mode through the mux (./bidi/mux.ts) a joiner's session.end is
19
+ * answered locally, so the explicit null restore is the only restore there.
20
+ * - downloadWillBegin/downloadEnd fire for EVERY download, armed or not; the user's own downloads
21
+ * included. Only a download whose filepath is inside our staging folder is ever recorded.
22
+ * - Firefox de-duplicates a name collision itself ("one.txt" -> "one(1).txt") and reports the
23
+ * de-duplicated name as suggestedFilename.
24
+ * - permissions.setPermission: granted/denied/prompt are reflected by navigator.permissions.query.
25
+ * A grant SURVIVES session.end and a fresh session.new (it lives in the profile's permission
26
+ * manager), unlike Chrome's, which dies with the granting CDP client.
27
+ * - Firefox's PermissionName enum rejects clipboard-read/clipboard-write, background-sync,
28
+ * local-fonts, idle-detection, accelerometer ("not a valid value for enumeration"), and
29
+ * storage-access is "currently unsupported".
30
+ *
31
+ * ASYMMETRIES vs CHROME (for the README):
32
+ * 1. Downloads: Chrome stays armed for the life of the server once armed. Firefox is armed by
33
+ * every wait_for_download call and DISARMED (downloadBehavior:null) when a collecting call
34
+ * returns or times out, so the user's everyday Firefox goes back to normal downloads. A download
35
+ * started after one collecting call and before the next arm is therefore not captured: on
36
+ * Firefox, arm (arm:true or a pending wait) before EVERY download, not just the first.
37
+ * 2. Downloads: while armed, ANY download in that Firefox (including one the human starts) is
38
+ * redirected into the capture folder and can be the one a wait returns.
39
+ * 3. Downloads: two same-named downloads both uncollected at once get Firefox's own "(1)" suffix
40
+ * in suggestedFilename (Firefox de-dupes inside the staging folder before we see the name);
41
+ * the common case still gets Chrome's "name-1.ext" via nextFreeName.
42
+ * 4. Permissions take W3C descriptors, so Chrome PermissionType names are mapped through
43
+ * FIREFOX_PERMISSION_DESCRIPTORS — a local allowlist, which Chrome's implementation
44
+ * deliberately does not keep. A name with no measured Firefox equivalent is refused
45
+ * ("unsupported", naming it) before anything is granted, never silently skipped.
46
+ * 5. Permissions persist in the Firefox profile. To keep Chrome's "the grant lives as long as the
47
+ * server process" contract (and leave the user's Firefox as it was), every grant is undone
48
+ * when the session is disposed (server shutdown; end of a CLI command) and by reset:true. The
49
+ * undo restores the state the page reported BEFORE the first grant when the grant origin is the
50
+ * target tab's own origin; for any other origin the prior state cannot be read, and it is
51
+ * restored to "prompt". A process killed with SIGKILL leaves its grants in the profile.
52
+ * 6. Per CDP's docs (not measured here) Browser.grantPermissions also rejects the permissions it
53
+ * was NOT given for that origin; Firefox's setPermission touches only the named ones, and this
54
+ * implementation deliberately does not deny everything else in the user's real profile.
55
+ * 7. All of the above was measured headless. Download-panel / dialog behavior of a headed
56
+ * everyday Firefox under "allowed" was not observed.
57
+ */
58
+ import { mkdir, readdir, realpath, rename, stat } from "node:fs/promises";
59
+ import { basename, dirname, join, resolve } from "node:path";
60
+ import type { BidiConnection } from "./bidi/client.ts";
61
+ import { requireFirefox } from "./bidi/driver.ts";
62
+ import type { PermissionsPermissionDescriptor, PermissionsPermissionState } from "./bidi/protocol.ts";
63
+ import type { BrowserDriver, DriverError, PageDriver } from "./driver.ts";
64
+ import { DOWNLOADS_DIR, DOWNLOAD_BUFFER_LIMIT } from "./tools/browser-session.ts";
65
+ import {
66
+ nextFreeName, safeFilename, validateWaitForDownloadArgs,
67
+ type ArmDownloadResult, type WaitForDownloadArgs, type WaitForDownloadResult,
68
+ } from "./tools/downloads.ts";
69
+ import { originOf, validateGrantPermissionsArgs, type GrantPermissionsArgs, type GrantPermissionsResult } from "./tools/permissions.ts";
70
+
71
+ function unsupported(message: string): DriverError {
72
+ return Object.assign(new Error(message), { code: "unsupported" as const }) as DriverError;
73
+ }
74
+
75
+ /** The slice of BidiConnection these tools use; a structural type so tests can pass a stub. */
76
+ export type BrowserConn = Pick<BidiConnection, "send" | "on" | "capabilities">;
77
+
78
+ /** What BidiBrowserDriver adds for browser-scoped work (see its withBrowserConnection). */
79
+ interface BrowserScope {
80
+ withBrowserConnection<T>(fn: (conn: BrowserConn) => Promise<T>): Promise<T>;
81
+ setDisposeHook(key: string, hook: ((conn: BrowserConn) => Promise<void>) | undefined): void;
82
+ }
83
+
84
+ function scopeOf(driver: BrowserDriver, tool: string): BrowserScope {
85
+ const d = driver as Partial<BrowserScope>;
86
+ if (typeof d.withBrowserConnection !== "function" || typeof d.setDisposeHook !== "function") {
87
+ throw unsupported(`${tool}: this driver has no browser-scoped connection (the Firefox BiDi driver does; Chrome uses src/tools/).`);
88
+ }
89
+ return d as BrowserScope;
90
+ }
91
+
92
+ async function targetOf(driver: BrowserDriver, target: WaitForDownloadArgs["target"]): Promise<{ id: string; url: string; title: string }> {
93
+ const page = await driver.page(target);
94
+ try {
95
+ return { id: page.info.id, url: page.info.url, title: page.info.title };
96
+ } finally {
97
+ await page.release();
98
+ }
99
+ }
100
+
101
+ /* ===================================== downloads ===================================== */
102
+
103
+ /** Firefox writes here; wait_for_download then renames each file into DOWNLOADS_DIR under the
104
+ * page's own name, exactly as Chrome's guid files are renamed. A SIBLING of DOWNLOADS_DIR, never
105
+ * inside it, so it cannot count as a filename collision. */
106
+ export const FIREFOX_DOWNLOAD_STAGING_DIR = join(dirname(DOWNLOADS_DIR), "downloads-firefox-staging");
107
+
108
+ interface FfDownload {
109
+ id: string;
110
+ url?: string;
111
+ suggestedFilename?: string;
112
+ /** Where the finished file sits now (moved off Firefox's own name into an id-named file). */
113
+ filePath?: string;
114
+ state: "inProgress" | "completed";
115
+ consumed: boolean;
116
+ }
117
+
118
+ interface DownloadState {
119
+ downloads: FfDownload[];
120
+ /** In-progress downloads by id, until downloadEnd decides whether they are ours. */
121
+ begun: Map<string, FfDownload>;
122
+ waiters: Array<(r: FfDownload) => void>;
123
+ /** Accepted spellings of the staging folder (macOS /tmp -> /private/tmp). */
124
+ stagingDirs: Set<string>;
125
+ }
126
+
127
+ const downloadStates = new WeakMap<object, DownloadState>();
128
+
129
+ /** willBegin/downloadEnd correlate on `download` per the spec; Firefox 160 also populates
130
+ * `navigation` with the same id, so either is accepted. */
131
+ function downloadId(p: { download?: unknown; navigation?: unknown }): string | undefined {
132
+ const v = p.download ?? p.navigation;
133
+ return typeof v === "string" && v.length > 0 ? v : undefined;
134
+ }
135
+
136
+ function deliver(s: DownloadState, r: FfDownload): void {
137
+ r.state = "completed";
138
+ s.downloads.push(r);
139
+ while (s.downloads.length > DOWNLOAD_BUFFER_LIMIT) {
140
+ const i = s.downloads.findIndex((d) => d.consumed);
141
+ s.downloads.splice(i >= 0 ? i : 0, 1);
142
+ }
143
+ const waiter = s.waiters.shift();
144
+ if (waiter) {
145
+ r.consumed = true;
146
+ waiter(r);
147
+ }
148
+ }
149
+
150
+ function downloadStateFor(conn: BrowserConn): DownloadState {
151
+ let s = downloadStates.get(conn);
152
+ if (s) return s;
153
+ const state: DownloadState = { downloads: [], begun: new Map(), waiters: [], stagingDirs: new Set([resolve(FIREFOX_DOWNLOAD_STAGING_DIR)]) };
154
+ downloadStates.set(conn, state);
155
+ conn.on("browsingContext.downloadWillBegin", (p) => {
156
+ const id = downloadId(p);
157
+ if (!id) return;
158
+ state.begun.set(id, { id, url: p.url, suggestedFilename: p.suggestedFilename, state: "inProgress", consumed: false });
159
+ // Bound the map: a download that never reports an end must not grow it forever.
160
+ if (state.begun.size > DOWNLOAD_BUFFER_LIMIT) state.begun.delete(state.begun.keys().next().value as string);
161
+ });
162
+ conn.on("browsingContext.downloadEnd", (p) => {
163
+ const id = downloadId(p);
164
+ if (!id) return;
165
+ const rec = state.begun.get(id) ?? { id, state: "inProgress" as const, consumed: false };
166
+ state.begun.delete(id);
167
+ if (p.status !== "complete" || !p.filepath) return; // canceled, or nothing on disk: never returned
168
+ // Only OUR captures: an unarmed download (the human's own, into their normal folder) is left alone.
169
+ if (!state.stagingDirs.has(resolve(dirname(p.filepath)))) return;
170
+ rec.url ??= p.url;
171
+ const held = join(dirname(p.filepath), `${id.replace(/[^A-Za-z0-9-]/g, "_")}.download`);
172
+ // Move off Firefox's own name at once, so the next same-named download is not de-duplicated
173
+ // by Firefox into "name(1).ext" while this one waits to be collected.
174
+ rename(p.filepath, held).then(
175
+ () => { rec.filePath = held; },
176
+ () => { rec.filePath = p.filepath ?? undefined; },
177
+ ).finally(() => deliver(state, rec));
178
+ });
179
+ return state;
180
+ }
181
+
182
+ async function armFirefoxDownloads(conn: BrowserConn, s: DownloadState, scope: BrowserScope): Promise<void> {
183
+ await mkdir(FIREFOX_DOWNLOAD_STAGING_DIR, { recursive: true });
184
+ await mkdir(DOWNLOADS_DIR, { recursive: true });
185
+ s.stagingDirs.add(resolve(await realpath(FIREFOX_DOWNLOAD_STAGING_DIR)));
186
+ // The restore is registered BEFORE the override, so there is no window in which the browser is
187
+ // redirected with nothing scheduled to put it back.
188
+ scope.setDisposeHook("browser.downloads", async (c) => { await c.send("browser.setDownloadBehavior", { downloadBehavior: null }); });
189
+ await conn.send("browser.setDownloadBehavior", { downloadBehavior: { type: "allowed", destinationFolder: FIREFOX_DOWNLOAD_STAGING_DIR } });
190
+ }
191
+
192
+ async function disarmFirefoxDownloads(conn: BrowserConn, scope: BrowserScope): Promise<void> {
193
+ await conn.send("browser.setDownloadBehavior", { downloadBehavior: null });
194
+ scope.setDisposeHook("browser.downloads", undefined);
195
+ }
196
+
197
+ function nextFirefoxDownload(s: DownloadState, timeoutMs: number): Promise<FfDownload> {
198
+ const buffered = s.downloads.find((d) => !d.consumed);
199
+ if (buffered) {
200
+ buffered.consumed = true;
201
+ return Promise.resolve(buffered);
202
+ }
203
+ return new Promise<FfDownload>((resolvePromise, reject) => {
204
+ const waiter = (r: FfDownload): void => {
205
+ clearTimeout(timer);
206
+ resolvePromise(r);
207
+ };
208
+ const timer = setTimeout(() => {
209
+ const i = s.waiters.indexOf(waiter);
210
+ if (i >= 0) s.waiters.splice(i, 1);
211
+ reject(new Error(
212
+ `wait_for_download: no download completed within ${timeoutMs}ms. On Firefox, downloads are captured only while a wait_for_download call is armed: arm (arm:true) BEFORE the triggering click, and again before every later download, because each collecting call restores Firefox's normal download behavior when it returns.`,
213
+ ));
214
+ }, timeoutMs);
215
+ s.waiters.push(waiter);
216
+ });
217
+ }
218
+
219
+ /** Firefox `wait_for_download`. Same args, validation and result shapes as src/tools/downloads.ts. */
220
+ export async function waitForDownloadFirefox(driver: BrowserDriver, args: WaitForDownloadArgs = {}): Promise<WaitForDownloadResult | ArmDownloadResult> {
221
+ validateWaitForDownloadArgs(args);
222
+ const scope = scopeOf(driver, "wait_for_download");
223
+ const target = await targetOf(driver, args.target); // the lease gate, before any browser state is touched
224
+ return scope.withBrowserConnection(async (conn) => {
225
+ requireFirefox(conn, "browser.downloads");
226
+ const s = downloadStateFor(conn);
227
+ await armFirefoxDownloads(conn, s, scope);
228
+ if (args.arm === true) {
229
+ return { armed: true as const, downloadPath: DOWNLOADS_DIR, pending: s.downloads.filter((d) => !d.consumed).length, target };
230
+ }
231
+ let rec: FfDownload;
232
+ try {
233
+ rec = await nextFirefoxDownload(s, args.timeoutMs ?? 30_000);
234
+ } finally {
235
+ // Put the user's Firefox back to normal downloads — unless another wait is still pending on
236
+ // this connection, which still needs capture armed.
237
+ if (s.waiters.length === 0) await disarmFirefoxDownloads(conn, scope).catch(() => undefined);
238
+ }
239
+ if (!rec.filePath) {
240
+ throw new Error(`wait_for_download: download ${rec.id} completed without a file path (nothing to return)`);
241
+ }
242
+ const suggestedFilename = safeFilename(rec.suggestedFilename);
243
+ const taken = new Set(await readdir(DOWNLOADS_DIR).catch(() => [] as string[]));
244
+ taken.delete(basename(rec.filePath));
245
+ const finalName = nextFreeName(suggestedFilename, taken);
246
+ const path = join(DOWNLOADS_DIR, finalName);
247
+ await rename(rec.filePath, path);
248
+ const bytes = (await stat(path)).size;
249
+ return { path, suggestedFilename, bytes, ...(rec.url ? { url: rec.url } : {}), target };
250
+ });
251
+ }
252
+
253
+ /* ==================================== permissions ==================================== */
254
+
255
+ /**
256
+ * Chrome PermissionType name -> the W3C PermissionDescriptor Firefox 160's permissions.setPermission
257
+ * accepts. ONLY pairs measured working (setPermission succeeded AND navigator.permissions.query
258
+ * followed) are listed; everything else is refused by name. Chrome's notifications grant also covers
259
+ * push; on Firefox, granting notifications made a {name:"push"} query report "granted" too (measured).
260
+ */
261
+ export const FIREFOX_PERMISSION_DESCRIPTORS: Readonly<Record<string, PermissionsPermissionDescriptor>> = {
262
+ geolocation: { name: "geolocation" },
263
+ notifications: { name: "notifications" },
264
+ audioCapture: { name: "microphone" },
265
+ videoCapture: { name: "camera" },
266
+ durableStorage: { name: "persistent-storage" },
267
+ midi: { name: "midi" },
268
+ midiSysex: { name: "midi", sysex: true },
269
+ wakeLockScreen: { name: "screen-wake-lock" },
270
+ };
271
+
272
+ /** Map every name or throw "unsupported" naming the first unmappable one. Pure, for unit tests. */
273
+ export function mapFirefoxPermissions(names: readonly string[]): PermissionsPermissionDescriptor[] {
274
+ return names.map((n) => {
275
+ const d = Object.hasOwn(FIREFOX_PERMISSION_DESCRIPTORS, n) ? FIREFOX_PERMISSION_DESCRIPTORS[n] : undefined;
276
+ if (!d) {
277
+ throw unsupported(
278
+ `grant_permissions: permission '${n}' is not supported on Firefox (WebDriver BiDi permissions.setPermission has no measured equivalent). Supported on Firefox: ${Object.keys(FIREFOX_PERMISSION_DESCRIPTORS).join(", ")}.`,
279
+ );
280
+ }
281
+ return d;
282
+ });
283
+ }
284
+
285
+ interface TrackedGrant {
286
+ origin: string;
287
+ descriptor: PermissionsPermissionDescriptor;
288
+ /** The state to put back on reset/dispose: what the page reported before our first grant. */
289
+ previous: PermissionsPermissionState;
290
+ }
291
+
292
+ /** Grants this process made, per driver (the dispose hook is per driver endpoint). */
293
+ const trackedGrants = new WeakMap<object, Map<string, TrackedGrant>>();
294
+
295
+ function grantKey(origin: string, d: PermissionsPermissionDescriptor): string {
296
+ return `${origin} ${JSON.stringify(d)}`;
297
+ }
298
+
299
+ async function restoreGrants(conn: BrowserConn, grants: Map<string, TrackedGrant>): Promise<void> {
300
+ const all = [...grants.values()];
301
+ grants.clear();
302
+ for (const g of all) {
303
+ await conn.send("permissions.setPermission", { descriptor: g.descriptor, state: g.previous, origin: g.origin });
304
+ }
305
+ }
306
+
307
+ async function queryState(page: PageDriver, d: PermissionsPermissionDescriptor): Promise<PermissionsPermissionState> {
308
+ try {
309
+ const v = await page.evaluate(
310
+ `navigator.permissions.query(${JSON.stringify(d)}).then((p) => p.state, () => "prompt")`,
311
+ { awaitPromise: true },
312
+ );
313
+ return v === "granted" || v === "denied" ? v : "prompt";
314
+ } catch {
315
+ return "prompt";
316
+ }
317
+ }
318
+
319
+ /** Firefox `grant_permissions`. Same args, validation and result shape as src/tools/permissions.ts. */
320
+ export async function grantPermissionsFirefox(driver: BrowserDriver, args: GrantPermissionsArgs = {}): Promise<GrantPermissionsResult> {
321
+ validateGrantPermissionsArgs(args);
322
+ const reset = args.reset === true;
323
+ const permissions = args.permissions ?? [];
324
+ // Every name is mapped BEFORE anything is granted: one bad name must not leave a half-applied grant.
325
+ const descriptors = mapFirefoxPermissions(permissions);
326
+ const scope = scopeOf(driver, "grant_permissions");
327
+ let grants = trackedGrants.get(driver);
328
+ if (!grants) { grants = new Map(); trackedGrants.set(driver, grants); }
329
+ const tracked = grants;
330
+
331
+ const page = await driver.page(args.target); // the lease gate
332
+ try {
333
+ const target = { id: page.info.id, url: page.info.url, title: page.info.title };
334
+ return await scope.withBrowserConnection(async (conn) => {
335
+ requireFirefox(conn, "browser.permissions");
336
+ if (reset) await restoreGrants(conn, tracked);
337
+ if (permissions.length === 0) return { reset: true as const, target };
338
+
339
+ const origin = args.origin ?? originOf(page.info.url);
340
+ if (!origin) {
341
+ throw new Error(
342
+ `grant_permissions: cannot derive an origin from the target tab's url (${JSON.stringify(page.info.url)}); pass 'origin' explicitly, e.g. origin:"https://example.com"`,
343
+ );
344
+ }
345
+ const pageIsOrigin = originOf(page.info.url) === origin;
346
+ // Restore is registered before the first grant lands (see armFirefoxDownloads for why).
347
+ scope.setDisposeHook("browser.permissions", (c) => restoreGrants(c, tracked));
348
+ for (const d of descriptors) {
349
+ const key = grantKey(origin, d);
350
+ if (!tracked.has(key)) {
351
+ tracked.set(key, { origin, descriptor: d, previous: pageIsOrigin ? await queryState(page, d) : "prompt" });
352
+ }
353
+ await conn.send("permissions.setPermission", { descriptor: d, state: "granted", origin });
354
+ }
355
+ return { granted: [...permissions], origin, ...(reset ? { reset: true as const } : {}), target };
356
+ });
357
+ } finally {
358
+ await page.release();
359
+ }
360
+ }
361
+
362
+ /** Registered in src/firefox-tools.ts. */
363
+ export const BIDI_BROWSER_TOOLS = {
364
+ wait_for_download: waitForDownloadFirefox,
365
+ grant_permissions: grantPermissionsFirefox,
366
+ } satisfies Record<string, (driver: BrowserDriver, args: never) => Promise<unknown>>;
package/src/bidi-tools.ts CHANGED
@@ -10,6 +10,7 @@
10
10
  import type { BrowserDriver, InterceptRule, PageDriver, PageInfo } from "./driver.ts";
11
11
  import { selectRule, buildFulfillParams, effectiveAction } from "./tools/network_mock.ts";
12
12
  import type { TargetSelector } from "./types.ts";
13
+ import { modifierBits, validateDispatchMouseArgs, type DispatchMouseArgs, type DispatchMouseResult } from "./tools/dispatch-mouse.ts";
13
14
  import { isWorkerSelector, WORKER_SELECTOR_UNSUPPORTED_MESSAGE } from "./workers.ts";
14
15
 
15
16
  class BidiToolError extends Error {}
@@ -23,6 +24,20 @@ async function withPage<T>(driver: BrowserDriver, target: TargetSelector | undef
23
24
  }
24
25
  }
25
26
 
27
+ /* ------------------------------ dispatch_mouse (Firefox 160+) ------------------------------ */
28
+ // Same schema, validator and result shape as Chrome's tools/dispatch-mouse.ts (capability "input.raw");
29
+ // the event itself rides PageDriver.dispatchMouse (bidi/driver.ts, one pointer action per call).
30
+ // A page driver without that method (Chrome's, which never reaches this registry) is "unsupported".
31
+ export async function dispatchMouse(driver: BrowserDriver, args: DispatchMouseArgs): Promise<DispatchMouseResult> {
32
+ validateDispatchMouseArgs(args);
33
+ modifierBits(args.modifiers); // validates the closed Alt/Control/Meta/Shift enum, same refusal text as Chrome
34
+ return withPage(driver, args.target, async (page) => {
35
+ if (!page.dispatchMouse) throw new BidiToolError("dispatch_mouse: this page driver has no raw mouse dispatch");
36
+ await page.dispatchMouse({ action: args.action, x: args.x, y: args.y, button: args.button, clickCount: args.clickCount, modifiers: args.modifiers });
37
+ return { dispatched: args.action, x: args.x, y: args.y };
38
+ });
39
+ }
40
+
26
41
  /* ------------------------------ console + network (4) ------------------------------ */
27
42
  // No recorder-style raw-CDP buffer exists for the neutral driver. Buffering rides
28
43
  // PageDriver.on(), scoped to the calling process's lifetime, an identical constraint
@@ -113,7 +128,7 @@ export async function listNetworkRequests(
113
128
 
114
129
  export async function getNetworkRequest(
115
130
  driver: BrowserDriver,
116
- args: { target?: TargetSelector; requestId?: string; url?: string } = {},
131
+ args: { target?: TargetSelector; requestId?: string; url?: string; includeBody?: boolean } = {},
117
132
  ): Promise<Record<string, unknown>> {
118
133
  refuseWorkerSelector(driver, args.target);
119
134
  if (!args.requestId && !args.url) throw new BidiToolError("get_network_request requires requestId or url");
@@ -122,6 +137,17 @@ export async function getNetworkRequest(
122
137
  const found = args.requestId
123
138
  ? buf.find((r) => r.requestId === args.requestId || r.request === args.requestId)
124
139
  : buf.find((r) => typeof r.url === "string" && (r.url as string).includes(args.url as string));
140
+ if (args.includeBody) {
141
+ // Firefox >= 160 retains response bodies per SESSION (network.responseBodyPostHoc, armed when
142
+ // the session is created), so a body is readable for a request made BEFORE this call, by its
143
+ // request id, with no reload. A requestId therefore needs no buffer entry; a url alone does,
144
+ // because the url -> id map is the buffer (filled by list_network_requests{reload:true}).
145
+ // A driver without the capability answers getResponseBody with "unsupported", surfaced as is.
146
+ const id = args.requestId ?? (found ? String(found.requestId ?? found.request ?? "") : "");
147
+ if (!id) throw new BidiToolError("get_network_request includeBody on this backend needs a requestId, or a url already present in the buffer (run list_network_requests with reload first)");
148
+ const { body, base64Encoded } = await page.getResponseBody(id);
149
+ return { ...(found ?? { requestId: id }), body, bodyBase64Encoded: base64Encoded };
150
+ }
125
151
  if (!found) throw new BidiToolError("no matching network request in the current buffer; run list_network_requests first");
126
152
  return found;
127
153
  });
@@ -202,7 +228,7 @@ export async function clearMocks(
202
228
  // `intercept(rules)` surface rather than re-implementing.
203
229
  void selectRule; void buildFulfillParams; void effectiveAction;
204
230
 
205
- /** The 7 Firefox-only tools: no Chrome equivalent is wired through this file (see header). */
231
+ /** The 7 Firefox-only tools, plus dispatch_mouse (a Firefox handler beside Chrome's tools/dispatch-mouse.ts). */
206
232
  export const BIDI_ONLY_TOOLS = {
207
233
  list_console_messages: listConsoleMessages,
208
234
  get_console_message: getConsoleMessage,
@@ -211,4 +237,5 @@ export const BIDI_ONLY_TOOLS = {
211
237
  mock_request: mockRequest,
212
238
  list_mocks: listMocks,
213
239
  clear_mocks: clearMocks,
240
+ dispatch_mouse: dispatchMouse,
214
241
  } satisfies Record<string, (driver: BrowserDriver, args: never) => Promise<unknown>>;
package/src/cdp/driver.ts CHANGED
@@ -5,7 +5,8 @@
5
5
  * one connection via openPage and holds it for the PageDriver's life; release() closes it. Uid
6
6
  * codec (scheme "cdp"): `cdp:<backendDOMNodeId>`, or a bare legacy numeric uid, per THE UID CODEC block in ../driver.ts.
7
7
  */
8
- import { CdpConnection, CdpError, listTargets, openBrowser, openPage, resolveTarget } from "../client.ts";
8
+ import { CdpConnection, CdpError, listTargets, openBrowser, openPage, resolveTarget, type PageConnection } from "../client.ts";
9
+ import { openSession } from "./session.ts";
9
10
  import type { Target, TargetSelector } from "../types.ts";
10
11
  import { chromeLeaseBackend, LeaseConflictError } from "../leases.ts";
11
12
  import { currentEndpoint } from "../endpoints.ts";
@@ -82,7 +83,7 @@ export function cdpSameSite(sameSite?: "strict" | "lax" | "none" | "default"): "
82
83
 
83
84
  /* ---------------------- copied helpers, see attributions below ---------------------- */
84
85
  // Copied verbatim from src/tools/input.ts `centerOf`: scroll into view, read viewport-space center.
85
- async function centerOf(conn: CdpConnection, objectId: string): Promise<{ x: number; y: number }> {
86
+ async function centerOf(conn: PageConnection, objectId: string): Promise<{ x: number; y: number }> {
86
87
  const fn = "function(){this.scrollIntoView({block:'center',inline:'center'});const r=this.getBoundingClientRect();if(r.width===0&&r.height===0)return null;return {x:r.left+r.width/2,y:r.top+r.height/2};}";
87
88
  const { result, exceptionDetails } = await conn.send<{ result: { value?: { x: number; y: number } | null }; exceptionDetails?: { text?: string } }>(
88
89
  "Runtime.callFunctionOn", { objectId, functionDeclaration: fn, returnByValue: true },
@@ -91,7 +92,7 @@ async function centerOf(conn: CdpConnection, objectId: string): Promise<{ x: num
91
92
  if (!result.value) throw driverError("page-error", "element has zero size / is not visible; cannot compute a click point");
92
93
  return result.value;
93
94
  }
94
- async function focusElement(conn: CdpConnection, objectId: string): Promise<void> {
95
+ async function focusElement(conn: PageConnection, objectId: string): Promise<void> {
95
96
  await conn.send("Runtime.callFunctionOn", { objectId, functionDeclaration: "function(){this.focus&&this.focus();}", returnByValue: true });
96
97
  }
97
98
  /**
@@ -113,10 +114,10 @@ async function focusElement(conn: CdpConnection, objectId: string): Promise<void
113
114
  const ARM_SCROLL_SETTLE_WATCH =
114
115
  "(function(){window.__cdpScrollSettle=new Promise((resolve)=>{let t;const done=()=>{window.removeEventListener('scroll',on,true);resolve(true);};" +
115
116
  "const on=()=>{clearTimeout(t);t=setTimeout(done,60);};window.addEventListener('scroll',on,true);t=setTimeout(done,60);setTimeout(done,500);});})()";
116
- async function armScrollSettleWatch(conn: CdpConnection): Promise<void> {
117
+ async function armScrollSettleWatch(conn: PageConnection): Promise<void> {
117
118
  await conn.send("Runtime.evaluate", { expression: ARM_SCROLL_SETTLE_WATCH, returnByValue: true });
118
119
  }
119
- async function awaitScrollSettle(conn: CdpConnection): Promise<void> {
120
+ async function awaitScrollSettle(conn: PageConnection): Promise<void> {
120
121
  // Best-effort: a navigation racing the wheel event could tear down window.__cdpScrollSettle
121
122
  // before this reads it, and that is not a scroll failure worth surfacing as one.
122
123
  await conn.send("Runtime.evaluate", { expression: "window.__cdpScrollSettle", awaitPromise: true, returnByValue: true }).catch(() => undefined);
@@ -130,7 +131,7 @@ async function awaitScrollSettle(conn: CdpConnection): Promise<void> {
130
131
  // It is a parameter rather than a `conn.send` here because the choke point is per-PAGE
131
132
  // (it knows the target id) and this helper only has a connection.
132
133
  async function setValueOnObject(
133
- conn: CdpConnection,
134
+ conn: PageConnection,
134
135
  objectId: string,
135
136
  value: string,
136
137
  sendInput: (method: string, params: Record<string, unknown>) => Promise<unknown>,
@@ -246,7 +247,7 @@ function axExtras(node: AxNode): Record<string, string> {
246
247
  }
247
248
  /* ------------------------------- locator helpers ------------------------------- */
248
249
  // css branch copied from src/tools/input.ts `resolveElement`; uid/text/xpath branches are new.
249
- async function resolveElementLocator(conn: CdpConnection, loc: ElementLocator): Promise<{ objectId: string }> {
250
+ async function resolveElementLocator(conn: PageConnection, loc: ElementLocator): Promise<{ objectId: string }> {
250
251
  if ("uid" in loc) {
251
252
  return resolveUid(conn, decodeUid(loc.uid)).catch(() => {
252
253
  throw driverError("stale-uid", `uid does not resolve: ${loc.uid}`);
@@ -271,7 +272,7 @@ async function resolveElementLocator(conn: CdpConnection, loc: ElementLocator):
271
272
  * XPath expression and disambiguates them itself. Not copied from any tools/ module (none
272
273
  * implement this); built only on the client primitives per CONTRACT.md rule 2.
273
274
  */
274
- async function searchLocate(conn: CdpConnection, query: string): Promise<number> {
275
+ async function searchLocate(conn: PageConnection, query: string): Promise<number> {
275
276
  await conn.send("DOM.getDocument", { depth: 0 }).catch(() => undefined);
276
277
  const { searchId, resultCount } = await conn.send<{ searchId: string; resultCount: number }>("DOM.performSearch", { query });
277
278
  try {
@@ -286,7 +287,7 @@ async function searchLocate(conn: CdpConnection, query: string): Promise<number>
286
287
  }
287
288
  }
288
289
 
289
- async function backendNodeIdOf(conn: CdpConnection, loc: ElementLocator): Promise<number> {
290
+ async function backendNodeIdOf(conn: PageConnection, loc: ElementLocator): Promise<number> {
290
291
  if ("uid" in loc) return decodeUid(loc.uid);
291
292
  if ("css" in loc) {
292
293
  const { objectId } = await resolveElementLocator(conn, loc);
@@ -324,7 +325,7 @@ interface LayoutMetrics {
324
325
  cssVisualViewport?: { pageX?: number; pageY?: number; clientWidth?: number; clientHeight?: number };
325
326
  cssContentSize?: { width: number; height: number };
326
327
  }
327
- async function layoutMetrics(conn: CdpConnection): Promise<LayoutMetrics> {
328
+ async function layoutMetrics(conn: PageConnection): Promise<LayoutMetrics> {
328
329
  return conn.send<LayoutMetrics>("Page.getLayoutMetrics");
329
330
  }
330
331
  /**
@@ -555,7 +556,7 @@ export function planTiledCapture(
555
556
  * document-frame correction below is what buys correctness. Keeping it also means the offset this
556
557
  * scroll CREATES must be read after it settles — see capture()'s ordering.
557
558
  */
558
- async function elementBox(conn: CdpConnection, loc: ElementLocator): Promise<{ x: number; y: number; width: number; height: number }> {
559
+ async function elementBox(conn: PageConnection, loc: ElementLocator): Promise<{ x: number; y: number; width: number; height: number }> {
559
560
  const backendNodeId = await backendNodeIdOf(conn, loc);
560
561
  await conn.send("DOM.scrollIntoViewIfNeeded", { backendNodeId }).catch(() => undefined);
561
562
  const box = await conn.send<{ model: { content: number[] } }>("DOM.getBoxModel", { backendNodeId });
@@ -652,7 +653,7 @@ const CDP_CAPABILITIES: ReadonlySet<Capability> = new Set<Capability>([
652
653
  "emulate.mediaFeatures", "emulate.deviceMetrics", "emulate.networkConditions",
653
654
  "screenshot.fullPage", "screenshot.element", "screenshot.scale", "screenshot.renderSize", "screenshot.tile", "network.intercept",
654
655
  "snapshot.accessibilityTree", "input.insertTextAtomic", "locate.text", "locate.xpath",
655
- "capture.screencast", "input.raw", "input.html5Drag", "emulate.focus",
656
+ "capture.screencast", "input.raw", "input.modifierClick", "input.html5Drag", "emulate.focus",
656
657
  "browser.downloads", "browser.permissions", "worker.targets", "frame.targets",
657
658
  ]);
658
659
  /* ---------------------------------- PageDriver ---------------------------------- */
@@ -664,7 +665,7 @@ class CdpPageDriver implements PageDriver {
664
665
  // side effect) it did not have before this migration. See the per-method comments below.
665
666
  private readonly enabledDomains = new Set<string>();
666
667
  private released = false;
667
- constructor(private readonly conn: CdpConnection, target: Target, readonly browser: BrowserDriver) {
668
+ constructor(private readonly conn: PageConnection, target: Target, readonly browser: BrowserDriver) {
668
669
  this.info = { id: target.id, url: target.url, title: target.title, type: target.type };
669
670
  }
670
671
  private async ensureDomain(name: string): Promise<void> {
@@ -1596,7 +1597,7 @@ class CdpPageDriver implements PageDriver {
1596
1597
  * process, which degrades the beacon to current-document-only — correct, since
1597
1598
  * a CLI process cannot hold anything across calls by construction.
1598
1599
  */
1599
- const beaconSessions = new BeaconSessions<CdpConnection>((conn) => conn.close());
1600
+ const beaconSessions = new BeaconSessions<PageConnection>((conn) => conn.close());
1600
1601
 
1601
1602
  /** Beacon sessions are keyed by endpoint plus target id: a target id only means
1602
1603
  * something inside one browser, and named endpoints are separate browsers. The
@@ -1606,10 +1607,22 @@ function beaconKey(targetId: string): string {
1606
1607
  return backend === "chrome" ? targetId : `${backend}\u0000${targetId}`;
1607
1608
  }
1608
1609
 
1609
- /** The page endpoint for a target id, or undefined if the browser no longer has it. */
1610
- async function targetWsUrl(targetId: string): Promise<string | undefined> {
1610
+ /**
1611
+ * A connection to one target by id, or undefined if the browser no longer has
1612
+ * it. The beacon paths' counterpart of client.ts's `openPage`, and deliberately
1613
+ * NOT that function: these three callers are gate-free by contract (see
1614
+ * ../driver.ts) and must not go through the lease gate `resolveTarget` applies.
1615
+ *
1616
+ * Transport-routed like `openPage`, for the same reason: on a browser-ws
1617
+ * endpoint the listing carries no per-target URL to dial.
1618
+ */
1619
+ async function openTargetConn(targetId: string, opts: { timeoutMs?: number } = {}): Promise<PageConnection | undefined> {
1611
1620
  const hit = (await listTargets()).find((t) => t.id === targetId);
1612
- return hit?.webSocketDebuggerUrl;
1621
+ if (!hit) return undefined;
1622
+ // Same marker openPage reads: no per-target URL means this endpoint serves
1623
+ // none, so the target is reached by session instead.
1624
+ if (!hit.webSocketDebuggerUrl) return openSession(targetId, opts).catch(() => undefined);
1625
+ return new CdpConnection(hit.webSocketDebuggerUrl, opts).connect().catch(() => undefined);
1613
1626
  }
1614
1627
 
1615
1628
  /**
@@ -1621,7 +1634,7 @@ async function targetWsUrl(targetId: string): Promise<string | undefined> {
1621
1634
  * its tab look exactly like a live tab nobody has touched, and the held session
1622
1635
  * would never be dropped or retried.
1623
1636
  */
1624
- async function readBeaconOver(conn: CdpConnection): Promise<number | null | undefined> {
1637
+ async function readBeaconOver(conn: PageConnection): Promise<number | null | undefined> {
1625
1638
  try {
1626
1639
  const res = await conn.send<{ result: { value?: unknown } }>("Runtime.evaluate", {
1627
1640
  expression: BEACON_READ_EXPRESSION,
@@ -1643,7 +1656,7 @@ async function readBeaconOver(conn: CdpConnection): Promise<number | null | unde
1643
1656
  * the same {responsive:false} — that IS the correct answer for both, since the
1644
1657
  * caller cannot drive either tab any faster than this already told it.
1645
1658
  */
1646
- async function probeOver(conn: CdpConnection, timeoutMs: number): Promise<{ responsive: boolean; beaconTs: number | null }> {
1659
+ async function probeOver(conn: PageConnection, timeoutMs: number): Promise<{ responsive: boolean; beaconTs: number | null }> {
1647
1660
  try {
1648
1661
  const res = await conn.send<{ result: { value?: unknown } }>(
1649
1662
  "Runtime.evaluate",
@@ -1842,9 +1855,7 @@ class CdpBrowserDriver implements BrowserDriver {
1842
1855
  // build a fresh one rather than reporting a beacon that is not there.
1843
1856
  beaconSessions.drop(key);
1844
1857
  }
1845
- const wsUrl = await targetWsUrl(targetId).catch(() => undefined);
1846
- if (!wsUrl) return false;
1847
- const conn = await new CdpConnection(wsUrl).connect().catch(() => undefined);
1858
+ const conn = await openTargetConn(targetId).catch(() => undefined);
1848
1859
  if (!conn) return false;
1849
1860
  try {
1850
1861
  await conn.send("Page.enable");
@@ -1876,9 +1887,7 @@ class CdpBrowserDriver implements BrowserDriver {
1876
1887
  if (value !== undefined) return value;
1877
1888
  beaconSessions.drop(key);
1878
1889
  }
1879
- const wsUrl = await targetWsUrl(targetId).catch(() => undefined);
1880
- if (!wsUrl) return null;
1881
- const conn = await new CdpConnection(wsUrl).connect().catch(() => undefined);
1890
+ const conn = await openTargetConn(targetId).catch(() => undefined);
1882
1891
  if (!conn) return null;
1883
1892
  try {
1884
1893
  return (await readBeaconOver(conn)) ?? null;
@@ -1904,14 +1913,8 @@ class CdpBrowserDriver implements BrowserDriver {
1904
1913
  async probeRenderer(targetId: string, timeoutMs: number = RENDERER_PROBE_TIMEOUT_MS): Promise<{ responsive: boolean; beaconTs: number | null }> {
1905
1914
  const held = beaconSessions.get(beaconKey(targetId));
1906
1915
  if (held) return probeOver(held, timeoutMs);
1907
- const wsUrl = await targetWsUrl(targetId).catch(() => undefined);
1908
- if (!wsUrl) return { responsive: false, beaconTs: null };
1909
- const conn = new CdpConnection(wsUrl, { timeoutMs });
1910
- try {
1911
- await conn.connect();
1912
- } catch {
1913
- return { responsive: false, beaconTs: null };
1914
- }
1916
+ const conn = await openTargetConn(targetId, { timeoutMs }).catch(() => undefined);
1917
+ if (!conn) return { responsive: false, beaconTs: null };
1915
1918
  try {
1916
1919
  return await probeOver(conn, timeoutMs);
1917
1920
  } finally {