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.
@@ -2003,119 +2003,7 @@ function buildSnapshotFunctionSource() {
2003
2003
  return true;
2004
2004
  }
2005
2005
 
2006
- function truncate(s) {
2007
- s = s.trim().replace(/\\s+/g, " ");
2008
- if (s.length > MAX_NAME_LENGTH) return s.slice(0, MAX_NAME_LENGTH - 1) + "\\u2026";
2009
- return s;
2010
- }
2011
-
2012
- function textOf(el) {
2013
- return el.textContent || "";
2014
- }
2015
-
2016
- function idRefsText(doc, ids) {
2017
- var parts = [];
2018
- var list = ids.trim().split(/\\s+/);
2019
- for (var i = 0; i < list.length; i++) {
2020
- var ref = doc.getElementById(list[i]);
2021
- if (ref) parts.push(textOf(ref));
2022
- }
2023
- return parts.join(" ").trim();
2024
- }
2025
-
2026
- // Text of a <label>, minus any nested form control's own content: a
2027
- // label that WRAPS its control ("<label>Color <select>...</select></label>")
2028
- // would otherwise include every option's text in the control's own name.
2029
- function labelOwnText(label) {
2030
- var clone = label.cloneNode(true);
2031
- var controls = clone.querySelectorAll("input, select, textarea, button");
2032
- for (var i = 0; i < controls.length; i++) {
2033
- controls[i].parentNode.removeChild(controls[i]);
2034
- }
2035
- return textOf(clone);
2036
- }
2037
-
2038
- // Guard: without this, an <option> inside a labelled <select> would
2039
- // inherit the select's own label via closest("label"), not its text.
2040
- var LABELABLE_TAGS = { INPUT: 1, TEXTAREA: 1, SELECT: 1, BUTTON: 1, METER: 1, OUTPUT: 1, PROGRESS: 1 };
2041
-
2042
- function nativeLabelText(el) {
2043
- if (!LABELABLE_TAGS[el.tagName]) return "";
2044
- var doc = el.ownerDocument;
2045
- if (el.id) {
2046
- var forLabel = doc.querySelector('label[for="' + el.id + '"]');
2047
- if (forLabel) return labelOwnText(forLabel);
2048
- }
2049
- var ancestor = el.closest ? el.closest("label") : null;
2050
- if (ancestor) return labelOwnText(ancestor);
2051
- return "";
2052
- }
2053
-
2054
- // Reduced accname: aria-labelledby, then aria-label, then native label,
2055
- // then alt/title/placeholder, then trimmed own text for content-named
2056
- // elements. Not the full W3C accname algorithm (no recursive traversal
2057
- // rules for nested presentational content) but covers the common cases.
2058
- function accessibleName(el, contentNamed) {
2059
- var doc = el.ownerDocument;
2060
- var labelledby = el.getAttribute("aria-labelledby");
2061
- if (labelledby) {
2062
- var viaIds = idRefsText(doc, labelledby);
2063
- if (viaIds) return truncate(viaIds);
2064
- }
2065
- var ariaLabel = el.getAttribute("aria-label");
2066
- if (ariaLabel && ariaLabel.trim()) return truncate(ariaLabel);
2067
- var native = nativeLabelText(el);
2068
- if (native && native.trim()) return truncate(native);
2069
- var alt = el.getAttribute("alt");
2070
- if (alt && alt.trim()) return truncate(alt);
2071
- var title = el.getAttribute("title");
2072
- if (title && title.trim()) return truncate(title);
2073
- var placeholder = el.getAttribute("placeholder");
2074
- if (placeholder && placeholder.trim()) return truncate(placeholder);
2075
- if (contentNamed) {
2076
- var text = textOf(el);
2077
- if (text && text.trim()) return truncate(text);
2078
- }
2079
- return "";
2080
- }
2081
-
2082
- var IMPLICIT_ROLE_BY_TAG = {
2083
- A: "link", BUTTON: "button", NAV: "navigation", MAIN: "main", FORM: "form", DIALOG: "dialog",
2084
- UL: "list", OL: "list", LI: "listitem", TABLE: "table", TR: "row", TD: "cell", TH: "columnheader",
2085
- SELECT: "combobox", OPTION: "option", TEXTAREA: "textbox", IMG: "img",
2086
- H1: "heading", H2: "heading", H3: "heading", H4: "heading", H5: "heading", H6: "heading",
2087
- PROGRESS: "progressbar", METER: "meter"
2088
- };
2089
-
2090
- var INPUT_TYPE_ROLE = {
2091
- button: "button", submit: "button", reset: "button", checkbox: "checkbox", radio: "radio",
2092
- range: "slider", number: "spinbutton", search: "searchbox", email: "textbox", tel: "textbox",
2093
- url: "textbox", password: "textbox", text: "textbox", image: "button"
2094
- };
2095
-
2096
- var CONTENT_NAMED_ROLES = {
2097
- button: true, link: true, heading: true, option: true, cell: true,
2098
- columnheader: true, listitem: true, menuitem: true, tab: true
2099
- };
2100
-
2101
- function implicitRole(el) {
2102
- var explicit = el.getAttribute("role");
2103
- if (explicit) return explicit;
2104
- var tag = el.tagName;
2105
- if (tag === "INPUT") {
2106
- var type = (el.getAttribute("type") || "text").toLowerCase();
2107
- return INPUT_TYPE_ROLE[type] || "textbox";
2108
- }
2109
- if (tag === "A" && !el.getAttribute("href")) return "";
2110
- if (Object.prototype.hasOwnProperty.call(IMPLICIT_ROLE_BY_TAG, tag)) {
2111
- return IMPLICIT_ROLE_BY_TAG[tag];
2112
- }
2113
- // Deliberate divergence: Chrome's real AX tree says "generic" here,
2114
- // but "textbox" is the useful signal an agent needs. Chrome is out of
2115
- // step, do not "fix" this toward parity.
2116
- if (el.isContentEditable) return "textbox";
2117
- return "";
2118
- }
2006
+ ${ACCNAME_HELPERS_SOURCE}
2119
2007
 
