cdp-toolkit 3.1.0 → 3.2.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/CHANGELOG.md +15 -0
- package/README.md +38 -0
- package/dist/bidi/mux-daemon.js +359 -120
- package/dist/cli.js +850 -535
- package/dist/index.js +706 -78
- package/dist/mcp.js +840 -525
- package/package.json +3 -1
- package/src/bidi/snapshot.ts +123 -113
- package/src/cdp/driver.ts +35 -32
- package/src/cdp/endpoint.ts +200 -0
- package/src/cdp/session.ts +246 -0
- package/src/client.ts +118 -10
- package/src/shared-tools.ts +92 -21
- package/src/toolDocs.ts +2 -2
- package/src/tools/evaluate.ts +3 -3
- package/src/tools/navigation.ts +3 -3
- package/src/tools/network_mock.ts +2 -2
- package/src/tools/performance.ts +5 -5
- package/src/tools/recorder.ts +3 -3
- package/src/tools/screencast.ts +46 -6
- package/src/tools/snapshot.ts +2 -2
- package/src/version.ts +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,21 @@ and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.ht
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [3.2.0] - 2026-11-10
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- Action results now say what they touched, not just where. `click`, `hover`, `fill`, `type_text` and `upload_file` return an `element` field with a snapshot-style `role "name"` string (`{"clicked":true,"element":"button \"Save\"","x":85,"y":95}`), so a transcript shows "clicked button Save" instead of a bare uid. `fill_form` returns `elements` (one per field, `null` where none could be read) and `drag` returns `element` for the source plus `target_element` when `to` is an element. The description is read in the page before the action (a click can navigate or unmount its node; `fill` reports the field's label, not the new value), is bounded to 2s, and is omitted rather than thrown on failure, so it can never break or mask the action's own result or error. Additive: no existing field changed. (`src/shared-tools.ts`, `test/describe-element.test.ts`)
|
|
15
|
+
- The role and accessible-name heuristics behind the Firefox snapshot walker are now one shared in-page source (`ACCNAME_HELPERS_SOURCE`, `src/bidi/snapshot.ts`) used by both the walker and the new describe step; the walker's generated function is byte-identical modulo whitespace. Caveat: on Chrome the snapshot comes from the native accessibility tree while `element` uses this DOM heuristic, so the two agree for buttons, links, tabs and labelled inputs but can differ on exotic accname cases.
|
|
16
|
+
- **Browser-WebSocket transport: attach to a Chrome that serves no `/json`.** A Chrome that had debugging turned on at runtime, through the toggle on `chrome://inspect/#remote-debugging`, serves only the browser-level socket — measured on Chrome 153, `/devtools/browser/<uuid>` returns 101 while `/devtools/page/<targetId>` returns 403 and `/json/version`+`/json/list` both return 404. That is the transport a user gets when they attach to the browser they were already using rather than relaunching it, and the toolkit could not reach it at all. Discovery now falls back to `Target.getTargets` over that one socket, and each call reaches its page through a flat `Target.attachToTarget` session on it. **The HTTP path is byte-for-byte unchanged**: `listTargets` issues its original `GET /json/list` first and unconditionally, and only a request that did not answer reaches the fallback — no added round-trip, no added failure mode, and the transport is cached after the first listing. The switch happens only when detection confirms the endpoint serves no `/json`: on a Chrome that does, a single failed `/json/list` (a restart, a timeout) is reported and the next call tries HTTP again, and `/json/version` is still asked on every call, so a restarted Chrome's new browser uuid is picked up. A cached browser-socket URL that stops answering is detected again once, which picks up a restarted Chrome's new `DevToolsActivePort`. The one-target-per-call guarantee holds: `Target.getTargets` is metadata-only and attaches to nothing, so a browser with hundreds of tabs costs one round trip rather than one attach per tab. Nothing is auto-discovered — a runtime-toggled Chrome raises a modal consent prompt for each new client, so the browser is named explicitly with `CDP_BROWSER_WS` (the socket URL) or `CDP_USER_DATA_DIR` (the profile whose `DevToolsActivePort` holds it), and the default profile is never scanned. (`src/cdp/endpoint.ts`, `src/cdp/session.ts`, `src/client.ts`, `src/cdp/driver.ts`)
|
|
17
|
+
- **`bun run browser-ws:smoke` and `bun run browser-ws:wedge`.** Both spawn their own disposable headless Chrome and front it with a proxy that removes exactly what the runtime-toggle mode removes (`test/browser-ws-only-proxy.ts`), because that mode cannot be requested with a flag and puts a consent dialog in front of every client. The smoke drives discovery and per-tab work against a confirmed `/json/version=404 /json/list=404 page-ws=403` endpoint, with every phase capped at the real 60s MCP tool timeout: at `TABS=200` it listed 201 pages (410 targets across 6 types) in 0.08s, evaluated in 0.09s, snapshotted in 0.03s, and drove 5 consecutive tabs in 0.03s. The wedge proves the timeout bound survives socket sharing, which `bench:wedge` cannot — that benchmark gives every page its own socket, where a hung renderer can only block the one socket dialed into it, while this transport puts every page on ONE socket. Observed in CI on headless Chrome 156 against a 5s bound: the blackholed tab rejected at 5.00s while a witness tab answered in 3ms, `list_pages` in 4ms and a freshly opened tab in 13ms, all on the same socket. (An earlier "under 1ms" figure was an artifact: the wedge read the clock before awaiting the call, so every success measured about 0ms.) Both scripts now run in CI, in their own job. (`test/browser-ws-smoke.ts`, `test/browser-ws-wedge.ts`)
|
|
18
|
+
- With named endpoints, transport detection runs per endpoint. `CDP_BROWSER_WS` and `CDP_USER_DATA_DIR` each name one browser, so they apply to the default endpoint only. (`src/cdp/endpoint.ts`)
|
|
19
|
+
|
|
20
|
+
### Fixed
|
|
21
|
+
|
|
22
|
+
- `stop_screen_recording` failed on new ffmpeg (9.0.1 on Homebrew) with `Unrecognized option 'vsync'`, because `-vsync` is gone there. The encoder probe now also reads `ffmpeg -version` and uses `-fps_mode vfr` on ffmpeg 5.1 and later (and git snapshots), keeping `-vsync vfr` for 4.4 and 5.0. If `-version` fails or prints no readable version, the probe reads the option list from `-h full` instead, and if that fails too it picks `-fps_mode`, never the removed `-vsync`. Verified on ffmpeg 9.0.1: a 4 s two-frame ledger encoded to 4.04 s with `-fps_mode`; the old argv exited 8. (`src/tools/screencast.ts` `supportsFpsMode`, `test/screencast.test.ts`)
|
|
23
|
+
- Tests could reach the developer's own browser on the default DevTools port. A stub that fails `/json/list` on purpose sent the browser-ws fallback to the real `/json/version`, and the transport learned there stayed cached for the rest of the run, so later stubbed listing tests read live tabs. A `bun test` preload (`test/helpers/no-live-browser.ts`, wired in `bunfig.toml`) now refuses any fetch or WebSocket to the default endpoint's port and clears the transport caches before each test.
|
|
24
|
+
|
|
10
25
|
## [3.1.0] - 2026-11-10
|
|
11
26
|
|
|
12
27
|
### Added
|
package/README.md
CHANGED
|
@@ -239,6 +239,8 @@ await TOOLS.navigate_page({ target: "index:0", url: "https://example.com" });
|
|
|
239
239
|
| `CDP_ENDPOINTS` | unset | Chrome only. Extra named endpoints, `name=url` comma-separated, e.g. `browser=http://127.0.0.1:9222,teams=http://127.0.0.1:9333?mode=read`. See "Named endpoints" below. |
|
|
240
240
|
| `CDP_ENDPOINTS_FILE` | unset | Chrome only. Path to a JSON file defining named endpoints (same meaning as `CDP_ENDPOINTS`, merged with it). See "Named endpoints" below. |
|
|
241
241
|
| `CDP_TIMEOUT_MS` | `15000` | Per-command timeout. |
|
|
242
|
+
| `CDP_BROWSER_WS` | unset | The `ws://…/devtools/browser/<uuid>` URL, for a Chrome that serves no `/json`. Only consulted after an HTTP listing has already failed. See "Attaching to a Chrome that serves no `/json`" below. |
|
|
243
|
+
| `CDP_USER_DATA_DIR` | unset | Profile directory to read `DevToolsActivePort` from, to find that browser socket without naming its uuid. Opt-in on purpose: nothing is scanned unless you name it. |
|
|
242
244
|
| `CDP_ARTIFACT_DIR` | `/tmp/cdp-toolkit` | Screenshots, traces, heap snapshots, lighthouse reports, recorder buffers. |
|
|
243
245
|
| `CDP_STATE_DIR` | `/tmp/cdp-toolkit` | `select_page` selected-target file, in-flight trace state. |
|
|
244
246
|
| `CDP_EXTRACT_BASE_URL` | `http://127.0.0.1:8090/v1` | `extract_page` only. Base URL of the OpenAI-compatible extraction endpoint (the server appends `/chat/completions`). The default is loopback llm-ferry, so page content never leaves the machine; overriding it sends page content wherever the operator points. |
|
|
@@ -338,6 +340,42 @@ The server serves **both** eras off the same stdio transport, and the era is pin
|
|
|
338
340
|
|
|
339
341
|
Measured 2026-09-01: Claude Code 2.1.258 and Codex CLI 0.147.0 both connect and both pin the **legacy** era — their binaries carry the 2026-07-28 client strings, but neither opens with `server/discover` by default, and the MCP SDK's own `Client` behaves the same unless it opts in. So serving both eras is load-bearing, not courtesy, and today the `ttlMs`/`cacheScope` hints reach only clients that ask for the modern era. The static listing pays off on either one — no mid-session tool churn, and no prompt-cache invalidation.
|
|
340
342
|
|
|
343
|
+
## Attaching to a Chrome that serves no `/json`
|
|
344
|
+
|
|
345
|
+
Chrome has two ways in, and until recently every build served both: (A) the HTTP discovery endpoints `/json/version` and `/json/list`, plus a per-target socket at `/devtools/page/<targetId>`; and (B) one browser-level socket at `/devtools/browser/<uuid>`, over which `Target.getTargets` lists and `Target.attachToTarget` reaches a page.
|
|
346
|
+
|
|
347
|
+
A Chrome started with `--remote-debugging-port` serves both, and nothing below is reached on one. A Chrome that had debugging turned on **at runtime**, through the toggle on `chrome://inspect/#remote-debugging`, serves only (B) — measured on Chrome 153:
|
|
348
|
+
|
|
349
|
+
| Request | `--remote-debugging-port` Chrome | runtime-toggled Chrome |
|
|
350
|
+
|---|---|---|
|
|
351
|
+
| `ws://127.0.0.1:<port>/devtools/browser/<uuid>` | 101 | **101** |
|
|
352
|
+
| `ws://127.0.0.1:<port>/devtools/page/<targetId>` | 101 | **403** |
|
|
353
|
+
| `http://127.0.0.1:<port>/json/version`, `/json/list` | 200 | **404** |
|
|
354
|
+
|
|
355
|
+
That is the transport a user gets when they attach to the browser they were *already using* rather than relaunching it — a logged-in profile with their real tabs — so it is worth supporting rather than working around. cdp-toolkit reaches it with `Target.getTargets` for discovery and one flat `Target.attachToTarget` session per call for the work, over a single refcounted browser socket.
|
|
356
|
+
|
|
357
|
+
**The HTTP path is untouched.** `list_pages` issues its original `GET /json/list` first and unconditionally; only a request that did *not* answer reaches the fallback. On a Chrome that serves (A) the code path is the one that shipped, with no added round-trip and no added failure mode. The transport is then cached, so the 404 is paid once per process.
|
|
358
|
+
|
|
359
|
+
**Nothing is auto-discovered — you name the browser.** Connecting to a DevTools endpoint is not a neutral act: a runtime-toggled Chrome raises a modal *"Allow remote debugging?"* prompt on the user's screen for each new client, and that prompt grants full access to a logged-in session. So cdp-toolkit never scans the default profile looking for a browser socket. Point it at one explicitly:
|
|
360
|
+
|
|
361
|
+
```bash
|
|
362
|
+
# the browser socket directly (its uuid is minted fresh on every Chrome start)
|
|
363
|
+
CDP_BROWSER_WS=ws://127.0.0.1:9222/devtools/browser/<uuid> cdp list_pages
|
|
364
|
+
|
|
365
|
+
# or name the profile, and the uuid is read from its DevToolsActivePort file
|
|
366
|
+
CDP_USER_DATA_DIR="$HOME/Library/Application Support/Google/Chrome" cdp list_pages
|
|
367
|
+
```
|
|
368
|
+
|
|
369
|
+
**The one-target-per-call guarantee still holds.** Discovery is one `Target.getTargets` — metadata only, it attaches to nothing — so a browser with hundreds of tabs costs one round trip, not one attach per tab. Each call then attaches to the one target it named and detaches on close. Every command still carries `CDP_TIMEOUT_MS`, per command id rather than per socket, so a wedged tab rejects at the bound and the shared socket stays clear for everyone else. `bun run browser-ws:wedge` proves exactly that: it blackholes one tab, then measures a witness tab, `list_pages`, and a freshly opened tab on the same socket.
|
|
370
|
+
|
|
371
|
+
```bash
|
|
372
|
+
bun run browser-ws:smoke # drives discovery + per-tab work on a browser-ws-only endpoint
|
|
373
|
+
TABS=200 bun run browser-ws:smoke
|
|
374
|
+
bun run browser-ws:wedge # one stuck tab must not wedge the shared socket
|
|
375
|
+
```
|
|
376
|
+
|
|
377
|
+
Both spawn their own disposable headless Chrome and front it with a proxy that removes exactly what the runtime-toggle mode removes (`test/browser-ws-only-proxy.ts`), because the real mode cannot be requested with a flag and puts a consent dialog in front of every client. They never look for a Chrome you are already running.
|
|
378
|
+
|
|
341
379
|
## Structured page extraction (`extract_page`)
|
|
342
380
|
|
|
343
381
|
`extract_page` turns a page into **schema-conformant JSON** instead of prose: it grabs the target page's HTML, cleans it (scripts, styles, hidden elements and other non-content noise stripped), and sends it to an OpenAI-compatible `/chat/completions` endpoint along with your JSON Schema, returning JSON that matches the schema — fields you name, not a paragraph you have to parse. A `selector` scopes extraction to one subtree (piercing open shadow roots), so you can extract the article or the table rather than the whole page.
|
package/dist/bidi/mux-daemon.js
CHANGED
|
@@ -2003,119 +2003,7 @@ function buildSnapshotFunctionSource() {
|
|
|
2003
2003
|
return true;
|
|
2004
2004
|
}
|
|
2005
2005
|
|
|
2006
|
-
|
|
2007
|
-
s = s.trim().replace(/\\s+/g, " ");
|
|
2008
|
-
if (s.length > MAX_NAME_LENGTH) return s.slice(0, MAX_NAME_LENGTH - 1) + "\\u2026";
|
|
2009
|
-
return s;
|
|
2010
|
-
}
|
|
2011
|
-
|
|
2012
|
-
function textOf(el) {
|
|
2013
|
-
return el.textContent || "";
|
|
2014
|
-
}
|
|
2015
|
-
|
|
2016
|
-
function idRefsText(doc, ids) {
|
|
2017
|
-
var parts = [];
|
|
2018
|
-
var list = ids.trim().split(/\\s+/);
|
|
2019
|
-
for (var i = 0; i < list.length; i++) {
|
|
2020
|
-
var ref = doc.getElementById(list[i]);
|
|
2021
|
-
if (ref) parts.push(textOf(ref));
|
|
2022
|
-
}
|
|
2023
|
-
return parts.join(" ").trim();
|
|
2024
|
-
}
|
|
2025
|
-
|
|
2026
|
-
// Text of a <label>, minus any nested form control's own content: a
|
|
2027
|
-
// label that WRAPS its control ("<label>Color <select>...</select></label>")
|
|
2028
|
-
// would otherwise include every option's text in the control's own name.
|
|
2029
|
-
function labelOwnText(label) {
|
|
2030
|
-
var clone = label.cloneNode(true);
|
|
2031
|
-
var controls = clone.querySelectorAll("input, select, textarea, button");
|
|
2032
|
-
for (var i = 0; i < controls.length; i++) {
|
|
2033
|
-
controls[i].parentNode.removeChild(controls[i]);
|
|
2034
|
-
}
|
|
2035
|
-
return textOf(clone);
|
|
2036
|
-
}
|
|
2037
|
-
|
|
2038
|
-
// Guard: without this, an <option> inside a labelled <select> would
|
|
2039
|
-
// inherit the select's own label via closest("label"), not its text.
|
|
2040
|
-
var LABELABLE_TAGS = { INPUT: 1, TEXTAREA: 1, SELECT: 1, BUTTON: 1, METER: 1, OUTPUT: 1, PROGRESS: 1 };
|
|
2041
|
-
|
|
2042
|
-
function nativeLabelText(el) {
|
|
2043
|
-
if (!LABELABLE_TAGS[el.tagName]) return "";
|
|
2044
|
-
var doc = el.ownerDocument;
|
|
2045
|
-
if (el.id) {
|
|
2046
|
-
var forLabel = doc.querySelector('label[for="' + el.id + '"]');
|
|
2047
|
-
if (forLabel) return labelOwnText(forLabel);
|
|
2048
|
-
}
|
|
2049
|
-
var ancestor = el.closest ? el.closest("label") : null;
|
|
2050
|
-
if (ancestor) return labelOwnText(ancestor);
|
|
2051
|
-
return "";
|
|
2052
|
-
}
|
|
2053
|
-
|
|
2054
|
-
// Reduced accname: aria-labelledby, then aria-label, then native label,
|
|
2055
|
-
// then alt/title/placeholder, then trimmed own text for content-named
|
|
2056
|
-
// elements. Not the full W3C accname algorithm (no recursive traversal
|
|
2057
|
-
// rules for nested presentational content) but covers the common cases.
|
|
2058
|
-
function accessibleName(el, contentNamed) {
|
|
2059
|
-
var doc = el.ownerDocument;
|
|
2060
|
-
var labelledby = el.getAttribute("aria-labelledby");
|
|
2061
|
-
if (labelledby) {
|
|
2062
|
-
var viaIds = idRefsText(doc, labelledby);
|
|
2063
|
-
if (viaIds) return truncate(viaIds);
|
|
2064
|
-
}
|
|
2065
|
-
var ariaLabel = el.getAttribute("aria-label");
|
|
2066
|
-
if (ariaLabel && ariaLabel.trim()) return truncate(ariaLabel);
|
|
2067
|
-
var native = nativeLabelText(el);
|
|
2068
|
-
if (native && native.trim()) return truncate(native);
|
|
2069
|
-
var alt = el.getAttribute("alt");
|
|
2070
|
-
if (alt && alt.trim()) return truncate(alt);
|
|
2071
|
-
var title = el.getAttribute("title");
|
|
2072
|
-
if (title && title.trim()) return truncate(title);
|
|
2073
|
-
var placeholder = el.getAttribute("placeholder");
|
|
2074
|
-
if (placeholder && placeholder.trim()) return truncate(placeholder);
|
|
2075
|
-
if (contentNamed) {
|
|
2076
|
-
var text = textOf(el);
|
|
2077
|
-
if (text && text.trim()) return truncate(text);
|
|
2078
|
-
}
|
|
2079
|
-
return "";
|
|
2080
|
-
}
|
|
2081
|
-
|
|
2082
|
-
var IMPLICIT_ROLE_BY_TAG = {
|
|
2083
|
-
A: "link", BUTTON: "button", NAV: "navigation", MAIN: "main", FORM: "form", DIALOG: "dialog",
|
|
2084
|
-
UL: "list", OL: "list", LI: "listitem", TABLE: "table", TR: "row", TD: "cell", TH: "columnheader",
|
|
2085
|
-
SELECT: "combobox", OPTION: "option", TEXTAREA: "textbox", IMG: "img",
|
|
2086
|
-
H1: "heading", H2: "heading", H3: "heading", H4: "heading", H5: "heading", H6: "heading",
|
|
2087
|
-
PROGRESS: "progressbar", METER: "meter"
|
|
2088
|
-
};
|
|
2089
|
-
|
|
2090
|
-
var INPUT_TYPE_ROLE = {
|
|
2091
|
-
button: "button", submit: "button", reset: "button", checkbox: "checkbox", radio: "radio",
|
|
2092
|
-
range: "slider", number: "spinbutton", search: "searchbox", email: "textbox", tel: "textbox",
|
|
2093
|
-
url: "textbox", password: "textbox", text: "textbox", image: "button"
|
|
2094
|
-
};
|
|
2095
|
-
|
|
2096
|
-
var CONTENT_NAMED_ROLES = {
|
|
2097
|
-
button: true, link: true, heading: true, option: true, cell: true,
|
|
2098
|
-
columnheader: true, listitem: true, menuitem: true, tab: true
|
|
2099
|
-
};
|
|
2100
|
-
|
|
2101
|
-
function implicitRole(el) {
|
|
2102
|
-
var explicit = el.getAttribute("role");
|
|
2103
|
-
if (explicit) return explicit;
|
|
2104
|
-
var tag = el.tagName;
|
|
2105
|
-
if (tag === "INPUT") {
|
|
2106
|
-
var type = (el.getAttribute("type") || "text").toLowerCase();
|
|
2107
|
-
return INPUT_TYPE_ROLE[type] || "textbox";
|
|
2108
|
-
}
|
|
2109
|
-
if (tag === "A" && !el.getAttribute("href")) return "";
|
|
2110
|
-
if (Object.prototype.hasOwnProperty.call(IMPLICIT_ROLE_BY_TAG, tag)) {
|
|
2111
|
-
return IMPLICIT_ROLE_BY_TAG[tag];
|
|
2112
|
-
}
|
|
2113
|
-
// Deliberate divergence: Chrome's real AX tree says "generic" here,
|
|
2114
|
-
// but "textbox" is the useful signal an agent needs. Chrome is out of
|
|
2115
|
-
// step, do not "fix" this toward parity.
|
|
2116
|
-
if (el.isContentEditable) return "textbox";
|
|
2117
|
-
return "";
|
|
2118
|
-
}
|
|
2006
|
+
${ACCNAME_HELPERS_SOURCE}
|
|
2119
2007
|
|
|
2120
2008
|
function headingLevel(el) {
|
|
2121
2009
|
var m = /^H([1-6])$/.exec(el.tagName);
|
|
@@ -2257,7 +2145,319 @@ function buildSnapshotFunctionSource() {
|
|
|
2257
2145
|
return { snapshot: lines.join("\\n"), nodeCount: nodeCount };
|
|
2258
2146
|
}`;
|
|
2259
2147
|
}
|
|
2260
|
-
var STAMP_ATTR = "data-cdp-uid",
|
|
2148
|
+
var STAMP_ATTR = "data-cdp-uid", ACCNAME_HELPERS_SOURCE = `
|
|
2149
|
+
function truncate(s) {
|
|
2150
|
+
s = s.trim().replace(/\\s+/g, " ");
|
|
2151
|
+
if (s.length > MAX_NAME_LENGTH) return s.slice(0, MAX_NAME_LENGTH - 1) + "\\u2026";
|
|
2152
|
+
return s;
|
|
2153
|
+
}
|
|
2154
|
+
|
|
2155
|
+
function textOf(el) {
|
|
2156
|
+
return el.textContent || "";
|
|
2157
|
+
}
|
|
2158
|
+
|
|
2159
|
+
function idRefsText(doc, ids) {
|
|
2160
|
+
var parts = [];
|
|
2161
|
+
var list = ids.trim().split(/\\s+/);
|
|
2162
|
+
for (var i = 0; i < list.length; i++) {
|
|
2163
|
+
var ref = doc.getElementById(list[i]);
|
|
2164
|
+
if (ref) parts.push(textOf(ref));
|
|
2165
|
+
}
|
|
2166
|
+
return parts.join(" ").trim();
|
|
2167
|
+
}
|
|
2168
|
+
|
|
2169
|
+
// Text of a <label>, minus any nested form control's own content: a
|
|
2170
|
+
// label that WRAPS its control ("<label>Color <select>...</select></label>")
|
|
2171
|
+
// would otherwise include every option's text in the control's own name.
|
|
2172
|
+
function labelOwnText(label) {
|
|
2173
|
+
var clone = label.cloneNode(true);
|
|
2174
|
+
var controls = clone.querySelectorAll("input, select, textarea, button");
|
|
2175
|
+
for (var i = 0; i < controls.length; i++) {
|
|
2176
|
+
controls[i].parentNode.removeChild(controls[i]);
|
|
2177
|
+
}
|
|
2178
|
+
return textOf(clone);
|
|
2179
|
+
}
|
|
2180
|
+
|
|
2181
|
+
// Guard: without this, an <option> inside a labelled <select> would
|
|
2182
|
+
// inherit the select's own label via closest("label"), not its text.
|
|
2183
|
+
var LABELABLE_TAGS = { INPUT: 1, TEXTAREA: 1, SELECT: 1, BUTTON: 1, METER: 1, OUTPUT: 1, PROGRESS: 1 };
|
|
2184
|
+
|
|
2185
|
+
function nativeLabelText(el) {
|
|
2186
|
+
if (!LABELABLE_TAGS[el.tagName]) return "";
|
|
2187
|
+
var doc = el.ownerDocument;
|
|
2188
|
+
if (el.id) {
|
|
2189
|
+
var forLabel = doc.querySelector('label[for="' + el.id + '"]');
|
|
2190
|
+
if (forLabel) return labelOwnText(forLabel);
|
|
2191
|
+
}
|
|
2192
|
+
var ancestor = el.closest ? el.closest("label") : null;
|
|
2193
|
+
if (ancestor) return labelOwnText(ancestor);
|
|
2194
|
+
return "";
|
|
2195
|
+
}
|
|
2196
|
+
|
|
2197
|
+
// Reduced accname: aria-labelledby, then aria-label, then native label,
|
|
2198
|
+
// then alt/title/placeholder, then trimmed own text for content-named
|
|
2199
|
+
// elements. Not the full W3C accname algorithm (no recursive traversal
|
|
2200
|
+
// rules for nested presentational content) but covers the common cases.
|
|
2201
|
+
function accessibleName(el, contentNamed) {
|
|
2202
|
+
var doc = el.ownerDocument;
|
|
2203
|
+
var labelledby = el.getAttribute("aria-labelledby");
|
|
2204
|
+
if (labelledby) {
|
|
2205
|
+
var viaIds = idRefsText(doc, labelledby);
|
|
2206
|
+
if (viaIds) return truncate(viaIds);
|
|
2207
|
+
}
|
|
2208
|
+
var ariaLabel = el.getAttribute("aria-label");
|
|
2209
|
+
if (ariaLabel && ariaLabel.trim()) return truncate(ariaLabel);
|
|
2210
|
+
var native = nativeLabelText(el);
|
|
2211
|
+
if (native && native.trim()) return truncate(native);
|
|
2212
|
+
var alt = el.getAttribute("alt");
|
|
2213
|
+
if (alt && alt.trim()) return truncate(alt);
|
|
2214
|
+
var title = el.getAttribute("title");
|
|
2215
|
+
if (title && title.trim()) return truncate(title);
|
|
2216
|
+
var placeholder = el.getAttribute("placeholder");
|
|
2217
|
+
if (placeholder && placeholder.trim()) return truncate(placeholder);
|
|
2218
|
+
if (contentNamed) {
|
|
2219
|
+
var text = textOf(el);
|
|
2220
|
+
if (text && text.trim()) return truncate(text);
|
|
2221
|
+
}
|
|
2222
|
+
return "";
|
|
2223
|
+
}
|
|
2224
|
+
|
|
2225
|
+
var IMPLICIT_ROLE_BY_TAG = {
|
|
2226
|
+
A: "link", BUTTON: "button", NAV: "navigation", MAIN: "main", FORM: "form", DIALOG: "dialog",
|
|
2227
|
+
UL: "list", OL: "list", LI: "listitem", TABLE: "table", TR: "row", TD: "cell", TH: "columnheader",
|
|
2228
|
+
SELECT: "combobox", OPTION: "option", TEXTAREA: "textbox", IMG: "img",
|
|
2229
|
+
H1: "heading", H2: "heading", H3: "heading", H4: "heading", H5: "heading", H6: "heading",
|
|
2230
|
+
PROGRESS: "progressbar", METER: "meter"
|
|
2231
|
+
};
|
|
2232
|
+
|
|
2233
|
+
var INPUT_TYPE_ROLE = {
|
|
2234
|
+
button: "button", submit: "button", reset: "button", checkbox: "checkbox", radio: "radio",
|
|
2235
|
+
range: "slider", number: "spinbutton", search: "searchbox", email: "textbox", tel: "textbox",
|
|
2236
|
+
url: "textbox", password: "textbox", text: "textbox", image: "button"
|
|
2237
|
+
};
|
|
2238
|
+
|
|
2239
|
+
var CONTENT_NAMED_ROLES = {
|
|
2240
|
+
button: true, link: true, heading: true, option: true, cell: true,
|
|
2241
|
+
columnheader: true, listitem: true, menuitem: true, tab: true
|
|
2242
|
+
};
|
|
2243
|
+
|
|
2244
|
+
function implicitRole(el) {
|
|
2245
|
+
var explicit = el.getAttribute("role");
|
|
2246
|
+
if (explicit) return explicit;
|
|
2247
|
+
var tag = el.tagName;
|
|
2248
|
+
if (tag === "INPUT") {
|
|
2249
|
+
var type = (el.getAttribute("type") || "text").toLowerCase();
|
|
2250
|
+
return INPUT_TYPE_ROLE[type] || "textbox";
|
|
2251
|
+
}
|
|
2252
|
+
if (tag === "A" && !el.getAttribute("href")) return "";
|
|
2253
|
+
if (Object.prototype.hasOwnProperty.call(IMPLICIT_ROLE_BY_TAG, tag)) {
|
|
2254
|
+
return IMPLICIT_ROLE_BY_TAG[tag];
|
|
2255
|
+
}
|
|
2256
|
+
// Deliberate divergence: Chrome's real AX tree says "generic" here,
|
|
2257
|
+
// but "textbox" is the useful signal an agent needs. Chrome is out of
|
|
2258
|
+
// step, do not "fix" this toward parity.
|
|
2259
|
+
if (el.isContentEditable) return "textbox";
|
|
2260
|
+
return "";
|
|
2261
|
+
}
|
|
2262
|
+
`, MAX_NAME_LENGTH = 120;
|
|
2263
|
+
|
|
2264
|
+
// src/cdp/endpoint.ts
|
|
2265
|
+
import { readFile as readFile5 } from "node:fs/promises";
|
|
2266
|
+
import { join as join5 } from "node:path";
|
|
2267
|
+
async function browserWsFromPortFile(dir, base) {
|
|
2268
|
+
const raw = await readFile5(join5(dir, "DevToolsActivePort"), "utf8").catch(() => {
|
|
2269
|
+
return;
|
|
2270
|
+
});
|
|
2271
|
+
if (!raw)
|
|
2272
|
+
return;
|
|
2273
|
+
const [port, path] = raw.split(`
|
|
2274
|
+
`);
|
|
2275
|
+
if (!port?.trim() || !path?.trim())
|
|
2276
|
+
return;
|
|
2277
|
+
const host = new URL(base).hostname;
|
|
2278
|
+
return `ws://${host}:${port.trim()}${path.trim()}`;
|
|
2279
|
+
}
|
|
2280
|
+
async function discoverBrowserWs(base) {
|
|
2281
|
+
const dir = process.env.CDP_USER_DATA_DIR;
|
|
2282
|
+
return dir ? browserWsFromPortFile(dir, base) : undefined;
|
|
2283
|
+
}
|
|
2284
|
+
async function handshake(url, timeoutMs) {
|
|
2285
|
+
const conn = new CdpConnection(url, { timeoutMs });
|
|
2286
|
+
try {
|
|
2287
|
+
await conn.connect();
|
|
2288
|
+
return true;
|
|
2289
|
+
} catch {
|
|
2290
|
+
return false;
|
|
2291
|
+
} finally {
|
|
2292
|
+
conn.close();
|
|
2293
|
+
}
|
|
2294
|
+
}
|
|
2295
|
+
function detectEndpoint() {
|
|
2296
|
+
const endpoint = currentEndpoint();
|
|
2297
|
+
const base = endpoint.base;
|
|
2298
|
+
const isDefault = isDefaultEndpoint(endpoint);
|
|
2299
|
+
const hit = cached.get(base);
|
|
2300
|
+
if (hit)
|
|
2301
|
+
return hit;
|
|
2302
|
+
const detection = (async () => {
|
|
2303
|
+
const forced = isDefault ? process.env.CDP_BROWSER_WS : undefined;
|
|
2304
|
+
if (forced)
|
|
2305
|
+
return { transport: "browser-ws", browserWsUrl: forced };
|
|
2306
|
+
const discovered = isDefault ? await discoverBrowserWs(base) : undefined;
|
|
2307
|
+
if (discovered && await handshake(discovered, 5000)) {
|
|
2308
|
+
return { transport: "browser-ws", browserWsUrl: discovered };
|
|
2309
|
+
}
|
|
2310
|
+
const version = await fetch(`${base}/json/version`, { signal: AbortSignal.timeout(5000) }).then((r) => r.ok ? r.json() : undefined).catch(() => {
|
|
2311
|
+
return;
|
|
2312
|
+
});
|
|
2313
|
+
if (version?.webSocketDebuggerUrl) {
|
|
2314
|
+
return { transport: "http", browserWsUrl: version.webSocketDebuggerUrl };
|
|
2315
|
+
}
|
|
2316
|
+
const dir = isDefault ? process.env.CDP_USER_DATA_DIR : undefined;
|
|
2317
|
+
throw new Error(`no DevTools endpoint at ${base}: GET /json/version did not answer and ` + (dir ? `no live browser socket was named by ${dir}/DevToolsActivePort. ` : `no profile was searched — CDP_USER_DATA_DIR is unset, and no profile is ever scanned unless you name one. `) + `Set CDP_BROWSER_WS to the ws://.../devtools/browser/<uuid> URL, or CDP_USER_DATA_DIR to the profile in use.`);
|
|
2318
|
+
})().then((info) => {
|
|
2319
|
+
if (info.transport === "http")
|
|
2320
|
+
cached.delete(base);
|
|
2321
|
+
return info;
|
|
2322
|
+
}, (error) => {
|
|
2323
|
+
cached.delete(base);
|
|
2324
|
+
throw error;
|
|
2325
|
+
});
|
|
2326
|
+
cached.set(base, detection);
|
|
2327
|
+
return detection;
|
|
2328
|
+
}
|
|
2329
|
+
function forgetEndpoint() {
|
|
2330
|
+
cached.delete(currentEndpoint().base);
|
|
2331
|
+
}
|
|
2332
|
+
var cached;
|
|
2333
|
+
var init_endpoint = __esm(() => {
|
|
2334
|
+
init_endpoints();
|
|
2335
|
+
init_client2();
|
|
2336
|
+
cached = new Map;
|
|
2337
|
+
});
|
|
2338
|
+
|
|
2339
|
+
// src/cdp/session.ts
|
|
2340
|
+
async function acquireBrowserConn() {
|
|
2341
|
+
if (shared) {
|
|
2342
|
+
shared.refs++;
|
|
2343
|
+
return shared.conn;
|
|
2344
|
+
}
|
|
2345
|
+
if (!opening) {
|
|
2346
|
+
opening = (async () => {
|
|
2347
|
+
let { browserWsUrl } = await detectEndpoint();
|
|
2348
|
+
let conn;
|
|
2349
|
+
try {
|
|
2350
|
+
conn = await new CdpConnection(browserWsUrl).connect();
|
|
2351
|
+
} catch (error) {
|
|
2352
|
+
forgetEndpoint();
|
|
2353
|
+
const fresh = (await detectEndpoint().catch(() => {
|
|
2354
|
+
return;
|
|
2355
|
+
}))?.browserWsUrl;
|
|
2356
|
+
if (!fresh || fresh === browserWsUrl)
|
|
2357
|
+
throw error;
|
|
2358
|
+
browserWsUrl = fresh;
|
|
2359
|
+
conn = await new CdpConnection(browserWsUrl).connect();
|
|
2360
|
+
}
|
|
2361
|
+
shared = { conn, refs: 0, url: browserWsUrl };
|
|
2362
|
+
return conn;
|
|
2363
|
+
})().finally(() => {
|
|
2364
|
+
opening = undefined;
|
|
2365
|
+
});
|
|
2366
|
+
}
|
|
2367
|
+
const conn = await opening;
|
|
2368
|
+
shared.refs++;
|
|
2369
|
+
return conn;
|
|
2370
|
+
}
|
|
2371
|
+
function releaseBrowserConn() {
|
|
2372
|
+
if (!shared)
|
|
2373
|
+
return;
|
|
2374
|
+
shared.refs--;
|
|
2375
|
+
if (shared.refs <= 0) {
|
|
2376
|
+
const { conn } = shared;
|
|
2377
|
+
shared = undefined;
|
|
2378
|
+
conn.close();
|
|
2379
|
+
}
|
|
2380
|
+
}
|
|
2381
|
+
async function withBrowserSocket(fn) {
|
|
2382
|
+
const conn = await acquireBrowserConn();
|
|
2383
|
+
try {
|
|
2384
|
+
return await fn(conn);
|
|
2385
|
+
} finally {
|
|
2386
|
+
releaseBrowserConn();
|
|
2387
|
+
}
|
|
2388
|
+
}
|
|
2389
|
+
|
|
2390
|
+
class SessionConnection {
|
|
2391
|
+
browser;
|
|
2392
|
+
sessionId;
|
|
2393
|
+
opts;
|
|
2394
|
+
detached = false;
|
|
2395
|
+
offs = [];
|
|
2396
|
+
constructor(browser, sessionId, opts = {}) {
|
|
2397
|
+
this.browser = browser;
|
|
2398
|
+
this.sessionId = sessionId;
|
|
2399
|
+
this.opts = opts;
|
|
2400
|
+
}
|
|
2401
|
+
send(method, params = {}, opts = {}) {
|
|
2402
|
+
if (this.detached)
|
|
2403
|
+
return Promise.reject(new CdpError("connection not open"));
|
|
2404
|
+
return this.browser.send(method, params, {
|
|
2405
|
+
timeoutMs: opts.timeoutMs ?? this.opts.timeoutMs,
|
|
2406
|
+
sessionId: opts.sessionId ?? this.sessionId
|
|
2407
|
+
});
|
|
2408
|
+
}
|
|
2409
|
+
on(method, handler) {
|
|
2410
|
+
const off = this.browser.on(method, (params, sessionId) => {
|
|
2411
|
+
if (sessionId && sessionId !== this.sessionId)
|
|
2412
|
+
return;
|
|
2413
|
+
handler(params, sessionId);
|
|
2414
|
+
});
|
|
2415
|
+
this.offs.push(off);
|
|
2416
|
+
return off;
|
|
2417
|
+
}
|
|
2418
|
+
waitFor(method, predicate, timeoutMs = this.opts.timeoutMs ?? DEFAULT_TIMEOUT_MS3) {
|
|
2419
|
+
return new Promise((resolve, reject) => {
|
|
2420
|
+
const timer = setTimeout(() => {
|
|
2421
|
+
off();
|
|
2422
|
+
reject(new CdpError(`waitFor('${method}') timed out after ${timeoutMs}ms`));
|
|
2423
|
+
}, timeoutMs);
|
|
2424
|
+
const off = this.on(method, (params) => {
|
|
2425
|
+
if (!predicate || predicate(params)) {
|
|
2426
|
+
clearTimeout(timer);
|
|
2427
|
+
off();
|
|
2428
|
+
resolve(params);
|
|
2429
|
+
}
|
|
2430
|
+
});
|
|
2431
|
+
});
|
|
2432
|
+
}
|
|
2433
|
+
close() {
|
|
2434
|
+
if (this.detached)
|
|
2435
|
+
return;
|
|
2436
|
+
this.detached = true;
|
|
2437
|
+
for (const off of this.offs)
|
|
2438
|
+
off();
|
|
2439
|
+
this.offs.length = 0;
|
|
2440
|
+
this.browser.send("Target.detachFromTarget", { sessionId: this.sessionId }).catch(() => {});
|
|
2441
|
+
releaseBrowserConn();
|
|
2442
|
+
}
|
|
2443
|
+
}
|
|
2444
|
+
async function openSession(targetId, opts = {}) {
|
|
2445
|
+
const browser = await acquireBrowserConn();
|
|
2446
|
+
try {
|
|
2447
|
+
const { sessionId } = await browser.send("Target.attachToTarget", { targetId, flatten: true }, { timeoutMs: opts.timeoutMs });
|
|
2448
|
+
if (!sessionId)
|
|
2449
|
+
throw new CdpError(`Target.attachToTarget returned no sessionId for ${targetId}`);
|
|
2450
|
+
return new SessionConnection(browser, sessionId, opts);
|
|
2451
|
+
} catch (e) {
|
|
2452
|
+
releaseBrowserConn();
|
|
2453
|
+
throw e;
|
|
2454
|
+
}
|
|
2455
|
+
}
|
|
2456
|
+
var shared, opening;
|
|
2457
|
+
var init_session = __esm(() => {
|
|
2458
|
+
init_client2();
|
|
2459
|
+
init_endpoint();
|
|
2460
|
+
});
|
|
2261
2461
|
|
|
2262
2462
|
// src/client.ts
|
|
2263
2463
|
class CdpConnection {
|
|
@@ -2391,12 +2591,47 @@ async function httpJson(path) {
|
|
|
2391
2591
|
throw new CdpError(`${path} -> HTTP ${res.status}`);
|
|
2392
2592
|
return await res.json();
|
|
2393
2593
|
}
|
|
2394
|
-
function
|
|
2395
|
-
|
|
2594
|
+
async function getTargetsOverBrowserWs() {
|
|
2595
|
+
const { targetInfos } = await withBrowserSocket((conn) => conn.send("Target.getTargets", { filter: [{}] }));
|
|
2596
|
+
return targetInfos.map((t) => ({
|
|
2597
|
+
id: t.targetId,
|
|
2598
|
+
type: t.type,
|
|
2599
|
+
title: t.title,
|
|
2600
|
+
url: t.url,
|
|
2601
|
+
webSocketDebuggerUrl: "",
|
|
2602
|
+
...t.openerId ? { parentId: t.openerId } : {}
|
|
2603
|
+
}));
|
|
2604
|
+
}
|
|
2605
|
+
async function listTargets() {
|
|
2606
|
+
const base = currentEndpoint().base;
|
|
2607
|
+
if (knownTransports.get(base) === "browser-ws")
|
|
2608
|
+
return getTargetsOverBrowserWs();
|
|
2609
|
+
try {
|
|
2610
|
+
const listing = await httpJson("/json/list");
|
|
2611
|
+
knownTransports.set(base, "http");
|
|
2612
|
+
return listing;
|
|
2613
|
+
} catch (httpError) {
|
|
2614
|
+
const detected = await detectEndpoint().catch(() => {
|
|
2615
|
+
return;
|
|
2616
|
+
});
|
|
2617
|
+
if (detected?.transport !== "browser-ws")
|
|
2618
|
+
throw httpError;
|
|
2619
|
+
const targets = await getTargetsOverBrowserWs().catch(() => {
|
|
2620
|
+
throw httpError;
|
|
2621
|
+
});
|
|
2622
|
+
knownTransports.set(base, "browser-ws");
|
|
2623
|
+
return targets;
|
|
2624
|
+
}
|
|
2396
2625
|
}
|
|
2397
2626
|
async function browserWsUrl() {
|
|
2398
|
-
|
|
2399
|
-
|
|
2627
|
+
if (knownTransports.get(currentEndpoint().base) !== "browser-ws") {
|
|
2628
|
+
const version = await httpJson("/json/version").catch(() => {
|
|
2629
|
+
return;
|
|
2630
|
+
});
|
|
2631
|
+
if (version?.webSocketDebuggerUrl)
|
|
2632
|
+
return version.webSocketDebuggerUrl;
|
|
2633
|
+
}
|
|
2634
|
+
return (await detectEndpoint()).browserWsUrl;
|
|
2400
2635
|
}
|
|
2401
2636
|
async function resolveTarget(selector, opts = {}) {
|
|
2402
2637
|
const targets = await listTargets();
|
|
@@ -2478,7 +2713,7 @@ async function openBrowser(opts = {}) {
|
|
|
2478
2713
|
}
|
|
2479
2714
|
async function openPage(selector, opts = {}) {
|
|
2480
2715
|
const target = await resolveTarget(selector, { lease: opts.lease });
|
|
2481
|
-
const conn = await new CdpConnection(target.webSocketDebuggerUrl, opts).connect();
|
|
2716
|
+
const conn = target.webSocketDebuggerUrl ? await new CdpConnection(target.webSocketDebuggerUrl, opts).connect() : await openSession(target.id, opts);
|
|
2482
2717
|
return { conn, target };
|
|
2483
2718
|
}
|
|
2484
2719
|
async function withPage(selector, fn, opts = {}) {
|
|
@@ -2489,13 +2724,16 @@ async function withPage(selector, fn, opts = {}) {
|
|
|
2489
2724
|
conn.close();
|
|
2490
2725
|
}
|
|
2491
2726
|
}
|
|
2492
|
-
var BASE, DEFAULT_TIMEOUT_MS3, CdpError;
|
|
2727
|
+
var BASE, DEFAULT_TIMEOUT_MS3, CdpError, knownTransports;
|
|
2493
2728
|
var init_client2 = __esm(() => {
|
|
2494
2729
|
init_leases();
|
|
2495
2730
|
init_origins();
|
|
2496
2731
|
init_endpoints();
|
|
2497
2732
|
init_workers();
|
|
2498
2733
|
init_frames();
|
|
2734
|
+
init_endpoint();
|
|
2735
|
+
init_session();
|
|
2736
|
+
init_session();
|
|
2499
2737
|
BASE = (() => {
|
|
2500
2738
|
try {
|
|
2501
2739
|
return defaultEndpoint().base;
|
|
@@ -2514,6 +2752,7 @@ var init_client2 = __esm(() => {
|
|
|
2514
2752
|
this.name = "CdpError";
|
|
2515
2753
|
}
|
|
2516
2754
|
};
|
|
2755
|
+
knownTransports = new Map;
|
|
2517
2756
|
});
|
|
2518
2757
|
|
|
2519
2758
|
// src/tools/network_mock.ts
|