cdp-toolkit 1.8.0 → 1.9.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 +119 -0
- package/CONTRACT.md +4 -0
- package/README.md +23 -4
- package/dist/cli.js +338 -111
- package/dist/index.js +319 -110
- package/dist/mcp.js +380 -151
- package/package.json +3 -2
- package/src/bidi/driver.ts +28 -0
- package/src/cdp/driver.ts +16 -1
- package/src/cdp/workers.ts +177 -0
- package/src/cli.ts +3 -1
- package/src/client.ts +52 -2
- package/src/driver.ts +27 -1
- package/src/leases-tools.ts +2 -2
- package/src/manifest.ts +44 -40
- package/src/mcp.ts +1 -1
- package/src/origins.ts +41 -1
- package/src/shared-tools.ts +104 -3
- package/src/types.ts +20 -0
- package/src/workers.ts +159 -0
package/dist/index.js
CHANGED
|
@@ -276,6 +276,169 @@ async function listLeases(opts = {}) {
|
|
|
276
276
|
return out;
|
|
277
277
|
}
|
|
278
278
|
|
|
279
|
+
// src/origins.ts
|
|
280
|
+
import { mkdir as mkdir2, readFile as readFile2, readdir as readdir2, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
|
|
281
|
+
import { join as join2 } from "node:path";
|
|
282
|
+
function safeId2(id) {
|
|
283
|
+
return id.replace(/[^A-Za-z0-9._-]/g, "_");
|
|
284
|
+
}
|
|
285
|
+
function originFile(backend, targetId) {
|
|
286
|
+
return join2(leaseDir(), `origin-${backend}-${safeId2(targetId)}.json`);
|
|
287
|
+
}
|
|
288
|
+
var ORIGIN_FILE_RE = /^origin-(chrome|firefox)-(.+)\.json$/;
|
|
289
|
+
async function recordOrigin(backend, targetId, opts = {}) {
|
|
290
|
+
const record = {
|
|
291
|
+
backend,
|
|
292
|
+
targetId,
|
|
293
|
+
label: typeof opts.label === "string" && opts.label.length ? opts.label : defaultLabel(),
|
|
294
|
+
pid: process.pid,
|
|
295
|
+
createdAt: opts.now ?? Date.now()
|
|
296
|
+
};
|
|
297
|
+
const file = originFile(backend, targetId);
|
|
298
|
+
try {
|
|
299
|
+
await mkdir2(leaseDir(), { recursive: true });
|
|
300
|
+
try {
|
|
301
|
+
await writeFile2(file, JSON.stringify(record), { flag: "wx" });
|
|
302
|
+
return;
|
|
303
|
+
} catch (err) {
|
|
304
|
+
if (err.code !== "EEXIST")
|
|
305
|
+
throw err;
|
|
306
|
+
}
|
|
307
|
+
await unlink2(file).catch(() => {
|
|
308
|
+
return;
|
|
309
|
+
});
|
|
310
|
+
await writeFile2(file, JSON.stringify(record), { flag: "wx" });
|
|
311
|
+
} catch {}
|
|
312
|
+
}
|
|
313
|
+
async function readOrigin(backend, targetId) {
|
|
314
|
+
let raw;
|
|
315
|
+
try {
|
|
316
|
+
raw = await readFile2(originFile(backend, targetId), "utf8");
|
|
317
|
+
} catch {
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
try {
|
|
321
|
+
const rec = JSON.parse(raw);
|
|
322
|
+
if (typeof rec?.targetId === "string" && typeof rec?.label === "string" && typeof rec?.createdAt === "number")
|
|
323
|
+
return rec;
|
|
324
|
+
} catch {}
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
async function listOrigins(opts = {}) {
|
|
328
|
+
let names = [];
|
|
329
|
+
try {
|
|
330
|
+
names = await readdir2(leaseDir());
|
|
331
|
+
} catch {
|
|
332
|
+
return [];
|
|
333
|
+
}
|
|
334
|
+
const live = opts.liveIds === undefined ? undefined : new Set(opts.liveIds.map((id) => safeId2(id)));
|
|
335
|
+
const out = [];
|
|
336
|
+
for (const name of names) {
|
|
337
|
+
const parts = ORIGIN_FILE_RE.exec(name);
|
|
338
|
+
if (!parts)
|
|
339
|
+
continue;
|
|
340
|
+
const backend = parts[1];
|
|
341
|
+
const nameId = parts[2];
|
|
342
|
+
const scoped = live !== undefined && (opts.liveBackend === undefined || opts.liveBackend === backend);
|
|
343
|
+
if (scoped && !live.has(nameId)) {
|
|
344
|
+
await unlink2(join2(leaseDir(), name)).catch(() => {
|
|
345
|
+
return;
|
|
346
|
+
});
|
|
347
|
+
continue;
|
|
348
|
+
}
|
|
349
|
+
const fromName = { backend, targetId: nameId, label: "", pid: 0, createdAt: 0 };
|
|
350
|
+
let rec;
|
|
351
|
+
try {
|
|
352
|
+
rec = JSON.parse(await readFile2(join2(leaseDir(), name), "utf8"));
|
|
353
|
+
} catch (err) {
|
|
354
|
+
const code = err.code;
|
|
355
|
+
if (code === "ENOENT")
|
|
356
|
+
continue;
|
|
357
|
+
out.push({ ...fromName, unreadable: code ?? "unparseable" });
|
|
358
|
+
continue;
|
|
359
|
+
}
|
|
360
|
+
if (typeof rec?.targetId !== "string" || typeof rec?.label !== "string" || typeof rec?.createdAt !== "number") {
|
|
361
|
+
out.push({ ...fromName, unreadable: "unparseable" });
|
|
362
|
+
continue;
|
|
363
|
+
}
|
|
364
|
+
out.push({ backend: rec.backend, targetId: rec.targetId, label: rec.label, pid: rec.pid, createdAt: rec.createdAt });
|
|
365
|
+
}
|
|
366
|
+
return out;
|
|
367
|
+
}
|
|
368
|
+
async function originIndex(backend, liveIds) {
|
|
369
|
+
const rows = await listOrigins({ liveIds, liveBackend: backend }).catch(() => []);
|
|
370
|
+
const index = new Map;
|
|
371
|
+
for (const row of rows) {
|
|
372
|
+
if (row.backend !== backend)
|
|
373
|
+
continue;
|
|
374
|
+
index.set(row.targetId, row);
|
|
375
|
+
}
|
|
376
|
+
return index;
|
|
377
|
+
}
|
|
378
|
+
async function newTrackedPage(driver, backend, opts = {}) {
|
|
379
|
+
const page = await driver.newPage(opts.url);
|
|
380
|
+
await recordOrigin(backend, page.id, { label: opts.label });
|
|
381
|
+
return page;
|
|
382
|
+
}
|
|
383
|
+
async function resolveLiveLabel(backend, label, liveIds) {
|
|
384
|
+
const live = new Set(liveIds);
|
|
385
|
+
const [origins, leases] = await Promise.all([originIndex(backend), listLeases({ liveBackend: backend })]);
|
|
386
|
+
const knownLabels = new Set;
|
|
387
|
+
const matchIds = new Set;
|
|
388
|
+
for (const rec of origins.values()) {
|
|
389
|
+
if (rec.unreadable !== undefined || !live.has(rec.targetId))
|
|
390
|
+
continue;
|
|
391
|
+
knownLabels.add(rec.label);
|
|
392
|
+
if (rec.label === label)
|
|
393
|
+
matchIds.add(rec.targetId);
|
|
394
|
+
}
|
|
395
|
+
for (const rec of leases) {
|
|
396
|
+
if (rec.backend !== backend || rec.unreadable !== undefined || !live.has(rec.targetId))
|
|
397
|
+
continue;
|
|
398
|
+
knownLabels.add(rec.label);
|
|
399
|
+
if (rec.label === label)
|
|
400
|
+
matchIds.add(rec.targetId);
|
|
401
|
+
}
|
|
402
|
+
return { matchIds: [...matchIds], knownLabels: [...knownLabels].sort() };
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
// src/workers.ts
|
|
406
|
+
var WORKER_SELECTOR_PREFIX = "worker:";
|
|
407
|
+
var WORKER_TARGET_TYPES = new Set(["service_worker", "shared_worker"]);
|
|
408
|
+
function isWorkerSelector(selector) {
|
|
409
|
+
return typeof selector === "string" && selector.startsWith(WORKER_SELECTOR_PREFIX);
|
|
410
|
+
}
|
|
411
|
+
function workerNeedle(selector) {
|
|
412
|
+
return selector.slice(WORKER_SELECTOR_PREFIX.length);
|
|
413
|
+
}
|
|
414
|
+
function isWorkerTargetType(type) {
|
|
415
|
+
return type !== undefined && WORKER_TARGET_TYPES.has(type);
|
|
416
|
+
}
|
|
417
|
+
function resolveWorkerTargets(targets, needle) {
|
|
418
|
+
const liveWorkers = targets.filter((t) => isWorkerTargetType(t.type));
|
|
419
|
+
return {
|
|
420
|
+
matches: needle === "" ? [] : liveWorkers.filter((t) => t.url.includes(needle)),
|
|
421
|
+
liveWorkers
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
var WORKER_EMPTY_NEEDLE_MESSAGE = "'worker:' needs a substring of the worker's url, e.g. worker:<extension-id> or worker:background.js";
|
|
425
|
+
var WORKER_SELECTOR_UNSUPPORTED_MESSAGE = "target 'worker:<substring>' selects a service/shared worker, which this backend cannot address " + "(WebDriver BiDi has no extension service-worker target; Capability 'worker.targets' is Chrome-only). " + "Use --browser chrome to evaluate in an extension's background worker.";
|
|
426
|
+
var WORKER_SELECTOR_PAGE_ONLY_MESSAGE = "target 'worker:<substring>' selects a service/shared worker, and this tool is page-only " + "(closing, selecting or releasing a worker is meaningless). evaluate_script is the one tool that " + "accepts a worker: target.";
|
|
427
|
+
function urlList(workers) {
|
|
428
|
+
return workers.map((w) => w.url).join(", ");
|
|
429
|
+
}
|
|
430
|
+
function workerAmbiguityMessage(needle, matches) {
|
|
431
|
+
return `'worker:${needle}' matches more than one running worker: ` + matches.map((m) => `${m.url} (${m.id})`).join(", ") + ". Narrow the substring, or pass the worker's target id directly.";
|
|
432
|
+
}
|
|
433
|
+
function workerMissMessage(needle, opts) {
|
|
434
|
+
const running = opts.liveWorkers?.length ? ` (running workers: ${urlList(opts.liveWorkers)})` : " (no workers are running)";
|
|
435
|
+
if (!opts.wakeAttempted) {
|
|
436
|
+
return `no running worker whose url contains '${needle}'${running}. ` + "An MV3 extension service worker is idle-evicted after seconds of inactivity and then appears in NO target " + "listing, so this is usually a sleeping worker rather than a wrong substring. You passed wake:false; " + "wake:true (the default) asks Chrome to start it first.";
|
|
437
|
+
}
|
|
438
|
+
const scopes = opts.registeredScopes?.length ? ` Registered service-worker scopes in this browser: ${opts.registeredScopes.join(", ")}.` : " No service-worker registrations were reported by this browser at all.";
|
|
439
|
+
return `no worker whose url contains '${needle}' could be reached${running}. ` + `A start was requested (wake:true) and no matching worker appeared.${scopes} ` + "If the extension is installed but its worker never starts, check the worker script for a top-level throw.";
|
|
440
|
+
}
|
|
441
|
+
|
|
279
442
|
// src/client.ts
|
|
280
443
|
var BASE = process.env.CDP_BASE ?? "http://127.0.0.1:9222";
|
|
281
444
|
var DEFAULT_TIMEOUT_MS = Number(process.env.CDP_TIMEOUT_MS ?? 15000);
|
|
@@ -431,11 +594,13 @@ async function browserWsUrl() {
|
|
|
431
594
|
}
|
|
432
595
|
async function resolveTarget(selector, opts = {}) {
|
|
433
596
|
const targets = await listTargets();
|
|
434
|
-
const hit = pickTarget(targets, selector);
|
|
597
|
+
const hit = await pickTarget(targets, selector);
|
|
598
|
+
if (isWorkerTargetType(hit.type))
|
|
599
|
+
return hit;
|
|
435
600
|
await assertLeaseOk("chrome", hit.id, { lease: opts.lease, url: hit.url, title: hit.title });
|
|
436
601
|
return hit;
|
|
437
602
|
}
|
|
438
|
-
function pickTarget(targets, selector) {
|
|
603
|
+
async function pickTarget(targets, selector) {
|
|
439
604
|
const pages = targets.filter((t) => t.type === "page");
|
|
440
605
|
if (!selector || selector === "active") {
|
|
441
606
|
if (!pages.length)
|
|
@@ -462,6 +627,30 @@ function pickTarget(targets, selector) {
|
|
|
462
627
|
throw new CdpError(`no page title containing '${needle}'`);
|
|
463
628
|
return hit;
|
|
464
629
|
}
|
|
630
|
+
if (selector.startsWith("label:")) {
|
|
631
|
+
const label = selector.slice(6);
|
|
632
|
+
const { matchIds, knownLabels } = await resolveLiveLabel("chrome", label, pages.map((t) => t.id));
|
|
633
|
+
if (matchIds.length > 1) {
|
|
634
|
+
throw new CdpError(`label 'label:${label}' matches more than one live target: ${matchIds.join(", ")}. Resolve by target id instead.`);
|
|
635
|
+
}
|
|
636
|
+
if (matchIds.length === 1) {
|
|
637
|
+
const hit = pages.find((t) => t.id === matchIds[0]);
|
|
638
|
+
if (hit)
|
|
639
|
+
return hit;
|
|
640
|
+
}
|
|
641
|
+
throw new CdpError(knownLabels.length ? `no live target with label '${label}' (labels currently in use: ${knownLabels.join(", ")})` : `no live target with label '${label}' (no labels are currently assigned to any open target)`);
|
|
642
|
+
}
|
|
643
|
+
if (isWorkerSelector(selector)) {
|
|
644
|
+
const needle = workerNeedle(selector);
|
|
645
|
+
if (needle === "")
|
|
646
|
+
throw new CdpError(WORKER_EMPTY_NEEDLE_MESSAGE);
|
|
647
|
+
const { matches, liveWorkers } = resolveWorkerTargets(targets, needle);
|
|
648
|
+
if (matches.length > 1)
|
|
649
|
+
throw new CdpError(workerAmbiguityMessage(needle, matches));
|
|
650
|
+
if (matches.length === 1)
|
|
651
|
+
return matches[0];
|
|
652
|
+
throw new CdpError(workerMissMessage(needle, { wakeAttempted: false, liveWorkers }));
|
|
653
|
+
}
|
|
465
654
|
const byId = targets.find((t) => t.id === selector);
|
|
466
655
|
if (!byId)
|
|
467
656
|
throw new CdpError(`no target with id '${selector}'`);
|
|
@@ -651,6 +840,91 @@ async function resolveUid(conn, uid) {
|
|
|
651
840
|
return { objectId: object.objectId };
|
|
652
841
|
}
|
|
653
842
|
|
|
843
|
+
// src/cdp/workers.ts
|
|
844
|
+
var INVENTORY_FIRST_EVENT_MS = 1500;
|
|
845
|
+
var INVENTORY_SETTLE_MS = 250;
|
|
846
|
+
var WAKE_POLL_MS = 300;
|
|
847
|
+
var WAKE_POLL_ATTEMPTS = 30;
|
|
848
|
+
var NO_HOST_PAGE_MESSAGE = "cannot start a service worker: the ServiceWorker CDP domain is only reachable over a page session, " + "and this browser has no page target open. Open any tab (new_page) and retry — the tab does not have " + "to belong to the extension.";
|
|
849
|
+
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
850
|
+
async function requestWorkerStart(needle) {
|
|
851
|
+
const conn = await openBrowser();
|
|
852
|
+
try {
|
|
853
|
+
const host = (await listTargets()).find((t) => t.type === "page");
|
|
854
|
+
if (!host)
|
|
855
|
+
throw new CdpError(NO_HOST_PAGE_MESSAGE);
|
|
856
|
+
const { sessionId } = await conn.send("Target.attachToTarget", {
|
|
857
|
+
targetId: host.id,
|
|
858
|
+
flatten: true
|
|
859
|
+
});
|
|
860
|
+
if (!sessionId)
|
|
861
|
+
throw new CdpError("could not attach a session to host the ServiceWorker domain");
|
|
862
|
+
const scopeById = new Map;
|
|
863
|
+
const versions = [];
|
|
864
|
+
conn.on("ServiceWorker.workerRegistrationUpdated", (params) => {
|
|
865
|
+
for (const r of params.registrations ?? []) {
|
|
866
|
+
if (r.isDeleted === true)
|
|
867
|
+
continue;
|
|
868
|
+
scopeById.set(String(r.registrationId), String(r.scopeURL ?? ""));
|
|
869
|
+
}
|
|
870
|
+
});
|
|
871
|
+
conn.on("ServiceWorker.workerVersionUpdated", (params) => {
|
|
872
|
+
for (const v of params.versions ?? []) {
|
|
873
|
+
versions.push({ registrationId: String(v.registrationId), scriptURL: String(v.scriptURL ?? "") });
|
|
874
|
+
}
|
|
875
|
+
});
|
|
876
|
+
await conn.send("ServiceWorker.enable", {}, { sessionId });
|
|
877
|
+
await conn.waitFor("ServiceWorker.workerVersionUpdated", undefined, INVENTORY_FIRST_EVENT_MS).catch(() => {
|
|
878
|
+
return;
|
|
879
|
+
});
|
|
880
|
+
await sleep(INVENTORY_SETTLE_MS);
|
|
881
|
+
const scopes = [...new Set(scopeById.values())].filter((s) => s.length > 0).sort();
|
|
882
|
+
const matched = new Set;
|
|
883
|
+
for (const v of versions) {
|
|
884
|
+
const scope = scopeById.get(v.registrationId);
|
|
885
|
+
if (scope === undefined)
|
|
886
|
+
continue;
|
|
887
|
+
if (v.scriptURL.includes(needle) || scope.includes(needle))
|
|
888
|
+
matched.add(scope);
|
|
889
|
+
}
|
|
890
|
+
if (matched.size === 0)
|
|
891
|
+
return { startRequested: false, scopes };
|
|
892
|
+
if (matched.size > 1) {
|
|
893
|
+
throw new CdpError(`'worker:${needle}' matches more than one registered service-worker scope: ${[...matched].sort().join(", ")}. ` + "Narrow the substring.");
|
|
894
|
+
}
|
|
895
|
+
await conn.send("ServiceWorker.startWorker", { scopeURL: [...matched][0] }, { sessionId });
|
|
896
|
+
return { startRequested: true, scopes };
|
|
897
|
+
} finally {
|
|
898
|
+
conn.close();
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
async function resolveWorkerSelector(selector, opts) {
|
|
902
|
+
const needle = workerNeedle(selector);
|
|
903
|
+
if (needle === "")
|
|
904
|
+
throw new CdpError(WORKER_EMPTY_NEEDLE_MESSAGE);
|
|
905
|
+
const first = resolveWorkerTargets(await listTargets(), needle);
|
|
906
|
+
if (first.matches.length > 1)
|
|
907
|
+
throw new CdpError(workerAmbiguityMessage(needle, first.matches));
|
|
908
|
+
if (first.matches.length === 1)
|
|
909
|
+
return first.matches[0];
|
|
910
|
+
if (!opts.wake) {
|
|
911
|
+
throw new CdpError(workerMissMessage(needle, { wakeAttempted: false, liveWorkers: first.liveWorkers }));
|
|
912
|
+
}
|
|
913
|
+
const { startRequested, scopes } = await requestWorkerStart(needle);
|
|
914
|
+
if (startRequested) {
|
|
915
|
+
for (let i = 0;i < WAKE_POLL_ATTEMPTS; i++) {
|
|
916
|
+
await sleep(WAKE_POLL_MS);
|
|
917
|
+
const again = resolveWorkerTargets(await listTargets(), needle);
|
|
918
|
+
if (again.matches.length > 1)
|
|
919
|
+
throw new CdpError(workerAmbiguityMessage(needle, again.matches));
|
|
920
|
+
if (again.matches.length === 1)
|
|
921
|
+
return again.matches[0];
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
const final = resolveWorkerTargets(await listTargets(), needle);
|
|
925
|
+
throw new CdpError(workerMissMessage(needle, { wakeAttempted: true, liveWorkers: final.liveWorkers, registeredScopes: scopes }));
|
|
926
|
+
}
|
|
927
|
+
|
|
654
928
|
// src/tools/network_mock.ts
|
|
655
929
|
function escapeRegExpChar(ch) {
|
|
656
930
|
return /[.*+?^${}()|[\]\\]/.test(ch) ? `\\${ch}` : ch;
|
|
@@ -1132,7 +1406,8 @@ var CDP_CAPABILITIES = new Set([
|
|
|
1132
1406
|
"input.raw",
|
|
1133
1407
|
"input.html5Drag",
|
|
1134
1408
|
"browser.downloads",
|
|
1135
|
-
"browser.permissions"
|
|
1409
|
+
"browser.permissions",
|
|
1410
|
+
"worker.targets"
|
|
1136
1411
|
]);
|
|
1137
1412
|
|
|
1138
1413
|
class CdpPageDriver {
|
|
@@ -1700,6 +1975,10 @@ class CdpBrowserDriver {
|
|
|
1700
1975
|
await withBrowserConn((conn) => conn.send("Target.activateTarget", { targetId: target.id }));
|
|
1701
1976
|
return { id: target.id, url: target.url, title: target.title };
|
|
1702
1977
|
}
|
|
1978
|
+
async resolveWorkerTarget(selector, opts) {
|
|
1979
|
+
const target = await resolveWorkerSelector(selector, opts).catch(noSuchTarget);
|
|
1980
|
+
return { id: target.id, url: target.url, title: target.title, type: target.type };
|
|
1981
|
+
}
|
|
1703
1982
|
async page(selector) {
|
|
1704
1983
|
const { conn, target } = await openPage(selector).catch(noSuchTarget);
|
|
1705
1984
|
return new CdpPageDriver(conn, target, this);
|
|
@@ -1786,111 +2065,6 @@ function createCdpDriver() {
|
|
|
1786
2065
|
return new CdpBrowserDriver;
|
|
1787
2066
|
}
|
|
1788
2067
|
|
|
1789
|
-
// src/origins.ts
|
|
1790
|
-
import { mkdir as mkdir2, readFile as readFile2, readdir as readdir2, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
|
|
1791
|
-
import { join as join2 } from "node:path";
|
|
1792
|
-
function safeId2(id) {
|
|
1793
|
-
return id.replace(/[^A-Za-z0-9._-]/g, "_");
|
|
1794
|
-
}
|
|
1795
|
-
function originFile(backend, targetId) {
|
|
1796
|
-
return join2(leaseDir(), `origin-${backend}-${safeId2(targetId)}.json`);
|
|
1797
|
-
}
|
|
1798
|
-
var ORIGIN_FILE_RE = /^origin-(chrome|firefox)-(.+)\.json$/;
|
|
1799
|
-
async function recordOrigin(backend, targetId, opts = {}) {
|
|
1800
|
-
const record = {
|
|
1801
|
-
backend,
|
|
1802
|
-
targetId,
|
|
1803
|
-
label: typeof opts.label === "string" && opts.label.length ? opts.label : defaultLabel(),
|
|
1804
|
-
pid: process.pid,
|
|
1805
|
-
createdAt: opts.now ?? Date.now()
|
|
1806
|
-
};
|
|
1807
|
-
const file = originFile(backend, targetId);
|
|
1808
|
-
try {
|
|
1809
|
-
await mkdir2(leaseDir(), { recursive: true });
|
|
1810
|
-
try {
|
|
1811
|
-
await writeFile2(file, JSON.stringify(record), { flag: "wx" });
|
|
1812
|
-
return;
|
|
1813
|
-
} catch (err) {
|
|
1814
|
-
if (err.code !== "EEXIST")
|
|
1815
|
-
throw err;
|
|
1816
|
-
}
|
|
1817
|
-
await unlink2(file).catch(() => {
|
|
1818
|
-
return;
|
|
1819
|
-
});
|
|
1820
|
-
await writeFile2(file, JSON.stringify(record), { flag: "wx" });
|
|
1821
|
-
} catch {}
|
|
1822
|
-
}
|
|
1823
|
-
async function readOrigin(backend, targetId) {
|
|
1824
|
-
let raw;
|
|
1825
|
-
try {
|
|
1826
|
-
raw = await readFile2(originFile(backend, targetId), "utf8");
|
|
1827
|
-
} catch {
|
|
1828
|
-
return;
|
|
1829
|
-
}
|
|
1830
|
-
try {
|
|
1831
|
-
const rec = JSON.parse(raw);
|
|
1832
|
-
if (typeof rec?.targetId === "string" && typeof rec?.label === "string" && typeof rec?.createdAt === "number")
|
|
1833
|
-
return rec;
|
|
1834
|
-
} catch {}
|
|
1835
|
-
return;
|
|
1836
|
-
}
|
|
1837
|
-
async function listOrigins(opts = {}) {
|
|
1838
|
-
let names = [];
|
|
1839
|
-
try {
|
|
1840
|
-
names = await readdir2(leaseDir());
|
|
1841
|
-
} catch {
|
|
1842
|
-
return [];
|
|
1843
|
-
}
|
|
1844
|
-
const live = opts.liveIds === undefined ? undefined : new Set(opts.liveIds.map((id) => safeId2(id)));
|
|
1845
|
-
const out = [];
|
|
1846
|
-
for (const name of names) {
|
|
1847
|
-
const parts = ORIGIN_FILE_RE.exec(name);
|
|
1848
|
-
if (!parts)
|
|
1849
|
-
continue;
|
|
1850
|
-
const backend = parts[1];
|
|
1851
|
-
const nameId = parts[2];
|
|
1852
|
-
const scoped = live !== undefined && (opts.liveBackend === undefined || opts.liveBackend === backend);
|
|
1853
|
-
if (scoped && !live.has(nameId)) {
|
|
1854
|
-
await unlink2(join2(leaseDir(), name)).catch(() => {
|
|
1855
|
-
return;
|
|
1856
|
-
});
|
|
1857
|
-
continue;
|
|
1858
|
-
}
|
|
1859
|
-
const fromName = { backend, targetId: nameId, label: "", pid: 0, createdAt: 0 };
|
|
1860
|
-
let rec;
|
|
1861
|
-
try {
|
|
1862
|
-
rec = JSON.parse(await readFile2(join2(leaseDir(), name), "utf8"));
|
|
1863
|
-
} catch (err) {
|
|
1864
|
-
const code = err.code;
|
|
1865
|
-
if (code === "ENOENT")
|
|
1866
|
-
continue;
|
|
1867
|
-
out.push({ ...fromName, unreadable: code ?? "unparseable" });
|
|
1868
|
-
continue;
|
|
1869
|
-
}
|
|
1870
|
-
if (typeof rec?.targetId !== "string" || typeof rec?.label !== "string" || typeof rec?.createdAt !== "number") {
|
|
1871
|
-
out.push({ ...fromName, unreadable: "unparseable" });
|
|
1872
|
-
continue;
|
|
1873
|
-
}
|
|
1874
|
-
out.push({ backend: rec.backend, targetId: rec.targetId, label: rec.label, pid: rec.pid, createdAt: rec.createdAt });
|
|
1875
|
-
}
|
|
1876
|
-
return out;
|
|
1877
|
-
}
|
|
1878
|
-
async function originIndex(backend, liveIds) {
|
|
1879
|
-
const rows = await listOrigins({ liveIds, liveBackend: backend }).catch(() => []);
|
|
1880
|
-
const index = new Map;
|
|
1881
|
-
for (const row of rows) {
|
|
1882
|
-
if (row.backend !== backend)
|
|
1883
|
-
continue;
|
|
1884
|
-
index.set(row.targetId, row);
|
|
1885
|
-
}
|
|
1886
|
-
return index;
|
|
1887
|
-
}
|
|
1888
|
-
async function newTrackedPage(driver, backend, opts = {}) {
|
|
1889
|
-
const page = await driver.newPage(opts.url);
|
|
1890
|
-
await recordOrigin(backend, page.id, { label: opts.label });
|
|
1891
|
-
return page;
|
|
1892
|
-
}
|
|
1893
|
-
|
|
1894
2068
|
// src/reap.ts
|
|
1895
2069
|
function staleAgentTabs(input) {
|
|
1896
2070
|
const live = new Set(input.livePageIds);
|
|
@@ -1991,6 +2165,11 @@ async function pickPage(driver, pages, selector) {
|
|
|
1991
2165
|
throw new SharedToolError(`no page title containing '${needle}'`);
|
|
1992
2166
|
return p;
|
|
1993
2167
|
}
|
|
2168
|
+
if (selector.startsWith("label:"))
|
|
2169
|
+
return pickByLabel(driver, pages, selector.slice(6));
|
|
2170
|
+
if (isWorkerSelector(selector)) {
|
|
2171
|
+
throw new SharedToolError(backendOf(driver) === "firefox" ? WORKER_SELECTOR_UNSUPPORTED_MESSAGE : WORKER_SELECTOR_PAGE_ONLY_MESSAGE);
|
|
2172
|
+
}
|
|
1994
2173
|
const exactPage = pages.find((x) => x.id === selector);
|
|
1995
2174
|
if (exactPage)
|
|
1996
2175
|
return exactPage;
|
|
@@ -2000,6 +2179,18 @@ async function pickPage(driver, pages, selector) {
|
|
|
2000
2179
|
return exact;
|
|
2001
2180
|
throw new SharedToolError(`no target with id '${selector}'`);
|
|
2002
2181
|
}
|
|
2182
|
+
async function pickByLabel(driver, pages, label) {
|
|
2183
|
+
const { matchIds, knownLabels } = await resolveLiveLabel(backendOf(driver), label, pages.map((x) => x.id));
|
|
2184
|
+
if (matchIds.length > 1) {
|
|
2185
|
+
throw new SharedToolError(`label 'label:${label}' matches more than one live target: ${matchIds.join(", ")}. Resolve by target id instead.`);
|
|
2186
|
+
}
|
|
2187
|
+
if (matchIds.length === 1) {
|
|
2188
|
+
const p = pages.find((x) => x.id === matchIds[0]);
|
|
2189
|
+
if (p)
|
|
2190
|
+
return p;
|
|
2191
|
+
}
|
|
2192
|
+
throw new SharedToolError(knownLabels.length ? `no live target with label '${label}' (labels currently in use: ${knownLabels.join(", ")})` : `no live target with label '${label}' (no labels are currently assigned to any open target)`);
|
|
2193
|
+
}
|
|
2003
2194
|
function locatorOf(args) {
|
|
2004
2195
|
const hasUid = args.uid !== undefined && args.uid !== null && args.uid !== "";
|
|
2005
2196
|
const hasSelector = typeof args.selector === "string" && args.selector.length > 0;
|
|
@@ -2141,11 +2332,29 @@ async function writeJsonSink(savePath, value) {
|
|
|
2141
2332
|
function sinkRequested(savePath) {
|
|
2142
2333
|
return savePath !== undefined && savePath !== "";
|
|
2143
2334
|
}
|
|
2335
|
+
var EXPRESSION_ALIAS_KEYS = ["function", "code", "js", "script", "fn", "body"];
|
|
2336
|
+
async function resolveWorkerSelectorFor(driver, selector, wake) {
|
|
2337
|
+
if (!driver.capabilities.has("worker.targets") || typeof driver.resolveWorkerTarget !== "function") {
|
|
2338
|
+
throw new SharedToolError(`evaluateScript: ${WORKER_SELECTOR_UNSUPPORTED_MESSAGE}`);
|
|
2339
|
+
}
|
|
2340
|
+
return driver.resolveWorkerTarget(selector, { wake });
|
|
2341
|
+
}
|
|
2144
2342
|
async function evaluateScript(driver, args) {
|
|
2145
2343
|
if (typeof args.expression !== "string" || args.expression.length === 0) {
|
|
2344
|
+
const wrongKey = EXPRESSION_ALIAS_KEYS.find((k) => args[k] !== undefined);
|
|
2345
|
+
if (wrongKey !== undefined) {
|
|
2346
|
+
throw new SharedToolError(`evaluateScript: you passed '${wrongKey}'; the key is 'expression' — function literals go in 'expression', invoked with 'args'.`);
|
|
2347
|
+
}
|
|
2146
2348
|
throw new SharedToolError("evaluateScript: 'expression' must be a non-empty string");
|
|
2147
2349
|
}
|
|
2148
|
-
|
|
2350
|
+
if (args.wake !== undefined && typeof args.wake !== "boolean") {
|
|
2351
|
+
throw new SharedToolError("evaluateScript: 'wake' must be a boolean");
|
|
2352
|
+
}
|
|
2353
|
+
if (args.wake !== undefined && !isWorkerSelector(args.target)) {
|
|
2354
|
+
throw new SharedToolError("evaluateScript: 'wake' only applies to a target of the form 'worker:<substring>'; a page target is never asleep.");
|
|
2355
|
+
}
|
|
2356
|
+
const target = isWorkerSelector(args.target) ? (await resolveWorkerSelectorFor(driver, args.target, args.wake ?? true)).id : args.target;
|
|
2357
|
+
return withPage2(driver, target, async (page) => {
|
|
2149
2358
|
const value = await page.evaluate(args.expression, { args: args.args, awaitPromise: args.awaitPromise ?? true });
|
|
2150
2359
|
if (!sinkRequested(args.savePath))
|
|
2151
2360
|
return value;
|
|
@@ -2509,7 +2718,7 @@ async function claimPage(driver, args = {}) {
|
|
|
2509
2718
|
const hasTarget = typeof args.target === "string" && args.target.length > 0;
|
|
2510
2719
|
const hasTargetId = typeof args.targetId === "string" && args.targetId.length > 0;
|
|
2511
2720
|
if (hasTarget && hasTargetId) {
|
|
2512
|
-
throw new LeaseToolError("claim_page takes at most one of 'target' (any selector: active | index:N | url:<substr> | title:<substr> | <targetId>) or 'targetId' (an exact target id, kept for back-compat). Pass 'target' alone to claim an open tab, or neither to open a fresh one.");
|
|
2721
|
+
throw new LeaseToolError("claim_page takes at most one of 'target' (any selector: active | index:N | url:<substr> | title:<substr> | label:<name> | <targetId>) or 'targetId' (an exact target id, kept for back-compat). Pass 'target' alone to claim an open tab, or neither to open a fresh one.");
|
|
2513
2722
|
}
|
|
2514
2723
|
const backend = backendOf2(driver);
|
|
2515
2724
|
const label = typeof args.label === "string" && args.label.length ? args.label : defaultLabel();
|