cdp-toolkit 3.0.2 → 3.1.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/index.js CHANGED
@@ -10,11 +10,308 @@ var __esm = (fn, res, err) => () => {
10
10
  return res;
11
11
  };
12
12
 
13
- // src/leases.ts
13
+ // src/endpoints.ts
14
14
  import { AsyncLocalStorage } from "node:async_hooks";
15
+ import { readFileSync } from "node:fs";
16
+ function checkName(name, where) {
17
+ if (!NAME_RE.test(name)) {
18
+ throw new EndpointConfigError(`${where}: endpoint name '${name}' is invalid; names are letters, digits and '_' only (no '-', '/', ':' or spaces)`);
19
+ }
20
+ }
21
+ function sameBase(a, b) {
22
+ return a.replace(/\/+$/, "") === b.replace(/\/+$/, "");
23
+ }
24
+ function parseBase(raw, where) {
25
+ let url;
26
+ try {
27
+ url = new URL(raw);
28
+ } catch {
29
+ throw new EndpointConfigError(`${where}: '${raw}' is not a valid URL (expected e.g. http://127.0.0.1:9222)`);
30
+ }
31
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
32
+ throw new EndpointConfigError(`${where}: '${raw}' must be an http:// or https:// DevTools origin, not ${url.protocol}`);
33
+ }
34
+ if (url.hash)
35
+ throw new EndpointConfigError(`${where}: '${raw}' must not carry a #fragment`);
36
+ let mode;
37
+ for (const [key, value] of url.searchParams) {
38
+ if (key !== "mode") {
39
+ throw new EndpointConfigError(`${where}: unknown query parameter '${key}' in '${raw}' (only ?mode=read or ?mode=write is understood)`);
40
+ }
41
+ if (value !== "read" && value !== "write") {
42
+ throw new EndpointConfigError(`${where}: unknown mode '${value}' in '${raw}' (use mode=read or mode=write)`);
43
+ }
44
+ mode = value;
45
+ }
46
+ const path = url.pathname.replace(/\/+$/, "");
47
+ return { base: `${url.protocol}//${url.host}${path}`, mode };
48
+ }
49
+ function parseEnvString(spec) {
50
+ const out = [];
51
+ const seen = new Set;
52
+ for (const part of spec.split(",")) {
53
+ const entry = part.trim();
54
+ if (!entry)
55
+ continue;
56
+ const eq = entry.indexOf("=");
57
+ if (eq <= 0) {
58
+ throw new EndpointConfigError(`CDP_ENDPOINTS: entry '${entry}' is not name=url (e.g. teams=http://127.0.0.1:9333)`);
59
+ }
60
+ const name = entry.slice(0, eq).trim();
61
+ checkName(name, "CDP_ENDPOINTS");
62
+ if (seen.has(name))
63
+ throw new EndpointConfigError(`CDP_ENDPOINTS: duplicate endpoint name '${name}'`);
64
+ seen.add(name);
65
+ const { base, mode } = parseBase(entry.slice(eq + 1).trim(), `CDP_ENDPOINTS endpoint '${name}'`);
66
+ out.push({ name, base, readOnly: mode === "read" });
67
+ }
68
+ return out;
69
+ }
70
+ function parseFile(path) {
71
+ let text;
72
+ try {
73
+ text = readFileSync(path, "utf8");
74
+ } catch (err) {
75
+ const code = err.code ?? String(err);
76
+ throw new EndpointConfigError(`CDP_ENDPOINTS_FILE: cannot read '${path}' (${code})`);
77
+ }
78
+ let json;
79
+ try {
80
+ json = JSON.parse(text);
81
+ } catch (err) {
82
+ throw new EndpointConfigError(`CDP_ENDPOINTS_FILE: '${path}' is not valid JSON (${err instanceof Error ? err.message : String(err)})`);
83
+ }
84
+ const where = `CDP_ENDPOINTS_FILE '${path}'`;
85
+ if (!json || typeof json !== "object" || Array.isArray(json)) {
86
+ throw new EndpointConfigError(`${where}: top level must be an object {"default"?, "endpoints": {...}}`);
87
+ }
88
+ const top = json;
89
+ for (const key of Object.keys(top)) {
90
+ if (key !== "default" && key !== "endpoints")
91
+ throw new EndpointConfigError(`${where}: unknown top-level key '${key}'`);
92
+ }
93
+ if (top.default !== undefined && typeof top.default !== "string") {
94
+ throw new EndpointConfigError(`${where}: "default" must be an endpoint name string`);
95
+ }
96
+ const raw = top.endpoints ?? {};
97
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
98
+ throw new EndpointConfigError(`${where}: "endpoints" must be an object keyed by endpoint name`);
99
+ }
100
+ const endpoints = [];
101
+ for (const [name, value] of Object.entries(raw)) {
102
+ checkName(name, where);
103
+ const at = `${where} endpoint '${name}'`;
104
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
105
+ throw new EndpointConfigError(`${at}: must be an object like {"base":"http://127.0.0.1:9333"}`);
106
+ }
107
+ const v = value;
108
+ for (const key of Object.keys(v)) {
109
+ if (key !== "base" && key !== "readOnly" && key !== "mode") {
110
+ throw new EndpointConfigError(`${at}: unknown key '${key}' (known: base, readOnly, mode)`);
111
+ }
112
+ }
113
+ if (typeof v.base !== "string")
114
+ throw new EndpointConfigError(`${at}: "base" is required and must be a URL string`);
115
+ if (v.readOnly !== undefined && typeof v.readOnly !== "boolean")
116
+ throw new EndpointConfigError(`${at}: "readOnly" must be a boolean`);
117
+ if (v.mode !== undefined && v.mode !== "read" && v.mode !== "write") {
118
+ throw new EndpointConfigError(`${at}: unknown mode '${String(v.mode)}' (use "read" or "write")`);
119
+ }
120
+ const parsed = parseBase(v.base, at);
121
+ const votes = [parsed.mode, v.mode, v.readOnly === undefined ? undefined : v.readOnly ? "read" : "write"].filter((x) => x !== undefined);
122
+ if (new Set(votes).size > 1)
123
+ throw new EndpointConfigError(`${at}: readOnly / mode settings contradict each other`);
124
+ endpoints.push({ name, base: parsed.base, readOnly: votes[0] === "read" });
125
+ }
126
+ return { endpoints, defaultName: top.default };
127
+ }
128
+ function loadEndpoints(env = process.env) {
129
+ const fromEnv = env.CDP_ENDPOINTS !== undefined ? parseEnvString(env.CDP_ENDPOINTS) : [];
130
+ const file = env.CDP_ENDPOINTS_FILE ? parseFile(env.CDP_ENDPOINTS_FILE) : { endpoints: [], defaultName: undefined };
131
+ const merged = new Map;
132
+ for (const ep of fromEnv)
133
+ merged.set(ep.name, ep);
134
+ for (const ep of file.endpoints) {
135
+ const prior = merged.get(ep.name);
136
+ if (prior && (prior.base !== ep.base || prior.readOnly !== ep.readOnly)) {
137
+ throw new EndpointConfigError(`endpoint '${ep.name}' is defined differently in CDP_ENDPOINTS (${prior.base}${prior.readOnly ? " read-only" : ""}) and CDP_ENDPOINTS_FILE (${ep.base}${ep.readOnly ? " read-only" : ""})`);
138
+ }
139
+ if (!prior)
140
+ merged.set(ep.name, ep);
141
+ }
142
+ const cdpBase = env.CDP_BASE;
143
+ if (cdpBase !== undefined) {
144
+ const configured = merged.get("default");
145
+ if (configured && !sameBase(configured.base, cdpBase)) {
146
+ throw new EndpointConfigError(`CDP_BASE (${cdpBase}) and the configured endpoint 'default' (${configured.base}) disagree; drop one or make them match`);
147
+ }
148
+ merged.set("default", { name: "default", base: cdpBase, readOnly: configured?.readOnly ?? false });
149
+ }
150
+ const defaultName = file.defaultName ?? "default";
151
+ if (!merged.has(defaultName)) {
152
+ if (file.defaultName !== undefined) {
153
+ throw new EndpointConfigError(`CDP_ENDPOINTS_FILE names default endpoint '${file.defaultName}', which is not defined (known: ${[...merged.keys()].join(", ") || "none"})`);
154
+ }
155
+ merged.set("default", { name: "default", base: DEFAULT_CDP_BASE, readOnly: false });
156
+ }
157
+ const def = merged.get(defaultName);
158
+ const byName = new Map([[def.name, def]]);
159
+ for (const [name, ep] of merged)
160
+ if (name !== def.name)
161
+ byName.set(name, ep);
162
+ return { default: def, byName };
163
+ }
164
+ function signature(env) {
165
+ return JSON.stringify([env.CDP_BASE ?? null, env.CDP_ENDPOINTS ?? null, env.CDP_ENDPOINTS_FILE ?? null]);
166
+ }
167
+ function endpointConfig() {
168
+ const sig = signature(process.env);
169
+ if (cache?.sig === sig)
170
+ return cache.config;
171
+ const config = loadEndpoints(process.env);
172
+ cache = { sig, config };
173
+ return config;
174
+ }
175
+ function defaultEndpoint() {
176
+ return endpointConfig().default;
177
+ }
178
+ function allEndpoints() {
179
+ return [...endpointConfig().byName.values()];
180
+ }
181
+ function getEndpoint(name) {
182
+ const { byName } = endpointConfig();
183
+ const ep = byName.get(name);
184
+ if (!ep) {
185
+ throw new EndpointConfigError(`unknown endpoint '${name}' (known: ${[...byName.keys()].join(", ")}). Configure it with CDP_ENDPOINTS or CDP_ENDPOINTS_FILE.`);
186
+ }
187
+ return ep;
188
+ }
189
+ function leaseNamespace(ep) {
190
+ const { default: def, byName } = endpointConfig();
191
+ if (sameBase(ep.base, def.base))
192
+ return;
193
+ for (const other of byName.values())
194
+ if (sameBase(other.base, ep.base))
195
+ return other.name;
196
+ return ep.name;
197
+ }
198
+ function hasEndpointPrefix(target) {
199
+ return typeof target === "string" && target.startsWith(ENDPOINT_PREFIX);
200
+ }
201
+ function splitEndpointSelector(target) {
202
+ if (!hasEndpointPrefix(target))
203
+ return { endpoint: defaultEndpoint(), rest: target };
204
+ const body = target.slice(ENDPOINT_PREFIX.length);
205
+ const slash = body.indexOf("/");
206
+ const name = slash < 0 ? body : body.slice(0, slash);
207
+ if (!name)
208
+ throw new EndpointConfigError(`selector '${target}' has an empty endpoint name; use endpoint:<name>/<selector>`);
209
+ const rest = slash < 0 ? undefined : body.slice(slash + 1);
210
+ return { endpoint: getEndpoint(name), rest: rest === "" ? undefined : rest };
211
+ }
212
+ function usesEndpointArgs(args) {
213
+ if (!args || typeof args !== "object")
214
+ return false;
215
+ const a = args;
216
+ return SELECTOR_KEYS.some((k) => hasEndpointPrefix(a[k])) || a.endpoint !== undefined || a.allEndpoints === true;
217
+ }
218
+ function stripEndpointArgs(args) {
219
+ if (!args || typeof args !== "object" || Array.isArray(args))
220
+ return { endpoint: defaultEndpoint(), args };
221
+ const a = args;
222
+ const picks = [];
223
+ let out;
224
+ for (const key of SELECTOR_KEYS) {
225
+ const v = a[key];
226
+ if (!hasEndpointPrefix(v))
227
+ continue;
228
+ const { endpoint, rest } = splitEndpointSelector(v);
229
+ picks.push({ from: `${key} '${v}'`, endpoint });
230
+ out ??= { ...a };
231
+ if (rest === undefined)
232
+ delete out[key];
233
+ else
234
+ out[key] = rest;
235
+ }
236
+ if (a.endpoint !== undefined) {
237
+ if (typeof a.endpoint !== "string" || a.endpoint === "") {
238
+ throw new EndpointConfigError("`endpoint` must be a non-empty endpoint name string");
239
+ }
240
+ picks.push({ from: `endpoint '${a.endpoint}'`, endpoint: getEndpoint(a.endpoint) });
241
+ out ??= { ...a };
242
+ delete out.endpoint;
243
+ }
244
+ const token = leaseTokenNamespace(a.lease);
245
+ if (!picks.length) {
246
+ if (token?.ns === undefined)
247
+ return { endpoint: defaultEndpoint(), args };
248
+ return { endpoint: endpointForNamespace(token.ns), args };
249
+ }
250
+ const first = picks[0];
251
+ for (const p of picks.slice(1)) {
252
+ if (p.endpoint.name !== first.endpoint.name) {
253
+ throw new EndpointConfigError(`conflicting endpoints: ${first.from} vs ${p.from}; name one endpoint per call`);
254
+ }
255
+ }
256
+ if (token && leaseNamespace(first.endpoint) !== token.ns) {
257
+ throw new EndpointConfigError(`conflicting endpoints: ${first.from} vs the lease token, which belongs to ${token.ns === undefined ? "the default endpoint" : `endpoint '${token.ns}'`}; name one endpoint per call`);
258
+ }
259
+ return { endpoint: first.endpoint, args: out ?? a };
260
+ }
261
+ function leaseTokenNamespace(lease) {
262
+ if (typeof lease !== "string")
263
+ return null;
264
+ const colon = lease.indexOf(":");
265
+ if (colon <= 0)
266
+ return null;
267
+ const head = lease.slice(0, colon);
268
+ if (head === "chrome")
269
+ return { ns: undefined };
270
+ if (!head.startsWith("chrome@"))
271
+ return null;
272
+ const ns = head.slice("chrome@".length);
273
+ return NAME_RE.test(ns) ? { ns } : null;
274
+ }
275
+ function endpointForNamespace(ns) {
276
+ for (const ep of endpointConfig().byName.values())
277
+ if (leaseNamespace(ep) === ns)
278
+ return ep;
279
+ throw new EndpointConfigError(`the lease token belongs to endpoint '${ns}', which is not configured (known: ${[...endpointConfig().byName.keys()].join(", ")})`);
280
+ }
281
+ function currentEndpoint() {
282
+ return endpointScope.getStore() ?? defaultEndpoint();
283
+ }
284
+ function isDefaultEndpoint(ep) {
285
+ return ep.name === defaultEndpoint().name;
286
+ }
287
+ function withEndpointScope(ep, fn) {
288
+ return endpointScope.run(ep, fn);
289
+ }
290
+ var EndpointConfigError, DEFAULT_CDP_BASE = "http://127.0.0.1:9222", ENDPOINT_PREFIX = "endpoint:", NAME_RE, cache, SELECTOR_KEYS, ENDPOINTS_FIREFOX_MESSAGE = "named CDP endpoints (an 'endpoint:<name>/' selector prefix, the endpoint arg, list_pages allEndpoints) need the Chrome backend; the Firefox BiDi backend has one session and no endpoints", endpointScope;
291
+ var init_endpoints = __esm(() => {
292
+ EndpointConfigError = class EndpointConfigError extends Error {
293
+ constructor(message) {
294
+ super(message);
295
+ this.name = "EndpointConfigError";
296
+ }
297
+ };
298
+ NAME_RE = /^[A-Za-z0-9_]+$/;
299
+ SELECTOR_KEYS = ["target", "targetId"];
300
+ endpointScope = new AsyncLocalStorage;
301
+ });
302
+
303
+ // src/leases.ts
304
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
15
305
  import { randomBytes } from "node:crypto";
