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/cli.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
  }
@@ -4049,6 +4472,7 @@ var init_driver2 = __esm(() => {
4049
4472
 
4050
4473
  // src/cdp/driver.ts
4051
4474
  init_client();
4475
+ init_session();
4052
4476
  init_leases();
4053
4477
  init_endpoints();
4054
4478
  init_activity();
@@ -4512,6 +4936,7 @@ var CDP_CAPABILITIES = new Set([
4512
4936
  "locate.xpath",
4513
4937
  "capture.screencast",
4514
4938
  "input.raw",
4939
+ "input.modifierClick",
4515
4940
  "input.html5Drag",
4516
4941
  "emulate.focus",
4517
4942
  "browser.downloads",
@@ -5136,9 +5561,17 @@ function beaconKey(targetId) {
5136
5561
  const backend = chromeLeaseBackend(currentEndpoint());
5137
5562
  return backend === "chrome" ? targetId : `${backend}\x00${targetId}`;
5138
5563
  }
5139
- async function targetWsUrl(targetId) {
5564
+ async function openTargetConn(targetId, opts = {}) {
5140
5565
  const hit = (await listTargets()).find((t) => t.id === targetId);
5141
- return hit?.webSocketDebuggerUrl;
5566
+ if (!hit)
5567
+ return;
5568
+ if (!hit.webSocketDebuggerUrl)
5569
+ return openSession(targetId, opts).catch(() => {
5570
+ return;
5571
+ });
5572
+ return new CdpConnection(hit.webSocketDebuggerUrl, opts).connect().catch(() => {
5573
+ return;
5574
+ });
5142
5575
  }
5143
5576
  async function readBeaconOver(conn) {
5144
5577
  try {
@@ -5263,12 +5696,7 @@ class CdpBrowserDriver {
5263
5696
  return true;
5264
5697
  beaconSessions.drop(key);
5265
5698
  }
5266
- const wsUrl = await targetWsUrl(targetId).catch(() => {
5267
- return;
5268
- });
5269
- if (!wsUrl)
5270
- return false;
5271
- const conn = await new CdpConnection(wsUrl).connect().catch(() => {
5699
+ const conn = await openTargetConn(targetId).catch(() => {
5272
5700
  return;
5273
5701
  });
5274
5702
  if (!conn)
@@ -5293,12 +5721,7 @@ class CdpBrowserDriver {
5293
5721
  return value;
5294
5722
  beaconSessions.drop(key);
5295
5723
  }
5296
- const wsUrl = await targetWsUrl(targetId).catch(() => {
5297
- return;
5298
- });
5299
- if (!wsUrl)
5300
- return null;
5301
- const conn = await new CdpConnection(wsUrl).connect().catch(() => {
5724
+ const conn = await openTargetConn(targetId).catch(() => {
5302
5725
  return;
5303
5726
  });
5304
5727
  if (!conn)
@@ -5313,17 +5736,11 @@ class CdpBrowserDriver {
5313
5736
  const held = beaconSessions.get(beaconKey(targetId));
5314
5737
  if (held)
5315
5738
  return probeOver(held, timeoutMs);
5316
- const wsUrl = await targetWsUrl(targetId).catch(() => {
5739
+ const conn = await openTargetConn(targetId, { timeoutMs }).catch(() => {
5317
5740
  return;
5318
5741
  });
5319
- if (!wsUrl)
5320
- return { responsive: false, beaconTs: null };
5321
- const conn = new CdpConnection(wsUrl, { timeoutMs });
5322
- try {
5323
- await conn.connect();
5324
- } catch {
5742
+ if (!conn)
5325
5743
  return { responsive: false, beaconTs: null };
5326
- }
5327
5744
  try {
5328
5745
  return await probeOver(conn, timeoutMs);
5329
5746
  } finally {
@@ -5399,7 +5816,7 @@ async function reapStaleAgentTabs(driver, backend) {
5399
5816
  // src/shared-tools.ts
5400
5817
  init_driver();
5401
5818
  import { mkdir as mkdir5, writeFile as writeFile4 } from "node:fs/promises";
5402
- import { dirname as dirname2, join as join4 } from "node:path";
5819
+ import { dirname as dirname2, join as join5 } from "node:path";
5403
5820
 
5404
5821
  // src/png.ts
5405
5822
  import { once } from "node:events";
@@ -6104,7 +6521,7 @@ async function closePage(driver, args) {
6104
6521
  }
6105
6522
  async function writeSelectedFile(id) {
6106
6523
  await mkdir5(STATE_DIR, { recursive: true });
6107
- await writeFile4(join4(STATE_DIR, "selected"), id, "utf8");
6524
+ await writeFile4(join5(STATE_DIR, "selected"), id, "utf8");
6108
6525
  }
6109
6526
  async function selectPage(driver, args) {
6110
6527
  if (args.target === undefined || args.target === "")
@@ -6168,7 +6585,7 @@ function serializeForSink(value) {
6168
6585
  return json ?? "null";
6169
6586
  }
6170
6587
  async function writeJsonSink(savePath, value) {
6171
- const path = savePath.startsWith("/") ? savePath : join4(ARTIFACT_DIR, savePath);
6588
+ const path = savePath.startsWith("/") ? savePath : join5(ARTIFACT_DIR, savePath);
6172
6589
  await mkdir5(dirname2(path), { recursive: true });
6173
6590
  const json = serializeForSink(value);
6174
6591
  await writeFile4(path, json, "utf8");
@@ -6312,10 +6729,45 @@ async function takeSnapshot(driver, args = {}) {
6312
6729
  `), target: target3(page.info), nodeCount: nodes.length };
6313
6730
  });
6314
6731
  }
6732
+ function describeElementSource() {
6733
+ return `function() {
6734
+ var MAX_NAME_LENGTH = ${MAX_NAME_LENGTH};
6735
+ ${ACCNAME_HELPERS_SOURCE}
6736
+ var el = this;
6737
+ if (!el || el.nodeType !== 1) return null;
6738
+ var role = implicitRole(el);
6739
+ var name = accessibleName(el, !!CONTENT_NAMED_ROLES[role]);
6740
+ if (!name) name = truncate(el.innerText || el.textContent || "");
6741
+ return (role || el.tagName.toLowerCase()) + (name ? " " + JSON.stringify(name) : "");
6742
+ }`;
6743
+ }
6744
+ var DESCRIBE_TIMEOUT_MS = 2000;
6745
+ async function describeElement(page, loc) {
6746
+ let timer;
6747
+ try {
6748
+ const timeout = new Promise((r) => {
6749
+ timer = setTimeout(() => r(undefined), DESCRIBE_TIMEOUT_MS);
6750
+ });
6751
+ const desc = await Promise.race([page.callOnElement(loc, describeElementSource()), timeout]);
6752
+ return typeof desc === "string" && desc.length > 0 ? desc : undefined;
6753
+ } catch {
6754
+ return;
6755
+ } finally {
6756
+ clearTimeout(timer);
6757
+ }
6758
+ }
6759
+ function isElementLocator(d) {
6760
+ return !("x" in d) && !("dx" in d);
6761
+ }
6762
+ function elementField(element) {
6763
+ return element === undefined ? {} : { element };
6764
+ }
6315
6765
  async function click(driver, args) {
6766
+ const loc = locatorOf(args);
6316
6767
  return withPage2(driver, args.target, async (page) => {
6317
- const { x, y } = await page.click(locatorOf(args), { button: args.button ?? "left", clickCount: args.clickCount ?? 1, modifiers: args.modifiers });
6318
- return { clicked: true, x, y };
6768
+ const element = await describeElement(page, loc);
6769
+ const { x, y } = await page.click(loc, { button: args.button ?? "left", clickCount: args.clickCount ?? 1, modifiers: args.modifiers });
6770
+ return { clicked: true, ...elementField(element), x, y };
6319
6771
  });
6320
6772
  }
6321
6773
  function resolveScrollAnchor(args) {
@@ -6351,9 +6803,11 @@ async function scroll(driver, args) {
6351
6803
  });
6352
6804
  }
6353
6805
  async function hover(driver, args) {
6806
+ const loc = locatorOf(args);
6354
6807
  return withPage2(driver, args.target, async (page) => {
6355
- const { x, y } = await page.hover(locatorOf(args));
6356
- return { hovered: true, x, y };
6808
+ const element = await describeElement(page, loc);
6809
+ const { x, y } = await page.hover(loc);
6810
+ return { hovered: true, ...elementField(element), x, y };
6357
6811
  });
6358
6812
  }
6359
6813
  function resolveDragTo(to) {
@@ -6419,16 +6873,29 @@ async function drag(driver, args) {
6419
6873
  const steps = resolveDragSteps(args.steps);
6420
6874
  const mode = resolveDragMode(args.mode, driver.capabilities);
6421
6875
  return withPage2(driver, args.target, async (page) => {
6422
- const { from, to } = await page.drag(locatorOf(args.from), destination, { mode, steps });
6423
- return { dragged: true, mode, steps, from, to };
6876
+ const fromLoc = locatorOf(args.from);
6877
+ const element = await describeElement(page, fromLoc);
6878
+ const targetElement = isElementLocator(destination) ? await describeElement(page, destination) : undefined;
6879
+ const { from, to } = await page.drag(fromLoc, destination, { mode, steps });
6880
+ return {
6881
+ dragged: true,
6882
+ ...elementField(element),
6883
+ ...targetElement === undefined ? {} : { target_element: targetElement },
6884
+ mode,
6885
+ steps,
6886
+ from,
6887
+ to
6888
+ };
6424
6889
  });
6425
6890
  }
6426
6891
  async function fill(driver, args) {
6427
6892
  if (typeof args.value !== "string")
6428
6893
  throw new SharedToolError("fill requires a string { value }");
6894
+ const loc = locatorOf(args);
6429
6895
  return withPage2(driver, args.target, async (page) => {
6430
- await page.setValue(locatorOf(args), args.value);
6431
- return { filled: true, value: args.value };
6896
+ const element = await describeElement(page, loc);
6897
+ await page.setValue(loc, args.value);
6898
+ return { filled: true, ...elementField(element), value: args.value };
6432
6899
  });
6433
6900
  }
6434
6901
  async function fillForm(driver, args) {
@@ -6436,21 +6903,26 @@ async function fillForm(driver, args) {
6436
6903
  throw new SharedToolError("fill_form requires a non-empty { fields } array");
6437
6904
  return withPage2(driver, args.target, async (page) => {
6438
6905
  let filled = 0;
6906
+ const elements = [];
6439
6907
  for (const f of args.fields) {
6440
6908
  if (typeof f.value !== "string")
6441
6909
  throw new SharedToolError("each fill_form field requires a string value");
6442
- await page.setValue(locatorOf(f), f.value);
6910
+ const loc = locatorOf(f);
6911
+ elements.push(await describeElement(page, loc) ?? null);
6912
+ await page.setValue(loc, f.value);
6443
6913
  filled++;
6444
6914
  }
6445
- return { filled, fields: args.fields.length };
6915
+ return { filled, fields: args.fields.length, elements };
6446
6916
  });
6447
6917
  }
6448
6918
  async function typeText(driver, args) {
6449
6919
  if (typeof args.text !== "string")
6450
6920
  throw new SharedToolError("type_text requires a string { text }");
6921
+ const loc = locatorOf(args);
6451
6922
  return withPage2(driver, args.target, async (page) => {
6452
- await page.typeText(locatorOf(args), args.text);
6453
- return { typed: true, text: args.text };
6923
+ const element = await describeElement(page, loc);
6924
+ await page.typeText(loc, args.text);
6925
+ return { typed: true, ...elementField(element), text: args.text };
6454
6926
  });
6455
6927
  }
6456
6928
  async function pressKey(driver, args) {
@@ -6468,8 +6940,10 @@ async function uploadFile(driver, args) {
6468
6940
  throw new SharedToolError("upload_file requires { files } as a non-empty path or array of paths");
6469
6941
  }
6470
6942
  return withPage2(driver, args.target, async (page) => {
6471
- await page.setFiles(locatorOf(args), files);
6472
- return { uploaded: files };
6943
+ const loc = locatorOf(args);
6944
+ const element = await describeElement(page, loc);
6945
+ await page.setFiles(loc, files);
6946
+ return { uploaded: files, ...elementField(element) };
6473
6947
  });
6474
6948
  }
6475
6949
  function stamp() {
@@ -6483,7 +6957,7 @@ function resolveScreenshotScale(scale, capabilities) {
6483
6957
  throw new SharedToolError(`take_screenshot: 'scale' must be a finite number greater than 0 and at most ${MAX_SCREENSHOT_SCALE} (default 1)`);
6484
6958
  }
6485
6959
  if (scale !== 1 && !capabilities.has("screenshot.scale")) {
6486
- 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.`);
6960
+ 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.`);
6487
6961
  }
6488
6962
  return scale;
6489
6963
  }
@@ -6583,7 +7057,7 @@ async function takeScreenshot(driver, args = {}) {
6583
7057
  return withPage2(driver, args.target, async (page) => {
6584
7058
  const clip = args.uid !== undefined || args.selector ? locatorOf(args) : undefined;
6585
7059
  const ext = format === "jpeg" ? "jpg" : "png";
6586
- const path = args.savePath ?? join4(ARTIFACT_DIR, `screenshot-${page.info.id.slice(0, 8)}-${stamp()}.${ext}`);
7060
+ const path = args.savePath ?? join5(ARTIFACT_DIR, `screenshot-${page.info.id.slice(0, 8)}-${stamp()}.${ext}`);
6587
7061
  const stitch = async (banded) => {
6588
7062
  if (format !== "png")
6589
7063
  throw tiledCaptureRefusal("format", banded);
@@ -6808,7 +7282,7 @@ var LEASE_TOOLS = {
6808
7282
 
6809
7283
  // src/tools/console.ts
6810
7284
  init_client();
6811
- import { readFile as readFile4 } from "node:fs/promises";
7285
+ import { readFile as readFile5 } from "node:fs/promises";
6812
7286
 
6813
7287
  // src/tools/recorder.ts
6814
7288
  init_client();
@@ -7011,7 +7485,7 @@ function lineToEntry(line, index) {
7011
7485
  async function readConsoleEntries(file) {
7012
7486
  let raw;
7013
7487
  try {
7014
- raw = await readFile4(file, "utf8");
7488
+ raw = await readFile5(file, "utf8");
7015
7489
  } catch {
7016
7490
  return [];
7017
7491
  }
@@ -7069,7 +7543,7 @@ async function getConsoleMessage(args = {}) {
7069
7543
 
7070
7544
  // src/tools/network.ts
7071
7545
  init_client();
7072
- import { readFile as readFile5 } from "node:fs/promises";
7546
+ import { readFile as readFile6 } from "node:fs/promises";
7073
7547
  var DEFAULT_CAPTURE_MS2 = 2500;
7074
7548
  function asHeaders(v) {
7075
7549
  if (!v || typeof v !== "object")
@@ -7136,7 +7610,7 @@ function correlate(lines) {
7136
7610
  async function readNetworkRequests(file) {
7137
7611
  let raw;
7138
7612
  try {
7139
- raw = await readFile5(file, "utf8");
7613
+ raw = await readFile6(file, "utf8");
7140
7614
  } catch {
7141
7615
  return [];
7142
7616
  }
@@ -7221,8 +7695,8 @@ async function getNetworkRequest(args = {}) {
7221
7695
 
7222
7696
  // src/tools/performance.ts
7223
7697
  init_client();
7224
- import { mkdir as mkdir7, readFile as readFile6, writeFile as writeFile6, stat, unlink as unlink4 } from "node:fs/promises";
7225
- import { join as join5 } from "node:path";
7698
+ import { mkdir as mkdir7, readFile as readFile7, writeFile as writeFile6, stat, unlink as unlink4 } from "node:fs/promises";
7699
+ import { join as join6 } from "node:path";
7226
7700
  var ARTIFACT_DIR2 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
7227
7701
  var STATE_DIR2 = process.env.CDP_STATE_DIR ?? "/tmp/cdp-toolkit";
7228
7702
  var DEFAULT_CATEGORIES = [
@@ -7240,7 +7714,7 @@ function shortId(id) {
7240
7714
  return id.slice(0, 8);
7241
7715
  }
7242
7716
  function stateFilePath() {
7243
- return join5(STATE_DIR2, "trace-state.json");
7717
+ return join6(STATE_DIR2, "trace-state.json");
7244
7718
  }
7245
7719
  function bufferTraceData(conn, sink) {
7246
7720
  return conn.on("Tracing.dataCollected", (params) => {
@@ -7263,7 +7737,7 @@ async function endTrace(conn, sink, timeoutMs = 30000) {
7263
7737
  }
7264
7738
  async function writeTrace(events, targetId) {
7265
7739
  await mkdir7(ARTIFACT_DIR2, { recursive: true });
7266
- const path = join5(ARTIFACT_DIR2, `trace-${shortId(targetId)}-${stamp2()}.json`);
7740
+ const path = join6(ARTIFACT_DIR2, `trace-${shortId(targetId)}-${stamp2()}.json`);
7267
7741
  const body = JSON.stringify({ traceEvents: events, metadata: { source: "cdp-toolkit" } });
7268
7742
  await writeFile6(path, body, "utf8");
7269
7743
  const { size } = await stat(path);
@@ -7306,7 +7780,7 @@ async function performanceStopTrace(args = {}) {
7306
7780
  if (!entry) {
7307
7781
  let hint = "";
7308
7782
  try {
7309
- const raw = await readFile6(stateFilePath(), "utf8");
7783
+ const raw = await readFile7(stateFilePath(), "utf8");
7310
7784
  const state = JSON.parse(raw);
7311
7785
  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)`;
7312
7786
  } catch {}
@@ -7436,7 +7910,7 @@ async function performanceAnalyzeInsight(args = {}) {
7436
7910
  }
7437
7911
  let raw;
7438
7912
  try {
7439
- raw = await readFile6(args.tracePath, "utf8");
7913
+ raw = await readFile7(args.tracePath, "utf8");
7440
7914
  } catch (err) {
7441
7915
  throw new CdpError(`cannot read trace file '${args.tracePath}': ${err.message}`);
7442
7916
  }
@@ -7456,7 +7930,7 @@ async function performanceAnalyzeInsight(args = {}) {
7456
7930
  init_client();
7457
7931
  import { spawn } from "node:child_process";
7458
7932
  import { mkdir as mkdir8, rm as rm2, stat as stat2, writeFile as writeFile7 } from "node:fs/promises";
7459
- import { join as join6 } from "node:path";
7933
+ import { join as join7 } from "node:path";
7460
7934
  var ARTIFACT_DIR3 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
7461
7935
  var FFMPEG_BIN = process.env.CDP_FFMPEG ?? "ffmpeg";
7462
7936
  function frameDurationsMs(ledger, stopWallclockMs) {
@@ -7572,6 +8046,22 @@ function selectEncoder(encodersOutput) {
7572
8046
  }
7573
8047
  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).");
7574
8048
  }
8049
+ function supportsFpsMode(versionOutput) {
8050
+ const m = /ffmpeg version n?(\d+)\.(\d+)/.exec(versionOutput);
8051
+ if (!m)
8052
+ return /ffmpeg version N-/.test(versionOutput) ? true : undefined;
8053
+ const major = Number(m[1]);
8054
+ const minor = Number(m[2]);
8055
+ return major > 5 || major === 5 && minor >= 1;
8056
+ }
8057
+ function chooseFpsMode(versionOutput, helpOutput) {
8058
+ const byVersion = versionOutput === undefined ? undefined : supportsFpsMode(versionOutput);
8059
+ if (byVersion !== undefined)
8060
+ return byVersion;
8061
+ if (helpOutput !== undefined && /-vsync\b|-fps_mode\b/.test(helpOutput))
8062
+ return /-fps_mode\b/.test(helpOutput);
8063
+ return true;
8064
+ }
7575
8065
  function buildFfmpegArgs(manifestPath, outPath, choice) {
7576
8066
  return [
7577
8067
  "-hide_banner",
@@ -7584,8 +8074,7 @@ function buildFfmpegArgs(manifestPath, outPath, choice) {
7584
8074
  "0",
7585
8075
  "-i",
7586
8076
  manifestPath,
7587
- "-vsync",
7588
- "vfr",
8077
+ ...choice.fpsMode ? ["-fps_mode", "vfr"] : ["-vsync", "vfr"],
7589
8078
  "-vf",
7590
8079
  "scale=trunc(iw/2)*2:trunc(ih/2)*2",
7591
8080
  "-c:v",
@@ -7627,8 +8116,19 @@ async function probeEncoder() {
7627
8116
  }
7628
8117
  if (res.code !== 0)
7629
8118
  throw new CdpError(`${FFMPEG_MISSING} ('-encoders' exited ${res.code}: ${res.stderr.trim().slice(0, 300)})`);
7630
- return selectEncoder(`${res.stdout}
8119
+ const choice = selectEncoder(`${res.stdout}
7631
8120
  ${res.stderr}`);
8121
+ const output = async (args) => {
8122
+ const r = await run(FFMPEG_BIN, args).catch(() => {
8123
+ return;
8124
+ });
8125
+ return r && r.code === 0 ? `${r.stdout}
8126
+ ${r.stderr}` : undefined;
8127
+ };
8128
+ const version = await output(["-version"]);
8129
+ const byVersion = version === undefined ? undefined : supportsFpsMode(version);
8130
+ const help = byVersion === undefined ? await output(["-hide_banner", "-h", "full"]) : undefined;
8131
+ return { ...choice, fpsMode: chooseFpsMode(version, help) };
7632
8132
  })();
7633
8133
  encoderProbe.catch(() => {
7634
8134
  encoderProbe = undefined;
@@ -7677,7 +8177,7 @@ async function startScreenRecording(args = {}) {
7677
8177
  conn.close();
7678
8178
  throw err;
7679
8179
  }
7680
- const spoolDir = join6(ARTIFACT_DIR3, `screencast-${shortId2(target.id)}-${stamp3()}`);
8180
+ const spoolDir = join7(ARTIFACT_DIR3, `screencast-${shortId2(target.id)}-${stamp3()}`);
7681
8181
  try {
7682
8182
  await mkdir8(spoolDir, { recursive: true });
7683
8183
  } catch (err) {
@@ -7720,7 +8220,7 @@ async function startScreenRecording(args = {}) {
7720
8220
  seq += 1;
7721
8221
  const file = `frame-${String(seq).padStart(6, "0")}.${ext}`;
7722
8222
  rec.ledger.push({ file, timestamp, width: size.width, height: size.height });
7723
- rec.writes = rec.writes.then(() => writeFile7(join6(spoolDir, file), buf)).catch(() => {
8223
+ rec.writes = rec.writes.then(() => writeFile7(join7(spoolDir, file), buf)).catch(() => {
7724
8224
  rec.dropped += 1;
7725
8225
  rec.unwritten.add(file);
7726
8226
  });
@@ -7784,9 +8284,9 @@ async function stopScreenRecording(args = {}) {
7784
8284
  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.`);
7785
8285
  }
7786
8286
  await mkdir8(ARTIFACT_DIR3, { recursive: true });
7787
- const outPath = args.savePath ?? join6(ARTIFACT_DIR3, `screen-recording-${shortId2(rec.target.id)}-${stamp3()}.mp4`);
8287
+ const outPath = args.savePath ?? join7(ARTIFACT_DIR3, `screen-recording-${shortId2(rec.target.id)}-${stamp3()}.mp4`);
7788
8288
  const frames = coalesceToConcatGrid(ledger, stoppedAt);
7789
- const manifestPath = join6(rec.spoolDir, "frames.ffconcat");
8289
+ const manifestPath = join7(rec.spoolDir, "frames.ffconcat");
7790
8290
  await writeFile7(manifestPath, buildConcatManifest(frames), "utf8");
7791
8291
  const durationMs = frames.reduce((total, f) => total + f.durationMs, 0);
7792
8292
  const { width, height } = evenDimensions(ledger[0].width, ledger[0].height);
@@ -7820,7 +8320,7 @@ ffmpeg said: ${res.stderr.trim().slice(0, 800)}`);
7820
8320
  // src/tools/heap.ts
7821
8321
  init_client();
7822
8322
  import { mkdir as mkdir9, writeFile as writeFile8 } from "node:fs/promises";
7823
- import { join as join7 } from "node:path";
8323
+ import { join as join8 } from "node:path";
7824
8324
  var ARTIFACT_DIR4 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
7825
8325
  function stamp4(targetId) {
7826
8326
  const short = targetId.slice(0, 8);
@@ -7846,7 +8346,7 @@ async function takeHeapsnapshot(args = {}) {
7846
8346
  throw new Error("HeapProfiler.takeHeapSnapshot produced no chunks");
7847
8347
  }
7848
8348
  await mkdir9(ARTIFACT_DIR4, { recursive: true });
7849
- const path = args.savePath ? args.savePath.startsWith("/") ? args.savePath : join7(ARTIFACT_DIR4, args.savePath) : join7(ARTIFACT_DIR4, `take_heapsnapshot-${stamp4(target.id)}.heapsnapshot`);
8349
+ const path = args.savePath ? args.savePath.startsWith("/") ? args.savePath : join8(ARTIFACT_DIR4, args.savePath) : join8(ARTIFACT_DIR4, `take_heapsnapshot-${stamp4(target.id)}.heapsnapshot`);
7850
8350
  await writeFile8(path, snapshot, "utf8");
7851
8351
  const bytes = Buffer.byteLength(snapshot, "utf8");
7852
8352
  return {
@@ -7862,7 +8362,7 @@ async function takeHeapsnapshot(args = {}) {
7862
8362
  init_client();
7863
8363
  init_endpoints();
7864
8364
  import { spawn as spawn2 } from "node:child_process";
7865
- import { mkdir as mkdir10, readFile as readFile7, stat as stat3 } from "node:fs/promises";
8365
+ import { mkdir as mkdir10, readFile as readFile8, stat as stat3 } from "node:fs/promises";
7866
8366
  var ARTIFACT_DIR5 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
7867
8367
  function cdpPort() {
7868
8368
  const base = currentEndpoint().base;
@@ -7952,7 +8452,7 @@ async function lighthouseAudit(args) {
7952
8452
  }
7953
8453
  let raw;
7954
8454
  try {
7955
- raw = await readFile7(outPath, "utf8");
8455
+ raw = await readFile8(outPath, "utf8");
7956
8456
  } catch {
7957
8457
  raw = undefined;
7958
8458
  }
@@ -8142,15 +8642,15 @@ async function clickFocusGated(args) {
8142
8642
  // src/tools/downloads.ts
8143
8643
  init_client();
8144
8644
  import { readdir as readdir3, rename as rename2, stat as stat4 } from "node:fs/promises";
8145
- import { basename, extname, join as join9 } from "node:path";
8645
+ import { basename, extname, join as join10 } from "node:path";
8146
8646
 
8147
8647
  // src/tools/browser-session.ts
8148
8648
  init_client();
8149
8649
  init_endpoints();
8150
8650
  import { mkdir as mkdir11 } from "node:fs/promises";
8151
- import { join as join8 } from "node:path";
8651
+ import { join as join9 } from "node:path";
8152
8652
  var ARTIFACT_DIR6 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
8153
- var DOWNLOADS_DIR = join8(ARTIFACT_DIR6, "downloads");
8653
+ var DOWNLOADS_DIR = join9(ARTIFACT_DIR6, "downloads");
8154
8654
  var DOWNLOAD_BUFFER_LIMIT = 50;
8155
8655
  var sessions2 = new Map;
8156
8656
  function sessionKey() {
@@ -8317,7 +8817,7 @@ async function waitForDownload(args = {}) {
8317
8817
  const taken = new Set(await readdir3(DOWNLOADS_DIR).catch(() => []));
8318
8818
  taken.delete(basename(rec.filePath));
8319
8819
  const finalName = nextFreeName(suggestedFilename, taken);
8320
- const path = join9(DOWNLOADS_DIR, finalName);
8820
+ const path = join10(DOWNLOADS_DIR, finalName);
8321
8821
  await rename2(rec.filePath, path);
8322
8822
  const bytes = (await stat4(path)).size;
8323
8823
  return { path, suggestedFilename, bytes, ...rec.url ? { url: rec.url } : {}, target };
@@ -8376,7 +8876,7 @@ async function grantPermissions(args = {}) {
8376
8876
  // src/tools/extract.ts
8377
8877
  init_client();
8378
8878
  import { mkdir as mkdir12, writeFile as writeFile9 } from "node:fs/promises";
8379
- import { dirname as dirname3, join as join10 } from "node:path";
8879
+ import { dirname as dirname3, join as join11 } from "node:path";
8380
8880
  var ARTIFACT_DIR7 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
8381
8881
  var DEFAULT_BASE_URL = "http://127.0.0.1:8090/v1";
8382
8882
  var DEFAULT_MODEL = "schematron";
@@ -8777,7 +9277,7 @@ async function extractPage(driver, args) {
8777
9277
  };
8778
9278
  if (args.savePath === undefined || args.savePath === "")
8779
9279
  return result;
8780
- const path = args.savePath.startsWith("/") ? args.savePath : join10(ARTIFACT_DIR7, args.savePath);
9280
+ const path = args.savePath.startsWith("/") ? args.savePath : join11(ARTIFACT_DIR7, args.savePath);
8781
9281
  await mkdir12(dirname3(path), { recursive: true });
8782
9282
  const json = JSON.stringify(result, null, 2);
8783
9283
  await writeFile9(path, json, "utf8");
@@ -8858,7 +9358,7 @@ import { spawn as spawn4 } from "node:child_process";
8858
9358
  import { existsSync as existsSync2, mkdtempSync, readFileSync as readFileSync2, rmSync, writeFileSync } from "node:fs";
8859
9359
  import { createConnection, createServer as createServer2 } from "node:net";
8860
9360
  import { tmpdir } from "node:os";
8861
- import { join as join12 } from "node:path";
9361
+ import { join as join13 } from "node:path";
8862
9362
  function resolveBinary() {
8863
9363
  const candidates = [
8864
9364
  process.env.FIREFOX_BIN,
@@ -8938,7 +9438,7 @@ var LAUNCH_USER_JS_PREFS = {
8938
9438
  "dom.file.createInChild": true
8939
9439
  };
8940
9440
  function writeLaunchUserJs(profilePath) {
8941
- const target = join12(profilePath, "user.js");
9441
+ const target = join13(profilePath, "user.js");
8942
9442
  const existing = existsSync2(target) ? readFileSync2(target, "utf8") : "";
8943
9443
  const present = new Set;
8944
9444
  for (const line of existing.split(`
@@ -8960,7 +9460,7 @@ async function launchFirefox(opts = {}) {
8960
9460
  const binary = resolveBinary();
8961
9461
  const port = await pickPort(opts.port);
8962
9462
  const isThrowaway = opts.profilePath === undefined;
8963
- const profilePath = opts.profilePath ?? mkdtempSync(join12(tmpdir(), "cdp-toolkit-ff-profile-"));
9463
+ const profilePath = opts.profilePath ?? mkdtempSync(join13(tmpdir(), "cdp-toolkit-ff-profile-"));
8964
9464
  if (isThrowaway)
8965
9465
  writeLaunchUserJs(profilePath);
8966
9466
  const args = ["--profile", profilePath, "--remote-debugging-port", String(port), "--no-remote"];
@@ -9160,6 +9660,16 @@ async function withPage4(driver, target, fn) {
9160
9660
  await page.release();
9161
9661
  }
9162
9662
  }
9663
+ async function dispatchMouse2(driver, args) {
9664
+ validateDispatchMouseArgs(args);
9665
+ modifierBits(args.modifiers);
9666
+ return withPage4(driver, args.target, async (page) => {
9667
+ if (!page.dispatchMouse)
9668
+ throw new BidiToolError("dispatch_mouse: this page driver has no raw mouse dispatch");
9669
+ await page.dispatchMouse({ action: args.action, x: args.x, y: args.y, button: args.button, clickCount: args.clickCount, modifiers: args.modifiers });
9670
+ return { dispatched: args.action, x: args.x, y: args.y };
9671
+ });
9672
+ }
9163
9673
  var consoleBuffers = new Map;
9164
9674
  var networkBuffers = new Map;
9165
9675
  function refuseWorkerSelector(driver, target) {
@@ -9232,6 +9742,13 @@ async function getNetworkRequest2(driver, args = {}) {
9232
9742
  return withPage4(driver, args.target, async (page) => {
9233
9743
  const buf = bufferFor(networkBuffers, page.info.id);
9234
9744
  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));
9745
+ if (args.includeBody) {
9746
+ const id = args.requestId ?? (found ? String(found.requestId ?? found.request ?? "") : "");
9747
+ if (!id)
9748
+ 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)");
9749
+ const { body, base64Encoded } = await page.getResponseBody(id);
9750
+ return { ...found ?? { requestId: id }, body, bodyBase64Encoded: base64Encoded };
9751
+ }
9235
9752
  if (!found)
9236
9753
  throw new BidiToolError("no matching network request in the current buffer; run list_network_requests first");
9237
9754
  return found;
@@ -9307,7 +9824,232 @@ var BIDI_ONLY_TOOLS = {
9307
9824
  get_network_request: getNetworkRequest2,
9308
9825
  mock_request: mockRequest2,
9309
9826
  list_mocks: listMocks2,
9310
- clear_mocks: clearMocks2
9827
+ clear_mocks: clearMocks2,
9828
+ dispatch_mouse: dispatchMouse2
9829
+ };
9830
+
9831
+ // src/bidi-browser-tools.ts
9832
+ init_driver2();
9833
+ import { mkdir as mkdir14, readdir as readdir4, realpath, rename as rename4, stat as stat5 } from "node:fs/promises";
9834
+ import { basename as basename2, dirname as dirname4, join as join14, resolve } from "node:path";
9835
+ function unsupported(message) {
9836
+ return Object.assign(new Error(message), { code: "unsupported" });
9837
+ }
9838
+ function scopeOf(driver, tool) {
9839
+ const d = driver;
9840
+ if (typeof d.withBrowserConnection !== "function" || typeof d.setDisposeHook !== "function") {
9841
+ throw unsupported(`${tool}: this driver has no browser-scoped connection (the Firefox BiDi driver does; Chrome uses src/tools/).`);
9842
+ }
9843
+ return d;
9844
+ }
9845
+ async function targetOf(driver, target) {
9846
+ const page = await driver.page(target);
9847
+ try {
9848
+ return { id: page.info.id, url: page.info.url, title: page.info.title };
9849
+ } finally {
9850
+ await page.release();
9851
+ }
9852
+ }
9853
+ var FIREFOX_DOWNLOAD_STAGING_DIR = join14(dirname4(DOWNLOADS_DIR), "downloads-firefox-staging");
9854
+ var downloadStates = new WeakMap;
9855
+ function downloadId(p) {
9856
+ const v = p.download ?? p.navigation;
9857
+ return typeof v === "string" && v.length > 0 ? v : undefined;
9858
+ }
9859
+ function deliver(s, r) {
9860
+ r.state = "completed";
9861
+ s.downloads.push(r);
9862
+ while (s.downloads.length > DOWNLOAD_BUFFER_LIMIT) {
9863
+ const i = s.downloads.findIndex((d) => d.consumed);
9864
+ s.downloads.splice(i >= 0 ? i : 0, 1);
9865
+ }
9866
+ const waiter = s.waiters.shift();
9867
+ if (waiter) {
9868
+ r.consumed = true;
9869
+ waiter(r);
9870
+ }
9871
+ }
9872
+ function downloadStateFor(conn) {
9873
+ let s = downloadStates.get(conn);
9874
+ if (s)
9875
+ return s;
9876
+ const state = { downloads: [], begun: new Map, waiters: [], stagingDirs: new Set([resolve(FIREFOX_DOWNLOAD_STAGING_DIR)]) };
9877
+ downloadStates.set(conn, state);
9878
+ conn.on("browsingContext.downloadWillBegin", (p) => {
9879
+ const id = downloadId(p);
9880
+ if (!id)
9881
+ return;
9882
+ state.begun.set(id, { id, url: p.url, suggestedFilename: p.suggestedFilename, state: "inProgress", consumed: false });
9883
+ if (state.begun.size > DOWNLOAD_BUFFER_LIMIT)
9884
+ state.begun.delete(state.begun.keys().next().value);
9885
+ });
9886
+ conn.on("browsingContext.downloadEnd", (p) => {
9887
+ const id = downloadId(p);
9888
+ if (!id)
9889
+ return;
9890
+ const rec = state.begun.get(id) ?? { id, state: "inProgress", consumed: false };
9891
+ state.begun.delete(id);
9892
+ if (p.status !== "complete" || !p.filepath)
9893
+ return;
9894
+ if (!state.stagingDirs.has(resolve(dirname4(p.filepath))))
9895
+ return;
9896
+ rec.url ??= p.url;
9897
+ const held = join14(dirname4(p.filepath), `${id.replace(/[^A-Za-z0-9-]/g, "_")}.download`);
9898
+ rename4(p.filepath, held).then(() => {
9899
+ rec.filePath = held;
9900
+ }, () => {
9901
+ rec.filePath = p.filepath ?? undefined;
9902
+ }).finally(() => deliver(state, rec));
9903
+ });
9904
+ return state;
9905
+ }
9906
+ async function armFirefoxDownloads(conn, s, scope) {
9907
+ await mkdir14(FIREFOX_DOWNLOAD_STAGING_DIR, { recursive: true });
9908
+ await mkdir14(DOWNLOADS_DIR, { recursive: true });
9909
+ s.stagingDirs.add(resolve(await realpath(FIREFOX_DOWNLOAD_STAGING_DIR)));
9910
+ scope.setDisposeHook("browser.downloads", async (c) => {
9911
+ await c.send("browser.setDownloadBehavior", { downloadBehavior: null });
9912
+ });
9913
+ await conn.send("browser.setDownloadBehavior", { downloadBehavior: { type: "allowed", destinationFolder: FIREFOX_DOWNLOAD_STAGING_DIR } });
9914
+ }
9915
+ async function disarmFirefoxDownloads(conn, scope) {
9916
+ await conn.send("browser.setDownloadBehavior", { downloadBehavior: null });
9917
+ scope.setDisposeHook("browser.downloads", undefined);
9918
+ }
9919
+ function nextFirefoxDownload(s, timeoutMs) {
9920
+ const buffered = s.downloads.find((d) => !d.consumed);
9921
+ if (buffered) {
9922
+ buffered.consumed = true;
9923
+ return Promise.resolve(buffered);
9924
+ }
9925
+ return new Promise((resolvePromise, reject) => {
9926
+ const waiter = (r) => {
9927
+ clearTimeout(timer);
9928
+ resolvePromise(r);
9929
+ };
9930
+ const timer = setTimeout(() => {
9931
+ const i = s.waiters.indexOf(waiter);
9932
+ if (i >= 0)
9933
+ s.waiters.splice(i, 1);
9934
+ 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.`));
9935
+ }, timeoutMs);
9936
+ s.waiters.push(waiter);
9937
+ });
9938
+ }
9939
+ async function waitForDownloadFirefox(driver, args = {}) {
9940
+ validateWaitForDownloadArgs(args);
9941
+ const scope = scopeOf(driver, "wait_for_download");
9942
+ const target = await targetOf(driver, args.target);
9943
+ return scope.withBrowserConnection(async (conn) => {
9944
+ requireFirefox(conn, "browser.downloads");
9945
+ const s = downloadStateFor(conn);
9946
+ await armFirefoxDownloads(conn, s, scope);
9947
+ if (args.arm === true) {
9948
+ return { armed: true, downloadPath: DOWNLOADS_DIR, pending: s.downloads.filter((d) => !d.consumed).length, target };
9949
+ }
9950
+ let rec;
9951
+ try {
9952
+ rec = await nextFirefoxDownload(s, args.timeoutMs ?? 30000);
9953
+ } finally {
9954
+ if (s.waiters.length === 0)
9955
+ await disarmFirefoxDownloads(conn, scope).catch(() => {
9956
+ return;
9957
+ });
9958
+ }
9959
+ if (!rec.filePath) {
9960
+ throw new Error(`wait_for_download: download ${rec.id} completed without a file path (nothing to return)`);
9961
+ }
9962
+ const suggestedFilename = safeFilename(rec.suggestedFilename);
9963
+ const taken = new Set(await readdir4(DOWNLOADS_DIR).catch(() => []));
9964
+ taken.delete(basename2(rec.filePath));
9965
+ const finalName = nextFreeName(suggestedFilename, taken);
9966
+ const path = join14(DOWNLOADS_DIR, finalName);
9967
+ await rename4(rec.filePath, path);
9968
+ const bytes = (await stat5(path)).size;
9969
+ return { path, suggestedFilename, bytes, ...rec.url ? { url: rec.url } : {}, target };
9970
+ });
9971
+ }
9972
+ var FIREFOX_PERMISSION_DESCRIPTORS = {
9973
+ geolocation: { name: "geolocation" },
9974
+ notifications: { name: "notifications" },
9975
+ audioCapture: { name: "microphone" },
9976
+ videoCapture: { name: "camera" },
9977
+ durableStorage: { name: "persistent-storage" },
9978
+ midi: { name: "midi" },
9979
+ midiSysex: { name: "midi", sysex: true },
9980
+ wakeLockScreen: { name: "screen-wake-lock" }
9981
+ };
9982
+ function mapFirefoxPermissions(names) {
9983
+ return names.map((n) => {
9984
+ const d = Object.hasOwn(FIREFOX_PERMISSION_DESCRIPTORS, n) ? FIREFOX_PERMISSION_DESCRIPTORS[n] : undefined;
9985
+ if (!d) {
9986
+ 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(", ")}.`);
9987
+ }
9988
+ return d;
9989
+ });
9990
+ }
9991
+ var trackedGrants = new WeakMap;
9992
+ function grantKey(origin, d) {
9993
+ return `${origin} ${JSON.stringify(d)}`;
9994
+ }
9995
+ async function restoreGrants(conn, grants) {
9996
+ const all = [...grants.values()];
9997
+ grants.clear();
9998
+ for (const g of all) {
9999
+ await conn.send("permissions.setPermission", { descriptor: g.descriptor, state: g.previous, origin: g.origin });
10000
+ }
10001
+ }
10002
+ async function queryState(page, d) {
10003
+ try {
10004
+ const v = await page.evaluate(`navigator.permissions.query(${JSON.stringify(d)}).then((p) => p.state, () => "prompt")`, { awaitPromise: true });
10005
+ return v === "granted" || v === "denied" ? v : "prompt";
10006
+ } catch {
10007
+ return "prompt";
10008
+ }
10009
+ }
10010
+ async function grantPermissionsFirefox(driver, args = {}) {
10011
+ validateGrantPermissionsArgs(args);
10012
+ const reset = args.reset === true;
10013
+ const permissions = args.permissions ?? [];
10014
+ const descriptors = mapFirefoxPermissions(permissions);
10015
+ const scope = scopeOf(driver, "grant_permissions");
10016
+ let grants = trackedGrants.get(driver);
10017
+ if (!grants) {
10018
+ grants = new Map;
10019
+ trackedGrants.set(driver, grants);
10020
+ }
10021
+ const tracked = grants;
10022
+ const page = await driver.page(args.target);
10023
+ try {
10024
+ const target = { id: page.info.id, url: page.info.url, title: page.info.title };
10025
+ return await scope.withBrowserConnection(async (conn) => {
10026
+ requireFirefox(conn, "browser.permissions");
10027
+ if (reset)
10028
+ await restoreGrants(conn, tracked);
10029
+ if (permissions.length === 0)
10030
+ return { reset: true, target };
10031
+ const origin = args.origin ?? originOf(page.info.url);
10032
+ if (!origin) {
10033
+ 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"`);
10034
+ }
10035
+ const pageIsOrigin = originOf(page.info.url) === origin;
10036
+ scope.setDisposeHook("browser.permissions", (c) => restoreGrants(c, tracked));
10037
+ for (const d of descriptors) {
10038
+ const key = grantKey(origin, d);
10039
+ if (!tracked.has(key)) {
10040
+ tracked.set(key, { origin, descriptor: d, previous: pageIsOrigin ? await queryState(page, d) : "prompt" });
10041
+ }
10042
+ await conn.send("permissions.setPermission", { descriptor: d, state: "granted", origin });
10043
+ }
10044
+ return { granted: [...permissions], origin, ...reset ? { reset: true } : {}, target };
10045
+ });
10046
+ } finally {
10047
+ await page.release();
10048
+ }
10049
+ }
10050
+ var BIDI_BROWSER_TOOLS = {
10051
+ wait_for_download: waitForDownloadFirefox,
10052
+ grant_permissions: grantPermissionsFirefox
9311
10053
  };
9312
10054
 
9313
10055
  // src/firefox-tools.ts
@@ -9315,6 +10057,7 @@ var FIREFOX_TOOLS = {
9315
10057
  ...SHARED_TOOLS,
9316
10058
  ...BIDI_ONLY_TOOLS,
9317
10059
  ...LEASE_TOOLS,
10060
+ ...BIDI_BROWSER_TOOLS,
9318
10061
  extract_page: extractPage
9319
10062
  };
9320
10063
 
@@ -9923,7 +10666,7 @@ var MANIFEST = [
9923
10666
  },
9924
10667
  {
9925
10668
  name: "dispatch_mouse",
9926
- description: "Dispatch one raw mouse event at viewport coordinates; Chrome-only.",
10669
+ description: "Dispatch one raw mouse event at viewport coordinates; Firefox needs 160 or newer.",
9927
10670
  inputSchema: {
9928
10671
  type: "object",
9929
10672
  properties: {
@@ -10080,7 +10823,7 @@ var MANIFEST = [
10080
10823
  },
10081
10824
  {
10082
10825
  name: "grant_permissions",
10083
- description: "Grant or reset browser permissions; permissions are origin-scoped and Chrome-only.",
10826
+ description: "Grant or reset browser permissions; permissions are origin-scoped (Chrome, Firefox 160+).",
10084
10827
  inputSchema: {
10085
10828
  type: "object",
10086
10829
  properties: {
@@ -11252,13 +11995,13 @@ function toolAnnotations(name) {
11252
11995
  // src/install/wizard.ts
11253
11996
  import { createInterface } from "node:readline";
11254
11997
  import { homedir as homedir3 } from "node:os";
11255
- import { join as join15 } from "node:path";
11998
+ import { join as join17 } from "node:path";
11256
11999
 
11257
12000
  // src/install/browser.ts
11258
12001
  import { existsSync as existsSync3 } from "node:fs";
11259
- import { mkdir as mkdir14, readFile as readFile9, writeFile as writeFile11 } from "node:fs/promises";
12002
+ import { mkdir as mkdir15, readFile as readFile10, writeFile as writeFile11 } from "node:fs/promises";
11260
12003
  import { homedir } from "node:os";
11261
- import { delimiter, dirname as dirname4, join as join13 } from "node:path";
12004
+ import { delimiter, dirname as dirname5, join as join15 } from "node:path";
11262
12005
  var CANDIDATE_BUILDERS = {
11263
12006
  chrome: () => [
11264
12007
  process.env.CHROME_BIN,
@@ -11288,7 +12031,7 @@ function existsOnPath(cmd) {
11288
12031
  for (const dir of pathEnv.split(delimiter)) {
11289
12032
  if (!dir)
11290
12033
  continue;
11291
- if (existsSync3(join13(dir, cmd)))
12034
+ if (existsSync3(join15(dir, cmd)))
11292
12035
  return true;
11293
12036
  }
11294
12037
  return false;
@@ -11338,10 +12081,10 @@ function aliasLine(o) {
11338
12081
  function detectShellRc() {
11339
12082
  const shell = process.env.SHELL ?? "";
11340
12083
  if (shell.endsWith("zsh"))
11341
- return join13(homedir(), ".zshrc");
12084
+ return join15(homedir(), ".zshrc");
11342
12085
  if (shell.endsWith("bash"))
11343
- return join13(homedir(), ".bashrc");
11344
- return join13(homedir(), process.platform === "darwin" ? ".zshrc" : ".bashrc");
12086
+ return join15(homedir(), ".bashrc");
12087
+ return join15(homedir(), process.platform === "darwin" ? ".zshrc" : ".bashrc");
11345
12088
  }
11346
12089
  var MARKER_START = "# >>> cdp-toolkit alias >>>";
11347
12090
  var MARKER_END = "# <<< cdp-toolkit alias <<<";
@@ -11353,7 +12096,7 @@ function ensureTrailingNewline(s) {
11353
12096
  async function appendAliasToRc(rcPath, aliasBlockBody) {
11354
12097
  let existing = "";
11355
12098
  try {
11356
- existing = await readFile9(rcPath, "utf8");
12099
+ existing = await readFile10(rcPath, "utf8");
11357
12100
  } catch (err) {
11358
12101
  if (err.code !== "ENOENT")
11359
12102
  throw err;
@@ -11377,7 +12120,7 @@ ${after}`);
11377
12120
  await writeFile11(rcPath, next, "utf8");
11378
12121
  return { rcPath, action: "replaced-block" };
11379
12122
  }
11380
- await mkdir14(dirname4(rcPath), { recursive: true });
12123
+ await mkdir15(dirname5(rcPath), { recursive: true });
11381
12124
  const sep = existing.length === 0 || existing.endsWith(`
11382
12125
  `) ? "" : `
11383
12126
  `;
@@ -11389,9 +12132,9 @@ ${after}`);
11389
12132
 
11390
12133
  // src/install/harness.ts
11391
12134
  import { spawnSync } from "node:child_process";
11392
- import { mkdir as mkdir15, readFile as readFile10, writeFile as writeFile12 } from "node:fs/promises";
12135
+ import { mkdir as mkdir16, readFile as readFile11, writeFile as writeFile12 } from "node:fs/promises";
11393
12136
  import { homedir as homedir2 } from "node:os";
11394
- import { dirname as dirname5, join as join14 } from "node:path";
12137
+ import { dirname as dirname6, join as join16 } from "node:path";
11395
12138
  async function installMcpServer(harness, name, cfg, opts = {}) {
11396
12139
  switch (harness) {
11397
12140
  case "claude":
@@ -11407,11 +12150,11 @@ async function installMcpServer(harness, name, cfg, opts = {}) {
11407
12150
  }
11408
12151
  }
11409
12152
  async function installClaude(name, cfg, opts) {
11410
- const path = opts.configPath ?? join14(opts.homeDir ?? homedir2(), ".claude.json");
12153
+ const path = opts.configPath ?? join16(opts.homeDir ?? homedir2(), ".claude.json");
11411
12154
  let root;
11412
12155
  let fileExisted;
11413
12156
  try {
11414
- const text = await readFile10(path, "utf8");
12157
+ const text = await readFile11(path, "utf8");
11415
12158
  const parsed = JSON.parse(text);
11416
12159
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
11417
12160
  throw new Error(`${path} does not contain a JSON object at its top level`);
@@ -11438,7 +12181,7 @@ async function installClaude(name, cfg, opts) {
11438
12181
  if (action === "unchanged") {
11439
12182
  return { harness: "claude", method: "file", path, action, detail: "no change needed" };
11440
12183
  }
11441
- await mkdir15(dirname5(path), { recursive: true });
12184
+ await mkdir16(dirname6(path), { recursive: true });
11442
12185
  await writeFile12(path, JSON.stringify(root, null, 2) + `
11443
12186
  `, "utf8");
11444
12187
  return {
@@ -11675,7 +12418,7 @@ async function promptPort(def) {
11675
12418
  }
11676
12419
  function harnessTargetDesc(harness, io) {
11677
12420
  if (harness === "claude") {
11678
- return io.configPath ?? join15(io.homeDir ?? homedir3(), ".claude.json");
12421
+ return io.configPath ?? join17(io.homeDir ?? homedir3(), ".claude.json");
11679
12422
  }
11680
12423
  return `via \`${harness} mcp add\``;
11681
12424
  }