2120
2008
  function headingLevel(el) {
2121
2009
  var m = /^H([1-6])$/.exec(el.tagName);
@@ -2257,7 +2145,319 @@ function buildSnapshotFunctionSource() {
2257
2145
  return { snapshot: lines.join("\\n"), nodeCount: nodeCount };
2258
2146
  }`;
2259
2147
  }
2260
- var STAMP_ATTR = "data-cdp-uid", MAX_NAME_LENGTH = 120;
2148
+ var STAMP_ATTR = "data-cdp-uid", ACCNAME_HELPERS_SOURCE = `
2149
+ function truncate(s) {
2150
+ s = s.trim().replace(/\\s+/g, " ");
2151
+ if (s.length > MAX_NAME_LENGTH) return s.slice(0, MAX_NAME_LENGTH - 1) + "\\u2026";
2152
+ return s;
2153
+ }
2154
+
2155
+ function textOf(el) {
2156
+ return el.textContent || "";
2157
+ }
2158
+
2159
+ function idRefsText(doc, ids) {
2160
+ var parts = [];
2161
+ var list = ids.trim().split(/\\s+/);
2162
+ for (var i = 0; i < list.length; i++) {
2163
+ var ref = doc.getElementById(list[i]);
2164
+ if (ref) parts.push(textOf(ref));
2165
+ }
2166
+ return parts.join(" ").trim();
2167
+ }
2168
+
2169
+ // Text of a <label>, minus any nested form control's own content: a
2170
+ // label that WRAPS its control ("<label>Color <select>...</select></label>")
2171
+ // would otherwise include every option's text in the control's own name.
2172
+ function labelOwnText(label) {
2173
+ var clone = label.cloneNode(true);
2174
+ var controls = clone.querySelectorAll("input, select, textarea, button");
2175
+ for (var i = 0; i < controls.length; i++) {
2176
+ controls[i].parentNode.removeChild(controls[i]);
2177
+ }
2178
+ return textOf(clone);
2179
+ }
2180
+
2181
+ // Guard: without this, an <option> inside a labelled <select> would
2182
+ // inherit the select's own label via closest("label"), not its text.
2183
+ var LABELABLE_TAGS = { INPUT: 1, TEXTAREA: 1, SELECT: 1, BUTTON: 1, METER: 1, OUTPUT: 1, PROGRESS: 1 };
2184
+
2185
+ function nativeLabelText(el) {
2186
+ if (!LABELABLE_TAGS[el.tagName]) return "";
2187
+ var doc = el.ownerDocument;
2188
+ if (el.id) {
2189
+ var forLabel = doc.querySelector('label[for="' + el.id + '"]');
2190
+ if (forLabel) return labelOwnText(forLabel);
2191
+ }
2192
+ var ancestor = el.closest ? el.closest("label") : null;
2193
+ if (ancestor) return labelOwnText(ancestor);
2194
+ return "";
2195
+ }
2196
+
2197
+ // Reduced accname: aria-labelledby, then aria-label, then native label,
2198
+ // then alt/title/placeholder, then trimmed own text for content-named
2199
+ // elements. Not the full W3C accname algorithm (no recursive traversal
2200
+ // rules for nested presentational content) but covers the common cases.
2201
+ function accessibleName(el, contentNamed) {
2202
+ var doc = el.ownerDocument;
2203
+ var labelledby = el.getAttribute("aria-labelledby");
2204
+ if (labelledby) {
2205
+ var viaIds = idRefsText(doc, labelledby);
2206
+ if (viaIds) return truncate(viaIds);
2207
+ }
2208
+ var ariaLabel = el.getAttribute("aria-label");
2209
+ if (ariaLabel && ariaLabel.trim()) return truncate(ariaLabel);
2210
+ var native = nativeLabelText(el);
2211
+ if (native && native.trim()) return truncate(native);
2212
+ var alt = el.getAttribute("alt");
2213
+ if (alt && alt.trim()) return truncate(alt);
2214
+ var title = el.getAttribute("title");
2215
+ if (title && title.trim()) return truncate(title);
2216
+ var placeholder = el.getAttribute("placeholder");
2217
+ if (placeholder && placeholder.trim()) return truncate(placeholder);
2218
+ if (contentNamed) {
2219
+ var text = textOf(el);
2220
+ if (text && text.trim()) return truncate(text);
2221
+ }
2222
+ return "";
2223
+ }
2224
+
2225
+ var IMPLICIT_ROLE_BY_TAG = {
2226
+ A: "link", BUTTON: "button", NAV: "navigation", MAIN: "main", FORM: "form", DIALOG: "dialog",
2227
+ UL: "list", OL: "list", LI: "listitem", TABLE: "table", TR: "row", TD: "cell", TH: "columnheader",
2228
+ SELECT: "combobox", OPTION: "option", TEXTAREA: "textbox", IMG: "img",
2229
+ H1: "heading", H2: "heading", H3: "heading", H4: "heading", H5: "heading", H6: "heading",
2230
+ PROGRESS: "progressbar", METER: "meter"
2231
+ };
2232
+
2233
+ var INPUT_TYPE_ROLE = {
2234
+ button: "button", submit: "button", reset: "button", checkbox: "checkbox", radio: "radio",
2235
+ range: "slider", number: "spinbutton", search: "searchbox", email: "textbox", tel: "textbox",
2236
+ url: "textbox", password: "textbox", text: "textbox", image: "button"
2237
+ };
2238
+
2239
+ var CONTENT_NAMED_ROLES = {
2240
+ button: true, link: true, heading: true, option: true, cell: true,
2241
+ columnheader: true, listitem: true, menuitem: true, tab: true
2242
+ };
2243
+
2244
+ function implicitRole(el) {
2245
+ var explicit = el.getAttribute("role");
2246
+ if (explicit) return explicit;
2247
+ var tag = el.tagName;
2248
+ if (tag === "INPUT") {
2249
+ var type = (el.getAttribute("type") || "text").toLowerCase();
2250
+ return INPUT_TYPE_ROLE[type] || "textbox";
2251
+ }
2252
+ if (tag === "A" && !el.getAttribute("href")) return "";
2253
+ if (Object.prototype.hasOwnProperty.call(IMPLICIT_ROLE_BY_TAG, tag)) {
2254
+ return IMPLICIT_ROLE_BY_TAG[tag];
2255
+ }
2256
+ // Deliberate divergence: Chrome's real AX tree says "generic" here,
2257
+ // but "textbox" is the useful signal an agent needs. Chrome is out of
2258
+ // step, do not "fix" this toward parity.
2259
+ if (el.isContentEditable) return "textbox";
2260
+ return "";
2261
+ }
2262
+ `, MAX_NAME_LENGTH = 120;
2263
+
2264
+ // src/cdp/endpoint.ts
2265
+ import { readFile as readFile5 } from "node:fs/promises";
2266
+ import { join as join5 } from "node:path";
2267
+ async function browserWsFromPortFile(dir, base) {
2268
+ const raw = await readFile5(join5(dir, "DevToolsActivePort"), "utf8").catch(() => {
2269
+ return;
2270
+ });
2271
+ if (!raw)
2272
+ return;
2273
+ const [port, path] = raw.split(`
2274
+ `);
2275
+ if (!port?.trim() || !path?.trim())
2276
+ return;
2277
+ const host = new URL(base).hostname;
2278
+ return `ws://${host}:${port.trim()}${path.trim()}`;
2279
+ }
2280
+ async function discoverBrowserWs(base) {
2281
+ const dir = process.env.CDP_USER_DATA_DIR;
2282
+ return dir ? browserWsFromPortFile(dir, base) : undefined;
2283
+ }
2284
+ async function handshake(url, timeoutMs) {
2285
+ const conn = new CdpConnection(url, { timeoutMs });
2286
+ try {
2287
+ await conn.connect();
2288
+ return true;
2289
+ } catch {
2290
+ return false;
2291
+ } finally {
2292
+ conn.close();
2293
+ }
2294
+ }
2295
+ function detectEndpoint() {
2296
+ const endpoint = currentEndpoint();
2297
+ const base = endpoint.base;
2298
+ const isDefault = isDefaultEndpoint(endpoint);
2299
+ const hit = cached.get(base);
2300
+ if (hit)
2301
+ return hit;
2302
+ const detection = (async () => {
2303
+ const forced = isDefault ? process.env.CDP_BROWSER_WS : undefined;
2304
+ if (forced)
2305
+ return { transport: "browser-ws", browserWsUrl: forced };
2306
+ const discovered = isDefault ? await discoverBrowserWs(base) : undefined;
2307
+ if (discovered && await handshake(discovered, 5000)) {
2308
+ return { transport: "browser-ws", browserWsUrl: discovered };
2309
+ }
2310
+ const version = await fetch(`${base}/json/version`, { signal: AbortSignal.timeout(5000) }).then((r) => r.ok ? r.json() : undefined).catch(() => {
2311
+ return;
2312
+ });
2313
+ if (version?.webSocketDebuggerUrl) {
2314
+ return { transport: "http", browserWsUrl: version.webSocketDebuggerUrl };
2315
+ }
2316
+ const dir = isDefault ? process.env.CDP_USER_DATA_DIR : undefined;
2317
+ throw new Error(`no DevTools endpoint at ${base}: GET /json/version did not answer and ` + (dir ? `no live browser socket was named by ${dir}/DevToolsActivePort. ` : `no profile was searched — CDP_USER_DATA_DIR is unset, and no profile is ever scanned unless you name one. `) + `Set CDP_BROWSER_WS to the ws://.../devtools/browser/<uuid> URL, or CDP_USER_DATA_DIR to the profile in use.`);
2318
+ })().then((info) => {
2319
+ if (info.transport === "http")
2320
+ cached.delete(base);
2321
+ return info;
2322
+ }, (error) => {
2323
+ cached.delete(base);
2324
+ throw error;
2325
+ });
2326
+ cached.set(base, detection);
2327
+ return detection;
2328
+ }
2329
+ function forgetEndpoint() {
2330
+ cached.delete(currentEndpoint().base);
2331
+ }
2332
+ var cached;
2333
+ var init_endpoint = __esm(() => {
2334
+ init_endpoints();
2335
+ init_client2();
2336
+ cached = new Map;
2337
+ });
2338
+
2339
+ // src/cdp/session.ts
2340
+ async function acquireBrowserConn() {
2341
+ if (shared) {
2342
+ shared.refs++;
2343
+ return shared.conn;
2344
+ }
2345
+ if (!opening) {
2346
+ opening = (async () => {
2347
+ let { browserWsUrl } = await detectEndpoint();
2348
+ let conn;
2349
+ try {
2350
+ conn = await new CdpConnection(browserWsUrl).connect();
2351
+ } catch (error) {
2352
+ forgetEndpoint();
2353
+ const fresh = (await detectEndpoint().catch(() => {
2354
+ return;
2355
+ }))?.browserWsUrl;
2356
+ if (!fresh || fresh === browserWsUrl)
2357
+ throw error;
2358
+ browserWsUrl = fresh;
2359
+ conn = await new CdpConnection(browserWsUrl).connect();
2360
+ }
2361
+ shared = { conn, refs: 0, url: browserWsUrl };
2362
+ return conn;
2363
+ })().finally(() => {
2364
+ opening = undefined;
2365
+ });
2366
+ }
2367
+ const conn = await opening;
2368
+ shared.refs++;
2369
+ return conn;
2370
+ }
2371
+ function releaseBrowserConn() {
2372
+ if (!shared)
2373
+ return;
2374
+ shared.refs--;
2375
+ if (shared.refs <= 0) {
2376
+ const { conn } = shared;
2377
+ shared = undefined;
2378
+ conn.close();
2379
+ }
2380
+ }
2381
+ async function withBrowserSocket(fn) {
2382
+ const conn = await acquireBrowserConn();
2383
+ try {
2384
+ return await fn(conn);
2385
+ } finally {
2386
+ releaseBrowserConn();
2387
+ }
2388
+ }
2389
+
2390
+ class SessionConnection {
2391
+ browser;
2392
+ sessionId;
2393
+ opts;
2394
+ detached = false;
2395
+ offs = [];
2396
+ constructor(browser, sessionId, opts = {}) {
2397
+ this.browser = browser;
2398
+ this.sessionId = sessionId;
2399
+ this.opts = opts;
2400
+ }
2401
+ send(method, params = {}, opts = {}) {
2402
+ if (this.detached)
2403
+ return Promise.reject(new CdpError("connection not open"));
2404
+ return this.browser.send(method, params, {
2405
+ timeoutMs: opts.timeoutMs ?? this.opts.timeoutMs,
2406
+ sessionId: opts.sessionId ?? this.sessionId
2407
+ });
2408
+ }
2409
+ on(method, handler) {
2410
+ const off = this.browser.on(method, (params, sessionId) => {
2411
+ if (sessionId && sessionId !== this.sessionId)
2412
+ return;
2413
+ handler(params, sessionId);
2414
+ });
2415
+ this.offs.push(off);
2416
+ return off;
2417
+ }
2418
+ waitFor(method, predicate, timeoutMs = this.opts.timeoutMs ?? DEFAULT_TIMEOUT_MS3) {
2419
+ return new Promise((resolve, reject) => {
2420
+ const timer = setTimeout(() => {
2421
+ off();
2422
+ reject(new CdpError(`waitFor('${method}') timed out after ${timeoutMs}ms`));
2423
+ }, timeoutMs);
2424
+ const off = this.on(method, (params) => {
2425
+ if (!predicate || predicate(params)) {
2426
+ clearTimeout(timer);
2427
+ off();
2428
+ resolve(params);
2429
+ }
2430
+ });
2431
+ });
2432
+ }
2433
+ close() {
2434
+ if (this.detached)
2435
+ return;
2436
+ this.detached = true;
2437
+ for (const off of this.offs)
2438
+ off();
2439
+ this.offs.length = 0;
2440
+ this.browser.send("Target.detachFromTarget", { sessionId: this.sessionId }).catch(() => {});
2441
+ releaseBrowserConn();
2442
+ }
2443
+ }
2444
+ async function openSession(targetId, opts = {}) {
2445
+ const browser = await acquireBrowserConn();
2446
+ try {
2447
+ const { sessionId } = await browser.send("Target.attachToTarget", { targetId, flatten: true }, { timeoutMs: opts.timeoutMs });
2448
+ if (!sessionId)
2449
+ throw new CdpError(`Target.attachToTarget returned no sessionId for ${targetId}`);
2450
+ return new SessionConnection(browser, sessionId, opts);
2451
+ } catch (e) {
2452
+ releaseBrowserConn();
2453
+ throw e;
2454
+ }
2455
+ }
2456
+ var shared, opening;
2457
+ var init_session = __esm(() => {
2458
+ init_client2();
2459
+ init_endpoint();
2460
+ });
2261
2461
 
