@xbrowser/cli 1.28.0 → 1.30.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.
Files changed (48) hide show
  1. package/README.md +2 -2
  2. package/dist/{browser-4IYIHZ6R.js → browser-6PFTHZI3.js} +8 -6
  3. package/dist/{browser-NYYCR4O7.js → browser-I2NLJN2A.js} +5 -3
  4. package/dist/{browser-ZD53IMUJ.js → browser-KOUA4ZDA.js} +6 -4
  5. package/dist/{cdp-driver-EFEW4ZEN.js → cdp-driver-3ETNFQA4.js} +4 -4
  6. package/dist/{cdp-driver-HB744QB4.js → cdp-driver-U7HDQMQ5.js} +1578 -896
  7. package/dist/{cdp-driver-4X6Q62WI.js → cdp-driver-WBFJNOLD.js} +3 -3
  8. package/dist/{chunk-SEEWE5SJ.js → chunk-2KPI5GKP.js} +3 -0
  9. package/dist/{chunk-OEC7ZSFW.js → chunk-3K57RYVC.js} +1942 -1580
  10. package/dist/{chunk-75DNUI6M.js → chunk-6UJU2FJK.js} +146 -0
  11. package/dist/{chunk-FNXA6FDM.js → chunk-BND5O5KC.js} +2 -1
  12. package/dist/{chunk-KECYFWJO.js → chunk-BOZTIIBT.js} +441 -427
  13. package/dist/{chunk-WK3INZLA.js → chunk-KPTD3SNJ.js} +1121 -759
  14. package/dist/{chunk-OSZNJT4U.js → chunk-LM32MNBB.js} +79 -8
  15. package/dist/{chunk-T2AI24A5.js → chunk-NAIHOVDZ.js} +3 -0
  16. package/dist/{chunk-WYETQ5C7.js → chunk-NEE6EMYA.js} +14 -1
  17. package/dist/{chunk-3PUOISKE.js → chunk-NINETOM4.js} +524 -495
  18. package/dist/{chunk-SOPN4XDK.js → chunk-O5PASNI7.js} +2 -1
  19. package/dist/{chunk-ME5FO5YV.js → chunk-OCECE22C.js} +1578 -896
  20. package/dist/{chunk-HSYRAV3H.js → chunk-OSIDUT4H.js} +2151 -1440
  21. package/dist/{chunk-HBMEFSTB.js → chunk-QCV2PI7U.js} +2 -1
  22. package/dist/{chunk-IR6C24P7.js → chunk-RMYKVZIZ.js} +1103 -1043
  23. package/dist/{chunk-R3F4K2SB.js → chunk-SMYSNO4M.js} +10 -0
  24. package/dist/{chunk-J3HXZVSN.js → chunk-SPNWUUHA.js} +1452 -916
  25. package/dist/{chunk-PGKV24QN.js → chunk-TBJUSUKF.js} +1 -1
  26. package/dist/{chunk-V6KGBU5J.js → chunk-VYTQLZAX.js} +1091 -1040
  27. package/dist/cli.js +3447 -3377
  28. package/dist/daemon-main.js +1240 -786
  29. package/dist/{human-interaction-CTZ4IWXJ.js → human-interaction-ISMMOJOK.js} +2 -2
  30. package/dist/{human-interaction-HJCK45SL.js → human-interaction-STTZZZ5N.js} +1 -1
  31. package/dist/{human-interaction-V3VDGHHI.js → human-interaction-UXFYV7DU.js} +1 -1
  32. package/dist/index.d.ts +458 -476
  33. package/dist/index.js +3766 -3576
  34. package/dist/{launcher-SJ44X25U.js → launcher-TOLF23ET.js} +1 -1
  35. package/dist/{launcher-XHKIC4GP.js → launcher-ZYB32LSZ.js} +1 -1
  36. package/dist/{plugin-singleton-GGSBI3EG.js → plugin-singleton-A6RNITJW.js} +1 -1
  37. package/dist/{proxy-NKCYE76M.js → proxy-H3RIUOCN.js} +2 -2
  38. package/dist/{recovery-EBKORYEU.js → recovery-JFGV3DBX.js} +1 -1
  39. package/dist/{recovery-5C4FBA5O.js → recovery-ORHJSBDN.js} +2 -2
  40. package/dist/{recovery-IMZUGWSS.js → recovery-XDKN63O5.js} +1 -1
  41. package/dist/{server-26SE6YZR.js → server-TG47W7MV.js} +7 -7
  42. package/dist/{server-JXF3JOAM.js → server-U3YAX5MJ.js} +4 -4
  43. package/dist/{session-recorder-GEZVQBKW.js → session-recorder-N7VEKJVW.js} +1 -1
  44. package/dist/{session-recorder-563ISSJK.js → session-recorder-RUNQOJ7T.js} +1 -1
  45. package/dist/{session-replayer-TXTNTG33.js → session-replayer-XLWQ47BB.js} +1 -1
  46. package/dist/{stealth-QNSMIHQK.js → stealth-FMPZO2OB.js} +1 -1
  47. package/dist/{stealth-MHJNBJY7.js → stealth-MCKFKPZ6.js} +1 -1
  48. package/package.json +9 -3
@@ -5,7 +5,7 @@ import {
5
5
  landingOffset,
6
6
  rand,
7
7
  typingDelay
8
- } from "./chunk-R3F4K2SB.js";
8
+ } from "./chunk-SMYSNO4M.js";
9
9
  import {
10
10
  connectToCDP,
11
11
  errMsg,
@@ -13,7 +13,7 @@ import {
13
13
  getCDPTargets,
14
14
  killChrome,
15
15
  launchChrome
16
- } from "./chunk-T2AI24A5.js";
16
+ } from "./chunk-NAIHOVDZ.js";
17
17
  import {
18
18
  __require
19
19
  } from "./chunk-3RG5ZIWI.js";
@@ -31,12 +31,16 @@ import { EventEmitter as EventEmitter2 } from "events";
31
31
  import { EventEmitter } from "events";
32
32
 
33
33
  // src/cdp-driver/mouse.ts
34
+ function buttonBit(button) {
35
+ return button === "left" ? 1 : button === "right" ? 2 : 4;
36
+ }
34
37
  var XBMouseImpl = class {
35
38
  conn;
36
39
  sessionId;
37
40
  _x = 0;
38
41
  _y = 0;
39
42
  _button = "none";
43
+ _buttons = 0;
40
44
  constructor(conn, sessionId) {
41
45
  this.conn = conn;
42
46
  this.sessionId = sessionId;
@@ -67,7 +71,7 @@ var XBMouseImpl = class {
67
71
  _truncated = true;
68
72
  break;
69
73
  }
70
- await this.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: p.x, y: p.y, button: this._button });
74
+ await this.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: p.x, y: p.y, button: this._button, buttons: this._buttons });
71
75
  this._x = p.x;
72
76
  this._y = p.y;
73
77
  await sleep(p.delay);
@@ -75,7 +79,7 @@ var XBMouseImpl = class {
75
79
  this._x = tx;
76
80
  this._y = ty;
77
81
  if (_truncated) {
78
- await this.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: tx, y: ty, button: this._button });
82
+ await this.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: tx, y: ty, button: this._button, buttons: this._buttons });
79
83
  }
80
84
  await sleep(rand(...DEFAULT_STEALTH_CONFIG.aimPause));
81
85
  } else {
@@ -87,7 +91,7 @@ var XBMouseImpl = class {
87
91
  const ry = stealth ? this._y + rand(...DEFAULT_STEALTH_CONFIG.releaseDrift) * (Math.random() < 0.5 ? -1 : 1) : this._y;
88
92
  this._x = rx;
89
93
  this._y = ry;
90
- await this.send("Input.dispatchMouseEvent", { type: "mouseReleased", x: rx, y: ry, button, clickCount: opts.clickCount ?? 1 });
94
+ await this.send("Input.dispatchMouseEvent", { type: "mouseReleased", x: rx, y: ry, button, buttons: this._buttons, clickCount: opts.clickCount ?? 1 });
91
95
  for (let i = 1; i < (opts.clickCount ?? 1); i++) {
92
96
  if (opts.delay) await sleep(opts.delay);
93
97
  await this.down({ button });
@@ -100,11 +104,13 @@ var XBMouseImpl = class {
100
104
  async down(opts = {}) {
101
105
  const button = opts.button ?? "left";
102
106
  this._button = button;
107
+ this._buttons |= buttonBit(button);
103
108
  await this.send("Input.dispatchMouseEvent", {
104
109
  type: "mousePressed",
105
110
  x: this._x,
106
111
  y: this._y,
107
112
  button,
113
+ buttons: this._buttons,
108
114
  // r23: press 必须与 release 声明同一 clickCount——Chrome 按序列计数
109
115
  // 合成 click/dblclick,press 缺声明会把计数器重置(dblclick 永不合成)
110
116
  clickCount: opts.clickCount ?? 1
@@ -118,8 +124,11 @@ var XBMouseImpl = class {
118
124
  x: this._x,
119
125
  y: this._y,
120
126
  button,
127
+ // release 先带位发送再清位(Puppeteer 同序——DOM mouseup 的 buttons 反映释放后状态)
128
+ buttons: this._buttons,
121
129
  clickCount: opts.clickCount ?? 1
122
130
  });
131
+ this._buttons &= ~buttonBit(button);
123
132
  }
124
133
  async move(x, y, opts = {}) {
125
134
  const stealth = opts.stealth ?? process.env.XBROWSER_STEALTH !== "off";
@@ -137,7 +146,8 @@ var XBMouseImpl = class {
137
146
  type: "mouseMoved",
138
147
  x: this._x,
139
148
  y: this._y,
140
- button: this._button
149
+ button: this._button,
150
+ buttons: this._buttons
141
151
  });
142
152
  }
143
153
  this._x = x;
@@ -157,9 +167,11 @@ var XBMouseImpl = class {
157
167
  x: this._x,
158
168
  y: this._y,
159
169
  button: "left",
170
+ buttons: 1,
160
171
  clickCount: 1
161
172
  });
162
173
  this._button = "left";
174
+ this._buttons |= 1;
163
175
  const steps = opts.steps ?? Math.max(10, Math.min(24, Math.round(Math.hypot(x - this._x, y - this._y) / 20)));
164
176
  const fx = this._x, fy = this._y;
165
177
  for (let i = 1; i <= steps; i++) {
@@ -171,7 +183,8 @@ var XBMouseImpl = class {
171
183
  type: "mouseMoved",
172
184
  x: this._x,
173
185
  y: this._y,
174
- button: this._button
186
+ button: this._button,
187
+ buttons: this._buttons
175
188
  });
176
189
  }
177
190
  this._x = x;
@@ -182,15 +195,22 @@ var XBMouseImpl = class {
182
195
  x,
183
196
  y,
184
197
  button: "left",
198
+ buttons: this._buttons,
185
199
  clickCount: 1
186
200
  });
187
201
  this._button = "none";
202
+ this._buttons &= ~1;
203
+ }
204
+ async wheelAt(x, y, deltaX, deltaY) {
205
+ await this.move(x, y);
206
+ await this.wheel(deltaX, deltaY);
188
207
  }
189
208
  async wheel(deltaX, deltaY) {
190
209
  await this.send("Input.dispatchMouseEvent", {
191
210
  type: "mouseWheel",
192
211
  x: this._x,
193
212
  y: this._y,
213
+ buttons: this._buttons,
194
214
  deltaX,
195
215
  deltaY
196
216
  });
@@ -1430,6 +1450,216 @@ var XBElementHandleImpl = class {
1430
1450
  }
1431
1451
  };
1432
1452
 
1453
+ // src/cdp-driver/page-media.ts
1454
+ var MediaService = class {
1455
+ constructor(options) {
1456
+ this.options = options;
1457
+ }
1458
+ options;
1459
+ async screenshot(opts = {}) {
1460
+ const params = {
1461
+ format: opts.type ?? "png"
1462
+ };
1463
+ if (opts.quality !== void 0 && (opts.type === "jpeg" || !opts.type && opts.quality)) {
1464
+ params.quality = opts.quality;
1465
+ }
1466
+ if (opts.fullPage) {
1467
+ params.captureBeyondViewport = true;
1468
+ }
1469
+ if (opts.clip) {
1470
+ const clip = {
1471
+ x: Math.round(opts.clip.x),
1472
+ y: Math.round(opts.clip.y),
1473
+ width: Math.round(Math.max(1, opts.clip.width)),
1474
+ height: Math.round(Math.max(1, opts.clip.height)),
1475
+ scale: opts.clip.scale ?? 1
1476
+ };
1477
+ params.clip = clip;
1478
+ }
1479
+ if (opts.omitBackground) {
1480
+ params.omitBackground = true;
1481
+ }
1482
+ const result = await this.options.conn.send(
1483
+ "Page.captureScreenshot",
1484
+ params,
1485
+ this.options.sessionId
1486
+ );
1487
+ return Buffer.from(result.data, "base64");
1488
+ }
1489
+ async pdf(opts = {}) {
1490
+ const params = {};
1491
+ if (opts.landscape !== void 0) params.landscape = opts.landscape;
1492
+ if (opts.printBackground !== void 0) params.printBackground = opts.printBackground;
1493
+ if (opts.scale !== void 0) params.scale = opts.scale;
1494
+ if (opts.format) params.paperFormat = opts.format;
1495
+ if (opts.preferCSSPageSize !== void 0) params.preferCSSPageSize = opts.preferCSSPageSize;
1496
+ if (opts.margin) {
1497
+ if (opts.margin.top) params.marginTop = parseFloat(opts.margin.top);
1498
+ if (opts.margin.bottom) params.marginBottom = parseFloat(opts.margin.bottom);
1499
+ if (opts.margin.left) params.marginLeft = parseFloat(opts.margin.left);
1500
+ if (opts.margin.right) params.marginRight = parseFloat(opts.margin.right);
1501
+ }
1502
+ const result = await this.options.conn.send("Page.printToPDF", params, this.options.sessionId);
1503
+ return Buffer.from(result.data, "base64");
1504
+ }
1505
+ viewportSize() {
1506
+ return this.options.viewportSize ?? null;
1507
+ }
1508
+ async setViewportSize(size) {
1509
+ await this.options.conn.send(
1510
+ "Emulation.setDeviceMetricsOverride",
1511
+ {
1512
+ width: size.width,
1513
+ height: size.height,
1514
+ deviceScaleFactor: 1,
1515
+ mobile: false
1516
+ },
1517
+ this.options.sessionId
1518
+ );
1519
+ this.options.onViewportSize(size);
1520
+ }
1521
+ /**
1522
+ * env-E2: 缩放变异——deviceScaleFactor 切换(CSS 像素坐标空间不变,
1523
+ * 物理像素翻倍)。保留当前 CSS 视口尺寸,只换 DSF。
1524
+ */
1525
+ async setDeviceScaleFactor(dsf) {
1526
+ const size = this.options.viewportSize ?? await this.options.evaluate(
1527
+ "({ width: window.innerWidth, height: window.innerHeight })"
1528
+ );
1529
+ await this.options.conn.send(
1530
+ "Emulation.setDeviceMetricsOverride",
1531
+ {
1532
+ width: size.width,
1533
+ height: size.height,
1534
+ deviceScaleFactor: dsf,
1535
+ mobile: false
1536
+ },
1537
+ this.options.sessionId
1538
+ );
1539
+ this.options.onViewportSize(size);
1540
+ }
1541
+ // ── Scripts ─────────────────────────────────────────────────
1542
+ };
1543
+
1544
+ // src/cdp-driver/page-file-input.ts
1545
+ var FileInputService = class {
1546
+ constructor(options) {
1547
+ this.options = options;
1548
+ }
1549
+ options;
1550
+ async dropFiles(selector, payload) {
1551
+ await this.options.evaluate(`
1552
+ (function() {
1553
+ var el = ${queryJS(selector)};
1554
+ if (!el) throw new Error('drop target not found: ' + ${JSON.stringify(selector)});
1555
+ var b64 = ${JSON.stringify(payload.buffer.toString("base64"))};
1556
+ var bin = atob(b64);
1557
+ var buf = new Uint8Array(bin.length);
1558
+ for (var i = 0; i < bin.length; i++) buf[i] = bin.charCodeAt(i);
1559
+ var file = new File([buf], ${JSON.stringify(payload.name)}, { type: ${JSON.stringify(payload.mimeType)} });
1560
+ var dt = new DataTransfer();
1561
+ dt.items.add(file);
1562
+ var rect = el.getBoundingClientRect();
1563
+ var opts = {
1564
+ bubbles: true, cancelable: true,
1565
+ clientX: rect.x + rect.width / 2, clientY: rect.y + rect.height / 2,
1566
+ };
1567
+ el.dispatchEvent(new DragEvent('dragenter', Object.assign({ dataTransfer: dt }, opts)));
1568
+ el.dispatchEvent(new DragEvent('dragover', Object.assign({ dataTransfer: dt }, opts)));
1569
+ el.dispatchEvent(new DragEvent('drop', Object.assign({ dataTransfer: dt }, opts)));
1570
+ })()
1571
+ `);
1572
+ }
1573
+ async setInputFiles(selector, files) {
1574
+ const fileArr = Array.isArray(files) ? files : [files];
1575
+ const fileList = fileArr.map((f) => ({
1576
+ name: f.name,
1577
+ type: f.mimeType,
1578
+ dataBase64: f.buffer.toString("base64")
1579
+ }));
1580
+ await this.options.evaluate(`
1581
+ (function() {
1582
+ var selector = ${JSON.stringify(selector)};
1583
+ var input = ${queryJS(selector)};
1584
+ if (!input) throw new Error('Element not found: ' + selector);
1585
+
1586
+ var fileList = ${JSON.stringify(fileList)};
1587
+ var dt = new DataTransfer();
1588
+
1589
+ fileList.forEach(function(f) {
1590
+ var binary = atob(f.dataBase64);
1591
+ var bytes = new Uint8Array(binary.length);
1592
+ for (var i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
1593
+ var blob = new Blob([bytes], { type: f.type });
1594
+ var file = new File([blob], f.name, { type: f.type });
1595
+ dt.items.add(file);
1596
+ });
1597
+
1598
+ input.files = dt.files;
1599
+ input.dispatchEvent(new Event('input', { bubbles: true }));
1600
+ input.dispatchEvent(new Event('change', { bubbles: true }));
1601
+ })()
1602
+ `);
1603
+ }
1604
+ // ── dragAndDrop ─────────────────────────────────────────────
1605
+ async dragAndDrop(source, target) {
1606
+ const sourceRect = await this.options.evaluate(`
1607
+ (function() {
1608
+ const el = ${queryJS(source)};
1609
+ if (!el) throw new Error('Source not found: ${source}');
1610
+ el.scrollIntoView({ behavior: 'instant', block: 'center' });
1611
+ const r = el.getBoundingClientRect();
1612
+ return { x: r.x, y: r.y, width: r.width, height: r.height };
1613
+ })()
1614
+ `);
1615
+ const targetRect = await this.options.evaluate(`
1616
+ (function() {
1617
+ const el = ${queryJS(target)};
1618
+ if (!el) throw new Error('Target not found: ${target}');
1619
+ el.scrollIntoView({ behavior: 'instant', block: 'center' });
1620
+ const r = el.getBoundingClientRect();
1621
+ return { x: r.x, y: r.y, width: r.width, height: r.height };
1622
+ })()
1623
+ `);
1624
+ const sx = sourceRect.x + sourceRect.width / 2;
1625
+ const sy = sourceRect.y + sourceRect.height / 2;
1626
+ const tx = targetRect.x + targetRect.width / 2;
1627
+ const ty = targetRect.y + targetRect.height / 2;
1628
+ try {
1629
+ await this.options.conn.send("Input.dispatchDragEvent", {
1630
+ type: "dragStart",
1631
+ x: sx,
1632
+ y: sy,
1633
+ data: { items: [], dragOperations: ["copy", "move", "link"] }
1634
+ }, this.options.sessionId);
1635
+ await this.options.conn.send("Input.dispatchDragEvent", {
1636
+ type: "dragOver",
1637
+ x: tx,
1638
+ y: ty,
1639
+ data: { items: [], dragOperations: ["copy", "move", "link"] }
1640
+ }, this.options.sessionId);
1641
+ await this.options.conn.send("Input.dispatchDragEvent", {
1642
+ type: "drop",
1643
+ x: tx,
1644
+ y: ty,
1645
+ data: { items: [], dragOperations: ["copy", "move", "link"] }
1646
+ }, this.options.sessionId);
1647
+ await this.options.conn.send("Input.dispatchDragEvent", {
1648
+ type: "dragCancel",
1649
+ x: sx,
1650
+ y: sy,
1651
+ data: { items: [], dragOperations: ["copy", "move", "link"] }
1652
+ }, this.options.sessionId);
1653
+ } catch {
1654
+ await this.options.mouse.move(sx, sy);
1655
+ await this.options.mouse.down();
1656
+ await this.options.mouse.move(tx, ty, { steps: 10 });
1657
+ await this.options.mouse.up();
1658
+ }
1659
+ }
1660
+ // ── setOfflineMode ──────────────────────────────────────────
1661
+ };
1662
+
1433
1663
  // src/cdp-driver/page-helpers.ts
