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.
package/dist/mcp.js CHANGED
@@ -803,6 +803,204 @@ var init_frames = __esm(() => {
803
803
  FRAME_SELECTOR_PAGE_ONLY_MESSAGE = "target 'frame:<substring>' selects an out-of-process iframe, and this tool is page-only " + "(closing, selecting, releasing or claiming an iframe is meaningless; these act on the embedder tab). " + `The page-only tools are ${FRAME_PAGE_ONLY_TOOLS.join(", ")}; every other tool that takes a 'target' ` + "accepts a frame: selector.";
804
804
  });
805
805
 
806
+ // src/cdp/endpoint.ts
807
+ import { readFile as readFile3 } from "node:fs/promises";
808
+ import { join as join3 } from "node:path";
809
+ async function browserWsFromPortFile(dir, base) {
810
+ const raw = await readFile3(join3(dir, "DevToolsActivePort"), "utf8").catch(() => {
811
+ return;
812
+ });
813
+ if (!raw)
814
+ return;
815
+ const [port, path] = raw.split(`
816
+ `);
817
+ if (!port?.trim() || !path?.trim())
818
+ return;
819
+ const host = new URL(base).hostname;
820
+ return `ws://${host}:${port.trim()}${path.trim()}`;
821
+ }
822
+ async function discoverBrowserWs(base) {
823
+ const dir = process.env.CDP_USER_DATA_DIR;
824
+ return dir ? browserWsFromPortFile(dir, base) : undefined;
825
+ }
826
+ async function handshake(url, timeoutMs) {
827
+ const conn = new CdpConnection(url, { timeoutMs });
828
+ try {
829
+ await conn.connect();
830
+ return true;
831
+ } catch {
832
+ return false;
833
+ } finally {
834
+ conn.close();
835
+ }
836
+ }
837
+ function detectEndpoint() {
838
+ const endpoint = currentEndpoint();
839
+ const base = endpoint.base;
840
+ const isDefault = isDefaultEndpoint(endpoint);
841
+ const hit = cached.get(base);
842
+ if (hit)
843
+ return hit;
844
+ const detection = (async () => {
845
+ const forced = isDefault ? process.env.CDP_BROWSER_WS : undefined;
846
+ if (forced)
847
+ return { transport: "browser-ws", browserWsUrl: forced };
848
+ const discovered = isDefault ? await discoverBrowserWs(base) : undefined;
849
+ if (discovered && await handshake(discovered, 5000)) {
850
+ return { transport: "browser-ws", browserWsUrl: discovered };
851
+ }
852
+ const version = await fetch(`${base}/json/version`, { signal: AbortSignal.timeout(5000) }).then((r) => r.ok ? r.json() : undefined).catch(() => {
853
+ return;
854
+ });
855
+ if (version?.webSocketDebuggerUrl) {
856
+ return { transport: "http", browserWsUrl: version.webSocketDebuggerUrl };
857
+ }
858
+ const dir = isDefault ? process.env.CDP_USER_DATA_DIR : undefined;
859
+ 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.`);
860
+ })().then((info) => {
861
+ if (info.transport === "http")
862
+ cached.delete(base);
863
+ return info;
864
+ }, (error) => {
865
+ cached.delete(base);
866
+ throw error;
867
+ });
868
+ cached.set(base, detection);
869
+ return detection;
870
+ }
871
+ function forgetEndpoint() {
872
+ cached.delete(currentEndpoint().base);
873
+ }
874
+ var cached;
875
+ var init_endpoint = __esm(() => {
876
+ init_endpoints();
877
+ init_client();
878
+ cached = new Map;
879
+ });
880
+
881
+ // src/cdp/session.ts
882
+ async function acquireBrowserConn() {
883
+ if (shared) {
884
+ shared.refs++;
885
+ return shared.conn;
886
+ }
887
+ if (!opening) {
888
+ opening = (async () => {
889
+ let { browserWsUrl } = await detectEndpoint();
890
+ let conn;
891
+ try {
892
+ conn = await new CdpConnection(browserWsUrl).connect();
893
+ } catch (error) {
894
+ forgetEndpoint();
895
+ const fresh = (await detectEndpoint().catch(() => {
896
+ return;
897
+ }))?.browserWsUrl;
898
+ if (!fresh || fresh === browserWsUrl)
899
+ throw error;
900
+ browserWsUrl = fresh;
901
+ conn = await new CdpConnection(browserWsUrl).connect();
902
+ }
903
+ shared = { conn, refs: 0, url: browserWsUrl };
904
+ return conn;
905
+ })().finally(() => {
906
+ opening = undefined;
907
+ });
908
+ }
909
+ const conn = await opening;
910
+ shared.refs++;
911
+ return conn;
912
+ }
913
+ function releaseBrowserConn() {
914
+ if (!shared)
915
+ return;
916
+ shared.refs--;
917
+ if (shared.refs <= 0) {
918
+ const { conn } = shared;
919
+ shared = undefined;
920
+ conn.close();
921
+ }
922
+ }
923
+ async function withBrowserSocket(fn) {
924
+ const conn = await acquireBrowserConn();
925
+ try {
926
+ return await fn(conn);
927
+ } finally {
928
+ releaseBrowserConn();
929
+ }
930
+ }
931
+
932
+ class SessionConnection {
933
+ browser;
934
+ sessionId;
935
+ opts;
936
+ detached = false;
937
+ offs = [];
938
+ constructor(browser, sessionId, opts = {}) {
939
+ this.browser = browser;
940
+ this.sessionId = sessionId;
941
+ this.opts = opts;
942
+ }
943
+ send(method, params = {}, opts = {}) {
944
+ if (this.detached)
945
+ return Promise.reject(new CdpError("connection not open"));
946
+ return this.browser.send(method, params, {
947
+ timeoutMs: opts.timeoutMs ?? this.opts.timeoutMs,
948
+ sessionId: opts.sessionId ?? this.sessionId
949
+ });
950
+ }
951
+ on(method, handler) {
952
+ const off = this.browser.on(method, (params, sessionId) => {
953
+ if (sessionId && sessionId !== this.sessionId)
954
+ return;
955
+ handler(params, sessionId);
956
+ });
957
+ this.offs.push(off);
958
+ return off;
959
+ }
960
+ waitFor(method, predicate, timeoutMs = this.opts.timeoutMs ?? DEFAULT_TIMEOUT_MS) {
961
+ return new Promise((resolve, reject) => {
962
+ const timer = setTimeout(() => {
963
+ off();
964
+ reject(new CdpError(`waitFor('${method}') timed out after ${timeoutMs}ms`));
965
+ }, timeoutMs);
966
+ const off = this.on(method, (params) => {
967
+ if (!predicate || predicate(params)) {
968
+ clearTimeout(timer);
969
+ off();
970
+ resolve(params);
971
+ }
972
+ });
973
+ });
974
+ }
975
+ close() {
976
+ if (this.detached)
977
+ return;
978
+ this.detached = true;
979
+ for (const off of this.offs)
980
+ off();
981
+ this.offs.length = 0;
982
+ this.browser.send("Target.detachFromTarget", { sessionId: this.sessionId }).catch(() => {});
983
+ releaseBrowserConn();
984
+ }
985
+ }
986
+ async function openSession(targetId, opts = {}) {
987
+ const browser = await acquireBrowserConn();
988
+ try {
989
+ const { sessionId } = await browser.send("Target.attachToTarget", { targetId, flatten: true }, { timeoutMs: opts.timeoutMs });
990
+ if (!sessionId)
991
+ throw new CdpError(`Target.attachToTarget returned no sessionId for ${targetId}`);
992
+ return new SessionConnection(browser, sessionId, opts);
993
+ } catch (e) {
994
+ releaseBrowserConn();
995
+ throw e;
996
+ }
997
+ }
998
+ var shared, opening;
999
+ var init_session = __esm(() => {
1000
+ init_client();
1001
+ init_endpoint();
1002
+ });
1003
+
806
1004
  // src/client.ts
807
1005
  class CdpConnection {
808
1006
  wsUrl;
@@ -935,12 +1133,47 @@ async function httpJson(path) {
935
1133
  throw new CdpError(`${path} -> HTTP ${res.status}`);
936
1134
  return await res.json();
937
1135
  }
938
- function listTargets() {
939
- return httpJson("/json/list");
1136
+ async function getTargetsOverBrowserWs() {
1137
+ const { targetInfos } = await withBrowserSocket((conn) => conn.send("Target.getTargets", { filter: [{}] }));
1138
+ return targetInfos.map((t) => ({
1139
+ id: t.targetId,
1140
+ type: t.type,
1141
+ title: t.title,
1142
+ url: t.url,
1143
+ webSocketDebuggerUrl: "",
1144
+ ...t.openerId ? { parentId: t.openerId } : {}
1145
+ }));
1146
+ }
1147
+ async function listTargets() {
1148
+ const base = currentEndpoint().base;
1149
+ if (knownTransports.get(base) === "browser-ws")
1150
+ return getTargetsOverBrowserWs();
1151
+ try {
1152
+ const listing = await httpJson("/json/list");
1153
+ knownTransports.set(base, "http");
1154
+ return listing;
1155
+ } catch (httpError) {
1156
+ const detected = await detectEndpoint().catch(() => {
1157
+ return;
1158
+ });
1159
+ if (detected?.transport !== "browser-ws")
1160
+ throw httpError;
1161
+ const targets = await getTargetsOverBrowserWs().catch(() => {
1162
+ throw httpError;
1163
+ });
1164
+ knownTransports.set(base, "browser-ws");
1165
+ return targets;
1166
+ }
940
1167
  }
941
1168
  async function browserWsUrl() {
942
- const v = await httpJson("/json/version");
943
- return v.webSocketDebuggerUrl;
1169
+ if (knownTransports.get(currentEndpoint().base) !== "browser-ws") {
1170
+ const version = await httpJson("/json/version").catch(() => {
1171
+ return;
1172
+ });
1173
+ if (version?.webSocketDebuggerUrl)
1174
+ return version.webSocketDebuggerUrl;
1175
+ }
1176
+ return (await detectEndpoint()).browserWsUrl;
944
1177
  }
945
1178
  async function resolveTarget(selector, opts = {}) {
946
1179
  const targets = await listTargets();
@@ -1022,7 +1255,7 @@ async function openBrowser(opts = {}) {
1022
1255
  }
1023
1256
  async function openPage(selector, opts = {}) {
1024
1257
  const target = await resolveTarget(selector, { lease: opts.lease });
1025
- const conn = await new CdpConnection(target.webSocketDebuggerUrl, opts).connect();
1258
+ const conn = target.webSocketDebuggerUrl ? await new CdpConnection(target.webSocketDebuggerUrl, opts).connect() : await openSession(target.id, opts);
1026
1259
  return { conn, target };
1027
1260
  }
1028
1261
  async function withPage(selector, fn, opts = {}) {
@@ -1033,13 +1266,16 @@ async function withPage(selector, fn, opts = {}) {
1033
1266
  conn.close();
1034
1267
  }
1035
1268
  }
1036
- var BASE, DEFAULT_TIMEOUT_MS, CdpError;
1269
+ var BASE, DEFAULT_TIMEOUT_MS, CdpError, knownTransports;
1037
1270
  var init_client = __esm(() => {
1038
1271
  init_leases();
1039
1272
  init_origins();
1040
1273
  init_endpoints();
1041
1274
  init_workers();
1042
1275
  init_frames();
1276
+ init_endpoint();
1277
+ init_session();
1278
+ init_session();
1043
1279
  BASE = (() => {
1044
1280
  try {
1045
1281
  return defaultEndpoint().base;
@@ -1058,6 +1294,7 @@ var init_client = __esm(() => {
1058
1294
  this.name = "CdpError";
1059
1295
  }
1060
1296
  };
1297
+ knownTransports = new Map;
1061
1298
  });
1062
1299
 
1063
1300
  // src/activity.ts
@@ -1374,8 +1611,8 @@ var init_network_mock = __esm(() => {
1374
1611
  });
1375
1612
 
1376
1613
  // src/driver.ts
1377
- import { mkdir as mkdir3, readFile as readFile3, unlink as unlink3, writeFile as writeFile3 } from "node:fs/promises";
1378
- import { join as join3 } from "node:path";
1614
+ import { mkdir as mkdir3, readFile as readFile4, unlink as unlink3, writeFile as writeFile3 } from "node:fs/promises";
1615
+ import { join as join4 } from "node:path";
1379
1616
  function isDriverError(e) {
1380
1617
  return e instanceof Error && typeof e.code === "string";
1381
1618
  }
@@ -1391,11 +1628,11 @@ function isTiledCapture(delivery) {
1391
1628
  return delivery.tiled === true;
1392
1629
  }
1393
1630
  function viewportRecordFile(scheme, targetId) {
1394
- return join3(leaseDir(), `viewport-${scheme}-${targetId.replace(/[^A-Za-z0-9._-]/g, "_")}.json`);
1631
+ return join4(leaseDir(), `viewport-${scheme}-${targetId.replace(/[^A-Za-z0-9._-]/g, "_")}.json`);
1395
1632
  }
1396
1633
  async function readViewportRecord(scheme, targetId) {
1397
1634
  try {
1398
- const raw = JSON.parse(await readFile3(viewportRecordFile(scheme, targetId), "utf8"));
1635
+ const raw = JSON.parse(await readFile4(viewportRecordFile(scheme, targetId), "utf8"));
1399
1636
  if (typeof raw?.width !== "number" || typeof raw?.height !== "number")
1400
1637
  return;
1401
1638
  return {
@@ -1414,37 +1651,352 @@ async function writeViewportRecord(scheme, targetId, rec) {
1414
1651
  await writeFile3(viewportRecordFile(scheme, targetId), JSON.stringify({ scheme, targetId, ...rec }), "utf8");
1415
1652
  } catch {}
1416
1653
  }
1417
- function renderRestoreFailureNote(size, why) {
1418
- return `— AND the ${size.width}x${size.height} render-size override could NOT be restored (${why}), so this page is STILL ` + `emulated at ${size.width}x${size.height}: put it back with emulate{width,height} or emulate{clearOverrides:true}.`;
1654
+ function renderRestoreFailureNote(size, why) {
1655
+ return `— AND the ${size.width}x${size.height} render-size override could NOT be restored (${why}), so this page is STILL ` + `emulated at ${size.width}x${size.height}: put it back with emulate{width,height} or emulate{clearOverrides:true}.`;
1656
+ }
1657
+ async function clearViewportRecord(scheme, targetId) {
1658
+ try {
1659
+ await unlink3(viewportRecordFile(scheme, targetId));
1660
+ } catch {}
1661
+ }
1662
+ var UID_STAMP_ATTR = "data-cdp-uid", LEGACY_NUMERIC_UID, REQUIRED_CAPABILITIES;
1663
+ var init_driver = __esm(() => {
1664
+ init_leases();
1665
+ LEGACY_NUMERIC_UID = /^[0-9]+$/;
1666
+ REQUIRED_CAPABILITIES = {
1667
+ performance_start_trace: ["trace.performance"],
1668
+ performance_stop_trace: ["trace.performance"],
1669
+ performance_analyze_insight: ["trace.performance"],
1670
+ performance_trace: ["trace.performance"],
1671
+ take_heapsnapshot: ["heap.snapshot"],
1672
+ lighthouse_audit: ["audit.lighthouse"],
1673
+ start_screen_recording: ["capture.screencast"],
1674
+ stop_screen_recording: ["capture.screencast"],
1675
+ mock_request: ["network.intercept"],
1676
+ list_mocks: ["network.intercept"],
1677
+ clear_mocks: ["network.intercept"],
1678
+ dispatch_mouse: ["input.raw"],
1679
+ focus_emulation: ["emulate.focus"],
1680
+ click_focus_gated: ["emulate.focus"],
1681
+ wait_for_download: ["browser.downloads"],
1682
+ grant_permissions: ["browser.permissions"]
1683
+ };
1684
+ });
1685
+
1686
+ // src/bidi/snapshot.ts
1687
+ async function takeStampedSnapshot(evaluate) {
1688
+ const raw = await evaluate(buildSnapshotFunctionSource());
1689
+ return coerceSnapshotResult(raw);
1690
+ }
1691
+ function coerceSnapshotResult(raw) {
1692
+ if (typeof raw !== "object" || raw === null || typeof raw.snapshot !== "string" || typeof raw.nodeCount !== "number") {
1693
+ throw new Error("takeStampedSnapshot: evaluate() returned an unexpected shape");
1694
+ }
1695
+ return { snapshot: raw.snapshot, nodeCount: raw.nodeCount };
1696
+ }
1697
+ function buildSnapshotFunctionSource() {
1698
+ return `function() {
1699
+ var STAMP_ATTR = ${JSON.stringify(STAMP_ATTR)};
1700
+ var MAX_NAME_LENGTH = ${MAX_NAME_LENGTH};
1701
+ var lines = [];
1702
+ var nodeCount = 0;
1703
+
1704
+ // THE UID CODEC (driver.ts) documents a bidi payload as exactly 12 lowercase hex chars,
1705
+ // /^[0-9a-f]{12}$/. Build it from two padded random blocks so the length is exact regardless
1706
+ // of the random value drawn, never from string concatenation that could come up short.
1707
+ function nextStamp() {
1708
+ var hi = Math.floor(Math.random() * 0x100000000).toString(16).padStart(8, "0");
1709
+ var lo = Math.floor(Math.random() * 0x10000).toString(16).padStart(4, "0");
1710
+ return hi + lo;
1711
+ }
1712
+
1713
+ function stampOf(el) {
1714
+ var existing = el.getAttribute(STAMP_ATTR);
1715
+ if (existing) return existing;
1716
+ var stamp = nextStamp();
1717
+ el.setAttribute(STAMP_ATTR, stamp);
1718
+ return stamp;
1719
+ }
1720
+
1721
+ // skipSizeCheck exempts <option>/<optgroup> from the zero-size prune: a
1722
+ // closed select's popup is unpainted (0x0) though its options are still
1723
+ // present and pickable. Other visibility rules still apply to them.
1724
+ function isVisible(el, skipSizeCheck) {
1725
+ if (el.hidden) return false;
1726
+ if (el.getAttribute("aria-hidden") === "true") return false;
1727
+ var style;
1728
+ try {
1729
+ style = el.ownerDocument.defaultView.getComputedStyle(el);
1730
+ } catch (e) {
1731
+ style = null;
1732
+ }
1733
+ if (style) {
1734
+ if (style.display === "none" || style.visibility === "hidden") return false;
1735
+ }
1736
+ if (!skipSizeCheck) {
1737
+ var rect = el.getBoundingClientRect();
1738
+ if (rect.width === 0 && rect.height === 0) return false;
1739
+ }
1740
+ return true;
1741
+ }
1742
+
1743
+ ${ACCNAME_HELPERS_SOURCE}
1744
+
1745
+ function headingLevel(el) {
1746
+ var m = /^H([1-6])$/.exec(el.tagName);
1747
+ return m ? m[1] : null;
1748
+ }
1749
+
1750
+ function currentValue(el) {
1751
+ var tag = el.tagName;
1752
+ if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") {
1753
+ return el.value;
1754
+ }
1755
+ if (el.isContentEditable) return textOf(el);
1756
+ return undefined;
1757
+ }
1758
+
1759
+ function isChecked(el) {
1760
+ var tag = el.tagName;
1761
+ if (tag === "INPUT") {
1762
+ var type = (el.getAttribute("type") || "").toLowerCase();
1763
+ if (type === "checkbox" || type === "radio") return !!el.checked;
1764
+ }
1765
+ var aria = el.getAttribute("aria-checked");
1766
+ if (aria === "true") return true;
1767
+ return false;
1768
+ }
1769
+
1770
+ function describeNode(el, role) {
1771
+ var contentNamed = !!CONTENT_NAMED_ROLES[role];
1772
+ var name = accessibleName(el, contentNamed);
1773
+ var extras = [];
1774
+ var value = currentValue(el);
1775
+ if (value !== undefined && value !== "") extras.push("value=" + JSON.stringify(String(value)));
1776
+ if (isChecked(el)) extras.push("checked=true");
1777
+ if (el.tagName === "OPTION" && el.selected) extras.push("selected");
1778
+ var href = el.getAttribute("href");
1779
+ if (href) extras.push("url=" + href);
1780
+ if (el.disabled || el.getAttribute("aria-disabled") === "true") extras.push("disabled");
1781
+ var level = headingLevel(el);
1782
+ if (level) extras.push("level=" + level);
1783
+ var label = name ? " " + JSON.stringify(name) : "";
1784
+ var extra = extras.length ? " [" + extras.join(" ") + "]" : "";
1785
+ return { role: role, label: label, extra: extra, name: name };
1786
+ }
1787
+
1788
+ // Traverses light DOM, open shadow roots, and same-origin iframe documents.
1789
+ // A cross-origin iframe throws on contentDocument access; caught and
1790
+ // skipped rather than aborting the whole walk, and noted in a comment
1791
+ // here rather than silently vanishing from the tree without a trace.
1792
+ function walk(root, depth) {
1793
+ var children = root.children ? Array.prototype.slice.call(root.children) : [];
1794
+ for (var i = 0; i < children.length; i++) {
1795
+ var el = children[i];
1796
+ var isSelectChild = el.tagName === "OPTION" || el.tagName === "OPTGROUP";
1797
+ if (!isVisible(el, isSelectChild)) continue;
1798
+
1799
+ var role = implicitRole(el);
1800
+ var isLandmarkOrControl = !!role;
1801
+ var described = null;
1802
+ if (isLandmarkOrControl) {
1803
+ described = describeNode(el, role);
1804
+ }
1805
+
1806
+ var hasContent = described && (described.name || described.extra);
1807
+ var isStructural = isLandmarkOrControl && (hasContent || isInteractiveRole(role) || isLandmarkRole(role));
1808
+
1809
+ // Role-less visible leaf text (measured vs Chrome's take_snapshot,
1810
+ // which keeps a StaticText under a generic wrapper for this case,
1811
+ // e.g. a plain status <div>). Only a leaf (no element children, so
1812
+ // its text is not already captured by a nested control/label).
1813
+ var hasElementChildren = !!(el.children && el.children.length > 0);
1814
+ var leafName = !isStructural && !hasElementChildren ? truncate(textOf(el)) : "";
1815
+ var isLeafText = !!leafName;
1816
+
1817
+ var nextDepth = depth;
1818
+ if (isStructural || isLeafText) {
1819
+ var stamp = stampOf(el);
1820
+ var indent = new Array(depth + 1).join(" ");
1821
+ var lineTail = isStructural
1822
+ ? described.role + described.label + described.extra
1823
+ : "text " + JSON.stringify(leafName);
1824
+ lines.push(indent + "[" + stamp + "] " + lineTail);
1825
+ nodeCount += 1;
1826
+ nextDepth = depth + 1;
1827
+ }
1828
+
1829
+ if (el.shadowRoot) {
1830
+ walk(el.shadowRoot, nextDepth);
1831
+ } else if (el.tagName === "IFRAME") {
1832
+ try {
1833
+ var doc = el.contentDocument;
1834
+ if (doc && doc.body) walk(doc.body, nextDepth);
1835
+ } catch (e) {
1836
+ // cross-origin iframe: intentionally skipped, not silently merged
1837
+ // into the parent tree as though it were empty.
1838
+ }
1839
+ } else {
1840
+ walk(el, nextDepth);
1841
+ }
1842
+ }
1843
+ }
1844
+
1845
+ function isInteractiveRole(role) {
1846
+ return (
1847
+ role === "button" ||
1848
+ role === "link" ||
1849
+ role === "textbox" ||
1850
+ role === "searchbox" ||
1851
+ role === "checkbox" ||
1852
+ role === "radio" ||
1853
+ role === "combobox" ||
1854
+ role === "listbox" ||
1855
+ role === "option" ||
1856
+ role === "slider" ||
1857
+ role === "spinbutton" ||
1858
+ role === "progressbar" ||
1859
+ role === "meter"
1860
+ );
1861
+ }
1862
+
1863
+ function isLandmarkRole(role) {
1864
+ return (
1865
+ role === "navigation" ||
1866
+ role === "main" ||
1867
+ role === "form" ||
1868
+ role === "dialog" ||
1869
+ role === "region" ||
1870
+ role === "heading" ||
1871
+ role === "list" ||
1872
+ role === "listitem" ||
1873
+ role === "table" ||
1874
+ role === "row" ||
1875
+ role === "cell" ||
1876
+ role === "columnheader" ||
1877
+ role === "img"
1878
+ );
1879
+ }
1880
+
1881
+ walk(document.body, 0);
1882
+ return { snapshot: lines.join("\\n"), nodeCount: nodeCount };
1883
+ }`;
1884
+ }
1885
+ var STAMP_ATTR = "data-cdp-uid", ACCNAME_HELPERS_SOURCE = `
1886
+ function truncate(s) {
1887
+ s = s.trim().replace(/\\s+/g, " ");
1888
+ if (s.length > MAX_NAME_LENGTH) return s.slice(0, MAX_NAME_LENGTH - 1) + "\\u2026";
1889
+ return s;
1890
+ }
1891
+
1892
+ function textOf(el) {
1893
+ return el.textContent || "";
1894
+ }
1895
+
1896
+ function idRefsText(doc, ids) {
1897
+ var parts = [];
1898
+ var list = ids.trim().split(/\\s+/);
1899
+ for (var i = 0; i < list.length; i++) {
1900
+ var ref = doc.getElementById(list[i]);
1901
+ if (ref) parts.push(textOf(ref));
1902
+ }
1903
+ return parts.join(" ").trim();
1904
+ }
1905
+
1906
+ // Text of a <label>, minus any nested form control's own content: a
1907
+ // label that WRAPS its control ("<label>Color <select>...</select></label>")
1908
+ // would otherwise include every option's text in the control's own name.
1909
+ function labelOwnText(label) {
1910
+ var clone = label.cloneNode(true);
1911
+ var controls = clone.querySelectorAll("input, select, textarea, button");
1912
+ for (var i = 0; i < controls.length; i++) {
1913
+ controls[i].parentNode.removeChild(controls[i]);
1914
+ }
1915
+ return textOf(clone);
1916
+ }
1917
+
1918
+ // Guard: without this, an <option> inside a labelled <select> would
1919
+ // inherit the select's own label via closest("label"), not its text.
1920
+ var LABELABLE_TAGS = { INPUT: 1, TEXTAREA: 1, SELECT: 1, BUTTON: 1, METER: 1, OUTPUT: 1, PROGRESS: 1 };
1921
+
1922
+ function nativeLabelText(el) {
1923
+ if (!LABELABLE_TAGS[el.tagName]) return "";
1924
+ var doc = el.ownerDocument;
1925
+ if (el.id) {
1926
+ var forLabel = doc.querySelector('label[for="' + el.id + '"]');
1927
+ if (forLabel) return labelOwnText(forLabel);
1928
+ }
1929
+ var ancestor = el.closest ? el.closest("label") : null;
1930
+ if (ancestor) return labelOwnText(ancestor);
1931
+ return "";
1932
+ }
1933
+
1934
+ // Reduced accname: aria-labelledby, then aria-label, then native label,
1935
+ // then alt/title/placeholder, then trimmed own text for content-named
1936
+ // elements. Not the full W3C accname algorithm (no recursive traversal
1937
+ // rules for nested presentational content) but covers the common cases.
1938
+ function accessibleName(el, contentNamed) {
1939
+ var doc = el.ownerDocument;
1940
+ var labelledby = el.getAttribute("aria-labelledby");
1941
+ if (labelledby) {
1942
+ var viaIds = idRefsText(doc, labelledby);
1943
+ if (viaIds) return truncate(viaIds);
1944
+ }
1945
+ var ariaLabel = el.getAttribute("aria-label");
1946
+ if (ariaLabel && ariaLabel.trim()) return truncate(ariaLabel);
1947
+ var native = nativeLabelText(el);
1948
+ if (native && native.trim()) return truncate(native);
1949
+ var alt = el.getAttribute("alt");
1950
+ if (alt && alt.trim()) return truncate(alt);
1951
+ var title = el.getAttribute("title");
1952
+ if (title && title.trim()) return truncate(title);
1953
+ var placeholder = el.getAttribute("placeholder");
1954
+ if (placeholder && placeholder.trim()) return truncate(placeholder);
1955
+ if (contentNamed) {
1956
+ var text = textOf(el);
1957
+ if (text && text.trim()) return truncate(text);
1958
+ }
1959
+ return "";
1419
1960
  }
1420
- async function clearViewportRecord(scheme, targetId) {
1421
- try {
1422
- await unlink3(viewportRecordFile(scheme, targetId));
1423
- } catch {}
1961
+
1962
+ var IMPLICIT_ROLE_BY_TAG = {
1963
+ A: "link", BUTTON: "button", NAV: "navigation", MAIN: "main", FORM: "form", DIALOG: "dialog",
1964
+ UL: "list", OL: "list", LI: "listitem", TABLE: "table", TR: "row", TD: "cell", TH: "columnheader",
1965
+ SELECT: "combobox", OPTION: "option", TEXTAREA: "textbox", IMG: "img",
1966
+ H1: "heading", H2: "heading", H3: "heading", H4: "heading", H5: "heading", H6: "heading",
1967
+ PROGRESS: "progressbar", METER: "meter"
1968
+ };
1969
+
1970
+ var INPUT_TYPE_ROLE = {
1971
+ button: "button", submit: "button", reset: "button", checkbox: "checkbox", radio: "radio",
1972
+ range: "slider", number: "spinbutton", search: "searchbox", email: "textbox", tel: "textbox",
1973
+ url: "textbox", password: "textbox", text: "textbox", image: "button"
1974
+ };
1975
+
1976
+ var CONTENT_NAMED_ROLES = {
1977
+ button: true, link: true, heading: true, option: true, cell: true,
1978
+ columnheader: true, listitem: true, menuitem: true, tab: true
1979
+ };
1980
+
1981
+ function implicitRole(el) {
1982
+ var explicit = el.getAttribute("role");
1983
+ if (explicit) return explicit;
1984
+ var tag = el.tagName;
1985
+ if (tag === "INPUT") {
1986
+ var type = (el.getAttribute("type") || "text").toLowerCase();
1987
+ return INPUT_TYPE_ROLE[type] || "textbox";
1988
+ }
1989
+ if (tag === "A" && !el.getAttribute("href")) return "";
1990
+ if (Object.prototype.hasOwnProperty.call(IMPLICIT_ROLE_BY_TAG, tag)) {
1991
+ return IMPLICIT_ROLE_BY_TAG[tag];
1992
+ }
1993
+ // Deliberate divergence: Chrome's real AX tree says "generic" here,
1994
+ // but "textbox" is the useful signal an agent needs. Chrome is out of
1995
+ // step, do not "fix" this toward parity.
1996
+ if (el.isContentEditable) return "textbox";
1997
+ return "";
1424
1998
  }
1425
- var UID_STAMP_ATTR = "data-cdp-uid", LEGACY_NUMERIC_UID, REQUIRED_CAPABILITIES;
1426
- var init_driver = __esm(() => {
1427
- init_leases();
1428
- LEGACY_NUMERIC_UID = /^[0-9]+$/;
1429
- REQUIRED_CAPABILITIES = {
1430
- performance_start_trace: ["trace.performance"],
1431
- performance_stop_trace: ["trace.performance"],
1432
- performance_analyze_insight: ["trace.performance"],
1433
- performance_trace: ["trace.performance"],
1434
- take_heapsnapshot: ["heap.snapshot"],
1435
- lighthouse_audit: ["audit.lighthouse"],
1436
- start_screen_recording: ["capture.screencast"],
1437
- stop_screen_recording: ["capture.screencast"],
1438
- mock_request: ["network.intercept"],
1439
- list_mocks: ["network.intercept"],
1440
- clear_mocks: ["network.intercept"],
1441
- dispatch_mouse: ["input.raw"],
1442
- focus_emulation: ["emulate.focus"],
1443
- click_focus_gated: ["emulate.focus"],
1444
- wait_for_download: ["browser.downloads"],
1445
- grant_permissions: ["browser.permissions"]
1446
- };
1447
- });
1999
+ `, MAX_NAME_LENGTH = 120;
1448
2000
 
1449
2001
  // src/bidi/client.ts
1450
2002
  class BidiConnection {
@@ -1645,16 +2197,16 @@ var init_client2 = __esm(() => {
1645
2197
  });
1646
2198
 
1647
2199
  // src/bidi/session-lease.ts
1648
- import { mkdir as mkdir13, readFile as readFile8, rename as rename3, unlink as unlink5, writeFile as writeFile10 } from "node:fs/promises";
1649
- import { join as join11 } from "node:path";
2200
+ import { mkdir as mkdir13, readFile as readFile9, rename as rename3, unlink as unlink5, writeFile as writeFile10 } from "node:fs/promises";
2201
+ import { join as join12 } from "node:path";
1650
2202
  function safeEndpoint(endpoint) {
1651
2203
  return endpoint.replace(/[^A-Za-z0-9._-]/g, "_");
1652
2204
  }
1653
2205
  function sessionSlotFile(endpoint) {
1654
- return join11(leaseDir(), `ff-session-${safeEndpoint(endpoint)}.json`);
2206
+ return join12(leaseDir(), `ff-session-${safeEndpoint(endpoint)}.json`);
1655
2207
  }
1656
2208
  function muxDaemonLogFile(endpoint) {
1657
- return join11(leaseDir(), `ff-mux-${safeEndpoint(endpoint)}.log`);
2209
+ return join12(leaseDir(), `ff-mux-${safeEndpoint(endpoint)}.log`);
1658
2210
  }
1659
2211
  function sessionWaitMs() {
1660
2212
  const raw = Number(process.env.CDP_FIREFOX_SESSION_WAIT_MS);
@@ -1663,7 +2215,7 @@ function sessionWaitMs() {
1663
2215
  async function readSessionSlot(endpoint) {
1664
2216
  let raw;
1665
2217
  try {
1666
- raw = await readFile8(sessionSlotFile(endpoint), "utf8");
2218
+ raw = await readFile9(sessionSlotFile(endpoint), "utf8");
1667
2219
  } catch (err) {
1668
2220
  if (err.code === "ENOENT")
1669
2221
  return;
@@ -2350,353 +2902,40 @@ function forceClearOrphanSession(marionettePort, opts = {}) {
2350
2902
  decoder.push(chunk);
2351
2903
  for (;; ) {
2352
2904
  const frame = decoder.next();
2353
- if (frame === undefined)
2354
- break;
2355
- if (!handshakeSeen) {
2356
- handshakeSeen = true;
2357
- continue;
2358
- }
2359
- settle(isSlotFreedReply(frame));
2360
- return;
2361
- }
2362
- if (handshakeSeen && !commandSent) {
2363
- commandSent = true;
2364
- sock.write(DELETE_SESSION_FRAME);
2365
- }
2366
- } catch {
2367
- settle(false);
2368
- }
2369
- });
2370
- try {
2371
- sock.connect(marionettePort, HOST);
2372
- } catch {
2373
- settle(false);
2374
- }
2375
- });
2376
- }
2377
- var DEFAULT_MARIONETTE_PORT = 2828, DEFAULT_TIMEOUT_MS4 = 4000, HOST = "127.0.0.1", COLON = 58, DELETE_SESSION_FRAME, MarionetteProtocolError;
2378
- var init_marionette = __esm(() => {
2379
- DELETE_SESSION_FRAME = encodeFrame2([0, 1, "WebDriver:DeleteSession", {}]);
2380
- MarionetteProtocolError = class MarionetteProtocolError extends Error {
2381
- constructor(message) {
2382
- super(message);
2383
- this.name = "MarionetteProtocolError";
2384
- }
2385
- };
2386
- });
2387
-
2388
- // src/bidi/snapshot.ts
2389
- async function takeStampedSnapshot(evaluate) {
2390
- const raw = await evaluate(buildSnapshotFunctionSource());
2391
- return coerceSnapshotResult(raw);
2392
- }
2393
- function coerceSnapshotResult(raw) {
2394
- if (typeof raw !== "object" || raw === null || typeof raw.snapshot !== "string" || typeof raw.nodeCount !== "number") {
2395
- throw new Error("takeStampedSnapshot: evaluate() returned an unexpected shape");
2396
- }
2397
- return { snapshot: raw.snapshot, nodeCount: raw.nodeCount };
2398
- }
2399
- function buildSnapshotFunctionSource() {
2400
- return `function() {
2401
- var STAMP_ATTR = ${JSON.stringify(STAMP_ATTR)};
2402
- var MAX_NAME_LENGTH = ${MAX_NAME_LENGTH};
2403
- var lines = [];
2404
- var nodeCount = 0;
2405
-
2406
- // THE UID CODEC (driver.ts) documents a bidi payload as exactly 12 lowercase hex chars,
2407
- // /^[0-9a-f]{12}$/. Build it from two padded random blocks so the length is exact regardless
2408
- // of the random value drawn, never from string concatenation that could come up short.
2409
- function nextStamp() {
2410
- var hi = Math.floor(Math.random() * 0x100000000).toString(16).padStart(8, "0");
2411
- var lo = Math.floor(Math.random() * 0x10000).toString(16).padStart(4, "0");
2412
- return hi + lo;
2413
- }
2414
-
2415
- function stampOf(el) {
2416
- var existing = el.getAttribute(STAMP_ATTR);
2417
- if (existing) return existing;
2418
- var stamp = nextStamp();
2419
- el.setAttribute(STAMP_ATTR, stamp);
2420
- return stamp;
2421
- }
2422
-
2423
- // skipSizeCheck exempts <option>/<optgroup> from the zero-size prune: a
2424
- // closed select's popup is unpainted (0x0) though its options are still
2425
- // present and pickable. Other visibility rules still apply to them.
2426
- function isVisible(el, skipSizeCheck) {
2427
- if (el.hidden) return false;
2428
- if (el.getAttribute("aria-hidden") === "true") return false;
2429
- var style;
2430
- try {
2431
- style = el.ownerDocument.defaultView.getComputedStyle(el);
2432
- } catch (e) {
2433
- style = null;
2434
- }
2435
- if (style) {
2436
- if (style.display === "none" || style.visibility === "hidden") return false;
2437
- }
2438
- if (!skipSizeCheck) {
2439
- var rect = el.getBoundingClientRect();
2440
- if (rect.width === 0 && rect.height === 0) return false;
2441
- }
2442
- return true;
2443
- }
2444
-
2445
- function truncate(s) {
2446
- s = s.trim().replace(/\\s+/g, " ");
2447
- if (s.length > MAX_NAME_LENGTH) return s.slice(0, MAX_NAME_LENGTH - 1) + "\\u2026";
2448
- return s;
2449
- }
2450
-
2451
- function textOf(el) {
2452
- return el.textContent || "";
2453
- }
2454
-
2455
- function idRefsText(doc, ids) {
2456
- var parts = [];
2457
- var list = ids.trim().split(/\\s+/);
2458
- for (var i = 0; i < list.length; i++) {
2459
- var ref = doc.getElementById(list[i]);
2460
- if (ref) parts.push(textOf(ref));
2461
- }
2462
- return parts.join(" ").trim();
2463
- }
2464
-
2465
- // Text of a <label>, minus any nested form control's own content: a
2466
- // label that WRAPS its control ("<label>Color <select>...</select></label>")
2467
- // would otherwise include every option's text in the control's own name.
2468
- function labelOwnText(label) {
2469
- var clone = label.cloneNode(true);
2470
- var controls = clone.querySelectorAll("input, select, textarea, button");
2471
- for (var i = 0; i < controls.length; i++) {
2472
- controls[i].parentNode.removeChild(controls[i]);
2473
- }
2474
- return textOf(clone);
2475
- }
2476
-
2477
- // Guard: without this, an <option> inside a labelled <select> would
2478
- // inherit the select's own label via closest("label"), not its text.
2479
- var LABELABLE_TAGS = { INPUT: 1, TEXTAREA: 1, SELECT: 1, BUTTON: 1, METER: 1, OUTPUT: 1, PROGRESS: 1 };
2480
-
2481
- function nativeLabelText(el) {
2482
- if (!LABELABLE_TAGS[el.tagName]) return "";
2483
- var doc = el.ownerDocument;
2484
- if (el.id) {
2485
- var forLabel = doc.querySelector('label[for="' + el.id + '"]');
2486
- if (forLabel) return labelOwnText(forLabel);
2487
- }
2488
- var ancestor = el.closest ? el.closest("label") : null;
2489
- if (ancestor) return labelOwnText(ancestor);
2490
- return "";
2491
- }
2492
-
2493
- // Reduced accname: aria-labelledby, then aria-label, then native label,
2494
- // then alt/title/placeholder, then trimmed own text for content-named
2495
- // elements. Not the full W3C accname algorithm (no recursive traversal
2496
- // rules for nested presentational content) but covers the common cases.
2497
- function accessibleName(el, contentNamed) {
2498
- var doc = el.ownerDocument;
2499
- var labelledby = el.getAttribute("aria-labelledby");
2500
- if (labelledby) {
2501
- var viaIds = idRefsText(doc, labelledby);
2502
- if (viaIds) return truncate(viaIds);
2503
- }
2504
- var ariaLabel = el.getAttribute("aria-label");
2505
- if (ariaLabel && ariaLabel.trim()) return truncate(ariaLabel);
2506
- var native = nativeLabelText(el);
2507
- if (native && native.trim()) return truncate(native);
2508
- var alt = el.getAttribute("alt");
2509
- if (alt && alt.trim()) return truncate(alt);
2510
- var title = el.getAttribute("title");
2511
- if (title && title.trim()) return truncate(title);
2512
- var placeholder = el.getAttribute("placeholder");
2513
- if (placeholder && placeholder.trim()) return truncate(placeholder);
2514
- if (contentNamed) {
2515
- var text = textOf(el);
2516
- if (text && text.trim()) return truncate(text);
2517
- }
2518
- return "";
2519
- }
2520
-
2521
- var IMPLICIT_ROLE_BY_TAG = {
2522
- A: "link", BUTTON: "button", NAV: "navigation", MAIN: "main", FORM: "form", DIALOG: "dialog",
2523
- UL: "list", OL: "list", LI: "listitem", TABLE: "table", TR: "row", TD: "cell", TH: "columnheader",
2524
- SELECT: "combobox", OPTION: "option", TEXTAREA: "textbox", IMG: "img",
2525
- H1: "heading", H2: "heading", H3: "heading", H4: "heading", H5: "heading", H6: "heading",
2526
- PROGRESS: "progressbar", METER: "meter"
2527
- };
2528
-
2529
- var INPUT_TYPE_ROLE = {
2530
- button: "button", submit: "button", reset: "button", checkbox: "checkbox", radio: "radio",
2531
- range: "slider", number: "spinbutton", search: "searchbox", email: "textbox", tel: "textbox",
2532
- url: "textbox", password: "textbox", text: "textbox", image: "button"
2533
- };
2534
-
2535
- var CONTENT_NAMED_ROLES = {
2536
- button: true, link: true, heading: true, option: true, cell: true,
2537
- columnheader: true, listitem: true, menuitem: true, tab: true
2538
- };
2539
-
2540
- function implicitRole(el) {
2541
- var explicit = el.getAttribute("role");
2542
- if (explicit) return explicit;
2543
- var tag = el.tagName;
2544
- if (tag === "INPUT") {
2545
- var type = (el.getAttribute("type") || "text").toLowerCase();
2546
- return INPUT_TYPE_ROLE[type] || "textbox";
2547
- }
2548
- if (tag === "A" && !el.getAttribute("href")) return "";
2549
- if (Object.prototype.hasOwnProperty.call(IMPLICIT_ROLE_BY_TAG, tag)) {
2550
- return IMPLICIT_ROLE_BY_TAG[tag];
2551
- }
2552
- // Deliberate divergence: Chrome's real AX tree says "generic" here,
2553
- // but "textbox" is the useful signal an agent needs. Chrome is out of
2554
- // step, do not "fix" this toward parity.
2555
- if (el.isContentEditable) return "textbox";
2556
- return "";
2557
- }
2558
-
2559
- function headingLevel(el) {
2560
- var m = /^H([1-6])$/.exec(el.tagName);
2561
- return m ? m[1] : null;
2562
- }
2563
-
2564
- function currentValue(el) {
2565
- var tag = el.tagName;
2566
- if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") {
2567
- return el.value;
2568
- }
2569
- if (el.isContentEditable) return textOf(el);
2570
- return undefined;
2571
- }
2572
-
2573
- function isChecked(el) {
2574
- var tag = el.tagName;
2575
- if (tag === "INPUT") {
2576
- var type = (el.getAttribute("type") || "").toLowerCase();
2577
- if (type === "checkbox" || type === "radio") return !!el.checked;
2578
- }
2579
- var aria = el.getAttribute("aria-checked");
2580
- if (aria === "true") return true;
2581
- return false;
2582
- }
2583
-
2584
- function describeNode(el, role) {
2585
- var contentNamed = !!CONTENT_NAMED_ROLES[role];
2586
- var name = accessibleName(el, contentNamed);
2587
- var extras = [];
2588
- var value = currentValue(el);
2589
- if (value !== undefined && value !== "") extras.push("value=" + JSON.stringify(String(value)));
2590
- if (isChecked(el)) extras.push("checked=true");
2591
- if (el.tagName === "OPTION" && el.selected) extras.push("selected");
2592
- var href = el.getAttribute("href");
2593
- if (href) extras.push("url=" + href);
2594
- if (el.disabled || el.getAttribute("aria-disabled") === "true") extras.push("disabled");
2595
- var level = headingLevel(el);
2596
- if (level) extras.push("level=" + level);
2597
- var label = name ? " " + JSON.stringify(name) : "";
2598
- var extra = extras.length ? " [" + extras.join(" ") + "]" : "";
2599
- return { role: role, label: label, extra: extra, name: name };
2600
- }
2601
-
2602
- // Traverses light DOM, open shadow roots, and same-origin iframe documents.
2603
- // A cross-origin iframe throws on contentDocument access; caught and
2604
- // skipped rather than aborting the whole walk, and noted in a comment
2605
- // here rather than silently vanishing from the tree without a trace.
2606
- function walk(root, depth) {
2607
- var children = root.children ? Array.prototype.slice.call(root.children) : [];
2608
- for (var i = 0; i < children.length; i++) {
2609
- var el = children[i];
2610
- var isSelectChild = el.tagName === "OPTION" || el.tagName === "OPTGROUP";
2611
- if (!isVisible(el, isSelectChild)) continue;
2612
-
2613
- var role = implicitRole(el);
2614
- var isLandmarkOrControl = !!role;
2615
- var described = null;
2616
- if (isLandmarkOrControl) {
2617
- described = describeNode(el, role);
2618
- }
2619
-
2620
- var hasContent = described && (described.name || described.extra);
2621
- var isStructural = isLandmarkOrControl && (hasContent || isInteractiveRole(role) || isLandmarkRole(role));
2622
-
2623
- // Role-less visible leaf text (measured vs Chrome's take_snapshot,
2624
- // which keeps a StaticText under a generic wrapper for this case,
2625
- // e.g. a plain status <div>). Only a leaf (no element children, so
2626
- // its text is not already captured by a nested control/label).
2627
- var hasElementChildren = !!(el.children && el.children.length > 0);
2628
- var leafName = !isStructural && !hasElementChildren ? truncate(textOf(el)) : "";
2629
- var isLeafText = !!leafName;
2630
-
2631
- var nextDepth = depth;
2632
- if (isStructural || isLeafText) {
2633
- var stamp = stampOf(el);
2634
- var indent = new Array(depth + 1).join(" ");
2635
- var lineTail = isStructural
2636
- ? described.role + described.label + described.extra
2637
- : "text " + JSON.stringify(leafName);
2638
- lines.push(indent + "[" + stamp + "] " + lineTail);
2639
- nodeCount += 1;
2640
- nextDepth = depth + 1;
2641
- }
2642
-
2643
- if (el.shadowRoot) {
2644
- walk(el.shadowRoot, nextDepth);
2645
- } else if (el.tagName === "IFRAME") {
2646
- try {
2647
- var doc = el.contentDocument;
2648
- if (doc && doc.body) walk(doc.body, nextDepth);
2649
- } catch (e) {
2650
- // cross-origin iframe: intentionally skipped, not silently merged
2651
- // into the parent tree as though it were empty.
2905
+ if (frame === undefined)
2906
+ break;
2907
+ if (!handshakeSeen) {
2908
+ handshakeSeen = true;
2909
+ continue;
2652
2910
  }
2653
- } else {
2654
- walk(el, nextDepth);
2911
+ settle(isSlotFreedReply(frame));
2912
+ return;
2913
+ }
2914
+ if (handshakeSeen && !commandSent) {
2915
+ commandSent = true;
2916
+ sock.write(DELETE_SESSION_FRAME);
2655
2917
  }
2918
+ } catch {
2919
+ settle(false);
2656
2920
  }
2921
+ });
2922
+ try {
2923
+ sock.connect(marionettePort, HOST);
2924
+ } catch {
2925
+ settle(false);
2657
2926
  }
2658
-
2659
- function isInteractiveRole(role) {
2660
- return (
2661
- role === "button" ||
2662
- role === "link" ||
2663
- role === "textbox" ||
2664
- role === "searchbox" ||
2665
- role === "checkbox" ||
2666
- role === "radio" ||
2667
- role === "combobox" ||
2668
- role === "listbox" ||
2669
- role === "option" ||
2670
- role === "slider" ||
2671
- role === "spinbutton" ||
2672
- role === "progressbar" ||
2673
- role === "meter"
2674
- );
2675
- }
2676
-
2677
- function isLandmarkRole(role) {
2678
- return (
2679
- role === "navigation" ||
2680
- role === "main" ||
2681
- role === "form" ||
2682
- role === "dialog" ||
2683
- role === "region" ||
2684
- role === "heading" ||
2685
- role === "list" ||
2686
- role === "listitem" ||
2687
- role === "table" ||
2688
- role === "row" ||
2689
- role === "cell" ||
2690
- role === "columnheader" ||
2691
- role === "img"
2692
- );
2693
- }
2694
-
2695
- walk(document.body, 0);
2696
- return { snapshot: lines.join("\\n"), nodeCount: nodeCount };
2697
- }`;
2927
+ });
2698
2928
  }
2699
- var STAMP_ATTR = "data-cdp-uid", MAX_NAME_LENGTH = 120;
2929
+ var DEFAULT_MARIONETTE_PORT = 2828, DEFAULT_TIMEOUT_MS4 = 4000, HOST = "127.0.0.1", COLON = 58, DELETE_SESSION_FRAME, MarionetteProtocolError;
2930
+ var init_marionette = __esm(() => {
2931
+ DELETE_SESSION_FRAME = encodeFrame2([0, 1, "WebDriver:DeleteSession", {}]);
2932
+ MarionetteProtocolError = class MarionetteProtocolError extends Error {
2933
+ constructor(message) {
2934
+ super(message);
2935
+ this.name = "MarionetteProtocolError";
2936
+ }
2937
+ };
2938
+ });
2700
2939
 
2701
2940
  // src/bidi/driver.ts
2702
2941
  import { spawn as spawn3 } from "node:child_process";
@@ -2761,6 +3000,8 @@ function mapBidiError(e) {
2761
3000
  return driverError2("disconnected", e.message);
2762
3001
  if (code === "unsupported operation")
2763
3002
  return driverError2("unsupported", e.message);
3003
+ if (code === "unknown command")
3004
+ return driverError2("unsupported", `${e.message} (this Firefox predates that WebDriver BiDi command; see BIDI_CAPABILITY_MIN_FIREFOX for the version each capability needs)`);
2764
3005
  if (!code && /timed out/i.test(e.message))
2765
3006
  return driverError2("timeout", e.message);
2766
3007
  if (!code && /(disposed|not open|connection closed)/i.test(e.message))
@@ -2914,6 +3155,69 @@ async function resolveElementLocator2(conn, contextId, loc) {
2914
3155
  throw driverError2("no-such-element", `text '${loc.text}' matched no element`);
2915
3156
  return sharedRefOf(nodes[0], `text '${loc.text}'`);
2916
3157
  }
3158
+ function modifierKeyValues(mods) {
3159
+ const out = [];
3160
+ for (const m of mods ?? []) {
3161
+ const v = MODIFIER_VALUES[m.toLowerCase()];
3162
+ if (v === undefined)
3163
+ throw driverError2("page-error", `unknown modifier '${m}' (use Alt, Control, Meta, or Shift)`);
3164
+ if (!out.includes(v))
3165
+ out.push(v);
3166
+ }
3167
+ return out;
3168
+ }
3169
+ function modifierChord(pointerId, actions, keys) {
3170
+ const pointer = actions;
3171
+ if (keys.length === 0)
3172
+ return [{ type: "pointer", id: pointerId, actions: pointer }];
3173
+ const k = keys.length;
3174
+ const pause = () => ({ type: "pause" });
3175
+ const keyActions = [
3176
+ ...keys.map((v) => ({ type: "keyDown", value: v })),
3177
+ ...pointer.map(pause),
3178
+ ...[...keys].reverse().map((v) => ({ type: "keyUp", value: v }))
3179
+ ];
3180
+ const pointerActions = [
3181
+ ...Array.from({ length: k }, pause),
3182
+ ...pointer,
3183
+ ...Array.from({ length: k }, pause)
3184
+ ];
3185
+ return [
3186
+ { type: "key", id: "cdp-keyboard", actions: keyActions },
3187
+ { type: "pointer", id: pointerId, actions: pointerActions }
3188
+ ];
3189
+ }
3190
+ function firefoxMajor(conn) {
3191
+ const v = conn.capabilities?.browserVersion;
3192
+ if (typeof v !== "string")
3193
+ return;
3194
+ const major = Number.parseInt(v, 10);
3195
+ return Number.isFinite(major) ? major : undefined;
3196
+ }
3197
+ function requireFirefox(conn, token) {
3198
+ const min = BIDI_CAPABILITY_MIN_FIREFOX[token];
3199
+ if (min === undefined)
3200
+ return;
3201
+ const major = firefoxMajor(conn);
3202
+ if (major !== undefined && major < min) {
3203
+ const v = conn.capabilities.browserVersion;
3204
+ throw driverError2("unsupported", `${token} needs Firefox ${min} or newer; this Firefox is ${v}.`);
3205
+ }
3206
+ }
3207
+ async function armPostHocBodies(conn) {
3208
+ if (process.env.CDP_FIREFOX_BODY_COLLECTOR === "off")
3209
+ return;
3210
+ try {
3211
+ requireFirefox(conn, "network.responseBodyPostHoc");
3212
+ } catch {
3213
+ return;
3214
+ }
3215
+ try {
3216
+ await conn.send("network.addDataCollector", { dataTypes: ["response"], maxEncodedDataSize: POST_HOC_BODY_MAX_BYTES });
3217
+ } catch (e) {
3218
+ console.error(`[cdp-toolkit] firefox response-body collector not armed: ${e instanceof Error ? e.message : String(e)}`);
3219
+ }
3220
+ }
2917
3221
  function bumpEpoch(endpoint, conn) {
2918
3222
  sessionEpochs.set(endpoint, (sessionEpochs.get(endpoint) ?? 0) + 1);
2919
3223
  connEndpoints.set(conn, endpoint);
@@ -3111,6 +3415,7 @@ async function getConnection(endpoint, timeoutMs, attached = false) {
3111
3415
  }
3112
3416
  connections.set(endpoint, conn);
3113
3417
  bumpEpoch(endpoint, conn);
3418
+ await armPostHocBodies(conn);
3114
3419
  if (muxMode(attached) !== "off") {
3115
3420
  try {
3116
3421
  const mux = await startBidiMux(conn);
@@ -3326,7 +3631,35 @@ class BidiBrowserDriver {
3326
3631
  conn.release();
3327
3632
  }
3328
3633
  }
3634
+ async withBrowserConnection(fn) {
3635
+ const conn = await getConnection(this.endpoint, this.timeoutMs, this.attached);
3636
+ try {
3637
+ return await fn(conn);
3638
+ } finally {
3639
+ conn.release();
3640
+ }
3641
+ }
3642
+ setDisposeHook(key, hook) {
3643
+ let hooks = disposeHooks.get(this.endpoint);
3644
+ if (!hooks) {
3645
+ hooks = new Map;
3646
+ disposeHooks.set(this.endpoint, hooks);
3647
+ }
3648
+ if (hook)
3649
+ hooks.set(key, hook);
3650
+ else
3651
+ hooks.delete(key);
3652
+ }
3329
3653
  async dispose() {
3654
+ const hooks = disposeHooks.get(this.endpoint);
3655
+ disposeHooks.delete(this.endpoint);
3656
+ const live = connections.get(this.endpoint);
3657
+ if (hooks && live) {
3658
+ for (const hook of hooks.values())
3659
+ await hook(live).catch(() => {
3660
+ return;
3661
+ });
3662
+ }
3330
3663
  for (const key of [...bidiBeaconScripts.keys()]) {
3331
3664
  if (key.startsWith(`${this.endpoint}:`))
3332
3665
  bidiBeaconScripts.delete(key);
@@ -3401,7 +3734,7 @@ async function hostFirefoxMux(endpoint, opts = {}) {
3401
3734
  function createFirefoxDriverForEndpoint(wsUrl, opts) {
3402
3735
  return new BidiBrowserDriver(wsUrl, opts?.timeoutMs, true);
3403
3736
  }
3404
- var LINE_RE, INTERACTIVE_ROLES3, 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, sleep3 = (ms) => new Promise((r) => setTimeout(r, ms)), slotLabelOverride, bidiBeaconScripts, BidiPageDriver;
3737
+ var LINE_RE, INTERACTIVE_ROLES3, 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, sleep3 = (ms) => new Promise((r) => setTimeout(r, ms)), slotLabelOverride, bidiBeaconScripts, BidiPageDriver;
3405
3738
  var init_driver2 = __esm(() => {
3406
3739
  init_driver();
3407
3740
  init_leases();
@@ -3456,13 +3789,25 @@ var init_driver2 = __esm(() => {
3456
3789
  MODIFIER_VALUES = { shift: "", control: "", ctrl: "", alt: "", meta: "", cmd: "", command: "" };
3457
3790
  BUTTON_CODES = { left: 0, middle: 1, right: 2 };
3458
3791
  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);});}";
3792
+ BIDI_CAPABILITY_MIN_FIREFOX = {
3793
+ "browser.downloads": 160,
3794
+ "browser.permissions": 160,
3795
+ "emulate.mediaFeatures": 160,
3796
+ "emulate.networkConditions": 160,
3797
+ "input.raw": 160,
3798
+ "input.modifierClick": 160,
3799
+ "network.responseBodyPostHoc": 160,
3800
+ "screenshot.scale": 160
3801
+ };
3802
+ POST_HOC_BODY_MAX_BYTES = 2 * 1024 * 1024;
3459
3803
  BIDI_CAPABILITIES = new Set([
3460
3804
  "emulate.deviceMetrics",
3461
3805
  "screenshot.fullPage",
3462
3806
  "screenshot.element",
3463
3807
  "screenshot.renderSize",
3464
3808
  "network.intercept",
3465
- "locate.xpath"
3809
+ "locate.xpath",
3810
+ ...Object.keys(BIDI_CAPABILITY_MIN_FIREFOX)
3466
3811
  ]);
3467
3812
  connections = new Map;
3468
3813
  slotHandles = new Map;
@@ -3471,6 +3816,7 @@ var init_driver2 = __esm(() => {
3471
3816
  connecting = new Map;
3472
3817
  sessionEpochs = new Map;
3473
3818
  connEndpoints = new WeakMap;
3819
+ disposeHooks = new Map;
3474
3820
  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";
3475
3821
  bidiBeaconScripts = new Map;
3476
3822
  BidiPageDriver = class BidiPageDriver {
@@ -3637,18 +3983,30 @@ var init_driver2 = __esm(() => {
3637
3983
  return { x, y };
3638
3984
  }
3639
3985
  async click(loc, opts) {
3640
- if (opts?.modifiers && opts.modifiers.length > 0) {
3641
- throw driverError2("unsupported", "click: 'modifiers' is not supported by the Firefox/BiDi driver; omit 'modifiers' or use --browser chrome for a modifier click.");
3642
- }
3986
+ const hasModifiers = !!opts?.modifiers && opts.modifiers.length > 0;
3987
+ if (hasModifiers)
3988
+ requireFirefox(this.conn, "input.modifierClick");
3989
+ const keys = modifierKeyValues(opts?.modifiers);
3643
3990
  const ref = await resolveElementLocator2(this.conn, this.contextId, loc);
3644
3991
  const { x, y } = await this.centerOf(ref);
3645
3992
  const button = BUTTON_CODES[opts?.button ?? "left"];
3646
3993
  const actions = [{ type: "pointerMove", x, y, duration: 0 }];
3647
3994
  for (let i = 0;i < (opts?.clickCount ?? 1); i++)
3648
3995
  actions.push({ type: "pointerDown", button }, { type: "pointerUp", button });
3649
- await this.performActions([{ type: "pointer", id: "cdp-mouse", actions }]);
3996
+ await this.performActions(modifierChord("cdp-mouse", actions, keys));
3650
3997
  return { x, y };
3651
3998
  }
3999
+ async dispatchMouse(event) {
4000
+ requireFirefox(this.conn, "input.raw");
4001
+ const keys = modifierKeyValues(event.modifiers);
4002
+ const button = BUTTON_CODES[event.button ?? "left"];
4003
+ const actions = [{ type: "pointerMove", x: event.x, y: event.y, duration: 0 }];
4004
+ if (event.action === "down")
4005
+ actions.push({ type: "pointerDown", button });
4006
+ else if (event.action === "up")
4007
+ actions.push({ type: "pointerUp", button });
4008
+ await this.performActions(modifierChord(RAW_MOUSE_SOURCE_ID, actions, keys));
4009
+ }
3652
4010
  async scroll(anchor, opts) {
3653
4011
  const { x, y } = await this.resolveScrollPoint(anchor);
3654
4012
  const deltaX = Math.round(opts.deltaX ?? 0);
@@ -3757,11 +4115,23 @@ var init_driver2 = __esm(() => {
3757
4115
  }
3758
4116
  async screenshot(opts, _consumeBands) {
3759
4117
  const renderSize = opts?.renderWidth !== undefined && opts?.renderHeight !== undefined ? { width: opts.renderWidth, height: opts.renderHeight } : undefined;
3760
- if (!renderSize)
4118
+ const scale = opts?.scale !== undefined && opts.scale !== 1 ? opts.scale : undefined;
4119
+ if (!renderSize && scale === undefined)
3761
4120
  return this.capture(opts);
4121
+ if (scale !== undefined)
4122
+ requireFirefox(this.conn, "screenshot.scale");
3762
4123
  const previous = await readViewportRecord(this.browser.scheme, this.contextId);
4124
+ let dprOverride;
4125
+ if (scale !== undefined) {
4126
+ const base = previous?.deviceScaleFactor ?? Number(await this.evaluate("window.devicePixelRatio").catch(() => 1));
4127
+ dprOverride = (Number.isFinite(base) && base > 0 ? base : 1) * scale;
4128
+ }
3763
4129
  try {
3764
- await this.conn.send("browsingContext.setViewport", { context: this.contextId, viewport: { width: renderSize.width, height: renderSize.height } });
4130
+ await this.conn.send("browsingContext.setViewport", {
4131
+ context: this.contextId,
4132
+ ...renderSize ? { viewport: { width: renderSize.width, height: renderSize.height } } : {},
4133
+ ...dprOverride !== undefined ? { devicePixelRatio: dprOverride } : {}
4134
+ });
3765
4135
  } catch (e) {
3766
4136
  throw mapBidiError(e);
3767
4137
  }
@@ -3778,29 +4148,35 @@ var init_driver2 = __esm(() => {
3778
4148
  await this.conn.send("browsingContext.setViewport", {
3779
4149
  context: this.contextId,
3780
4150
  viewport: { width: previous.width, height: previous.height },
3781
- ...previous.deviceScaleFactor != null ? { devicePixelRatio: previous.deviceScaleFactor } : {}
4151
+ ...previous.deviceScaleFactor != null ? { devicePixelRatio: previous.deviceScaleFactor } : scale !== undefined ? { devicePixelRatio: null } : {}
3782
4152
  });
3783
4153
  } else {
3784
- await this.conn.send("browsingContext.setViewport", { context: this.contextId, viewport: null });
4154
+ await this.conn.send("browsingContext.setViewport", {
4155
+ context: this.contextId,
4156
+ ...renderSize ? { viewport: null } : {},
4157
+ ...scale !== undefined ? { devicePixelRatio: null } : {}
4158
+ });
3785
4159
  }
3786
4160
  } catch (e) {
3787
4161
  restoreError = e instanceof Error ? e.message : String(e);
3788
4162
  }
3789
4163
  if (!shot) {
3790
4164
  if (restoreError !== undefined && captureError instanceof Error) {
3791
- captureError.message = `${captureError.message} ${renderRestoreFailureNote(renderSize, restoreError)}`;
4165
+ 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})`;
3792
4166
  }
3793
4167
  throw captureError;
3794
4168
  }
