cdp-toolkit 3.2.0 → 3.4.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 +31 -0
- package/CONTRACT.md +1 -1
- package/README.md +35 -19
- package/dist/bidi/mux-daemon.js +263 -24
- package/dist/cli.js +633 -80
- package/dist/index.js +144 -38
- package/dist/mcp.js +641 -85
- package/package.json +1 -1
- package/src/bidi/driver.ts +367 -60
- package/src/bidi/protocol.ts +27 -9
- package/src/bidi-browser-tools.ts +366 -0
- package/src/bidi-tools.ts +29 -2
- package/src/cdp/driver.ts +119 -18
- package/src/driver.ts +42 -10
- package/src/firefox-tools.ts +6 -3
- package/src/frontApp.ts +62 -0
- package/src/leases-tools.ts +3 -2
- package/src/manifest.ts +17 -5
- package/src/origins.ts +3 -2
- package/src/policy.ts +4 -3
- package/src/shared-tools.ts +47 -24
- package/src/toolDocs.ts +18 -15
- package/src/tools/dispatch-mouse.ts +6 -1
- package/src/tools/downloads.ts +5 -6
- package/src/tools/permissions.ts +5 -5
- package/src/version.ts +1 -1
package/dist/cli.js
CHANGED
|
@@ -687,7 +687,7 @@ async function originIndex(backend, liveIds) {
|
|
|
687
687
|
return index;
|
|
688
688
|
}
|
|
689
689
|
async function newTrackedPage(driver, backend, opts = {}) {
|
|
690
|
-
const page = await driver.newPage(opts.url);
|
|
690
|
+
const page = await driver.newPage(opts.url, { focus: opts.focus === true });
|
|
691
691
|
await recordOrigin(backend, page.id, { label: opts.label });
|
|
692
692
|
return page;
|
|
693
693
|
}
|
|
@@ -1297,6 +1297,53 @@ var init_client = __esm(() => {
|
|
|
1297
1297
|
knownTransports = new Map;
|
|
1298
1298
|
});
|
|
1299
1299
|
|
|
1300
|
+
// src/frontApp.ts
|
|
1301
|
+
import { execFile } from "node:child_process";
|
|
1302
|
+
function run(cmd, args) {
|
|
1303
|
+
return new Promise((resolve) => {
|
|
1304
|
+
execFile(cmd, args, { timeout: 2000 }, (err, stdout) => resolve(err ? "" : String(stdout)));
|
|
1305
|
+
});
|
|
1306
|
+
}
|
|
1307
|
+
function restoreFrontAppEnabled(platform = process.platform) {
|
|
1308
|
+
return platform === "darwin" && (process.env.CDP_RESTORE_FRONT_APP ?? "").trim() !== "0";
|
|
1309
|
+
}
|
|
1310
|
+
async function keepFrontApp(fn, opts = {}) {
|
|
1311
|
+
const enabled = opts.enabled ?? restoreFrontAppEnabled();
|
|
1312
|
+
if (!enabled)
|
|
1313
|
+
return fn();
|
|
1314
|
+
const ops = opts.ops ?? macFrontAppOps;
|
|
1315
|
+
const before = await ops.front().catch(() => null);
|
|
1316
|
+
const result = await fn();
|
|
1317
|
+
if (before === null)
|
|
1318
|
+
return result;
|
|
1319
|
+
const fix = async () => {
|
|
1320
|
+
const now = await ops.front().catch(() => null);
|
|
1321
|
+
if (now !== null && now !== before)
|
|
1322
|
+
await ops.setFront(before).catch(() => {
|
|
1323
|
+
return;
|
|
1324
|
+
});
|
|
1325
|
+
};
|
|
1326
|
+
await fix();
|
|
1327
|
+
await new Promise((r) => setTimeout(r, opts.recheckMs ?? 250));
|
|
1328
|
+
await fix();
|
|
1329
|
+
return result;
|
|
1330
|
+
}
|
|
1331
|
+
var macFrontAppOps;
|
|
1332
|
+
var init_frontApp = __esm(() => {
|
|
1333
|
+
macFrontAppOps = {
|
|
1334
|
+
async front() {
|
|
1335
|
+
const asn = (await run("lsappinfo", ["front"])).trim();
|
|
1336
|
+
if (!asn)
|
|
1337
|
+
return null;
|
|
1338
|
+
const m = /"?pid"?\s*=\s*(\d+)/.exec(await run("lsappinfo", ["info", "-only", "pid", asn]));
|
|
1339
|
+
return m ? Number(m[1]) : null;
|
|
1340
|
+
},
|
|
1341
|
+
async setFront(pid) {
|
|
1342
|
+
await run("osascript", ["-e", `tell application "System Events" to set frontmost of (first process whose unix id is ${pid}) to true`]);
|
|
1343
|
+
}
|
|
1344
|
+
};
|
|
1345
|
+
});
|
|
1346
|
+
|
|
1300
1347
|
// src/activity.ts
|
|
1301
1348
|
function dispatchKey(backend, targetId) {
|
|
1302
1349
|
return `${backend}:${targetId}`;
|
|
@@ -3000,6 +3047,8 @@ function mapBidiError(e) {
|
|
|
3000
3047
|
return driverError2("disconnected", e.message);
|
|
3001
3048
|
if (code === "unsupported operation")
|
|
3002
3049
|
return driverError2("unsupported", e.message);
|
|
3050
|
+
if (code === "unknown command")
|
|
3051
|
+
return driverError2("unsupported", `${e.message} (this Firefox predates that WebDriver BiDi command; see BIDI_CAPABILITY_MIN_FIREFOX for the version each capability needs)`);
|
|
3003
3052
|
if (!code && /timed out/i.test(e.message))
|
|
3004
3053
|
return driverError2("timeout", e.message);
|
|
3005
3054
|
if (!code && /(disposed|not open|connection closed)/i.test(e.message))
|
|
@@ -3153,6 +3202,69 @@ async function resolveElementLocator2(conn, contextId, loc) {
|
|
|
3153
3202
|
throw driverError2("no-such-element", `text '${loc.text}' matched no element`);
|
|
3154
3203
|
return sharedRefOf(nodes[0], `text '${loc.text}'`);
|
|
3155
3204
|
}
|
|
3205
|
+
function modifierKeyValues(mods) {
|
|
3206
|
+
const out = [];
|
|
3207
|
+
for (const m of mods ?? []) {
|
|
3208
|
+
const v = MODIFIER_VALUES[m.toLowerCase()];
|
|
3209
|
+
if (v === undefined)
|
|
3210
|
+
throw driverError2("page-error", `unknown modifier '${m}' (use Alt, Control, Meta, or Shift)`);
|
|
3211
|
+
if (!out.includes(v))
|
|
3212
|
+
out.push(v);
|
|
3213
|
+
}
|
|
3214
|
+
return out;
|
|
3215
|
+
}
|
|
3216
|
+
function modifierChord(pointerId, actions, keys) {
|
|
3217
|
+
const pointer = actions;
|
|
3218
|
+
if (keys.length === 0)
|
|
3219
|
+
return [{ type: "pointer", id: pointerId, actions: pointer }];
|
|
3220
|
+
const k = keys.length;
|
|
3221
|
+
const pause = () => ({ type: "pause" });
|
|
3222
|
+
const keyActions = [
|
|
3223
|
+
...keys.map((v) => ({ type: "keyDown", value: v })),
|
|
3224
|
+
...pointer.map(pause),
|
|
3225
|
+
...[...keys].reverse().map((v) => ({ type: "keyUp", value: v }))
|
|
3226
|
+
];
|
|
3227
|
+
const pointerActions = [
|
|
3228
|
+
...Array.from({ length: k }, pause),
|
|
3229
|
+
...pointer,
|
|
3230
|
+
...Array.from({ length: k }, pause)
|
|
3231
|
+
];
|
|
3232
|
+
return [
|
|
3233
|
+
{ type: "key", id: "cdp-keyboard", actions: keyActions },
|
|
3234
|
+
{ type: "pointer", id: pointerId, actions: pointerActions }
|
|
3235
|
+
];
|
|
3236
|
+
}
|
|
3237
|
+
function firefoxMajor(conn) {
|
|
3238
|
+
const v = conn.capabilities?.browserVersion;
|
|
3239
|
+
if (typeof v !== "string")
|
|
3240
|
+
return;
|
|
3241
|
+
const major = Number.parseInt(v, 10);
|
|
3242
|
+
return Number.isFinite(major) ? major : undefined;
|
|
3243
|
+
}
|
|
3244
|
+
function requireFirefox(conn, token) {
|
|
3245
|
+
const min = BIDI_CAPABILITY_MIN_FIREFOX[token];
|
|
3246
|
+
if (min === undefined)
|
|
3247
|
+
return;
|
|
3248
|
+
const major = firefoxMajor(conn);
|
|
3249
|
+
if (major !== undefined && major < min) {
|
|
3250
|
+
const v = conn.capabilities.browserVersion;
|
|
3251
|
+
throw driverError2("unsupported", `${token} needs Firefox ${min} or newer; this Firefox is ${v}.`);
|
|
3252
|
+
}
|
|
3253
|
+
}
|
|
3254
|
+
async function armPostHocBodies(conn) {
|
|
3255
|
+
if (process.env.CDP_FIREFOX_BODY_COLLECTOR === "off")
|
|
3256
|
+
return;
|
|
3257
|
+
try {
|
|
3258
|
+
requireFirefox(conn, "network.responseBodyPostHoc");
|
|
3259
|
+
} catch {
|
|
3260
|
+
return;
|
|
3261
|
+
}
|
|
3262
|
+
try {
|
|
3263
|
+
await conn.send("network.addDataCollector", { dataTypes: ["response"], maxEncodedDataSize: POST_HOC_BODY_MAX_BYTES });
|
|
3264
|
+
} catch (e) {
|
|
3265
|
+
console.error(`[cdp-toolkit] firefox response-body collector not armed: ${e instanceof Error ? e.message : String(e)}`);
|
|
3266
|
+
}
|
|
3267
|
+
}
|
|
3156
3268
|
function bumpEpoch(endpoint, conn) {
|
|
3157
3269
|
sessionEpochs.set(endpoint, (sessionEpochs.get(endpoint) ?? 0) + 1);
|
|
3158
3270
|
connEndpoints.set(conn, endpoint);
|
|
@@ -3350,6 +3462,7 @@ async function getConnection(endpoint, timeoutMs, attached = false) {
|
|
|
3350
3462
|
}
|
|
3351
3463
|
connections.set(endpoint, conn);
|
|
3352
3464
|
bumpEpoch(endpoint, conn);
|
|
3465
|
+
await armPostHocBodies(conn);
|
|
3353
3466
|
if (muxMode(attached) !== "off") {
|
|
3354
3467
|
try {
|
|
3355
3468
|
const mux = await startBidiMux(conn);
|
|
@@ -3440,6 +3553,9 @@ async function pickContext(conn, contexts, selector) {
|
|
|
3440
3553
|
return exact;
|
|
3441
3554
|
throw driverError2("no-such-target", `no context matching '${selector}'`);
|
|
3442
3555
|
}
|
|
3556
|
+
function bidiCreateTabParams(opts) {
|
|
3557
|
+
return { type: "tab", background: opts?.focus !== true };
|
|
3558
|
+
}
|
|
3443
3559
|
|
|
3444
3560
|
class BidiBrowserDriver {
|
|
3445
3561
|
endpoint;
|
|
@@ -3466,12 +3582,13 @@ class BidiBrowserDriver {
|
|
|
3466
3582
|
conn.release();
|
|
3467
3583
|
}
|
|
3468
3584
|
}
|
|
3469
|
-
async newPage(url) {
|
|
3585
|
+
async newPage(url, opts) {
|
|
3470
3586
|
const conn = await getConnection(this.endpoint, this.timeoutMs, this.attached);
|
|
3471
3587
|
try {
|
|
3472
|
-
const
|
|
3588
|
+
const create = () => conn.send("browsingContext.create", bidiCreateTabParams(opts)).catch((e) => {
|
|
3473
3589
|
throw mapBidiError(e);
|
|
3474
3590
|
});
|
|
3591
|
+
const { context } = opts?.focus === true ? await create() : await keepFrontApp(create);
|
|
3475
3592
|
if (url)
|
|
3476
3593
|
await conn.send("browsingContext.navigate", { context, url, wait: "complete" }).catch((e) => {
|
|
3477
3594
|
throw mapBidiError(e);
|
|
@@ -3484,9 +3601,9 @@ class BidiBrowserDriver {
|
|
|
3484
3601
|
async closePage(id) {
|
|
3485
3602
|
const conn = await getConnection(this.endpoint, this.timeoutMs, this.attached);
|
|
3486
3603
|
try {
|
|
3487
|
-
await conn.send("browsingContext.close", { context: id }).catch((e) => {
|
|
3604
|
+
await keepFrontApp(() => conn.send("browsingContext.close", { context: id }).catch((e) => {
|
|
3488
3605
|
throw mapBidiError(e);
|
|
3489
|
-
});
|
|
3606
|
+
}));
|
|
3490
3607
|
return { success: true };
|
|
3491
3608
|
} finally {
|
|
3492
3609
|
conn.release();
|
|
@@ -3565,7 +3682,35 @@ class BidiBrowserDriver {
|
|
|
3565
3682
|
conn.release();
|
|
3566
3683
|
}
|
|
3567
3684
|
}
|
|
3685
|
+
async withBrowserConnection(fn) {
|
|
3686
|
+
const conn = await getConnection(this.endpoint, this.timeoutMs, this.attached);
|
|
3687
|
+
try {
|
|
3688
|
+
return await fn(conn);
|
|
3689
|
+
} finally {
|
|
3690
|
+
conn.release();
|
|
3691
|
+
}
|
|
3692
|
+
}
|
|
3693
|
+
setDisposeHook(key, hook) {
|
|
3694
|
+
let hooks = disposeHooks.get(this.endpoint);
|
|
3695
|
+
if (!hooks) {
|
|
3696
|
+
hooks = new Map;
|
|
3697
|
+
disposeHooks.set(this.endpoint, hooks);
|
|
3698
|
+
}
|
|
3699
|
+
if (hook)
|
|
3700
|
+
hooks.set(key, hook);
|
|
3701
|
+
else
|
|
3702
|
+
hooks.delete(key);
|
|
3703
|
+
}
|
|
3568
3704
|
async dispose() {
|
|
3705
|
+
const hooks = disposeHooks.get(this.endpoint);
|
|
3706
|
+
disposeHooks.delete(this.endpoint);
|
|
3707
|
+
const live = connections.get(this.endpoint);
|
|
3708
|
+
if (hooks && live) {
|
|
3709
|
+
for (const hook of hooks.values())
|
|
3710
|
+
await hook(live).catch(() => {
|
|
3711
|
+
return;
|
|
3712
|
+
});
|
|
3713
|
+
}
|
|
3569
3714
|
for (const key of [...bidiBeaconScripts.keys()]) {
|
|
3570
3715
|
if (key.startsWith(`${this.endpoint}:`))
|
|
3571
3716
|
bidiBeaconScripts.delete(key);
|
|
@@ -3640,8 +3785,9 @@ async function hostFirefoxMux(endpoint, opts = {}) {
|
|
|
3640
3785
|
function createFirefoxDriverForEndpoint(wsUrl, opts) {
|
|
3641
3786
|
return new BidiBrowserDriver(wsUrl, opts?.timeoutMs, true);
|
|
3642
3787
|
}
|
|
3643
|
-
var LINE_RE, INTERACTIVE_ROLES3, STAMP_ONE_SOURCE, KEY_VALUES, MODIFIER_VALUES, BUTTON_CODES, ARM_SCROLL_SETTLE_WATCH_SOURCE, AWAIT_SCROLL_SETTLE_SOURCE = "function(){return window.__cdpScrollSettle;}", BIDI_CAPABILITIES, connections, slotHandles, muxes, joined, connecting, sessionEpochs, connEndpoints, STALE_ID_HINT, sleep3 = (ms) => new Promise((r) => setTimeout(r, ms)), slotLabelOverride, bidiBeaconScripts, BidiPageDriver;
|
|
3788
|
+
var LINE_RE, INTERACTIVE_ROLES3, STAMP_ONE_SOURCE, KEY_VALUES, MODIFIER_VALUES, BUTTON_CODES, RAW_MOUSE_SOURCE_ID = "cdp-raw-mouse", ARM_SCROLL_SETTLE_WATCH_SOURCE, AWAIT_SCROLL_SETTLE_SOURCE = "function(){return window.__cdpScrollSettle;}", BIDI_CAPABILITY_MIN_FIREFOX, POST_HOC_BODY_MAX_BYTES, BIDI_CAPABILITIES, connections, slotHandles, muxes, joined, connecting, sessionEpochs, connEndpoints, disposeHooks, STALE_ID_HINT, sleep3 = (ms) => new Promise((r) => setTimeout(r, ms)), slotLabelOverride, bidiBeaconScripts, BidiPageDriver;
|
|
3644
3789
|
var init_driver2 = __esm(() => {
|
|
3790
|
+
init_frontApp();
|
|
3645
3791
|
init_driver();
|
|
3646
3792
|
init_leases();
|
|
3647
3793
|
init_origins();
|
|
@@ -3695,13 +3841,25 @@ var init_driver2 = __esm(() => {
|
|
|
3695
3841
|
MODIFIER_VALUES = { shift: "", control: "", ctrl: "", alt: "", meta: "", cmd: "", command: "" };
|
|
3696
3842
|
BUTTON_CODES = { left: 0, middle: 1, right: 2 };
|
|
3697
3843
|
ARM_SCROLL_SETTLE_WATCH_SOURCE = "function(){window.__cdpScrollSettle=new Promise((resolve)=>{let t;const done=()=>{window.removeEventListener('scroll',on,true);resolve(true);};" + "const on=()=>{clearTimeout(t);t=setTimeout(done,60);};window.addEventListener('scroll',on,true);t=setTimeout(done,60);setTimeout(done,500);});}";
|
|
3844
|
+
BIDI_CAPABILITY_MIN_FIREFOX = {
|
|
3845
|
+
"browser.downloads": 160,
|
|
3846
|
+
"browser.permissions": 160,
|
|
3847
|
+
"emulate.mediaFeatures": 160,
|
|
3848
|
+
"emulate.networkConditions": 160,
|
|
3849
|
+
"input.raw": 160,
|
|
3850
|
+
"input.modifierClick": 160,
|
|
3851
|
+
"network.responseBodyPostHoc": 160,
|
|
3852
|
+
"screenshot.scale": 160
|
|
3853
|
+
};
|
|
3854
|
+
POST_HOC_BODY_MAX_BYTES = 2 * 1024 * 1024;
|
|
3698
3855
|
BIDI_CAPABILITIES = new Set([
|
|
3699
3856
|
"emulate.deviceMetrics",
|
|
3700
3857
|
"screenshot.fullPage",
|
|
3701
3858
|
"screenshot.element",
|
|
3702
3859
|
"screenshot.renderSize",
|
|
3703
3860
|
"network.intercept",
|
|
3704
|
-
"locate.xpath"
|
|
3861
|
+
"locate.xpath",
|
|
3862
|
+
...Object.keys(BIDI_CAPABILITY_MIN_FIREFOX)
|
|
3705
3863
|
]);
|
|
3706
3864
|
connections = new Map;
|
|
3707
3865
|
slotHandles = new Map;
|
|
@@ -3710,6 +3868,7 @@ var init_driver2 = __esm(() => {
|
|
|
3710
3868
|
connecting = new Map;
|
|
3711
3869
|
sessionEpochs = new Map;
|
|
3712
3870
|
connEndpoints = new WeakMap;
|
|
3871
|
+
disposeHooks = new Map;
|
|
3713
3872
|
STALE_ID_HINT = " — the Firefox BiDi session was re-established after its previous holder went away, and Firefox " + "assigns new context ids per session — re-resolve the tab with list_pages (url:/title: selectors) " + "and claim it again";
|
|
3714
3873
|
bidiBeaconScripts = new Map;
|
|
3715
3874
|
BidiPageDriver = class BidiPageDriver {
|
|
@@ -3876,18 +4035,30 @@ var init_driver2 = __esm(() => {
|
|
|
3876
4035
|
return { x, y };
|
|
3877
4036
|
}
|
|
3878
4037
|
async click(loc, opts) {
|
|
3879
|
-
|
|
3880
|
-
|
|
3881
|
-
|
|
4038
|
+
const hasModifiers = !!opts?.modifiers && opts.modifiers.length > 0;
|
|
4039
|
+
if (hasModifiers)
|
|
4040
|
+
requireFirefox(this.conn, "input.modifierClick");
|
|
4041
|
+
const keys = modifierKeyValues(opts?.modifiers);
|
|
3882
4042
|
const ref = await resolveElementLocator2(this.conn, this.contextId, loc);
|
|
3883
4043
|
const { x, y } = await this.centerOf(ref);
|
|
3884
4044
|
const button = BUTTON_CODES[opts?.button ?? "left"];
|
|
3885
4045
|
const actions = [{ type: "pointerMove", x, y, duration: 0 }];
|
|
3886
4046
|
for (let i = 0;i < (opts?.clickCount ?? 1); i++)
|
|
3887
4047
|
actions.push({ type: "pointerDown", button }, { type: "pointerUp", button });
|
|
3888
|
-
await this.performActions(
|
|
4048
|
+
await this.performActions(modifierChord("cdp-mouse", actions, keys));
|
|
3889
4049
|
return { x, y };
|
|
3890
4050
|
}
|
|
4051
|
+
async dispatchMouse(event) {
|
|
4052
|
+
requireFirefox(this.conn, "input.raw");
|
|
4053
|
+
const keys = modifierKeyValues(event.modifiers);
|
|
4054
|
+
const button = BUTTON_CODES[event.button ?? "left"];
|
|
4055
|
+
const actions = [{ type: "pointerMove", x: event.x, y: event.y, duration: 0 }];
|
|
4056
|
+
if (event.action === "down")
|
|
4057
|
+
actions.push({ type: "pointerDown", button });
|
|
4058
|
+
else if (event.action === "up")
|
|
4059
|
+
actions.push({ type: "pointerUp", button });
|
|
4060
|
+
await this.performActions(modifierChord(RAW_MOUSE_SOURCE_ID, actions, keys));
|
|
4061
|
+
}
|
|
3891
4062
|
async scroll(anchor, opts) {
|
|
3892
4063
|
const { x, y } = await this.resolveScrollPoint(anchor);
|
|
3893
4064
|
const deltaX = Math.round(opts.deltaX ?? 0);
|
|
@@ -3958,8 +4129,11 @@ var init_driver2 = __esm(() => {
|
|
|
3958
4129
|
await this.callFunctionValue(BidiPageDriver.INSERT_TEXT_SOURCE, [value, false], ref);
|
|
3959
4130
|
return;
|
|
3960
4131
|
}
|
|
3961
|
-
const clear = "function(){this.focus&&this.focus();if('value' in this){this.value='';this.dispatchEvent(new Event('input',{bubbles:true}));}}";
|
|
3962
|
-
await this.callFunctionValue(clear, [], ref);
|
|
4132
|
+
const clear = "function(){if(this.disabled||this.readOnly)return this.disabled?'disabled':'readonly';this.focus&&this.focus();if('value' in this){this.value='';this.dispatchEvent(new Event('input',{bubbles:true}));}return 'ok';}";
|
|
4133
|
+
const state = await this.callFunctionValue(clear, [], ref);
|
|
4134
|
+
if (state === "disabled" || state === "readonly") {
|
|
4135
|
+
throw driverError2("page-error", `cannot fill a ${state} field: it was left unchanged`);
|
|
4136
|
+
}
|
|
3963
4137
|
await this.sendKeys(value);
|
|
3964
4138
|
}
|
|
3965
4139
|
async typeText(loc, text) {
|
|
@@ -3996,11 +4170,23 @@ var init_driver2 = __esm(() => {
|
|
|
3996
4170
|
}
|
|
3997
4171
|
async screenshot(opts, _consumeBands) {
|
|
3998
4172
|
const renderSize = opts?.renderWidth !== undefined && opts?.renderHeight !== undefined ? { width: opts.renderWidth, height: opts.renderHeight } : undefined;
|
|
3999
|
-
|
|
4173
|
+
const scale = opts?.scale !== undefined && opts.scale !== 1 ? opts.scale : undefined;
|
|
4174
|
+
if (!renderSize && scale === undefined)
|
|
4000
4175
|
return this.capture(opts);
|
|
4176
|
+
if (scale !== undefined)
|
|
4177
|
+
requireFirefox(this.conn, "screenshot.scale");
|
|
4001
4178
|
const previous = await readViewportRecord(this.browser.scheme, this.contextId);
|
|
4179
|
+
let dprOverride;
|
|
4180
|
+
if (scale !== undefined) {
|
|
4181
|
+
const base = previous?.deviceScaleFactor ?? Number(await this.evaluate("window.devicePixelRatio").catch(() => 1));
|
|
4182
|
+
dprOverride = (Number.isFinite(base) && base > 0 ? base : 1) * scale;
|
|
4183
|
+
}
|
|
4002
4184
|
try {
|
|
4003
|
-
await this.conn.send("browsingContext.setViewport", {
|
|
4185
|
+
await this.conn.send("browsingContext.setViewport", {
|
|
4186
|
+
context: this.contextId,
|
|
4187
|
+
...renderSize ? { viewport: { width: renderSize.width, height: renderSize.height } } : {},
|
|
4188
|
+
...dprOverride !== undefined ? { devicePixelRatio: dprOverride } : {}
|
|
4189
|
+
});
|
|
4004
4190
|
} catch (e) {
|
|
4005
4191
|
throw mapBidiError(e);
|
|
4006
4192
|
}
|
|
@@ -4017,29 +4203,35 @@ var init_driver2 = __esm(() => {
|
|
|
4017
4203
|
await this.conn.send("browsingContext.setViewport", {
|
|
4018
4204
|
context: this.contextId,
|
|
4019
4205
|
viewport: { width: previous.width, height: previous.height },
|
|
4020
|
-
...previous.deviceScaleFactor != null ? { devicePixelRatio: previous.deviceScaleFactor } : {}
|
|
4206
|
+
...previous.deviceScaleFactor != null ? { devicePixelRatio: previous.deviceScaleFactor } : scale !== undefined ? { devicePixelRatio: null } : {}
|
|
4021
4207
|
});
|
|
4022
4208
|
} else {
|
|
4023
|
-
await this.conn.send("browsingContext.setViewport", {
|
|
4209
|
+
await this.conn.send("browsingContext.setViewport", {
|
|
4210
|
+
context: this.contextId,
|
|
4211
|
+
...renderSize ? { viewport: null } : {},
|
|
4212
|
+
...scale !== undefined ? { devicePixelRatio: null } : {}
|
|
4213
|
+
});
|
|
4024
4214
|
}
|
|
4025
4215
|
} catch (e) {
|
|
4026
4216
|
restoreError = e instanceof Error ? e.message : String(e);
|
|
4027
4217
|
}
|
|
4028
4218
|
if (!shot) {
|
|
4029
4219
|
if (restoreError !== undefined && captureError instanceof Error) {
|
|
4030
|
-
captureError.message = `${captureError.message} ${renderRestoreFailureNote(renderSize, restoreError)}`;
|
|
4220
|
+
captureError.message = renderSize ? `${captureError.message} ${renderRestoreFailureNote(renderSize, restoreError)}` : `${captureError.message} (and restoring the device pixel ratio failed too, the tab may still be emulated at ratio ${dprOverride}: ${restoreError})`;
|
|
4031
4221
|
}
|
|
4032
4222
|
throw captureError;
|
|
4033
4223
|
}
|
|
4224
|
+
if (!renderSize) {
|
|
4225
|
+
if (restoreError !== undefined)
|
|
4226
|
+
throw driverError2("page-error", `screenshot captured, but restoring the device pixel ratio failed (the tab may still be emulated at ratio ${dprOverride}): ${restoreError}`);
|
|
4227
|
+
return shot;
|
|
4228
|
+
}
|
|
4034
4229
|
const result = { ...shot, renderSize, renderRestored: restoreError === undefined };
|
|
4035
4230
|
if (restoreError !== undefined)
|
|
4036
4231
|
result.renderRestoreError = restoreError;
|
|
4037
4232
|
return result;
|
|
4038
4233
|
}
|
|
4039
4234
|
async capture(opts) {
|
|
4040
|
-
if (opts?.scale !== undefined && opts.scale !== 1) {
|
|
4041
|
-
throw driverError2("unsupported", `screenshot scale ${opts.scale} is not supported by this backend (WebDriver BiDi's ` + "browsingContext.captureScreenshot has no scale parameter). Call emulate with " + `deviceScaleFactor:${opts.scale} first and capture at scale 1, or use --browser chrome.`);
|
|
4042
|
-
}
|
|
4043
4235
|
if (opts?.tile === true) {
|
|
4044
4236
|
throw driverError2("unsupported", "screenshot tile:true is not supported by this backend: band tiling is declared only where the band " + "arithmetic has been measured against a real browser, and Firefox was not driven for it " + `(browsingContext.captureScreenshot's clip:{type:"box"} is the primitive it would ride, untested). ` + "Capture a smaller region or a single element, or use --browser chrome for a tiled capture.");
|
|
4045
4237
|
}
|
|
@@ -4067,10 +4259,29 @@ var init_driver2 = __esm(() => {
|
|
|
4067
4259
|
await this.conn.send("browsingContext.setViewport", { context: this.contextId, viewport: null, devicePixelRatio: null }).catch(() => {
|
|
4068
4260
|
return;
|
|
4069
4261
|
});
|
|
4262
|
+
await this.conn.send("emulation.setMediaFeaturesOverride", { features: null, contexts: [this.contextId] }).catch(() => {
|
|
4263
|
+
return;
|
|
4264
|
+
});
|
|
4265
|
+
await this.conn.send("emulation.setNetworkConditions", { networkConditions: null, contexts: [this.contextId] }).catch(() => {
|
|
4266
|
+
return;
|
|
4267
|
+
});
|
|
4070
4268
|
await clearViewportRecord(this.browser.scheme, this.contextId);
|
|
4071
4269
|
return { applied: [] };
|
|
4072
4270
|
}
|
|
4073
4271
|
const applied = [];
|
|
4272
|
+
if (opts.media != null && opts.media !== "") {
|
|
4273
|
+
throw driverError2("unsupported", `emulate media "${opts.media}": WebDriver BiDi's emulation.setMediaFeaturesOverride takes media features (prefers-color-scheme, ...) but has no print/screen media-type override. Use mediaFeatures, or --browser chrome for media type emulation.`);
|
|
4274
|
+
}
|
|
4275
|
+
const net = opts.networkConditions;
|
|
4276
|
+
if (net != null) {
|
|
4277
|
+
const throttled = (net.latency ?? 0) > 0 || (net.downloadThroughput ?? -1) >= 0 || (net.uploadThroughput ?? -1) >= 0;
|
|
4278
|
+
if (throttled) {
|
|
4279
|
+
throw driverError2("unsupported", 'emulate networkConditions: Firefox only emulates offline (emulation.setNetworkConditions has the single type "offline"); latency and download/upload throughput throttling are not available. Pass only {offline:true|false}, or use --browser chrome.');
|
|
4280
|
+
}
|
|
4281
|
+
requireFirefox(this.conn, "emulate.networkConditions");
|
|
4282
|
+
}
|
|
4283
|
+
if (opts.mediaFeatures != null)
|
|
4284
|
+
requireFirefox(this.conn, "emulate.mediaFeatures");
|
|
4074
4285
|
try {
|
|
4075
4286
|
if (opts.width != null && opts.height != null) {
|
|
4076
4287
|
await this.conn.send("browsingContext.setViewport", { context: this.contextId, viewport: { width: opts.width, height: opts.height }, ...opts.deviceScaleFactor != null ? { devicePixelRatio: opts.deviceScaleFactor } : {} });
|
|
@@ -4085,6 +4296,21 @@ var init_driver2 = __esm(() => {
|
|
|
4085
4296
|
await this.conn.send("emulation.setUserAgentOverride", { userAgent: opts.userAgent, contexts: [this.contextId] });
|
|
4086
4297
|
applied.push("userAgent");
|
|
4087
4298
|
}
|
|
4299
|
+
if (opts.mediaFeatures != null) {
|
|
4300
|
+
const features = Object.fromEntries(opts.mediaFeatures.map((f) => [f.name, f.value]));
|
|
4301
|
+
await this.conn.send("emulation.setMediaFeaturesOverride", {
|
|
4302
|
+
features: opts.mediaFeatures.length > 0 ? features : null,
|
|
4303
|
+
contexts: [this.contextId]
|
|
4304
|
+
});
|
|
4305
|
+
applied.push("mediaFeatures");
|
|
4306
|
+
}
|
|
4307
|
+
if (net != null) {
|
|
4308
|
+
await this.conn.send("emulation.setNetworkConditions", {
|
|
4309
|
+
networkConditions: net.offline ? { type: "offline" } : null,
|
|
4310
|
+
contexts: [this.contextId]
|
|
4311
|
+
});
|
|
4312
|
+
applied.push("networkConditions");
|
|
4313
|
+
}
|
|
4088
4314
|
} catch (e) {
|
|
4089
4315
|
throw mapBidiError(e);
|
|
4090
4316
|
}
|
|
@@ -4219,12 +4445,25 @@ var init_driver2 = __esm(() => {
|
|
|
4219
4445
|
};
|
|
4220
4446
|
}
|
|
4221
4447
|
async getResponseBody(requestId) {
|
|
4222
|
-
|
|
4223
|
-
|
|
4448
|
+
let collector;
|
|
4449
|
+
try {
|
|
4450
|
+
requireFirefox(this.conn, "network.responseBodyPostHoc");
|
|
4451
|
+
} catch (e) {
|
|
4452
|
+
if (!this.bodyCollector) {
|
|
4453
|
+
throw driverError2("unsupported", `${e.message} Call startBodyCapture() before the request to read its body on this Firefox.`);
|
|
4454
|
+
}
|
|
4455
|
+
collector = this.bodyCollector;
|
|
4456
|
+
}
|
|
4224
4457
|
try {
|
|
4225
|
-
const { bytes } = await this.conn.send("network.getData", { dataType: "response",
|
|
4458
|
+
const { bytes } = await this.conn.send("network.getData", { dataType: "response", request: requestId, ...collector ? { collector } : {} });
|
|
4226
4459
|
return bytes.type === "base64" ? { body: bytes.value, base64Encoded: true } : { body: bytes.value, base64Encoded: false };
|
|
4227
4460
|
} catch (e) {
|
|
4461
|
+
if (e instanceof BidiError && e.code === "unavailable network data") {
|
|
4462
|
+
throw driverError2("page-error", `getResponseBody: the body of request ${requestId} was collected but has been evicted (Firefox keeps only a bounded recent window of response bodies, on the order of 100-200 MB). Re-issue the request, then read it sooner.`);
|
|
4463
|
+
}
|
|
4464
|
+
if (e instanceof BidiError && e.code === "no such network data") {
|
|
4465
|
+
throw driverError2("page-error", `getResponseBody: no body is held for request ${requestId}. Firefox cannot say which of these applies: the id is wrong, the request started before this Firefox session did, the response was larger than ${POST_HOC_BODY_MAX_BYTES} bytes (not retained), or it has no body.`);
|
|
4466
|
+
}
|
|
4228
4467
|
throw mapBidiError(e);
|
|
4229
4468
|
}
|
|
4230
4469
|
}
|
|
@@ -4289,6 +4528,7 @@ var init_driver2 = __esm(() => {
|
|
|
4289
4528
|
// src/cdp/driver.ts
|
|
4290
4529
|
init_client();
|
|
4291
4530
|
init_session();
|
|
4531
|
+
init_frontApp();
|
|
4292
4532
|
init_leases();
|
|
4293
4533
|
init_endpoints();
|
|
4294
4534
|
init_activity();
|
|
@@ -4466,6 +4706,47 @@ async function centerOf(conn, objectId) {
|
|
|
4466
4706
|
throw driverError("page-error", "element has zero size / is not visible; cannot compute a click point");
|
|
4467
4707
|
return result.value;
|
|
4468
4708
|
}
|
|
4709
|
+
var SNAPSHOT_TEXT_FN = "function(){var e=this;e.__cdpSawInput=false;var f=function(){e.__cdpSawInput=true;};" + "e.addEventListener('beforeinput',f,{capture:true,once:true});e.addEventListener('input',f,{capture:true,once:true});" + "return e.isContentEditable?e.textContent:('value' in e?String(e.value):null);}";
|
|
4710
|
+
var LANDED_TEXT_FN = "function(before){var e=this;var now=function(){return e.isContentEditable?e.textContent:('value' in e?String(e.value):null);};" + "var hit=function(){return e.__cdpSawInput===true||now()!==before;};" + "if(hit())return true;return new Promise(function(r){setTimeout(function(){r(hit());},50);});}";
|
|
4711
|
+
var FALLBACK_TEXT_FN = "function(t){var e=this;if(e.disabled||e.readOnly)return 'skipped';var ce=e.isContentEditable===true;" + "var ta=e instanceof HTMLTextAreaElement;var inp=e instanceof HTMLInputElement&&!/^(checkbox|radio|file|button|submit|reset|image|hidden|range|color)$/i.test(e.type);" + "if(!ce&&!ta&&!inp)return 'skipped';e.focus();" + "if(ce){var r=document.createRange();r.selectNodeContents(e);r.collapse(false);var s=window.getSelection();s.removeAllRanges();s.addRange(r);}" + "else{try{var n=e.value.length;e.setSelectionRange(n,n);}catch(x){}}" + "var read=function(){return ce?e.textContent:e.value;};var before=read();" + "if(document.execCommand('insertText',false,t)&&read()!==before){e.dispatchEvent(new Event('change',{bubbles:true}));return 'execCommand';}" + "if(ce)return 'failed';var proto=ta?HTMLTextAreaElement.prototype:HTMLInputElement.prototype;" + "Object.getOwnPropertyDescriptor(proto,'value').set.call(e,before+t);" + "e.dispatchEvent(new InputEvent('input',{bubbles:true,inputType:'insertText',data:t}));" + "e.dispatchEvent(new Event('change',{bubbles:true}));return 'setter';}";
|
|
4712
|
+
async function insertTextVerified(conn, objectId, text, sendInput) {
|
|
4713
|
+
const call = async (fn, args = [], awaitPromise = false) => {
|
|
4714
|
+
const { result, exceptionDetails } = await conn.send("Runtime.callFunctionOn", {
|
|
4715
|
+
objectId,
|
|
4716
|
+
functionDeclaration: fn,
|
|
4717
|
+
arguments: args.map((value) => ({ value })),
|
|
4718
|
+
returnByValue: true,
|
|
4719
|
+
awaitPromise
|
|
4720
|
+
});
|
|
4721
|
+
if (exceptionDetails)
|
|
4722
|
+
throw driverError("page-error", `text input check failed: ${exceptionDetails.text ?? "error"}`);
|
|
4723
|
+
return result?.value;
|
|
4724
|
+
};
|
|
4725
|
+
const before = await call(SNAPSHOT_TEXT_FN);
|
|
4726
|
+
await sendInput("Input.insertText", { text });
|
|
4727
|
+
if (await call(LANDED_TEXT_FN, [before], true) === true)
|
|
4728
|
+
return "trusted";
|
|
4729
|
+
const via = await call(FALLBACK_TEXT_FN, [text]);
|
|
4730
|
+
if (via === "execCommand" || via === "setter" || via === "skipped")
|
|
4731
|
+
return via;
|
|
4732
|
+
throw driverError("page-error", "text did not land: trusted Input.insertText was not delivered (a background tab gets no trusted keyboard input) and document.execCommand('insertText') changed nothing on this element");
|
|
4733
|
+
}
|
|
4734
|
+
var ARM_KEY_WITNESS = "(function(){window.__cdpKeySeen=false;window.addEventListener('keydown',function(){window.__cdpKeySeen=true;},{capture:true,once:true});return true;})()";
|
|
4735
|
+
var READ_KEY_WITNESS = "(function(){if(window.__cdpKeySeen===true)return true;return new Promise(function(r){setTimeout(function(){r(window.__cdpKeySeen===true);},50);});})()";
|
|
4736
|
+
async function pressKeyObserved(conn, dispatch) {
|
|
4737
|
+
const eval_ = (expression, awaitPromise = false) => conn.send("Runtime.evaluate", { expression, returnByValue: true, awaitPromise }).then((r) => r.result?.value, () => {
|
|
4738
|
+
return;
|
|
4739
|
+
});
|
|
4740
|
+
const armed = await eval_(ARM_KEY_WITNESS) === true;
|
|
4741
|
+
await dispatch();
|
|
4742
|
+
if (!armed)
|
|
4743
|
+
return;
|
|
4744
|
+
const seen = await eval_(READ_KEY_WITNESS, true);
|
|
4745
|
+
if (seen === false)
|
|
4746
|
+
return { delivered: false };
|
|
4747
|
+
if (seen === true)
|
|
4748
|
+
return { delivered: true };
|
|
4749
|
+
}
|
|
4469
4750
|
async function focusElement(conn, objectId) {
|
|
4470
4751
|
await conn.send("Runtime.callFunctionOn", { objectId, functionDeclaration: "function(){this.focus&&this.focus();}", returnByValue: true });
|
|
4471
4752
|
}
|
|
@@ -4480,10 +4761,12 @@ async function awaitScrollSettle(conn) {
|
|
|
4480
4761
|
}
|
|
4481
4762
|
async function setValueOnObject(conn, objectId, value, sendInput) {
|
|
4482
4763
|
await focusElement(conn, objectId);
|
|
4483
|
-
const fn = "function(){if('value'in this){this.value='';this.dispatchEvent(new Event('input',{bubbles:true}));}else if(this.isContentEditable){this.textContent='';}}";
|
|
4484
|
-
await conn.send("Runtime.callFunctionOn", { objectId, functionDeclaration: fn, returnByValue: true });
|
|
4485
|
-
if (value
|
|
4486
|
-
|
|
4764
|
+
const fn = "function(){if(this.disabled||this.readOnly)return this.disabled?'disabled':'readonly';if('value'in this){this.value='';this.dispatchEvent(new Event('input',{bubbles:true}));}else if(this.isContentEditable){this.textContent='';}return 'ok';}";
|
|
4765
|
+
const { result } = await conn.send("Runtime.callFunctionOn", { objectId, functionDeclaration: fn, returnByValue: true });
|
|
4766
|
+
if (result?.value === "disabled" || result?.value === "readonly") {
|
|
4767
|
+
throw driverError("page-error", `cannot fill a ${result.value} field: it was left unchanged`);
|
|
4768
|
+
}
|
|
4769
|
+
return value.length ? insertTextVerified(conn, objectId, value, sendInput) : "trusted";
|
|
4487
4770
|
}
|
|
4488
4771
|
var NAMED_KEYS = {
|
|
4489
4772
|
enter: { key: "Enter", code: "Enter", keyCode: 13, text: "\r" },
|
|
@@ -4752,6 +5035,7 @@ var CDP_CAPABILITIES = new Set([
|
|
|
4752
5035
|
"locate.xpath",
|
|
4753
5036
|
"capture.screencast",
|
|
4754
5037
|
"input.raw",
|
|
5038
|
+
"input.modifierClick",
|
|
4755
5039
|
"input.html5Drag",
|
|
4756
5040
|
"emulate.focus",
|
|
4757
5041
|
"browser.downloads",
|
|
@@ -5030,13 +5314,12 @@ class CdpPageDriver {
|
|
|
5030
5314
|
}
|
|
5031
5315
|
async setValue(loc, value) {
|
|
5032
5316
|
const { objectId } = await resolveElementLocator(this.conn, loc);
|
|
5033
|
-
|
|
5317
|
+
return setValueOnObject(this.conn, objectId, value, (method, params) => this.dispatchInput(method, params));
|
|
5034
5318
|
}
|
|
5035
5319
|
async typeText(loc, text) {
|
|
5036
5320
|
const { objectId } = await resolveElementLocator(this.conn, loc);
|
|
5037
5321
|
await focusElement(this.conn, objectId);
|
|
5038
|
-
|
|
5039
|
-
await this.dispatchInput("Input.insertText", { text });
|
|
5322
|
+
return text.length ? insertTextVerified(this.conn, objectId, text, (method, params) => this.dispatchInput(method, params)) : "trusted";
|
|
5040
5323
|
}
|
|
5041
5324
|
async pressKey(press) {
|
|
5042
5325
|
const spec = resolveKey(press.key);
|
|
@@ -5051,8 +5334,10 @@ class CdpPageDriver {
|
|
|
5051
5334
|
const down = { type: "keyDown", key: spec.key, code: spec.code, windowsVirtualKeyCode: spec.keyCode, nativeVirtualKeyCode: spec.keyCode, modifiers: modBits };
|
|
5052
5335
|
if (spec.text && !suppressText)
|
|
5053
5336
|
down.text = spec.text;
|
|
5054
|
-
|
|
5055
|
-
|
|
5337
|
+
return pressKeyObserved(this.conn, async () => {
|
|
5338
|
+
await this.dispatchInput("Input.dispatchKeyEvent", down);
|
|
5339
|
+
await this.dispatchInput("Input.dispatchKeyEvent", { type: "keyUp", key: spec.key, code: spec.code, windowsVirtualKeyCode: spec.keyCode, nativeVirtualKeyCode: spec.keyCode, modifiers: modBits });
|
|
5340
|
+
});
|
|
5056
5341
|
}
|
|
5057
5342
|
async setFiles(loc, files) {
|
|
5058
5343
|
const { objectId } = await resolveElementLocator(this.conn, loc);
|
|
@@ -5429,7 +5714,7 @@ function noSuchTarget(e) {
|
|
|
5429
5714
|
throw driverError("no-such-target", e instanceof CdpError ? e.message : String(e));
|
|
5430
5715
|
}
|
|
5431
5716
|
var NEW_TARGET_SETTLE_MS = 2000;
|
|
5432
|
-
async function createSettledTarget(conn, url, settleMs = NEW_TARGET_SETTLE_MS) {
|
|
5717
|
+
async function createSettledTarget(conn, url, settleMs = NEW_TARGET_SETTLE_MS, opts = {}) {
|
|
5433
5718
|
const changed = new Set;
|
|
5434
5719
|
let id = "";
|
|
5435
5720
|
let wake;
|
|
@@ -5445,7 +5730,8 @@ async function createSettledTarget(conn, url, settleMs = NEW_TARGET_SETTLE_MS) {
|
|
|
5445
5730
|
await conn.send("Target.setDiscoverTargets", { discover: true }).catch(() => {
|
|
5446
5731
|
return;
|
|
5447
5732
|
});
|
|
5448
|
-
const
|
|
5733
|
+
const create = () => conn.send("Target.createTarget", { url, background: opts.focus !== true });
|
|
5734
|
+
const { targetId } = opts.focus === true ? await create() : await keepFrontApp(create);
|
|
5449
5735
|
if (!targetId)
|
|
5450
5736
|
throw driverError("page-error", "Target.createTarget returned no targetId");
|
|
5451
5737
|
id = targetId;
|
|
@@ -5475,15 +5761,15 @@ class CdpBrowserDriver {
|
|
|
5475
5761
|
const filtered = opts?.all ? targets : targets.filter((t) => t.type === "page");
|
|
5476
5762
|
return filtered.map((t) => ({ id: t.id, url: t.url, title: t.title, type: t.type }));
|
|
5477
5763
|
}
|
|
5478
|
-
async newPage(url) {
|
|
5764
|
+
async newPage(url, opts) {
|
|
5479
5765
|
return withBrowserConn(async (conn) => {
|
|
5480
|
-
const targetId = await createSettledTarget(conn, url ?? "about:blank");
|
|
5766
|
+
const targetId = await createSettledTarget(conn, url ?? "about:blank", NEW_TARGET_SETTLE_MS, { focus: opts?.focus === true });
|
|
5481
5767
|
return { id: targetId, url: url ?? "about:blank", title: "" };
|
|
5482
5768
|
});
|
|
5483
5769
|
}
|
|
5484
5770
|
async closePage(id) {
|
|
5485
5771
|
return withBrowserConn(async (conn) => {
|
|
5486
|
-
const res = await conn.send("Target.closeTarget", { targetId: id });
|
|
5772
|
+
const res = await keepFrontApp(() => conn.send("Target.closeTarget", { targetId: id }));
|
|
5487
5773
|
if (res.success !== false)
|
|
5488
5774
|
beaconSessions.drop(beaconKey(id));
|
|
5489
5775
|
return { success: res.success ?? true };
|
|
@@ -6153,7 +6439,6 @@ init_workers();
|
|
|
6153
6439
|
init_frames();
|
|
6154
6440
|
init_endpoints();
|
|
6155
6441
|
var ARTIFACT_DIR = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
|
|
6156
|
-
var STATE_DIR = process.env.CDP_STATE_DIR ?? "/tmp/cdp-toolkit";
|
|
6157
6442
|
|
|
6158
6443
|
class SharedToolError extends Error {
|
|
6159
6444
|
}
|
|
@@ -6312,7 +6597,7 @@ async function listPagesOne(driver, args = {}) {
|
|
|
6312
6597
|
}
|
|
6313
6598
|
async function newPage(driver, args = {}) {
|
|
6314
6599
|
const label = typeof args.label === "string" && args.label.length ? args.label : defaultLabel();
|
|
6315
|
-
const p = await newTrackedPage(driver, backendOf(driver), { url: args.url, label });
|
|
6600
|
+
const p = await newTrackedPage(driver, backendOf(driver), { url: args.url, label, focus: args.focus === true });
|
|
6316
6601
|
const explicit = args.claim === true;
|
|
6317
6602
|
if (!explicit && !requireLease())
|
|
6318
6603
|
return { targetId: p.id, url: p.url };
|
|
@@ -6335,16 +6620,17 @@ async function closePage(driver, args) {
|
|
|
6335
6620
|
return { closed: p.id, success: true, ...released.released ? { leaseReleased: true } : {} };
|
|
6336
6621
|
}
|
|
6337
6622
|
async function writeSelectedFile(id) {
|
|
6338
|
-
|
|
6339
|
-
await
|
|
6623
|
+
const stateDir = process.env.CDP_STATE_DIR ?? "/tmp/cdp-toolkit";
|
|
6624
|
+
await mkdir5(stateDir, { recursive: true });
|
|
6625
|
+
await writeFile4(join5(stateDir, "selected"), id, "utf8");
|
|
6340
6626
|
}
|
|
6341
6627
|
async function selectPage(driver, args) {
|
|
6342
6628
|
if (args.target === undefined || args.target === "")
|
|
6343
6629
|
throw new SharedToolError("select_page requires an explicit target");
|
|
6344
6630
|
const p = await resolvePage(driver, args.target);
|
|
6345
|
-
const
|
|
6346
|
-
await writeSelectedFile(
|
|
6347
|
-
return { selected:
|
|
6631
|
+
const id = args.focus === true ? (await driver.activatePage(p.id)).id : p.id;
|
|
6632
|
+
await writeSelectedFile(id);
|
|
6633
|
+
return { selected: id, focused: args.focus === true };
|
|
6348
6634
|
}
|
|
6349
6635
|
function toLegacyWaitedFor(w) {
|
|
6350
6636
|
if (w === "committed")
|
|
@@ -6703,14 +6989,17 @@ async function drag(driver, args) {
|
|
|
6703
6989
|
};
|
|
6704
6990
|
});
|
|
6705
6991
|
}
|
|
6992
|
+
function inputPathField(path) {
|
|
6993
|
+
return path && path !== "trusted" ? { inputPath: path } : {};
|
|
6994
|
+
}
|
|
6706
6995
|
async function fill(driver, args) {
|
|
6707
6996
|
if (typeof args.value !== "string")
|
|
6708
6997
|
throw new SharedToolError("fill requires a string { value }");
|
|
6709
6998
|
const loc = locatorOf(args);
|
|
6710
6999
|
return withPage2(driver, args.target, async (page) => {
|
|
6711
7000
|
const element = await describeElement(page, loc);
|
|
6712
|
-
await page.setValue(loc, args.value);
|
|
6713
|
-
return { filled: true, ...elementField(element), value: args.value };
|
|
7001
|
+
const path = await page.setValue(loc, args.value);
|
|
7002
|
+
return { filled: true, ...elementField(element), value: args.value, ...inputPathField(path) };
|
|
6714
7003
|
});
|
|
6715
7004
|
}
|
|
6716
7005
|
async function fillForm(driver, args) {
|
|
@@ -6719,15 +7008,16 @@ async function fillForm(driver, args) {
|
|
|
6719
7008
|
return withPage2(driver, args.target, async (page) => {
|
|
6720
7009
|
let filled = 0;
|
|
6721
7010
|
const elements = [];
|
|
7011
|
+
const paths = [];
|
|
6722
7012
|
for (const f of args.fields) {
|
|
6723
7013
|
if (typeof f.value !== "string")
|
|
6724
7014
|
throw new SharedToolError("each fill_form field requires a string value");
|
|
6725
7015
|
const loc = locatorOf(f);
|
|
6726
7016
|
elements.push(await describeElement(page, loc) ?? null);
|
|
6727
|
-
await page.setValue(loc, f.value);
|
|
7017
|
+
paths.push(await page.setValue(loc, f.value) || "trusted");
|
|
6728
7018
|
filled++;
|
|
6729
7019
|
}
|
|
6730
|
-
return { filled, fields: args.fields.length, elements };
|
|
7020
|
+
return { filled, fields: args.fields.length, elements, ...paths.some((p) => p !== "trusted") ? { inputPaths: paths } : {} };
|
|
6731
7021
|
});
|
|
6732
7022
|
}
|
|
6733
7023
|
async function typeText(driver, args) {
|
|
@@ -6736,8 +7026,8 @@ async function typeText(driver, args) {
|
|
|
6736
7026
|
const loc = locatorOf(args);
|
|
6737
7027
|
return withPage2(driver, args.target, async (page) => {
|
|
6738
7028
|
const element = await describeElement(page, loc);
|
|
6739
|
-
await page.typeText(loc, args.text);
|
|
6740
|
-
return { typed: true, ...elementField(element), text: args.text };
|
|
7029
|
+
const path = await page.typeText(loc, args.text);
|
|
7030
|
+
return { typed: true, ...elementField(element), text: args.text, ...inputPathField(path) };
|
|
6741
7031
|
});
|
|
6742
7032
|
}
|
|
6743
7033
|
async function pressKey(driver, args) {
|
|
@@ -6745,7 +7035,15 @@ async function pressKey(driver, args) {
|
|
|
6745
7035
|
throw new SharedToolError("press_key requires a non-empty { key }");
|
|
6746
7036
|
const modifiers = args.modifiers ?? [];
|
|
6747
7037
|
return withPage2(driver, args.target, async (page) => {
|
|
6748
|
-
await page.pressKey({ key: args.key, modifiers });
|
|
7038
|
+
const res = await page.pressKey({ key: args.key, modifiers });
|
|
7039
|
+
if (res && res.delivered === false) {
|
|
7040
|
+
return {
|
|
7041
|
+
pressed: args.key,
|
|
7042
|
+
modifiers,
|
|
7043
|
+
delivered: false,
|
|
7044
|
+
note: "the page saw no keydown: a background tab gets no trusted keyboard input. A click on the tab's page (click tool) usually gives it focus so keys land; or open the tab with new_page focus:true. A key handled inside a cross-origin iframe also reads as not delivered."
|
|
7045
|
+
};
|
|
7046
|
+
}
|
|
6749
7047
|
return { pressed: args.key, modifiers };
|
|
6750
7048
|
});
|
|
6751
7049
|
}
|
|
@@ -6772,7 +7070,7 @@ function resolveScreenshotScale(scale, capabilities) {
|
|
|
6772
7070
|
throw new SharedToolError(`take_screenshot: 'scale' must be a finite number greater than 0 and at most ${MAX_SCREENSHOT_SCALE} (default 1)`);
|
|
6773
7071
|
}
|
|
6774
7072
|
if (scale !== 1 && !capabilities.has("screenshot.scale")) {
|
|
6775
|
-
throw new SharedToolError("take_screenshot: 'scale' is not supported by this backend (
|
|
7073
|
+
throw new SharedToolError("take_screenshot: 'scale' is not supported by this backend (no per-capture scale primitive). " + `Call emulate with deviceScaleFactor:${scale} first and capture at scale 1, or use --browser chrome for a per-capture scale.`);
|
|
6776
7074
|
}
|
|
6777
7075
|
return scale;
|
|
6778
7076
|
}
|
|
@@ -7013,7 +7311,7 @@ async function claimPage(driver, args = {}) {
|
|
|
7013
7311
|
url = existing.url;
|
|
7014
7312
|
opened = false;
|
|
7015
7313
|
} else {
|
|
7016
|
-
const page = await newTrackedPage(driver, backend, { url: args.url, label });
|
|
7314
|
+
const page = await newTrackedPage(driver, backend, { url: args.url, label, focus: args.focus === true });
|
|
7017
7315
|
targetId = page.id;
|
|
7018
7316
|
url = page.url;
|
|
7019
7317
|
opened = true;
|
|
@@ -7513,7 +7811,7 @@ init_client();
|
|
|
7513
7811
|
import { mkdir as mkdir7, readFile as readFile7, writeFile as writeFile6, stat, unlink as unlink4 } from "node:fs/promises";
|
|
7514
7812
|
import { join as join6 } from "node:path";
|
|
7515
7813
|
var ARTIFACT_DIR2 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
|
|
7516
|
-
var
|
|
7814
|
+
var STATE_DIR = process.env.CDP_STATE_DIR ?? "/tmp/cdp-toolkit";
|
|
7517
7815
|
var DEFAULT_CATEGORIES = [
|
|
7518
7816
|
"devtools.timeline",
|
|
7519
7817
|
"blink.user_timing",
|
|
@@ -7529,7 +7827,7 @@ function shortId(id) {
|
|
|
7529
7827
|
return id.slice(0, 8);
|
|
7530
7828
|
}
|
|
7531
7829
|
function stateFilePath() {
|
|
7532
|
-
return join6(
|
|
7830
|
+
return join6(STATE_DIR, "trace-state.json");
|
|
7533
7831
|
}
|
|
7534
7832
|
function bufferTraceData(conn, sink) {
|
|
7535
7833
|
return conn.on("Tracing.dataCollected", (params) => {
|
|
@@ -7574,7 +7872,7 @@ async function performanceStartTrace(args = {}) {
|
|
|
7574
7872
|
throw err;
|
|
7575
7873
|
}
|
|
7576
7874
|
liveTraces.set(target.id, { conn, target, events, startedAt: Date.now() });
|
|
7577
|
-
await mkdir7(
|
|
7875
|
+
await mkdir7(STATE_DIR, { recursive: true });
|
|
7578
7876
|
const state = {
|
|
7579
7877
|
targetId: target.id,
|
|
7580
7878
|
url: target.url,
|
|
@@ -7903,7 +8201,7 @@ function buildFfmpegArgs(manifestPath, outPath, choice) {
|
|
|
7903
8201
|
outPath
|
|
7904
8202
|
];
|
|
7905
8203
|
}
|
|
7906
|
-
function
|
|
8204
|
+
function run2(bin, args) {
|
|
7907
8205
|
return new Promise((resolve, reject) => {
|
|
7908
8206
|
const child = spawn(bin, args, { stdio: ["ignore", "pipe", "pipe"] });
|
|
7909
8207
|
let stdout = "";
|
|
@@ -7925,7 +8223,7 @@ async function probeEncoder() {
|
|
|
7925
8223
|
encoderProbe = (async () => {
|
|
7926
8224
|
let res;
|
|
7927
8225
|
try {
|
|
7928
|
-
res = await
|
|
8226
|
+
res = await run2(FFMPEG_BIN, ["-hide_banner", "-encoders"]);
|
|
7929
8227
|
} catch (err) {
|
|
7930
8228
|
throw new CdpError(`${FFMPEG_MISSING} (${err.message})`);
|
|
7931
8229
|
}
|
|
@@ -7934,7 +8232,7 @@ async function probeEncoder() {
|
|
|
7934
8232
|
const choice = selectEncoder(`${res.stdout}
|
|
7935
8233
|
${res.stderr}`);
|
|
7936
8234
|
const output = async (args) => {
|
|
7937
|
-
const r = await
|
|
8235
|
+
const r = await run2(FFMPEG_BIN, args).catch(() => {
|
|
7938
8236
|
return;
|
|
7939
8237
|
});
|
|
7940
8238
|
return r && r.code === 0 ? `${r.stdout}
|
|
@@ -8107,7 +8405,7 @@ async function stopScreenRecording(args = {}) {
|
|
|
8107
8405
|
const { width, height } = evenDimensions(ledger[0].width, ledger[0].height);
|
|
8108
8406
|
let res;
|
|
8109
8407
|
try {
|
|
8110
|
-
res = await
|
|
8408
|
+
res = await run2(FFMPEG_BIN, buildFfmpegArgs(manifestPath, outPath, rec.encoder));
|
|
8111
8409
|
} catch (err) {
|
|
8112
8410
|
throw new CdpError(`${FFMPEG_MISSING} Spooled frames kept at ${rec.spoolDir}. (${err.message})`);
|
|
8113
8411
|
}
|
|
@@ -9475,6 +9773,16 @@ async function withPage4(driver, target, fn) {
|
|
|
9475
9773
|
await page.release();
|
|
9476
9774
|
}
|
|
9477
9775
|
}
|
|
9776
|
+
async function dispatchMouse2(driver, args) {
|
|
9777
|
+
validateDispatchMouseArgs(args);
|
|
9778
|
+
modifierBits(args.modifiers);
|
|
9779
|
+
return withPage4(driver, args.target, async (page) => {
|
|
9780
|
+
if (!page.dispatchMouse)
|
|
9781
|
+
throw new BidiToolError("dispatch_mouse: this page driver has no raw mouse dispatch");
|
|
9782
|
+
await page.dispatchMouse({ action: args.action, x: args.x, y: args.y, button: args.button, clickCount: args.clickCount, modifiers: args.modifiers });
|
|
9783
|
+
return { dispatched: args.action, x: args.x, y: args.y };
|
|
9784
|
+
});
|
|
9785
|
+
}
|
|
9478
9786
|
var consoleBuffers = new Map;
|
|
9479
9787
|
var networkBuffers = new Map;
|
|
9480
9788
|
function refuseWorkerSelector(driver, target) {
|
|
@@ -9547,6 +9855,13 @@ async function getNetworkRequest2(driver, args = {}) {
|
|
|
9547
9855
|
return withPage4(driver, args.target, async (page) => {
|
|
9548
9856
|
const buf = bufferFor(networkBuffers, page.info.id);
|
|
9549
9857
|
const found = args.requestId ? buf.find((r) => r.requestId === args.requestId || r.request === args.requestId) : buf.find((r) => typeof r.url === "string" && r.url.includes(args.url));
|
|
9858
|
+
if (args.includeBody) {
|
|
9859
|
+
const id = args.requestId ?? (found ? String(found.requestId ?? found.request ?? "") : "");
|
|
9860
|
+
if (!id)
|
|
9861
|
+
throw new BidiToolError("get_network_request includeBody on this backend needs a requestId, or a url already present in the buffer (run list_network_requests with reload first)");
|
|
9862
|
+
const { body, base64Encoded } = await page.getResponseBody(id);
|
|
9863
|
+
return { ...found ?? { requestId: id }, body, bodyBase64Encoded: base64Encoded };
|
|
9864
|
+
}
|
|
9550
9865
|
if (!found)
|
|
9551
9866
|
throw new BidiToolError("no matching network request in the current buffer; run list_network_requests first");
|
|
9552
9867
|
return found;
|
|
@@ -9622,7 +9937,232 @@ var BIDI_ONLY_TOOLS = {
|
|
|
9622
9937
|
get_network_request: getNetworkRequest2,
|
|
9623
9938
|
mock_request: mockRequest2,
|
|
9624
9939
|
list_mocks: listMocks2,
|
|
9625
|
-
clear_mocks: clearMocks2
|
|
9940
|
+
clear_mocks: clearMocks2,
|
|
9941
|
+
dispatch_mouse: dispatchMouse2
|
|
9942
|
+
};
|
|
9943
|
+
|
|
9944
|
+
// src/bidi-browser-tools.ts
|
|
9945
|
+
init_driver2();
|
|
9946
|
+
import { mkdir as mkdir14, readdir as readdir4, realpath, rename as rename4, stat as stat5 } from "node:fs/promises";
|
|
9947
|
+
import { basename as basename2, dirname as dirname4, join as join14, resolve } from "node:path";
|
|
9948
|
+
function unsupported(message) {
|
|
9949
|
+
return Object.assign(new Error(message), { code: "unsupported" });
|
|
9950
|
+
}
|
|
9951
|
+
function scopeOf(driver, tool) {
|
|
9952
|
+
const d = driver;
|
|
9953
|
+
if (typeof d.withBrowserConnection !== "function" || typeof d.setDisposeHook !== "function") {
|
|
9954
|
+
throw unsupported(`${tool}: this driver has no browser-scoped connection (the Firefox BiDi driver does; Chrome uses src/tools/).`);
|
|
9955
|
+
}
|
|
9956
|
+
return d;
|
|
9957
|
+
}
|
|
9958
|
+
async function targetOf(driver, target) {
|
|
9959
|
+
const page = await driver.page(target);
|
|
9960
|
+
try {
|
|
9961
|
+
return { id: page.info.id, url: page.info.url, title: page.info.title };
|
|
9962
|
+
} finally {
|
|
9963
|
+
await page.release();
|
|
9964
|
+
}
|
|
9965
|
+
}
|
|
9966
|
+
var FIREFOX_DOWNLOAD_STAGING_DIR = join14(dirname4(DOWNLOADS_DIR), "downloads-firefox-staging");
|
|
9967
|
+
var downloadStates = new WeakMap;
|
|
9968
|
+
function downloadId(p) {
|
|
9969
|
+
const v = p.download ?? p.navigation;
|
|
9970
|
+
return typeof v === "string" && v.length > 0 ? v : undefined;
|
|
9971
|
+
}
|
|
9972
|
+
function deliver(s, r) {
|
|
9973
|
+
r.state = "completed";
|
|
9974
|
+
s.downloads.push(r);
|
|
9975
|
+
while (s.downloads.length > DOWNLOAD_BUFFER_LIMIT) {
|
|
9976
|
+
const i = s.downloads.findIndex((d) => d.consumed);
|
|
9977
|
+
s.downloads.splice(i >= 0 ? i : 0, 1);
|
|
9978
|
+
}
|
|
9979
|
+
const waiter = s.waiters.shift();
|
|
9980
|
+
if (waiter) {
|
|
9981
|
+
r.consumed = true;
|
|
9982
|
+
waiter(r);
|
|
9983
|
+
}
|
|
9984
|
+
}
|
|
9985
|
+
function downloadStateFor(conn) {
|
|
9986
|
+
let s = downloadStates.get(conn);
|
|
9987
|
+
if (s)
|
|
9988
|
+
return s;
|
|
9989
|
+
const state = { downloads: [], begun: new Map, waiters: [], stagingDirs: new Set([resolve(FIREFOX_DOWNLOAD_STAGING_DIR)]) };
|
|
9990
|
+
downloadStates.set(conn, state);
|
|
9991
|
+
conn.on("browsingContext.downloadWillBegin", (p) => {
|
|
9992
|
+
const id = downloadId(p);
|
|
9993
|
+
if (!id)
|
|
9994
|
+
return;
|
|
9995
|
+
state.begun.set(id, { id, url: p.url, suggestedFilename: p.suggestedFilename, state: "inProgress", consumed: false });
|
|
9996
|
+
if (state.begun.size > DOWNLOAD_BUFFER_LIMIT)
|
|
9997
|
+
state.begun.delete(state.begun.keys().next().value);
|
|
9998
|
+
});
|
|
9999
|
+
conn.on("browsingContext.downloadEnd", (p) => {
|
|
10000
|
+
const id = downloadId(p);
|
|
10001
|
+
if (!id)
|
|
10002
|
+
return;
|
|
10003
|
+
const rec = state.begun.get(id) ?? { id, state: "inProgress", consumed: false };
|
|
10004
|
+
state.begun.delete(id);
|
|
10005
|
+
if (p.status !== "complete" || !p.filepath)
|
|
10006
|
+
return;
|
|
10007
|
+
if (!state.stagingDirs.has(resolve(dirname4(p.filepath))))
|
|
10008
|
+
return;
|
|
10009
|
+
rec.url ??= p.url;
|
|
10010
|
+
const held = join14(dirname4(p.filepath), `${id.replace(/[^A-Za-z0-9-]/g, "_")}.download`);
|
|
10011
|
+
rename4(p.filepath, held).then(() => {
|
|
10012
|
+
rec.filePath = held;
|
|
10013
|
+
}, () => {
|
|
10014
|
+
rec.filePath = p.filepath ?? undefined;
|
|
10015
|
+
}).finally(() => deliver(state, rec));
|
|
10016
|
+
});
|
|
10017
|
+
return state;
|
|
10018
|
+
}
|
|
10019
|
+
async function armFirefoxDownloads(conn, s, scope) {
|
|
10020
|
+
await mkdir14(FIREFOX_DOWNLOAD_STAGING_DIR, { recursive: true });
|
|
10021
|
+
await mkdir14(DOWNLOADS_DIR, { recursive: true });
|
|
10022
|
+
s.stagingDirs.add(resolve(await realpath(FIREFOX_DOWNLOAD_STAGING_DIR)));
|
|
10023
|
+
scope.setDisposeHook("browser.downloads", async (c) => {
|
|
10024
|
+
await c.send("browser.setDownloadBehavior", { downloadBehavior: null });
|
|
10025
|
+
});
|
|
10026
|
+
await conn.send("browser.setDownloadBehavior", { downloadBehavior: { type: "allowed", destinationFolder: FIREFOX_DOWNLOAD_STAGING_DIR } });
|
|
10027
|
+
}
|
|
10028
|
+
async function disarmFirefoxDownloads(conn, scope) {
|
|
10029
|
+
await conn.send("browser.setDownloadBehavior", { downloadBehavior: null });
|
|
10030
|
+
scope.setDisposeHook("browser.downloads", undefined);
|
|
10031
|
+
}
|
|
10032
|
+
function nextFirefoxDownload(s, timeoutMs) {
|
|
10033
|
+
const buffered = s.downloads.find((d) => !d.consumed);
|
|
10034
|
+
if (buffered) {
|
|
10035
|
+
buffered.consumed = true;
|
|
10036
|
+
return Promise.resolve(buffered);
|
|
10037
|
+
}
|
|
10038
|
+
return new Promise((resolvePromise, reject) => {
|
|
10039
|
+
const waiter = (r) => {
|
|
10040
|
+
clearTimeout(timer);
|
|
10041
|
+
resolvePromise(r);
|
|
10042
|
+
};
|
|
10043
|
+
const timer = setTimeout(() => {
|
|
10044
|
+
const i = s.waiters.indexOf(waiter);
|
|
10045
|
+
if (i >= 0)
|
|
10046
|
+
s.waiters.splice(i, 1);
|
|
10047
|
+
reject(new Error(`wait_for_download: no download completed within ${timeoutMs}ms. On Firefox, downloads are captured only while a wait_for_download call is armed: arm (arm:true) BEFORE the triggering click, and again before every later download, because each collecting call restores Firefox's normal download behavior when it returns.`));
|
|
10048
|
+
}, timeoutMs);
|
|
10049
|
+
s.waiters.push(waiter);
|
|
10050
|
+
});
|
|
10051
|
+
}
|
|
10052
|
+
async function waitForDownloadFirefox(driver, args = {}) {
|
|
10053
|
+
validateWaitForDownloadArgs(args);
|
|
10054
|
+
const scope = scopeOf(driver, "wait_for_download");
|
|
10055
|
+
const target = await targetOf(driver, args.target);
|
|
10056
|
+
return scope.withBrowserConnection(async (conn) => {
|
|
10057
|
+
requireFirefox(conn, "browser.downloads");
|
|
10058
|
+
const s = downloadStateFor(conn);
|
|
10059
|
+
await armFirefoxDownloads(conn, s, scope);
|
|
10060
|
+
if (args.arm === true) {
|
|
10061
|
+
return { armed: true, downloadPath: DOWNLOADS_DIR, pending: s.downloads.filter((d) => !d.consumed).length, target };
|
|
10062
|
+
}
|
|
10063
|
+
let rec;
|
|
10064
|
+
try {
|
|
10065
|
+
rec = await nextFirefoxDownload(s, args.timeoutMs ?? 30000);
|
|
10066
|
+
} finally {
|
|
10067
|
+
if (s.waiters.length === 0)
|
|
10068
|
+
await disarmFirefoxDownloads(conn, scope).catch(() => {
|
|
10069
|
+
return;
|
|
10070
|
+
});
|
|
10071
|
+
}
|
|
10072
|
+
if (!rec.filePath) {
|
|
10073
|
+
throw new Error(`wait_for_download: download ${rec.id} completed without a file path (nothing to return)`);
|
|
10074
|
+
}
|
|
10075
|
+
const suggestedFilename = safeFilename(rec.suggestedFilename);
|
|
10076
|
+
const taken = new Set(await readdir4(DOWNLOADS_DIR).catch(() => []));
|
|
10077
|
+
taken.delete(basename2(rec.filePath));
|
|
10078
|
+
const finalName = nextFreeName(suggestedFilename, taken);
|
|
10079
|
+
const path = join14(DOWNLOADS_DIR, finalName);
|
|
10080
|
+
await rename4(rec.filePath, path);
|
|
10081
|
+
const bytes = (await stat5(path)).size;
|
|
10082
|
+
return { path, suggestedFilename, bytes, ...rec.url ? { url: rec.url } : {}, target };
|
|
10083
|
+
});
|
|
10084
|
+
}
|
|
10085
|
+
var FIREFOX_PERMISSION_DESCRIPTORS = {
|
|
10086
|
+
geolocation: { name: "geolocation" },
|
|
10087
|
+
notifications: { name: "notifications" },
|
|
10088
|
+
audioCapture: { name: "microphone" },
|
|
10089
|
+
videoCapture: { name: "camera" },
|
|
10090
|
+
durableStorage: { name: "persistent-storage" },
|
|
10091
|
+
midi: { name: "midi" },
|
|
10092
|
+
midiSysex: { name: "midi", sysex: true },
|
|
10093
|
+
wakeLockScreen: { name: "screen-wake-lock" }
|
|
10094
|
+
};
|
|
10095
|
+
function mapFirefoxPermissions(names) {
|
|
10096
|
+
return names.map((n) => {
|
|
10097
|
+
const d = Object.hasOwn(FIREFOX_PERMISSION_DESCRIPTORS, n) ? FIREFOX_PERMISSION_DESCRIPTORS[n] : undefined;
|
|
10098
|
+
if (!d) {
|
|
10099
|
+
throw unsupported(`grant_permissions: permission '${n}' is not supported on Firefox (WebDriver BiDi permissions.setPermission has no measured equivalent). Supported on Firefox: ${Object.keys(FIREFOX_PERMISSION_DESCRIPTORS).join(", ")}.`);
|
|
10100
|
+
}
|
|
10101
|
+
return d;
|
|
10102
|
+
});
|
|
10103
|
+
}
|
|
10104
|
+
var trackedGrants = new WeakMap;
|
|
10105
|
+
function grantKey(origin, d) {
|
|
10106
|
+
return `${origin} ${JSON.stringify(d)}`;
|
|
10107
|
+
}
|
|
10108
|
+
async function restoreGrants(conn, grants) {
|
|
10109
|
+
const all = [...grants.values()];
|
|
10110
|
+
grants.clear();
|
|
10111
|
+
for (const g of all) {
|
|
10112
|
+
await conn.send("permissions.setPermission", { descriptor: g.descriptor, state: g.previous, origin: g.origin });
|
|
10113
|
+
}
|
|
10114
|
+
}
|
|
10115
|
+
async function queryState(page, d) {
|
|
10116
|
+
try {
|
|
10117
|
+
const v = await page.evaluate(`navigator.permissions.query(${JSON.stringify(d)}).then((p) => p.state, () => "prompt")`, { awaitPromise: true });
|
|
10118
|
+
return v === "granted" || v === "denied" ? v : "prompt";
|
|
10119
|
+
} catch {
|
|
10120
|
+
return "prompt";
|
|
10121
|
+
}
|
|
10122
|
+
}
|
|
10123
|
+
async function grantPermissionsFirefox(driver, args = {}) {
|
|
10124
|
+
validateGrantPermissionsArgs(args);
|
|
10125
|
+
const reset = args.reset === true;
|
|
10126
|
+
const permissions = args.permissions ?? [];
|
|
10127
|
+
const descriptors = mapFirefoxPermissions(permissions);
|
|
10128
|
+
const scope = scopeOf(driver, "grant_permissions");
|
|
10129
|
+
let grants = trackedGrants.get(driver);
|
|
10130
|
+
if (!grants) {
|
|
10131
|
+
grants = new Map;
|
|
10132
|
+
trackedGrants.set(driver, grants);
|
|
10133
|
+
}
|
|
10134
|
+
const tracked = grants;
|
|
10135
|
+
const page = await driver.page(args.target);
|
|
10136
|
+
try {
|
|
10137
|
+
const target = { id: page.info.id, url: page.info.url, title: page.info.title };
|
|
10138
|
+
return await scope.withBrowserConnection(async (conn) => {
|
|
10139
|
+
requireFirefox(conn, "browser.permissions");
|
|
10140
|
+
if (reset)
|
|
10141
|
+
await restoreGrants(conn, tracked);
|
|
10142
|
+
if (permissions.length === 0)
|
|
10143
|
+
return { reset: true, target };
|
|
10144
|
+
const origin = args.origin ?? originOf(page.info.url);
|
|
10145
|
+
if (!origin) {
|
|
10146
|
+
throw new Error(`grant_permissions: cannot derive an origin from the target tab's url (${JSON.stringify(page.info.url)}); pass 'origin' explicitly, e.g. origin:"https://example.com"`);
|
|
10147
|
+
}
|
|
10148
|
+
const pageIsOrigin = originOf(page.info.url) === origin;
|
|
10149
|
+
scope.setDisposeHook("browser.permissions", (c) => restoreGrants(c, tracked));
|
|
10150
|
+
for (const d of descriptors) {
|
|
10151
|
+
const key = grantKey(origin, d);
|
|
10152
|
+
if (!tracked.has(key)) {
|
|
10153
|
+
tracked.set(key, { origin, descriptor: d, previous: pageIsOrigin ? await queryState(page, d) : "prompt" });
|
|
10154
|
+
}
|
|
10155
|
+
await conn.send("permissions.setPermission", { descriptor: d, state: "granted", origin });
|
|
10156
|
+
}
|
|
10157
|
+
return { granted: [...permissions], origin, ...reset ? { reset: true } : {}, target };
|
|
10158
|
+
});
|
|
10159
|
+
} finally {
|
|
10160
|
+
await page.release();
|
|
10161
|
+
}
|
|
10162
|
+
}
|
|
10163
|
+
var BIDI_BROWSER_TOOLS = {
|
|
10164
|
+
wait_for_download: waitForDownloadFirefox,
|
|
10165
|
+
grant_permissions: grantPermissionsFirefox
|
|
9626
10166
|
};
|
|
9627
10167
|
|
|
9628
10168
|
// src/firefox-tools.ts
|
|
@@ -9630,6 +10170,7 @@ var FIREFOX_TOOLS = {
|
|
|
9630
10170
|
...SHARED_TOOLS,
|
|
9631
10171
|
...BIDI_ONLY_TOOLS,
|
|
9632
10172
|
...LEASE_TOOLS,
|
|
10173
|
+
...BIDI_BROWSER_TOOLS,
|
|
9633
10174
|
extract_page: extractPage
|
|
9634
10175
|
};
|
|
9635
10176
|
|
|
@@ -9672,7 +10213,7 @@ var MANIFEST = [
|
|
|
9672
10213
|
},
|
|
9673
10214
|
{
|
|
9674
10215
|
name: "new_page",
|
|
9675
|
-
description: "Open a browser tab, optionally claim it; navigation is not awaited.",
|
|
10216
|
+
description: "Open a browser tab in the background, optionally claim it; navigation is not awaited.",
|
|
9676
10217
|
inputSchema: {
|
|
9677
10218
|
type: "object",
|
|
9678
10219
|
properties: {
|
|
@@ -9699,6 +10240,10 @@ var MANIFEST = [
|
|
|
9699
10240
|
ttlMs: {
|
|
9700
10241
|
type: "number",
|
|
9701
10242
|
description: "Lease TTL in milliseconds."
|
|
10243
|
+
},
|
|
10244
|
+
focus: {
|
|
10245
|
+
type: "boolean",
|
|
10246
|
+
description: "Open in the foreground and take focus; default false (background tab)."
|
|
9702
10247
|
}
|
|
9703
10248
|
},
|
|
9704
10249
|
required: [],
|
|
@@ -9728,7 +10273,7 @@ var MANIFEST = [
|
|
|
9728
10273
|
},
|
|
9729
10274
|
{
|
|
9730
10275
|
name: "select_page",
|
|
9731
|
-
description: "
|
|
10276
|
+
description: "Persist a page as selected; focus:true also raises it. Target must resolve explicitly.",
|
|
9732
10277
|
inputSchema: {
|
|
9733
10278
|
type: "object",
|
|
9734
10279
|
properties: {
|
|
@@ -9739,6 +10284,10 @@ var MANIFEST = [
|
|
|
9739
10284
|
target: {
|
|
9740
10285
|
type: "string",
|
|
9741
10286
|
description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
|
|
10287
|
+
},
|
|
10288
|
+
focus: {
|
|
10289
|
+
type: "boolean",
|
|
10290
|
+
description: "Also raise the tab and take window focus; default false (selection only)."
|
|
9742
10291
|
}
|
|
9743
10292
|
},
|
|
9744
10293
|
required: [
|
|
@@ -10238,7 +10787,7 @@ var MANIFEST = [
|
|
|
10238
10787
|
},
|
|
10239
10788
|
{
|
|
10240
10789
|
name: "dispatch_mouse",
|
|
10241
|
-
description: "Dispatch one raw mouse event at viewport coordinates;
|
|
10790
|
+
description: "Dispatch one raw mouse event at viewport coordinates; Firefox needs 160 or newer.",
|
|
10242
10791
|
inputSchema: {
|
|
10243
10792
|
type: "object",
|
|
10244
10793
|
properties: {
|
|
@@ -10395,7 +10944,7 @@ var MANIFEST = [
|
|
|
10395
10944
|
},
|
|
10396
10945
|
{
|
|
10397
10946
|
name: "grant_permissions",
|
|
10398
|
-
description: "Grant or reset browser permissions; permissions are origin-scoped
|
|
10947
|
+
description: "Grant or reset browser permissions; permissions are origin-scoped (Chrome, Firefox 160+).",
|
|
10399
10948
|
inputSchema: {
|
|
10400
10949
|
type: "object",
|
|
10401
10950
|
properties: {
|
|
@@ -11330,7 +11879,7 @@ var MANIFEST = [
|
|
|
11330
11879
|
},
|
|
11331
11880
|
{
|
|
11332
11881
|
name: "claim_page",
|
|
11333
|
-
description: "Claim an existing tab or open a fresh one; CLI use is refused.",
|
|
11882
|
+
description: "Claim an existing tab or open a fresh one in the background; CLI use is refused.",
|
|
11334
11883
|
inputSchema: {
|
|
11335
11884
|
type: "object",
|
|
11336
11885
|
properties: {
|
|
@@ -11353,6 +11902,10 @@ var MANIFEST = [
|
|
|
11353
11902
|
ttlMs: {
|
|
11354
11903
|
type: "number",
|
|
11355
11904
|
description: "Lease TTL in milliseconds."
|
|
11905
|
+
},
|
|
11906
|
+
focus: {
|
|
11907
|
+
type: "boolean",
|
|
11908
|
+
description: "Fresh tab only: open it in the foreground; default false (background)."
|
|
11356
11909
|
}
|
|
11357
11910
|
},
|
|
11358
11911
|
required: [],
|
|
@@ -11567,13 +12120,13 @@ function toolAnnotations(name) {
|
|
|
11567
12120
|
// src/install/wizard.ts
|
|
11568
12121
|
import { createInterface } from "node:readline";
|
|
11569
12122
|
import { homedir as homedir3 } from "node:os";
|
|
11570
|
-
import { join as
|
|
12123
|
+
import { join as join17 } from "node:path";
|
|
11571
12124
|
|
|
11572
12125
|
// src/install/browser.ts
|
|
11573
12126
|
import { existsSync as existsSync3 } from "node:fs";
|
|
11574
|
-
import { mkdir as
|
|
12127
|
+
import { mkdir as mkdir15, readFile as readFile10, writeFile as writeFile11 } from "node:fs/promises";
|
|
11575
12128
|
import { homedir } from "node:os";
|
|
11576
|
-
import { delimiter, dirname as
|
|
12129
|
+
import { delimiter, dirname as dirname5, join as join15 } from "node:path";
|
|
11577
12130
|
var CANDIDATE_BUILDERS = {
|
|
11578
12131
|
chrome: () => [
|
|
11579
12132
|
process.env.CHROME_BIN,
|
|
@@ -11603,7 +12156,7 @@ function existsOnPath(cmd) {
|
|
|
11603
12156
|
for (const dir of pathEnv.split(delimiter)) {
|
|
11604
12157
|
if (!dir)
|
|
11605
12158
|
continue;
|
|
11606
|
-
if (existsSync3(
|
|
12159
|
+
if (existsSync3(join15(dir, cmd)))
|
|
11607
12160
|
return true;
|
|
11608
12161
|
}
|
|
11609
12162
|
return false;
|
|
@@ -11653,10 +12206,10 @@ function aliasLine(o) {
|
|
|
11653
12206
|
function detectShellRc() {
|
|
11654
12207
|
const shell = process.env.SHELL ?? "";
|
|
11655
12208
|
if (shell.endsWith("zsh"))
|
|
11656
|
-
return
|
|
12209
|
+
return join15(homedir(), ".zshrc");
|
|
11657
12210
|
if (shell.endsWith("bash"))
|
|
11658
|
-
return
|
|
11659
|
-
return
|
|
12211
|
+
return join15(homedir(), ".bashrc");
|
|
12212
|
+
return join15(homedir(), process.platform === "darwin" ? ".zshrc" : ".bashrc");
|
|
11660
12213
|
}
|
|
11661
12214
|
var MARKER_START = "# >>> cdp-toolkit alias >>>";
|
|
11662
12215
|
var MARKER_END = "# <<< cdp-toolkit alias <<<";
|
|
@@ -11692,7 +12245,7 @@ ${after}`);
|
|
|
11692
12245
|
await writeFile11(rcPath, next, "utf8");
|
|
11693
12246
|
return { rcPath, action: "replaced-block" };
|
|
11694
12247
|
}
|
|
11695
|
-
await
|
|
12248
|
+
await mkdir15(dirname5(rcPath), { recursive: true });
|
|
11696
12249
|
const sep = existing.length === 0 || existing.endsWith(`
|
|
11697
12250
|
`) ? "" : `
|
|
11698
12251
|
`;
|
|
@@ -11704,9 +12257,9 @@ ${after}`);
|
|
|
11704
12257
|
|
|
11705
12258
|
// src/install/harness.ts
|
|
11706
12259
|
import { spawnSync } from "node:child_process";
|
|
11707
|
-
import { mkdir as
|
|
12260
|
+
import { mkdir as mkdir16, readFile as readFile11, writeFile as writeFile12 } from "node:fs/promises";
|
|
11708
12261
|
import { homedir as homedir2 } from "node:os";
|
|
11709
|
-
import { dirname as
|
|
12262
|
+
import { dirname as dirname6, join as join16 } from "node:path";
|
|
11710
12263
|
async function installMcpServer(harness, name, cfg, opts = {}) {
|
|
11711
12264
|
switch (harness) {
|
|
11712
12265
|
case "claude":
|
|
@@ -11722,7 +12275,7 @@ async function installMcpServer(harness, name, cfg, opts = {}) {
|
|
|
11722
12275
|
}
|
|
11723
12276
|
}
|
|
11724
12277
|
async function installClaude(name, cfg, opts) {
|
|
11725
|
-
const path = opts.configPath ??
|
|
12278
|
+
const path = opts.configPath ?? join16(opts.homeDir ?? homedir2(), ".claude.json");
|
|
11726
12279
|
let root;
|
|
11727
12280
|
let fileExisted;
|
|
11728
12281
|
try {
|
|
@@ -11753,7 +12306,7 @@ async function installClaude(name, cfg, opts) {
|
|
|
11753
12306
|
if (action === "unchanged") {
|
|
11754
12307
|
return { harness: "claude", method: "file", path, action, detail: "no change needed" };
|
|
11755
12308
|
}
|
|
11756
|
-
await
|
|
12309
|
+
await mkdir16(dirname6(path), { recursive: true });
|
|
11757
12310
|
await writeFile12(path, JSON.stringify(root, null, 2) + `
|
|
11758
12311
|
`, "utf8");
|
|
11759
12312
|
return {
|
|
@@ -11990,7 +12543,7 @@ async function promptPort(def) {
|
|
|
11990
12543
|
}
|
|
11991
12544
|
function harnessTargetDesc(harness, io) {
|
|
11992
12545
|
if (harness === "claude") {
|
|
11993
|
-
return io.configPath ??
|
|
12546
|
+
return io.configPath ?? join17(io.homeDir ?? homedir3(), ".claude.json");
|
|
11994
12547
|
}
|
|
11995
12548
|
return `via \`${harness} mcp add\``;
|
|
11996
12549
|
}
|