1434
1664
  function globToRegex(glob) {
1435
1665
  let pattern = glob.replace(/[\\^${}()|[\]+]/g, "\\$&").replace(/\./g, "\\.").replace(/\*\*/g, "{{DOUBLESTAR}}").replace(/\*/g, "[^/]*").replace(/{{DOUBLESTAR}}/g, ".*").replace(/\?/g, ".");
@@ -1581,65 +1811,1078 @@ function createXBRouteFetch(conn, sessionId, params, emitter) {
1581
1811
  };
1582
1812
  }
1583
1813
 
1584
- // src/cdp-driver/page.ts
1585
- var XBPageImpl = class _XBPageImpl {
1586
- conn;
1587
- _emitter = new EventEmitter();
1588
- _subscriptions = [];
1589
- sessionId;
1590
- _targetId;
1591
- _contextImpl;
1592
- _browserImpl;
1593
- _closed = false;
1594
- _url = "about:blank";
1595
- _title = "";
1596
- _viewportSize = null;
1597
- _loadState = {
1598
- loadFired: true,
1599
- domContentFired: true,
1600
- networkIdle: true
1601
- };
1602
- mouse;
1603
- keyboard;
1604
- // Network tracking for waitForLoadState('networkidle')
1605
- inflightRequests = /* @__PURE__ */ new Set();
1606
- networkIdleResolve = null;
1607
- networkIdleTimer = null;
1608
- static NETWORK_IDLE_MS = 500;
1609
- constructor(conn, sessionId, targetId, context, browser) {
1610
- this.conn = conn;
1611
- this.sessionId = sessionId;
1612
- this._targetId = targetId;
1613
- this._contextImpl = context;
1614
- this._browserImpl = browser;
1615
- this.mouse = new XBMouseImpl(conn, sessionId);
1616
- this.keyboard = new XBKeyboardImpl(conn, sessionId);
1617
- }
1618
- _emit(event, ...args) {
1619
- this._emitter.emit(event, ...args);
1620
- }
1621
- /** Internal initialization — must be called after construction */
1622
- async _init() {
1623
- await this.conn.send("Page.enable", void 0, this.sessionId);
1624
- await this.conn.send("Runtime.enable", void 0, this.sessionId);
1625
- await this.conn.send("Network.enable", void 0, this.sessionId);
1626
- await this.conn.send("DOM.enable", void 0, this.sessionId).catch(() => {
1627
- });
1628
- if (this._contextImpl.ignoreHTTPSErrors) {
1629
- await this.conn.send("Security.enable", void 0, this.sessionId).catch(() => {
1814
+ // src/cdp-driver/page-network-events.ts
1815
+ function setupNetworkEvents(options) {
1816
+ options.addSubscription(
1817
+ options.conn.subscribe("Network.requestWillBeSent", options.sessionId, (params) => {
1818
+ const p = params;
1819
+ options.state.inflightRequests.add(p.requestId);
1820
+ options.storeRequest(p.requestId, {
1821
+ url: p.request.url,
1822
+ method: p.request.method,
1823
+ headers: p.request.headers,
1824
+ postData: p.request.postData ?? null,
1825
+ resourceType: p.type
1630
1826
  });
1631
- await this.conn.send("Security.setIgnoreCertificateErrors", { ignore: true }, this.sessionId).catch(() => {
1827
+ options.emit("request", createXBRequest(
1828
+ null,
1829
+ {
1830
+ requestId: p.requestId,
1831
+ url: p.request.url,
1832
+ method: p.request.method,
1833
+ headers: p.request.headers,
1834
+ postData: p.request.postData ?? null,
1835
+ resourceType: p.type
1836
+ }
1837
+ ));
1838
+ options.checkNetworkIdle();
1839
+ })
1840
+ );
1841
+ options.addSubscription(
1842
+ options.conn.subscribe("Network.responseReceived", options.sessionId, (params) => {
1843
+ const p = params;
1844
+ options.storeResponse(p.requestId, {
1845
+ status: p.response.status,
1846
+ url: p.response.url,
1847
+ headers: p.response.headers
1632
1848
  });
1849
+ options.emit("response", createXBResponse(
1850
+ { requestId: p.requestId, status: p.response.status, url: p.response.url, headers: p.response.headers },
1851
+ options.conn,
1852
+ options.sessionId
1853
+ ));
1854
+ })
1855
+ );
1856
+ options.addSubscription(
1857
+ options.conn.subscribe("Network.loadingFinished", options.sessionId, (params) => {
1858
+ const p = params;
1859
+ options.state.inflightRequests.delete(p.requestId);
1860
+ options.emit("requestfinished", p);
1861
+ options.checkNetworkIdle();
1862
+ })
1863
+ );
1864
+ options.addSubscription(
1865
+ options.conn.subscribe("Network.loadingFailed", options.sessionId, (params) => {
1866
+ const p = params;
1867
+ options.state.inflightRequests.delete(p.requestId);
1868
+ options.checkNetworkIdle();
1869
+ })
1870
+ );
1871
+ }
1872
+
1873
+ // src/cdp-driver/page-lifecycle-events.ts
1874
+ function setupPageEvents(options) {
1875
+ options.addSubscription(
1876
+ options.conn.subscribe("Page.frameNavigated", options.sessionId, (params) => {
1877
+ const p = params;
1878
+ if (p.frame) {
1879
+ options.setUrl(p.frame.url);
1880
+ }
1881
+ options.emit("framenavigated", options.mainFrame());
1882
+ })
1883
+ );
1884
+ options.addSubscription(
1885
+ options.conn.subscribe("Page.loadEventFired", options.sessionId, () => {
1886
+ options.markLoadFired();
1887
+ })
1888
+ );
1889
+ options.addSubscription(
1890
+ options.conn.subscribe("Page.domContentEventFired", options.sessionId, () => {
1891
+ options.markDomContentFired();
1892
+ })
1893
+ );
1894
+ options.addSubscription(
1895
+ options.conn.subscribe("Page.javascriptDialogOpening", options.sessionId, (params) => {
1896
+ const p = params;
1897
+ const dialog = {
1898
+ type: p.type,
1899
+ message: () => p.message,
1900
+ defaultValue: () => p.defaultValue,
1901
+ accept: async (text) => {
1902
+ await options.conn.send("Page.handleJavaScriptDialog", {
1903
+ accept: true,
1904
+ promptText: text
1905
+ }, options.sessionId);
1906
+ },
1907
+ dismiss: async () => {
1908
+ await options.conn.send("Page.handleJavaScriptDialog", {
1909
+ accept: false
1910
+ }, options.sessionId);
1911
+ }
1912
+ };
1913
+ options.emit("dialog", dialog);
1914
+ const autoAccept = p.type === "beforeunload" ? options.getBeforeUnloadAccept() : false;
1915
+ setTimeout(() => {
1916
+ options.conn.send("Page.handleJavaScriptDialog", { accept: autoAccept }, options.sessionId).catch(() => {
1917
+ });
1918
+ }, 0);
1919
+ })
1920
+ );
1921
+ options.addSubscription(
1922
+ options.conn.subscribe("Page.fileChooserOpened", options.sessionId, async (params) => {
1923
+ const p = params;
1924
+ let selector = "";
1925
+ try {
1926
+ const result = await options.conn.send("DOM.describeNode", { backendNodeId: p.backendNodeId }, options.sessionId);
1927
+ const attrs = result.node?.attributes || [];
1928
+ const idIdx = attrs.indexOf("id");
1929
+ if (idIdx >= 0) selector = "#" + attrs[idIdx + 1];
1930
+ } catch {
1931
+ }
1932
+ if (!selector) {
1933
+ try {
1934
+ const result = await options.conn.send("DOM.resolveNode", { backendNodeId: p.backendNodeId }, options.sessionId);
1935
+ const evalResult = await options.conn.send("Runtime.callFunctionOn", {
1936
+ objectId: result.objectId,
1937
+ functionDeclaration: 'function() { return this.id || this.name || "" }',
1938
+ returnByValue: true
1939
+ }, options.sessionId);
1940
+ if (evalResult.result?.value) selector = "#" + evalResult.result.value;
1941
+ } catch {
1942
+ }
1943
+ }
1944
+ const fileChooser = {
1945
+ selector,
1946
+ isMultiple: p.mode === "selectMultiple",
1947
+ setFiles: async (files) => {
1948
+ const fileArray = Array.isArray(files) ? files : [files];
1949
+ await options.setInputFiles(selector || 'input[type="file"]', fileArray);
1950
+ }
1951
+ };
1952
+ options.emit("filechooser", fileChooser);
1953
+ })
1954
+ );
1955
+ }
1956
+
1957
+ // src/cdp-driver/page-network-waits.ts
1958
+ var NetworkWaitService = class {
1959
+ constructor(options) {
1960
+ this.options = options;
1961
+ }
1962
+ options;
1963
+ // ── waitForResponse ─────────────────────────────────────────
1964
+ async waitForResponse(urlOrPredicate, opts = {}) {
1965
+ const timeout = opts.timeout ?? 3e4;
1966
+ const predicate = createResponsePredicate(urlOrPredicate);
1967
+ for (const [, data] of this.options.responses) {
1968
+ const response = createXBResponse(data, this.options.conn, this.options.sessionId);
1969
+ if (predicate(response)) return response;
1633
1970
  }
1634
- if (this._contextImpl.httpCredentials) {
1635
- await this.conn.send("Fetch.enable", {
1636
- patterns: [{ urlPattern: "*", requestStage: "Request" }],
1971
+ return new Promise((resolve, reject) => {
1972
+ const timer = setTimeout(() => {
1973
+ this.options.off("response", handler);
1974
+ reject(new Error(`waitForResponse timed out after ${timeout}ms`));
1975
+ }, timeout);
1976
+ const handler = (params) => {
1977
+ let response;
1978
+ const respObj = params;
1979
+ if (respObj.response) {
1980
+ const data = {
1981
+ requestId: respObj.requestId || "",
1982
+ status: respObj.response.status || 0,
1983
+ url: respObj.response.url || "",
1984
+ headers: respObj.response.headers || {}
1985
+ };
1986
+ response = createXBResponse(data, this.options.conn, this.options.sessionId);
1987
+ } else if (typeof params.status === "function") {
1988
+ response = params;
1989
+ } else {
1990
+ return;
1991
+ }
1992
+ if (predicate(response)) {
1993
+ clearTimeout(timer);
1994
+ this.options.off("response", handler);
1995
+ resolve(response);
1996
+ }
1997
+ };
1998
+ this.options.on("response", handler);
1999
+ });
2000
+ }
2001
+ // ── waitForRequest ──────────────────────────────────────────
2002
+ async waitForRequest(urlOrPredicate, opts = {}) {
2003
+ const timeout = opts.timeout ?? 3e4;
2004
+ const predicate = createRequestPredicate(urlOrPredicate);
2005
+ for (const [, data] of this.options.requests) {
2006
+ const request = createXBRequest(this.pageLike(), data);
2007
+ if (predicate(request)) return request;
2008
+ }
2009
+ return new Promise((resolve, reject) => {
2010
+ const timer = setTimeout(() => {
2011
+ this.options.off("request", handler);
2012
+ reject(new Error(`waitForRequest timed out after ${timeout}ms`));
2013
+ }, timeout);
2014
+ const handler = (params) => {
2015
+ let request;
2016
+ const reqObj = params;
2017
+ if (reqObj.request) {
2018
+ request = createXBRequest(this.pageLike(), {
2019
+ requestId: reqObj.requestId || "",
2020
+ url: reqObj.request.url || "",
2021
+ method: reqObj.request.method || "",
2022
+ headers: reqObj.request.headers || {},
2023
+ postData: reqObj.request.postData ?? null,
2024
+ resourceType: reqObj.type || ""
2025
+ });
2026
+ } else if (typeof params.url === "function") {
2027
+ request = params;
2028
+ } else {
2029
+ return;
2030
+ }
2031
+ if (predicate(request)) {
2032
+ clearTimeout(timer);
2033
+ this.options.off("request", handler);
2034
+ resolve(request);
2035
+ }
2036
+ };
2037
+ this.options.on("request", handler);
2038
+ });
2039
+ }
2040
+ // ── waitForURL ──────────────────────────────────────────────
2041
+ async waitForURL(url, opts = {}) {
2042
+ const timeout = opts.timeout ?? 3e4;
2043
+ const checkFn = typeof url === "function" ? url : typeof url === "string" ? (current) => matchGlob(url, current) : (current) => url.test(current);
2044
+ if (checkFn(this.options.currentUrl())) return;
2045
+ return new Promise((resolve, reject) => {
2046
+ const timer = setTimeout(() => {
2047
+ this.options.off("framenavigated", handler);
2048
+ reject(new Error(`waitForURL timed out after ${timeout}ms`));
2049
+ }, timeout);
2050
+ const handler = () => {
2051
+ if (checkFn(this.options.currentUrl())) {
2052
+ clearTimeout(timer);
2053
+ this.options.off("framenavigated", handler);
2054
+ resolve();
2055
+ }
2056
+ };
2057
+ this.options.on("framenavigated", handler);
2058
+ });
2059
+ }
2060
+ pageLike() {
2061
+ return {
2062
+ _networkResponses: this.options.responses,
2063
+ _connection: this.options.conn,
2064
+ sessionId: this.options.sessionId
2065
+ };
2066
+ }
2067
+ };
2068
+
2069
+ // src/cdp-driver/page-routes.ts
2070
+ var NetworkRouteService = class {
2071
+ constructor(options) {
2072
+ this.options = options;
2073
+ }
2074
+ options;
2075
+ routeHandlers = [];
2076
+ interceptionEnabled = false;
2077
+ get isInterceptionEnabled() {
2078
+ return this.interceptionEnabled;
2079
+ }
2080
+ subscriptions = [];
2081
+ async route(url, handler) {
2082
+ const regex = typeof url === "string" ? globToRegex(url) : url;
2083
+ this.routeHandlers.push({ pattern: String(url), regex, handler });
2084
+ if (!this.interceptionEnabled) {
2085
+ this.interceptionEnabled = true;
2086
+ await this.options.conn.send("Fetch.enable", {
2087
+ patterns: [{ urlPattern: "*", requestStage: "Request" }],
2088
+ // sup-s9: 保留认证自动响应(Fetch.enable 为替换语义,不带此参数
2089
+ // 会顶掉 _init 的 auth 配置)
2090
+ handleAuthRequests: true
2091
+ }, this.options.sessionId);
2092
+ this.subscriptions.push(
2093
+ this.options.conn.subscribe("Fetch.requestPaused", this.options.sessionId, (params) => {
2094
+ this._handleRequestPaused(params);
2095
+ })
2096
+ );
2097
+ }
2098
+ }
2099
+ async unroute(url, handler) {
2100
+ const regex = typeof url === "string" ? globToRegex(url) : url;
2101
+ this.routeHandlers = this.routeHandlers.filter(
2102
+ (h) => !(regex.source === h.regex.source && (!handler || h.handler === handler))
2103
+ );
2104
+ if (this.routeHandlers.length === 0 && this.interceptionEnabled) {
2105
+ this.interceptionEnabled = false;
2106
+ await this.options.conn.send("Fetch.disable", void 0, this.options.sessionId).catch(() => {
2107
+ });
2108
+ }
2109
+ }
2110
+ async _handleRequestPaused(params) {
2111
+ const requestUrl = params.request.url;
2112
+ for (const { regex, handler } of this.routeHandlers) {
2113
+ if (regex.test(requestUrl)) {
2114
+ this.options.emit("request", createXBRequest(
2115
+ null,
2116
+ {
2117
+ requestId: params.requestId,
2118
+ url: params.request.url,
2119
+ method: params.request.method,
2120
+ headers: params.request.headers,
2121
+ postData: params.request.postData ?? null,
2122
+ resourceType: params.resourceType
2123
+ }
2124
+ ));
2125
+ const route = createXBRouteFetch(this.options.conn, this.options.sessionId, params, void 0);
2126
+ try {
2127
+ await handler(route);
2128
+ } catch {
2129
+ await this.options.conn.send("Fetch.continueRequest", {
2130
+ requestId: params.requestId
2131
+ }, this.options.sessionId).catch(() => {
2132
+ });
2133
+ }
2134
+ return;
2135
+ }
2136
+ }
2137
+ await this.options.conn.send("Fetch.continueRequest", {
2138
+ requestId: params.requestId
2139
+ }, this.options.sessionId).catch(() => {
2140
+ });
2141
+ }
2142
+ };
2143
+
2144
+ // src/cdp-driver/page-navigation.ts
2145
+ var NavigationService = class {
2146
+ constructor(options) {
2147
+ this.options = options;
2148
+ }
2149
+ options;
2150
+ async goto(url, opts = {}) {
2151
+ if (this.options.isClosed()) throw new Error("Page is closed");
2152
+ const waitUntil = opts.waitUntil ?? "load";
2153
+ const timeout = opts.timeout ?? 3e4;
2154
+ this.options.state.loadFired = false;
2155
+ this.options.state.domContentFired = false;
2156
+ this.options.state.networkIdle = false;
2157
+ if (process.env.XBROWSER_STEALTH !== "off") {
2158
+ try {
2159
+ await this.options.conn.send(
2160
+ "Page.addScriptToEvaluateOnNewDocument",
2161
+ { source: buildStealthInitScript({ ...DEFAULT_STEALTH_CONFIG, ...this.options.stealthConfig ?? {} }) },
2162
+ this.options.sessionId
2163
+ );
2164
+ } catch {
2165
+ }
2166
+ try {
2167
+ const rawUa = await this.options.conn.send(
2168
+ "Runtime.evaluate",
2169
+ { expression: "navigator.userAgent", returnByValue: true },
2170
+ this.options.sessionId
2171
+ );
2172
+ const ua = rawUa?.value || "";
2173
+ const cleaned = ua.replace(/HeadlessChrome/g, "Chrome");
2174
+ if (cleaned !== ua) {
2175
+ await this.options.conn.send(
2176
+ "Network.setUserAgentOverride",
2177
+ { userAgent: cleaned },
2178
+ this.options.sessionId
2179
+ );
2180
+ }
2181
+ } catch {
2182
+ }
2183
+ }
2184
+ const result = await this.options.conn.send(
2185
+ "Page.navigate",
2186
+ { url, referrer: opts.referer },
2187
+ this.options.sessionId
2188
+ );
2189
+ if (result.errorText) {
2190
+ throw new Error(`Navigation failed: ${result.errorText}`);
2191
+ }
2192
+ if (waitUntil === "commit") {
2193
+ this.options.setUrl(url);
2194
+ return {
2195
+ status: () => 0,
2196
+ ok: () => false,
2197
+ url: () => url,
2198
+ headers: () => ({})
2199
+ };
2200
+ }
2201
+ await this.options.waitForLoadState(waitUntil, timeout);
2202
+ this.options.setUrl(url);
2203
+ const statusCode = 200;
2204
+ const finalUrl = url;
2205
+ const headers = {};
2206
+ return {
2207
+ status: () => statusCode,
2208
+ ok: () => statusCode >= 200 && statusCode < 300,
2209
+ url: () => finalUrl,
2210
+ headers: () => headers
2211
+ };
2212
+ }
2213
+ async goBack(opts = {}) {
2214
+ try {
2215
+ const navHistory = await this.options.conn.send("Page.getNavigationHistory", void 0, this.options.sessionId);
2216
+ if (navHistory.currentIndex > 0) {
2217
+ const prevUrl = navHistory.entries[navHistory.currentIndex - 1]?.url;
2218
+ if (prevUrl && prevUrl !== "about:blank") {
2219
+ await this.options.conn.send("Page.navigate", { url: prevUrl }, this.options.sessionId);
2220
+ await this.options.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
2221
+ });
2222
+ this.options.setUrl(prevUrl);
2223
+ return;
2224
+ }
2225
+ }
2226
+ } catch {
2227
+ }
2228
+ await this.options.evaluate("() => history.back()");
2229
+ await this.options.waitForTimeout(3e3);
2230
+ this.options.setUrl(await this.options.evaluate("location.href").catch(() => this.options.currentUrl()));
2231
+ }
2232
+ async goForward(opts = {}) {
2233
+ try {
2234
+ const navHistory = await this.options.conn.send("Page.getNavigationHistory", void 0, this.options.sessionId);
2235
+ if (navHistory.currentIndex < navHistory.entries.length - 1) {
2236
+ const nextUrl = navHistory.entries[navHistory.currentIndex + 1]?.url;
2237
+ if (nextUrl && nextUrl !== "about:blank") {
2238
+ await this.options.conn.send("Page.navigate", { url: nextUrl }, this.options.sessionId);
2239
+ await this.options.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
2240
+ });
2241
+ this.options.setUrl(nextUrl);
2242
+ return;
2243
+ }
2244
+ }
2245
+ } catch {
2246
+ }
2247
+ await this.options.evaluate("() => history.forward()");
2248
+ await this.options.waitForTimeout(3e3);
2249
+ this.options.setUrl(await this.options.evaluate("location.href").catch(() => this.options.currentUrl()));
2250
+ }
2251
+ async reload(opts = {}) {
2252
+ this.options.state.loadFired = false;
2253
+ this.options.state.domContentFired = false;
2254
+ this.options.state.networkIdle = false;
2255
+ await this.options.conn.send("Page.reload", void 0, this.options.sessionId);
2256
+ await this.options.waitForLoadState(opts.waitUntil ?? "load", opts.timeout);
2257
+ }
2258
+ async waitForLoadState(state = "load", timeout = 3e4) {
2259
+ if (this.options.isClosed()) throw new Error("Page is closed");
2260
+ const checkState = () => {
2261
+ switch (state) {
2262
+ case "domcontentloaded":
2263
+ return this.options.state.domContentFired;
2264
+ case "load":
2265
+ return this.options.state.loadFired;
2266
+ case "networkidle":
2267
+ return this.options.state.networkIdle;
2268
+ case "commit":
2269
+ return this.options.state.domContentFired;
2270
+ default:
2271
+ return true;
2272
+ }
2273
+ };
2274
+ if (checkState()) return;
2275
+ return new Promise((resolve, reject) => {
2276
+ const timer = setTimeout(() => {
2277
+ reject(new Error(`waitForLoadState('${state}') timeout after ${timeout}ms`));
2278
+ }, timeout);
2279
+ const check = () => {
2280
+ if (checkState()) {
2281
+ clearTimeout(timer);
2282
+ resolve();
2283
+ } else {
2284
+ setTimeout(check, 50);
2285
+ }
2286
+ };
2287
+ check();
2288
+ });
2289
+ }
2290
+ async waitForTimeout(ms) {
2291
+ await new Promise((resolve) => {
2292
+ const timer = setTimeout(resolve, ms);
2293
+ if (typeof timer.unref === "function") timer.unref();
2294
+ });
2295
+ }
2296
+ };
2297
+
2298
+ // src/cdp-driver/page-dom.ts
2299
+ var DomQueryService = class {
2300
+ constructor(options) {
2301
+ this.options = options;
2302
+ }
2303
+ options;
2304
+ /** Query a single element, returns CDP nodeId or 0 if not found */
2305
+ async querySelector(selector) {
2306
+ if (selector.startsWith("xpath=")) {
2307
+ const found = await this.options.evaluate(`
2308
+ (() => { const el = ${queryJS(selector)}; return !!el; })()
2309
+ `).catch(() => false);
2310
+ if (!found) return 0;
2311
+ try {
2312
+ const search = await this.options.conn.send(
2313
+ "DOM.performSearch",
2314
+ { query: selector.slice(6) },
2315
+ this.options.sessionId
2316
+ );
2317
+ if (search.nodeId) return search.nodeId;
2318
+ } catch {
2319
+ }
2320
+ return 1;
2321
+ }
2322
+ const withTimeout = (p, ms) => Promise.race([p, new Promise((r) => setTimeout(() => r(null), ms))]);
2323
+ const doc = await withTimeout(
2324
+ this.options.conn.send("DOM.getDocument", { depth: 0 }, this.options.sessionId),
2325
+ 8e3
2326
+ );
2327
+ if (!doc) return 0;
2328
+ const result = await withTimeout(
2329
+ this.options.conn.send(
2330
+ "DOM.querySelector",
2331
+ { nodeId: doc.root.nodeId, selector },
2332
+ this.options.sessionId
2333
+ ),
2334
+ 8e3
2335
+ );
2336
+ if (!result) return 0;
2337
+ return result.nodeId;
2338
+ }
2339
+ /** Query all matching elements, returns array of CDP nodeIds */
2340
+ async querySelectorAll(selector) {
2341
+ const doc = await this.options.conn.send(
2342
+ "DOM.getDocument",
2343
+ { depth: 0 },
2344
+ this.options.sessionId
2345
+ );
2346
+ const result = await this.options.conn.send(
2347
+ "DOM.querySelectorAll",
2348
+ { nodeId: doc.root.nodeId, selector },
2349
+ this.options.sessionId
2350
+ );
2351
+ return result.nodeIds ?? [];
2352
+ }
2353
+ /** Resolve a CDP nodeId to a RemoteObject for evaluate */
2354
+ async resolveNode(nodeId) {
2355
+ const result = await this.options.conn.send(
2356
+ "DOM.resolveNode",
2357
+ { nodeId },
2358
+ this.options.sessionId
2359
+ );
2360
+ return result.object.objectId;
2361
+ }
2362
+ /** Get the box model for a nodeId */
2363
+ async getBoxModel(nodeId) {
2364
+ try {
2365
+ const result = await this.options.conn.send("DOM.getBoxModel", { nodeId }, this.options.sessionId);
2366
+ const c = result.model?.content;
2367
+ if (!c || c.length < 8) return null;
2368
+ const x1 = c[0];
2369
+ const y1 = c[1];
2370
+ const x2 = c[4];
2371
+ const y2 = c[5];
2372
+ return {
2373
+ x: Math.min(x1, x2),
2374
+ y: Math.min(y1, y2),
2375
+ width: Math.abs(x2 - x1),
2376
+ height: Math.abs(y2 - y1)
2377
+ };
2378
+ } catch {
2379
+ return null;
2380
+ }
2381
+ }
2382
+ /** Call a function on a RemoteObject */
2383
+ async callFunctionOn(objectId, functionDeclaration, args = []) {
2384
+ const result = await this.options.conn.send("Runtime.callFunctionOn", {
2385
+ objectId,
2386
+ functionDeclaration,
2387
+ arguments: args.map((a) => ({ value: a })),
2388
+ returnByValue: true
2389
+ }, this.options.sessionId);
2390
+ if (result.exceptionDetails) {
2391
+ throw new Error(`CallFunctionOn error: ${result.exceptionDetails.text}`);
2392
+ }
2393
+ return result.result?.value;
2394
+ }
2395
+ /** Send a CDP command scoped to this page's session */
2396
+ async _cdpSend(method, params) {
2397
+ return this.options.conn.send(method, params, this.options.sessionId);
2398
+ }
2399
+ /** sup-s11: beforeunload 自动应答语义——'accept'(默认,离开页面,与录制
2400
+ * 意图一致)或 'dismiss'(取消导航留守原页,尽力而为:此构建上 CDP
2401
+ * accept:false 对浏览器侧导航的取消语义不稳定,不保证)。 */
2402
+ };
2403
+
2404
+ // src/cdp-driver/page-runtime.ts
2405
+ var RuntimeEvaluationService = class {
2406
+ constructor(options) {
2407
+ this.options = options;
2408
+ }
2409
+ options;
2410
+ async title() {
2411
+ let title = "";
2412
+ for (let attempt = 0; attempt < 20; attempt++) {
2413
+ try {
2414
+ title = await this.evaluate("document.title");
2415
+ if (title) return title;
2416
+ } catch {
2417
+ }
2418
+ await new Promise((resolve) => setTimeout(resolve, 50));
2419
+ }
2420
+ return title;
2421
+ }
2422
+ async content() {
2423
+ return this.evaluate("document.documentElement.outerHTML");
2424
+ }
2425
+ // ── Evaluation ──────────────────────────────────────────────
2426
+ async evaluate(fn, ...args) {
2427
+ if (this.options.isClosed()) throw new Error("Page is closed");
2428
+ this.options.conn.send("Page.handleJavaScriptDialog", { accept: false }, this.options.sessionId).catch(() => {
2429
+ });
2430
+ let expression;
2431
+ if (typeof fn === "string") {
2432
+ expression = fn;
2433
+ } else {
2434
+ const argStr = args.length > 0 ? `...${JSON.stringify(args)}` : "";
2435
+ expression = `(()=>{const __fn=(${fn.toString()});return __fn(${argStr});})()`;
2436
+ }
2437
+ const result = await this.options.conn.send("Runtime.evaluate", {
2438
+ expression,
2439
+ returnByValue: true,
2440
+ awaitPromise: true
2441
+ }, this.options.sessionId);
2442
+ if (result.exceptionDetails) {
2443
+ const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.exception?.value ?? result.exceptionDetails.text;
2444
+ throw new Error(`${detail}`);
2445
+ }
2446
+ return result.result?.value;
2447
+ }
2448
+ /**
2449
+ * 在指定 iframe 上下文中执行表达式(攻防 D16 能力建设,2026-08-19)。
2450
+ *
2451
+ * 双路径:
2452
+ * 1. 同进程 iframe —— Runtime.enable 收集 executionContextCreated,
2453
+ * 找到目标 frameId 的 contextId,用 contextId 定向执行;
2454
+ * 2. 跨域 OOPIF(独立 target)—— Target.setAutoAttach(flatten) 监听
2455
+ * attachedToTarget 中 type==='iframe' 的会话,用其 sessionId 执行。
2456
+ *
2457
+ * 这绕过了页面同源策略(那是页面 JS 的约束,CDP 是调试通道)——
2458
+ * 支付窗/验证码/第三方嵌入内容的读写都靠它。
2459
+ */
2460
+ async evaluateInFrame(urlIncludes, expression) {
2461
+ if (this.options.isClosed()) throw new Error("Page is closed");
2462
+ const evalIn = async (sessionId, contextId) => {
2463
+ const params = { expression, returnByValue: true, awaitPromise: true };
2464
+ if (contextId !== void 0) params.contextId = contextId;
2465
+ const result = await this.options.conn.send("Runtime.evaluate", params, sessionId);
2466
+ if (result.exceptionDetails) {
2467
+ const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.exception?.value ?? result.exceptionDetails.text;
2468
+ throw new Error(`[frame ${urlIncludes}] ${detail}`);
2469
+ }
2470
+ return result.result?.value;
2471
+ };
2472
+ const attachedA = await this.tryAttachViaTargets(urlIncludes);
2473
+ if (attachedA) {
2474
+ try {
2475
+ return await evalIn(attachedA);
2476
+ } finally {
2477
+ this.detachQuietly(attachedA);
2478
+ }
2479
+ }
2480
+ const tree = await this.options.conn.send("Page.getFrameTree", void 0, this.options.sessionId);
2481
+ const all = [];
2482
+ const walk = (node) => {
2483
+ all.push({ id: node.frame.id, url: node.frame.url });
2484
+ for (const child of node.childFrames || []) walk(child);
2485
+ };
2486
+ walk(tree.frameTree);
2487
+ const mainId = tree.frameTree?.frame?.id;
2488
+ const target = all.find((f) => f.id !== mainId && f.url.includes(urlIncludes));
2489
+ if (target) {
2490
+ const contexts = [];
2491
+ const onCtx = (raw) => {
2492
+ const c = raw?.context;
2493
+ if (c?.id && c?.auxData?.frameId) contexts.push({ id: c.id, frameId: c.auxData.frameId });
2494
+ };
2495
+ this.options.conn.on("Runtime.executionContextCreated", onCtx);
2496
+ try {
2497
+ await this.options.conn.send("Runtime.enable", void 0, this.options.sessionId).catch(() => {
2498
+ });
2499
+ await new Promise((r) => setTimeout(r, 400));
2500
+ } finally {
2501
+ this.options.conn.off("Runtime.executionContextCreated", onCtx);
2502
+ }
2503
+ const ctx = contexts.find((c) => c.frameId === target.id);
2504
+ if (ctx) return evalIn(this.options.sessionId, ctx.id);
2505
+ }
2506
+ const attachedC = await this.tryAttachViaAutoAttach(urlIncludes);
2507
+ if (attachedC) {
2508
+ try {
2509
+ return await evalIn(attachedC);
2510
+ } finally {
2511
+ this.detachQuietly(attachedC);
2512
+ }
2513
+ }
2514
+ 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`);
2515
+ }
2516
+ /**
2517
+ * 输入专用 frame session 解析(mouse/click/fill --frame)。
2518
+ *
2519
+ * 与 evaluateInFrame 的区别:必须拿到**真实 target session**(Input 域
2520
+ * 事件派发到该 session 才会进入 iframe 的渲染进程——主页面 session 上
2521
+ * 派发的输入进不去 OOPIF,qqmail 验证码 4 次页面级拖动全败的实证)。
2522
+ * 因此只走 A(getTargets attach)/ C(auto-attach)两路;同进程 frame
2523
+ * 没有 session,但 locator 层的坐标偏移本就支持同源 iframe,直接用普通
2524
+ * click/fill 即可。
2525
+ *
2526
+ * 坐标语义:返回的 session 上派发 Input 事件用 **iframe 局部坐标**
2527
+ * (与该 session 内 getBoundingClientRect 一致)。
2528
+ */
2529
+ async resolveFrameSession(urlIncludes) {
2530
+ if (this.options.isClosed()) throw new Error("Page is closed");
2531
+ const viaTargets = await this.tryAttachViaTargets(urlIncludes);
2532
+ if (viaTargets) return viaTargets;
2533
+ const viaAuto = await this.tryAttachViaAutoAttach(urlIncludes);
2534
+ if (viaAuto) return viaAuto;
2535
+ try {
2536
+ const tree = await this.options.conn.send("Page.getFrameTree", void 0, this.options.sessionId);
2537
+ const urls = [];
2538
+ const walk = (node) => {
2539
+ urls.push(node.frame.url);
2540
+ for (const child of node.childFrames || []) walk(child);
2541
+ };
2542
+ walk(tree.frameTree);
2543
+ if (urls.some((u) => u.includes(urlIncludes))) {
2544
+ 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`);
2545
+ }
2546
+ } catch (err) {
2547
+ if (err instanceof Error && err.message.includes("\u540C\u8FDB\u7A0B")) throw err;
2548
+ }
2549
+ 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`);
2550
+ }
2551
+ /** 浏览器级 iframe target 列表(OOPIF 可见性——Page.getFrameTree 看不到它们) */
2552
+ async listFrameTargets() {
2553
+ try {
2554
+ const tg = await this.options.conn.send("Target.getTargets", void 0);
2555
+ return (tg.targetInfos || []).filter((t) => t.type === "iframe").map((t) => ({ url: t.url || "", targetId: t.targetId }));
2556
+ } catch {
2557
+ return [];
2558
+ }
2559
+ }
2560
+ /** 路径 A:浏览器级 Target.getTargets 平铺 iframe target,按 URL 子串 attach。
2561
+ * 多次导航后列表里可能残留正在销毁的陈旧 target——attach 后用 location.href
2562
+ * 验证候选确实是活目标,不匹配则换下一个(验证码 iframe 重建场景实测会撞上)。 */
2563
+ async tryAttachViaTargets(urlIncludes) {
2564
+ try {
2565
+ const tg = await this.options.conn.send("Target.getTargets", void 0);
2566
+ const candidates = (tg.targetInfos || []).filter((t) => t.type === "iframe" && (t.url || "").includes(urlIncludes));
2567
+ for (const hit of candidates) {
2568
+ try {
2569
+ const att = await this.options.conn.send("Target.attachToTarget", { targetId: hit.targetId, flatten: true });
2570
+ const probe = await this.options.conn.send("Runtime.evaluate", { expression: "location.href", returnByValue: true }, att.sessionId);
2571
+ const href = typeof probe.result?.value === "string" ? probe.result.value : "";
2572
+ if (probe.exceptionDetails || !href.includes(urlIncludes)) {
2573
+ this.detachQuietly(att.sessionId);
2574
+ continue;
2575
+ }
2576
+ return att.sessionId;
2577
+ } catch {
2578
+ continue;
2579
+ }
2580
+ }
2581
+ } catch {
2582
+ }
2583
+ return null;
2584
+ }
2585
+ /** 路径 C:Target.setAutoAttach 监听后续 attach 的 iframe target(兜底) */
2586
+ async tryAttachViaAutoAttach(urlIncludes) {
2587
+ const attached = [];
2588
+ const onAttach = (raw) => {
2589
+ const ev = raw;
2590
+ if (ev?.sessionId && ev.targetInfo?.type === "iframe") {
2591
+ attached.push({ sessionId: ev.sessionId, url: ev.targetInfo.url || "" });
2592
+ }
2593
+ };
2594
+ this.options.conn.on("Target.attachedToTarget", onAttach);
2595
+ try {
2596
+ await this.options.conn.send("Target.setAutoAttach", {
2597
+ autoAttach: true,
2598
+ waitForDebuggerOnStart: false,
2599
+ flatten: true
2600
+ }, this.options.sessionId);
2601
+ await new Promise((r) => setTimeout(r, 600));
2602
+ } finally {
2603
+ this.options.conn.off("Target.attachedToTarget", onAttach);
2604
+ this.options.conn.send("Target.setAutoAttach", { autoAttach: false, waitForDebuggerOnStart: false, flatten: true }, this.options.sessionId).catch(() => {
2605
+ });
2606
+ }
2607
+ const hit = attached.find((a) => a.url.includes(urlIncludes));
2608
+ return hit ? hit.sessionId : null;
2609
+ }
2610
+ detachQuietly(sessionId) {
2611
+ this.options.conn.send("Target.detachFromTarget", { sessionId }).catch(() => {
2612
+ });
2613
+ }
2614
+ /** evaluateHandle — evaluates fn and returns a handle for element bounding box */
2615
+ async evaluateHandle(fn, ...args) {
2616
+ let expression;
2617
+ if (typeof fn === "string") {
2618
+ expression = fn;
2619
+ } else {
2620
+ const argStr = args.length > 0 ? `...${JSON.stringify(args)}` : "";
2621
+ expression = `(()=>{const __fn=(${fn.toString()});const __el=__fn(${argStr});if(__el&&typeof __el.getBoundingClientRect==='function'){const r=__el.getBoundingClientRect();return JSON.parse(JSON.stringify({x:r.x,y:r.y,w:r.width,h:r.height}));}return null;})()`;
2622
+ }
2623
+ const result = await this.options.conn.send("Runtime.evaluate", { expression, returnByValue: true }).catch(() => ({ result: { value: null } }));
2624
+ let box = null;
2625
+ try {
2626
+ box = JSON.parse(result.result?.value);
2627
+ } catch {
2628
+ }
2629
+ return {
2630
+ asElement: () => box ? { boundingBox: async () => box } : null
2631
+ };
2632
+ }
2633
+ async $eval(selector, fn, ...args) {
2634
+ const fnBody = typeof fn === "function" ? fn.toString() : fn;
2635
+ const selJSON = JSON.stringify(selector);
2636
+ const xpathPrefix = selector.startsWith("xpath=") ? JSON.stringify(selector.slice(6)) : "null";
2637
+ return this.evaluate(
2638
+ `(function(sel, xpathExpr, fnStr, ...evalArgs) {
2639
+ const el = xpathExpr
2640
+ ? document.evaluate(xpathExpr, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
2641
+ : document.querySelector(sel);
2642
+ if (!el) throw new Error('No element found for selector: ' + sel);
2643
+ const fn = new Function('return ' + fnStr)();
2644
+ return fn(el, ...evalArgs);
2645
+ })(${selJSON}, ${xpathPrefix}, ${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
2646
+ );
2647
+ }
2648
+ async $$eval(selector, fn, ...args) {
2649
+ const fnBody = typeof fn === "function" ? fn.toString() : fn;
2650
+ const selJSON = JSON.stringify(selector);
2651
+ const xpathPrefix = selector.startsWith("xpath=") ? JSON.stringify(selector.slice(6)) : "null";
2652
+ return this.evaluate(
2653
+ `(function(sel, xpathExpr, fnStr, ...evalArgs) {
2654
+ const els = xpathExpr
2655
+ ? (() => { const it = document.evaluate(xpathExpr, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); const r=[]; for(let i=0;i<it.snapshotLength;i++) r.push(it.snapshotItem(i)); return r; })()
2656
+ : Array.from(document.querySelectorAll(sel));
2657
+ const fn = new Function('return ' + fnStr)();
2658
+ return fn(els, ...evalArgs);
2659
+ })(${selJSON}, ${xpathPrefix}, ${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
2660
+ );
2661
+ }
2662
+ };
2663
+
2664
+ // src/cdp-driver/page-frame-input.ts
2665
+ function isSessionDeadError(err) {
2666
+ return /session (with given id )?not found|no session with given id/i.test(errMsg(err));
2667
+ }
2668
+ var FrameInputService = class {
2669
+ constructor(deps) {
2670
+ this.deps = deps;
2671
+ }
2672
+ deps;
2673
+ /** urlIncludes → 已 attach 的 session + 鼠标实例(跨命令保持位置状态) */
2674
+ cache = /* @__PURE__ */ new Map();
2675
+ /**
2676
+ * 拿到指定 OOPIF 的鼠标(Input 域派发进 iframe 渲染进程,isTrusted=true)。
2677
+ * 缓存的 session 失效(iframe 重建/刷新)时自动重 attach;重 attach 会
2678
+ * 重置鼠标位置——调用方需重新读取目标元素坐标。
2679
+ */
2680
+ async frameMouse(urlIncludes, opts = {}) {
2681
+ if (opts.fresh) this.cache.delete(urlIncludes);
2682
+ const cached = this.cache.get(urlIncludes);
2683
+ if (cached) {
2684
+ try {
2685
+ await this.deps.conn.send("Runtime.evaluate", { expression: "1", returnByValue: true }, cached.sessionId);
2686
+ return cached.mouse;
2687
+ } catch {
2688
+ this.cache.delete(urlIncludes);
2689
+ }
2690
+ }
2691
+ const sessionId = await this.deps.resolveFrameSession(urlIncludes);
2692
+ const mouse = new XBMouseImpl(this.deps.conn, sessionId);
2693
+ this.cache.set(urlIncludes, { sessionId, mouse });
2694
+ return mouse;
2695
+ }
2696
+ /**
2697
+ * 带重试的 frame 鼠标操作:Chrome 异步销毁旧 OOPIF target 的窗口期里
2698
+ * (连续导航/验证码 iframe 重建),probe 通过后 dispatch 仍可能撞上死
2699
+ * session——session 失效时强制重 attach 再做一次。
2700
+ */
2701
+ async runFrameMouse(urlIncludes, fn) {
2702
+ try {
2703
+ return await fn(await this.frameMouse(urlIncludes));
2704
+ } catch (err) {
2705
+ if (!isSessionDeadError(err)) throw err;
2706
+ this.cache.delete(urlIncludes);
2707
+ return fn(await this.frameMouse(urlIncludes, { fresh: true }));
2708
+ }
2709
+ }
2710
+ /** 在 OOPIF 内点击选择器命中的元素(frame 局部坐标,stealth 落点偏移继承) */
2711
+ async clickInFrame(urlIncludes, selector, opts = {}) {
2712
+ const rect = await this.pollFrameRect(urlIncludes, selector, opts.timeoutMs ?? 5e3);
2713
+ const x = rect.x + rect.width / 2;
2714
+ const y = rect.y + rect.height / 2;
2715
+ await this.runFrameMouse(urlIncludes, (mouse) => mouse.click(x, y, { elementWidth: rect.width, elementHeight: rect.height }));
2716
+ return { x, y };
2717
+ }
2718
+ /** 在 OOPIF 内填输入框:点击聚焦 → el.select() 全选 → insertText 整体替换 → 回读验证 */
2719
+ async fillInFrame(urlIncludes, selector, text, opts = {}) {
2720
+ try {
2721
+ return await this.fillInFrameInner(urlIncludes, selector, text, opts);
2722
+ } catch (err) {
2723
+ if (!isSessionDeadError(err)) throw err;
2724
+ this.cache.delete(urlIncludes);
2725
+ return this.fillInFrameInner(urlIncludes, selector, text, opts);
2726
+ }
2727
+ }
2728
+ async fillInFrameInner(urlIncludes, selector, text, opts = {}) {
2729
+ await this.clickInFrame(urlIncludes, selector, opts);
2730
+ const cached = this.cache.get(urlIncludes);
2731
+ if (!cached) throw new Error(`frame session lost for "${urlIncludes}"`);
2732
+ await this.deps.evaluateInFrame(
2733
+ urlIncludes,
2734
+ `(() => { const el = document.querySelector(${JSON.stringify(selector)}); if (el && typeof el.select === 'function') el.select(); return true; })()`
2735
+ );
2736
+ await this.deps.conn.send("Input.insertText", { text }, cached.sessionId);
2737
+ const readback = await this.deps.evaluateInFrame(
2738
+ urlIncludes,
2739
+ `(() => { const el = document.querySelector(${JSON.stringify(selector)}); return el ? String(el.value ?? '') : ''; })()`
2740
+ );
2741
+ return { value: readback ?? "" };
2742
+ }
2743
+ /** 轮询 OOPIF 内元素 rect(等待元素出现/可测量) */
2744
+ async pollFrameRect(urlIncludes, selector, timeoutMs) {
2745
+ 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 }; })()`;
2746
+ const deadline = Date.now() + timeoutMs;
2747
+ let lastErr;
2748
+ while (Date.now() < deadline) {
2749
+ try {
2750
+ const rect = await this.deps.evaluateInFrame(urlIncludes, expr);
2751
+ if (rect) return rect;
2752
+ } catch (err) {
2753
+ lastErr = err;
2754
+ }
2755
+ await new Promise((r) => setTimeout(r, 200));
2756
+ }
2757
+ throw new Error(`[frame ${urlIncludes}] element "${selector}" not found/visible within ${timeoutMs}ms${lastErr instanceof Error ? `\uFF08last: ${lastErr.message}\uFF09` : ""}`);
2758
+ }
2759
+ };
2760
+
2761
+ // src/cdp-driver/page.ts
2762
+ var XBPageImpl = class _XBPageImpl {
2763
+ conn;
2764
+ _emitter = new EventEmitter();
2765
+ _subscriptions = [];
2766
+ sessionId;
2767
+ _targetId;
2768
+ _contextImpl;
2769
+ _browserImpl;
2770
+ _closed = false;
2771
+ _url = "about:blank";
2772
+ _viewportSize = null;
2773
+ _loadState = {
2774
+ loadFired: true,
2775
+ domContentFired: true,
2776
+ networkIdle: true
2777
+ };
2778
+ mouse;
2779
+ keyboard;
2780
+ mediaService;
2781
+ fileInputService;
2782
+ networkWaitService;
2783
+ networkRouteService;
2784
+ navigationService;
2785
+ domQueryService;
2786
+ runtimeEvaluationService;
2787
+ frameInputService;
2788
+ // Network tracking for waitForLoadState('networkidle')
2789
+ inflightRequests = /* @__PURE__ */ new Set();
2790
+ networkIdleResolve = null;
2791
+ networkIdleTimer = null;
2792
+ static NETWORK_IDLE_MS = 500;
2793
+ constructor(conn, sessionId, targetId, context, browser) {
2794
+ this.conn = conn;
2795
+ this.sessionId = sessionId;
2796
+ this._targetId = targetId;
2797
+ this._contextImpl = context;
2798
+ this._browserImpl = browser;
2799
+ this.mouse = new XBMouseImpl(conn, sessionId);
2800
+ this.keyboard = new XBKeyboardImpl(conn, sessionId);
2801
+ this.mediaService = new MediaService({
2802
+ conn,
2803
+ sessionId,
2804
+ viewportSize: this._viewportSize,
2805
+ evaluate: (script) => this.evaluate(script),
2806
+ onViewportSize: (size) => {
2807
+ this._viewportSize = size;
2808
+ }
2809
+ });
2810
+ this.fileInputService = new FileInputService({
2811
+ conn,
2812
+ sessionId,
2813
+ evaluate: (script) => this.evaluate(script),
2814
+ mouse: this.mouse
2815
+ });
2816
+ this.networkWaitService = new NetworkWaitService({
2817
+ conn,
2818
+ sessionId,
2819
+ responses: this._networkResponses,
2820
+ requests: this._networkRequests,
2821
+ on: (event, handler) => this._emitter.on(event, handler),
2822
+ off: (event, handler) => this._emitter.removeListener(event, handler),
2823
+ currentUrl: () => this.url()
2824
+ });
2825
+ this.networkRouteService = new NetworkRouteService({
2826
+ conn,
2827
+ sessionId,
2828
+ emit: (event, ...args) => this._emit(event, ...args)
2829
+ });
2830
+ this.navigationService = new NavigationService({
2831
+ conn,
2832
+ sessionId,
2833
+ state: this._loadState,
2834
+ stealthConfig: this._contextImpl.stealthConfig,
2835
+ isClosed: () => this._closed,
2836
+ setUrl: (url) => {
2837
+ this._url = url;
2838
+ },
2839
+ currentUrl: () => this.url(),
2840
+ waitForLoadState: (state, timeout) => this.waitForLoadState(state, timeout),
2841
+ waitForTimeout: (ms) => this.waitForTimeout(ms),
2842
+ evaluate: (script) => this.evaluate(script)
2843
+ });
2844
+ this.runtimeEvaluationService = new RuntimeEvaluationService({
2845
+ conn,
2846
+ sessionId,
2847
+ isClosed: () => this._closed,
2848
+ url: () => this.url()
2849
+ });
2850
+ this.frameInputService = new FrameInputService({
2851
+ conn,
2852
+ resolveFrameSession: (urlIncludes) => this.runtimeEvaluationService.resolveFrameSession(urlIncludes),
2853
+ evaluateInFrame: (urlIncludes, expression) => this.evaluateInFrame(urlIncludes, expression)
2854
+ });
2855
+ this.domQueryService = new DomQueryService({
2856
+ conn,
2857
+ sessionId,
2858
+ evaluate: (script) => this.evaluate(script)
2859
+ });
2860
+ }
2861
+ _emit(event, ...args) {
2862
+ this._emitter.emit(event, ...args);
2863
+ }
2864
+ /** Internal initialization — must be called after construction */
2865
+ async _init() {
2866
+ await this.conn.send("Page.enable", void 0, this.sessionId);
2867
+ await this.conn.send("Runtime.enable", void 0, this.sessionId);
2868
+ await this.conn.send("Network.enable", void 0, this.sessionId);
2869
+ await this.conn.send("DOM.enable", void 0, this.sessionId).catch(() => {
2870
+ });
2871
+ if (this._contextImpl.ignoreHTTPSErrors) {
2872
+ await this.conn.send("Security.enable", void 0, this.sessionId).catch(() => {
2873
+ });
2874
+ await this.conn.send("Security.setIgnoreCertificateErrors", { ignore: true }, this.sessionId).catch(() => {
2875
+ });
2876
+ }
2877
+ if (this._contextImpl.httpCredentials) {
2878
+ await this.conn.send("Fetch.enable", {
2879
+ patterns: [{ urlPattern: "*", requestStage: "Request" }],
1637
2880
  handleAuthRequests: true
1638
2881
  }, this.sessionId).catch(() => {
1639
2882
  });
1640
2883
  this._subscriptions.push(
1641
2884
  this.conn.subscribe("Fetch.requestPaused", this.sessionId, (params) => {
1642
- if (this._interceptionEnabled) return;
2885
+ if (this.networkRouteService.isInterceptionEnabled) return;
1643
2886
  const p = params;
1644
2887
  this.conn.send("Fetch.continueRequest", { requestId: p.requestId }, this.sessionId).catch(() => {
1645
2888
  });
@@ -1818,9 +3061,9 @@ var XBPageImpl = class _XBPageImpl {
1818
3061
  "Target.getTargetInfo",
1819
3062
  { targetId: this._targetId }
1820
3063
  );
1821
- this._url = info.url;
1822
- this._title = info.title;
1823
- if (info.url && info.url !== "about:blank" && info.url !== "") {
3064
+ const curUrl = info.targetInfo?.url ?? info.url;
3065
+ if (curUrl) this._url = curUrl;
3066
+ if (curUrl && curUrl !== "about:blank" && curUrl !== "") {
1824
3067
  this._loadState = { loadFired: true, domContentFired: true, networkIdle: true };
1825
3068
  }
1826
3069
  } catch {
@@ -1831,108 +3074,16 @@ var XBPageImpl = class _XBPageImpl {
1831
3074
  }
1832
3075
  // ── Navigation ──────────────────────────────────────────────
1833
3076
  async goto(url, opts = {}) {
1834
- if (this._closed) throw new Error("Page is closed");
1835
- const waitUntil = opts.waitUntil ?? "load";
1836
- const timeout = opts.timeout ?? 3e4;
1837
- this._loadState = { loadFired: false, domContentFired: false, networkIdle: false };
1838
- if (process.env.XBROWSER_STEALTH !== "off") {
1839
- try {
1840
- await this.conn.send(
1841
- "Page.addScriptToEvaluateOnNewDocument",
1842
- { source: buildStealthInitScript({ ...DEFAULT_STEALTH_CONFIG, ...this._contextImpl.stealthConfig ?? {} }) },
1843
- this.sessionId
1844
- );
1845
- } catch {
1846
- }
1847
- try {
1848
- const rawUa = await this.conn.send(
1849
- "Runtime.evaluate",
1850
- { expression: "navigator.userAgent", returnByValue: true },
1851
- this.sessionId
1852
- );
1853
- const ua = rawUa?.value || "";
1854
- const cleaned = ua.replace(/HeadlessChrome/g, "Chrome");
1855
- if (cleaned !== ua) {
1856
- await this.conn.send(
1857
- "Network.setUserAgentOverride",
1858
- { userAgent: cleaned },
1859
- this.sessionId
1860
- );
1861
- }
1862
- } catch {
1863
- }
1864
- }
1865
- const result = await this.conn.send(
1866
- "Page.navigate",
1867
- { url, referrer: opts.referer },
1868
- this.sessionId
1869
- );
1870
- if (result.errorText) {
1871
- throw new Error(`Navigation failed: ${result.errorText}`);
1872
- }
1873
- if (waitUntil === "commit") {
1874
- this._url = url;
1875
- return {
1876
- status: () => 0,
1877
- ok: () => false,
1878
- url: () => url,
1879
- headers: () => ({})
1880
- };
1881
- }
1882
- await this.waitForLoadState(waitUntil, timeout);
1883
- this._url = url;
1884
- const statusCode = 200;
1885
- const finalUrl = url;
1886
- const headers = {};
1887
- return {
1888
- status: () => statusCode,
1889
- ok: () => statusCode >= 200 && statusCode < 300,
1890
- url: () => finalUrl,
1891
- headers: () => headers
1892
- };
3077
+ return this.navigationService.goto(url, opts);
1893
3078
  }
1894
3079
  async goBack(opts = {}) {
1895
- try {
1896
- const navHistory = await this.conn.send("Page.getNavigationHistory", void 0, this.sessionId);
1897
- if (navHistory.currentIndex > 0) {
1898
- const prevUrl = navHistory.entries[navHistory.currentIndex - 1]?.url;
1899
- if (prevUrl && prevUrl !== "about:blank") {
1900
- await this.conn.send("Page.navigate", { url: prevUrl }, this.sessionId);
1901
- await this.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
1902
- });
1903
- this._url = prevUrl;
1904
- return;
1905
- }
1906
- }
1907
- } catch {
1908
- }
1909
- await this.evaluate("() => history.back()");
1910
- await this.waitForTimeout(3e3);
1911
- this._url = await this.evaluate("location.href").catch(() => this._url);
3080
+ return this.navigationService.goBack(opts);
1912
3081
  }
1913
3082
  async goForward(opts = {}) {
1914
- try {
1915
- const navHistory = await this.conn.send("Page.getNavigationHistory", void 0, this.sessionId);
1916
- if (navHistory.currentIndex < navHistory.entries.length - 1) {
1917
- const nextUrl = navHistory.entries[navHistory.currentIndex + 1]?.url;
1918
- if (nextUrl && nextUrl !== "about:blank") {
1919
- await this.conn.send("Page.navigate", { url: nextUrl }, this.sessionId);
1920
- await this.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
1921
- });
1922
- this._url = nextUrl;
1923
- return;
1924
- }
1925
- }
1926
- } catch {
1927
- }
1928
- await this.evaluate("() => history.forward()");
1929
- await this.waitForTimeout(3e3);
1930
- this._url = await this.evaluate("location.href").catch(() => this._url);
3083
+ return this.navigationService.goForward(opts);
1931
3084
  }
1932
3085
  async reload(opts = {}) {
1933
- this._loadState = { loadFired: false, domContentFired: false, networkIdle: false };
1934
- await this.conn.send("Page.reload", void 0, this.sessionId);
1935
- await this.waitForLoadState(opts.waitUntil ?? "load", opts.timeout);
3086
+ return this.navigationService.reload(opts);
1936
3087
  }
1937
3088
  async waitForLoadState(state = "load", timeout = 3e4) {
1938
3089
  if (this._closed) throw new Error("Page is closed");
@@ -2008,201 +3159,66 @@ var XBPageImpl = class _XBPageImpl {
2008
3159
  while (Date.now() < deadline) {
2009
3160
  try {
2010
3161
  const result = await this.evaluate(
2011
- `(function(fnStr, ...evalArgs) { const fn = new Function('return ' + fnStr); return fn(...evalArgs); })(${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
2012
- );
2013
- if (result) return result;
2014
- } catch (err) {
2015
- lastError = err instanceof Error ? err : new Error(errMsg(err));
2016
- }
2017
- const pollMs = typeof polling === "number" ? polling : 16;
2018
- await this.waitForTimeout(pollMs);
2019
- }
2020
- const detail = lastError ? `
2021
- Last error: ${lastError.message}` : "";
2022
- throw new Error(`waitForFunction timeout after ${timeout}ms${detail}`);
2023
- }
2024
- url() {
2025
- return this._url;
2026
- }
2027
- async title() {
2028
- for (let i = 0; i < 20; i++) {
2029
- try {
2030
- this._title = await this.evaluate("document.title");
2031
- if (this._title) return this._title;
2032
- } catch {
2033
- }
2034
- await new Promise((r) => setTimeout(r, 50));
2035
- }
2036
- try {
2037
- const info = await this._cdpSend("Target.getTargetInfo", { targetId: this._targetId });
2038
- if (info?.title) {
2039
- this._title = info.title;
2040
- return this._title;
2041
- }
2042
- } catch {
2043
- }
2044
- return this._title;
2045
- }
2046
- async content() {
2047
- return this.evaluate("document.documentElement.outerHTML");
2048
- }
2049
- // ── Evaluation ──────────────────────────────────────────────
2050
- async evaluate(fn, ...args) {
2051
- if (this._closed) throw new Error("Page is closed");
2052
- this.conn.send("Page.handleJavaScriptDialog", { accept: false }, this.sessionId).catch(() => {
2053
- });
2054
- let expression;
2055
- if (typeof fn === "string") {
2056
- expression = fn;
2057
- } else {
2058
- const argStr = args.length > 0 ? `...${JSON.stringify(args)}` : "";
2059
- expression = `(()=>{const __fn=(${fn.toString()});return __fn(${argStr});})()`;
2060
- }
2061
- const result = await this.conn.send("Runtime.evaluate", {
2062
- expression,
2063
- returnByValue: true,
2064
- awaitPromise: true
2065
- }, this.sessionId);
2066
- if (result.exceptionDetails) {
2067
- const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.exception?.value ?? result.exceptionDetails.text;
2068
- throw new Error(`${detail}`);
2069
- }
2070
- return result.result?.value;
2071
- }
2072
- /**
2073
- * 在指定 iframe 上下文中执行表达式(攻防 D16 能力建设,2026-08-19)。
2074
- *
2075
- * 双路径:
2076
- * 1. 同进程 iframe —— Runtime.enable 收集 executionContextCreated,
2077
- * 找到目标 frameId 的 contextId,用 contextId 定向执行;
2078
- * 2. 跨域 OOPIF(独立 target)—— Target.setAutoAttach(flatten) 监听
2079
- * attachedToTarget 中 type==='iframe' 的会话,用其 sessionId 执行。
2080
- *
2081
- * 这绕过了页面同源策略(那是页面 JS 的约束,CDP 是调试通道)——
2082
- * 支付窗/验证码/第三方嵌入内容的读写都靠它。
2083
- */
2084
- async evaluateInFrame(urlIncludes, expression) {
2085
- if (this._closed) throw new Error("Page is closed");
2086
- const evalIn = async (sessionId, contextId) => {
2087
- const params = { expression, returnByValue: true, awaitPromise: true };
2088
- if (contextId !== void 0) params.contextId = contextId;
2089
- const result = await this.conn.send("Runtime.evaluate", params, sessionId);
2090
- if (result.exceptionDetails) {
2091
- const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.exception?.value ?? result.exceptionDetails.text;
2092
- throw new Error(`[frame ${urlIncludes}] ${detail}`);
2093
- }
2094
- return result.result?.value;
2095
- };
2096
- try {
2097
- const tg = await this.conn.send("Target.getTargets", void 0);
2098
- const hit2 = (tg.targetInfos || []).find((t) => t.type === "iframe" && (t.url || "").includes(urlIncludes));
2099
- if (hit2) {
2100
- const att = await this.conn.send("Target.attachToTarget", { targetId: hit2.targetId, flatten: true });
2101
- return evalIn(att.sessionId);
2102
- }
2103
- } catch {
2104
- }
2105
- const tree = await this.conn.send("Page.getFrameTree", void 0, this.sessionId);
2106
- const all = [];
2107
- const walk = (node) => {
2108
- all.push({ id: node.frame.id, url: node.frame.url });
2109
- for (const child of node.childFrames || []) walk(child);
2110
- };
2111
- walk(tree.frameTree);
2112
- const mainId = tree.frameTree?.frame?.id;
2113
- const target = all.find((f) => f.id !== mainId && f.url.includes(urlIncludes));
2114
- if (target) {
2115
- const contexts = [];
2116
- const onCtx = (raw) => {
2117
- const c = raw?.context;
2118
- if (c?.id && c?.auxData?.frameId) contexts.push({ id: c.id, frameId: c.auxData.frameId });
2119
- };
2120
- this.conn.on("Runtime.executionContextCreated", onCtx);
2121
- try {
2122
- await this.conn.send("Runtime.enable", void 0, this.sessionId).catch(() => {
2123
- });
2124
- await new Promise((r) => setTimeout(r, 400));
2125
- } finally {
2126
- this.conn.off("Runtime.executionContextCreated", onCtx);
2127
- }
2128
- const ctx = contexts.find((c) => c.frameId === target.id);
2129
- if (ctx) return evalIn(this.sessionId, ctx.id);
2130
- }
2131
- const attached = [];
2132
- const onAttach = (raw) => {
2133
- const ev = raw;
2134
- if (ev?.sessionId && ev.targetInfo?.type === "iframe") {
2135
- attached.push({ sessionId: ev.sessionId, url: ev.targetInfo.url || "" });
2136
- }
2137
- };
2138
- this.conn.on("Target.attachedToTarget", onAttach);
2139
- try {
2140
- await this.conn.send("Target.setAutoAttach", {
2141
- autoAttach: true,
2142
- waitForDebuggerOnStart: false,
2143
- flatten: true
2144
- }, this.sessionId);
2145
- await new Promise((r) => setTimeout(r, 600));
2146
- } finally {
2147
- this.conn.off("Target.attachedToTarget", onAttach);
2148
- this.conn.send("Target.setAutoAttach", { autoAttach: false, waitForDebuggerOnStart: false, flatten: true }, this.sessionId).catch(() => {
2149
- });
2150
- }
2151
- const hit = attached.find((a) => a.url.includes(urlIncludes));
2152
- if (!hit) {
2153
- 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`);
2154
- }
2155
- return evalIn(hit.sessionId);
2156
- }
2157
- /** evaluateHandle — evaluates fn and returns a handle for element bounding box */
2158
- async evaluateHandle(fn, ...args) {
2159
- let expression;
2160
- if (typeof fn === "string") {
2161
- expression = fn;
2162
- } else {
2163
- const argStr = args.length > 0 ? `...${JSON.stringify(args)}` : "";
2164
- expression = `(()=>{const __fn=(${fn.toString()});const __el=__fn(${argStr});if(__el&&typeof __el.getBoundingClientRect==='function'){const r=__el.getBoundingClientRect();return JSON.parse(JSON.stringify({x:r.x,y:r.y,w:r.width,h:r.height}));}return null;})()`;
2165
- }
2166
- const result = await this.conn.send("Runtime.evaluate", { expression, returnByValue: true }).catch(() => ({ result: { value: null } }));
2167
- let box = null;
2168
- try {
2169
- box = JSON.parse(result.result?.value);
2170
- } catch {
3162
+ `(function(fnStr, ...evalArgs) { const fn = new Function('return ' + fnStr); return fn(...evalArgs); })(${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
3163
+ );
3164
+ if (result) return result;
3165
+ } catch (err) {
3166
+ lastError = err instanceof Error ? err : new Error(errMsg(err));
3167
+ }
3168
+ const pollMs = typeof polling === "number" ? polling : 16;
3169
+ await this.waitForTimeout(pollMs);
2171
3170
  }
2172
- return {
2173
- asElement: () => box ? { boundingBox: async () => box } : null
2174
- };
3171
+ const detail = lastError ? `
3172
+ Last error: ${lastError.message}` : "";
3173
+ throw new Error(`waitForFunction timeout after ${timeout}ms${detail}`);
3174
+ }
3175
+ url() {
3176
+ return this._url;
3177
+ }
3178
+ async title() {
3179
+ return this.runtimeEvaluationService.title();
3180
+ }
3181
+ async content() {
3182
+ return this.runtimeEvaluationService.content();
3183
+ }
3184
+ async evaluate(fn, ...args) {
3185
+ return this.runtimeEvaluationService.evaluate(fn, ...args);
3186
+ }
3187
+ async evaluateInFrame(urlIncludes, expression) {
3188
+ return this.runtimeEvaluationService.evaluateInFrame(urlIncludes, expression);
3189
+ }
3190
+ /** 浏览器级 iframe target 列表(OOPIF 可见——frames 命令用) */
3191
+ async listFrameTargets() {
3192
+ return this.runtimeEvaluationService.listFrameTargets();
3193
+ }
3194
+ /**
3195
+ * 拿到指定 OOPIF 的鼠标(Input 域派发进 iframe 渲染进程,isTrusted=true)。
3196
+ * 坐标语义:iframe 局部坐标(与该 session 内 getBoundingClientRect 一致)。
3197
+ * session 失效自动重 attach(鼠标位置会重置,需重读目标坐标)。
3198
+ */
3199
+ async frameMouse(urlIncludes, opts) {
3200
+ return this.frameInputService.frameMouse(urlIncludes, opts);
3201
+ }
3202
+ async runFrameMouse(urlIncludes, fn) {
3203
+ return this.frameInputService.runFrameMouse(urlIncludes, fn);
3204
+ }
3205
+ /** 在 OOPIF 内点击选择器命中的元素(轮询等待 + stealth 落点) */
3206
+ async clickInFrame(urlIncludes, selector, opts) {
3207
+ return this.frameInputService.clickInFrame(urlIncludes, selector, opts);
3208
+ }
3209
+ /** 在 OOPIF 内填输入框(点击聚焦 + insertText + 回读) */
3210
+ async fillInFrame(urlIncludes, selector, text, opts) {
3211
+ return this.frameInputService.fillInFrame(urlIncludes, selector, text, opts);
3212
+ }
3213
+ async evaluateHandle(script, ...args) {
3214
+ return this.runtimeEvaluationService.evaluateHandle(script, ...args);
2175
3215
  }
2176
3216
  async $eval(selector, fn, ...args) {
2177
- const fnBody = typeof fn === "function" ? fn.toString() : fn;
2178
- const selJSON = JSON.stringify(selector);
2179
- const xpathPrefix = selector.startsWith("xpath=") ? JSON.stringify(selector.slice(6)) : "null";
2180
- return this.evaluate(
2181
- `(function(sel, xpathExpr, fnStr, ...evalArgs) {
2182
- const el = xpathExpr
2183
- ? document.evaluate(xpathExpr, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
2184
- : document.querySelector(sel);
2185
- if (!el) throw new Error('No element found for selector: ' + sel);
2186
- const fn = new Function('return ' + fnStr)();
2187
- return fn(el, ...evalArgs);
2188
- })(${selJSON}, ${xpathPrefix}, ${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
2189
- );
3217
+ return this.runtimeEvaluationService.$eval(selector, fn, ...args);
2190
3218
  }
2191
3219
  async $$eval(selector, fn, ...args) {
2192
- const fnBody = typeof fn === "function" ? fn.toString() : fn;
2193
- const selJSON = JSON.stringify(selector);
2194
- const xpathPrefix = selector.startsWith("xpath=") ? JSON.stringify(selector.slice(6)) : "null";
2195
- return this.evaluate(
2196
- `(function(sel, xpathExpr, fnStr, ...evalArgs) {
2197
- const els = xpathExpr
2198
- ? (() => { const it = document.evaluate(xpathExpr, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); const r=[]; for(let i=0;i<it.snapshotLength;i++) r.push(it.snapshotItem(i)); return r; })()
2199
- : Array.from(document.querySelectorAll(sel));
2200
- const fn = new Function('return ' + fnStr)();
2201
- return fn(els, ...evalArgs);
2202
- })(${selJSON}, ${xpathPrefix}, ${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
2203
- );
3220
+ return this.runtimeEvaluationService.$$eval(selector, fn, ...args);
2204
3221
  }
2205
- // ── Locator ─────────────────────────────────────────────────
2206
3222
  locator(selector) {
2207
3223
  return new XBLocatorImpl(this, selector);
2208
3224
  }
@@ -2323,88 +3339,20 @@ Last error: ${lastError.message}` : "";
2323
3339
  }
2324
3340
  // ── Screen ──────────────────────────────────────────────────
2325
3341
  async screenshot(opts = {}) {
2326
- const params = {
2327
- format: opts.type ?? "png"
2328
- };
2329
- if (opts.quality !== void 0 && (opts.type === "jpeg" || !opts.type && opts.quality)) {
2330
- params.quality = opts.quality;
2331
- }
2332
- if (opts.fullPage) {
2333
- params.captureBeyondViewport = true;
2334
- }
2335
- if (opts.clip) {
2336
- const clip = {
2337
- x: Math.round(opts.clip.x),
2338
- y: Math.round(opts.clip.y),
2339
- width: Math.round(Math.max(1, opts.clip.width)),
2340
- height: Math.round(Math.max(1, opts.clip.height)),
2341
- scale: 1
2342
- };
2343
- params.clip = clip;
2344
- }
2345
- if (opts.omitBackground) {
2346
- params.omitBackground = true;
2347
- }
2348
- const result = await this.conn.send(
2349
- "Page.captureScreenshot",
2350
- params,
2351
- this.sessionId
2352
- );
2353
- return Buffer.from(result.data, "base64");
3342
+ return this.mediaService.screenshot(opts);
2354
3343
  }
2355
3344
  async pdf(opts = {}) {
2356
- const params = {};
2357
- if (opts.landscape !== void 0) params.landscape = opts.landscape;
2358
- if (opts.printBackground !== void 0) params.printBackground = opts.printBackground;
2359
- if (opts.scale !== void 0) params.scale = opts.scale;
2360
- if (opts.format) params.paperFormat = opts.format;
2361
- if (opts.preferCSSPageSize !== void 0) params.preferCSSPageSize = opts.preferCSSPageSize;
2362
- if (opts.margin) {
2363
- if (opts.margin.top) params.marginTop = parseFloat(opts.margin.top);
2364
- if (opts.margin.bottom) params.marginBottom = parseFloat(opts.margin.bottom);
2365
- if (opts.margin.left) params.marginLeft = parseFloat(opts.margin.left);
2366
- if (opts.margin.right) params.marginRight = parseFloat(opts.margin.right);
2367
- }
2368
- const result = await this.conn.send("Page.printToPDF", params, this.sessionId);
2369
- return Buffer.from(result.data, "base64");
3345
+ return this.mediaService.pdf(opts);
2370
3346
  }
2371
3347
  viewportSize() {
2372
- return this._viewportSize ?? null;
3348
+ return this._viewportSize;
2373
3349
  }
2374
3350
  async setViewportSize(size) {
2375
- await this.conn.send(
2376
- "Emulation.setDeviceMetricsOverride",
2377
- {
2378
- width: size.width,
2379
- height: size.height,
2380
- deviceScaleFactor: 1,
2381
- mobile: false
2382
- },
2383
- this.sessionId
2384
- );
2385
- this._viewportSize = size;
3351
+ return this.mediaService.setViewportSize(size);
2386
3352
  }
2387
- /**
2388
- * env-E2: 缩放变异——deviceScaleFactor 切换(CSS 像素坐标空间不变,
2389
- * 物理像素翻倍)。保留当前 CSS 视口尺寸,只换 DSF。
2390
- */
2391
3353
  async setDeviceScaleFactor(dsf) {
2392
- const size = this._viewportSize ?? await this.evaluate(
2393
- "({ width: window.innerWidth, height: window.innerHeight })"
2394
- );
2395
- await this.conn.send(
2396
- "Emulation.setDeviceMetricsOverride",
2397
- {
2398
- width: size.width,
2399
- height: size.height,
2400
- deviceScaleFactor: dsf,
2401
- mobile: false
2402
- },
2403
- this.sessionId
2404
- );
2405
- this._viewportSize = size;
3354
+ return this.mediaService.setDeviceScaleFactor(dsf);
2406
3355
  }
2407
- // ── Scripts ─────────────────────────────────────────────────
2408
3356
  async addInitScript(script) {
2409
3357
  await this.conn.send(
2410
3358
  "Page.addScriptToEvaluateOnNewDocument",
@@ -2532,83 +3480,17 @@ Last error: ${lastError.message}` : "";
2532
3480
  }
2533
3481
  }
2534
3482
  // ── CDP helpers exposed for locator/element ─────────────────
2535
- /** Query a single element, returns CDP nodeId or 0 if not found */
2536
3483
  async querySelector(selector) {
2537
- if (selector.startsWith("xpath=")) {
2538
- const found = await this.evaluate(`
2539
- (() => { const el = ${queryJS(selector)}; return !!el; })()
2540
- `).catch(() => false);
2541
- if (!found) return 0;
2542
- try {
2543
- const search = await this.conn.send(
2544
- "DOM.performSearch",
2545
- { query: selector.slice(6) },
2546
- this.sessionId
2547
- );
2548
- if (search.nodeId) return search.nodeId;
2549
- } catch {
2550
- }
2551
- return 1;
2552
- }
2553
- const withTimeout = (p, ms) => Promise.race([p, new Promise((r) => setTimeout(() => r(null), ms))]);
2554
- const doc = await withTimeout(
2555
- this.conn.send("DOM.getDocument", { depth: 0 }, this.sessionId),
2556
- 8e3
2557
- );
2558
- if (!doc) return 0;
2559
- const result = await withTimeout(
2560
- this.conn.send(
2561
- "DOM.querySelector",
2562
- { nodeId: doc.root.nodeId, selector },
2563
- this.sessionId
2564
- ),
2565
- 8e3
2566
- );
2567
- if (!result) return 0;
2568
- return result.nodeId;
3484
+ return this.domQueryService.querySelector(selector);
2569
3485
  }
2570
- /** Query all matching elements, returns array of CDP nodeIds */
2571
3486
  async querySelectorAll(selector) {
2572
- const doc = await this.conn.send(
2573
- "DOM.getDocument",
2574
- { depth: 0 },
2575
- this.sessionId
2576
- );
2577
- const result = await this.conn.send(
2578
- "DOM.querySelectorAll",
2579
- { nodeId: doc.root.nodeId, selector },
2580
- this.sessionId
2581
- );
2582
- return result.nodeIds ?? [];
3487
+ return this.domQueryService.querySelectorAll(selector);
2583
3488
  }
2584
- /** Resolve a CDP nodeId to a RemoteObject for evaluate */
2585
3489
  async resolveNode(nodeId) {
2586
- const result = await this.conn.send(
2587
- "DOM.resolveNode",
2588
- { nodeId },
2589
- this.sessionId
2590
- );
2591
- return result.object.objectId;
3490
+ return this.domQueryService.resolveNode(nodeId);
2592
3491
  }
2593
- /** Get the box model for a nodeId */
2594
3492
  async getBoxModel(nodeId) {
2595
- try {
2596
- const result = await this.conn.send("DOM.getBoxModel", { nodeId }, this.sessionId);
2597
- const c = result.model?.content;
2598
- if (!c || c.length < 8) return null;
2599
- const x1 = c[0];
2600
- const y1 = c[1];
2601
- const x2 = c[4];
2602
- const y2 = c[5];
2603
- return {
2604
- x: Math.min(x1, x2),
2605
- y: Math.min(y1, y2),
2606
- width: Math.abs(x2 - x1),
2607
- height: Math.abs(y2 - y1)
2608
- };
2609
- } catch {
2610
- return null;
2611
- }
3493
+ return this.domQueryService.getBoxModel(nodeId);
2612
3494
  }
2613
3495
  /** Call a function on a RemoteObject */
2614
3496
  async callFunctionOn(objectId, functionDeclaration, args = []) {
@@ -2627,9 +3509,6 @@ Last error: ${lastError.message}` : "";
2627
3509
  async _cdpSend(method, params) {
2628
3510
  return this.conn.send(method, params, this.sessionId);
2629
3511
  }
2630
- /** sup-s11: beforeunload 自动应答语义——'accept'(默认,离开页面,与录制
2631
- * 意图一致)或 'dismiss'(取消导航留守原页,尽力而为:此构建上 CDP
2632
- * accept:false 对浏览器侧导航的取消语义不稳定,不保证)。 */
2633
3512
  setBeforeUnloadBehavior(mode) {
2634
3513
  this._beforeUnloadAccept = mode === "accept";
2635
3514
  }
@@ -2652,143 +3531,37 @@ Last error: ${lastError.message}` : "";
2652
3531
  }
2653
3532
  // ── Private: Event Setup ────────────────────────────────────
2654
3533
  setupPageEvents() {
2655
- this._subscriptions.push(
2656
- this.conn.subscribe("Page.frameNavigated", this.sessionId, (params) => {
2657
- const p = params;
2658
- if (p.frame) {
2659
- this._url = p.frame.url;
2660
- }
2661
- this._emit("framenavigated", this.mainFrame());
2662
- })
2663
- );
2664
- this._subscriptions.push(
2665
- this.conn.subscribe("Page.loadEventFired", this.sessionId, () => {
3534
+ setupPageEvents({
3535
+ conn: this.conn,
3536
+ sessionId: this.sessionId,
3537
+ addSubscription: (unsubscribe) => this._subscriptions.push(unsubscribe),
3538
+ emit: (event, ...args) => this._emit(event, ...args),
3539
+ setUrl: (url) => {
3540
+ this._url = url;
3541
+ },
3542
+ currentUrl: () => this.url(),
3543
+ mainFrame: () => this.mainFrame(),
3544
+ markLoadFired: () => {
2666
3545
  this._loadState.loadFired = true;
2667
- })
2668
- );
2669
- this._subscriptions.push(
2670
- this.conn.subscribe("Page.domContentEventFired", this.sessionId, () => {
3546
+ },
3547
+ markDomContentFired: () => {
2671
3548
  this._loadState.domContentFired = true;
2672
- })
2673
- );
2674
- this._subscriptions.push(
2675
- this.conn.subscribe("Page.javascriptDialogOpening", this.sessionId, (params) => {
2676
- const p = params;
2677
- const dialog = {
2678
- type: p.type,
2679
- message: () => p.message,
2680
- defaultValue: () => p.defaultValue,
2681
- accept: async (text) => {
2682
- await this.conn.send("Page.handleJavaScriptDialog", {
2683
- accept: true,
2684
- promptText: text
2685
- }, this.sessionId);
2686
- },
2687
- dismiss: async () => {
2688
- await this.conn.send("Page.handleJavaScriptDialog", {
2689
- accept: false
2690
- }, this.sessionId);
2691
- }
2692
- };
2693
- this._emit("dialog", dialog);
2694
- const autoAccept = p.type === "beforeunload" ? this._beforeUnloadAccept : false;
2695
- setTimeout(() => {
2696
- this.conn.send("Page.handleJavaScriptDialog", { accept: autoAccept }, this.sessionId).catch(() => {
2697
- });
2698
- }, 0);
2699
- })
2700
- );
2701
- this._subscriptions.push(
2702
- this.conn.subscribe("Page.fileChooserOpened", this.sessionId, async (params) => {
2703
- const p = params;
2704
- let selector = "";
2705
- try {
2706
- const result = await this.conn.send("DOM.describeNode", { backendNodeId: p.backendNodeId }, this.sessionId);
2707
- const attrs = result.node?.attributes || [];
2708
- const idIdx = attrs.indexOf("id");
2709
- if (idIdx >= 0) selector = "#" + attrs[idIdx + 1];
2710
- } catch {
2711
- }
2712
- if (!selector) {
2713
- try {
2714
- const result = await this.conn.send("DOM.resolveNode", { backendNodeId: p.backendNodeId }, this.sessionId);
2715
- const evalResult = await this.conn.send("Runtime.callFunctionOn", {
2716
- objectId: result.objectId,
2717
- functionDeclaration: 'function() { return this.id || this.name || "" }',
2718
- returnByValue: true
2719
- }, this.sessionId);
2720
- if (evalResult.result?.value) selector = "#" + evalResult.result.value;
2721
- } catch {
2722
- }
2723
- }
2724
- const fileChooser = {
2725
- selector,
2726
- isMultiple: p.mode === "selectMultiple",
2727
- setFiles: async (files) => {
2728
- const fileArray = Array.isArray(files) ? files : [files];
2729
- await this.setInputFiles(selector || 'input[type="file"]', fileArray);
2730
- }
2731
- };
2732
- this._emit("filechooser", fileChooser);
2733
- })
2734
- );
2735
- }
2736
- setupNetworkEvents() {
2737
- this._subscriptions.push(
2738
- this.conn.subscribe("Network.requestWillBeSent", this.sessionId, (params) => {
2739
- const p = params;
2740
- this.inflightRequests.add(p.requestId);
2741
- this._storeNetworkRequest(p.requestId, {
2742
- url: p.request.url,
2743
- method: p.request.method,
2744
- headers: p.request.headers,
2745
- postData: p.request.postData ?? null,
2746
- resourceType: p.type
2747
- });
2748
- this._emit("request", createXBRequest(
2749
- null,
2750
- {
2751
- requestId: p.requestId,
2752
- url: p.request.url,
2753
- method: p.request.method,
2754
- headers: p.request.headers,
2755
- postData: p.request.postData ?? null,
2756
- resourceType: p.type
2757
- }
2758
- ));
2759
- this.checkNetworkIdle();
2760
- })
2761
- );
2762
- this._subscriptions.push(
2763
- this.conn.subscribe("Network.responseReceived", this.sessionId, (params) => {
2764
- const p = params;
2765
- this._storeNetworkResponse(p.requestId, {
2766
- status: p.response.status,
2767
- url: p.response.url,
2768
- headers: p.response.headers
2769
- });
2770
- this._emit("response", createXBResponse(
2771
- { requestId: p.requestId, status: p.response.status, url: p.response.url, headers: p.response.headers },
2772
- this.conn,
2773
- this.sessionId
2774
- ));
2775
- })
2776
- );
2777
- this._subscriptions.push(
2778
- this.conn.subscribe("Network.loadingFinished", this.sessionId, (params) => {
2779
- const p = params;
2780
- this.inflightRequests.delete(p.requestId);
2781
- this._emit("requestfinished", p);
2782
- this.checkNetworkIdle();
2783
- })
2784
- );
2785
- this._subscriptions.push(
2786
- this.conn.subscribe("Network.loadingFailed", this.sessionId, (params) => {
2787
- const p = params;
2788
- this.inflightRequests.delete(p.requestId);
2789
- this.checkNetworkIdle();
2790
- })
2791
- );
3549
+ },
3550
+ getBeforeUnloadAccept: () => this._beforeUnloadAccept,
3551
+ setInputFiles: (selector, files) => this.setInputFiles(selector, files)
3552
+ });
3553
+ }
3554
+ setupNetworkEvents() {
3555
+ setupNetworkEvents({
3556
+ conn: this.conn,
3557
+ sessionId: this.sessionId,
3558
+ state: { inflightRequests: this.inflightRequests },
3559
+ emit: (event, ...args) => this._emit(event, ...args),
3560
+ storeRequest: (id, data) => this._storeNetworkRequest(id, data),
3561
+ storeResponse: (id, data) => this._storeNetworkResponse(id, data),
3562
+ checkNetworkIdle: () => this.checkNetworkIdle(),
3563
+ addSubscription: (unsubscribe) => this._subscriptions.push(unsubscribe)
3564
+ });
2792
3565
  }
2793
3566
  setupConsoleEvents() {
2794
3567
  this._subscriptions.push(
@@ -2834,8 +3607,6 @@ Last error: ${lastError.message}` : "";
2834
3607
  // ── Network Data Store (for waitForResponse/waitForRequest) ──
2835
3608
  _networkResponses = /* @__PURE__ */ new Map();
2836
3609
  _networkRequests = /* @__PURE__ */ new Map();
2837
- _routeHandlers = [];
2838
- _interceptionEnabled = false;
2839
3610
  _beforeUnloadAccept = true;
2840
3611
  /** Store network data — called by browser.ts installNetworkCapture or internal event handlers */
2841
3612
  _storeNetworkRequest(requestId, data) {
@@ -2844,284 +3615,30 @@ Last error: ${lastError.message}` : "";
2844
3615
  _storeNetworkResponse(requestId, data) {
2845
3616
  this._networkResponses.set(requestId, { requestId, ...data });
2846
3617
  }
2847
- // ── waitForResponse ─────────────────────────────────────────
2848
3618
  async waitForResponse(urlOrPredicate, opts = {}) {
2849
- const timeout = opts.timeout ?? 3e4;
2850
- const predicate = createResponsePredicate(urlOrPredicate);
2851
- for (const [, data] of this._networkResponses) {
2852
- const response = createXBResponse(data, this.conn, this.sessionId);
2853
- if (predicate(response)) return response;
2854
- }
2855
- return new Promise((resolve, reject) => {
2856
- const timer = setTimeout(() => {
2857
- this._emitter.removeListener("response", handler);
2858
- reject(new Error(`waitForResponse timed out after ${timeout}ms`));
2859
- }, timeout);
2860
- const handler = (params) => {
2861
- let response;
2862
- const respObj = params;
2863
- if (respObj.response) {
2864
- const data = {
2865
- requestId: respObj.requestId || "",
2866
- status: respObj.response.status || 0,
2867
- url: respObj.response.url || "",
2868
- headers: respObj.response.headers || {}
2869
- };
2870
- response = createXBResponse(data, this.conn, this.sessionId);
2871
- } else if (typeof params.status === "function") {
2872
- response = params;
2873
- } else {
2874
- return;
2875
- }
2876
- if (predicate(response)) {
2877
- clearTimeout(timer);
2878
- this._emitter.removeListener("response", handler);
2879
- resolve(response);
2880
- }
2881
- };
2882
- this._emitter.on("response", handler);
2883
- });
3619
+ return this.networkWaitService.waitForResponse(urlOrPredicate, opts);
2884
3620
  }
2885
- // ── waitForRequest ──────────────────────────────────────────
2886
3621
  async waitForRequest(urlOrPredicate, opts = {}) {
2887
- const timeout = opts.timeout ?? 3e4;
2888
- const predicate = createRequestPredicate(urlOrPredicate);
2889
- for (const [, data] of this._networkRequests) {
2890
- const request = createXBRequest(this, data);
2891
- if (predicate(request)) return request;
2892
- }
2893
- return new Promise((resolve, reject) => {
2894
- const timer = setTimeout(() => {
2895
- this._emitter.removeListener("request", handler);
2896
- reject(new Error(`waitForRequest timed out after ${timeout}ms`));
2897
- }, timeout);
2898
- const handler = (params) => {
2899
- let request;
2900
- const reqObj = params;
2901
- if (reqObj.request) {
2902
- request = createXBRequest(this, {
2903
- requestId: reqObj.requestId || "",
2904
- url: reqObj.request.url || "",
2905
- method: reqObj.request.method || "",
2906
- headers: reqObj.request.headers || {},
2907
- postData: reqObj.request.postData ?? null,
2908
- resourceType: reqObj.type || ""
2909
- });
2910
- } else if (typeof params.url === "function") {
2911
- request = params;
2912
- } else {
2913
- return;
2914
- }
2915
- if (predicate(request)) {
2916
- clearTimeout(timer);
2917
- this._emitter.removeListener("request", handler);
2918
- resolve(request);
2919
- }
2920
- };
2921
- this._emitter.on("request", handler);
2922
- });
3622
+ return this.networkWaitService.waitForRequest(urlOrPredicate, opts);
2923
3623
  }
2924
- // ── waitForURL ──────────────────────────────────────────────
2925
3624
  async waitForURL(url, opts = {}) {
2926
- const timeout = opts.timeout ?? 3e4;
2927
- const checkFn = typeof url === "function" ? url : typeof url === "string" ? (current) => matchGlob(url, current) : (current) => url.test(current);
2928
- if (checkFn(this._url)) return;
2929
- return new Promise((resolve, reject) => {
2930
- const timer = setTimeout(() => {
2931
- this._emitter.removeListener("framenavigated", handler);
2932
- reject(new Error(`waitForURL timed out after ${timeout}ms`));
2933
- }, timeout);
2934
- const handler = () => {
2935
- if (checkFn(this._url)) {
2936
- clearTimeout(timer);
2937
- this._emitter.removeListener("framenavigated", handler);
2938
- resolve();
2939
- }
2940
- };
2941
- this._emitter.on("framenavigated", handler);
2942
- });
2943
- }
2944
- // ── route / unroute ─────────────────────────────────────────
2945
- async route(url, handler) {
2946
- const regex = typeof url === "string" ? globToRegex(url) : url;
2947
- this._routeHandlers.push({ pattern: String(url), regex, handler });
2948
- if (!this._interceptionEnabled) {
2949
- this._interceptionEnabled = true;
2950
- await this.conn.send("Fetch.enable", {
2951
- patterns: [{ urlPattern: "*", requestStage: "Request" }],
2952
- // sup-s9: 保留认证自动响应(Fetch.enable 为替换语义,不带此参数
2953
- // 会顶掉 _init 的 auth 配置)
2954
- handleAuthRequests: true
2955
- }, this.sessionId);
2956
- this._subscriptions.push(
2957
- this.conn.subscribe("Fetch.requestPaused", this.sessionId, (params) => {
2958
- this._handleRequestPaused(params);
2959
- })
2960
- );
2961
- }
3625
+ return this.networkWaitService.waitForURL(url, opts);
2962
3626
  }
2963
- async unroute(url, handler) {
2964
- const regex = typeof url === "string" ? globToRegex(url) : url;
2965
- this._routeHandlers = this._routeHandlers.filter(
2966
- (h) => !(regex.source === h.regex.source && (!handler || h.handler === handler))
2967
- );
2968
- if (this._routeHandlers.length === 0 && this._interceptionEnabled) {
2969
- this._interceptionEnabled = false;
2970
- await this.conn.send("Fetch.disable", void 0, this.sessionId).catch(() => {
2971
- });
2972
- }
3627
+ async route(pattern, handler) {
3628
+ return this.networkRouteService.route(pattern, handler);
2973
3629
  }
2974
- async _handleRequestPaused(params) {
2975
- const requestUrl = params.request.url;
2976
- for (const { regex, handler } of this._routeHandlers) {
2977
- if (regex.test(requestUrl)) {
2978
- this._emit("request", createXBRequest(
2979
- null,
2980
- {
2981
- requestId: params.requestId,
2982
- url: params.request.url,
2983
- method: params.request.method,
2984
- headers: params.request.headers,
2985
- postData: params.request.postData ?? null,
2986
- resourceType: params.resourceType
2987
- }
2988
- ));
2989
- const route = createXBRouteFetch(this.conn, this.sessionId, params, this._emitter);
2990
- try {
2991
- await handler(route);
2992
- } catch {
2993
- await this.conn.send("Fetch.continueRequest", {
2994
- requestId: params.requestId
2995
- }, this.sessionId).catch(() => {
2996
- });
2997
- }
2998
- return;
2999
- }
3000
- }
3001
- await this.conn.send("Fetch.continueRequest", {
3002
- requestId: params.requestId
3003
- }, this.sessionId).catch(() => {
3004
- });
3630
+ async unroute(pattern) {
3631
+ return this.networkRouteService.unroute(pattern);
3005
3632
  }
3006
- // ── setInputFiles ───────────────────────────────────────────
3007
- /**
3008
- * sup-s4: Dropzone 拖拽上传模拟——Dropzone/Uppy/自绘上传区只监听
3009
- * dragover/drop(无 input[type=file] 可点),真实用户靠 OS 文件拖入
3010
- * 触发,自动化无法产生 OS 拖拽。页内构造 DataTransfer+File,按拖放
3011
- * 协议派发 dragenter/dragover/drop(bubbles+cancelable,坐标取目标
3012
- * 中心)。
3013
- */
3014
3633
  async dropFiles(selector, payload) {
3015
- await this.evaluate(`
3016
- (function() {
3017
- var el = ${queryJS(selector)};
3018
- if (!el) throw new Error('drop target not found: ' + ${JSON.stringify(selector)});
3019
- var b64 = ${JSON.stringify(payload.buffer.toString("base64"))};
3020
- var bin = atob(b64);
3021
- var buf = new Uint8Array(bin.length);
3022
- for (var i = 0; i < bin.length; i++) buf[i] = bin.charCodeAt(i);
3023
- var file = new File([buf], ${JSON.stringify(payload.name)}, { type: ${JSON.stringify(payload.mimeType)} });
3024
- var dt = new DataTransfer();
3025
- dt.items.add(file);
3026
- var rect = el.getBoundingClientRect();
3027
- var opts = {
3028
- bubbles: true, cancelable: true,
3029
- clientX: rect.x + rect.width / 2, clientY: rect.y + rect.height / 2,
3030
- };
3031
- el.dispatchEvent(new DragEvent('dragenter', Object.assign({ dataTransfer: dt }, opts)));
3032
- el.dispatchEvent(new DragEvent('dragover', Object.assign({ dataTransfer: dt }, opts)));
3033
- el.dispatchEvent(new DragEvent('drop', Object.assign({ dataTransfer: dt }, opts)));
3034
- })()
3035
- `);
3634
+ return this.fileInputService.dropFiles(selector, payload);
3036
3635
  }
3037
3636
  async setInputFiles(selector, files) {
3038
- const fileArr = Array.isArray(files) ? files : [files];
3039
- const fileList = fileArr.map((f) => ({
3040
- name: f.name,
3041
- type: f.mimeType,
3042
- dataBase64: f.buffer.toString("base64")
3043
- }));
3044
- await this.evaluate(`
3045
- (function() {
3046
- var selector = ${JSON.stringify(selector)};
3047
- var input = ${queryJS(selector)};
3048
- if (!input) throw new Error('Element not found: ' + selector);
3049
-
3050
- var fileList = ${JSON.stringify(fileList)};
3051
- var dt = new DataTransfer();
3052
-
3053
- fileList.forEach(function(f) {
3054
- var binary = atob(f.dataBase64);
3055
- var bytes = new Uint8Array(binary.length);
3056
- for (var i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
3057
- var blob = new Blob([bytes], { type: f.type });
3058
- var file = new File([blob], f.name, { type: f.type });
3059
- dt.items.add(file);
3060
- });
3061
-
3062
- input.files = dt.files;
3063
- input.dispatchEvent(new Event('input', { bubbles: true }));
3064
- input.dispatchEvent(new Event('change', { bubbles: true }));
3065
- })()
3066
- `);
3637
+ return this.fileInputService.setInputFiles(selector, files);
3067
3638
  }
3068
- // ── dragAndDrop ─────────────────────────────────────────────
3069
3639
  async dragAndDrop(source, target) {
3070
- const sourceRect = await this.evaluate(`
3071
- (function() {
3072
- const el = ${queryJS(source)};
3073
- if (!el) throw new Error('Source not found: ${source}');
3074
- el.scrollIntoView({ behavior: 'instant', block: 'center' });
3075
- const r = el.getBoundingClientRect();
3076
- return { x: r.x, y: r.y, width: r.width, height: r.height };
3077
- })()
3078
- `);
3079
- const targetRect = await this.evaluate(`
3080
- (function() {
3081
- const el = ${queryJS(target)};
3082
- if (!el) throw new Error('Target not found: ${target}');
3083
- el.scrollIntoView({ behavior: 'instant', block: 'center' });
3084
- const r = el.getBoundingClientRect();
3085
- return { x: r.x, y: r.y, width: r.width, height: r.height };
3086
- })()
3087
- `);
3088
- const sx = sourceRect.x + sourceRect.width / 2;
3089
- const sy = sourceRect.y + sourceRect.height / 2;
3090
- const tx = targetRect.x + targetRect.width / 2;
3091
- const ty = targetRect.y + targetRect.height / 2;
3092
- try {
3093
- await this.conn.send("Input.dispatchDragEvent", {
3094
- type: "dragStart",
3095
- x: sx,
3096
- y: sy,
3097
- data: { items: [], dragOperations: ["copy", "move", "link"] }
3098
- }, this.sessionId);
3099
- await this.conn.send("Input.dispatchDragEvent", {
3100
- type: "dragOver",
3101
- x: tx,
3102
- y: ty,
3103
- data: { items: [], dragOperations: ["copy", "move", "link"] }
3104
- }, this.sessionId);
3105
- await this.conn.send("Input.dispatchDragEvent", {
3106
- type: "drop",
3107
- x: tx,
3108
- y: ty,
3109
- data: { items: [], dragOperations: ["copy", "move", "link"] }
3110
- }, this.sessionId);
3111
- await this.conn.send("Input.dispatchDragEvent", {
3112
- type: "dragCancel",
3113
- x: sx,
3114
- y: sy,
3115
- data: { items: [], dragOperations: ["copy", "move", "link"] }
3116
- }, this.sessionId);
3117
- } catch {
3118
- await this.mouse.move(sx, sy);
3119
- await this.mouse.down();
3120
- await this.mouse.move(tx, ty, { steps: 10 });
3121
- await this.mouse.up();
3122
- }
3640
+ return this.fileInputService.dragAndDrop(source, target);
3123
3641
  }
3124
- // ── setOfflineMode ──────────────────────────────────────────
3125
3642
  async setOfflineMode(offline) {
3126
3643
  await this.conn.send("Network.emulateNetworkConditions", {
3127
3644
  offline,
@@ -3417,12 +3934,22 @@ var XBBrowserImpl = class {
3417
3934
  this._exitHandler = null;
3418
3935
  }
3419
3936
  if (this.childProcess) {
3420
- const { killChrome: killChrome2 } = await import("./launcher-SJ44X25U.js");
3937
+ const { killChrome: killChrome2 } = await import("./launcher-TOLF23ET.js");
3421
3938
  await killChrome2(this.childProcess, this.tmpDir);
3422
3939
  }
3423
3940
  await this.conn.close();
3424
3941
  this._emitter.emit("disconnected");
3425
3942
  }
3943
+ async disconnect() {
3944
+ if (this._disconnected) return;
3945
+ this._disconnected = true;
3946
+ if (this._exitHandler) {
3947
+ process.removeListener("exit", this._exitHandler);
3948
+ this._exitHandler = null;
3949
+ }
3950
+ await this.conn.close();
3951
+ this._emitter.emit("disconnected");
3952
+ }
3426
3953
  async newContext(opts = {}) {
3427
3954
  if (this.launchOpts?.stealthConfig && !opts.stealthConfig) {
3428
3955
  opts = { ...opts, stealthConfig: this.launchOpts.stealthConfig };
@@ -3587,7 +4114,7 @@ var XBBrowserImpl = class {
3587
4114
  if (pageTargets.length === 0 && httpFallbackUrl) {
3588
4115
  console.log(`[discoverContexts] Target.getTargets returned ${targetInfos.length} targets (0 page type). Falling back to HTTP /json/list at ${httpFallbackUrl}`);
3589
4116
  try {
3590
- const { getCDPTargets: getCDPTargets2 } = await import("./launcher-SJ44X25U.js");
4117
+ const { getCDPTargets: getCDPTargets2 } = await import("./launcher-TOLF23ET.js");
3591
4118
  const httpPages = await getCDPTargets2(httpFallbackUrl);
3592
4119
  console.log(`[discoverContexts] HTTP /json/list returned ${httpPages.length} pages`);
3593
4120
  for (const p of httpPages) {
@@ -4033,6 +4560,149 @@ Or add random variation: page.type(selector, text, {delay: 50 + Math.random() *
4033
4560
  return null;
4034
4561
  }
4035
4562
 
4563
+ // src/cdp-interceptor/rules/humanize-transform.ts
4564
+ var CURSOR_KEY = "humanize-cursor";
4565
+ var KEYS_KEY = "humanize-keys";
4566
+ var MOUSE_STEP_DELAYS = [16, 19, 23, 28];
4567
+ var TYPE_DELAYS = [42, 58, 74, 96, 118, 155, 210];
4568
+ function rand2(min, max) {
4569
+ return min + Math.random() * (max - min);
4570
+ }
4571
+ function roundCoordinate(value) {
4572
+ return Math.round(value * 100) / 100;
4573
+ }
4574
+ function humanMousePath(fromX, fromY, toX, toY) {
4575
+ const dist = Math.hypot(toX - fromX, toY - fromY);
4576
+ const n = Math.max(8, Math.min(28, Math.round(dist / 15)));
4577
+ const shortMove = dist < 120;
4578
+ const curvature = shortMove ? rand2(2, 6) : Math.max(dist * rand2(0.12, 0.22), rand2(18, 35));
4579
+ const dir = Math.random() < 0.5 ? 1 : -1;
4580
+ const dx = toX - fromX;
4581
+ const dy = toY - fromY;
4582
+ const d = dist || 1;
4583
+ const c1x = fromX + dx * 0.3 - dy / d * curvature * 0.5 * dir;
4584
+ const c1y = fromY + dy * 0.3 + dx / d * curvature * 0.5 * dir;
4585
+ const c2x = fromX + dx * 0.7 - dy / d * curvature * 0.8 * dir;
4586
+ const c2y = fromY + dy * 0.7 + dx / d * curvature * 0.8 * dir;
4587
+ const amp = shortMove ? Math.min(2, 3.2) : 3.2;
4588
+ const points = [];
4589
+ for (let i = 1; i <= n; i++) {
4590
+ const t = i / n;
4591
+ const eased = t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2;
4592
+ const mt = 1 - eased;
4593
+ const px = mt ** 3 * fromX + 3 * mt ** 2 * eased * c1x + 3 * mt * eased ** 2 * c2x + eased ** 3 * toX;
4594
+ const py = mt ** 3 * fromY + 3 * mt ** 2 * eased * c1y + 3 * mt * eased ** 2 * c2y + eased ** 3 * toY;
4595
+ points.push({
4596
+ x: roundCoordinate(px + rand2(-amp, amp)),
4597
+ y: roundCoordinate(py + rand2(-amp, amp)),
4598
+ delay: MOUSE_STEP_DELAYS[Math.floor(Math.random() * MOUSE_STEP_DELAYS.length)]
4599
+ });
4600
+ }
4601
+ if (!shortMove) {
4602
+ const over = rand2(6, 14);
4603
+ points.push({
4604
+ x: roundCoordinate(toX + dx / d * over + rand2(-2, 2)),
4605
+ y: roundCoordinate(toY + dy / d * over + rand2(-2, 2)),
4606
+ delay: Math.round(rand2(14, 30))
4607
+ });
4608
+ points.push({
4609
+ x: roundCoordinate(toX + dx / d * over * 0.4),
4610
+ y: roundCoordinate(toY + dy / d * over * 0.4),
4611
+ delay: Math.round(rand2(14, 30))
4612
+ });
4613
+ }
4614
+ points.push({
4615
+ x: roundCoordinate(toX + rand2(-1, 1)),
4616
+ y: roundCoordinate(toY + rand2(-1, 1)),
4617
+ delay: Math.round(rand2(14, 30))
4618
+ });
4619
+ return points;
4620
+ }
4621
+ function characterKeyEvents(text) {
4622
+ const events = [];
4623
+ for (const char of text) {
4624
+ if (char === "\n") {
4625
+ events.push(
4626
+ { type: "rawKeyDown", key: "Enter", code: "Enter", windowsVirtualKeyCode: 13 },
4627
+ { type: "char", text: "\r" },
4628
+ { type: "keyUp", key: "Enter", code: "Enter", windowsVirtualKeyCode: 13 }
4629
+ );
4630
+ continue;
4631
+ }
4632
+ events.push(
4633
+ { type: "rawKeyDown", key: char, text: char, unmodifiedText: char },
4634
+ { type: "char", text: char },
4635
+ { type: "keyUp", key: char }
4636
+ );
4637
+ }
4638
+ return events;
4639
+ }
4640
+ function isMouseEvent(method) {
4641
+ return method === "Input.dispatchMouseEvent";
4642
+ }
4643
+ var humanizeTransformRule = {
4644
+ id: "humanize-transform",
4645
+ name: "Humanize Trusted Input Transform",
4646
+ priority: 45,
4647
+ canHandle(ctx) {
4648
+ return isMouseEvent(ctx.method) || ctx.method === "Input.insertText";
4649
+ },
4650
+ evaluate(ctx) {
4651
+ if (ctx.method === "Input.insertText") return this.transformInsertText(ctx);
4652
+ return this.transformMouseEvent(ctx);
4653
+ },
4654
+ transformMouseEvent(ctx) {
4655
+ const params = ctx.params;
4656
+ if (params.type !== "mouseMoved" || typeof params.x !== "number" || typeof params.y !== "number") {
4657
+ const x = params.x;
4658
+ const y = params.y;
4659
+ if (typeof x === "number" && typeof y === "number") {
4660
+ ctx.sessionState.set(CURSOR_KEY, { x, y });
4661
+ }
4662
+ return null;
4663
+ }
4664
+ const cursor = ctx.sessionState.get(CURSOR_KEY) ?? { x: 0, y: 0 };
4665
+ const jump = Math.hypot(params.x - cursor.x, params.y - cursor.y);
4666
+ ctx.sessionState.set(CURSOR_KEY, { x: params.x, y: params.y });
4667
+ if (jump < 32) return null;
4668
+ const path = humanMousePath(cursor.x, cursor.y, params.x, params.y);
4669
+ return {
4670
+ ruleId: this.id,
4671
+ action: "transform",
4672
+ severity: "info",
4673
+ reason: `Expanded instant mouse jump of ${jump.toFixed(0)}px into ${path.length} trusted bezier moves.`,
4674
+ suggestion: "Use page.mouse.move with steps for explicit control; this transform preserves isTrusted=true.",
4675
+ transformedParams: { __sequence: path.map((point) => ({
4676
+ method: "Input.dispatchMouseEvent",
4677
+ params: { type: "mouseMoved", x: point.x, y: point.y, button: params.button ?? "none" },
4678
+ delayMs: point.delay
4679
+ })) }
4680
+ };
4681
+ },
4682
+ transformInsertText(ctx) {
4683
+ const params = ctx.params;
4684
+ const text = params.text ?? "";
4685
+ if (!text) return null;
4686
+ const timing = ctx.sessionState.get(KEYS_KEY) ?? { lastDelay: TYPE_DELAYS[1] };
4687
+ const bucket = TYPE_DELAYS[Math.floor(Math.random() * TYPE_DELAYS.length)];
4688
+ const events = characterKeyEvents(text).map((event, index) => ({
4689
+ method: "Input.dispatchKeyEvent",
4690
+ params: event,
4691
+ delayMs: index === 0 ? 0 : Math.max(24, Math.round(bucket + rand2(-bucket * 0.45, bucket * 0.55)))
4692
+ }));
4693
+ timing.lastDelay = bucket;
4694
+ ctx.sessionState.set(KEYS_KEY, timing);
4695
+ return {
4696
+ ruleId: this.id,
4697
+ action: "transform",
4698
+ severity: "info",
4699
+ reason: `Expanded Input.insertText (${text.length} chars) into ${events.length} trusted key events with variable rhythm.`,
4700
+ suggestion: "Use page.type for explicit control; this transform preserves the native keyboard command stream.",
4701
+ transformedParams: { __sequence: events }
4702
+ };
4703
+ }
4704
+ };
4705
+
4036
4706
  // src/cdp-interceptor/rules/automation-signals.ts
4037
4707
  var AUTOMATION_PATTERNS = [
4038
4708
  // ── Playwright markers ─────────────────────────
@@ -4551,6 +5221,7 @@ var BUILTIN_RULES = [
4551
5221
  eventSimulationRule,
4552
5222
  mouseTrajectoryRule,
4553
5223
  inputKeystrokeRule,
5224
+ humanizeTransformRule,
4554
5225
  emulationOverrideRule,
4555
5226
  networkAnomalyRule,
4556
5227
  pageLifecycleRule
@@ -4583,8 +5254,10 @@ function createRuleEngine(customRules) {
4583
5254
  if (isProbeMarked(code)) return null;
4584
5255
  } catch {
4585
5256
  }
5257
+ const humanizeEnabled = process.env.XBROWSER_HUMANIZE_CDP === "on";
4586
5258
  for (const rule of rules) {
4587
5259
  if (rule.canHandle && !rule.canHandle(fullCtx)) continue;
5260
+ if (rule.id === "humanize-transform" && !humanizeEnabled) continue;
4588
5261
  const decision = rule.evaluate(fullCtx);
4589
5262
  if (!decision) continue;
4590
5263
  if (decision.action !== "pass") return decision;
@@ -4726,6 +5399,15 @@ var CDPConnection = class _CDPConnection extends EventEmitter4 {
4726
5399
  if (decision && decision.action === "block") {
4727
5400
  throw new Error(`[CDP-Guard] ${decision.reason}${decision.suggestion ? " | \u66FF\u4EE3: " + decision.suggestion : ""} [${decision.ruleId}]`);
4728
5401
  }
5402
+ if (decision && decision.action === "transform" && Array.isArray(decision.transformedParams?.__sequence)) {
5403
+ const sequence = decision.transformedParams.__sequence;
5404
+ let last;
5405
+ for (const step of sequence) {
5406
+ if (step.delayMs) await new Promise((resolve) => setTimeout(resolve, step.delayMs));
5407
+ last = await this.send(step.method, step.params, sessionId, effectiveTimeout);
5408
+ }
5409
+ return last;
5410
+ }
4729
5411
  }
4730
5412
  if (this.closed) {
4731
5413
  throw new Error(`CDP connection closed: ${this.closeReason ?? "unknown"}`);
@@ -4968,7 +5650,7 @@ async function launch(options = {}) {
4968
5650
  const bv = await conn.send("Browser.getVersion");
4969
5651
  const m = bv.product.match(/(\d+)\.(\d+)\.(\d+)\.(\d+)/);
4970
5652
  if (m && !options.stealthConfig?.uaChProfile) {
4971
- const { deriveUaChProfileForBinary } = await import("./stealth-QNSMIHQK.js");
5653
+ const { deriveUaChProfileForBinary } = await import("./stealth-FMPZO2OB.js");
4972
5654
  stealthOpts = { stealthConfig: { uaChProfile: deriveUaChProfileForBinary(m[0], m[1]) } };
4973
5655
  }
4974
5656
  } catch {