cdp-toolkit 3.3.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/dist/index.js CHANGED
@@ -686,7 +686,7 @@ async function originIndex(backend, liveIds) {
686
686
  return index;
687
687
  }
688
688
  async function newTrackedPage(driver, backend, opts = {}) {
689
- const page = await driver.newPage(opts.url);
689
+ const page = await driver.newPage(opts.url, { focus: opts.focus === true });
690
690
  await recordOrigin(backend, page.id, { label: opts.label });
691
691
  return page;
692
692
  }
@@ -1296,6 +1296,53 @@ var init_client = __esm(() => {
1296
1296
  knownTransports = new Map;
1297
1297
  });
1298
1298
 
1299
+ // src/frontApp.ts
1300
+ import { execFile } from "node:child_process";
1301
+ function run(cmd, args) {
1302
+ return new Promise((resolve) => {
1303
+ execFile(cmd, args, { timeout: 2000 }, (err, stdout) => resolve(err ? "" : String(stdout)));
1304
+ });
1305
+ }
1306
+ function restoreFrontAppEnabled(platform = process.platform) {
1307
+ return platform === "darwin" && (process.env.CDP_RESTORE_FRONT_APP ?? "").trim() !== "0";
1308
+ }
1309
+ async function keepFrontApp(fn, opts = {}) {
1310
+ const enabled = opts.enabled ?? restoreFrontAppEnabled();
1311
+ if (!enabled)
1312
+ return fn();
1313
+ const ops = opts.ops ?? macFrontAppOps;
1314
+ const before = await ops.front().catch(() => null);
1315
+ const result = await fn();
1316
+ if (before === null)
1317
+ return result;
1318
+ const fix = async () => {
1319
+ const now = await ops.front().catch(() => null);
1320
+ if (now !== null && now !== before)
1321
+ await ops.setFront(before).catch(() => {
1322
+ return;
1323
+ });
1324
+ };
1325
+ await fix();
1326
+ await new Promise((r) => setTimeout(r, opts.recheckMs ?? 250));
1327
+ await fix();
1328
+ return result;
1329
+ }
1330
+ var macFrontAppOps;
1331
+ var init_frontApp = __esm(() => {
1332
+ macFrontAppOps = {
1333
+ async front() {
1334
+ const asn = (await run("lsappinfo", ["front"])).trim();
1335
+ if (!asn)
1336
+ return null;
1337
+ const m = /"?pid"?\s*=\s*(\d+)/.exec(await run("lsappinfo", ["info", "-only", "pid", asn]));
1338
+ return m ? Number(m[1]) : null;
1339
+ },
1340
+ async setFront(pid) {
1341
+ await run("osascript", ["-e", `tell application "System Events" to set frontmost of (first process whose unix id is ${pid}) to true`]);
1342
+ }
1343
+ };
1344
+ });
1345
+
1299
1346
  // src/activity.ts
1300
1347
  function dispatchKey(backend, targetId) {
1301
1348
  return `${backend}:${targetId}`;
@@ -2000,6 +2047,7 @@ function implicitRole(el) {
2000
2047
  // src/cdp/driver.ts
2001
2048
  init_client();
2002
2049
  init_session();
2050
+ init_frontApp();
2003
2051
  init_leases();
2004
2052
  init_endpoints();
2005
2053
  init_activity();
@@ -2177,6 +2225,47 @@ async function centerOf(conn, objectId) {
2177
2225
  throw driverError("page-error", "element has zero size / is not visible; cannot compute a click point");
2178
2226
  return result.value;
2179
2227
  }
2228
+ 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);}";
2229
+ 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);});}";
2230
+ 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';}";
2231
+ async function insertTextVerified(conn, objectId, text, sendInput) {
2232
+ const call = async (fn, args = [], awaitPromise = false) => {
2233
+ const { result, exceptionDetails } = await conn.send("Runtime.callFunctionOn", {
2234
+ objectId,
2235
+ functionDeclaration: fn,
2236
+ arguments: args.map((value) => ({ value })),
2237
+ returnByValue: true,
2238
+ awaitPromise
2239
+ });
2240
+ if (exceptionDetails)
2241
+ throw driverError("page-error", `text input check failed: ${exceptionDetails.text ?? "error"}`);
2242
+ return result?.value;
2243
+ };
2244
+ const before = await call(SNAPSHOT_TEXT_FN);
2245
+ await sendInput("Input.insertText", { text });
2246
+ if (await call(LANDED_TEXT_FN, [before], true) === true)
2247
+ return "trusted";
2248
+ const via = await call(FALLBACK_TEXT_FN, [text]);
2249
+ if (via === "execCommand" || via === "setter" || via === "skipped")
2250
+ return via;
2251
+ 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");
2252
+ }
2253
+ var ARM_KEY_WITNESS = "(function(){window.__cdpKeySeen=false;window.addEventListener('keydown',function(){window.__cdpKeySeen=true;},{capture:true,once:true});return true;})()";
2254
+ var READ_KEY_WITNESS = "(function(){if(window.__cdpKeySeen===true)return true;return new Promise(function(r){setTimeout(function(){r(window.__cdpKeySeen===true);},50);});})()";
2255
+ async function pressKeyObserved(conn, dispatch) {
2256
+ const eval_ = (expression, awaitPromise = false) => conn.send("Runtime.evaluate", { expression, returnByValue: true, awaitPromise }).then((r) => r.result?.value, () => {
2257
+ return;
2258
+ });
2259
+ const armed = await eval_(ARM_KEY_WITNESS) === true;
2260
+ await dispatch();
2261
+ if (!armed)
2262
+ return;
2263
+ const seen = await eval_(READ_KEY_WITNESS, true);
2264
+ if (seen === false)
2265
+ return { delivered: false };
2266
+ if (seen === true)
2267
+ return { delivered: true };
2268
+ }
2180
2269
  async function focusElement(conn, objectId) {
2181
2270
  await conn.send("Runtime.callFunctionOn", { objectId, functionDeclaration: "function(){this.focus&&this.focus();}", returnByValue: true });
2182
2271
  }
