@xbrowser/cli 1.29.0 → 1.30.1

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.
Files changed (36) hide show
  1. package/README.md +2 -2
  2. package/dist/{browser-XD3IOU5I.js → browser-6PFTHZI3.js} +2 -2
  3. package/dist/{browser-2K3XYAKM.js → browser-I2NLJN2A.js} +1 -1
  4. package/dist/{browser-OTEMG5NL.js → browser-KOUA4ZDA.js} +2 -2
  5. package/dist/{cdp-driver-AAS55KT2.js → cdp-driver-3ETNFQA4.js} +1 -1
  6. package/dist/{cdp-driver-XTPY7EXP.js → cdp-driver-U7HDQMQ5.js} +257 -19
  7. package/dist/{cdp-driver-O5I7SJ24.js → cdp-driver-WBFJNOLD.js} +1 -1
  8. package/dist/{chunk-SCYBNSOG.js → chunk-3K57RYVC.js} +378 -115
  9. package/dist/{chunk-FNXA6FDM.js → chunk-BND5O5KC.js} +2 -1
  10. package/dist/{chunk-P33R7F2D.js → chunk-BOZTIIBT.js} +30 -45
  11. package/dist/{chunk-GDKKVT2P.js → chunk-KPTD3SNJ.js} +379 -116
  12. package/dist/{chunk-CO2ZVOVT.js → chunk-NINETOM4.js} +30 -45
  13. package/dist/{chunk-SOPN4XDK.js → chunk-O5PASNI7.js} +2 -1
  14. package/dist/{chunk-NQPXZ74W.js → chunk-OCECE22C.js} +257 -19
  15. package/dist/{chunk-LFSLNHW5.js → chunk-OSIDUT4H.js} +286 -63
  16. package/dist/{chunk-HBMEFSTB.js → chunk-QCV2PI7U.js} +2 -1
  17. package/dist/{chunk-UZ6XPUBD.js → chunk-RMYKVZIZ.js} +78 -0
  18. package/dist/{chunk-N5XTLNKS.js → chunk-SPNWUUHA.js} +257 -19
  19. package/dist/{chunk-PGKV24QN.js → chunk-TBJUSUKF.js} +1 -1
  20. package/dist/{chunk-FCPVQFTQ.js → chunk-VYTQLZAX.js} +78 -0
  21. package/dist/cli.js +45 -16
  22. package/dist/daemon-main.js +581 -157
  23. package/dist/{human-interaction-CTZ4IWXJ.js → human-interaction-ISMMOJOK.js} +2 -2
  24. package/dist/{human-interaction-HJCK45SL.js → human-interaction-STTZZZ5N.js} +1 -1
  25. package/dist/{human-interaction-V3VDGHHI.js → human-interaction-UXFYV7DU.js} +1 -1
  26. package/dist/index.d.ts +106 -12
  27. package/dist/index.js +195 -46
  28. package/dist/{recovery-EBKORYEU.js → recovery-JFGV3DBX.js} +1 -1
  29. package/dist/{recovery-5C4FBA5O.js → recovery-ORHJSBDN.js} +2 -2
  30. package/dist/{recovery-IMZUGWSS.js → recovery-XDKN63O5.js} +1 -1
  31. package/dist/{server-ZTI2K5YJ.js → server-TG47W7MV.js} +3 -3
  32. package/dist/{server-LNZTDAKT.js → server-U3YAX5MJ.js} +2 -2
  33. package/dist/{session-recorder-DF2YGH2E.js → session-recorder-N7VEKJVW.js} +1 -1
  34. package/dist/{session-recorder-R3GDGXLJ.js → session-recorder-RUNQOJ7T.js} +1 -1
  35. package/dist/{session-replayer-CLTZ2URU.js → session-replayer-XLWQ47BB.js} +1 -1
  36. package/package.json +4 -1
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  createRuleEngine,
3
3
  launch
4
- } from "./chunk-NQPXZ74W.js";
4
+ } from "./chunk-OCECE22C.js";
5
5
  import {
6
6
  errMsg
7
7
  } from "./chunk-GDKLH7ZY.js";