4169
+ if (!renderSize) {
4170
+ if (restoreError !== undefined)
4171
+ throw driverError2("page-error", `screenshot captured, but restoring the device pixel ratio failed (the tab may still be emulated at ratio ${dprOverride}): ${restoreError}`);
4172
+ return shot;
4173
+ }
3795
4174
  const result = { ...shot, renderSize, renderRestored: restoreError === undefined };
3796
4175
  if (restoreError !== undefined)
3797
4176
  result.renderRestoreError = restoreError;
3798
4177
  return result;
3799
4178
  }
3800
4179
  async capture(opts) {
3801
- if (opts?.scale !== undefined && opts.scale !== 1) {
3802
- throw driverError2("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.`);
3803
- }
3804
4180
  if (opts?.tile === true) {
3805
4181
  throw driverError2("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.");
3806
4182
  }
@@ -3828,10 +4204,29 @@ var init_driver2 = __esm(() => {
3828
4204
  await this.conn.send("browsingContext.setViewport", { context: this.contextId, viewport: null, devicePixelRatio: null }).catch(() => {
3829
4205
  return;
3830
4206
  });
4207
+ await this.conn.send("emulation.setMediaFeaturesOverride", { features: null, contexts: [this.contextId] }).catch(() => {
4208
+ return;
4209
+ });
4210
+ await this.conn.send("emulation.setNetworkConditions", { networkConditions: null, contexts: [this.contextId] }).catch(() => {
4211
+ return;
4212
+ });
3831
4213
  await clearViewportRecord(this.browser.scheme, this.contextId);
3832
4214
  return { applied: [] };
3833
4215
  }
3834
4216
  const applied = [];
4217
+ if (opts.media != null && opts.media !== "") {
4218
+ throw driverError2("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.`);
4219
+ }
4220
+ const net = opts.networkConditions;
4221
+ if (net != null) {
4222
+ const throttled = (net.latency ?? 0) > 0 || (net.downloadThroughput ?? -1) >= 0 || (net.uploadThroughput ?? -1) >= 0;
4223
+ if (throttled) {
4224
+ throw driverError2("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.');
4225
+ }
4226
+ requireFirefox(this.conn, "emulate.networkConditions");
4227
+ }
4228
+ if (opts.mediaFeatures != null)
4229
+ requireFirefox(this.conn, "emulate.mediaFeatures");
3835
4230
  try {
3836
4231
  if (opts.width != null && opts.height != null) {
3837
4232
  await this.conn.send("browsingContext.setViewport", { context: this.contextId, viewport: { width: opts.width, height: opts.height }, ...opts.deviceScaleFactor != null ? { devicePixelRatio: opts.deviceScaleFactor } : {} });
@@ -3846,6 +4241,21 @@ var init_driver2 = __esm(() => {
3846
4241
  await this.conn.send("emulation.setUserAgentOverride", { userAgent: opts.userAgent, contexts: [this.contextId] });
3847
4242
  applied.push("userAgent");
3848
4243
  }
4244
+ if (opts.mediaFeatures != null) {
4245
+ const features = Object.fromEntries(opts.mediaFeatures.map((f) => [f.name, f.value]));
4246
+ await this.conn.send("emulation.setMediaFeaturesOverride", {
4247
+ features: opts.mediaFeatures.length > 0 ? features : null,
4248
+ contexts: [this.contextId]
4249
+ });
4250
+ applied.push("mediaFeatures");
4251
+ }
4252
+ if (net != null) {
4253
+ await this.conn.send("emulation.setNetworkConditions", {
4254
+ networkConditions: net.offline ? { type: "offline" } : null,
4255
+ contexts: [this.contextId]
4256
+ });
4257
+ applied.push("networkConditions");
4258
+ }
3849
4259
  } catch (e) {
3850
4260
  throw mapBidiError(e);
3851
4261
  }
@@ -3980,12 +4390,25 @@ var init_driver2 = __esm(() => {
3980
4390
  };
3981
4391
  }
3982
4392
  async getResponseBody(requestId) {
3983
- if (!this.bodyCollector)
3984
- throw driverError2("unsupported", "getResponseBody: call startBodyCapture() first (network.responseBodyPostHoc is not supported)");
4393
+ let collector;
4394
+ try {
4395
+ requireFirefox(this.conn, "network.responseBodyPostHoc");
4396
+ } catch (e) {
4397
+ if (!this.bodyCollector) {
4398
+ throw driverError2("unsupported", `${e.message} Call startBodyCapture() before the request to read its body on this Firefox.`);
4399
+ }
4400
+ collector = this.bodyCollector;
4401
+ }
3985
4402
  try {
3986
- const { bytes } = await this.conn.send("network.getData", { dataType: "response", collector: this.bodyCollector, request: requestId });
4403
+ const { bytes } = await this.conn.send("network.getData", { dataType: "response", request: requestId, ...collector ? { collector } : {} });
3987
4404
  return bytes.type === "base64" ? { body: bytes.value, base64Encoded: true } : { body: bytes.value, base64Encoded: false };
3988
4405
  } catch (e) {
4406
+ if (e instanceof BidiError && e.code === "unavailable network data") {
4407
+ throw driverError2("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.`);
4408
+ }
4409
+ if (e instanceof BidiError && e.code === "no such network data") {
4410
+ throw driverError2("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.`);
4411
+ }
3989
4412
  throw mapBidiError(e);
3990
4413
  }
3991
4414
  }
@@ -4062,6 +4485,7 @@ import { fileURLToPath as fileURLToPath2 } from "node:url";
4062
4485
 
4063
4486
  // src/cdp/driver.ts
4064
4487
  init_client();
4488
+ init_session();
4065
4489
  init_leases();
4066
4490
  init_endpoints();
4067
4491
  init_activity();
@@ -4525,6 +4949,7 @@ var CDP_CAPABILITIES = new Set([
4525
4949
  "locate.xpath",
4526
4950
  "capture.screencast",
4527
4951
  "input.raw",
4952
+ "input.modifierClick",
4528
4953
  "input.html5Drag",
4529
4954
  "emulate.focus",
4530
4955
  "browser.downloads",
@@ -5149,9 +5574,17 @@ function beaconKey(targetId) {
5149
5574
  const backend = chromeLeaseBackend(currentEndpoint());
5150
5575
  return backend === "chrome" ? targetId : `${backend}\x00${targetId}`;
5151
5576
  }
5152
- async function targetWsUrl(targetId) {
5577
+ async function openTargetConn(targetId, opts = {}) {
5153
5578
  const hit = (await listTargets()).find((t) => t.id === targetId);
5154
- return hit?.webSocketDebuggerUrl;
5579
+ if (!hit)
5580
+ return;
5581
+ if (!hit.webSocketDebuggerUrl)
5582
+ return openSession(targetId, opts).catch(() => {
5583
+ return;
5584
+ });
5585
+ return new CdpConnection(hit.webSocketDebuggerUrl, opts).connect().catch(() => {
5586
+ return;
5587
+ });
5155
5588
  }
5156
5589
  async function readBeaconOver(conn) {
5157
5590
  try {
@@ -5276,12 +5709,7 @@ class CdpBrowserDriver {
5276
5709
  return true;
5277
5710
  beaconSessions.drop(key);
5278
5711
  }
5279
- const wsUrl = await targetWsUrl(targetId).catch(() => {
5280
- return;
5281
- });
5282
- if (!wsUrl)
5283
- return false;
5284
- const conn = await new CdpConnection(wsUrl).connect().catch(() => {
5712
+ const conn = await openTargetConn(targetId).catch(() => {
5285
5713
  return;
5286
5714
  });
5287
5715
  if (!conn)
@@ -5306,12 +5734,7 @@ class CdpBrowserDriver {
5306
5734
  return value;
5307
5735
  beaconSessions.drop(key);
5308
5736
  }
5309
- const wsUrl = await targetWsUrl(targetId).catch(() => {
5310
- return;
5311
- });
5312
- if (!wsUrl)
5313
- return null;
5314
- const conn = await new CdpConnection(wsUrl).connect().catch(() => {
5737
+ const conn = await openTargetConn(targetId).catch(() => {
5315
5738
  return;
5316
5739
  });
5317
5740
  if (!conn)
@@ -5326,17 +5749,11 @@ class CdpBrowserDriver {
5326
5749
  const held = beaconSessions.get(beaconKey(targetId));
5327
5750
  if (held)
5328
5751
  return probeOver(held, timeoutMs);
5329
- const wsUrl = await targetWsUrl(targetId).catch(() => {
5752
+ const conn = await openTargetConn(targetId, { timeoutMs }).catch(() => {
5330
5753
  return;
5331
5754
  });
5332
- if (!wsUrl)
5333
- return { responsive: false, beaconTs: null };
5334
- const conn = new CdpConnection(wsUrl, { timeoutMs });
5335
- try {
5336
- await conn.connect();
5337
- } catch {
5755
+ if (!conn)
5338
5756
  return { responsive: false, beaconTs: null };
5339
- }
5340
5757
  try {
5341
5758
  return await probeOver(conn, timeoutMs);
5342
5759
  } finally {
@@ -5412,7 +5829,7 @@ async function reapStaleAgentTabs(driver, backend) {
5412
5829
  // src/shared-tools.ts
5413
5830
  init_driver();
5414
5831
  import { mkdir as mkdir5, writeFile as writeFile4 } from "node:fs/promises";
5415
- import { dirname as dirname2, join as join4 } from "node:path";
5832
+ import { dirname as dirname2, join as join5 } from "node:path";
5416
5833
 
5417
5834
  // src/png.ts
5418
5835
  import { once } from "node:events";
@@ -6117,7 +6534,7 @@ async function closePage(driver, args) {
6117
6534
  }
6118
6535
  async function writeSelectedFile(id) {
6119
6536
  await mkdir5(STATE_DIR, { recursive: true });
6120
- await writeFile4(join4(STATE_DIR, "selected"), id, "utf8");
6537
+ await writeFile4(join5(STATE_DIR, "selected"), id, "utf8");
6121
6538
  }
6122
6539
  async function selectPage(driver, args) {
6123
6540
  if (args.target === undefined || args.target === "")
@@ -6181,7 +6598,7 @@ function serializeForSink(value) {
6181
6598
  return json ?? "null";
6182
6599
  }
6183
6600
  async function writeJsonSink(savePath, value) {
6184
- const path = savePath.startsWith("/") ? savePath : join4(ARTIFACT_DIR, savePath);
6601
+ const path = savePath.startsWith("/") ? savePath : join5(ARTIFACT_DIR, savePath);
6185
6602
  await mkdir5(dirname2(path), { recursive: true });
6186
6603
  const json = serializeForSink(value);
6187
6604
  await writeFile4(path, json, "utf8");
@@ -6325,10 +6742,45 @@ async function takeSnapshot(driver, args = {}) {
6325
6742
  `), target: target3(page.info), nodeCount: nodes.length };
6326
6743
  });
6327
6744
  }
6745
+ function describeElementSource() {
6746
+ return `function() {
6747
+ var MAX_NAME_LENGTH = ${MAX_NAME_LENGTH};
6748
+ ${ACCNAME_HELPERS_SOURCE}
6749
+ var el = this;
6750
+ if (!el || el.nodeType !== 1) return null;
6751
+ var role = implicitRole(el);
6752
+ var name = accessibleName(el, !!CONTENT_NAMED_ROLES[role]);
6753
+ if (!name) name = truncate(el.innerText || el.textContent || "");
6754
+ return (role || el.tagName.toLowerCase()) + (name ? " " + JSON.stringify(name) : "");
6755
+ }`;
6756
+ }
6757
+ var DESCRIBE_TIMEOUT_MS = 2000;
6758
+ async function describeElement(page, loc) {
6759
+ let timer;
6760
+ try {
6761
+ const timeout = new Promise((r) => {
6762
+ timer = setTimeout(() => r(undefined), DESCRIBE_TIMEOUT_MS);
6763
+ });
6764
+ const desc = await Promise.race([page.callOnElement(loc, describeElementSource()), timeout]);
6765
+ return typeof desc === "string" && desc.length > 0 ? desc : undefined;
6766
+ } catch {
6767
+ return;
6768
+ } finally {
6769
+ clearTimeout(timer);
6770
+ }
6771
+ }
6772
+ function isElementLocator(d) {
6773
+ return !("x" in d) && !("dx" in d);
6774
+ }
6775
+ function elementField(element) {
6776
+ return element === undefined ? {} : { element };
6777
+ }
6328
6778
  async function click(driver, args) {
6779
+ const loc = locatorOf(args);
6329
6780
  return withPage2(driver, args.target, async (page) => {
6330
- const { x, y } = await page.click(locatorOf(args), { button: args.button ?? "left", clickCount: args.clickCount ?? 1, modifiers: args.modifiers });
6331
- return { clicked: true, x, y };
6781
+ const element = await describeElement(page, loc);
6782
+ const { x, y } = await page.click(loc, { button: args.button ?? "left", clickCount: args.clickCount ?? 1, modifiers: args.modifiers });
6783
+ return { clicked: true, ...elementField(element), x, y };
6332
6784
  });
6333
6785
  }
6334
6786
  function resolveScrollAnchor(args) {
@@ -6364,9 +6816,11 @@ async function scroll(driver, args) {
6364
6816
  });
6365
6817
  }
6366
6818
  async function hover(driver, args) {
6819
+ const loc = locatorOf(args);
6367
6820
  return withPage2(driver, args.target, async (page) => {
6368
- const { x, y } = await page.hover(locatorOf(args));
6369
- return { hovered: true, x, y };
6821
+ const element = await describeElement(page, loc);
6822
+ const { x, y } = await page.hover(loc);
6823
+ return { hovered: true, ...elementField(element), x, y };
6370
6824
  });
6371
6825
  }
6372
6826
  function resolveDragTo(to) {
@@ -6432,16 +6886,29 @@ async function drag(driver, args) {
6432
6886
  const steps = resolveDragSteps(args.steps);
6433
6887
  const mode = resolveDragMode(args.mode, driver.capabilities);
6434
6888
  return withPage2(driver, args.target, async (page) => {
6435
- const { from, to } = await page.drag(locatorOf(args.from), destination, { mode, steps });
6436
- return { dragged: true, mode, steps, from, to };
6889
+ const fromLoc = locatorOf(args.from);
6890
+ const element = await describeElement(page, fromLoc);
6891
+ const targetElement = isElementLocator(destination) ? await describeElement(page, destination) : undefined;
6892
+ const { from, to } = await page.drag(fromLoc, destination, { mode, steps });
6893
+ return {
6894
+ dragged: true,
6895
+ ...elementField(element),
6896
+ ...targetElement === undefined ? {} : { target_element: targetElement },
6897
+ mode,
6898
+ steps,
6899
+ from,
6900
+ to
6901
+ };
6437
6902
  });
6438
6903
  }
6439
6904
  async function fill(driver, args) {
6440
6905
  if (typeof args.value !== "string")
6441
6906
  throw new SharedToolError("fill requires a string { value }");
6907
+ const loc = locatorOf(args);
6442
6908
  return withPage2(driver, args.target, async (page) => {
6443
- await page.setValue(locatorOf(args), args.value);
6444
- return { filled: true, value: args.value };
6909
+ const element = await describeElement(page, loc);
6910
+ await page.setValue(loc, args.value);
6911
+ return { filled: true, ...elementField(element), value: args.value };
6445
6912
  });
6446
6913
  }
6447
6914
  async function fillForm(driver, args) {
@@ -6449,21 +6916,26 @@ async function fillForm(driver, args) {
6449
6916
  throw new SharedToolError("fill_form requires a non-empty { fields } array");
6450
6917
  return withPage2(driver, args.target, async (page) => {
6451
6918
  let filled = 0;
6919
+ const elements = [];
6452
6920
  for (const f of args.fields) {
6453
6921
  if (typeof f.value !== "string")
6454
6922
  throw new SharedToolError("each fill_form field requires a string value");
6455
- await page.setValue(locatorOf(f), f.value);
6923
+ const loc = locatorOf(f);
6924
+ elements.push(await describeElement(page, loc) ?? null);
6925
+ await page.setValue(loc, f.value);
6456
6926
  filled++;
6457
6927
  }
6458
- return { filled, fields: args.fields.length };
6928
+ return { filled, fields: args.fields.length, elements };
6459
6929
  });
6460
6930
  }
6461
6931
  async function typeText(driver, args) {
6462
6932
  if (typeof args.text !== "string")
6463
6933
  throw new SharedToolError("type_text requires a string { text }");
6934
+ const loc = locatorOf(args);
6464
6935
  return withPage2(driver, args.target, async (page) => {
6465
- await page.typeText(locatorOf(args), args.text);
6466
- return { typed: true, text: args.text };
6936
+ const element = await describeElement(page, loc);
6937
+ await page.typeText(loc, args.text);
6938
+ return { typed: true, ...elementField(element), text: args.text };
6467
6939
  });
6468
6940
  }
6469
6941
  async function pressKey(driver, args) {
@@ -6481,8 +6953,10 @@ async function uploadFile(driver, args) {
6481
6953
  throw new SharedToolError("upload_file requires { files } as a non-empty path or array of paths");
6482
6954
  }
6483
6955
  return withPage2(driver, args.target, async (page) => {
6484
- await page.setFiles(locatorOf(args), files);
6485
- return { uploaded: files };
6956
+ const loc = locatorOf(args);
6957
+ const element = await describeElement(page, loc);
6958
+ await page.setFiles(loc, files);
6959
+ return { uploaded: files, ...elementField(element) };
6486
6960
  });
6487
6961
  }
6488
6962
  function stamp() {
@@ -6496,7 +6970,7 @@ function resolveScreenshotScale(scale, capabilities) {
6496
6970
  throw new SharedToolError(`take_screenshot: 'scale' must be a finite number greater than 0 and at most ${MAX_SCREENSHOT_SCALE} (default 1)`);
6497
6971
  }
6498
6972
  if (scale !== 1 && !capabilities.has("screenshot.scale")) {
6499
- throw new SharedToolError("take_screenshot: 'scale' is not supported by this backend (WebDriver BiDi's browsingContext.captureScreenshot has no scale parameter). " + `Call emulate with deviceScaleFactor:${scale} first and capture at scale 1, or use --browser chrome for a per-capture scale.`);
6973
+ throw new SharedToolError("take_screenshot: 'scale' is not supported by this backend (no per-capture scale primitive). " + `Call emulate with deviceScaleFactor:${scale} first and capture at scale 1, or use --browser chrome for a per-capture scale.`);
6500
6974
  }
6501
6975
  return scale;
6502
6976
  }
@@ -6596,7 +7070,7 @@ async function takeScreenshot(driver, args = {}) {
6596
7070
  return withPage2(driver, args.target, async (page) => {
6597
7071
  const clip = args.uid !== undefined || args.selector ? locatorOf(args) : undefined;
6598
7072
  const ext = format === "jpeg" ? "jpg" : "png";
6599
- const path = args.savePath ?? join4(ARTIFACT_DIR, `screenshot-${page.info.id.slice(0, 8)}-${stamp()}.${ext}`);
7073
+ const path = args.savePath ?? join5(ARTIFACT_DIR, `screenshot-${page.info.id.slice(0, 8)}-${stamp()}.${ext}`);
6600
7074
  const stitch = async (banded) => {
6601
7075
  if (format !== "png")
6602
7076
  throw tiledCaptureRefusal("format", banded);
@@ -6821,7 +7295,7 @@ var LEASE_TOOLS = {
6821
7295
 
6822
7296
  // src/tools/console.ts
6823
7297
  init_client();
6824
- import { readFile as readFile4 } from "node:fs/promises";
7298
+ import { readFile as readFile5 } from "node:fs/promises";
6825
7299
 
6826
7300
  // src/tools/recorder.ts
6827
7301
  init_client();
@@ -7024,7 +7498,7 @@ function lineToEntry(line, index) {
7024
7498
  async function readConsoleEntries(file) {
7025
7499
  let raw;
7026
7500
  try {
7027
- raw = await readFile4(file, "utf8");
7501
+ raw = await readFile5(file, "utf8");
7028
7502
  } catch {
7029
7503
  return [];
7030
7504
  }
@@ -7082,7 +7556,7 @@ async function getConsoleMessage(args = {}) {
7082
7556
 
7083
7557
  // src/tools/network.ts
7084
7558
  init_client();
7085
- import { readFile as readFile5 } from "node:fs/promises";
7559
+ import { readFile as readFile6 } from "node:fs/promises";
7086
7560
  var DEFAULT_CAPTURE_MS2 = 2500;
7087
7561
  function asHeaders(v) {
7088
7562
  if (!v || typeof v !== "object")
@@ -7149,7 +7623,7 @@ function correlate(lines) {
7149
7623
  async function readNetworkRequests(file) {
7150
7624
  let raw;
7151
7625
  try {
7152
- raw = await readFile5(file, "utf8");
7626
+ raw = await readFile6(file, "utf8");
7153
7627
  } catch {
7154
7628
  return [];
7155
7629
  }
@@ -7234,8 +7708,8 @@ async function getNetworkRequest(args = {}) {
7234
7708
 
7235
7709
  // src/tools/performance.ts
7236
7710
  init_client();
7237
- import { mkdir as mkdir7, readFile as readFile6, writeFile as writeFile6, stat, unlink as unlink4 } from "node:fs/promises";
7238
- import { join as join5 } from "node:path";
7711
+ import { mkdir as mkdir7, readFile as readFile7, writeFile as writeFile6, stat, unlink as unlink4 } from "node:fs/promises";
7712
+ import { join as join6 } from "node:path";
7239
7713
  var ARTIFACT_DIR2 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
7240
7714
  var STATE_DIR2 = process.env.CDP_STATE_DIR ?? "/tmp/cdp-toolkit";
7241
7715
  var DEFAULT_CATEGORIES = [
@@ -7253,7 +7727,7 @@ function shortId(id) {
7253
7727
  return id.slice(0, 8);
7254
7728
  }
7255
7729
  function stateFilePath() {
7256
- return join5(STATE_DIR2, "trace-state.json");
7730
+ return join6(STATE_DIR2, "trace-state.json");
7257
7731
  }
7258
7732
  function bufferTraceData(conn, sink) {
7259
7733
  return conn.on("Tracing.dataCollected", (params) => {
@@ -7276,7 +7750,7 @@ async function endTrace(conn, sink, timeoutMs = 30000) {
7276
7750
  }
7277
7751
  async function writeTrace(events, targetId) {
7278
7752
  await mkdir7(ARTIFACT_DIR2, { recursive: true });
7279
- const path = join5(ARTIFACT_DIR2, `trace-${shortId(targetId)}-${stamp2()}.json`);
7753
+ const path = join6(ARTIFACT_DIR2, `trace-${shortId(targetId)}-${stamp2()}.json`);
7280
7754
  const body = JSON.stringify({ traceEvents: events, metadata: { source: "cdp-toolkit" } });
7281
7755
  await writeFile6(path, body, "utf8");
7282
7756
  const { size } = await stat(path);
@@ -7319,7 +7793,7 @@ async function performanceStopTrace(args = {}) {
7319
7793
  if (!entry) {
7320
7794
  let hint = "";
7321
7795
  try {
7322
- const raw = await readFile6(stateFilePath(), "utf8");
7796
+ const raw = await readFile7(stateFilePath(), "utf8");
7323
7797
  const state = JSON.parse(raw);
7324
7798
  hint = state.pid === process.pid ? ` (state file lists target ${shortId(state.targetId)} but its live connection is gone)` : ` (trace was started by a DIFFERENT process pid=${state.pid}; live recordings cannot cross process boundaries)`;
7325
7799
  } catch {}
@@ -7449,7 +7923,7 @@ async function performanceAnalyzeInsight(args = {}) {
7449
7923
  }
7450
7924
  let raw;
7451
7925
  try {
7452
- raw = await readFile6(args.tracePath, "utf8");
7926
+ raw = await readFile7(args.tracePath, "utf8");
7453
7927
  } catch (err) {
7454
7928
  throw new CdpError(`cannot read trace file '${args.tracePath}': ${err.message}`);
7455
7929
  }
@@ -7469,7 +7943,7 @@ async function performanceAnalyzeInsight(args = {}) {
7469
7943
  init_client();
7470
7944
  import { spawn } from "node:child_process";
7471
7945
  import { mkdir as mkdir8, rm as rm2, stat as stat2, writeFile as writeFile7 } from "node:fs/promises";
7472
- import { join as join6 } from "node:path";
7946
+ import { join as join7 } from "node:path";
7473
7947
  var ARTIFACT_DIR3 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
7474
7948
  var FFMPEG_BIN = process.env.CDP_FFMPEG ?? "ffmpeg";
7475
7949
  function frameDurationsMs(ledger, stopWallclockMs) {
@@ -7585,6 +8059,22 @@ function selectEncoder(encodersOutput) {
7585
8059
  }
7586
8060
  throw new CdpError(`ffmpeg reports none of the supported video encoders (${ENCODER_LADDER.map((c) => c.encoder).join(", ")}). ` + "Install a full ffmpeg build: 'brew install ffmpeg' (macOS) or 'apt install ffmpeg' (Debian/Ubuntu).");
7587
8061
  }
8062
+ function supportsFpsMode(versionOutput) {
8063
+ const m = /ffmpeg version n?(\d+)\.(\d+)/.exec(versionOutput);
8064
+ if (!m)
8065
+ return /ffmpeg version N-/.test(versionOutput) ? true : undefined;
8066
+ const major = Number(m[1]);
8067
+ const minor = Number(m[2]);
8068
+ return major > 5 || major === 5 && minor >= 1;
8069
+ }
8070
+ function chooseFpsMode(versionOutput, helpOutput) {
8071
+ const byVersion = versionOutput === undefined ? undefined : supportsFpsMode(versionOutput);
8072
+ if (byVersion !== undefined)
8073
+ return byVersion;
8074
+ if (helpOutput !== undefined && /-vsync\b|-fps_mode\b/.test(helpOutput))
8075
+ return /-fps_mode\b/.test(helpOutput);
8076
+ return true;
8077
+ }
7588
8078
  function buildFfmpegArgs(manifestPath, outPath, choice) {
7589
8079
  return [
7590
8080
  "-hide_banner",
@@ -7597,8 +8087,7 @@ function buildFfmpegArgs(manifestPath, outPath, choice) {
7597
8087
  "0",
7598
8088
  "-i",
7599
8089
  manifestPath,
7600
- "-vsync",
7601
- "vfr",
8090
+ ...choice.fpsMode ? ["-fps_mode", "vfr"] : ["-vsync", "vfr"],
7602
8091
  "-vf",
7603
8092
  "scale=trunc(iw/2)*2:trunc(ih/2)*2",
7604
8093
  "-c:v",
@@ -7640,8 +8129,19 @@ async function probeEncoder() {
7640
8129
  }
7641
8130
  if (res.code !== 0)
7642
8131
  throw new CdpError(`${FFMPEG_MISSING} ('-encoders' exited ${res.code}: ${res.stderr.trim().slice(0, 300)})`);
7643
- return selectEncoder(`${res.stdout}
8132
+ const choice = selectEncoder(`${res.stdout}
7644
8133
  ${res.stderr}`);
8134
+ const output = async (args) => {
8135
+ const r = await run(FFMPEG_BIN, args).catch(() => {
8136
+ return;
8137
+ });
8138
+ return r && r.code === 0 ? `${r.stdout}
8139
+ ${r.stderr}` : undefined;
8140
+ };
8141
+ const version = await output(["-version"]);
8142
+ const byVersion = version === undefined ? undefined : supportsFpsMode(version);
8143
+ const help = byVersion === undefined ? await output(["-hide_banner", "-h", "full"]) : undefined;
8144
+ return { ...choice, fpsMode: chooseFpsMode(version, help) };
7645
8145
  })();
7646
8146
  encoderProbe.catch(() => {
7647
8147
  encoderProbe = undefined;
@@ -7690,7 +8190,7 @@ async function startScreenRecording(args = {}) {
7690
8190
  conn.close();
7691
8191
  throw err;
7692
8192
  }
7693
- const spoolDir = join6(ARTIFACT_DIR3, `screencast-${shortId2(target.id)}-${stamp3()}`);
8193
+ const spoolDir = join7(ARTIFACT_DIR3, `screencast-${shortId2(target.id)}-${stamp3()}`);
7694
8194
  try {
7695
8195
  await mkdir8(spoolDir, { recursive: true });
7696
8196
  } catch (err) {
@@ -7733,7 +8233,7 @@ async function startScreenRecording(args = {}) {
7733
8233
  seq += 1;
7734
8234
  const file = `frame-${String(seq).padStart(6, "0")}.${ext}`;
7735
8235
  rec.ledger.push({ file, timestamp, width: size.width, height: size.height });
7736
- rec.writes = rec.writes.then(() => writeFile7(join6(spoolDir, file), buf)).catch(() => {
8236
+ rec.writes = rec.writes.then(() => writeFile7(join7(spoolDir, file), buf)).catch(() => {
7737
8237
  rec.dropped += 1;
7738
8238
  rec.unwritten.add(file);
7739
8239
  });
@@ -7797,9 +8297,9 @@ async function stopScreenRecording(args = {}) {
7797
8297
  throw new CdpError(`screen recording captured 0 frames for target ${shortId2(rec.target.id)}. Chrome emits a screencast frame only on repaint: a fully backgrounded or occluded tab may never paint. Retry with bringToFront:true, or drive the page while recording.`);
7798
8298
  }
7799
8299
  await mkdir8(ARTIFACT_DIR3, { recursive: true });
7800
- const outPath = args.savePath ?? join6(ARTIFACT_DIR3, `screen-recording-${shortId2(rec.target.id)}-${stamp3()}.mp4`);
8300
+ const outPath = args.savePath ?? join7(ARTIFACT_DIR3, `screen-recording-${shortId2(rec.target.id)}-${stamp3()}.mp4`);
7801
8301
  const frames = coalesceToConcatGrid(ledger, stoppedAt);
7802
- const manifestPath = join6(rec.spoolDir, "frames.ffconcat");
8302
+ const manifestPath = join7(rec.spoolDir, "frames.ffconcat");
7803
8303
  await writeFile7(manifestPath, buildConcatManifest(frames), "utf8");
7804
8304
  const durationMs = frames.reduce((total, f) => total + f.durationMs, 0);
7805
8305
  const { width, height } = evenDimensions(ledger[0].width, ledger[0].height);
@@ -7833,7 +8333,7 @@ ffmpeg said: ${res.stderr.trim().slice(0, 800)}`);
7833
8333
  // src/tools/heap.ts
7834
8334
  init_client();
7835
8335
  import { mkdir as mkdir9, writeFile as writeFile8 } from "node:fs/promises";
7836
- import { join as join7 } from "node:path";
8336
+ import { join as join8 } from "node:path";
7837
8337
  var ARTIFACT_DIR4 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
7838
8338
  function stamp4(targetId) {
7839
8339
  const short = targetId.slice(0, 8);
@@ -7859,7 +8359,7 @@ async function takeHeapsnapshot(args = {}) {
7859
8359
  throw new Error("HeapProfiler.takeHeapSnapshot produced no chunks");
7860
8360
  }
7861
8361
  await mkdir9(ARTIFACT_DIR4, { recursive: true });
7862
- const path = args.savePath ? args.savePath.startsWith("/") ? args.savePath : join7(ARTIFACT_DIR4, args.savePath) : join7(ARTIFACT_DIR4, `take_heapsnapshot-${stamp4(target.id)}.heapsnapshot`);
8362
+ const path = args.savePath ? args.savePath.startsWith("/") ? args.savePath : join8(ARTIFACT_DIR4, args.savePath) : join8(ARTIFACT_DIR4, `take_heapsnapshot-${stamp4(target.id)}.heapsnapshot`);
7863
8363
  await writeFile8(path, snapshot, "utf8");
7864
8364
  const bytes = Buffer.byteLength(snapshot, "utf8");
7865
8365
  return {
@@ -7875,7 +8375,7 @@ async function takeHeapsnapshot(args = {}) {
7875
8375
  init_client();
7876
8376
  init_endpoints();
7877
8377
  import { spawn as spawn2 } from "node:child_process";
7878
- import { mkdir as mkdir10, readFile as readFile7, stat as stat3 } from "node:fs/promises";
8378
+ import { mkdir as mkdir10, readFile as readFile8, stat as stat3 } from "node:fs/promises";
7879
8379
  var ARTIFACT_DIR5 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
7880
8380
  function cdpPort() {
7881
8381
  const base = currentEndpoint().base;
@@ -7965,7 +8465,7 @@ async function lighthouseAudit(args) {
7965
8465
  }
7966
8466
  let raw;
7967
8467
  try {
7968
- raw = await readFile7(outPath, "utf8");
8468
+ raw = await readFile8(outPath, "utf8");
7969
8469
  } catch {
7970
8470
  raw = undefined;
7971
8471
  }
@@ -8155,15 +8655,15 @@ async function clickFocusGated(args) {
8155
8655
  // src/tools/downloads.ts
8156
8656
  init_client();
8157
8657
  import { readdir as readdir3, rename as rename2, stat as stat4 } from "node:fs/promises";
8158
- import { basename, extname, join as join9 } from "node:path";
8658
+ import { basename, extname, join as join10 } from "node:path";
8159
8659
 
8160
8660
  // src/tools/browser-session.ts
8161
8661
  init_client();
8162
8662
  init_endpoints();
8163
8663
  import { mkdir as mkdir11 } from "node:fs/promises";
8164
- import { join as join8 } from "node:path";
8664
+ import { join as join9 } from "node:path";
8165
8665
  var ARTIFACT_DIR6 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
8166
- var DOWNLOADS_DIR = join8(ARTIFACT_DIR6, "downloads");
8666
+ var DOWNLOADS_DIR = join9(ARTIFACT_DIR6, "downloads");
8167
8667
  var DOWNLOAD_BUFFER_LIMIT = 50;
8168
8668
  var sessions2 = new Map;
8169
8669
  function sessionKey() {
@@ -8330,7 +8830,7 @@ async function waitForDownload(args = {}) {
8330
8830
  const taken = new Set(await readdir3(DOWNLOADS_DIR).catch(() => []));
8331
8831
  taken.delete(basename(rec.filePath));
8332
8832
  const finalName = nextFreeName(suggestedFilename, taken);
8333
- const path = join9(DOWNLOADS_DIR, finalName);
8833
+ const path = join10(DOWNLOADS_DIR, finalName);
8334
8834
  await rename2(rec.filePath, path);
8335
8835
  const bytes = (await stat4(path)).size;
8336
8836
  return { path, suggestedFilename, bytes, ...rec.url ? { url: rec.url } : {}, target };
@@ -8389,7 +8889,7 @@ async function grantPermissions(args = {}) {
8389
8889
  // src/tools/extract.ts
8390
8890
  init_client();
8391
8891
  import { mkdir as mkdir12, writeFile as writeFile9 } from "node:fs/promises";
8392
- import { dirname as dirname3, join as join10 } from "node:path";
8892
+ import { dirname as dirname3, join as join11 } from "node:path";
8393
8893
  var ARTIFACT_DIR7 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
8394
8894
  var DEFAULT_BASE_URL = "http://127.0.0.1:8090/v1";
8395
8895
  var DEFAULT_MODEL = "schematron";
@@ -8790,7 +9290,7 @@ async function extractPage(driver, args) {
8790
9290
  };
8791
9291
  if (args.savePath === undefined || args.savePath === "")
8792
9292
  return result;
8793
- const path = args.savePath.startsWith("/") ? args.savePath : join10(ARTIFACT_DIR7, args.savePath);
9293
+ const path = args.savePath.startsWith("/") ? args.savePath : join11(ARTIFACT_DIR7, args.savePath);
8794
9294
  await mkdir12(dirname3(path), { recursive: true });
8795
9295
  const json = JSON.stringify(result, null, 2);
8796
9296
  await writeFile9(path, json, "utf8");
@@ -9464,7 +9964,7 @@ var MANIFEST = [
9464
9964
  },
9465
9965
  {
9466
9966
  name: "dispatch_mouse",
9467
- description: "Dispatch one raw mouse event at viewport coordinates; Chrome-only.",
9967
+ description: "Dispatch one raw mouse event at viewport coordinates; Firefox needs 160 or newer.",
9468
9968
  inputSchema: {
9469
9969
  type: "object",
9470
9970
  properties: {
@@ -9621,7 +10121,7 @@ var MANIFEST = [
9621
10121
  },
9622
10122
  {
9623
10123
  name: "grant_permissions",
9624
- description: "Grant or reset browser permissions; permissions are origin-scoped and Chrome-only.",
10124
+ description: "Grant or reset browser permissions; permissions are origin-scoped (Chrome, Firefox 160+).",
9625
10125
  inputSchema: {
9626
10126
  type: "object",
9627
10127
  properties: {
@@ -10702,7 +11202,7 @@ import { spawn as spawn4 } from "node:child_process";
10702
11202
  import { existsSync as existsSync2, mkdtempSync, readFileSync as readFileSync2, rmSync, writeFileSync } from "node:fs";
10703
11203
  import { createConnection, createServer as createServer2 } from "node:net";
10704
11204
  import { tmpdir } from "node:os";
10705
- import { join as join12 } from "node:path";
11205
+ import { join as join13 } from "node:path";
10706
11206
  function resolveBinary() {
10707
11207
  const candidates = [
10708
11208
  process.env.FIREFOX_BIN,
@@ -10782,7 +11282,7 @@ var LAUNCH_USER_JS_PREFS = {
10782
11282
  "dom.file.createInChild": true
10783
11283
  };
10784
11284
  function writeLaunchUserJs(profilePath) {
10785
- const target = join12(profilePath, "user.js");
11285
+ const target = join13(profilePath, "user.js");
10786
11286
  const existing = existsSync2(target) ? readFileSync2(target, "utf8") : "";
10787
11287
  const present = new Set;
10788
11288
  for (const line of existing.split(`
@@ -10804,7 +11304,7 @@ async function launchFirefox(opts = {}) {
10804
11304
  const binary = resolveBinary();
10805
11305
  const port = await pickPort(opts.port);
10806
11306
  const isThrowaway = opts.profilePath === undefined;
10807
- const profilePath = opts.profilePath ?? mkdtempSync(join12(tmpdir(), "cdp-toolkit-ff-profile-"));
11307
+ const profilePath = opts.profilePath ?? mkdtempSync(join13(tmpdir(), "cdp-toolkit-ff-profile-"));
10808
11308
  if (isThrowaway)
10809
11309
  writeLaunchUserJs(profilePath);
10810
11310
  const args = ["--profile", profilePath, "--remote-debugging-port", String(port), "--no-remote"];
@@ -11004,6 +11504,16 @@ async function withPage4(driver, target, fn) {
11004
11504
  await page.release();
11005
11505
  }
11006
11506
  }
11507
+ async function dispatchMouse2(driver, args) {
11508
+ validateDispatchMouseArgs(args);
11509
+ modifierBits(args.modifiers);
11510
+ return withPage4(driver, args.target, async (page) => {
11511
+ if (!page.dispatchMouse)
11512
+ throw new BidiToolError("dispatch_mouse: this page driver has no raw mouse dispatch");
11513
+ await page.dispatchMouse({ action: args.action, x: args.x, y: args.y, button: args.button, clickCount: args.clickCount, modifiers: args.modifiers });
11514
+ return { dispatched: args.action, x: args.x, y: args.y };
11515
+ });
11516
+ }
11007
11517
  var consoleBuffers = new Map;
11008
11518
  var networkBuffers = new Map;
11009
11519
  function refuseWorkerSelector(driver, target) {
@@ -11076,6 +11586,13 @@ async function getNetworkRequest2(driver, args = {}) {
11076
11586
  return withPage4(driver, args.target, async (page) => {
11077
11587
  const buf = bufferFor(networkBuffers, page.info.id);
11078
11588
  const found = args.requestId ? buf.find((r) => r.requestId === args.requestId || r.request === args.requestId) : buf.find((r) => typeof r.url === "string" && r.url.includes(args.url));
11589
+ if (args.includeBody) {
11590
+ const id = args.requestId ?? (found ? String(found.requestId ?? found.request ?? "") : "");
11591
+ if (!id)
11592
+ 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)");
11593
+ const { body, base64Encoded } = await page.getResponseBody(id);
11594
+ return { ...found ?? { requestId: id }, body, bodyBase64Encoded: base64Encoded };
11595
+ }
11079
11596
  if (!found)
11080
11597
  throw new BidiToolError("no matching network request in the current buffer; run list_network_requests first");
11081
11598
  return found;
@@ -11151,7 +11668,232 @@ var BIDI_ONLY_TOOLS = {
11151
11668
  get_network_request: getNetworkRequest2,
11152
11669
  mock_request: mockRequest2,
11153
11670
  list_mocks: listMocks2,
11154
- clear_mocks: clearMocks2
11671
+ clear_mocks: clearMocks2,
11672
+ dispatch_mouse: dispatchMouse2
11673
+ };
11674
+
11675
+ // src/bidi-browser-tools.ts
11676
+ init_driver2();
11677
+ import { mkdir as mkdir14, readdir as readdir4, realpath, rename as rename4, stat as stat5 } from "node:fs/promises";
11678
+ import { basename as basename2, dirname as dirname4, join as join14, resolve } from "node:path";
11679
+ function unsupported(message) {
11680
+ return Object.assign(new Error(message), { code: "unsupported" });
11681
+ }
11682
+ function scopeOf(driver, tool) {
11683
+ const d = driver;
11684
+ if (typeof d.withBrowserConnection !== "function" || typeof d.setDisposeHook !== "function") {
11685
+ throw unsupported(`${tool}: this driver has no browser-scoped connection (the Firefox BiDi driver does; Chrome uses src/tools/).`);
11686
+ }
11687
+ return d;
11688
+ }
11689
+ async function targetOf(driver, target) {
11690
+ const page = await driver.page(target);
11691
+ try {
11692
+ return { id: page.info.id, url: page.info.url, title: page.info.title };
11693
+ } finally {
11694
+ await page.release();
11695
+ }
11696
+ }
11697
+ var FIREFOX_DOWNLOAD_STAGING_DIR = join14(dirname4(DOWNLOADS_DIR), "downloads-firefox-staging");
11698
+ var downloadStates = new WeakMap;
11699
+ function downloadId(p) {
11700
+ const v = p.download ?? p.navigation;
11701
+ return typeof v === "string" && v.length > 0 ? v : undefined;
11702
+ }
11703
+ function deliver(s, r) {
11704
+ r.state = "completed";
11705
+ s.downloads.push(r);
11706
+ while (s.downloads.length > DOWNLOAD_BUFFER_LIMIT) {
11707
+ const i = s.downloads.findIndex((d) => d.consumed);
11708
+ s.downloads.splice(i >= 0 ? i : 0, 1);
11709
+ }
11710
+ const waiter = s.waiters.shift();
11711
+ if (waiter) {
11712
+ r.consumed = true;
11713
+ waiter(r);
11714
+ }
11715
+ }
11716
+ function downloadStateFor(conn) {
11717
+ let s = downloadStates.get(conn);
11718
+ if (s)
11719
+ return s;
11720
+ const state = { downloads: [], begun: new Map, waiters: [], stagingDirs: new Set([resolve(FIREFOX_DOWNLOAD_STAGING_DIR)]) };
11721
+ downloadStates.set(conn, state);
11722
+ conn.on("browsingContext.downloadWillBegin", (p) => {
11723
+ const id = downloadId(p);
11724
+ if (!id)
11725
+ return;
11726
+ state.begun.set(id, { id, url: p.url, suggestedFilename: p.suggestedFilename, state: "inProgress", consumed: false });
11727
+ if (state.begun.size > DOWNLOAD_BUFFER_LIMIT)
11728
+ state.begun.delete(state.begun.keys().next().value);
11729
+ });
11730
+ conn.on("browsingContext.downloadEnd", (p) => {
11731
+ const id = downloadId(p);
11732
+ if (!id)
11733
+ return;
11734
+ const rec = state.begun.get(id) ?? { id, state: "inProgress", consumed: false };
11735
+ state.begun.delete(id);
11736
+ if (p.status !== "complete" || !p.filepath)
11737
+ return;
11738
+ if (!state.stagingDirs.has(resolve(dirname4(p.filepath))))
11739
+ return;
11740
+ rec.url ??= p.url;
11741
+ const held = join14(dirname4(p.filepath), `${id.replace(/[^A-Za-z0-9-]/g, "_")}.download`);
11742
+ rename4(p.filepath, held).then(() => {
11743
+ rec.filePath = held;
11744
+ }, () => {
11745
+ rec.filePath = p.filepath ?? undefined;
11746
+ }).finally(() => deliver(state, rec));
11747
+ });
11748
+ return state;
11749
+ }
11750
+ async function armFirefoxDownloads(conn, s, scope) {
11751
+ await mkdir14(FIREFOX_DOWNLOAD_STAGING_DIR, { recursive: true });
11752
+ await mkdir14(DOWNLOADS_DIR, { recursive: true });
11753
+ s.stagingDirs.add(resolve(await realpath(FIREFOX_DOWNLOAD_STAGING_DIR)));
11754
+ scope.setDisposeHook("browser.downloads", async (c) => {
11755
+ await c.send("browser.setDownloadBehavior", { downloadBehavior: null });
11756
+ });
11757
+ await conn.send("browser.setDownloadBehavior", { downloadBehavior: { type: "allowed", destinationFolder: FIREFOX_DOWNLOAD_STAGING_DIR } });
11758
+ }
11759
+ async function disarmFirefoxDownloads(conn, scope) {
11760
+ await conn.send("browser.setDownloadBehavior", { downloadBehavior: null });
11761
+ scope.setDisposeHook("browser.downloads", undefined);
11762
+ }
11763
+ function nextFirefoxDownload(s, timeoutMs) {
11764
+ const buffered = s.downloads.find((d) => !d.consumed);
11765
+ if (buffered) {
11766
+ buffered.consumed = true;
11767
+ return Promise.resolve(buffered);
11768
+ }
11769
+ return new Promise((resolvePromise, reject) => {
11770
+ const waiter = (r) => {
11771
+ clearTimeout(timer);
11772
+ resolvePromise(r);
11773
+ };
11774
+ const timer = setTimeout(() => {
11775
+ const i = s.waiters.indexOf(waiter);
11776
+ if (i >= 0)
11777
+ s.waiters.splice(i, 1);
11778
+ reject(new Error(`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.`));
11779
+ }, timeoutMs);
11780
+ s.waiters.push(waiter);
11781
+ });
11782
+ }
11783
+ async function waitForDownloadFirefox(driver, args = {}) {
11784
+ validateWaitForDownloadArgs(args);
11785
+ const scope = scopeOf(driver, "wait_for_download");
11786
+ const target = await targetOf(driver, args.target);
11787
+ return scope.withBrowserConnection(async (conn) => {
11788
+ requireFirefox(conn, "browser.downloads");
11789
+ const s = downloadStateFor(conn);
11790
+ await armFirefoxDownloads(conn, s, scope);
11791
+ if (args.arm === true) {
11792
+ return { armed: true, downloadPath: DOWNLOADS_DIR, pending: s.downloads.filter((d) => !d.consumed).length, target };
11793
+ }
11794
+ let rec;
11795
+ try {
11796
+ rec = await nextFirefoxDownload(s, args.timeoutMs ?? 30000);
11797
+ } finally {
11798
+ if (s.waiters.length === 0)
11799
+ await disarmFirefoxDownloads(conn, scope).catch(() => {
11800
+ return;
11801
+ });
11802
+ }
11803
+ if (!rec.filePath) {
11804
+ throw new Error(`wait_for_download: download ${rec.id} completed without a file path (nothing to return)`);
11805
+ }
11806
+ const suggestedFilename = safeFilename(rec.suggestedFilename);
11807
+ const taken = new Set(await readdir4(DOWNLOADS_DIR).catch(() => []));
11808
+ taken.delete(basename2(rec.filePath));
11809
+ const finalName = nextFreeName(suggestedFilename, taken);
11810
+ const path = join14(DOWNLOADS_DIR, finalName);
11811
+ await rename4(rec.filePath, path);
11812
+ const bytes = (await stat5(path)).size;
11813
+ return { path, suggestedFilename, bytes, ...rec.url ? { url: rec.url } : {}, target };
11814
+ });
11815
+ }
11816
+ var FIREFOX_PERMISSION_DESCRIPTORS = {
11817
+ geolocation: { name: "geolocation" },
11818
+ notifications: { name: "notifications" },
11819
+ audioCapture: { name: "microphone" },
11820
+ videoCapture: { name: "camera" },
11821
+ durableStorage: { name: "persistent-storage" },
11822
+ midi: { name: "midi" },
11823
+ midiSysex: { name: "midi", sysex: true },
11824
+ wakeLockScreen: { name: "screen-wake-lock" }
11825
+ };
11826
+ function mapFirefoxPermissions(names) {
11827
+ return names.map((n) => {
11828
+ const d = Object.hasOwn(FIREFOX_PERMISSION_DESCRIPTORS, n) ? FIREFOX_PERMISSION_DESCRIPTORS[n] : undefined;
11829
+ if (!d) {
11830
+ throw unsupported(`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(", ")}.`);
11831
+ }
11832
+ return d;
11833
+ });
11834
+ }
11835
+ var trackedGrants = new WeakMap;
11836
+ function grantKey(origin, d) {
11837
+ return `${origin} ${JSON.stringify(d)}`;
11838
+ }
11839
+ async function restoreGrants(conn, grants) {
11840
+ const all = [...grants.values()];
11841
+ grants.clear();
11842
+ for (const g of all) {
11843
+ await conn.send("permissions.setPermission", { descriptor: g.descriptor, state: g.previous, origin: g.origin });
11844
+ }
11845
+ }
11846
+ async function queryState(page, d) {
11847
+ try {
11848
+ const v = await page.evaluate(`navigator.permissions.query(${JSON.stringify(d)}).then((p) => p.state, () => "prompt")`, { awaitPromise: true });
11849
+ return v === "granted" || v === "denied" ? v : "prompt";
11850
+ } catch {
11851
+ return "prompt";
11852
+ }
11853
+ }
11854
+ async function grantPermissionsFirefox(driver, args = {}) {
11855
+ validateGrantPermissionsArgs(args);
11856
+ const reset = args.reset === true;
11857
+ const permissions = args.permissions ?? [];
11858
+ const descriptors = mapFirefoxPermissions(permissions);
11859
+ const scope = scopeOf(driver, "grant_permissions");
11860
+ let grants = trackedGrants.get(driver);
11861
+ if (!grants) {
11862
+ grants = new Map;
11863
+ trackedGrants.set(driver, grants);
11864
+ }
11865
+ const tracked = grants;
11866
+ const page = await driver.page(args.target);
11867
+ try {
11868
+ const target = { id: page.info.id, url: page.info.url, title: page.info.title };
11869
+ return await scope.withBrowserConnection(async (conn) => {
11870
+ requireFirefox(conn, "browser.permissions");
11871
+ if (reset)
11872
+ await restoreGrants(conn, tracked);
11873
+ if (permissions.length === 0)
11874
+ return { reset: true, target };
11875
+ const origin = args.origin ?? originOf(page.info.url);
11876
+ if (!origin) {
11877
+ throw new Error(`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"`);
11878
+ }
11879
+ const pageIsOrigin = originOf(page.info.url) === origin;
11880
+ scope.setDisposeHook("browser.permissions", (c) => restoreGrants(c, tracked));
11881
+ for (const d of descriptors) {
11882
+ const key = grantKey(origin, d);
11883
+ if (!tracked.has(key)) {
11884
+ tracked.set(key, { origin, descriptor: d, previous: pageIsOrigin ? await queryState(page, d) : "prompt" });
11885
+ }
11886
+ await conn.send("permissions.setPermission", { descriptor: d, state: "granted", origin });
11887
+ }
11888
+ return { granted: [...permissions], origin, ...reset ? { reset: true } : {}, target };
11889
+ });
11890
+ } finally {
11891
+ await page.release();
11892
+ }
11893
+ }
11894
+ var BIDI_BROWSER_TOOLS = {
11895
+ wait_for_download: waitForDownloadFirefox,
11896
+ grant_permissions: grantPermissionsFirefox
11155
11897
  };
11156
11898
 
11157
11899
  // src/firefox-tools.ts
@@ -11159,6 +11901,7 @@ var FIREFOX_TOOLS = {
11159
11901
  ...SHARED_TOOLS,
11160
11902
  ...BIDI_ONLY_TOOLS,
11161
11903
  ...LEASE_TOOLS,
11904
+ ...BIDI_BROWSER_TOOLS,
11162
11905
  extract_page: extractPage
11163
11906
  };
11164
11907
 
@@ -11394,7 +12137,7 @@ var TOOL_DOCS = {
11394
12137
  }
11395
12138
  },
11396
12139
  click: {
11397
- description: "Click an element via a synthetic mouse press/release at its scrolled-into-view center. Give exactly one of uid or selector. modifiers (Alt/Control/Meta/Shift) throws on the Firefox backend — use --browser chrome for a modifier-click. clickCount:3 triple-clicks (selects a line/paragraph in most editors).",
12140
+ description: 'Click an element via a synthetic mouse press/release at its scrolled-into-view center. Give exactly one of uid or selector. modifiers (Alt/Control/Meta/Shift) throws on the Firefox backend — use --browser chrome for a modifier-click. clickCount:3 triple-clicks (selects a line/paragraph in most editors). Returns {clicked,element,x,y}; element names what was hit, snapshot-style (button "Save"), read before the click and omitted if it cannot be read.',
11398
12141
  params: {
11399
12142
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11400
12143
  target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
@@ -11440,7 +12183,7 @@ var TOOL_DOCS = {
11440
12183
  }
11441
12184
  },
11442
12185
  dispatch_mouse: {
11443
- description: "Dispatches one raw mouse event (move/down/up) at absolute viewport coordinates — the toolkit's lowest-level input primitive. Compose move/down/move/up calls yourself for anything click/drag's fixed sequences can't reach: canvas drag-painting, marquee/rubber-band selection, custom hit-testing widgets. Chrome-only: absent from tools/list under the Firefox backend, never present-and-throwing.",
12186
+ description: "Dispatches one raw mouse event (move/down/up) at absolute viewport coordinates — the toolkit's lowest-level input primitive. Compose move/down/move/up calls yourself for anything click/drag's fixed sequences can't reach: canvas drag-painting, marquee/rubber-band selection, custom hit-testing widgets. Works on Chrome and on Firefox 160 or newer (WebDriver BiDi: a press held by 'down' in one call is released by 'up' in a later call); an older Firefox gets an unsupported error naming the version.",
11444
12187
  params: {
11445
12188
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11446
12189
  target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
@@ -11448,7 +12191,7 @@ var TOOL_DOCS = {
11448
12191
  x: "Viewport x-coordinate. Required every call — CDP has no 'current pointer position' to default from.",
11449
12192
  y: "Viewport y-coordinate. Required every call.",
11450
12193
  button: "Mouse button: 'left' (default), 'right', or 'middle'.",
11451
- clickCount: "Click-run length for a 'down' or 'up' event (2 = second half of a double-click, 3 = triple-click). Ignored for 'move'; defaults to 1.",
12194
+ clickCount: "Click-run length for a 'down' or 'up' event (2 = second half of a double-click, 3 = triple-click). Ignored for 'move'; defaults to 1. Ignored on Firefox (click counts follow native timing).",
11452
12195
  modifiers: "Modifier keys held for this one event, e.g. ['Shift']."
11453
12196
  }
11454
12197
  },
@@ -11473,7 +12216,7 @@ var TOOL_DOCS = {
11473
12216
  }
11474
12217
  },
11475
12218
  wait_for_download: {
11476
- description: "Wait for a file download to finish and return it as a real file on disk: {path,suggestedFilename,bytes,url,target}, written under the artifact dir's downloads/. ORDERING RULE, not optional: capture must be ARMED BEFORE the click that starts the download — call wait_for_download{arm:true} first (returns {armed:true,downloadPath,pending}), then click, then call again to collect the file. The download-behavior override is per-connection state Chrome REVERTS the moment the arming client disconnects, and an unarmed headless Chrome denies the download outright, so one triggered before arming is lost. SIDE EFFECT, browser-global: arming redirects EVERY download in this browser (all tabs, all origins) into the toolkit's downloads dir until this server exits — they no longer land in the user's normal Downloads folder. The arm lives on a connection this server holds open (an MCP-server capability): under the one-shot CLI the connection dies with the process and nothing is captured. Chrome-only (capability 'browser.downloads'): absent from tools/list under Firefox.",
12219
+ description: "Wait for a file download to finish and return it as a real file on disk: {path,suggestedFilename,bytes,url,target}, written under the artifact dir's downloads/. ORDERING RULE, not optional: capture must be ARMED BEFORE the click that starts the download — call wait_for_download{arm:true} first (returns {armed:true,downloadPath,pending}), then click, then call again to collect the file. The download-behavior override is per-connection state Chrome REVERTS the moment the arming client disconnects, and an unarmed headless Chrome denies the download outright, so one triggered before arming is lost. SIDE EFFECT, browser-global: arming redirects EVERY download in this browser (all tabs, all origins) into the toolkit's downloads dir until this server exits — they no longer land in the user's normal Downloads folder. The arm lives on a connection this server holds open (an MCP-server capability): under the one-shot CLI the connection dies with the process and nothing is captured. Capability 'browser.downloads': Chrome, and Firefox 160+ (an older Firefox is refused as unsupported). FIREFOX DIFFERS: every call arms, and a collecting call (no arm:true) RESTORES Firefox's normal download behavior when it returns or times out, so arm again before every later download.",
11477
12220
  params: {
11478
12221
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11479
12222
  target: "Names the tab for the lease check and the echoed target — a download is browser-scoped, so this does not pick which download is returned. Grammar: server instructions.",
@@ -11482,7 +12225,7 @@ var TOOL_DOCS = {
11482
12225
  }
11483
12226
  },
11484
12227
  grant_permissions: {
11485
- description: "Grant browser permissions for an origin up front, so a page asking for geolocation / notifications / clipboard gets an answer instead of a prompt no agent can click. 'permissions' takes CDP PermissionType values ('geolocation','notifications','clipboardReadWrite','camera',...); an unknown name is refused by Chrome, quoting the bad value. Returns {granted,origin,target}, or {reset:true,target} for a reset-only call. Grants are keyed by ORIGIN, not by tab: every tab on that origin is affected, including ones opened later. reset:true clears this server's previous grants first (or instead, when no permissions are given) — CDP's reset is not origin-scoped, so it clears them for every origin at once. The grant lives on a connection this server holds open and Chrome DISCARDS IT when that connection closes: an MCP-server capability, so under the one-shot CLI the grant dies with the process. Chrome-only (capability 'browser.permissions'): absent from tools/list under Firefox, never present-and-throwing.",
12228
+ description: "Grant browser permissions for an origin up front, so a page asking for geolocation / notifications / clipboard gets an answer instead of a prompt no agent can click. 'permissions' takes CDP PermissionType values ('geolocation','notifications','clipboardReadWrite','camera',...); an unknown name is refused by Chrome, quoting the bad value. Returns {granted,origin,target}, or {reset:true,target} for a reset-only call. Grants are keyed by ORIGIN, not by tab: every tab on that origin is affected, including ones opened later. reset:true clears this server's previous grants first (or instead, when no permissions are given) — CDP's reset is not origin-scoped, so it clears them for every origin at once. The grant lives on a connection this server holds open and Chrome DISCARDS IT when that connection closes: an MCP-server capability, so under the one-shot CLI the grant dies with the process. Capability 'browser.permissions': Chrome, and Firefox 160+ (an older Firefox is refused as unsupported). FIREFOX DIFFERS: only geolocation, notifications, audioCapture, videoCapture, durableStorage, midi, midiSysex, wakeLockScreen map to a Firefox permission (any other name, e.g. clipboardReadWrite, is refused as unsupported); Firefox stores grants in the profile, so this server undoes them on reset:true and at shutdown (back to the state the page reported before the grant, or 'prompt' for another origin).",
11486
12229
  params: {
11487
12230
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11488
12231
  target: "Also the origin source when 'origin' is omitted. Grammar: server instructions.",
@@ -11492,7 +12235,7 @@ var TOOL_DOCS = {
11492
12235
  }
11493
12236
  },
11494
12237
  fill: {
11495
- description: "Fills an element by focusing it, clearing existing content, then inserting value via Input.insertText (atomic paste-like commit, not per-character keystrokes — won't fire per-keypress handlers). Give exactly one of uid or selector.",
12238
+ description: `Fills an element by focusing it, clearing existing content, then inserting value via Input.insertText (atomic paste-like commit, not per-character keystrokes — won't fire per-keypress handlers). Give exactly one of uid or selector. Returns {filled,element,value}; element names the field (textbox "Email").`,
11496
12239
  params: {
11497
12240
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11498
12241
  target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
@@ -11546,7 +12289,7 @@ var TOOL_DOCS = {
11546
12289
  format: "Image format, default png. quality applies only to jpeg.",
11547
12290
  quality: "JPEG quality 0-100, default 80; ignored for png.",
11548
12291
  fullPage: "Capture the full scrollable height (via Page.getLayoutMetrics), not just the viewport.",
11549
- scale: "Output-pixel multiplier for this capture only (0<scale<=8, default 1): output px = ceil(css px x scale x devicePixelRatio); the page is never told anything changed. Chrome only (screenshot.scale) — Firefox BiDi has no scale param, use emulate{deviceScaleFactor} then scale:1. A projection over 16384 device px/side is refused up front, naming the largest scale that fits.",
12292
+ scale: "Output-pixel multiplier for this capture only (0<scale<=8, default 1): output px = ceil(css px x scale x devicePixelRatio); the page is never told anything changed. Needs capability screenshot.scale: Chrome, and Firefox 160 or newer (an older Firefox: emulate{deviceScaleFactor} then scale:1). A projection over 16384 device px/side is refused up front, naming the largest scale that fits.",
11550
12293
  renderWidth: "Emulates this viewport width (CSS px, 1-16384) for one capture, then restores it. Required with renderHeight. Unlike scale, this changes what the page believes (media queries re-flow) — e.g. capture a responsive page at 1920x1080 from a differently-sized tab. Restore only works for an override this toolkit itself set; check result.renderRestored (false = still emulated, fix via emulate). Works on both backends (capability screenshot.renderSize).",
11551
12294
  renderHeight: "Emulates this viewport height (CSS px, 1-16384) for one capture. Required with renderWidth — a viewport is two numbers. A narrow renderWidth often reflows pages TALLER, which is the usual way a render-size capture trips the 16384px encode limit.",
11552
12295
  tile: "Whether to allow vertical-band stitching: omitted=AUTO (band only if a single shot wouldn't fit), false=never band (refuse instead), true=always band (Chrome-only capability). Banded output is PNG-only, can't returnBase64, and only bands on HEIGHT (oversized WIDTH is refused, not split). Bands are a faithful crop, but lazy/virtualized content the real viewport never scrolled to renders blank.",
@@ -11880,7 +12623,7 @@ function toolAnnotations(name) {
11880
12623
  }
11881
12624
 
11882
12625
  // src/version.ts
11883
- var VERSION = "3.1.0";
12626
+ var VERSION = "3.3.0";
11884
12627
 
11885
12628
  // src/mcp.ts
11886
12629
  function isDirectRun() {