@@ -2191,10 +2280,12 @@ async function awaitScrollSettle(conn) {
2191
2280
  }
2192
2281
  async function setValueOnObject(conn, objectId, value, sendInput) {
2193
2282
  await focusElement(conn, objectId);
2194
- const fn = "function(){if('value'in this){this.value='';this.dispatchEvent(new Event('input',{bubbles:true}));}else if(this.isContentEditable){this.textContent='';}}";
2195
- await conn.send("Runtime.callFunctionOn", { objectId, functionDeclaration: fn, returnByValue: true });
2196
- if (value.length)
2197
- await sendInput("Input.insertText", { text: value });
2283
+ 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';}";
2284
+ const { result } = await conn.send("Runtime.callFunctionOn", { objectId, functionDeclaration: fn, returnByValue: true });
2285
+ if (result?.value === "disabled" || result?.value === "readonly") {
2286
+ throw driverError("page-error", `cannot fill a ${result.value} field: it was left unchanged`);
2287
+ }
2288
+ return value.length ? insertTextVerified(conn, objectId, value, sendInput) : "trusted";
2198
2289
  }
2199
2290
  var NAMED_KEYS = {
2200
2291
  enter: { key: "Enter", code: "Enter", keyCode: 13, text: "\r" },
@@ -2742,13 +2833,12 @@ class CdpPageDriver {
2742
2833
  }
2743
2834
  async setValue(loc, value) {
2744
2835
  const { objectId } = await resolveElementLocator(this.conn, loc);
2745
- await setValueOnObject(this.conn, objectId, value, (method, params) => this.dispatchInput(method, params));
2836
+ return setValueOnObject(this.conn, objectId, value, (method, params) => this.dispatchInput(method, params));
2746
2837
  }
2747
2838
  async typeText(loc, text) {
2748
2839
  const { objectId } = await resolveElementLocator(this.conn, loc);
2749
2840
  await focusElement(this.conn, objectId);
2750
- if (text.length)
2751
- await this.dispatchInput("Input.insertText", { text });
2841
+ return text.length ? insertTextVerified(this.conn, objectId, text, (method, params) => this.dispatchInput(method, params)) : "trusted";
2752
2842
  }
2753
2843
  async pressKey(press) {
2754
2844
  const spec = resolveKey(press.key);
@@ -2763,8 +2853,10 @@ class CdpPageDriver {
2763
2853
  const down = { type: "keyDown", key: spec.key, code: spec.code, windowsVirtualKeyCode: spec.keyCode, nativeVirtualKeyCode: spec.keyCode, modifiers: modBits };
2764
2854
  if (spec.text && !suppressText)
2765
2855
  down.text = spec.text;
2766
- await this.dispatchInput("Input.dispatchKeyEvent", down);
2767
- await this.dispatchInput("Input.dispatchKeyEvent", { type: "keyUp", key: spec.key, code: spec.code, windowsVirtualKeyCode: spec.keyCode, nativeVirtualKeyCode: spec.keyCode, modifiers: modBits });
2856
+ return pressKeyObserved(this.conn, async () => {
2857
+ await this.dispatchInput("Input.dispatchKeyEvent", down);
2858
+ await this.dispatchInput("Input.dispatchKeyEvent", { type: "keyUp", key: spec.key, code: spec.code, windowsVirtualKeyCode: spec.keyCode, nativeVirtualKeyCode: spec.keyCode, modifiers: modBits });
2859
+ });
2768
2860
  }
2769
2861
  async setFiles(loc, files) {
2770
2862
  const { objectId } = await resolveElementLocator(this.conn, loc);
@@ -3141,7 +3233,7 @@ function noSuchTarget(e) {
3141
3233
  throw driverError("no-such-target", e instanceof CdpError ? e.message : String(e));
3142
3234
  }
3143
3235
  var NEW_TARGET_SETTLE_MS = 2000;
3144
- async function createSettledTarget(conn, url, settleMs = NEW_TARGET_SETTLE_MS) {
3236
+ async function createSettledTarget(conn, url, settleMs = NEW_TARGET_SETTLE_MS, opts = {}) {
3145
3237
  const changed = new Set;
3146
3238
  let id = "";
3147
3239
  let wake;
@@ -3157,7 +3249,8 @@ async function createSettledTarget(conn, url, settleMs = NEW_TARGET_SETTLE_MS) {
3157
3249
  await conn.send("Target.setDiscoverTargets", { discover: true }).catch(() => {
3158
3250
  return;
3159
3251
  });
3160
- const { targetId } = await conn.send("Target.createTarget", { url });
3252
+ const create = () => conn.send("Target.createTarget", { url, background: opts.focus !== true });
3253
+ const { targetId } = opts.focus === true ? await create() : await keepFrontApp(create);
3161
3254
  if (!targetId)
3162
3255
  throw driverError("page-error", "Target.createTarget returned no targetId");
3163
3256
  id = targetId;
@@ -3187,15 +3280,15 @@ class CdpBrowserDriver {
3187
3280
  const filtered = opts?.all ? targets : targets.filter((t) => t.type === "page");
3188
3281
  return filtered.map((t) => ({ id: t.id, url: t.url, title: t.title, type: t.type }));
3189
3282
  }
3190
- async newPage(url) {
3283
+ async newPage(url, opts) {
3191
3284
  return withBrowserConn(async (conn) => {
3192
- const targetId = await createSettledTarget(conn, url ?? "about:blank");
3285
+ const targetId = await createSettledTarget(conn, url ?? "about:blank", NEW_TARGET_SETTLE_MS, { focus: opts?.focus === true });
3193
3286
  return { id: targetId, url: url ?? "about:blank", title: "" };
3194
3287
  });
3195
3288
  }
3196
3289
  async closePage(id) {
3197
3290
  return withBrowserConn(async (conn) => {
3198
- const res = await conn.send("Target.closeTarget", { targetId: id });
3291
+ const res = await keepFrontApp(() => conn.send("Target.closeTarget", { targetId: id }));
3199
3292
  if (res.success !== false)
3200
3293
  beaconSessions.drop(beaconKey(id));
3201
3294
  return { success: res.success ?? true };
@@ -3865,7 +3958,6 @@ init_workers();
3865
3958
  init_frames();
3866
3959
  init_endpoints();
3867
3960
  var ARTIFACT_DIR = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
3868
- var STATE_DIR = process.env.CDP_STATE_DIR ?? "/tmp/cdp-toolkit";
3869
3961
 
3870
3962
  class SharedToolError extends Error {
3871
3963
  }
@@ -4024,7 +4116,7 @@ async function listPagesOne(driver, args = {}) {
4024
4116
  }
4025
4117
  async function newPage(driver, args = {}) {
4026
4118
  const label = typeof args.label === "string" && args.label.length ? args.label : defaultLabel();
4027
- const p = await newTrackedPage(driver, backendOf(driver), { url: args.url, label });
4119
+ const p = await newTrackedPage(driver, backendOf(driver), { url: args.url, label, focus: args.focus === true });
4028
4120
  const explicit = args.claim === true;
4029
4121
  if (!explicit && !requireLease())
4030
4122
  return { targetId: p.id, url: p.url };
@@ -4047,16 +4139,17 @@ async function closePage(driver, args) {
4047
4139
  return { closed: p.id, success: true, ...released.released ? { leaseReleased: true } : {} };
4048
4140
  }
4049
4141
  async function writeSelectedFile(id) {
4050
- await mkdir5(STATE_DIR, { recursive: true });
4051
- await writeFile4(join5(STATE_DIR, "selected"), id, "utf8");
4142
+ const stateDir = process.env.CDP_STATE_DIR ?? "/tmp/cdp-toolkit";
4143
+ await mkdir5(stateDir, { recursive: true });
4144
+ await writeFile4(join5(stateDir, "selected"), id, "utf8");
4052
4145
  }
4053
4146
  async function selectPage(driver, args) {
4054
4147
  if (args.target === undefined || args.target === "")
4055
4148
  throw new SharedToolError("select_page requires an explicit target");
4056
4149
  const p = await resolvePage(driver, args.target);
4057
- const activated = await driver.activatePage(p.id);
4058
- await writeSelectedFile(activated.id);
4059
- return { selected: activated.id };
4150
+ const id = args.focus === true ? (await driver.activatePage(p.id)).id : p.id;
4151
+ await writeSelectedFile(id);
4152
+ return { selected: id, focused: args.focus === true };
4060
4153
  }
4061
4154
  function toLegacyWaitedFor(w) {
4062
4155
  if (w === "committed")
@@ -4415,14 +4508,17 @@ async function drag(driver, args) {
4415
4508
  };
4416
4509
  });
4417
4510
  }
4511
+ function inputPathField(path) {
4512
+ return path && path !== "trusted" ? { inputPath: path } : {};
4513
+ }
4418
4514
  async function fill(driver, args) {
4419
4515
  if (typeof args.value !== "string")
4420
4516
  throw new SharedToolError("fill requires a string { value }");
4421
4517
  const loc = locatorOf(args);
4422
4518
  return withPage2(driver, args.target, async (page) => {
4423
4519
  const element = await describeElement(page, loc);
4424
- await page.setValue(loc, args.value);
4425
- return { filled: true, ...elementField(element), value: args.value };
4520
+ const path = await page.setValue(loc, args.value);
4521
+ return { filled: true, ...elementField(element), value: args.value, ...inputPathField(path) };
4426
4522
  });
4427
4523
  }
4428
4524
  async function fillForm(driver, args) {
@@ -4431,15 +4527,16 @@ async function fillForm(driver, args) {
4431
4527
  return withPage2(driver, args.target, async (page) => {
4432
4528
  let filled = 0;
4433
4529
  const elements = [];
4530
+ const paths = [];
4434
4531
  for (const f of args.fields) {
4435
4532
  if (typeof f.value !== "string")
4436
4533
  throw new SharedToolError("each fill_form field requires a string value");
4437
4534
  const loc = locatorOf(f);
4438
4535
  elements.push(await describeElement(page, loc) ?? null);
4439
- await page.setValue(loc, f.value);
4536
+ paths.push(await page.setValue(loc, f.value) || "trusted");
4440
4537
  filled++;
4441
4538
  }
4442
- return { filled, fields: args.fields.length, elements };
4539
+ return { filled, fields: args.fields.length, elements, ...paths.some((p) => p !== "trusted") ? { inputPaths: paths } : {} };
4443
4540
  });
4444
4541
  }
4445
4542
  async function typeText(driver, args) {
@@ -4448,8 +4545,8 @@ async function typeText(driver, args) {
4448
4545
  const loc = locatorOf(args);
4449
4546
  return withPage2(driver, args.target, async (page) => {
4450
4547
  const element = await describeElement(page, loc);
4451
- await page.typeText(loc, args.text);
4452
- return { typed: true, ...elementField(element), text: args.text };
4548
+ const path = await page.typeText(loc, args.text);
4549
+ return { typed: true, ...elementField(element), text: args.text, ...inputPathField(path) };
4453
4550
  });
4454
4551
  }
4455
4552
  async function pressKey(driver, args) {
@@ -4457,7 +4554,15 @@ async function pressKey(driver, args) {
4457
4554
  throw new SharedToolError("press_key requires a non-empty { key }");
4458
4555
  const modifiers = args.modifiers ?? [];
4459
4556
  return withPage2(driver, args.target, async (page) => {
4460
- await page.pressKey({ key: args.key, modifiers });
4557
+ const res = await page.pressKey({ key: args.key, modifiers });
4558
+ if (res && res.delivered === false) {
4559
+ return {
4560
+ pressed: args.key,
4561
+ modifiers,
4562
+ delivered: false,
4563
+ 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."
4564
+ };
4565
+ }
4461
4566
  return { pressed: args.key, modifiers };
4462
4567
  });
4463
4568
  }
@@ -4725,7 +4830,7 @@ async function claimPage(driver, args = {}) {
4725
4830
  url = existing.url;
4726
4831
  opened = false;
4727
4832
  } else {
4728
- const page = await newTrackedPage(driver, backend, { url: args.url, label });
4833
+ const page = await newTrackedPage(driver, backend, { url: args.url, label, focus: args.focus === true });
4729
4834
  targetId = page.id;
4730
4835
  url = page.url;
4731
4836
  opened = true;
@@ -5225,7 +5330,7 @@ init_client();
5225
5330
  import { mkdir as mkdir7, readFile as readFile7, writeFile as writeFile6, stat, unlink as unlink4 } from "node:fs/promises";
5226
5331
  import { join as join6 } from "node:path";
5227
5332
  var ARTIFACT_DIR2 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
5228
- var STATE_DIR2 = process.env.CDP_STATE_DIR ?? "/tmp/cdp-toolkit";
5333
+ var STATE_DIR = process.env.CDP_STATE_DIR ?? "/tmp/cdp-toolkit";
5229
5334
  var DEFAULT_CATEGORIES = [
5230
5335
  "devtools.timeline",
5231
5336
  "blink.user_timing",
@@ -5241,7 +5346,7 @@ function shortId(id) {
5241
5346
  return id.slice(0, 8);
5242
5347
  }
5243
5348
  function stateFilePath() {
5244
- return join6(STATE_DIR2, "trace-state.json");
5349
+ return join6(STATE_DIR, "trace-state.json");
5245
5350
  }
5246
5351
  function bufferTraceData(conn, sink) {
5247
5352
  return conn.on("Tracing.dataCollected", (params) => {
@@ -5286,7 +5391,7 @@ async function performanceStartTrace(args = {}) {
5286
5391
  throw err;
5287
5392
  }
5288
5393
  liveTraces.set(target.id, { conn, target, events, startedAt: Date.now() });
5289
- await mkdir7(STATE_DIR2, { recursive: true });
5394
+ await mkdir7(STATE_DIR, { recursive: true });
5290
5395
  const state = {
5291
5396
  targetId: target.id,
5292
5397
  url: target.url,
@@ -5615,7 +5720,7 @@ function buildFfmpegArgs(manifestPath, outPath, choice) {
5615
5720
  outPath
5616
5721
  ];
5617
5722
  }
5618
- function run(bin, args) {
5723
+ function run2(bin, args) {
5619
5724
  return new Promise((resolve, reject) => {
5620
5725
  const child = spawn(bin, args, { stdio: ["ignore", "pipe", "pipe"] });
5621
5726
  let stdout = "";
@@ -5637,7 +5742,7 @@ async function probeEncoder() {
5637
5742
  encoderProbe = (async () => {
5638
5743
  let res;
5639
5744
  try {
5640
- res = await run(FFMPEG_BIN, ["-hide_banner", "-encoders"]);
5745
+ res = await run2(FFMPEG_BIN, ["-hide_banner", "-encoders"]);
5641
5746
  } catch (err) {
5642
5747
  throw new CdpError(`${FFMPEG_MISSING} (${err.message})`);
5643
5748
  }
@@ -5646,7 +5751,7 @@ async function probeEncoder() {
5646
5751
  const choice = selectEncoder(`${res.stdout}
5647
5752
  ${res.stderr}`);
5648
5753
  const output = async (args) => {
5649
- const r = await run(FFMPEG_BIN, args).catch(() => {
5754
+ const r = await run2(FFMPEG_BIN, args).catch(() => {
5650
5755
  return;
5651
5756
  });
5652
5757
  return r && r.code === 0 ? `${r.stdout}
@@ -5819,7 +5924,7 @@ async function stopScreenRecording(args = {}) {
5819
5924
  const { width, height } = evenDimensions(ledger[0].width, ledger[0].height);
5820
5925
  let res;
5821
5926
  try {
5822
- res = await run(FFMPEG_BIN, buildFfmpegArgs(manifestPath, outPath, rec.encoder));
5927
+ res = await run2(FFMPEG_BIN, buildFfmpegArgs(manifestPath, outPath, rec.encoder));
5823
5928
  } catch (err) {
5824
5929
  throw new CdpError(`${FFMPEG_MISSING} Spooled frames kept at ${rec.spoolDir}. (${err.message})`);
5825
5930
  }