16
306
  import { mkdir, readFile, readdir, unlink, writeFile } from "node:fs/promises";
17
307
  import { join } from "node:path";
308
+ function chromeLeaseBackend(ep = currentEndpoint()) {
309
+ const ns = leaseNamespace(ep);
310
+ return ns === undefined ? "chrome" : `chrome@${ns}`;
311
+ }
312
+ function isLeaseBackend(value) {
313
+ return BACKEND_KEY_RE.test(value);
314
+ }
18
315
  function leaseDir() {
19
316
  return process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
20
317
  }
@@ -51,7 +348,7 @@ function tokenParts(token) {
51
348
  if (first <= 0 || last <= first)
52
349
  return;
53
350
  const backend = token.slice(0, first);
54
- if (backend !== "chrome" && backend !== "firefox")
351
+ if (!isLeaseBackend(backend))
55
352
  return;
56
353
  const targetId = token.slice(first + 1, last);
57
354
  const nonce = token.slice(last + 1);
@@ -272,8 +569,10 @@ async function listLeases(opts = {}) {
272
569
  }
273
570
  return out;
274
571
  }
275
- var DEFAULT_LEASE_TTL_MS = 900000, longLived = false, LeaseConflictError, leaseScope, LEASE_FILE_RE;
572
+ var BACKEND_KEY_SOURCE = "chrome@[A-Za-z0-9_]+|chrome|firefox", BACKEND_KEY_RE, DEFAULT_LEASE_TTL_MS = 900000, longLived = false, LeaseConflictError, leaseScope, LEASE_FILE_RE;
276
573
  var init_leases = __esm(() => {
574
+ init_endpoints();
575
+ BACKEND_KEY_RE = new RegExp(`^(?:${BACKEND_KEY_SOURCE})$`);
277
576
  LeaseConflictError = class LeaseConflictError extends Error {
278
577
  targetId;
279
578
  holder;
@@ -284,8 +583,8 @@ var init_leases = __esm(() => {
284
583
  this.name = "LeaseConflictError";
285
584
  }
286
585
  };
287
- leaseScope = new AsyncLocalStorage;
288
- LEASE_FILE_RE = /^lease-(chrome|firefox)-(.+)\.json$/;
586
+ leaseScope = new AsyncLocalStorage2;
587
+ LEASE_FILE_RE = new RegExp(`^lease-(${BACKEND_KEY_SOURCE})-(.+)\\.json$`);
289
588
  });
290
589
 
291
590
  // src/origins.ts
@@ -415,7 +714,7 @@ async function resolveLiveLabel(backend, label, liveIds) {
415
714
  var ORIGIN_FILE_RE;
416
715
  var init_origins = __esm(() => {
417
716
  init_leases();
418
- ORIGIN_FILE_RE = /^origin-(chrome|firefox)-(.+)\.json$/;
717
+ ORIGIN_FILE_RE = new RegExp(`^origin-(${BACKEND_KEY_SOURCE})-(.+)\\.json$`);
419
718
  });
420
719
 
421
720
  // src/workers.ts
@@ -630,7 +929,7 @@ class CdpConnection {
630
929
  }
631
930
  }
632
931
  async function httpJson(path) {
633
- const res = await fetch(`${BASE}${path}`);
932
+ const res = await fetch(`${currentEndpoint().base}${path}`);
634
933
  if (!res.ok)
635
934
  throw new CdpError(`${path} -> HTTP ${res.status}`);
636
935
  return await res.json();
@@ -647,7 +946,7 @@ async function resolveTarget(selector, opts = {}) {
647
946
  const hit = await pickTarget(targets, selector);
648
947
  if (isWorkerTargetType(hit.type))
649
948
  return hit;
650
- await assertLeaseOk("chrome", hit.id, { lease: opts.lease, url: hit.url, title: hit.title });
949
+ await assertLeaseOk(chromeLeaseBackend(), hit.id, { lease: opts.lease, url: hit.url, title: hit.title });
651
950
  return hit;
652
951
  }
653
952
  async function pickTarget(targets, selector) {
@@ -679,7 +978,7 @@ async function pickTarget(targets, selector) {
679
978
  }
680
979
  if (selector.startsWith("label:")) {
681
980
  const label = selector.slice(6);
682
- const { matchIds, knownLabels } = await resolveLiveLabel("chrome", label, pages.map((t) => t.id));
981
+ const { matchIds, knownLabels } = await resolveLiveLabel(chromeLeaseBackend(), label, pages.map((t) => t.id));
683
982
  if (matchIds.length > 1) {
684
983
  throw new CdpError(`label 'label:${label}' matches more than one live target: ${matchIds.join(", ")}. Resolve by target id instead.`);
685
984
  }
@@ -737,9 +1036,16 @@ var BASE, DEFAULT_TIMEOUT_MS, CdpError;
737
1036
  var init_client = __esm(() => {
738
1037
  init_leases();
739
1038
  init_origins();
1039
+ init_endpoints();
740
1040
  init_workers();
741
1041
  init_frames();
742
- BASE = process.env.CDP_BASE ?? "http://127.0.0.1:9222";
1042
+ BASE = (() => {
1043
+ try {
1044
+ return defaultEndpoint().base;
1045
+ } catch {
1046
+ return process.env.CDP_BASE ?? DEFAULT_CDP_BASE;
1047
+ }
1048
+ })();
743
1049
  DEFAULT_TIMEOUT_MS = Number(process.env.CDP_TIMEOUT_MS ?? 15000);
744
1050
  CdpError = class CdpError extends Error {
745
1051
  code;
@@ -1142,6 +1448,7 @@ var init_driver = __esm(() => {
1142
1448
  // src/cdp/driver.ts
1143
1449
  init_client();
1144
1450
  init_leases();
1451
+ init_endpoints();
1145
1452
  init_activity();
1146
1453
 
1147
1454
  // src/tools/snapshot.ts
@@ -1629,7 +1936,7 @@ class CdpPageDriver {
1629
1936
  await this.conn.send(`${name}.enable`);
1630
1937
  }
1631
1938
  async dispatchInput(method, params = {}) {
1632
- return sendInput(this.conn, "chrome", this.info.id, method, params);
1939
+ return sendInput(this.conn, chromeLeaseBackend(), this.info.id, method, params);
1633
1940
  }
1634
1941
  async ensureDomainSoft(name) {
1635
1942
  if (this.enabledDomains.has(name))
@@ -2223,6 +2530,10 @@ class CdpPageDriver {
2223
2530
  }
2224
2531
  }
2225
2532
  var beaconSessions = new BeaconSessions((conn) => conn.close());
2533
+ function beaconKey(targetId) {
2534
+ const backend = chromeLeaseBackend(currentEndpoint());
2535
+ return backend === "chrome" ? targetId : `${backend}\x00${targetId}`;
2536
+ }
2226
2537
  async function targetWsUrl(targetId) {
2227
2538
  const hit = (await listTargets()).find((t) => t.id === targetId);
2228
2539
  return hit?.webSocketDebuggerUrl;
@@ -2267,6 +2578,41 @@ function noSuchTarget(e) {
2267
2578
  throw e;
2268
2579
  throw driverError("no-such-target", e instanceof CdpError ? e.message : String(e));
2269
2580
  }
2581
+ var NEW_TARGET_SETTLE_MS = 2000;
2582
+ async function createSettledTarget(conn, url, settleMs = NEW_TARGET_SETTLE_MS) {
2583
+ const changed = new Set;
2584
+ let id = "";
2585
+ let wake;
2586
+ const off = conn.on("Target.targetInfoChanged", (params) => {
2587
+ const t = params.targetInfo?.targetId;
2588
+ if (!t)
2589
+ return;
2590
+ changed.add(t);
2591
+ if (t === id)
2592
+ wake?.();
2593
+ });
2594
+ try {
2595
+ await conn.send("Target.setDiscoverTargets", { discover: true }).catch(() => {
2596
+ return;
2597
+ });
2598
+ const { targetId } = await conn.send("Target.createTarget", { url });
2599
+ if (!targetId)
2600
+ throw driverError("page-error", "Target.createTarget returned no targetId");
2601
+ id = targetId;
2602
+ if (!changed.has(targetId)) {
2603
+ await new Promise((resolve) => {
2604
+ const timer = setTimeout(resolve, settleMs);
2605
+ wake = () => {
2606
+ clearTimeout(timer);
2607
+ resolve();
2608
+ };
2609
+ });
2610
+ }
2611
+ return targetId;
2612
+ } finally {
2613
+ off();
2614
+ }
2615
+ }
2270
2616
 
2271
2617
  class CdpBrowserDriver {
2272
2618
  scheme = "cdp";
@@ -2281,9 +2627,7 @@ class CdpBrowserDriver {
2281
2627
  }
2282
2628
  async newPage(url) {
2283
2629
  return withBrowserConn(async (conn) => {
2284
- const { targetId } = await conn.send("Target.createTarget", { url: url ?? "about:blank" });
2285
- if (!targetId)
2286
- throw driverError("page-error", "Target.createTarget returned no targetId");
2630
+ const targetId = await createSettledTarget(conn, url ?? "about:blank");
2287
2631
  return { id: targetId, url: url ?? "about:blank", title: "" };
2288
2632
  });
2289
2633
  }
@@ -2291,7 +2635,7 @@ class CdpBrowserDriver {
2291
2635
  return withBrowserConn(async (conn) => {
2292
2636
  const res = await conn.send("Target.closeTarget", { targetId: id });
2293
2637
  if (res.success !== false)
2294
- beaconSessions.drop(id);
2638
+ beaconSessions.drop(beaconKey(id));
2295
2639
  return { success: res.success ?? true };
2296
2640
  });
2297
2641
  }
@@ -2309,12 +2653,13 @@ class CdpBrowserDriver {
2309
2653
  return new CdpPageDriver(conn, target, this);
2310
2654
  }
2311
2655
  async installActivityBeacon(targetId) {
2312
- const held = beaconSessions.get(targetId);
2656
+ const key = beaconKey(targetId);
2657
+ const held = beaconSessions.get(key);
2313
2658
  if (held) {
2314
2659
  const rearmed = await held.send("Runtime.evaluate", { expression: BEACON_SOURCE, returnByValue: true }).then(() => true).catch(() => false);
2315
2660
  if (rearmed)
2316
2661
  return true;
2317
- beaconSessions.drop(targetId);
2662
+ beaconSessions.drop(key);
2318
2663
  }
2319
2664
  const wsUrl = await targetWsUrl(targetId).catch(() => {
2320
2665
  return;
@@ -2334,16 +2679,17 @@ class CdpBrowserDriver {
2334
2679
  conn.close();
2335
2680
  return false;
2336
2681
  }
2337
- beaconSessions.set(targetId, conn);
2682
+ beaconSessions.set(key, conn);
2338
2683
  return true;
2339
2684
  }
2340
2685
  async readActivityBeacon(targetId) {
2341
- const held = beaconSessions.get(targetId);
2686
+ const key = beaconKey(targetId);
2687
+ const held = beaconSessions.get(key);
2342
2688
  if (held) {
2343
2689
  const value = await readBeaconOver(held);
2344
2690
  if (value !== undefined)
2345
2691
  return value;
2346
- beaconSessions.drop(targetId);
2692
+ beaconSessions.drop(key);
2347
2693
  }
2348
2694
  const wsUrl = await targetWsUrl(targetId).catch(() => {
2349
2695
  return;
@@ -2362,7 +2708,7 @@ class CdpBrowserDriver {
2362
2708
  }
2363
2709
  }
2364
2710
  async probeRenderer(targetId, timeoutMs = RENDERER_PROBE_TIMEOUT_MS) {
2365
- const held = beaconSessions.get(targetId);
2711
+ const held = beaconSessions.get(beaconKey(targetId));
2366
2712
  if (held)
2367
2713
  return probeOver(held, timeoutMs);
2368
2714
  const wsUrl = await targetWsUrl(targetId).catch(() => {
@@ -2395,6 +2741,7 @@ init_activity();
2395
2741
  init_origins();
2396
2742
 
2397
2743
  // src/reap.ts
2744
+ init_endpoints();
2398
2745
  init_leases();
2399
2746
  init_origins();
2400
2747
  function staleAgentTabs(input) {
@@ -2423,6 +2770,11 @@ function reapGraceMs() {
2423
2770
  const raw = Number(process.env.CDP_REAP_GRACE_MS);
2424
2771
  return Number.isFinite(raw) && raw >= 0 ? raw : DEFAULT_REAP_GRACE_MS;
2425
2772
  }
2773
+ function reapAllowed(driver) {
2774
+ if (driver.scheme === "bidi")
2775
+ return true;
2776
+ return !currentEndpoint().readOnly;
2777
+ }
2426
2778
  async function reapStaleAgentTabs(driver, backend) {
2427
2779
  const now = Date.now();
2428
2780
  const livePageIds = (await driver.listPages()).map((p) => p.id);
@@ -2965,6 +3317,7 @@ init_activity();
2965
3317
  init_origins();
2966
3318
  init_workers();
2967
3319
  init_frames();
3320
+ init_endpoints();
2968
3321
  var ARTIFACT_DIR = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
2969
3322
  var STATE_DIR = process.env.CDP_STATE_DIR ?? "/tmp/cdp-toolkit";
2970
3323
 
@@ -2974,7 +3327,7 @@ function target3(p) {
2974
3327
  return { id: p.id, url: p.url, title: p.title };
2975
3328
  }
2976
3329
  function backendOf(driver) {
2977
- return driver.scheme === "bidi" ? "firefox" : "chrome";
3330
+ return driver.scheme === "bidi" ? "firefox" : chromeLeaseBackend();
2978
3331
  }
2979
3332
  async function withPage2(driver, target, fn) {
2980
3333
  const page = await driver.page(target);
@@ -3062,8 +3415,44 @@ async function reapSet(driver, pages, all) {
3062
3415
  }
3063
3416
  }
3064
3417
  async function listPages(driver, args = {}) {
3418
+ const one = { all: args.all, probe: args.probe };
3419
+ if (args.allEndpoints === true) {
3420
+ if (driver.scheme === "bidi")
3421
+ throw new SharedToolError("list_pages: allEndpoints needs the Chrome backend; named endpoints are CDP-only");
3422
+ const results = await Promise.all(allEndpoints().map((ep) => withEndpointScope(ep, () => listPagesOne(driver, one)).then((r) => ({ ep, r }), (e) => ({ ep, error: e instanceof Error ? e.message : String(e) }))));
3423
+ const pages = [];
3424
+ const reaped = [];
3425
+ const endpoints = [];
3426
+ for (const res of results) {
3427
+ const { ep } = res;
3428
+ if ("error" in res) {
3429
+ endpoints.push({ endpoint: ep.name, base: ep.base, readOnly: ep.readOnly, down: true, error: res.error });
3430
+ continue;
3431
+ }
3432
+ for (const p of res.r.pages)
3433
+ pages.push({ ...p, endpoint: ep.name });
3434
+ for (const t of res.r.reaped ?? [])
3435
+ reaped.push({ ...t, endpoint: ep.name });
3436
+ endpoints.push({ endpoint: ep.name, base: ep.base, readOnly: ep.readOnly, count: res.r.count });
3437
+ }
3438
+ return { pages, count: pages.length, ...reaped.length ? { reaped } : {}, endpoints };
3439
+ }
3440
+ const res = await listPagesOne(driver, one);
3441
+ if (driver.scheme !== "bidi") {
3442
+ const ep = currentEndpoint();
3443
+ if (!isDefaultEndpoint(ep)) {
3444
+ return {
3445
+ ...res,
3446
+ pages: res.pages.map((p) => ({ ...p, endpoint: ep.name })),
3447
+ ...res.reaped ? { reaped: res.reaped.map((t) => ({ ...t, endpoint: ep.name })) } : {}
3448
+ };
3449
+ }
3450
+ }
3451
+ return res;
3452
+ }
3453
+ async function listPagesOne(driver, args = {}) {
3065
3454
  const backend = backendOf(driver);
3066
- const reaped = requireLease() ? await reapStaleAgentTabs(driver, backend) : [];
3455
+ const reaped = requireLease() && reapAllowed(driver) ? await reapStaleAgentTabs(driver, backend) : [];
3067
3456
  const reapedIds = new Set(reaped.map((r) => r.targetId));
3068
3457
  const pages = (await driver.listPages({ all: args.all })).filter((p) => !reapedIds.has(p.id));
3069
3458
  const ledger = await originIndex(backend, await reapSet(driver, pages, args.all));
@@ -3704,7 +4093,7 @@ init_leases();
3704
4093
  class LeaseToolError extends Error {
3705
4094
  }
3706
4095
  function backendOf2(driver) {
3707
- return driver.scheme === "bidi" ? "firefox" : "chrome";
4096
+ return driver.scheme === "bidi" ? "firefox" : chromeLeaseBackend();
3708
4097
  }
3709
4098
  async function claimPage(driver, args = {}) {
3710
4099
  const hasTarget = typeof args.target === "string" && args.target.length > 0;
@@ -3789,7 +4178,7 @@ async function releasePage(driver, args = {}) {
3789
4178
  }
3790
4179
  async function listLeasesTool(driver, _args = {}) {
3791
4180
  const backend = backendOf2(driver);
3792
- const reaped = requireLease() ? await reapStaleAgentTabs(driver, backend) : [];
4181
+ const reaped = requireLease() && reapAllowed(driver) ? await reapStaleAgentTabs(driver, backend) : [];
3793
4182
  const reapedIds = new Set(reaped.map((r) => r.targetId));
3794
4183
  const livePages = await driver.listPages();
3795
4184
  const liveIds = livePages.map((p) => p.id);
@@ -4869,11 +5258,12 @@ async function takeHeapsnapshot(args = {}) {
4869
5258
 
4870
5259
  // src/tools/lighthouse.ts
4871
5260
  init_client();
5261
+ init_endpoints();
4872
5262
  import { spawn as spawn2 } from "node:child_process";
4873
5263
  import { mkdir as mkdir10, readFile as readFile7, stat as stat3 } from "node:fs/promises";
4874
5264
  var ARTIFACT_DIR5 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
4875
5265
  function cdpPort() {
4876
- const base = process.env.CDP_BASE ?? "http://127.0.0.1:9222";
5266
+ const base = currentEndpoint().base;
4877
5267
  const m = base.match(/:(\d+)/);
4878
5268
  return m?.[1] ? Number(m[1]) : 9222;
4879
5269
  }
@@ -5010,6 +5400,7 @@ init_network_mock();
5010
5400
  // src/tools/dispatch-mouse.ts
5011
5401
  init_activity();
5012
5402
  init_client();
5403
+ init_leases();
5013
5404
  var CLICK_MODIFIER_BITS2 = { Alt: 1, Control: 2, Meta: 4, Shift: 8 };
5014
5405
  var BUTTONS = new Set(["left", "right", "middle"]);
5015
5406
  var CDP_EVENT_TYPE = {
@@ -5046,7 +5437,7 @@ async function dispatchMouse(args) {
5046
5437
  const params = { type: CDP_EVENT_TYPE[args.action], x: args.x, y: args.y, button, modifiers };
5047
5438
  if (args.action !== "move")
5048
5439
  params.clickCount = args.clickCount ?? 1;
5049
- await sendInput(conn, "chrome", target.id, "Input.dispatchMouseEvent", params);
5440
+ await sendInput(conn, chromeLeaseBackend(), target.id, "Input.dispatchMouseEvent", params);
5050
5441
  return { dispatched: args.action, x: args.x, y: args.y };
5051
5442
  });
5052
5443
  }
@@ -5054,6 +5445,7 @@ async function dispatchMouse(args) {
5054
5445
  // src/tools/focus-emulation.ts
5055
5446
  init_activity();
5056
5447
  init_client();
5448
+ init_leases();
5057
5449
  function validateFocusEmulationArgs(args) {
5058
5450
  if (typeof args.enabled !== "boolean") {
5059
5451
  throw new Error("focus_emulation requires { enabled } of true or false");
@@ -5120,9 +5512,10 @@ async function clickFocusGated(args) {
5120
5512
  const btn = result?.value;
5121
5513
  if (btn && !btn.disabled) {
5122
5514
  const base = { x: btn.x, y: btn.y, button: "left", buttons: 1, clickCount: 1 };
5123
- await sendInput(conn, "chrome", target.id, "Input.dispatchMouseEvent", { type: "mouseMoved", x: btn.x, y: btn.y });
5124
- await sendInput(conn, "chrome", target.id, "Input.dispatchMouseEvent", { ...base, type: "mousePressed" });
5125
- await sendInput(conn, "chrome", target.id, "Input.dispatchMouseEvent", { ...base, type: "mouseReleased" });
5515
+ const backend = chromeLeaseBackend();
5516
+ await sendInput(conn, backend, target.id, "Input.dispatchMouseEvent", { type: "mouseMoved", x: btn.x, y: btn.y });
5517
+ await sendInput(conn, backend, target.id, "Input.dispatchMouseEvent", { ...base, type: "mousePressed" });
5518
+ await sendInput(conn, backend, target.id, "Input.dispatchMouseEvent", { ...base, type: "mouseReleased" });
5126
5519
  return {
5127
5520
  clicked: true,
5128
5521
  x: btn.x,
@@ -5151,12 +5544,16 @@ import { basename, extname, join as join9 } from "node:path";
5151
5544
 
5152
5545
  // src/tools/browser-session.ts
5153
5546
  init_client();
5547
+ init_endpoints();
5154
5548
  import { mkdir as mkdir11 } from "node:fs/promises";
5155
5549
  import { join as join8 } from "node:path";
5156
5550
  var ARTIFACT_DIR6 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
5157
5551
  var DOWNLOADS_DIR = join8(ARTIFACT_DIR6, "downloads");
5158
5552
  var DOWNLOAD_BUFFER_LIMIT = 50;
5159
- var session;
5553
+ var sessions2 = new Map;
5554
+ function sessionKey() {
5555
+ return currentEndpoint().name;
5556
+ }
5160
5557
  function isDisconnect(e) {
5161
5558
  const m = e instanceof Error ? e.message : String(e);
5162
5559
  return /connection (not open|closed)|closed by caller|websocket|ECONNREFUSED|socket/i.test(m);
@@ -5201,13 +5598,15 @@ function subscribe(s) {
5201
5598
  });
5202
5599
  }
5203
5600
  async function getBrowserSession() {
5601
+ const key = sessionKey();
5602
+ const session = sessions2.get(key);
5204
5603
  if (session && !session.dead)
5205
5604
  return session;
5206
5605
  const previousPath = session?.armedPath;
5207
5606
  const conn = await openBrowser();
5208
5607
  const s = { conn, downloads: [], waiters: [], dead: false };
5209
5608
  subscribe(s);
5210
- session = s;
5609
+ sessions2.set(key, s);
5211
5610
  if (previousPath)
5212
5611
  await armDownloadsAt(previousPath);
5213
5612
  return s;
@@ -5238,7 +5637,7 @@ async function armDownloads() {
5238
5637
  return { downloadPath: DOWNLOADS_DIR };
5239
5638
  }
5240
5639
  function pendingDownloads() {
5241
- return (session?.downloads ?? []).filter((d) => d.state === "completed" && !d.consumed);
5640
+ return (sessions2.get(sessionKey())?.downloads ?? []).filter((d) => d.state === "completed" && !d.consumed);
5242
5641
  }
5243
5642
  async function nextCompletedDownload(timeoutMs) {
5244
5643
  const s = await getBrowserSession();
@@ -5262,14 +5661,14 @@ async function nextCompletedDownload(timeoutMs) {
5262
5661
  });
5263
5662
  }
5264
5663
  async function disposeBrowserSession() {
5265
- const s = session;
5266
- session = undefined;
5267
- if (!s)
5268
- return;
5269
- s.dead = true;
5270
- try {
5271
- s.conn.close();
5272
- } catch {}
5664
+ const all = [...sessions2.values()];
5665
+ sessions2.clear();
5666
+ for (const s of all) {
5667
+ s.dead = true;
5668
+ try {
5669
+ s.conn.close();
5670
+ } catch {}
5671
+ }
5273
5672
  }
5274
5673
 
5275
5674
  // src/tools/downloads.ts