@@ -796,6 +796,7 @@ async function createSessionImpl(name, url, options, deps) {
796
796
  const isCDP = !!options?.cdpEndpoint;
797
797
  let context;
798
798
  let page;
799
+ let reusedExistingPage = false;
799
800
  if (isCDP) {
800
801
  const targetHostname = url ? (() => {
801
802
  try {
@@ -877,22 +878,12 @@ async function createSessionImpl(name, url, options, deps) {
877
878
  const pUrl0 = await resolvePageUrl(p);
878
879
  if (ownedUrls.has(pUrl0)) continue;
879
880
  const pUrl = pUrl0;
880
- if (isRealPageUrl(pUrl) && pUrl.includes(targetHostname)) {
881
- targetPage = p;
882
- break;
881
+ let hostnameMatches = false;
882
+ try {
883
+ hostnameMatches = new URL(pUrl).hostname === targetHostname;
884
+ } catch {
883
885
  }
884
- }
885
- if (targetPage) break;
886
- }
887
- }
888
- if (!targetPage) {
889
- for (const ctx of contexts) {
890
- const pages = ctx.pages();
891
- for (const p of pages) {
892
- const pUrl0 = await resolvePageUrl(p);
893
- if (ownedUrls.has(pUrl0)) continue;
894
- const pUrl = pUrl0;
895
- if (isRealPageUrl(pUrl)) {
886
+ if (isRealPageUrl(pUrl) && hostnameMatches) {
896
887
  targetPage = p;
897
888
  break;
898
889
  }
@@ -910,9 +901,15 @@ async function createSessionImpl(name, url, options, deps) {
910
901
  } catch {
911
902
  }
912
903
  }
913
- const matchTarget = targets.find(
914
- (t) => t.url && t.url !== "about:blank" && !t.url.startsWith("chrome://") && !t.url.startsWith("chrome-untrusted://") && !t.url.startsWith("chrome-error://") && !ownedUrlsT.has(t.url) && (url ? t.url === url || t.url.includes(new URL(url).hostname) : true)
915
- );
904
+ const matchTarget = targets.find((t) => {
905
+ if (!t.url || !isRealPageUrl(t.url) || ownedUrlsT.has(t.url)) return false;
906
+ if (!url) return false;
907
+ try {
908
+ return new URL(t.url).hostname === targetHostname;
909
+ } catch {
910
+ return false;
911
+ }
912
+ });
916
913
  if (matchTarget && matchTarget.url) {
917
914
  const ownedUrls2 = /* @__PURE__ */ new Set();
918
915
  for (const ssn of sessions.list()) {
@@ -945,31 +942,12 @@ async function createSessionImpl(name, url, options, deps) {
945
942
  }
946
943
  }
947
944
  }
945
+ const targetPageExisted = !!targetPage;
948
946
  if (!targetPage) {
949
- const pages = context.pages();
950
- if (pages.length > 1) {
951
- try {
952
- const owned = /* @__PURE__ */ new Set();
953
- for (const ssn of sessions.list()) owned.add(ssn.page);
954
- for (const p of pages) {
955
- if (owned.has(p)) continue;
956
- const vis = await p.evaluate("document.visibilityState").catch(() => "hidden");
957
- if (vis === "visible") {
958
- targetPage = p;
959
- break;
960
- }
961
- }
962
- } catch {
963
- }
964
- }
965
- if (!targetPage && pages.length > 0) {
966
- targetPage = pages[0];
967
- }
968
- if (!targetPage) {
969
- targetPage = await context.newPage();
970
- }
947
+ targetPage = await context.newPage();
971
948
  }
972
949
  page = targetPage;
950
+ reusedExistingPage = targetPageExisted;
973
951
  if (isCDP) {
974
952
  await Promise.resolve(targetPage.bringToFront?.()).catch(() => {
975
953
  });
@@ -988,7 +966,8 @@ async function createSessionImpl(name, url, options, deps) {
988
966
  page,
989
967
  browser: b,
990
968
  isCDP,
991
- cdpEndpoint: options?.cdpEndpoint
969
+ cdpEndpoint: options?.cdpEndpoint,
970
+ ...isCDP ? { reusedExistingPage } : {}
992
971
  });
993
972
  deps.logSessionEvent("create_session", `name="${name}" id="${session.id}" url="${url || "(no url)"}" isCDP=${isCDP} cdpEndpoint=${options?.cdpEndpoint || "(none)"}`);
994
973
  await deps.installNetworkCapture(page, name);
@@ -1247,8 +1226,14 @@ async function closeSessionByName(name) {
1247
1226
  if (session.name === name || session.id === name) {
1248
1227
  logSessionEvent2("close_session", `name="${session.name}" id="${session.id}" url="${session.page.url()}"`);
1249
1228
  if (session.isCDP) {
1250
- if (session.browser) {
1251
- await session.browser.close().catch(() => {
1229
+ if (session.reusedExistingPage) {
1230
+ logSessionEvent2("close_session", `name="${session.name}" \u2014 reused existing tab, disconnecting only`);
1231
+ await session.browser.disconnect().catch(() => {
1232
+ });
1233
+ } else {
1234
+ await session.page.close().catch(() => {
1235
+ });
1236
+ await session.browser.disconnect().catch(() => {
1252
1237
  });
1253
1238
  }
1254
1239
  } else {
@@ -1271,7 +1256,7 @@ async function closeSessionByName(name) {
1271
1256
  } catch {
1272
1257
  }
1273
1258
  try {
1274
- const { SessionRecorder } = await import("./session-recorder-DF2YGH2E.js");
1259
+ const { SessionRecorder } = await import("./session-recorder-N7VEKJVW.js");
1275
1260
  SessionRecorder.cleanup(session.name);
1276
1261
  } catch {
1277
1262
  }
@@ -47,7 +47,8 @@ var ScreencastCapturer = class {
47
47
  if (!cb) return;
48
48
  cdp.send("Page.screencastFrameAck", { sessionId: params.sessionId }).catch(() => {
49
49
  });
50
- const viewport = {
50
+ const logicalViewport = page.viewportSize();
51
+ const viewport = logicalViewport ?? {
51
52
  width: params.metadata?.deviceWidth || this.maxWidth,
52
53
  height: params.metadata?.deviceHeight || this.maxHeight
53
54
  };
@@ -34,12 +34,16 @@ import { EventEmitter as EventEmitter2 } from "events";
34
34
  import { EventEmitter } from "events";
35
35
 
36
36
  // src/cdp-driver/mouse.ts
37
+ function buttonBit(button) {
38
+ return button === "left" ? 1 : button === "right" ? 2 : 4;
39
+ }
37
40
  var XBMouseImpl = class {
38
41
  conn;
39
42
  sessionId;
40
43
  _x = 0;
41
44
  _y = 0;
42
45
  _button = "none";
46
+ _buttons = 0;
43
47
  constructor(conn, sessionId) {
44
48
  this.conn = conn;
45
49
  this.sessionId = sessionId;
@@ -70,7 +74,7 @@ var XBMouseImpl = class {
70
74
  _truncated = true;
71
75
  break;
72
76
  }
73
- await this.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: p.x, y: p.y, button: this._button });
77
+ await this.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: p.x, y: p.y, button: this._button, buttons: this._buttons });
74
78
  this._x = p.x;
75
79
  this._y = p.y;
76
80
  await sleep(p.delay);
@@ -78,7 +82,7 @@ var XBMouseImpl = class {
78
82
  this._x = tx;
79
83
  this._y = ty;
80
84
  if (_truncated) {
81
- await this.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: tx, y: ty, button: this._button });
85
+ await this.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: tx, y: ty, button: this._button, buttons: this._buttons });
82
86
  }
83
87
  await sleep(rand(...DEFAULT_STEALTH_CONFIG.aimPause));
84
88
  } else {
@@ -90,7 +94,7 @@ var XBMouseImpl = class {
90
94
  const ry = stealth ? this._y + rand(...DEFAULT_STEALTH_CONFIG.releaseDrift) * (Math.random() < 0.5 ? -1 : 1) : this._y;
91
95
  this._x = rx;
92
96
  this._y = ry;
93
- await this.send("Input.dispatchMouseEvent", { type: "mouseReleased", x: rx, y: ry, button, clickCount: opts.clickCount ?? 1 });
97
+ await this.send("Input.dispatchMouseEvent", { type: "mouseReleased", x: rx, y: ry, button, buttons: this._buttons, clickCount: opts.clickCount ?? 1 });
94
98
  for (let i = 1; i < (opts.clickCount ?? 1); i++) {
95
99
  if (opts.delay) await sleep(opts.delay);
96
100
  await this.down({ button });
@@ -103,11 +107,13 @@ var XBMouseImpl = class {
103
107
  async down(opts = {}) {
104
108
  const button = opts.button ?? "left";
105
109
  this._button = button;
110
+ this._buttons |= buttonBit(button);
106
111
  await this.send("Input.dispatchMouseEvent", {
107
112
  type: "mousePressed",
108
113
  x: this._x,
109
114
  y: this._y,
110
115
  button,
116
+ buttons: this._buttons,
111
117
  // r23: press 必须与 release 声明同一 clickCount——Chrome 按序列计数
112
118
  // 合成 click/dblclick,press 缺声明会把计数器重置(dblclick 永不合成)
113
119
  clickCount: opts.clickCount ?? 1
@@ -121,8 +127,11 @@ var XBMouseImpl = class {
121
127
  x: this._x,
122
128
  y: this._y,
123
129
  button,
130
+ // release 先带位发送再清位(Puppeteer 同序——DOM mouseup 的 buttons 反映释放后状态)
131
+ buttons: this._buttons,
124
132
  clickCount: opts.clickCount ?? 1
125
133
  });
134
+ this._buttons &= ~buttonBit(button);
126
135
  }
127
136
  async move(x, y, opts = {}) {
128
137
  const stealth = opts.stealth ?? process.env.XBROWSER_STEALTH !== "off";
@@ -140,7 +149,8 @@ var XBMouseImpl = class {
140
149
  type: "mouseMoved",
141
150
  x: this._x,
142
151
  y: this._y,
143
- button: this._button
152
+ button: this._button,
153
+ buttons: this._buttons
144
154
  });
145
155
  }
146
156
  this._x = x;
@@ -160,9 +170,11 @@ var XBMouseImpl = class {
160
170
  x: this._x,
161
171
  y: this._y,
162
172
  button: "left",
173
+ buttons: 1,
163
174
  clickCount: 1
164
175
  });
165
176
  this._button = "left";
177
+ this._buttons |= 1;
166
178
  const steps = opts.steps ?? Math.max(10, Math.min(24, Math.round(Math.hypot(x - this._x, y - this._y) / 20)));
167
179
  const fx = this._x, fy = this._y;
168
180
  for (let i = 1; i <= steps; i++) {
@@ -174,7 +186,8 @@ var XBMouseImpl = class {
174
186
  type: "mouseMoved",
175
187
  x: this._x,
176
188
  y: this._y,
177
- button: this._button
189
+ button: this._button,
190
+ buttons: this._buttons
178
191
  });
179
192
  }
180
193
  this._x = x;
@@ -185,15 +198,22 @@ var XBMouseImpl = class {
185
198
  x,
186
199
  y,
187
200
  button: "left",
201
+ buttons: this._buttons,
188
202
  clickCount: 1
189
203
  });
190
204
  this._button = "none";
205
+ this._buttons &= ~1;
206
+ }
207
+ async wheelAt(x, y, deltaX, deltaY) {
208
+ await this.move(x, y);
209
+ await this.wheel(deltaX, deltaY);
191
210
  }
192
211
  async wheel(deltaX, deltaY) {
193
212
  await this.send("Input.dispatchMouseEvent", {
194
213
  type: "mouseWheel",
195
214
  x: this._x,
196
215
  y: this._y,
216
+ buttons: this._buttons,
197
217
  deltaX,
198
218
  deltaY
199
219
  });
@@ -1353,7 +1373,7 @@ var MediaService = class {
1353
1373
  y: Math.round(opts.clip.y),
1354
1374
  width: Math.round(Math.max(1, opts.clip.width)),
1355
1375
  height: Math.round(Math.max(1, opts.clip.height)),
1356
- scale: 1
1376
+ scale: opts.clip.scale ?? 1
1357
1377
  };
1358
1378
  params.clip = clip;
1359
1379
  }
@@ -2350,14 +2370,13 @@ var RuntimeEvaluationService = class {
2350
2370
  }
2351
2371
  return result.result?.value;
2352
2372
  };
2353
- try {
2354
- const tg = await this.options.conn.send("Target.getTargets", void 0);
2355
- const hit2 = (tg.targetInfos || []).find((t) => t.type === "iframe" && (t.url || "").includes(urlIncludes));
2356
- if (hit2) {
2357
- const att = await this.options.conn.send("Target.attachToTarget", { targetId: hit2.targetId, flatten: true });
2358
- return evalIn(att.sessionId);
2373
+ const attachedA = await this.tryAttachViaTargets(urlIncludes);
2374
+ if (attachedA) {
2375
+ try {
2376
+ return await evalIn(attachedA);
2377
+ } finally {
2378
+ this.detachQuietly(attachedA);
2359
2379
  }
2360
- } catch {
2361
2380
  }
2362
2381
  const tree = await this.options.conn.send("Page.getFrameTree", void 0, this.options.sessionId);
2363
2382
  const all = [];
@@ -2385,6 +2404,87 @@ var RuntimeEvaluationService = class {
2385
2404
  const ctx = contexts.find((c) => c.frameId === target.id);
2386
2405
  if (ctx) return evalIn(this.options.sessionId, ctx.id);
2387
2406
  }
2407
+ const attachedC = await this.tryAttachViaAutoAttach(urlIncludes);
2408
+ if (attachedC) {
2409
+ try {
2410
+ return await evalIn(attachedC);
2411
+ } finally {
2412
+ this.detachQuietly(attachedC);
2413
+ }
2414
+ }
2415
+ throw new Error(`frame not found for "${urlIncludes}"\uFF08OOPIF target\u3001frame \u6811\u3001auto-attach \u4E09\u8DEF\u5747\u672A\u547D\u4E2D\uFF1B\u53EF\u80FD\u4ECD\u5728\u52A0\u8F7D\uFF09`);
2416
+ }
2417
+ /**
2418
+ * 输入专用 frame session 解析(mouse/click/fill --frame)。
2419
+ *
2420
+ * 与 evaluateInFrame 的区别:必须拿到**真实 target session**(Input 域
2421
+ * 事件派发到该 session 才会进入 iframe 的渲染进程——主页面 session 上
2422
+ * 派发的输入进不去 OOPIF,qqmail 验证码 4 次页面级拖动全败的实证)。
2423
+ * 因此只走 A(getTargets attach)/ C(auto-attach)两路;同进程 frame
2424
+ * 没有 session,但 locator 层的坐标偏移本就支持同源 iframe,直接用普通
2425
+ * click/fill 即可。
2426
+ *
2427
+ * 坐标语义:返回的 session 上派发 Input 事件用 **iframe 局部坐标**
2428
+ * (与该 session 内 getBoundingClientRect 一致)。
2429
+ */
2430
+ async resolveFrameSession(urlIncludes) {
2431
+ if (this.options.isClosed()) throw new Error("Page is closed");
2432
+ const viaTargets = await this.tryAttachViaTargets(urlIncludes);
2433
+ if (viaTargets) return viaTargets;
2434
+ const viaAuto = await this.tryAttachViaAutoAttach(urlIncludes);
2435
+ if (viaAuto) return viaAuto;
2436
+ try {
2437
+ const tree = await this.options.conn.send("Page.getFrameTree", void 0, this.options.sessionId);
2438
+ const urls = [];
2439
+ const walk = (node) => {
2440
+ urls.push(node.frame.url);
2441
+ for (const child of node.childFrames || []) walk(child);
2442
+ };
2443
+ walk(tree.frameTree);
2444
+ if (urls.some((u) => u.includes(urlIncludes))) {
2445
+ throw new Error(`frame "${urlIncludes}" \u662F\u540C\u8FDB\u7A0B iframe\uFF08\u65E0\u72EC\u7ACB target\uFF09\u2014\u2014\u666E\u901A click/fill/mouse \u5373\u53EF\uFF08locator \u5C42\u5DF2\u652F\u6301\u540C\u6E90 iframe \u5750\u6807\u504F\u79FB\uFF09`);
2446
+ }
2447
+ } catch (err) {
2448
+ if (err instanceof Error && err.message.includes("\u540C\u8FDB\u7A0B")) throw err;
2449
+ }
2450
+ throw new Error(`no OOPIF target for "${urlIncludes}"\uFF08\u7528 'xbrowser frames' \u67E5\u770B\u53EF\u89C1\u7684 iframe target\uFF1BOOPIF \u53EA\u5728 Target.getTargets \u91CC\u51FA\u73B0\uFF09`);
2451
+ }
2452
+ /** 浏览器级 iframe target 列表(OOPIF 可见性——Page.getFrameTree 看不到它们) */
2453
+ async listFrameTargets() {
2454
+ try {
2455
+ const tg = await this.options.conn.send("Target.getTargets", void 0);
2456
+ return (tg.targetInfos || []).filter((t) => t.type === "iframe").map((t) => ({ url: t.url || "", targetId: t.targetId }));
2457
+ } catch {
2458
+ return [];
2459
+ }
2460
+ }
2461
+ /** 路径 A:浏览器级 Target.getTargets 平铺 iframe target,按 URL 子串 attach。
2462
+ * 多次导航后列表里可能残留正在销毁的陈旧 target——attach 后用 location.href
2463
+ * 验证候选确实是活目标,不匹配则换下一个(验证码 iframe 重建场景实测会撞上)。 */
2464
+ async tryAttachViaTargets(urlIncludes) {
2465
+ try {
2466
+ const tg = await this.options.conn.send("Target.getTargets", void 0);
2467
+ const candidates = (tg.targetInfos || []).filter((t) => t.type === "iframe" && (t.url || "").includes(urlIncludes));
2468
+ for (const hit of candidates) {
2469
+ try {
2470
+ const att = await this.options.conn.send("Target.attachToTarget", { targetId: hit.targetId, flatten: true });
2471
+ const probe = await this.options.conn.send("Runtime.evaluate", { expression: "location.href", returnByValue: true }, att.sessionId);
2472
+ const href = typeof probe.result?.value === "string" ? probe.result.value : "";
2473
+ if (probe.exceptionDetails || !href.includes(urlIncludes)) {
2474
+ this.detachQuietly(att.sessionId);
2475
+ continue;
2476
+ }
2477
+ return att.sessionId;
2478
+ } catch {
2479
+ continue;
2480
+ }
2481
+ }
2482
+ } catch {
2483
+ }
2484
+ return null;
2485
+ }
2486
+ /** 路径 C:Target.setAutoAttach 监听后续 attach 的 iframe target(兜底) */
2487
+ async tryAttachViaAutoAttach(urlIncludes) {
2388
2488
  const attached = [];
2389
2489
  const onAttach = (raw) => {
2390
2490
  const ev = raw;
@@ -2406,10 +2506,11 @@ var RuntimeEvaluationService = class {
2406
2506
  });
2407
2507
  }
2408
2508
  const hit = attached.find((a) => a.url.includes(urlIncludes));
2409
- if (!hit) {
2410
- throw new Error(`frame not found for "${urlIncludes}"\uFF08OOPIF target\u3001frame \u6811\u3001auto-attach \u4E09\u8DEF\u5747\u672A\u547D\u4E2D\uFF1B\u53EF\u80FD\u4ECD\u5728\u52A0\u8F7D\uFF09`);
2411
- }
2412
- return evalIn(hit.sessionId);
2509
+ return hit ? hit.sessionId : null;
2510
+ }
2511
+ detachQuietly(sessionId) {
2512
+ this.options.conn.send("Target.detachFromTarget", { sessionId }).catch(() => {
2513
+ });
2413
2514
  }
2414
2515
  /** evaluateHandle — evaluates fn and returns a handle for element bounding box */
2415
2516
  async evaluateHandle(fn, ...args) {
@@ -2461,6 +2562,103 @@ var RuntimeEvaluationService = class {
2461
2562
  }
2462
2563
  };
2463
2564
 
2565
+ // src/cdp-driver/page-frame-input.ts
2566
+ function isSessionDeadError(err) {
2567
+ return /session (with given id )?not found|no session with given id/i.test(errMsg(err));
2568
+ }
2569
+ var FrameInputService = class {
2570
+ constructor(deps) {
2571
+ this.deps = deps;
2572
+ }
2573
+ deps;
2574
+ /** urlIncludes → 已 attach 的 session + 鼠标实例(跨命令保持位置状态) */
2575
+ cache = /* @__PURE__ */ new Map();
2576
+ /**
2577
+ * 拿到指定 OOPIF 的鼠标(Input 域派发进 iframe 渲染进程,isTrusted=true)。
2578
+ * 缓存的 session 失效(iframe 重建/刷新)时自动重 attach;重 attach 会
2579
+ * 重置鼠标位置——调用方需重新读取目标元素坐标。
2580
+ */
2581
+ async frameMouse(urlIncludes, opts = {}) {
2582
+ if (opts.fresh) this.cache.delete(urlIncludes);
2583
+ const cached = this.cache.get(urlIncludes);
2584
+ if (cached) {
2585
+ try {
2586
+ await this.deps.conn.send("Runtime.evaluate", { expression: "1", returnByValue: true }, cached.sessionId);
2587
+ return cached.mouse;
2588
+ } catch {
2589
+ this.cache.delete(urlIncludes);
2590
+ }
2591
+ }
2592
+ const sessionId = await this.deps.resolveFrameSession(urlIncludes);
2593
+ const mouse = new XBMouseImpl(this.deps.conn, sessionId);
2594
+ this.cache.set(urlIncludes, { sessionId, mouse });
2595
+ return mouse;
2596
+ }
2597
+ /**
2598
+ * 带重试的 frame 鼠标操作:Chrome 异步销毁旧 OOPIF target 的窗口期里
2599
+ * (连续导航/验证码 iframe 重建),probe 通过后 dispatch 仍可能撞上死
2600
+ * session——session 失效时强制重 attach 再做一次。
2601
+ */
2602
+ async runFrameMouse(urlIncludes, fn) {
2603
+ try {
2604
+ return await fn(await this.frameMouse(urlIncludes));
2605
+ } catch (err) {
2606
+ if (!isSessionDeadError(err)) throw err;
2607
+ this.cache.delete(urlIncludes);
2608
+ return fn(await this.frameMouse(urlIncludes, { fresh: true }));
2609
+ }
2610
+ }
2611
+ /** 在 OOPIF 内点击选择器命中的元素(frame 局部坐标,stealth 落点偏移继承) */
2612
+ async clickInFrame(urlIncludes, selector, opts = {}) {
2613
+ const rect = await this.pollFrameRect(urlIncludes, selector, opts.timeoutMs ?? 5e3);
2614
+ const x = rect.x + rect.width / 2;
2615
+ const y = rect.y + rect.height / 2;
2616
+ await this.runFrameMouse(urlIncludes, (mouse) => mouse.click(x, y, { elementWidth: rect.width, elementHeight: rect.height }));
2617
+ return { x, y };
2618
+ }
2619
+ /** 在 OOPIF 内填输入框:点击聚焦 → el.select() 全选 → insertText 整体替换 → 回读验证 */
2620
+ async fillInFrame(urlIncludes, selector, text, opts = {}) {
2621
+ try {
2622
+ return await this.fillInFrameInner(urlIncludes, selector, text, opts);
2623
+ } catch (err) {
2624
+ if (!isSessionDeadError(err)) throw err;
2625
+ this.cache.delete(urlIncludes);
2626
+ return this.fillInFrameInner(urlIncludes, selector, text, opts);
2627
+ }
2628
+ }
2629
+ async fillInFrameInner(urlIncludes, selector, text, opts = {}) {
2630
+ await this.clickInFrame(urlIncludes, selector, opts);
2631
+ const cached = this.cache.get(urlIncludes);
2632
+ if (!cached) throw new Error(`frame session lost for "${urlIncludes}"`);
2633
+ await this.deps.evaluateInFrame(
2634
+ urlIncludes,
2635
+ `(() => { const el = document.querySelector(${JSON.stringify(selector)}); if (el && typeof el.select === 'function') el.select(); return true; })()`
2636
+ );
2637
+ await this.deps.conn.send("Input.insertText", { text }, cached.sessionId);
2638
+ const readback = await this.deps.evaluateInFrame(
2639
+ urlIncludes,
2640
+ `(() => { const el = document.querySelector(${JSON.stringify(selector)}); return el ? String(el.value ?? '') : ''; })()`
2641
+ );
2642
+ return { value: readback ?? "" };
2643
+ }
2644
+ /** 轮询 OOPIF 内元素 rect(等待元素出现/可测量) */
2645
+ async pollFrameRect(urlIncludes, selector, timeoutMs) {
2646
+ const expr = `(() => { const el = document.querySelector(${JSON.stringify(selector)}); if (!el) return null; const r = el.getBoundingClientRect(); if (r.width === 0 || r.height === 0) return null; return { x: r.x, y: r.y, width: r.width, height: r.height }; })()`;
2647
+ const deadline = Date.now() + timeoutMs;
2648
+ let lastErr;
2649
+ while (Date.now() < deadline) {
2650
+ try {
2651
+ const rect = await this.deps.evaluateInFrame(urlIncludes, expr);
2652
+ if (rect) return rect;
2653
+ } catch (err) {
2654
+ lastErr = err;
2655
+ }
2656
+ await new Promise((r) => setTimeout(r, 200));
2657
+ }
2658
+ throw new Error(`[frame ${urlIncludes}] element "${selector}" not found/visible within ${timeoutMs}ms${lastErr instanceof Error ? `\uFF08last: ${lastErr.message}\uFF09` : ""}`);
2659
+ }
2660
+ };
2661
+
2464
2662
  // src/cdp-driver/page.ts
2465
2663
  var XBPageImpl = class _XBPageImpl {
2466
2664
  conn;
@@ -2487,6 +2685,7 @@ var XBPageImpl = class _XBPageImpl {
2487
2685
  navigationService;
2488
2686
  domQueryService;
2489
2687
  runtimeEvaluationService;
2688
+ frameInputService;
2490
2689
  // Network tracking for waitForLoadState('networkidle')
2491
2690
  inflightRequests = /* @__PURE__ */ new Set();
2492
2691
  networkIdleResolve = null;
@@ -2549,6 +2748,11 @@ var XBPageImpl = class _XBPageImpl {
2549
2748
  isClosed: () => this._closed,
2550
2749
  url: () => this.url()
2551
2750
  });
2751
+ this.frameInputService = new FrameInputService({
2752
+ conn,
2753
+ resolveFrameSession: (urlIncludes) => this.runtimeEvaluationService.resolveFrameSession(urlIncludes),
2754
+ evaluateInFrame: (urlIncludes, expression) => this.evaluateInFrame(urlIncludes, expression)
2755
+ });
2552
2756
  this.domQueryService = new DomQueryService({
2553
2757
  conn,
2554
2758
  sessionId,
@@ -2758,8 +2962,9 @@ var XBPageImpl = class _XBPageImpl {
2758
2962
  "Target.getTargetInfo",
2759
2963
  { targetId: this._targetId }
2760
2964
  );
2761
- this._url = info.url;
2762
- if (info.url && info.url !== "about:blank" && info.url !== "") {
2965
+ const curUrl = info.targetInfo?.url ?? info.url;
2966
+ if (curUrl) this._url = curUrl;
2967
+ if (curUrl && curUrl !== "about:blank" && curUrl !== "") {
2763
2968
  this._loadState = { loadFired: true, domContentFired: true, networkIdle: true };
2764
2969
  }
2765
2970
  } catch {
@@ -2883,6 +3088,29 @@ Last error: ${lastError.message}` : "";
2883
3088
  async evaluateInFrame(urlIncludes, expression) {
2884
3089
  return this.runtimeEvaluationService.evaluateInFrame(urlIncludes, expression);
2885
3090
  }
3091
+ /** 浏览器级 iframe target 列表(OOPIF 可见——frames 命令用) */
3092
+ async listFrameTargets() {
3093
+ return this.runtimeEvaluationService.listFrameTargets();
3094
+ }
3095
+ /**
3096
+ * 拿到指定 OOPIF 的鼠标(Input 域派发进 iframe 渲染进程,isTrusted=true)。
3097
+ * 坐标语义:iframe 局部坐标(与该 session 内 getBoundingClientRect 一致)。
3098
+ * session 失效自动重 attach(鼠标位置会重置,需重读目标坐标)。
3099
+ */
3100
+ async frameMouse(urlIncludes, opts) {
3101
+ return this.frameInputService.frameMouse(urlIncludes, opts);
3102
+ }
3103
+ async runFrameMouse(urlIncludes, fn) {
3104
+ return this.frameInputService.runFrameMouse(urlIncludes, fn);
3105
+ }
3106
+ /** 在 OOPIF 内点击选择器命中的元素(轮询等待 + stealth 落点) */
3107
+ async clickInFrame(urlIncludes, selector, opts) {
3108
+ return this.frameInputService.clickInFrame(urlIncludes, selector, opts);
3109
+ }
3110
+ /** 在 OOPIF 内填输入框(点击聚焦 + insertText + 回读) */
3111
+ async fillInFrame(urlIncludes, selector, text, opts) {
3112
+ return this.frameInputService.fillInFrame(urlIncludes, selector, text, opts);
3113
+ }
2886
3114
  async evaluateHandle(script, ...args) {
2887
3115
  return this.runtimeEvaluationService.evaluateHandle(script, ...args);
2888
3116
  }
@@ -3613,6 +3841,16 @@ var XBBrowserImpl = class {
3613
3841
  await this.conn.close();
3614
3842
  this._emitter.emit("disconnected");
3615
3843
  }
3844
+ async disconnect() {
3845
+ if (this._disconnected) return;
3846
+ this._disconnected = true;
3847
+ if (this._exitHandler) {
3848
+ process.removeListener("exit", this._exitHandler);
3849
+ this._exitHandler = null;
3850
+ }
3851
+ await this.conn.close();
3852
+ this._emitter.emit("disconnected");
3853
+ }
3616
3854
  async newContext(opts = {}) {
3617
3855
  if (this.launchOpts?.stealthConfig && !opts.stealthConfig) {
3618
3856
  opts = { ...opts, stealthConfig: this.launchOpts.stealthConfig };