2262
2462
  // src/client.ts
2263
2463
  class CdpConnection {
@@ -2391,12 +2591,47 @@ async function httpJson(path) {
2391
2591
  throw new CdpError(`${path} -> HTTP ${res.status}`);
2392
2592
  return await res.json();
2393
2593
  }
2394
- function listTargets() {
2395
- return httpJson("/json/list");
2594
+ async function getTargetsOverBrowserWs() {
2595
+ const { targetInfos } = await withBrowserSocket((conn) => conn.send("Target.getTargets", { filter: [{}] }));
2596
+ return targetInfos.map((t) => ({
2597
+ id: t.targetId,
2598
+ type: t.type,
2599
+ title: t.title,
2600
+ url: t.url,
2601
+ webSocketDebuggerUrl: "",
2602
+ ...t.openerId ? { parentId: t.openerId } : {}
2603
+ }));
2604
+ }
2605
+ async function listTargets() {
2606
+ const base = currentEndpoint().base;
2607
+ if (knownTransports.get(base) === "browser-ws")
2608
+ return getTargetsOverBrowserWs();
2609
+ try {
2610
+ const listing = await httpJson("/json/list");
2611
+ knownTransports.set(base, "http");
2612
+ return listing;
2613
+ } catch (httpError) {
2614
+ const detected = await detectEndpoint().catch(() => {
2615
+ return;
2616
+ });
2617
+ if (detected?.transport !== "browser-ws")
2618
+ throw httpError;
2619
+ const targets = await getTargetsOverBrowserWs().catch(() => {
2620
+ throw httpError;
2621
+ });
2622
+ knownTransports.set(base, "browser-ws");
2623
+ return targets;
2624
+ }
2396
2625
  }
2397
2626
  async function browserWsUrl() {
2398
- const v = await httpJson("/json/version");
2399
- return v.webSocketDebuggerUrl;
2627
+ if (knownTransports.get(currentEndpoint().base) !== "browser-ws") {
2628
+ const version = await httpJson("/json/version").catch(() => {
2629
+ return;
2630
+ });
2631
+ if (version?.webSocketDebuggerUrl)
2632
+ return version.webSocketDebuggerUrl;
2633
+ }
2634
+ return (await detectEndpoint()).browserWsUrl;
2400
2635
  }
2401
2636
  async function resolveTarget(selector, opts = {}) {
2402
2637
  const targets = await listTargets();
@@ -2478,7 +2713,7 @@ async function openBrowser(opts = {}) {
2478
2713
  }
2479
2714
  async function openPage(selector, opts = {}) {
2480
2715
  const target = await resolveTarget(selector, { lease: opts.lease });
2481
- const conn = await new CdpConnection(target.webSocketDebuggerUrl, opts).connect();
2716
+ const conn = target.webSocketDebuggerUrl ? await new CdpConnection(target.webSocketDebuggerUrl, opts).connect() : await openSession(target.id, opts);
2482
2717
  return { conn, target };
2483
2718
  }
2484
2719
  async function withPage(selector, fn, opts = {}) {
@@ -2489,13 +2724,16 @@ async function withPage(selector, fn, opts = {}) {
2489
2724
  conn.close();
2490
2725
  }
2491
2726
  }
2492
- var BASE, DEFAULT_TIMEOUT_MS3, CdpError;
2727
+ var BASE, DEFAULT_TIMEOUT_MS3, CdpError, knownTransports;
2493
2728
  var init_client2 = __esm(() => {
2494
2729
  init_leases();
2495
2730
  init_origins();
2496
2731
  init_endpoints();
2497
2732
  init_workers();
2498
2733
  init_frames();
2734
+ init_endpoint();
2735
+ init_session();
2736
+ init_session();
2499
2737
  BASE = (() => {
2500
2738
  try {
2501
2739
  return defaultEndpoint().base;
@@ -2514,6 +2752,7 @@ var init_client2 = __esm(() => {
2514
2752
  this.name = "CdpError";
2515
2753
  }
2516
2754
  };
2755
+ knownTransports = new Map;
2517
2756
  });
2518
2757
 
2519
2758
  // src/tools/network_mock.ts
@@ -2760,6 +2999,8 @@ function mapBidiError(e) {
2760
2999
  return driverError("disconnected", e.message);
2761
3000
  if (code === "unsupported operation")
2762
3001
  return driverError("unsupported", e.message);
3002
+ if (code === "unknown command")
3003
+ return driverError("unsupported", `${e.message} (this Firefox predates that WebDriver BiDi command; see BIDI_CAPABILITY_MIN_FIREFOX for the version each capability needs)`);
2763
3004
  if (!code && /timed out/i.test(e.message))
2764
3005
  return driverError("timeout", e.message);
2765
3006
  if (!code && /(disposed|not open|connection closed)/i.test(e.message))
@@ -2913,6 +3154,69 @@ async function resolveElementLocator(conn, contextId, loc) {
2913
3154
  throw driverError("no-such-element", `text '${loc.text}' matched no element`);
2914
3155
  return sharedRefOf(nodes[0], `text '${loc.text}'`);
2915
3156
  }
3157
+ function modifierKeyValues(mods) {
3158
+ const out = [];
3159
+ for (const m of mods ?? []) {
3160
+ const v = MODIFIER_VALUES[m.toLowerCase()];
3161
+ if (v === undefined)
3162
+ throw driverError("page-error", `unknown modifier '${m}' (use Alt, Control, Meta, or Shift)`);
3163
+ if (!out.includes(v))
3164
+ out.push(v);
3165
+ }
3166
+ return out;
3167
+ }
3168
+ function modifierChord(pointerId, actions, keys) {
3169
+ const pointer = actions;
3170
+ if (keys.length === 0)
3171
+ return [{ type: "pointer", id: pointerId, actions: pointer }];
3172
+ const k = keys.length;
3173
+ const pause = () => ({ type: "pause" });
3174
+ const keyActions = [
3175
+ ...keys.map((v) => ({ type: "keyDown", value: v })),
3176
+ ...pointer.map(pause),
3177
+ ...[...keys].reverse().map((v) => ({ type: "keyUp", value: v }))
3178
+ ];
3179
+ const pointerActions = [
3180
+ ...Array.from({ length: k }, pause),
3181
+ ...pointer,
3182
+ ...Array.from({ length: k }, pause)
3183
+ ];
3184
+ return [
3185
+ { type: "key", id: "cdp-keyboard", actions: keyActions },
3186
+ { type: "pointer", id: pointerId, actions: pointerActions }
3187
+ ];
3188
+ }
3189
+ function firefoxMajor(conn) {
3190
+ const v = conn.capabilities?.browserVersion;
3191
+ if (typeof v !== "string")
3192
+ return;
3193
+ const major = Number.parseInt(v, 10);
3194
+ return Number.isFinite(major) ? major : undefined;
3195
+ }
3196
+ function requireFirefox(conn, token) {
3197
+ const min = BIDI_CAPABILITY_MIN_FIREFOX[token];
3198
+ if (min === undefined)
3199
+ return;
3200
+ const major = firefoxMajor(conn);
3201
+ if (major !== undefined && major < min) {
3202
+ const v = conn.capabilities.browserVersion;
3203
+ throw driverError("unsupported", `${token} needs Firefox ${min} or newer; this Firefox is ${v}.`);
3204
+ }
3205
+ }
3206
+ async function armPostHocBodies(conn) {
3207
+ if (process.env.CDP_FIREFOX_BODY_COLLECTOR === "off")
3208
+ return;
3209
+ try {
3210
+ requireFirefox(conn, "network.responseBodyPostHoc");
3211
+ } catch {
3212
+ return;
3213
+ }
3214
+ try {
3215
+ await conn.send("network.addDataCollector", { dataTypes: ["response"], maxEncodedDataSize: POST_HOC_BODY_MAX_BYTES });
3216
+ } catch (e) {
3217
+ console.error(`[cdp-toolkit] firefox response-body collector not armed: ${e instanceof Error ? e.message : String(e)}`);
3218
+ }
3219
+ }
2916
3220
  function bumpEpoch(endpoint, conn) {
2917
3221
  sessionEpochs.set(endpoint, (sessionEpochs.get(endpoint) ?? 0) + 1);
2918
3222
  connEndpoints.set(conn, endpoint);
@@ -3110,6 +3414,7 @@ async function getConnection(endpoint, timeoutMs, attached = false) {
3110
3414
  }
3111
3415
  connections.set(endpoint, conn);
3112
3416
  bumpEpoch(endpoint, conn);
3417
+ await armPostHocBodies(conn);
3113
3418
  if (muxMode(attached) !== "off") {
3114
3419
  try {
3115
3420
  const mux = await startBidiMux(conn);
@@ -3325,7 +3630,35 @@ class BidiBrowserDriver {
3325
3630
  conn.release();
3326
3631
  }
3327
3632
  }
3633
+ async withBrowserConnection(fn) {
3634
+ const conn = await getConnection(this.endpoint, this.timeoutMs, this.attached);
3635
+ try {
3636
+ return await fn(conn);
3637
+ } finally {
3638
+ conn.release();
3639
+ }
3640
+ }
3641
+ setDisposeHook(key, hook) {
3642
+ let hooks = disposeHooks.get(this.endpoint);
3643
+ if (!hooks) {
3644
+ hooks = new Map;
3645
+ disposeHooks.set(this.endpoint, hooks);
3646
+ }
3647
+ if (hook)
3648
+ hooks.set(key, hook);
3649
+ else
3650
+ hooks.delete(key);
3651
+ }
3328
3652
  async dispose() {
3653
+ const hooks = disposeHooks.get(this.endpoint);
3654
+ disposeHooks.delete(this.endpoint);
3655
+ const live = connections.get(this.endpoint);
3656
+ if (hooks && live) {
3657
+ for (const hook of hooks.values())
3658
+ await hook(live).catch(() => {
3659
+ return;
3660
+ });
3661
+ }
3329
3662
  for (const key of [...bidiBeaconScripts.keys()]) {
3330
3663
  if (key.startsWith(`${this.endpoint}:`))
3331
3664
  bidiBeaconScripts.delete(key);
@@ -3400,7 +3733,7 @@ async function hostFirefoxMux(endpoint, opts = {}) {
3400
3733
  function createFirefoxDriverForEndpoint(wsUrl, opts) {
3401
3734
  return new BidiBrowserDriver(wsUrl, opts?.timeoutMs, true);
3402
3735
  }
3403
- var LINE_RE, INTERACTIVE_ROLES, STAMP_ONE_SOURCE, KEY_VALUES, MODIFIER_VALUES, BUTTON_CODES, ARM_SCROLL_SETTLE_WATCH_SOURCE, AWAIT_SCROLL_SETTLE_SOURCE = "function(){return window.__cdpScrollSettle;}", BIDI_CAPABILITIES, connections, slotHandles, muxes, joined, connecting, sessionEpochs, connEndpoints, STALE_ID_HINT, sleep2 = (ms) => new Promise((r) => setTimeout(r, ms)), slotLabelOverride, bidiBeaconScripts, BidiPageDriver;
3736
+ var LINE_RE, INTERACTIVE_ROLES, STAMP_ONE_SOURCE, KEY_VALUES, MODIFIER_VALUES, BUTTON_CODES, RAW_MOUSE_SOURCE_ID = "cdp-raw-mouse", ARM_SCROLL_SETTLE_WATCH_SOURCE, AWAIT_SCROLL_SETTLE_SOURCE = "function(){return window.__cdpScrollSettle;}", BIDI_CAPABILITY_MIN_FIREFOX, POST_HOC_BODY_MAX_BYTES, BIDI_CAPABILITIES, connections, slotHandles, muxes, joined, connecting, sessionEpochs, connEndpoints, disposeHooks, STALE_ID_HINT, sleep2 = (ms) => new Promise((r) => setTimeout(r, ms)), slotLabelOverride, bidiBeaconScripts, BidiPageDriver;
3404
3737
  var init_driver2 = __esm(() => {
3405
3738
  init_driver();
3406
3739
  init_leases();
@@ -3455,13 +3788,25 @@ var init_driver2 = __esm(() => {
3455
3788
  MODIFIER_VALUES = { shift: "", control: "", ctrl: "", alt: "", meta: "", cmd: "", command: "" };
3456
3789
  BUTTON_CODES = { left: 0, middle: 1, right: 2 };
3457
3790
  ARM_SCROLL_SETTLE_WATCH_SOURCE = "function(){window.__cdpScrollSettle=new Promise((resolve)=>{let t;const done=()=>{window.removeEventListener('scroll',on,true);resolve(true);};" + "const on=()=>{clearTimeout(t);t=setTimeout(done,60);};window.addEventListener('scroll',on,true);t=setTimeout(done,60);setTimeout(done,500);});}";
3791
+ BIDI_CAPABILITY_MIN_FIREFOX = {
3792
+ "browser.downloads": 160,
3793
+ "browser.permissions": 160,
3794
+ "emulate.mediaFeatures": 160,
3795
+ "emulate.networkConditions": 160,
3796
+ "input.raw": 160,
3797
+ "input.modifierClick": 160,
3798
+ "network.responseBodyPostHoc": 160,
3799
+ "screenshot.scale": 160
3800
+ };
3801
+ POST_HOC_BODY_MAX_BYTES = 2 * 1024 * 1024;
3458
3802
  BIDI_CAPABILITIES = new Set([
3459
3803
  "emulate.deviceMetrics",
3460
3804
  "screenshot.fullPage",
3461
3805
  "screenshot.element",
3462
3806
  "screenshot.renderSize",
3463
3807
  "network.intercept",
3464
- "locate.xpath"
3808
+ "locate.xpath",
3809
+ ...Object.keys(BIDI_CAPABILITY_MIN_FIREFOX)
3465
3810
  ]);
3466
3811
  connections = new Map;
3467
3812
  slotHandles = new Map;
@@ -3470,6 +3815,7 @@ var init_driver2 = __esm(() => {
3470
3815
  connecting = new Map;
3471
3816
  sessionEpochs = new Map;
3472
3817
  connEndpoints = new WeakMap;
3818
+ disposeHooks = new Map;
3473
3819
  STALE_ID_HINT = " — the Firefox BiDi session was re-established after its previous holder went away, and Firefox " + "assigns new context ids per session — re-resolve the tab with list_pages (url:/title: selectors) " + "and claim it again";
3474
3820
  bidiBeaconScripts = new Map;
3475
3821
  BidiPageDriver = class BidiPageDriver {
@@ -3636,18 +3982,30 @@ var init_driver2 = __esm(() => {
3636
3982
  return { x, y };
3637
3983
  }
3638
3984
  async click(loc, opts) {
3639
- if (opts?.modifiers && opts.modifiers.length > 0) {
3640
- throw driverError("unsupported", "click: 'modifiers' is not supported by the Firefox/BiDi driver; omit 'modifiers' or use --browser chrome for a modifier click.");
3641
- }
3985
+ const hasModifiers = !!opts?.modifiers && opts.modifiers.length > 0;
3986
+ if (hasModifiers)
3987
+ requireFirefox(this.conn, "input.modifierClick");
3988
+ const keys = modifierKeyValues(opts?.modifiers);
3642
3989
  const ref = await resolveElementLocator(this.conn, this.contextId, loc);
3643
3990
  const { x, y } = await this.centerOf(ref);
3644
3991
  const button = BUTTON_CODES[opts?.button ?? "left"];
3645
3992
  const actions = [{ type: "pointerMove", x, y, duration: 0 }];
3646
3993
  for (let i = 0;i < (opts?.clickCount ?? 1); i++)
3647
3994
  actions.push({ type: "pointerDown", button }, { type: "pointerUp", button });
3648
- await this.performActions([{ type: "pointer", id: "cdp-mouse", actions }]);
3995
+ await this.performActions(modifierChord("cdp-mouse", actions, keys));
3649
3996
  return { x, y };
3650
3997
  }
3998
+ async dispatchMouse(event) {
3999
+ requireFirefox(this.conn, "input.raw");
4000
+ const keys = modifierKeyValues(event.modifiers);
4001
+ const button = BUTTON_CODES[event.button ?? "left"];
4002
+ const actions = [{ type: "pointerMove", x: event.x, y: event.y, duration: 0 }];
4003
+ if (event.action === "down")
4004
+ actions.push({ type: "pointerDown", button });
4005
+ else if (event.action === "up")
4006
+ actions.push({ type: "pointerUp", button });
4007
+ await this.performActions(modifierChord(RAW_MOUSE_SOURCE_ID, actions, keys));
4008
+ }
3651
4009
  async scroll(anchor, opts) {
3652
4010
  const { x, y } = await this.resolveScrollPoint(anchor);
3653
4011
  const deltaX = Math.round(opts.deltaX ?? 0);
@@ -3756,11 +4114,23 @@ var init_driver2 = __esm(() => {
3756
4114
  }
3757
4115
  async screenshot(opts, _consumeBands) {
3758
4116
  const renderSize = opts?.renderWidth !== undefined && opts?.renderHeight !== undefined ? { width: opts.renderWidth, height: opts.renderHeight } : undefined;
3759
- if (!renderSize)
4117
+ const scale = opts?.scale !== undefined && opts.scale !== 1 ? opts.scale : undefined;
4118
+ if (!renderSize && scale === undefined)
3760
4119
  return this.capture(opts);
4120
+ if (scale !== undefined)
4121
+ requireFirefox(this.conn, "screenshot.scale");
3761
4122
  const previous = await readViewportRecord(this.browser.scheme, this.contextId);
4123
+ let dprOverride;
4124
+ if (scale !== undefined) {
4125
+ const base = previous?.deviceScaleFactor ?? Number(await this.evaluate("window.devicePixelRatio").catch(() => 1));
4126
+ dprOverride = (Number.isFinite(base) && base > 0 ? base : 1) * scale;
4127
+ }
3762
4128
  try {
3763
- await this.conn.send("browsingContext.setViewport", { context: this.contextId, viewport: { width: renderSize.width, height: renderSize.height } });
4129
+ await this.conn.send("browsingContext.setViewport", {
4130
+ context: this.contextId,
4131
+ ...renderSize ? { viewport: { width: renderSize.width, height: renderSize.height } } : {},
4132
+ ...dprOverride !== undefined ? { devicePixelRatio: dprOverride } : {}
4133
+ });
3764
4134
  } catch (e) {
3765
4135
  throw mapBidiError(e);
3766
4136
  }
@@ -3777,29 +4147,35 @@ var init_driver2 = __esm(() => {
3777
4147
  await this.conn.send("browsingContext.setViewport", {
3778
4148
  context: this.contextId,
3779
4149
  viewport: { width: previous.width, height: previous.height },
3780
- ...previous.deviceScaleFactor != null ? { devicePixelRatio: previous.deviceScaleFactor } : {}
4150
+ ...previous.deviceScaleFactor != null ? { devicePixelRatio: previous.deviceScaleFactor } : scale !== undefined ? { devicePixelRatio: null } : {}
3781
4151
  });
3782
4152
  } else {
3783
- await this.conn.send("browsingContext.setViewport", { context: this.contextId, viewport: null });
4153
+ await this.conn.send("browsingContext.setViewport", {
4154
+ context: this.contextId,
4155
+ ...renderSize ? { viewport: null } : {},
4156
+ ...scale !== undefined ? { devicePixelRatio: null } : {}
4157
+ });
3784
4158
  }
3785
4159
  } catch (e) {
3786
4160
  restoreError = e instanceof Error ? e.message : String(e);
3787
4161
  }
3788
4162
  if (!shot) {
3789
4163
  if (restoreError !== undefined && captureError instanceof Error) {
3790
- captureError.message = `${captureError.message} ${renderRestoreFailureNote(renderSize, restoreError)}`;
4164
+ captureError.message = renderSize ? `${captureError.message} ${renderRestoreFailureNote(renderSize, restoreError)}` : `${captureError.message} (and restoring the device pixel ratio failed too, the tab may still be emulated at ratio ${dprOverride}: ${restoreError})`;
3791
4165
  }
3792
4166
  throw captureError;
3793
4167
  }
4168
+ if (!renderSize) {
4169
+ if (restoreError !== undefined)
4170
+ throw driverError("page-error", `screenshot captured, but restoring the device pixel ratio failed (the tab may still be emulated at ratio ${dprOverride}): ${restoreError}`);
4171
+ return shot;
4172
+ }
3794
4173
  const result = { ...shot, renderSize, renderRestored: restoreError === undefined };
3795
4174
  if (restoreError !== undefined)
3796
4175
  result.renderRestoreError = restoreError;
3797
4176
  return result;
3798
4177
  }
3799
4178
  async capture(opts) {
3800
- if (opts?.scale !== undefined && opts.scale !== 1) {
3801
- throw driverError("unsupported", `screenshot scale ${opts.scale} is not supported by this backend (WebDriver BiDi's ` + "browsingContext.captureScreenshot has no scale parameter). Call emulate with " + `deviceScaleFactor:${opts.scale} first and capture at scale 1, or use --browser chrome.`);
3802
- }
3803
4179
  if (opts?.tile === true) {
3804
4180
  throw driverError("unsupported", "screenshot tile:true is not supported by this backend: band tiling is declared only where the band " + "arithmetic has been measured against a real browser, and Firefox was not driven for it " + `(browsingContext.captureScreenshot's clip:{type:"box"} is the primitive it would ride, untested). ` + "Capture a smaller region or a single element, or use --browser chrome for a tiled capture.");
3805
4181
  }
@@ -3827,10 +4203,29 @@ var init_driver2 = __esm(() => {
3827
4203
  await this.conn.send("browsingContext.setViewport", { context: this.contextId, viewport: null, devicePixelRatio: null }).catch(() => {
3828
4204
  return;
3829
4205
  });
4206
+ await this.conn.send("emulation.setMediaFeaturesOverride", { features: null, contexts: [this.contextId] }).catch(() => {
4207
+ return;
4208
+ });
4209
+ await this.conn.send("emulation.setNetworkConditions", { networkConditions: null, contexts: [this.contextId] }).catch(() => {
4210
+ return;
4211
+ });
3830
4212
  await clearViewportRecord(this.browser.scheme, this.contextId);
3831
4213
  return { applied: [] };
3832
4214
  }
3833
4215
  const applied = [];
4216
+ if (opts.media != null && opts.media !== "") {
4217
+ throw driverError("unsupported", `emulate media "${opts.media}": WebDriver BiDi's emulation.setMediaFeaturesOverride takes media features (prefers-color-scheme, ...) but has no print/screen media-type override. Use mediaFeatures, or --browser chrome for media type emulation.`);
4218
+ }
4219
+ const net = opts.networkConditions;
4220
+ if (net != null) {
4221
+ const throttled = (net.latency ?? 0) > 0 || (net.downloadThroughput ?? -1) >= 0 || (net.uploadThroughput ?? -1) >= 0;
4222
+ if (throttled) {
4223
+ throw driverError("unsupported", 'emulate networkConditions: Firefox only emulates offline (emulation.setNetworkConditions has the single type "offline"); latency and download/upload throughput throttling are not available. Pass only {offline:true|false}, or use --browser chrome.');
4224
+ }
4225
+ requireFirefox(this.conn, "emulate.networkConditions");
4226
+ }
4227
+ if (opts.mediaFeatures != null)
4228
+ requireFirefox(this.conn, "emulate.mediaFeatures");
3834
4229
  try {
3835
4230
  if (opts.width != null && opts.height != null) {
3836
4231
  await this.conn.send("browsingContext.setViewport", { context: this.contextId, viewport: { width: opts.width, height: opts.height }, ...opts.deviceScaleFactor != null ? { devicePixelRatio: opts.deviceScaleFactor } : {} });
@@ -3845,6 +4240,21 @@ var init_driver2 = __esm(() => {
3845
4240
  await this.conn.send("emulation.setUserAgentOverride", { userAgent: opts.userAgent, contexts: [this.contextId] });
3846
4241
  applied.push("userAgent");
3847
4242
  }
4243
+ if (opts.mediaFeatures != null) {
4244
+ const features = Object.fromEntries(opts.mediaFeatures.map((f) => [f.name, f.value]));
4245
+ await this.conn.send("emulation.setMediaFeaturesOverride", {
4246
+ features: opts.mediaFeatures.length > 0 ? features : null,
4247
+ contexts: [this.contextId]
4248
+ });
4249
+ applied.push("mediaFeatures");
4250
+ }
4251
+ if (net != null) {
4252
+ await this.conn.send("emulation.setNetworkConditions", {
4253
+ networkConditions: net.offline ? { type: "offline" } : null,
4254
+ contexts: [this.contextId]
4255
+ });
4256
+ applied.push("networkConditions");
4257
+ }
3848
4258
  } catch (e) {
3849
4259
  throw mapBidiError(e);
3850
4260
  }
@@ -3979,12 +4389,25 @@ var init_driver2 = __esm(() => {
3979
4389
  };
3980
4390
  }
3981
4391
  async getResponseBody(requestId) {
3982
- if (!this.bodyCollector)
3983
- throw driverError("unsupported", "getResponseBody: call startBodyCapture() first (network.responseBodyPostHoc is not supported)");
4392
+ let collector;
3984
4393
  try {
3985
- const { bytes } = await this.conn.send("network.getData", { dataType: "response", collector: this.bodyCollector, request: requestId });
4394
+ requireFirefox(this.conn, "network.responseBodyPostHoc");
4395
+ } catch (e) {
4396
+ if (!this.bodyCollector) {
4397
+ throw driverError("unsupported", `${e.message} Call startBodyCapture() before the request to read its body on this Firefox.`);
4398
+ }
4399
+ collector = this.bodyCollector;
4400
+ }
4401
+ try {
4402
+ const { bytes } = await this.conn.send("network.getData", { dataType: "response", request: requestId, ...collector ? { collector } : {} });
3986
4403
  return bytes.type === "base64" ? { body: bytes.value, base64Encoded: true } : { body: bytes.value, base64Encoded: false };
3987
4404
  } catch (e) {
4405
+ if (e instanceof BidiError && e.code === "unavailable network data") {
4406
+ throw driverError("page-error", `getResponseBody: the body of request ${requestId} was collected but has been evicted (Firefox keeps only a bounded recent window of response bodies, on the order of 100-200 MB). Re-issue the request, then read it sooner.`);
4407
+ }
4408
+ if (e instanceof BidiError && e.code === "no such network data") {
4409
+ throw driverError("page-error", `getResponseBody: no body is held for request ${requestId}. Firefox cannot say which of these applies: the id is wrong, the request started before this Firefox session did, the response was larger than ${POST_HOC_BODY_MAX_BYTES} bytes (not retained), or it has no body.`);
4410
+ }
3988
4411
  throw mapBidiError(e);
3989
4412
  }
3990
4413
  }