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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cdp-toolkit",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.2.0",
|
|
4
4
|
"description": "A lightweight chrome-devtools-mcp alternative: an MCP server + CLI that drives the tabs you name, one target per call over one direct WebSocket, with a bounded timeout on every call, so a stuck page can't wedge your agent or force a /mcp restart. Chrome over CDP and Firefox over WebDriver BiDi, with tools a backend can't run absent from tools/list rather than throwing mid-task. 48 tools (only 5 core tools listed by default, plus search_tools/call_tool to reach the rest) including built-in network mocking, a cookie group, tab leases with human-activity detection, real HTML5 drag-and-drop, raw mouse/scroll dispatch, downloads, permission grants, and tab-to-video screen recording so several agents can drive one browser without stealing each other's tabs or a human's. No Puppeteer, no all-target fan-out.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -89,6 +89,8 @@
|
|
|
89
89
|
"extension:smoke": "bun run ./test/extension-smoke.ts",
|
|
90
90
|
"focus:smoke": "bun run ./test/focus-emulation-smoke.ts",
|
|
91
91
|
"extract:smoke": "bun run ./test/extract-smoke.ts",
|
|
92
|
+
"browser-ws:smoke": "bun run ./test/browser-ws-smoke.ts",
|
|
93
|
+
"browser-ws:wedge": "bun run ./test/browser-ws-wedge.ts",
|
|
92
94
|
"gateway:smoke": "bun run ./test/gateway-smoke.ts"
|
|
93
95
|
},
|
|
94
96
|
"devDependencies": {
|
package/src/bidi/snapshot.ts
CHANGED
|
@@ -49,6 +49,128 @@ export function coerceSnapshotResult(raw: unknown): StampedSnapshot {
|
|
|
49
49
|
return { snapshot: (raw as StampedSnapshot).snapshot, nodeCount: (raw as StampedSnapshot).nodeCount };
|
|
50
50
|
}
|
|
51
51
|
|
|
52
|
+
/**
|
|
53
|
+
* The reduced role + accessible-name heuristics, as in-page JS source. Shared by the snapshot
|
|
54
|
+
* walker below and by `describeElementSource` (src/shared-tools.ts), which names the element an
|
|
55
|
+
* action is about to touch, so a click result and a snapshot line agree on what "button \"Save\""
|
|
56
|
+
* means. Expects a `MAX_NAME_LENGTH` var in the enclosing function; interpolates nothing itself.
|
|
57
|
+
*/
|
|
58
|
+
export const ACCNAME_HELPERS_SOURCE = `
|
|
59
|
+
function truncate(s) {
|
|
60
|
+
s = s.trim().replace(/\\s+/g, " ");
|
|
61
|
+
if (s.length > MAX_NAME_LENGTH) return s.slice(0, MAX_NAME_LENGTH - 1) + "\\u2026";
|
|
62
|
+
return s;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function textOf(el) {
|
|
66
|
+
return el.textContent || "";
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function idRefsText(doc, ids) {
|
|
70
|
+
var parts = [];
|
|
71
|
+
var list = ids.trim().split(/\\s+/);
|
|
72
|
+
for (var i = 0; i < list.length; i++) {
|
|
73
|
+
var ref = doc.getElementById(list[i]);
|
|
74
|
+
if (ref) parts.push(textOf(ref));
|
|
75
|
+
}
|
|
76
|
+
return parts.join(" ").trim();
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Text of a <label>, minus any nested form control's own content: a
|
|
80
|
+
// label that WRAPS its control ("<label>Color <select>...</select></label>")
|
|
81
|
+
// would otherwise include every option's text in the control's own name.
|
|
82
|
+
function labelOwnText(label) {
|
|
83
|
+
var clone = label.cloneNode(true);
|
|
84
|
+
var controls = clone.querySelectorAll("input, select, textarea, button");
|
|
85
|
+
for (var i = 0; i < controls.length; i++) {
|
|
86
|
+
controls[i].parentNode.removeChild(controls[i]);
|
|
87
|
+
}
|
|
88
|
+
return textOf(clone);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Guard: without this, an <option> inside a labelled <select> would
|
|
92
|
+
// inherit the select's own label via closest("label"), not its text.
|
|
93
|
+
var LABELABLE_TAGS = { INPUT: 1, TEXTAREA: 1, SELECT: 1, BUTTON: 1, METER: 1, OUTPUT: 1, PROGRESS: 1 };
|
|
94
|
+
|
|
95
|
+
function nativeLabelText(el) {
|
|
96
|
+
if (!LABELABLE_TAGS[el.tagName]) return "";
|
|
97
|
+
var doc = el.ownerDocument;
|
|
98
|
+
if (el.id) {
|
|
99
|
+
var forLabel = doc.querySelector('label[for="' + el.id + '"]');
|
|
100
|
+
if (forLabel) return labelOwnText(forLabel);
|
|
101
|
+
}
|
|
102
|
+
var ancestor = el.closest ? el.closest("label") : null;
|
|
103
|
+
if (ancestor) return labelOwnText(ancestor);
|
|
104
|
+
return "";
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// Reduced accname: aria-labelledby, then aria-label, then native label,
|
|
108
|
+
// then alt/title/placeholder, then trimmed own text for content-named
|
|
109
|
+
// elements. Not the full W3C accname algorithm (no recursive traversal
|
|
110
|
+
// rules for nested presentational content) but covers the common cases.
|
|
111
|
+
function accessibleName(el, contentNamed) {
|
|
112
|
+
var doc = el.ownerDocument;
|
|
113
|
+
var labelledby = el.getAttribute("aria-labelledby");
|
|
114
|
+
if (labelledby) {
|
|
115
|
+
var viaIds = idRefsText(doc, labelledby);
|
|
116
|
+
if (viaIds) return truncate(viaIds);
|
|
117
|
+
}
|
|
118
|
+
var ariaLabel = el.getAttribute("aria-label");
|
|
119
|
+
if (ariaLabel && ariaLabel.trim()) return truncate(ariaLabel);
|
|
120
|
+
var native = nativeLabelText(el);
|
|
121
|
+
if (native && native.trim()) return truncate(native);
|
|
122
|
+
var alt = el.getAttribute("alt");
|
|
123
|
+
if (alt && alt.trim()) return truncate(alt);
|
|
124
|
+
var title = el.getAttribute("title");
|
|
125
|
+
if (title && title.trim()) return truncate(title);
|
|
126
|
+
var placeholder = el.getAttribute("placeholder");
|
|
127
|
+
if (placeholder && placeholder.trim()) return truncate(placeholder);
|
|
128
|
+
if (contentNamed) {
|
|
129
|
+
var text = textOf(el);
|
|
130
|
+
if (text && text.trim()) return truncate(text);
|
|
131
|
+
}
|
|
132
|
+
return "";
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
var IMPLICIT_ROLE_BY_TAG = {
|
|
136
|
+
A: "link", BUTTON: "button", NAV: "navigation", MAIN: "main", FORM: "form", DIALOG: "dialog",
|
|
137
|
+
UL: "list", OL: "list", LI: "listitem", TABLE: "table", TR: "row", TD: "cell", TH: "columnheader",
|
|
138
|
+
SELECT: "combobox", OPTION: "option", TEXTAREA: "textbox", IMG: "img",
|
|
139
|
+
H1: "heading", H2: "heading", H3: "heading", H4: "heading", H5: "heading", H6: "heading",
|
|
140
|
+
PROGRESS: "progressbar", METER: "meter"
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
var INPUT_TYPE_ROLE = {
|
|
144
|
+
button: "button", submit: "button", reset: "button", checkbox: "checkbox", radio: "radio",
|
|
145
|
+
range: "slider", number: "spinbutton", search: "searchbox", email: "textbox", tel: "textbox",
|
|
146
|
+
url: "textbox", password: "textbox", text: "textbox", image: "button"
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
var CONTENT_NAMED_ROLES = {
|
|
150
|
+
button: true, link: true, heading: true, option: true, cell: true,
|
|
151
|
+
columnheader: true, listitem: true, menuitem: true, tab: true
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
function implicitRole(el) {
|
|
155
|
+
var explicit = el.getAttribute("role");
|
|
156
|
+
if (explicit) return explicit;
|
|
157
|
+
var tag = el.tagName;
|
|
158
|
+
if (tag === "INPUT") {
|
|
159
|
+
var type = (el.getAttribute("type") || "text").toLowerCase();
|
|
160
|
+
return INPUT_TYPE_ROLE[type] || "textbox";
|
|
161
|
+
}
|
|
162
|
+
if (tag === "A" && !el.getAttribute("href")) return "";
|
|
163
|
+
if (Object.prototype.hasOwnProperty.call(IMPLICIT_ROLE_BY_TAG, tag)) {
|
|
164
|
+
return IMPLICIT_ROLE_BY_TAG[tag];
|
|
165
|
+
}
|
|
166
|
+
// Deliberate divergence: Chrome's real AX tree says "generic" here,
|
|
167
|
+
// but "textbox" is the useful signal an agent needs. Chrome is out of
|
|
168
|
+
// step, do not "fix" this toward parity.
|
|
169
|
+
if (el.isContentEditable) return "textbox";
|
|
170
|
+
return "";
|
|
171
|
+
}
|
|
172
|
+
`;
|
|
173
|
+
|
|
52
174
|
/**
|
|
53
175
|
* The in-page function source. Zero-argument, self-contained: no closures
|
|
54
176
|
* over TypeScript scope, no imports, nothing but plain DOM/ARIA calls that
|
|
@@ -102,119 +224,7 @@ export function buildSnapshotFunctionSource(): string {
|
|
|
102
224
|
return true;
|
|
103
225
|
}
|
|
104
226
|
|
|
105
|
-
|
|
106
|
-
s = s.trim().replace(/\\s+/g, " ");
|
|
107
|
-
if (s.length > MAX_NAME_LENGTH) return s.slice(0, MAX_NAME_LENGTH - 1) + "\\u2026";
|
|
108
|
-
return s;
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
function textOf(el) {
|
|
112
|
-
return el.textContent || "";
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
function idRefsText(doc, ids) {
|
|
116
|
-
var parts = [];
|
|
117
|
-
var list = ids.trim().split(/\\s+/);
|
|
118
|
-
for (var i = 0; i < list.length; i++) {
|
|
119
|
-
var ref = doc.getElementById(list[i]);
|
|
120
|
-
if (ref) parts.push(textOf(ref));
|
|
121
|
-
}
|
|
122
|
-
return parts.join(" ").trim();
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
// Text of a <label>, minus any nested form control's own content: a
|
|
126
|
-
// label that WRAPS its control ("<label>Color <select>...</select></label>")
|
|
127
|
-
// would otherwise include every option's text in the control's own name.
|
|
128
|
-
function labelOwnText(label) {
|
|
129
|
-
var clone = label.cloneNode(true);
|
|
130
|
-
var controls = clone.querySelectorAll("input, select, textarea, button");
|
|
131
|
-
for (var i = 0; i < controls.length; i++) {
|
|
132
|
-
controls[i].parentNode.removeChild(controls[i]);
|
|
133
|
-
}
|
|
134
|
-
return textOf(clone);
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
// Guard: without this, an <option> inside a labelled <select> would
|
|
138
|
-
// inherit the select's own label via closest("label"), not its text.
|
|
139
|
-
var LABELABLE_TAGS = { INPUT: 1, TEXTAREA: 1, SELECT: 1, BUTTON: 1, METER: 1, OUTPUT: 1, PROGRESS: 1 };
|
|
140
|
-
|
|
141
|
-
function nativeLabelText(el) {
|
|
142
|
-
if (!LABELABLE_TAGS[el.tagName]) return "";
|
|
143
|
-
var doc = el.ownerDocument;
|
|
144
|
-
if (el.id) {
|
|
145
|
-
var forLabel = doc.querySelector('label[for="' + el.id + '"]');
|
|
146
|
-
if (forLabel) return labelOwnText(forLabel);
|
|
147
|
-
}
|
|
148
|
-
var ancestor = el.closest ? el.closest("label") : null;
|
|
149
|
-
if (ancestor) return labelOwnText(ancestor);
|
|
150
|
-
return "";
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
// Reduced accname: aria-labelledby, then aria-label, then native label,
|
|
154
|
-
// then alt/title/placeholder, then trimmed own text for content-named
|
|
155
|
-
// elements. Not the full W3C accname algorithm (no recursive traversal
|
|
156
|
-
// rules for nested presentational content) but covers the common cases.
|
|
157
|
-
function accessibleName(el, contentNamed) {
|
|
158
|
-
var doc = el.ownerDocument;
|
|
159
|
-
var labelledby = el.getAttribute("aria-labelledby");
|
|
160
|
-
if (labelledby) {
|
|
161
|
-
var viaIds = idRefsText(doc, labelledby);
|
|
162
|
-
if (viaIds) return truncate(viaIds);
|
|
163
|
-
}
|
|
164
|
-
var ariaLabel = el.getAttribute("aria-label");
|
|
165
|
-
if (ariaLabel && ariaLabel.trim()) return truncate(ariaLabel);
|
|
166
|
-
var native = nativeLabelText(el);
|
|
167
|
-
if (native && native.trim()) return truncate(native);
|
|
168
|
-
var alt = el.getAttribute("alt");
|
|
169
|
-
if (alt && alt.trim()) return truncate(alt);
|
|
170
|
-
var title = el.getAttribute("title");
|
|
171
|
-
if (title && title.trim()) return truncate(title);
|
|
172
|
-
var placeholder = el.getAttribute("placeholder");
|
|
173
|
-
if (placeholder && placeholder.trim()) return truncate(placeholder);
|
|
174
|
-
if (contentNamed) {
|
|
175
|
-
var text = textOf(el);
|
|
176
|
-
if (text && text.trim()) return truncate(text);
|
|
177
|
-
}
|
|
178
|
-
return "";
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
var IMPLICIT_ROLE_BY_TAG = {
|
|
182
|
-
A: "link", BUTTON: "button", NAV: "navigation", MAIN: "main", FORM: "form", DIALOG: "dialog",
|
|
183
|
-
UL: "list", OL: "list", LI: "listitem", TABLE: "table", TR: "row", TD: "cell", TH: "columnheader",
|
|
184
|
-
SELECT: "combobox", OPTION: "option", TEXTAREA: "textbox", IMG: "img",
|
|
185
|
-
H1: "heading", H2: "heading", H3: "heading", H4: "heading", H5: "heading", H6: "heading",
|
|
186
|
-
PROGRESS: "progressbar", METER: "meter"
|
|
187
|
-
};
|
|
188
|
-
|
|
189
|
-
var INPUT_TYPE_ROLE = {
|
|
190
|
-
button: "button", submit: "button", reset: "button", checkbox: "checkbox", radio: "radio",
|
|
191
|
-
range: "slider", number: "spinbutton", search: "searchbox", email: "textbox", tel: "textbox",
|
|
192
|
-
url: "textbox", password: "textbox", text: "textbox", image: "button"
|
|
193
|
-
};
|
|
194
|
-
|
|
195
|
-
var CONTENT_NAMED_ROLES = {
|
|
196
|
-
button: true, link: true, heading: true, option: true, cell: true,
|
|
197
|
-
columnheader: true, listitem: true, menuitem: true, tab: true
|
|
198
|
-
};
|
|
199
|
-
|
|
200
|
-
function implicitRole(el) {
|
|
201
|
-
var explicit = el.getAttribute("role");
|
|
202
|
-
if (explicit) return explicit;
|
|
203
|
-
var tag = el.tagName;
|
|
204
|
-
if (tag === "INPUT") {
|
|
205
|
-
var type = (el.getAttribute("type") || "text").toLowerCase();
|
|
206
|
-
return INPUT_TYPE_ROLE[type] || "textbox";
|
|
207
|
-
}
|
|
208
|
-
if (tag === "A" && !el.getAttribute("href")) return "";
|
|
209
|
-
if (Object.prototype.hasOwnProperty.call(IMPLICIT_ROLE_BY_TAG, tag)) {
|
|
210
|
-
return IMPLICIT_ROLE_BY_TAG[tag];
|
|
211
|
-
}
|
|
212
|
-
// Deliberate divergence: Chrome's real AX tree says "generic" here,
|
|
213
|
-
// but "textbox" is the useful signal an agent needs. Chrome is out of
|
|
214
|
-
// step, do not "fix" this toward parity.
|
|
215
|
-
if (el.isContentEditable) return "textbox";
|
|
216
|
-
return "";
|
|
217
|
-
}
|
|
227
|
+
${ACCNAME_HELPERS_SOURCE}
|
|
218
228
|
|
|
219
229
|
function headingLevel(el) {
|
|
220
230
|
var m = /^H([1-6])$/.exec(el.tagName);
|
package/src/cdp/driver.ts
CHANGED
|
@@ -5,7 +5,8 @@
|
|
|
5
5
|
* one connection via openPage and holds it for the PageDriver's life; release() closes it. Uid
|
|
6
6
|
* codec (scheme "cdp"): `cdp:<backendDOMNodeId>`, or a bare legacy numeric uid, per THE UID CODEC block in ../driver.ts.
|
|
7
7
|
*/
|
|
8
|
-
import { CdpConnection, CdpError, listTargets, openBrowser, openPage, resolveTarget } from "../client.ts";
|
|
8
|
+
import { CdpConnection, CdpError, listTargets, openBrowser, openPage, resolveTarget, type PageConnection } from "../client.ts";
|
|
9
|
+
import { openSession } from "./session.ts";
|
|
9
10
|
import type { Target, TargetSelector } from "../types.ts";
|
|
10
11
|
import { chromeLeaseBackend, LeaseConflictError } from "../leases.ts";
|
|
11
12
|
import { currentEndpoint } from "../endpoints.ts";
|
|
@@ -82,7 +83,7 @@ export function cdpSameSite(sameSite?: "strict" | "lax" | "none" | "default"): "
|
|
|
82
83
|
|
|
83
84
|
/* ---------------------- copied helpers, see attributions below ---------------------- */
|
|
84
85
|
// Copied verbatim from src/tools/input.ts `centerOf`: scroll into view, read viewport-space center.
|
|
85
|
-
async function centerOf(conn:
|
|
86
|
+
async function centerOf(conn: PageConnection, objectId: string): Promise<{ x: number; y: number }> {
|
|
86
87
|
const fn = "function(){this.scrollIntoView({block:'center',inline:'center'});const r=this.getBoundingClientRect();if(r.width===0&&r.height===0)return null;return {x:r.left+r.width/2,y:r.top+r.height/2};}";
|
|
87
88
|
const { result, exceptionDetails } = await conn.send<{ result: { value?: { x: number; y: number } | null }; exceptionDetails?: { text?: string } }>(
|
|
88
89
|
"Runtime.callFunctionOn", { objectId, functionDeclaration: fn, returnByValue: true },
|
|
@@ -91,7 +92,7 @@ async function centerOf(conn: CdpConnection, objectId: string): Promise<{ x: num
|
|
|
91
92
|
if (!result.value) throw driverError("page-error", "element has zero size / is not visible; cannot compute a click point");
|
|
92
93
|
return result.value;
|
|
93
94
|
}
|
|
94
|
-
async function focusElement(conn:
|
|
95
|
+
async function focusElement(conn: PageConnection, objectId: string): Promise<void> {
|
|
95
96
|
await conn.send("Runtime.callFunctionOn", { objectId, functionDeclaration: "function(){this.focus&&this.focus();}", returnByValue: true });
|
|
96
97
|
}
|
|
97
98
|
/**
|
|
@@ -113,10 +114,10 @@ async function focusElement(conn: CdpConnection, objectId: string): Promise<void
|
|
|
113
114
|
const ARM_SCROLL_SETTLE_WATCH =
|
|
114
115
|
"(function(){window.__cdpScrollSettle=new Promise((resolve)=>{let t;const done=()=>{window.removeEventListener('scroll',on,true);resolve(true);};" +
|
|
115
116
|
"const on=()=>{clearTimeout(t);t=setTimeout(done,60);};window.addEventListener('scroll',on,true);t=setTimeout(done,60);setTimeout(done,500);});})()";
|
|
116
|
-
async function armScrollSettleWatch(conn:
|
|
117
|
+
async function armScrollSettleWatch(conn: PageConnection): Promise<void> {
|
|
117
118
|
await conn.send("Runtime.evaluate", { expression: ARM_SCROLL_SETTLE_WATCH, returnByValue: true });
|
|
118
119
|
}
|
|
119
|
-
async function awaitScrollSettle(conn:
|
|
120
|
+
async function awaitScrollSettle(conn: PageConnection): Promise<void> {
|
|
120
121
|
// Best-effort: a navigation racing the wheel event could tear down window.__cdpScrollSettle
|
|
121
122
|
// before this reads it, and that is not a scroll failure worth surfacing as one.
|
|
122
123
|
await conn.send("Runtime.evaluate", { expression: "window.__cdpScrollSettle", awaitPromise: true, returnByValue: true }).catch(() => undefined);
|
|
@@ -130,7 +131,7 @@ async function awaitScrollSettle(conn: CdpConnection): Promise<void> {
|
|
|
130
131
|
// It is a parameter rather than a `conn.send` here because the choke point is per-PAGE
|
|
131
132
|
// (it knows the target id) and this helper only has a connection.
|
|
132
133
|
async function setValueOnObject(
|
|
133
|
-
conn:
|
|
134
|
+
conn: PageConnection,
|
|
134
135
|
objectId: string,
|
|
135
136
|
value: string,
|
|
136
137
|
sendInput: (method: string, params: Record<string, unknown>) => Promise<unknown>,
|
|
@@ -246,7 +247,7 @@ function axExtras(node: AxNode): Record<string, string> {
|
|
|
246
247
|
}
|
|
247
248
|
/* ------------------------------- locator helpers ------------------------------- */
|
|
248
249
|
// css branch copied from src/tools/input.ts `resolveElement`; uid/text/xpath branches are new.
|
|
249
|
-
async function resolveElementLocator(conn:
|
|
250
|
+
async function resolveElementLocator(conn: PageConnection, loc: ElementLocator): Promise<{ objectId: string }> {
|
|
250
251
|
if ("uid" in loc) {
|
|
251
252
|
return resolveUid(conn, decodeUid(loc.uid)).catch(() => {
|
|
252
253
|
throw driverError("stale-uid", `uid does not resolve: ${loc.uid}`);
|
|
@@ -271,7 +272,7 @@ async function resolveElementLocator(conn: CdpConnection, loc: ElementLocator):
|
|
|
271
272
|
* XPath expression and disambiguates them itself. Not copied from any tools/ module (none
|
|
272
273
|
* implement this); built only on the client primitives per CONTRACT.md rule 2.
|
|
273
274
|
*/
|
|
274
|
-
async function searchLocate(conn:
|
|
275
|
+
async function searchLocate(conn: PageConnection, query: string): Promise<number> {
|
|
275
276
|
await conn.send("DOM.getDocument", { depth: 0 }).catch(() => undefined);
|
|
276
277
|
const { searchId, resultCount } = await conn.send<{ searchId: string; resultCount: number }>("DOM.performSearch", { query });
|
|
277
278
|
try {
|
|
@@ -286,7 +287,7 @@ async function searchLocate(conn: CdpConnection, query: string): Promise<number>
|
|
|
286
287
|
}
|
|
287
288
|
}
|
|
288
289
|
|
|
289
|
-
async function backendNodeIdOf(conn:
|
|
290
|
+
async function backendNodeIdOf(conn: PageConnection, loc: ElementLocator): Promise<number> {
|
|
290
291
|
if ("uid" in loc) return decodeUid(loc.uid);
|
|
291
292
|
if ("css" in loc) {
|
|
292
293
|
const { objectId } = await resolveElementLocator(conn, loc);
|
|
@@ -324,7 +325,7 @@ interface LayoutMetrics {
|
|
|
324
325
|
cssVisualViewport?: { pageX?: number; pageY?: number; clientWidth?: number; clientHeight?: number };
|
|
325
326
|
cssContentSize?: { width: number; height: number };
|
|
326
327
|
}
|
|
327
|
-
async function layoutMetrics(conn:
|
|
328
|
+
async function layoutMetrics(conn: PageConnection): Promise<LayoutMetrics> {
|
|
328
329
|
return conn.send<LayoutMetrics>("Page.getLayoutMetrics");
|
|
329
330
|
}
|
|
330
331
|
/**
|
|
@@ -555,7 +556,7 @@ export function planTiledCapture(
|
|
|
555
556
|
* document-frame correction below is what buys correctness. Keeping it also means the offset this
|
|
556
557
|
* scroll CREATES must be read after it settles — see capture()'s ordering.
|
|
557
558
|
*/
|
|
558
|
-
async function elementBox(conn:
|
|
559
|
+
async function elementBox(conn: PageConnection, loc: ElementLocator): Promise<{ x: number; y: number; width: number; height: number }> {
|
|
559
560
|
const backendNodeId = await backendNodeIdOf(conn, loc);
|
|
560
561
|
await conn.send("DOM.scrollIntoViewIfNeeded", { backendNodeId }).catch(() => undefined);
|
|
561
562
|
const box = await conn.send<{ model: { content: number[] } }>("DOM.getBoxModel", { backendNodeId });
|
|
@@ -664,7 +665,7 @@ class CdpPageDriver implements PageDriver {
|
|
|
664
665
|
// side effect) it did not have before this migration. See the per-method comments below.
|
|
665
666
|
private readonly enabledDomains = new Set<string>();
|
|
666
667
|
private released = false;
|
|
667
|
-
constructor(private readonly conn:
|
|
668
|
+
constructor(private readonly conn: PageConnection, target: Target, readonly browser: BrowserDriver) {
|
|
668
669
|
this.info = { id: target.id, url: target.url, title: target.title, type: target.type };
|
|
669
670
|
}
|
|
670
671
|
private async ensureDomain(name: string): Promise<void> {
|
|
@@ -1596,7 +1597,7 @@ class CdpPageDriver implements PageDriver {
|
|
|
1596
1597
|
* process, which degrades the beacon to current-document-only — correct, since
|
|
1597
1598
|
* a CLI process cannot hold anything across calls by construction.
|
|
1598
1599
|
*/
|
|
1599
|
-
const beaconSessions = new BeaconSessions<
|
|
1600
|
+
const beaconSessions = new BeaconSessions<PageConnection>((conn) => conn.close());
|
|
1600
1601
|
|
|
1601
1602
|
/** Beacon sessions are keyed by endpoint plus target id: a target id only means
|
|
1602
1603
|
* something inside one browser, and named endpoints are separate browsers. The
|
|
@@ -1606,10 +1607,22 @@ function beaconKey(targetId: string): string {
|
|
|
1606
1607
|
return backend === "chrome" ? targetId : `${backend}\u0000${targetId}`;
|
|
1607
1608
|
}
|
|
1608
1609
|
|
|
1609
|
-
/**
|
|
1610
|
-
|
|
1610
|
+
/**
|
|
1611
|
+
* A connection to one target by id, or undefined if the browser no longer has
|
|
1612
|
+
* it. The beacon paths' counterpart of client.ts's `openPage`, and deliberately
|
|
1613
|
+
* NOT that function: these three callers are gate-free by contract (see
|
|
1614
|
+
* ../driver.ts) and must not go through the lease gate `resolveTarget` applies.
|
|
1615
|
+
*
|
|
1616
|
+
* Transport-routed like `openPage`, for the same reason: on a browser-ws
|
|
1617
|
+
* endpoint the listing carries no per-target URL to dial.
|
|
1618
|
+
*/
|
|
1619
|
+
async function openTargetConn(targetId: string, opts: { timeoutMs?: number } = {}): Promise<PageConnection | undefined> {
|
|
1611
1620
|
const hit = (await listTargets()).find((t) => t.id === targetId);
|
|
1612
|
-
return
|
|
1621
|
+
if (!hit) return undefined;
|
|
1622
|
+
// Same marker openPage reads: no per-target URL means this endpoint serves
|
|
1623
|
+
// none, so the target is reached by session instead.
|
|
1624
|
+
if (!hit.webSocketDebuggerUrl) return openSession(targetId, opts).catch(() => undefined);
|
|
1625
|
+
return new CdpConnection(hit.webSocketDebuggerUrl, opts).connect().catch(() => undefined);
|
|
1613
1626
|
}
|
|
1614
1627
|
|
|
1615
1628
|
/**
|
|
@@ -1621,7 +1634,7 @@ async function targetWsUrl(targetId: string): Promise<string | undefined> {
|
|
|
1621
1634
|
* its tab look exactly like a live tab nobody has touched, and the held session
|
|
1622
1635
|
* would never be dropped or retried.
|
|
1623
1636
|
*/
|
|
1624
|
-
async function readBeaconOver(conn:
|
|
1637
|
+
async function readBeaconOver(conn: PageConnection): Promise<number | null | undefined> {
|
|
1625
1638
|
try {
|
|
1626
1639
|
const res = await conn.send<{ result: { value?: unknown } }>("Runtime.evaluate", {
|
|
1627
1640
|
expression: BEACON_READ_EXPRESSION,
|
|
@@ -1643,7 +1656,7 @@ async function readBeaconOver(conn: CdpConnection): Promise<number | null | unde
|
|
|
1643
1656
|
* the same {responsive:false} — that IS the correct answer for both, since the
|
|
1644
1657
|
* caller cannot drive either tab any faster than this already told it.
|
|
1645
1658
|
*/
|
|
1646
|
-
async function probeOver(conn:
|
|
1659
|
+
async function probeOver(conn: PageConnection, timeoutMs: number): Promise<{ responsive: boolean; beaconTs: number | null }> {
|
|
1647
1660
|
try {
|
|
1648
1661
|
const res = await conn.send<{ result: { value?: unknown } }>(
|
|
1649
1662
|
"Runtime.evaluate",
|
|
@@ -1842,9 +1855,7 @@ class CdpBrowserDriver implements BrowserDriver {
|
|
|
1842
1855
|
// build a fresh one rather than reporting a beacon that is not there.
|
|
1843
1856
|
beaconSessions.drop(key);
|
|
1844
1857
|
}
|
|
1845
|
-
const
|
|
1846
|
-
if (!wsUrl) return false;
|
|
1847
|
-
const conn = await new CdpConnection(wsUrl).connect().catch(() => undefined);
|
|
1858
|
+
const conn = await openTargetConn(targetId).catch(() => undefined);
|
|
1848
1859
|
if (!conn) return false;
|
|
1849
1860
|
try {
|
|
1850
1861
|
await conn.send("Page.enable");
|
|
@@ -1876,9 +1887,7 @@ class CdpBrowserDriver implements BrowserDriver {
|
|
|
1876
1887
|
if (value !== undefined) return value;
|
|
1877
1888
|
beaconSessions.drop(key);
|
|
1878
1889
|
}
|
|
1879
|
-
const
|
|
1880
|
-
if (!wsUrl) return null;
|
|
1881
|
-
const conn = await new CdpConnection(wsUrl).connect().catch(() => undefined);
|
|
1890
|
+
const conn = await openTargetConn(targetId).catch(() => undefined);
|
|
1882
1891
|
if (!conn) return null;
|
|
1883
1892
|
try {
|
|
1884
1893
|
return (await readBeaconOver(conn)) ?? null;
|
|
@@ -1904,14 +1913,8 @@ class CdpBrowserDriver implements BrowserDriver {
|
|
|
1904
1913
|
async probeRenderer(targetId: string, timeoutMs: number = RENDERER_PROBE_TIMEOUT_MS): Promise<{ responsive: boolean; beaconTs: number | null }> {
|
|
1905
1914
|
const held = beaconSessions.get(beaconKey(targetId));
|
|
1906
1915
|
if (held) return probeOver(held, timeoutMs);
|
|
1907
|
-
const
|
|
1908
|
-
if (!
|
|
1909
|
-
const conn = new CdpConnection(wsUrl, { timeoutMs });
|
|
1910
|
-
try {
|
|
1911
|
-
await conn.connect();
|
|
1912
|
-
} catch {
|
|
1913
|
-
return { responsive: false, beaconTs: null };
|
|
1914
|
-
}
|
|
1916
|
+
const conn = await openTargetConn(targetId, { timeoutMs }).catch(() => undefined);
|
|
1917
|
+
if (!conn) return { responsive: false, beaconTs: null };
|
|
1915
1918
|
try {
|
|
1916
1919
|
return await probeOver(conn, timeoutMs);
|
|
1917
1920
|
} finally {
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where the DevTools endpoint is, and which of its two transports this Chrome
|
|
3
|
+
* actually serves.
|
|
4
|
+
*
|
|
5
|
+
* THE FACT THIS MODULE EXISTS FOR. Chrome has always had two ways in, and
|
|
6
|
+
* until recently every build served both:
|
|
7
|
+
*
|
|
8
|
+
* A. the HTTP discovery endpoints — `/json/version`, `/json/list` — plus a
|
|
9
|
+
* per-target socket at `/devtools/page/<targetId>`;
|
|
10
|
+
* B. one browser-level socket at `/devtools/browser/<uuid>`, over which
|
|
11
|
+
* `Target.getTargets` lists and `Target.attachToTarget` reaches a page.
|
|
12
|
+
*
|
|
13
|
+
* A Chrome started with `--remote-debugging-port` serves both. A Chrome that
|
|
14
|
+
* had debugging turned on at RUNTIME, through the toggle on
|
|
15
|
+
* `chrome://inspect/#remote-debugging`, serves only (B) — measured on Chrome
|
|
16
|
+
* 153 (the same handshake on a `--remote-debugging-port` instance returns 101
|
|
17
|
+
* for all three):
|
|
18
|
+
*
|
|
19
|
+
* ws://127.0.0.1:<port>/devtools/browser/<uuid> -> HTTP 101
|
|
20
|
+
* ws://127.0.0.1:<port>/devtools/page/<targetId> -> HTTP 403
|
|
21
|
+
* http://127.0.0.1:<port>/json/version, /json/list -> HTTP 404
|
|
22
|
+
*
|
|
23
|
+
* That is not a degraded mode to work around, it is the transport a user gets
|
|
24
|
+
* when they attach to the browser they were already using rather than
|
|
25
|
+
* relaunching it. Everything the toolkit needs is reachable over (B).
|
|
26
|
+
*
|
|
27
|
+
* WHY DETECTED AND NOT CONFIGURED. Making the user declare the transport would
|
|
28
|
+
* make them diagnose a 404 first. The detection is cached per process.
|
|
29
|
+
*
|
|
30
|
+
* WHY THE FALLBACK IS DRIVEN BY A FAILED OPERATION, not by a probe that runs
|
|
31
|
+
* first. `listTargets` still issues its original `/json/list` request before
|
|
32
|
+
* anything here is consulted, and only a request that did NOT answer reaches
|
|
33
|
+
* the fallback. So on a Chrome that serves (A) the code path is the one that
|
|
34
|
+
* shipped, byte for byte, and the new transport cannot regress it — there is
|
|
35
|
+
* no added round-trip, no added failure mode, and no ordering question. The
|
|
36
|
+
* cost of (B) is one 404 on the first listing, then the decision is cached.
|
|
37
|
+
*
|
|
38
|
+
* WHY THE PORT FILE. The browser socket's URL contains a uuid that is minted
|
|
39
|
+
* fresh on every Chrome start, so it cannot be written into a config once. The
|
|
40
|
+
* uuid and the port are the two lines of `DevToolsActivePort` in the profile
|
|
41
|
+
* directory, which is where `/json/version` would otherwise have supplied it.
|
|
42
|
+
* Resolved at connect time for that reason, never memoized across a restart.
|
|
43
|
+
*/
|
|
44
|
+
import { readFile } from "node:fs/promises";
|
|
45
|
+
import { homedir } from "node:os";
|
|
46
|
+
import { join } from "node:path";
|
|
47
|
+
import { currentEndpoint, isDefaultEndpoint } from "../endpoints.ts";
|
|
48
|
+
// A cycle (client.ts imports this module), safe because CdpConnection is only
|
|
49
|
+
// used at call time, never while either module is still evaluating.
|
|
50
|
+
import { CdpConnection } from "../client.ts";
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Which transport this endpoint serves.
|
|
54
|
+
* "http" — `/json/*` answers; per-target sockets exist. The original path.
|
|
55
|
+
* "browser-ws" — only the browser socket answers; pages are reached by session.
|
|
56
|
+
*/
|
|
57
|
+
export type CdpTransport = "http" | "browser-ws";
|
|
58
|
+
|
|
59
|
+
export interface EndpointInfo {
|
|
60
|
+
transport: CdpTransport;
|
|
61
|
+
/** The browser-level WebSocket URL. Always present: both transports have one. */
|
|
62
|
+
browserWsUrl: string;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* The browser socket URL from a profile's `DevToolsActivePort`.
|
|
67
|
+
*
|
|
68
|
+
* The file is exactly two lines — port, then the path component including the
|
|
69
|
+
* uuid — and Chrome rewrites it on every start. A profile that is not running
|
|
70
|
+
* leaves a STALE file behind rather than deleting it, so a URL from here is a
|
|
71
|
+
* candidate to be handshaked, never a fact; `detectEndpoint` treats a failed
|
|
72
|
+
* connect as "not this profile" and moves on.
|
|
73
|
+
*/
|
|
74
|
+
async function browserWsFromPortFile(dir: string, base: string): Promise<string | undefined> {
|
|
75
|
+
const raw = await readFile(join(dir, "DevToolsActivePort"), "utf8").catch(() => undefined);
|
|
76
|
+
if (!raw) return undefined;
|
|
77
|
+
const [port, path] = raw.split("\n");
|
|
78
|
+
if (!port?.trim() || !path?.trim()) return undefined;
|
|
79
|
+
const host = new URL(base).hostname;
|
|
80
|
+
return `ws://${host}:${port.trim()}${path.trim()}`;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* The browser socket for an explicitly named profile, and ONLY an explicitly
|
|
85
|
+
* named one.
|
|
86
|
+
*
|
|
87
|
+
* NEVER SCANS THE DEFAULT PROFILE, and that restraint is the point rather than
|
|
88
|
+
* an omission. Connecting to a DevTools endpoint is not a neutral act: a Chrome
|
|
89
|
+
* with runtime debugging enabled raises a modal "Allow remote debugging?"
|
|
90
|
+
* consent prompt on the user's screen for each new client, and that prompt
|
|
91
|
+
* grants full access to a logged-in browsing session. A library that guesses
|
|
92
|
+
* its way to a browser nobody named would raise that prompt from a unit-test
|
|
93
|
+
* run — which is exactly how this restriction was found, by doing it.
|
|
94
|
+
*
|
|
95
|
+
* So the profile is opt-in: `CDP_USER_DATA_DIR` names it, or nothing is tried.
|
|
96
|
+
* Pointing this toolkit at a browser stays a decision the user makes.
|
|
97
|
+
*/
|
|
98
|
+
async function discoverBrowserWs(base: string): Promise<string | undefined> {
|
|
99
|
+
const dir = process.env.CDP_USER_DATA_DIR;
|
|
100
|
+
return dir ? browserWsFromPortFile(dir, base) : undefined;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* A bounded WebSocket handshake. The port file can name a Chrome that exited,
|
|
105
|
+
* and a dead port would otherwise stall the whole detection on a connect that
|
|
106
|
+
* never resolves. Goes through `CdpConnection` (CONTRIBUTING.md, code rule 2),
|
|
107
|
+
* whose connect is bounded by `timeoutMs`; the socket is closed either way.
|
|
108
|
+
*/
|
|
109
|
+
async function handshake(url: string, timeoutMs: number): Promise<boolean> {
|
|
110
|
+
const conn = new CdpConnection(url, { timeoutMs });
|
|
111
|
+
try {
|
|
112
|
+
await conn.connect();
|
|
113
|
+
return true;
|
|
114
|
+
} catch {
|
|
115
|
+
return false;
|
|
116
|
+
} finally {
|
|
117
|
+
conn.close();
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Keyed by endpoint base: named endpoints are separate browsers, each with its own transport. */
|
|
122
|
+
const cached = new Map<string, Promise<EndpointInfo>>();
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Locate the browser socket for an endpoint that serves no `/json`.
|
|
126
|
+
*
|
|
127
|
+
* Called only after an HTTP request has already failed, so it never runs at all
|
|
128
|
+
* against a Chrome started with `--remote-debugging-port`. `CDP_BROWSER_WS`
|
|
129
|
+
* short-circuits the profile lookup, for an endpoint the port file cannot name
|
|
130
|
+
* (a container, a forwarded port, a profile outside the defaults).
|
|
131
|
+
*
|
|
132
|
+
* Per endpoint: the base comes from currentEndpoint() on each call. CDP_BROWSER_WS and
|
|
133
|
+
* CDP_USER_DATA_DIR each name ONE browser, so they apply to the default endpoint only;
|
|
134
|
+
* a named endpoint is detected from its own `/json/version`.
|
|
135
|
+
*/
|
|
136
|
+
export function detectEndpoint(): Promise<EndpointInfo> {
|
|
137
|
+
// Only a resolved detection is worth keeping. A failure here is usually
|
|
138
|
+
// transient — Chrome still starting, a port file mid-rewrite — and caching
|
|
139
|
+
// the rejection would make the first unlucky call poison every later one.
|
|
140
|
+
const endpoint = currentEndpoint();
|
|
141
|
+
const base = endpoint.base;
|
|
142
|
+
const isDefault = isDefaultEndpoint(endpoint);
|
|
143
|
+
const hit = cached.get(base);
|
|
144
|
+
if (hit) return hit;
|
|
145
|
+
const detection = (async (): Promise<EndpointInfo> => {
|
|
146
|
+
const forced = isDefault ? process.env.CDP_BROWSER_WS : undefined;
|
|
147
|
+
if (forced) return { transport: "browser-ws", browserWsUrl: forced };
|
|
148
|
+
|
|
149
|
+
const discovered = isDefault ? await discoverBrowserWs(base) : undefined;
|
|
150
|
+
if (discovered && (await handshake(discovered, 5_000))) {
|
|
151
|
+
return { transport: "browser-ws", browserWsUrl: discovered };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// Bounded for the same reason the handshake above is: a host that accepts
|
|
155
|
+
// the connection and never answers would otherwise stall detection forever.
|
|
156
|
+
const version = await fetch(`${base}/json/version`, { signal: AbortSignal.timeout(5_000) })
|
|
157
|
+
.then((r) => (r.ok ? (r.json() as Promise<{ webSocketDebuggerUrl?: string }>) : undefined))
|
|
158
|
+
.catch(() => undefined);
|
|
159
|
+
if (version?.webSocketDebuggerUrl) {
|
|
160
|
+
return { transport: "http", browserWsUrl: version.webSocketDebuggerUrl };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const dir = isDefault ? process.env.CDP_USER_DATA_DIR : undefined;
|
|
164
|
+
throw new Error(
|
|
165
|
+
`no DevTools endpoint at ${base}: GET /json/version did not answer and ` +
|
|
166
|
+
(dir
|
|
167
|
+
? `no live browser socket was named by ${dir}/DevToolsActivePort. `
|
|
168
|
+
: `no profile was searched — CDP_USER_DATA_DIR is unset, and no profile is ever scanned unless you name one. `) +
|
|
169
|
+
`Set CDP_BROWSER_WS to the ws://.../devtools/browser/<uuid> URL, or CDP_USER_DATA_DIR to the profile in use.`,
|
|
170
|
+
);
|
|
171
|
+
})().then(
|
|
172
|
+
(info) => {
|
|
173
|
+
// Keep only a browser-ws answer. An "http" one carries a `/json/version`
|
|
174
|
+
// uuid that a Chrome restart invalidates, and that endpoint can simply be
|
|
175
|
+
// asked again, as the HTTP path always has.
|
|
176
|
+
if (info.transport === "http") cached.delete(base);
|
|
177
|
+
return info;
|
|
178
|
+
},
|
|
179
|
+
(error: unknown) => {
|
|
180
|
+
cached.delete(base);
|
|
181
|
+
throw error;
|
|
182
|
+
},
|
|
183
|
+
);
|
|
184
|
+
cached.set(base, detection);
|
|
185
|
+
return detection;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Forget the current endpoint's detection, so the next `detectEndpoint` looks
|
|
190
|
+
* again. For a browser socket that stopped answering: its URL carries a uuid
|
|
191
|
+
* Chrome mints on every start, so after a restart the cached one is stale.
|
|
192
|
+
*/
|
|
193
|
+
export function forgetEndpoint(): void {
|
|
194
|
+
cached.delete(currentEndpoint().base);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Test seam: drop the per-process detection cache. */
|
|
198
|
+
export function resetEndpointCache(): void {
|
|
199
|
+
cached.clear();
|
|
200
|
+
}
|