@xbrowser/cli 1.10.0 → 1.11.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 (27) hide show
  1. package/dist/{anti-bot-DR56Y63V.js → anti-bot-GTTYNEFB.js} +1 -1
  2. package/dist/{browser-T3V3JWVH.js → browser-Q5APBNF6.js} +1 -1
  3. package/dist/{browser-HBL72GPZ.js → browser-V3JIWSTR.js} +2 -2
  4. package/dist/{browser-WQZ3D6AE.js → browser-XNU7JQYC.js} +3 -2
  5. package/dist/{cdp-driver-J3YQ4LJV.js → cdp-driver-GD6YBBGE.js} +1 -1
  6. package/dist/cdp-driver-VEK6BNN6.js +49 -0
  7. package/dist/{cdp-driver-2T4P4ZE2.js → cdp-driver-XFTTZI5O.js} +436 -56
  8. package/dist/chunk-3FWLW7FS.js +106 -0
  9. package/dist/chunk-7OFM755Z.js +3509 -0
  10. package/dist/{chunk-5UGR6MUK.js → chunk-HBHOKZPN.js} +51 -16
  11. package/dist/{chunk-BAHSRZIX.js → chunk-HVPUVVSA.js} +13 -10
  12. package/dist/{chunk-NITFVWWS.js → chunk-JEDP4PJW.js} +448 -65
  13. package/dist/{chunk-INTQPBYF.js → chunk-JKVUFP3G.js} +6 -2
  14. package/dist/{chunk-4452SPFI.js → chunk-NODRQGOK.js} +51 -16
  15. package/dist/{chunk-YMUSHPU4.js → chunk-WHPBNUKB.js} +35 -1
  16. package/dist/{chunk-WSCP7QCJ.js → chunk-XKQVUFUS.js} +13 -10
  17. package/dist/{chunk-RRBXV7KE.js → chunk-XQ4HRPDJ.js} +384 -102
  18. package/dist/cli.js +72 -26
  19. package/dist/{daemon-client-GKEPT4NY.js → daemon-client-MMDRYCF5.js} +35 -1
  20. package/dist/{daemon-client-O6BYVRXV.js → daemon-client-Y2YSZCGK.js} +1 -1
  21. package/dist/daemon-main.js +89 -31
  22. package/dist/index.d.ts +8 -0
  23. package/dist/index.js +73 -27
  24. package/dist/{session-recorder-H3KEYU26.js → session-recorder-3BEVWHOK.js} +1 -1
  25. package/dist/{session-recorder-QRZMKFVL.js → session-recorder-SLDBENVF.js} +1 -1
  26. package/dist/{session-replayer-LJUC4TI7.js → session-replayer-WIUYVN5J.js} +90 -2
  27. package/package.json +1 -1
@@ -0,0 +1,3509 @@
1
+ import {
2
+ connectToCDP,
3
+ launchChrome
4
+ } from "./chunk-TNEN6VQ2.js";
5
+ import {
6
+ errMsg
7
+ } from "./chunk-GDKLH7ZY.js";
8
+ import {
9
+ __require
10
+ } from "./chunk-KFQGP6VL.js";
11
+
12
+ // src/cdp-driver/browser.ts
13
+ import { EventEmitter as EventEmitter3 } from "events";
14
+
15
+ // src/cdp-driver/context.ts
16
+ import { EventEmitter as EventEmitter2 } from "events";
17
+
18
+ // src/cdp-driver/page.ts
19
+ import { EventEmitter } from "events";
20
+
21
+ // src/cdp-driver/stealth.ts
22
+ var DEFAULT_STEALTH_CONFIG = {
23
+ bezierCurvature: [0.35, 0.6],
24
+ noiseAmplitude: 5.5,
25
+ overshootRange: [6, 14],
26
+ aimPause: [150, 400],
27
+ pressDuration: [60, 140],
28
+ releaseDrift: [0.8, 2.5],
29
+ landingOffsetSmall: [0.3, 2.5],
30
+ landingOffsetLarge: [1.5, 7],
31
+ smallElementThreshold: 30,
32
+ typingRhythm: {
33
+ fastProb: 0.22,
34
+ fastRange: [25, 60],
35
+ normalRange: [50, 350],
36
+ pauseProb: 0.18,
37
+ pauseRange: [400, 1200]
38
+ },
39
+ keyPressDuration: [50, 110],
40
+ typoProbability: 0.06,
41
+ wheelPeak: 180,
42
+ wheelDecayRate: 0.4
43
+ };
44
+ function rand(min, max) {
45
+ return min + Math.random() * (max - min);
46
+ }
47
+ function cosineEase(t) {
48
+ return 0.5 - 0.5 * Math.cos(Math.PI * t);
49
+ }
50
+ function bezierTrajectory(x0, y0, x1, y1, config = DEFAULT_STEALTH_CONFIG) {
51
+ const dist = Math.hypot(x1 - x0, y1 - y0);
52
+ const n = Math.max(10, Math.min(28, Math.round(dist / 15)));
53
+ const shortMove = dist < 120;
54
+ const curvature = shortMove ? rand(2, 6) : Math.max(dist * rand(...config.bezierCurvature), rand(18, 35));
55
+ const dir = Math.random() < 0.5 ? 1 : -1;
56
+ const d = dist || 1;
57
+ const dx = x1 - x0, dy = y1 - y0;
58
+ const c1x = x0 + dx * 0.3 - dy / d * curvature * 0.5 * dir;
59
+ const c1y = y0 + dy * 0.3 + dx / d * curvature * 0.5 * dir;
60
+ const c2x = x0 + dx * 0.7 - dy / d * curvature * 0.8 * dir;
61
+ const c2y = y0 + dy * 0.7 + dx / d * curvature * 0.8 * dir;
62
+ const points = [];
63
+ for (let i = 1; i <= n; i++) {
64
+ const t = cosineEase(i / n);
65
+ const mt = 1 - t;
66
+ let px = mt ** 3 * x0 + 3 * mt ** 2 * t * c1x + 3 * mt * t ** 2 * c2x + t ** 3 * x1;
67
+ let py = mt ** 3 * y0 + 3 * mt ** 2 * t * c1y + 3 * mt * t ** 2 * c2y + t ** 3 * y1;
68
+ const amp = shortMove ? Math.min(2, config.noiseAmplitude) : config.noiseAmplitude;
69
+ px += rand(-amp, amp);
70
+ py += rand(-amp, amp);
71
+ points.push({ x: px, y: py, delay: rand(9, 16) });
72
+ }
73
+ if (!shortMove) {
74
+ const over = rand(...config.overshootRange);
75
+ const ox = x1 + dx / d * over + rand(-2, 2);
76
+ const oy = y1 + dy / d * over + rand(-2, 2);
77
+ points.push({ x: ox, y: oy, delay: rand(14, 30) });
78
+ points.push({
79
+ x: x1 + dx / d * over * 0.4,
80
+ y: y1 + dy / d * over * 0.4,
81
+ delay: rand(14, 30)
82
+ });
83
+ }
84
+ points.push({ x: x1 + rand(-1, 1), y: y1 + rand(-1, 1), delay: rand(14, 30) });
85
+ return points;
86
+ }
87
+ function landingOffset(width, height, config = DEFAULT_STEALTH_CONFIG) {
88
+ const isSmall = Math.min(width, height) < config.smallElementThreshold;
89
+ const range = isSmall ? config.landingOffsetSmall : config.landingOffsetLarge;
90
+ const dx = rand(...range) * (Math.random() < 0.5 ? -1 : 1);
91
+ const dy = rand(...range) * (Math.random() < 0.5 ? -1 : 1);
92
+ return { dx, dy };
93
+ }
94
+ var KEY_MAP = {};
95
+ for (let i = 97; i <= 122; i++) {
96
+ const ch = String.fromCharCode(i);
97
+ KEY_MAP[ch] = { key: ch, code: "Key" + ch.toUpperCase(), vk: i - 32 };
98
+ }
99
+ for (let i = 65; i <= 90; i++) {
100
+ const ch = String.fromCharCode(i);
101
+ KEY_MAP[ch] = { key: ch, code: "Key" + ch, vk: i, shift: true };
102
+ }
103
+ for (let i = 48; i <= 57; i++) {
104
+ const ch = String.fromCharCode(i);
105
+ KEY_MAP[ch] = { key: ch, code: "Digit" + ch, vk: i };
106
+ }
107
+ Object.assign(KEY_MAP, {
108
+ " ": { key: " ", code: "Space", vk: 32 },
109
+ ".": { key: ".", code: "Period", vk: 190 },
110
+ "-": { key: "-", code: "Minus", vk: 189 },
111
+ "@": { key: "@", code: "Digit2", vk: 50, shift: true },
112
+ "_": { key: "_", code: "Minus", vk: 189, shift: true }
113
+ });
114
+ function buildStealthInitScript() {
115
+ return [
116
+ "(function(){",
117
+ // 1. AEL event proxy
118
+ " var o=EventTarget.prototype.addEventListener;",
119
+ " var fc=new InputDeviceCapabilities({firesTouchEvents:false});",
120
+ " var _ael=function(t,f){",
121
+ " var op=arguments[2];",
122
+ ' if(typeof f!=="function")return o.call(this,t,f,op);',
123
+ " var w=function(e){",
124
+ " if(!e||e.constructor===FocusEvent||e.constructor===KeyboardEvent)return f.call(this,e);",
125
+ " return f.call(this,new Proxy(e,{get:function(k,p){",
126
+ ' if(p==="sourceCapabilities")return fc;',
127
+ ' if(p==="isTrusted")return true;',
128
+ ' if((p==="clientX"||p==="clientY")&&k.type==="click"&&Number.isFinite(k[p])){',
129
+ " var _f=((k.timeStamp||Date.now())%89)/89*0.7+0.15;",
130
+ " return k[p]+_f;",
131
+ " }",
132
+ ' var v=Reflect.get(k,p);return typeof v==="function"?v.bind(k):v;',
133
+ " }}));",
134
+ " };",
135
+ " return o.call(this,t,w,op);",
136
+ " };",
137
+ " EventTarget.prototype.addEventListener=_ael;",
138
+ // 2. Screen override (prototype-level, not instance-level)
139
+ " var _gw=function(){return 1728};",
140
+ " var _gh=function(){return 1117};",
141
+ " var _gah=function(){return 1092};",
142
+ ' Object.defineProperty(Screen.prototype,"width",{get:_gw,configurable:true});',
143
+ ' Object.defineProperty(Screen.prototype,"height",{get:_gh,configurable:true});',
144
+ ' Object.defineProperty(Screen.prototype,"availWidth",{get:_gw,configurable:true});',
145
+ ' Object.defineProperty(Screen.prototype,"availHeight",{get:_gah,configurable:true});',
146
+ " document.hasFocus=function(){return true};",
147
+ // 3. toString disguise (name-list based)
148
+ " var _ts=Function.prototype.toString;",
149
+ " var _hf=document.hasFocus;",
150
+ " Function.prototype.toString=function(){",
151
+ ' if(this===_ael)return"function addEventListener(type, callback) { [native code] }";',
152
+ ' if(this===_hf)return"function hasFocus() { [native code] }";',
153
+ ' if(this===_gw)return"function get width() { [native code] }";',
154
+ ' if(this===_gh)return"function get height() { [native code] }";',
155
+ ' if(this===_gah)return"function get availHeight() { [native code] }";',
156
+ " return _ts.call(this);",
157
+ " };",
158
+ // 4. onclick prototype hijack (dual-stream consistency)
159
+ " var _ba=function(k,p){",
160
+ ' if(p==="isTrusted")return true;',
161
+ ' if((p==="clientX"||p==="clientY")&&k.type==="click"&&Number.isFinite(k[p])){',
162
+ " var _f=((k.timeStamp||Date.now())%89)/89*0.7+0.15;return k[p]+_f;",
163
+ " }",
164
+ ' var v=Reflect.get(k,p);return typeof v==="function"?v.bind(k):v;',
165
+ " };",
166
+ ' Object.defineProperty(Document.prototype,"onclick",{',
167
+ " configurable:true,",
168
+ " get:function(){var raw=this.__ocRaw||null;if(!raw)return null;var self=this;",
169
+ " return function(e){return raw.call(self,new Proxy(e,{get:function(k,p){return _ba(k,p)}}))}},",
170
+ " set:function(fn){this.__ocRaw=fn}",
171
+ " });",
172
+ "})()"
173
+ ].join("\n");
174
+ }
175
+
176
+ // src/cdp-driver/mouse.ts
177
+ var XBMouseImpl = class {
178
+ conn;
179
+ sessionId;
180
+ _x = 0;
181
+ _y = 0;
182
+ _button = "none";
183
+ constructor(conn, sessionId) {
184
+ this.conn = conn;
185
+ this.sessionId = sessionId;
186
+ }
187
+ /** Current cursor X position */
188
+ get x() {
189
+ return this._x;
190
+ }
191
+ /** Current cursor Y position */
192
+ get y() {
193
+ return this._y;
194
+ }
195
+ async click(x, y, opts = {}) {
196
+ const button = opts.button ?? "left";
197
+ const stealth = opts.stealth ?? true;
198
+ let tx = x, ty = y;
199
+ if (stealth && opts.elementWidth !== void 0 && opts.elementHeight !== void 0) {
200
+ const off = landingOffset(opts.elementWidth, opts.elementHeight);
201
+ tx += off.dx;
202
+ ty += off.dy;
203
+ }
204
+ if (stealth) {
205
+ const traj = bezierTrajectory(this._x, this._y, tx, ty);
206
+ for (const p of traj) {
207
+ await this.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: p.x, y: p.y, button: this._button });
208
+ this._x = p.x;
209
+ this._y = p.y;
210
+ await sleep(p.delay);
211
+ }
212
+ await sleep(rand(...DEFAULT_STEALTH_CONFIG.aimPause));
213
+ } else {
214
+ await this.move(tx, ty);
215
+ }
216
+ await this.down({ button });
217
+ await sleep(stealth ? rand(...DEFAULT_STEALTH_CONFIG.pressDuration) : opts.delay ?? 0);
218
+ const rx = stealth ? this._x + rand(...DEFAULT_STEALTH_CONFIG.releaseDrift) * (Math.random() < 0.5 ? -1 : 1) : this._x;
219
+ const ry = stealth ? this._y + rand(...DEFAULT_STEALTH_CONFIG.releaseDrift) * (Math.random() < 0.5 ? -1 : 1) : this._y;
220
+ this._x = rx;
221
+ this._y = ry;
222
+ await this.send("Input.dispatchMouseEvent", { type: "mouseReleased", x: rx, y: ry, button, clickCount: opts.clickCount ?? 1 });
223
+ for (let i = 1; i < (opts.clickCount ?? 1); i++) {
224
+ if (opts.delay) await sleep(opts.delay);
225
+ await this.down({ button });
226
+ await this.up({ button });
227
+ }
228
+ }
229
+ async dblclick(x, y, opts = {}) {
230
+ await this.click(x, y, { clickCount: 2, button: opts.button });
231
+ }
232
+ async down(opts = {}) {
233
+ const button = opts.button ?? "left";
234
+ this._button = button;
235
+ await this.send("Input.dispatchMouseEvent", {
236
+ type: "mousePressed",
237
+ x: this._x,
238
+ y: this._y,
239
+ button,
240
+ clickCount: 1
241
+ });
242
+ }
243
+ async up(opts = {}) {
244
+ const button = opts.button ?? "left";
245
+ this._button = "none";
246
+ await this.send("Input.dispatchMouseEvent", {
247
+ type: "mouseReleased",
248
+ x: this._x,
249
+ y: this._y,
250
+ button,
251
+ clickCount: 1
252
+ });
253
+ }
254
+ async move(x, y, opts = {}) {
255
+ const steps = Math.max(1, opts.steps ?? 1);
256
+ const fromX = this._x;
257
+ const fromY = this._y;
258
+ const dx = x - fromX;
259
+ const dy = y - fromY;
260
+ for (let i = 1; i <= steps; i++) {
261
+ const t = i / steps;
262
+ this._x = fromX + dx * t;
263
+ this._y = fromY + dy * t;
264
+ await this.send("Input.dispatchMouseEvent", {
265
+ type: "mouseMoved",
266
+ x: this._x,
267
+ y: this._y,
268
+ button: this._button
269
+ });
270
+ }
271
+ this._x = x;
272
+ this._y = y;
273
+ }
274
+ async wheel(deltaX, deltaY) {
275
+ await this.send("Input.dispatchMouseEvent", {
276
+ type: "mouseWheel",
277
+ x: this._x,
278
+ y: this._y,
279
+ deltaX,
280
+ deltaY
281
+ });
282
+ }
283
+ async send(method, params) {
284
+ await this.conn.send(method, params, this.sessionId);
285
+ }
286
+ };
287
+ function sleep(ms) {
288
+ return new Promise((resolve) => setTimeout(resolve, ms));
289
+ }
290
+
291
+ // src/cdp-driver/keyboard.ts
292
+ var XBKeyboardImpl = class {
293
+ conn;
294
+ sessionId;
295
+ constructor(conn, sessionId) {
296
+ this.conn = conn;
297
+ this.sessionId = sessionId;
298
+ }
299
+ async press(key, opts = {}) {
300
+ const delay = opts.delay ?? 0;
301
+ const mapping = resolveKeyMapping(key);
302
+ const downParams = {
303
+ type: "rawKeyDown",
304
+ key: mapping.key,
305
+ code: mapping.code
306
+ };
307
+ if (mapping.text) {
308
+ downParams.text = mapping.text;
309
+ downParams.unmodifiedText = mapping.text;
310
+ }
311
+ if (mapping.keyCode) {
312
+ downParams.windowsVirtualKeyCode = mapping.keyCode;
313
+ }
314
+ await this.dispatchKeyEvent(downParams);
315
+ if (mapping.text) {
316
+ await this.dispatchKeyEvent({
317
+ type: "char",
318
+ text: mapping.text
319
+ });
320
+ }
321
+ if (delay > 0) await sleep2(delay);
322
+ const upParams = {
323
+ type: "keyUp",
324
+ key: mapping.key,
325
+ code: mapping.code
326
+ };
327
+ if (mapping.keyCode) {
328
+ upParams.windowsVirtualKeyCode = mapping.keyCode;
329
+ }
330
+ await this.dispatchKeyEvent(upParams);
331
+ }
332
+ async down(key) {
333
+ const mapping = resolveKeyMapping(key);
334
+ const params = {
335
+ type: "rawKeyDown",
336
+ key: mapping.key,
337
+ code: mapping.code
338
+ };
339
+ if (mapping.text) {
340
+ params.text = mapping.text;
341
+ params.unmodifiedText = mapping.text;
342
+ }
343
+ if (mapping.keyCode) {
344
+ params.windowsVirtualKeyCode = mapping.keyCode;
345
+ }
346
+ await this.dispatchKeyEvent(params);
347
+ }
348
+ async up(key) {
349
+ const mapping = resolveKeyMapping(key);
350
+ const params = {
351
+ type: "keyUp",
352
+ key: mapping.key,
353
+ code: mapping.code
354
+ };
355
+ if (mapping.keyCode) {
356
+ params.windowsVirtualKeyCode = mapping.keyCode;
357
+ }
358
+ await this.dispatchKeyEvent(params);
359
+ }
360
+ async type(text, opts = {}) {
361
+ const delay = opts.delay ?? 0;
362
+ for (const char of text) {
363
+ if (delay > 0) await sleep2(delay);
364
+ const mapping = resolveKeyMapping(char);
365
+ const downParams = {
366
+ type: "rawKeyDown",
367
+ key: mapping.key,
368
+ code: mapping.code
369
+ };
370
+ if (mapping.text) {
371
+ downParams.text = mapping.text;
372
+ downParams.unmodifiedText = mapping.text;
373
+ }
374
+ if (mapping.keyCode) {
375
+ downParams.windowsVirtualKeyCode = mapping.keyCode;
376
+ }
377
+ await this.dispatchKeyEvent(downParams);
378
+ if (mapping.text) {
379
+ await this.dispatchKeyEvent({
380
+ type: "char",
381
+ text: mapping.text
382
+ });
383
+ }
384
+ await this.dispatchKeyEvent({
385
+ type: "keyUp",
386
+ key: mapping.key,
387
+ code: mapping.code,
388
+ ...mapping.keyCode ? { windowsVirtualKeyCode: mapping.keyCode } : {}
389
+ });
390
+ }
391
+ }
392
+ async insertText(text) {
393
+ await this.conn.send(
394
+ "Input.insertText",
395
+ { text },
396
+ this.sessionId
397
+ );
398
+ }
399
+ async dispatchKeyEvent(params) {
400
+ await this.conn.send("Input.dispatchKeyEvent", params, this.sessionId);
401
+ }
402
+ };
403
+ function resolveKeyMapping(key) {
404
+ if (KEY_MAP2[key]) return KEY_MAP2[key];
405
+ if (key.length === 1) {
406
+ const lower = key.toLowerCase();
407
+ if (lower >= "a" && lower <= "z") {
408
+ const code = `Key${lower.toUpperCase()}`;
409
+ const keyCode = lower.charCodeAt(0) - 32;
410
+ return { key, code, text: key, keyCode };
411
+ }
412
+ if (key >= "0" && key <= "9") {
413
+ const code = `Digit${key}`;
414
+ const keyCode = key.charCodeAt(0);
415
+ return { key, code, text: key, keyCode };
416
+ }
417
+ return { key, code: key, text: key };
418
+ }
419
+ return { key, code: key };
420
+ }
421
+ var KEY_MAP2 = {
422
+ Enter: { key: "Enter", code: "Enter", text: "\r", keyCode: 13 },
423
+ Tab: { key: "Tab", code: "Tab", text: " ", keyCode: 9 },
424
+ Escape: { key: "Escape", code: "Escape", keyCode: 27 },
425
+ Backspace: { key: "Backspace", code: "Backspace", keyCode: 8 },
426
+ Delete: { key: "Delete", code: "Delete", keyCode: 46 },
427
+ Space: { key: " ", code: "Space", text: " ", keyCode: 32 },
428
+ ArrowUp: { key: "ArrowUp", code: "ArrowUp", keyCode: 38 },
429
+ ArrowDown: { key: "ArrowDown", code: "ArrowDown", keyCode: 40 },
430
+ ArrowLeft: { key: "ArrowLeft", code: "ArrowLeft", keyCode: 37 },
431
+ ArrowRight: { key: "ArrowRight", code: "ArrowRight", keyCode: 39 },
432
+ Home: { key: "Home", code: "Home", keyCode: 36 },
433
+ End: { key: "End", code: "End", keyCode: 35 },
434
+ PageUp: { key: "PageUp", code: "PageUp", keyCode: 33 },
435
+ PageDown: { key: "PageDown", code: "PageDown", keyCode: 34 },
436
+ Control: { key: "Control", code: "ControlLeft", keyCode: 17 },
437
+ Shift: { key: "Shift", code: "ShiftLeft", keyCode: 16 },
438
+ Alt: { key: "Alt", code: "AltLeft", keyCode: 18 },
439
+ Meta: { key: "Meta", code: "MetaLeft", keyCode: 91 },
440
+ F1: { key: "F1", code: "F1", keyCode: 112 },
441
+ F2: { key: "F2", code: "F2", keyCode: 113 },
442
+ F3: { key: "F3", code: "F3", keyCode: 114 },
443
+ F4: { key: "F4", code: "F4", keyCode: 115 },
444
+ F5: { key: "F5", code: "F5", keyCode: 116 },
445
+ F6: { key: "F6", code: "F6", keyCode: 117 },
446
+ F7: { key: "F7", code: "F7", keyCode: 118 },
447
+ F8: { key: "F8", code: "F8", keyCode: 119 },
448
+ F9: { key: "F9", code: "F9", keyCode: 120 },
449
+ F10: { key: "F10", code: "F10", keyCode: 121 },
450
+ F11: { key: "F11", code: "F11", keyCode: 122 },
451
+ F12: { key: "F12", code: "F12", keyCode: 123 }
452
+ };
453
+ function sleep2(ms) {
454
+ return new Promise((resolve) => setTimeout(resolve, ms));
455
+ }
456
+
457
+ // src/cdp-driver/selector-utils.ts
458
+ function queryJS(selector) {
459
+ return `(${deepQueryIIFE})( ${JSON.stringify(queryMainJS(selector))} )`;
460
+ }
461
+ var deepQueryIIFE = `(function(mainExpr) {
462
+ const run = (root) => {
463
+ try { return new Function('document', 'return (' + mainExpr + ')')(root); }
464
+ catch (e) { return null; }
465
+ };
466
+ const scanRoot = (root) => {
467
+ const direct = run(root);
468
+ if (direct) return direct;
469
+ let all;
470
+ try { all = root.querySelectorAll('*'); } catch (e) { return null; }
471
+ for (const el of all) {
472
+ if (el.shadowRoot) {
473
+ const r = scanRoot(el.shadowRoot);
474
+ if (r) return r;
475
+ }
476
+ if (el.tagName === 'IFRAME') {
477
+ let inner = null;
478
+ try { inner = el.contentDocument; } catch (e) { /* cross-origin */ }
479
+ if (inner) {
480
+ const r = scanRoot(inner);
481
+ if (r) return r;
482
+ }
483
+ }
484
+ }
485
+ return null;
486
+ };
487
+ return scanRoot(document);
488
+ })`;
489
+ function queryMainJS(selector) {
490
+ if (selector.startsWith("xpath=")) {
491
+ const xpath = JSON.stringify(selector.slice(6));
492
+ return `document.evaluate(${xpath}, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue`;
493
+ }
494
+ if (selector.startsWith("text=")) {
495
+ const raw = selector.slice(5);
496
+ const exact = raw.startsWith('"') && raw.endsWith('"');
497
+ const text = exact ? raw.slice(1, -1) : raw;
498
+ return `(() => {
499
+ const target = ${JSON.stringify(text)};
500
+ const exact = ${exact};
501
+ // Match on OWN text nodes (not strict leaf elements): search-result
502
+ // titles mix text with inline highlight <em> marks \u2014 a strict leaf filter
503
+ // finds nothing there (real-world juejin). Own-text keeps the match
504
+ // precise (descendant-only text doesn't count) while tolerating markup.
505
+ const ownText = (e) => Array.prototype.filter.call(e.childNodes, (n) => n.nodeType === 3)
506
+ .map((n) => n.textContent).join('').trim();
507
+ const els = [...document.querySelectorAll('*')].filter(e => {
508
+ if (e.offsetParent === null && e.tagName !== 'BODY') return false;
509
+ const t = ownText(e);
510
+ if (!t) return false;
511
+ return exact ? t === target : t.toLowerCase().includes(target.toLowerCase());
512
+ });
513
+ // Rank instead of raw DOM order: exact text beats substring, interactive
514
+ // elements (button/a/[onclick]/inputs) beat prose. Prevents matching a
515
+ // description paragraph that merely MENTIONS the target label
516
+ // (rec-duel d06: header text "\u76EE\u6807\u9879\u300C\u7B2C 87 \u53F7\u300D" hijacked text=\u7B2C 87 \u53F7).
517
+ const isInteractive = (e) => {
518
+ const tag = e.tagName;
519
+ return tag === 'BUTTON' || tag === 'A' || tag === 'INPUT' || tag === 'SELECT'
520
+ || e.hasAttribute('onclick') || e.getAttribute('role') === 'button';
521
+ };
522
+ els.sort((a, b) => {
523
+ const ta = ownText(a), tb = ownText(b);
524
+ const ea = ta === target ? 0 : 1, eb = tb === target ? 0 : 1;
525
+ if (ea !== eb) return ea - eb;
526
+ const ia = isInteractive(a) ? 0 : 1, ib = isInteractive(b) ? 0 : 1;
527
+ if (ia !== ib) return ia - ib;
528
+ return 0; // stable \u2014 preserve DOM order
529
+ });
530
+ return els[0] || null;
531
+ })()`;
532
+ }
533
+ if (selector.startsWith("popup-text=")) {
534
+ const text = selector.slice("popup-text=".length);
535
+ return `(() => {
536
+ const target = ${JSON.stringify(text)};
537
+ const els = [...document.querySelectorAll('*')].filter(e => {
538
+ if (e.children.length > 0) return false;
539
+ if (e.offsetParent === null) return false;
540
+ if ((e.textContent || '').trim() !== target) return false;
541
+ return true;
542
+ });
543
+ return els[0] || null;
544
+ })()`;
545
+ }
546
+ return `document.querySelector(${JSON.stringify(selector)})`;
547
+ }
548
+ function queryAllJS(selector) {
549
+ if (selector.startsWith("xpath=")) {
550
+ const xpath = JSON.stringify(selector.slice(6));
551
+ return `(() => { const it = document.evaluate(${xpath}, 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; })()`;
552
+ }
553
+ if (selector.startsWith("text=") || selector.startsWith("popup-text=")) {
554
+ return `(() => { const el = ${queryJS(selector)}; return el ? [el] : []; })()`;
555
+ }
556
+ return `document.querySelectorAll(${JSON.stringify(selector)})`;
557
+ }
558
+
559
+ // src/cdp-driver/actionability.ts
560
+ async function waitForActionable(page, selector, opts = {}) {
561
+ const timeout = opts.timeout ?? 3e4;
562
+ if (opts.force) {
563
+ const deadline2 = Date.now() + timeout;
564
+ let lastError;
565
+ while (Date.now() < deadline2) {
566
+ const rect = await page.evaluate(`
567
+ (function() {
568
+ const el = ${queryJS(selector)};
569
+ if (!el) return null;
570
+ const r = el.getBoundingClientRect();
571
+ let x = r.x, y = r.y;
572
+ let doc = el.ownerDocument;
573
+ while (doc !== document) {
574
+ let host = null;
575
+ const scan = (d) => {
576
+ let frames;
577
+ try { frames = d.querySelectorAll('iframe'); } catch (e) { return null; }
578
+ for (const f of frames) {
579
+ let inner = null;
580
+ try { inner = f.contentDocument; } catch (e) { continue; }
581
+ if (!inner) continue;
582
+ if (inner === doc) return f;
583
+ const rr = scan(inner);
584
+ if (rr) return rr;
585
+ }
586
+ return null;
587
+ };
588
+ host = scan(document);
589
+ if (!host) break;
590
+ const hr = host.getBoundingClientRect();
591
+ x += hr.x; y += hr.y;
592
+ doc = host.ownerDocument;
593
+ }
594
+ return { x, y, width: r.width, height: r.height };
595
+ })()
596
+ `).catch(() => null);
597
+ if (rect && rect.width > 0 && rect.height > 0) return { nodeId: 0, rect };
598
+ lastError = `Element not visible (zero size): ${selector}`;
599
+ lastError = `Element not found: ${selector}`;
600
+ await page.waitForTimeout(200);
601
+ }
602
+ throw new Error(lastError || `Element not found: ${selector}`);
603
+ }
604
+ const deadline = Date.now() + timeout;
605
+ while (Date.now() < deadline) {
606
+ const result = await checkActionable(page, selector);
607
+ if (result.ok && result.rect) {
608
+ const nodeId = await page.querySelector(selector).catch(() => 0) ?? 0;
609
+ return { nodeId, rect: result.rect };
610
+ }
611
+ await page.waitForTimeout(50);
612
+ }
613
+ throw new Error(`Actionability timeout: element '${selector}' not ready after ${timeout}ms`);
614
+ }
615
+ async function checkActionable(page, selector) {
616
+ const result = await page.evaluate(`
617
+ (function() {
618
+ const el = ${queryJS(selector)};
619
+ if (!el) return { ok: false, reason: 'not_found' };
620
+
621
+ // Check attached to DOM
622
+ if (!el.isConnected) return { ok: false, reason: 'detached' };
623
+
624
+ // Check visibility
625
+ const style = window.getComputedStyle(el);
626
+ if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') {
627
+ return { ok: false, reason: 'invisible' };
628
+ }
629
+
630
+ // Check non-zero size
631
+ const rect = el.getBoundingClientRect();
632
+ if (rect.width === 0 || rect.height === 0) {
633
+ return { ok: false, reason: 'zero_size' };
634
+ }
635
+
636
+ // Check enabled (for form elements)
637
+ if (el.disabled) return { ok: false, reason: 'disabled' };
638
+ if (el.tagName === 'OPTION' && el.closest('select')?.disabled) {
639
+ return { ok: false, reason: 'parent_disabled' };
640
+ }
641
+
642
+ // Check not covered by another element at center.
643
+ // elementFromPoint must run in the element's OWN document: for iframe-
644
+ // internal elements the main-document hit-test returns the <iframe>
645
+ // host itself, which falsely reports "covered" (rec-duel d01).
646
+ // For shadow-internal elements the hit-test retargets to the shadow
647
+ // HOST \u2014 walk the host chain before declaring coverage (rec-duel d04).
648
+ const cx = rect.x + rect.width / 2;
649
+ const cy = rect.y + rect.height / 2;
650
+ const topEl = el.ownerDocument.elementFromPoint(cx, cy);
651
+ if (topEl && topEl !== el && !el.contains(topEl) && !topEl.contains(el)) {
652
+ let hostChain = [];
653
+ let rootNode = el.getRootNode();
654
+ while (rootNode && rootNode.host) {
655
+ hostChain.push(rootNode.host);
656
+ rootNode = rootNode.host.getRootNode();
657
+ }
658
+ if (!hostChain.includes(topEl)) {
659
+ return { ok: false, reason: 'covered', rect: { x: rect.x, y: rect.y, width: rect.width, height: rect.height } };
660
+ }
661
+ }
662
+
663
+ return {
664
+ ok: true,
665
+ rect: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
666
+ };
667
+ })()
668
+ `);
669
+ return result;
670
+ }
671
+ async function scrollIntoView(page, selector) {
672
+ await page.evaluate(`
673
+ (function() {
674
+ const el = ${queryJS(selector)};
675
+ if (el) el.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' });
676
+ })()
677
+ `);
678
+ }
679
+
680
+ // src/cdp-driver/locator.ts
681
+ var XBLocatorImpl = class _XBLocatorImpl {
682
+ page;
683
+ selector;
684
+ constructor(page, selector) {
685
+ this.page = page;
686
+ this.selector = selector;
687
+ }
688
+ /** Resolve selector to a JS expression that finds a single element (CSS or xpath). */
689
+ _q(sel) {
690
+ return queryJS(sel);
691
+ }
692
+ /** Resolve selector to a JS expression that finds all matching elements (CSS or xpath). */
693
+ _qa(sel) {
694
+ return queryAllJS(sel);
695
+ }
696
+ // ── Actions ─────────────────────────────────────────────────
697
+ async click(opts = {}) {
698
+ const { rect } = await waitForActionable(this.page, this.selector, opts);
699
+ await scrollIntoView(this.page, this.selector);
700
+ const updatedRect = await this.page.evaluate(`
701
+ (function() {
702
+ const el = ${this._q(this.selector)};
703
+ if (!el) return null;
704
+ const rect = el.getBoundingClientRect();
705
+ let x = rect.x, y = rect.y;
706
+ let doc = el.ownerDocument;
707
+ while (doc !== document) {
708
+ let host = null;
709
+ const scan = (d) => {
710
+ let frames;
711
+ try { frames = d.querySelectorAll('iframe'); } catch (e) { return null; }
712
+ for (const f of frames) {
713
+ let inner = null;
714
+ try { inner = f.contentDocument; } catch (e) { continue; }
715
+ if (!inner) continue;
716
+ if (inner === doc) return f;
717
+ const r = scan(inner);
718
+ if (r) return r;
719
+ }
720
+ return null;
721
+ };
722
+ host = scan(document);
723
+ if (!host) break;
724
+ const hr = host.getBoundingClientRect();
725
+ x += hr.x; y += hr.y;
726
+ doc = host.ownerDocument;
727
+ }
728
+ return { x, y, width: rect.width, height: rect.height };
729
+ })()
730
+ `);
731
+ const finalRect = updatedRect ?? rect;
732
+ const cx = finalRect.x + finalRect.width / 2;
733
+ const cy = finalRect.y + finalRect.height / 2;
734
+ await this.page.mouse.click(cx, cy, {
735
+ stealth: true,
736
+ elementWidth: finalRect.width,
737
+ elementHeight: finalRect.height,
738
+ ...{ button: opts.button ?? "left", clickCount: opts.clickCount ?? 1, delay: opts.delay }
739
+ });
740
+ }
741
+ async fill(value, opts = {}) {
742
+ await waitForActionable(this.page, this.selector, opts);
743
+ await scrollIntoView(this.page, this.selector);
744
+ await this.click({ ...opts });
745
+ await this.page.keyboard.type(value, { stealth: true });
746
+ return;
747
+ await this.page.evaluate(`
748
+ (function() {
749
+ const el = ${this._q(this.selector)};
750
+ if (!el) throw new Error('Element not found: ${this.selector.replace(/'/g, "\\'")}');
751
+ el.focus();
752
+ el.value = '';
753
+ el.dispatchEvent(new Event('input', { bubbles: true }));
754
+ })()
755
+ `);
756
+ await this.page.keyboard.insertText(value);
757
+ await this.page.evaluate(`
758
+ (function() {
759
+ const el = ${this._q(this.selector)};
760
+ if (el) {
761
+ el.dispatchEvent(new Event('input', { bubbles: true }));
762
+ el.dispatchEvent(new Event('change', { bubbles: true }));
763
+ }
764
+ })()
765
+ `);
766
+ }
767
+ async press(key, opts = {}) {
768
+ await waitForActionable(this.page, this.selector, { timeout: opts.timeout });
769
+ await scrollIntoView(this.page, this.selector);
770
+ await this.page.evaluate(`
771
+ (function() {
772
+ const el = ${this._q(this.selector)};
773
+ if (el) el.focus();
774
+ })()
775
+ `);
776
+ await this.page.keyboard.press(key);
777
+ }
778
+ async pressSequentially(text, opts = {}) {
779
+ await waitForActionable(this.page, this.selector, { timeout: opts.timeout });
780
+ await scrollIntoView(this.page, this.selector);
781
+ await this.page.evaluate(`
782
+ (function() {
783
+ const el = ${this._q(this.selector)};
784
+ if (el) el.focus();
785
+ })()
786
+ `);
787
+ await this.page.keyboard.type(text, { delay: opts.delay });
788
+ }
789
+ async hover(opts = {}) {
790
+ if (!opts.force) {
791
+ const { rect } = await waitForActionable(this.page, this.selector, { timeout: opts.timeout });
792
+ await scrollIntoView(this.page, this.selector);
793
+ const cx = rect.x + rect.width / 2;
794
+ const cy = rect.y + rect.height / 2;
795
+ await this.page.mouse.move(cx, cy);
796
+ } else {
797
+ await scrollIntoView(this.page, this.selector);
798
+ const rect = await this.page.evaluate(`
799
+ (function() {
800
+ const el = ${this._q(this.selector)};
801
+ if (!el) return { x: 0, y: 0, width: 0, height: 0 };
802
+ const r = el.getBoundingClientRect();
803
+ return { x: r.x, y: r.y, width: r.width, height: r.height };
804
+ })()
805
+ `);
806
+ const cx = rect.x + rect.width / 2;
807
+ const cy = rect.y + rect.height / 2;
808
+ await this.page.mouse.move(cx, cy);
809
+ }
810
+ }
811
+ async type(text, opts = {}) {
812
+ await this.pressSequentially(text, opts);
813
+ }
814
+ async check(opts = {}) {
815
+ await waitForActionable(this.page, this.selector, { timeout: opts.timeout });
816
+ const isChecked = await this.page.evaluate(`
817
+ (function() {
818
+ const el = ${this._q(this.selector)};
819
+ return el?.checked === true;
820
+ })()
821
+ `);
822
+ if (!isChecked) {
823
+ await this.click({ timeout: opts.timeout });
824
+ }
825
+ }
826
+ async uncheck(opts = {}) {
827
+ await waitForActionable(this.page, this.selector, { timeout: opts.timeout });
828
+ const isChecked = await this.page.evaluate(`
829
+ (function() {
830
+ const el = ${this._q(this.selector)};
831
+ return el?.checked === true;
832
+ })()
833
+ `);
834
+ if (isChecked) {
835
+ await this.click({ timeout: opts.timeout });
836
+ }
837
+ }
838
+ async selectOption(value) {
839
+ await waitForActionable(this.page, this.selector);
840
+ const values = Array.isArray(value) ? value : [value];
841
+ const selected = await this.page.evaluate(`
842
+ (function() {
843
+ const el = ${this._q(this.selector)};
844
+ if (!el || el.tagName !== 'SELECT') throw new Error('Not a select element');
845
+
846
+ const values = ${JSON.stringify(values)};
847
+ const selectedValues = [];
848
+
849
+ for (const opt of el.options) {
850
+ for (const v of values) {
851
+ if (typeof v === 'object') {
852
+ if (v.label && opt.label === v.label) { opt.selected = true; selectedValues.push(opt.value); }
853
+ else if (v.value && opt.value === v.value) { opt.selected = true; selectedValues.push(opt.value); }
854
+ else if (v.index !== undefined && opt.index === v.index) { opt.selected = true; selectedValues.push(opt.value); }
855
+ } else if (opt.value === v || opt.label === v) {
856
+ opt.selected = true;
857
+ selectedValues.push(opt.value);
858
+ }
859
+ }
860
+ }
861
+
862
+ el.dispatchEvent(new Event('input', { bubbles: true }));
863
+ el.dispatchEvent(new Event('change', { bubbles: true }));
864
+ return selectedValues;
865
+ })()
866
+ `);
867
+ return selected;
868
+ }
869
+ async screenshot(opts = {}) {
870
+ await waitForActionable(this.page, this.selector);
871
+ const box = await this.page.evaluate(`
872
+ (function() {
873
+ const el = ${this._q(this.selector)};
874
+ if (!el) return null;
875
+ const r = el.getBoundingClientRect();
876
+ return { x: r.x, y: r.y, width: r.width, height: r.height };
877
+ })()
878
+ `);
879
+ if (!box) throw new Error(`Element not found: ${this.selector}`);
880
+ return this.page.screenshot({
881
+ ...opts,
882
+ clip: { x: box.x, y: box.y, width: box.width, height: box.height }
883
+ });
884
+ }
885
+ // ── State checks ────────────────────────────────────────────
886
+ async waitFor(opts = {}) {
887
+ await this.page.waitForSelector(this.selector, opts);
888
+ }
889
+ async count() {
890
+ return this.page.evaluate(`
891
+ ${this._qa(this.selector)}.length
892
+ `);
893
+ }
894
+ async isVisible() {
895
+ try {
896
+ const result = await this.page.evaluate(`
897
+ (function() {
898
+ const el = ${this._q(this.selector)};
899
+ if (!el) return false;
900
+ if (!el.isConnected) return false;
901
+ const style = window.getComputedStyle(el);
902
+ if (style.display === 'none' || style.visibility === 'hidden') return false;
903
+ const rect = el.getBoundingClientRect();
904
+ return rect.width > 0 && rect.height > 0;
905
+ })()
906
+ `);
907
+ return Boolean(result);
908
+ } catch {
909
+ return false;
910
+ }
911
+ }
912
+ async isHidden() {
913
+ return !await this.isVisible();
914
+ }
915
+ async isEnabled() {
916
+ return this.page.evaluate(`
917
+ (function() {
918
+ const el = ${this._q(this.selector)};
919
+ if (!el) return false;
920
+ return !el.disabled;
921
+ })()
922
+ `);
923
+ }
924
+ async isDisabled() {
925
+ return !await this.isEnabled();
926
+ }
927
+ async boundingBox() {
928
+ return this.page.evaluate(`
929
+ (function() {
930
+ const el = ${this._q(this.selector)};
931
+ if (!el) return null;
932
+ const r = el.getBoundingClientRect();
933
+ return { x: r.x, y: r.y, width: r.width, height: r.height };
934
+ })()
935
+ `);
936
+ }
937
+ // ── Text/HTML ───────────────────────────────────────────────
938
+ async textContent() {
939
+ return this.page.evaluate(`
940
+ (function() {
941
+ const el = ${this._q(this.selector)};
942
+ return el?.textContent ?? null;
943
+ })()
944
+ `);
945
+ }
946
+ async innerText() {
947
+ return this.page.evaluate(`
948
+ (function() {
949
+ const el = ${this._q(this.selector)};
950
+ if (!el) throw new Error('Element not found');
951
+ return el.innerText;
952
+ })()
953
+ `);
954
+ }
955
+ async innerHTML() {
956
+ return this.page.evaluate(`
957
+ (function() {
958
+ const el = ${this._q(this.selector)};
959
+ if (!el) throw new Error('Element not found');
960
+ return el.innerHTML;
961
+ })()
962
+ `);
963
+ }
964
+ async getAttribute(name) {
965
+ return this.page.evaluate(`
966
+ (function() {
967
+ const el = ${this._q(this.selector)};
968
+ return el?.getAttribute(${JSON.stringify(name)}) ?? null;
969
+ })()
970
+ `);
971
+ }
972
+ // ── Evaluate ────────────────────────────────────────────────
973
+ async evaluate(fn, ...args) {
974
+ const fnBody = typeof fn === "function" ? fn.toString() : fn;
975
+ const sel = JSON.stringify(this.selector);
976
+ const xpathPrefix = this.selector.startsWith("xpath=") ? JSON.stringify(this.selector.slice(6)) : "null";
977
+ return this.page.evaluate(
978
+ `(function(sel, xpathExpr, fnStr, ...evalArgs) {
979
+ const el = xpathExpr
980
+ ? document.evaluate(xpathExpr, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
981
+ : document.querySelector(sel);
982
+ if (!el) throw new Error('No element found for selector: ' + sel);
983
+ const fn = new Function('return ' + fnStr)();
984
+ return fn(el, ...evalArgs);
985
+ })(${sel}, ${xpathPrefix}, ${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
986
+ );
987
+ }
988
+ async ariaSnapshot() {
989
+ const result = await this.page._cdpSend(
990
+ "Accessibility.getFullAXTree"
991
+ );
992
+ return result.nodes.map((n) => `${n.role?.value}: ${n.name?.value ?? ""}`).join("\n");
993
+ }
994
+ // ── Filtering ───────────────────────────────────────────────
995
+ first() {
996
+ return new FilteredLocator(this.page, this.selector, 0);
997
+ }
998
+ last() {
999
+ return new FilteredLocator(this.page, this.selector, -1);
1000
+ }
1001
+ nth(index) {
1002
+ return new FilteredLocator(this.page, this.selector, index);
1003
+ }
1004
+ filter(opts) {
1005
+ if (opts.visible) {
1006
+ return new VisibleFilteredLocator(this.page, this.selector);
1007
+ }
1008
+ return new _XBLocatorImpl(this.page, this.selector);
1009
+ }
1010
+ async all() {
1011
+ const n = await this.page.evaluate(`
1012
+ ${this._qa(this.selector)}.length
1013
+ `);
1014
+ const locators = [];
1015
+ for (let i = 0; i < n; i++) {
1016
+ locators.push(new FilteredLocator(this.page, this.selector, i));
1017
+ }
1018
+ return locators;
1019
+ }
1020
+ async focus() {
1021
+ await this.page.evaluate(`
1022
+ (function() {
1023
+ const el = ${this._q(this.selector)};
1024
+ if (el) el.focus();
1025
+ })()
1026
+ `);
1027
+ }
1028
+ };
1029
+ var FilteredLocator = class extends XBLocatorImpl {
1030
+ index;
1031
+ constructor(page, selector, index) {
1032
+ const indexedSelector = selector.startsWith("xpath=") ? selector : index === -1 ? `${selector}:last-of-type` : `${selector}:nth-of-type(${index + 1})`;
1033
+ super(page, indexedSelector);
1034
+ this.index = index;
1035
+ this._rawSelector = selector;
1036
+ }
1037
+ /** Original selector before index filtering */
1038
+ _rawSelector;
1039
+ /** For xpath selectors, override _q to return the nth element from evaluate results */
1040
+ _q(sel) {
1041
+ if (!sel.startsWith("xpath=")) return super._q(sel);
1042
+ const xpath = JSON.stringify(this._rawSelector.slice(6));
1043
+ return `(() => { const it = document.evaluate(${xpath}, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); return ${this.index === -1 ? "it.snapshotItem(it.snapshotLength - 1)" : `it.snapshotItem(${this.index})`}; })()`;
1044
+ }
1045
+ /** For xpath selectors, override _qa to return all matching elements from evaluate */
1046
+ _qa(sel) {
1047
+ if (!sel.startsWith("xpath=")) return super._qa(sel);
1048
+ const xpath = JSON.stringify(this._rawSelector.slice(6));
1049
+ return `(() => { const it = document.evaluate(${xpath}, 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; })()`;
1050
+ }
1051
+ };
1052
+ var VisibleFilteredLocator = class extends XBLocatorImpl {
1053
+ async _withVisibleTag(fn) {
1054
+ const tag = `data-xb-vt-${Date.now()}-${Math.floor(Math.random() * 1e6)}`;
1055
+ const found = await this.page.evaluate(`
1056
+ (function() {
1057
+ const els = ${this._qa(this.selector)};
1058
+ for (const el of els) {
1059
+ if (!el.isConnected) continue;
1060
+ const style = window.getComputedStyle(el);
1061
+ if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') continue;
1062
+ const rect = el.getBoundingClientRect();
1063
+ if (rect.width === 0 || rect.height === 0) continue;
1064
+ el.setAttribute(${JSON.stringify(tag)}, '');
1065
+ return true;
1066
+ }
1067
+ return false;
1068
+ })()
1069
+ `);
1070
+ if (!found) throw new Error(`No visible element found for: ${this.selector}`);
1071
+ try {
1072
+ return await fn(`[${tag}]`);
1073
+ } finally {
1074
+ await this.page.evaluate(`
1075
+ ${this._qa(`[${tag}]`)}.forEach(el => el.removeAttribute(${JSON.stringify(tag)}))
1076
+ `);
1077
+ }
1078
+ }
1079
+ async click(opts) {
1080
+ return this._withVisibleTag((tagSel) => new XBLocatorImpl(this.page, tagSel).click(opts));
1081
+ }
1082
+ async fill(value, opts) {
1083
+ return this._withVisibleTag((tagSel) => new XBLocatorImpl(this.page, tagSel).fill(value, opts));
1084
+ }
1085
+ async press(key, opts) {
1086
+ return this._withVisibleTag((tagSel) => new XBLocatorImpl(this.page, tagSel).press(key, opts));
1087
+ }
1088
+ async hover(opts) {
1089
+ return this._withVisibleTag((tagSel) => new XBLocatorImpl(this.page, tagSel).hover(opts));
1090
+ }
1091
+ async count() {
1092
+ return this.page.evaluate(`
1093
+ (function() {
1094
+ let count = 0;
1095
+ const els = ${this._qa(this.selector)};
1096
+ for (const el of els) {
1097
+ if (!el.isConnected) continue;
1098
+ const style = window.getComputedStyle(el);
1099
+ if (style.display === 'none' || style.visibility === 'hidden') continue;
1100
+ const rect = el.getBoundingClientRect();
1101
+ if (rect.width === 0 || rect.height === 0) continue;
1102
+ count++;
1103
+ }
1104
+ return count;
1105
+ })()
1106
+ `);
1107
+ }
1108
+ async isVisible() {
1109
+ try {
1110
+ const result = await this.page.evaluate(`
1111
+ (function() {
1112
+ const els = ${this._qa(this.selector)};
1113
+ for (const el of els) {
1114
+ if (!el.isConnected) continue;
1115
+ const style = window.getComputedStyle(el);
1116
+ if (style.display === 'none' || style.visibility === 'hidden') continue;
1117
+ const rect = el.getBoundingClientRect();
1118
+ if (rect.width > 0 && rect.height > 0) return true;
1119
+ }
1120
+ return false;
1121
+ })()
1122
+ `);
1123
+ return result;
1124
+ } catch {
1125
+ return false;
1126
+ }
1127
+ }
1128
+ async textContent() {
1129
+ return this._withVisibleTag((tagSel) => new XBLocatorImpl(this.page, tagSel).textContent());
1130
+ }
1131
+ async innerText() {
1132
+ return this._withVisibleTag((tagSel) => new XBLocatorImpl(this.page, tagSel).innerText());
1133
+ }
1134
+ async waitFor(opts) {
1135
+ const deadline = Date.now() + (opts?.timeout ?? 3e4);
1136
+ while (Date.now() < deadline) {
1137
+ if (await this.isVisible()) return;
1138
+ await this.page.waitForTimeout(50);
1139
+ }
1140
+ throw new Error(`Timeout waiting for visible element: ${this.selector}`);
1141
+ }
1142
+ };
1143
+
1144
+ // src/cdp-driver/element-handle.ts
1145
+ var XBElementHandleImpl = class {
1146
+ page;
1147
+ nodeId;
1148
+ disposed = false;
1149
+ constructor(page, nodeId) {
1150
+ this.page = page;
1151
+ this.nodeId = nodeId;
1152
+ }
1153
+ get _nodeId() {
1154
+ return this.nodeId;
1155
+ }
1156
+ async click(opts = {}) {
1157
+ if (this.disposed) throw new Error("Element handle disposed");
1158
+ const box = await this.boundingBox();
1159
+ if (!box) throw new Error("Element has no box");
1160
+ await this.scrollIntoViewIfNeeded();
1161
+ const cx = box.x + box.width / 2;
1162
+ const cy = box.y + box.height / 2;
1163
+ await this.page.mouse.click(cx, cy, {
1164
+ button: opts.button ?? "left",
1165
+ clickCount: opts.clickCount ?? 1,
1166
+ delay: opts.delay
1167
+ });
1168
+ }
1169
+ async fill(value, _opts = {}) {
1170
+ if (this.disposed) throw new Error("Element handle disposed");
1171
+ const objectId = await this.page.resolveNode(this.nodeId);
1172
+ await this.page.callFunctionOn(
1173
+ objectId,
1174
+ `function(value) {
1175
+ this.focus();
1176
+ this.value = '';
1177
+ this.dispatchEvent(new Event('input', { bubbles: true }));
1178
+ }`,
1179
+ [value]
1180
+ );
1181
+ await this.page.keyboard.insertText(value);
1182
+ await this.page.callFunctionOn(
1183
+ objectId,
1184
+ `function() {
1185
+ this.dispatchEvent(new Event('input', { bubbles: true }));
1186
+ this.dispatchEvent(new Event('change', { bubbles: true }));
1187
+ }`
1188
+ );
1189
+ }
1190
+ async hover() {
1191
+ const box = await this.boundingBox();
1192
+ if (!box) throw new Error("Element has no box");
1193
+ await this.scrollIntoViewIfNeeded();
1194
+ await this.page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
1195
+ }
1196
+ async press(key) {
1197
+ const objectId = await this.page.resolveNode(this.nodeId);
1198
+ await this.page.callFunctionOn(objectId, "function() { this.focus(); }");
1199
+ await this.page.keyboard.press(key);
1200
+ }
1201
+ async screenshot(opts = {}) {
1202
+ const box = await this.boundingBox();
1203
+ if (!box) throw new Error("Element has no box");
1204
+ return this.page.screenshot({
1205
+ ...opts,
1206
+ clip: box
1207
+ });
1208
+ }
1209
+ async boundingBox() {
1210
+ return this.page.getBoxModel(this.nodeId);
1211
+ }
1212
+ async isVisible() {
1213
+ try {
1214
+ const objectId = await this.page.resolveNode(this.nodeId);
1215
+ const result = await this.page.callFunctionOn(
1216
+ objectId,
1217
+ `function() {
1218
+ if (!this.isConnected) return false;
1219
+ const style = window.getComputedStyle(this);
1220
+ if (style.display === 'none' || style.visibility === 'hidden') return false;
1221
+ const rect = this.getBoundingClientRect();
1222
+ return rect.width > 0 && rect.height > 0;
1223
+ }`
1224
+ );
1225
+ return Boolean(result);
1226
+ } catch {
1227
+ return false;
1228
+ }
1229
+ }
1230
+ async isEnabled() {
1231
+ const objectId = await this.page.resolveNode(this.nodeId);
1232
+ return this.page.callFunctionOn(objectId, "function() { return !this.disabled; }");
1233
+ }
1234
+ async textContent() {
1235
+ const objectId = await this.page.resolveNode(this.nodeId);
1236
+ return this.page.callFunctionOn(objectId, "function() { return this.textContent; }");
1237
+ }
1238
+ async innerText() {
1239
+ const objectId = await this.page.resolveNode(this.nodeId);
1240
+ return this.page.callFunctionOn(objectId, "function() { return this.innerText; }");
1241
+ }
1242
+ async innerHTML() {
1243
+ const objectId = await this.page.resolveNode(this.nodeId);
1244
+ return this.page.callFunctionOn(objectId, "function() { return this.innerHTML; }");
1245
+ }
1246
+ async getAttribute(name) {
1247
+ const objectId = await this.page.resolveNode(this.nodeId);
1248
+ return this.page.callFunctionOn(objectId, `function() { return this.getAttribute(${JSON.stringify(name)}); }`);
1249
+ }
1250
+ async scrollIntoViewIfNeeded() {
1251
+ if (this.disposed) return;
1252
+ const objectId = await this.page.resolveNode(this.nodeId);
1253
+ await this.page.callFunctionOn(
1254
+ objectId,
1255
+ 'function() { this.scrollIntoView({ block: "center", inline: "center", behavior: "instant" }); }'
1256
+ );
1257
+ }
1258
+ dispose() {
1259
+ this.disposed = true;
1260
+ }
1261
+ };
1262
+
1263
+ // src/cdp-driver/page-helpers.ts
1264
+ function globToRegex(glob) {
1265
+ let pattern = glob.replace(/[\\^${}()|[\]+]/g, "\\$&").replace(/\./g, "\\.").replace(/\*\*/g, "{{DOUBLESTAR}}").replace(/\*/g, "[^/]*").replace(/{{DOUBLESTAR}}/g, ".*").replace(/\?/g, ".");
1266
+ if (!pattern.startsWith("http") && !pattern.startsWith("\\.")) {
1267
+ pattern = ".*" + pattern;
1268
+ }
1269
+ return new RegExp("^" + pattern + "$", "i");
1270
+ }
1271
+ function matchGlob(pattern, url) {
1272
+ return globToRegex(pattern).test(url);
1273
+ }
1274
+ function createResponsePredicate(urlOrPredicate) {
1275
+ if (typeof urlOrPredicate === "function") {
1276
+ return urlOrPredicate;
1277
+ }
1278
+ if (urlOrPredicate instanceof RegExp) {
1279
+ return (resp) => urlOrPredicate.test(resp.url());
1280
+ }
1281
+ const regex = globToRegex(urlOrPredicate);
1282
+ return (resp) => regex.test(resp.url());
1283
+ }
1284
+ function createRequestPredicate(urlOrPredicate) {
1285
+ if (typeof urlOrPredicate === "function") {
1286
+ return urlOrPredicate;
1287
+ }
1288
+ if (urlOrPredicate instanceof RegExp) {
1289
+ return (req) => urlOrPredicate.test(req.url());
1290
+ }
1291
+ const regex = globToRegex(urlOrPredicate);
1292
+ return (req) => regex.test(req.url());
1293
+ }
1294
+ function createXBResponse(data, conn, sessionId, requestData) {
1295
+ const request = requestData ? createXBRequest(null, requestData) : createXBRequest(null, { requestId: data.requestId, url: data.url, method: "GET", headers: {}, postData: null, resourceType: "other" });
1296
+ return {
1297
+ status: () => data.status,
1298
+ statusText: () => "",
1299
+ url: () => data.url,
1300
+ headers: () => data.headers,
1301
+ ok: () => data.status >= 200 && data.status < 300,
1302
+ body: async () => {
1303
+ if (!conn) throw new Error("Response body not available");
1304
+ try {
1305
+ const resp = await conn.send(
1306
+ "Network.getResponseBody",
1307
+ { requestId: data.requestId },
1308
+ sessionId
1309
+ );
1310
+ return Buffer.from(resp.body, resp.base64Encoded ? "base64" : "utf8");
1311
+ } catch {
1312
+ throw new Error("Response body not available");
1313
+ }
1314
+ },
1315
+ text: async () => {
1316
+ if (!conn) throw new Error("Response body not available");
1317
+ try {
1318
+ const resp = await conn.send(
1319
+ "Network.getResponseBody",
1320
+ { requestId: data.requestId },
1321
+ sessionId
1322
+ );
1323
+ return resp.base64Encoded ? Buffer.from(resp.body, "base64").toString("utf8") : resp.body;
1324
+ } catch {
1325
+ throw new Error("Response body not available");
1326
+ }
1327
+ },
1328
+ json: async () => {
1329
+ const text = await (async () => {
1330
+ if (!conn) throw new Error("Response body not available");
1331
+ try {
1332
+ const resp = await conn.send(
1333
+ "Network.getResponseBody",
1334
+ { requestId: data.requestId },
1335
+ sessionId
1336
+ );
1337
+ return resp.base64Encoded ? Buffer.from(resp.body, "base64").toString("utf8") : resp.body;
1338
+ } catch {
1339
+ throw new Error("Response body not available");
1340
+ }
1341
+ })();
1342
+ return JSON.parse(text);
1343
+ },
1344
+ request: () => request
1345
+ };
1346
+ }
1347
+ function createXBRequest(page, data) {
1348
+ return {
1349
+ url: () => data.url,
1350
+ method: () => data.method,
1351
+ headers: () => data.headers,
1352
+ postData: () => data.postData,
1353
+ resourceType: () => data.resourceType,
1354
+ response: async () => {
1355
+ if (!page?._networkResponses) return null;
1356
+ const resp = page._networkResponses.get(data.requestId);
1357
+ if (!resp) return null;
1358
+ return createXBResponse(resp, page._connection, page.sessionId, data);
1359
+ }
1360
+ };
1361
+ }
1362
+ function createXBRouteFetch(conn, sessionId, params, emitter) {
1363
+ const request = createXBRequest(null, {
1364
+ requestId: params.requestId,
1365
+ url: params.request.url,
1366
+ method: params.request.method,
1367
+ headers: params.request.headers,
1368
+ postData: params.request.postData ?? null,
1369
+ resourceType: params.resourceType
1370
+ });
1371
+ return {
1372
+ request: () => request,
1373
+ abort: async (errorCode) => {
1374
+ await conn.send("Fetch.failRequest", {
1375
+ requestId: params.requestId,
1376
+ errorReason: errorCode || "Failed"
1377
+ }, sessionId);
1378
+ },
1379
+ continue: async (opts) => {
1380
+ await conn.send("Fetch.continueRequest", {
1381
+ requestId: params.requestId,
1382
+ url: opts?.url,
1383
+ method: opts?.method,
1384
+ headers: opts?.headers ? Object.entries(opts.headers).map(([k, v]) => ({ name: k, value: v })) : void 0,
1385
+ postData: opts?.postData ? Buffer.from(opts.postData).toString("base64") : void 0
1386
+ }, sessionId);
1387
+ },
1388
+ fulfill: async (opts) => {
1389
+ const bodyStr = typeof opts.body === "string" ? opts.body : opts.body ? opts.body.toString("utf8") : "";
1390
+ const bodyBytes = Buffer.from(bodyStr, "utf8");
1391
+ const headers = { ...opts.headers };
1392
+ if (opts.contentType) headers["content-type"] = opts.contentType;
1393
+ headers["access-control-allow-origin"] = "*";
1394
+ await conn.send("Fetch.fulfillRequest", {
1395
+ requestId: params.requestId,
1396
+ responseCode: opts.status ?? 200,
1397
+ responseHeaders: Object.entries(headers).map(([k, v]) => ({ name: k, value: v })),
1398
+ body: bodyBytes.toString("base64")
1399
+ }, sessionId);
1400
+ if (emitter) {
1401
+ const responseData = {
1402
+ requestId: params.requestId,
1403
+ status: opts.status ?? 200,
1404
+ url: params.request.url,
1405
+ headers
1406
+ };
1407
+ const response = createXBResponse(responseData, conn, sessionId);
1408
+ emitter.emit("response", response);
1409
+ }
1410
+ }
1411
+ };
1412
+ }
1413
+
1414
+ // src/cdp-driver/page.ts
1415
+ var XBPageImpl = class _XBPageImpl {
1416
+ conn;
1417
+ _emitter = new EventEmitter();
1418
+ _subscriptions = [];
1419
+ sessionId;
1420
+ _targetId;
1421
+ _contextImpl;
1422
+ _browserImpl;
1423
+ _closed = false;
1424
+ _url = "about:blank";
1425
+ _title = "";
1426
+ _viewportSize = null;
1427
+ _loadState = {
1428
+ loadFired: true,
1429
+ domContentFired: true,
1430
+ networkIdle: true
1431
+ };
1432
+ mouse;
1433
+ keyboard;
1434
+ // Network tracking for waitForLoadState('networkidle')
1435
+ inflightRequests = /* @__PURE__ */ new Set();
1436
+ networkIdleResolve = null;
1437
+ networkIdleTimer = null;
1438
+ static NETWORK_IDLE_MS = 500;
1439
+ constructor(conn, sessionId, targetId, context, browser) {
1440
+ this.conn = conn;
1441
+ this.sessionId = sessionId;
1442
+ this._targetId = targetId;
1443
+ this._contextImpl = context;
1444
+ this._browserImpl = browser;
1445
+ this.mouse = new XBMouseImpl(conn, sessionId);
1446
+ this.keyboard = new XBKeyboardImpl(conn, sessionId);
1447
+ }
1448
+ _emit(event, ...args) {
1449
+ this._emitter.emit(event, ...args);
1450
+ }
1451
+ /** Internal initialization — must be called after construction */
1452
+ async _init() {
1453
+ await this.conn.send("Page.enable", void 0, this.sessionId);
1454
+ await this.conn.send("Runtime.enable", void 0, this.sessionId);
1455
+ await this.conn.send("Network.enable", void 0, this.sessionId);
1456
+ await this.conn.send("DOM.enable", void 0, this.sessionId).catch(() => {
1457
+ });
1458
+ this.setupPageEvents();
1459
+ this.setupNetworkEvents();
1460
+ this.setupConsoleEvents();
1461
+ await this.conn.send("Runtime.runIfWaitingForDebugger", void 0, this.sessionId).catch(() => {
1462
+ });
1463
+ try {
1464
+ const info = await this.conn.send(
1465
+ "Target.getTargetInfo",
1466
+ { targetId: this._targetId }
1467
+ );
1468
+ this._url = info.url;
1469
+ this._title = info.title;
1470
+ if (info.url && info.url !== "about:blank" && info.url !== "") {
1471
+ this._loadState = { loadFired: true, domContentFired: true, networkIdle: true };
1472
+ }
1473
+ } catch {
1474
+ }
1475
+ }
1476
+ get _connection() {
1477
+ return this.conn;
1478
+ }
1479
+ // ── Navigation ──────────────────────────────────────────────
1480
+ async goto(url, opts = {}) {
1481
+ if (this._closed) throw new Error("Page is closed");
1482
+ const waitUntil = opts.waitUntil ?? "load";
1483
+ const timeout = opts.timeout ?? 3e4;
1484
+ this._loadState = { loadFired: false, domContentFired: false, networkIdle: false };
1485
+ if (process.env.XBROWSER_STEALTH !== "off") {
1486
+ try {
1487
+ await this.conn.send(
1488
+ "Page.addScriptToEvaluateOnNewDocument",
1489
+ { source: buildStealthInitScript() },
1490
+ this.sessionId
1491
+ );
1492
+ } catch {
1493
+ }
1494
+ }
1495
+ const result = await this.conn.send(
1496
+ "Page.navigate",
1497
+ { url, referrer: opts.referer },
1498
+ this.sessionId
1499
+ );
1500
+ if (result.errorText) {
1501
+ throw new Error(`Navigation failed: ${result.errorText}`);
1502
+ }
1503
+ if (waitUntil === "commit") {
1504
+ this._url = url;
1505
+ return {
1506
+ status: () => 0,
1507
+ ok: () => false,
1508
+ url: () => url,
1509
+ headers: () => ({})
1510
+ };
1511
+ }
1512
+ await this.waitForLoadState(waitUntil, timeout);
1513
+ this._url = url;
1514
+ const statusCode = 200;
1515
+ const finalUrl = url;
1516
+ const headers = {};
1517
+ return {
1518
+ status: () => statusCode,
1519
+ ok: () => statusCode >= 200 && statusCode < 300,
1520
+ url: () => finalUrl,
1521
+ headers: () => headers
1522
+ };
1523
+ }
1524
+ async goBack(opts = {}) {
1525
+ try {
1526
+ const navHistory = await this.conn.send("Page.getNavigationHistory", void 0, this.sessionId);
1527
+ if (navHistory.currentIndex > 0) {
1528
+ const prevUrl = navHistory.entries[navHistory.currentIndex - 1]?.url;
1529
+ if (prevUrl && prevUrl !== "about:blank") {
1530
+ await this.conn.send("Page.navigate", { url: prevUrl }, this.sessionId);
1531
+ await this.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
1532
+ });
1533
+ this._url = prevUrl;
1534
+ return;
1535
+ }
1536
+ }
1537
+ } catch {
1538
+ }
1539
+ await this.evaluate("() => history.back()");
1540
+ await this.waitForTimeout(3e3);
1541
+ this._url = await this.evaluate("location.href").catch(() => this._url);
1542
+ }
1543
+ async goForward(opts = {}) {
1544
+ try {
1545
+ const navHistory = await this.conn.send("Page.getNavigationHistory", void 0, this.sessionId);
1546
+ if (navHistory.currentIndex < navHistory.entries.length - 1) {
1547
+ const nextUrl = navHistory.entries[navHistory.currentIndex + 1]?.url;
1548
+ if (nextUrl && nextUrl !== "about:blank") {
1549
+ await this.conn.send("Page.navigate", { url: nextUrl }, this.sessionId);
1550
+ await this.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
1551
+ });
1552
+ this._url = nextUrl;
1553
+ return;
1554
+ }
1555
+ }
1556
+ } catch {
1557
+ }
1558
+ await this.evaluate("() => history.forward()");
1559
+ await this.waitForTimeout(3e3);
1560
+ this._url = await this.evaluate("location.href").catch(() => this._url);
1561
+ }
1562
+ async reload(opts = {}) {
1563
+ this._loadState = { loadFired: false, domContentFired: false, networkIdle: false };
1564
+ await this.conn.send("Page.reload", void 0, this.sessionId);
1565
+ await this.waitForLoadState(opts.waitUntil ?? "load", opts.timeout);
1566
+ }
1567
+ async waitForLoadState(state = "load", timeout = 3e4) {
1568
+ if (this._closed) throw new Error("Page is closed");
1569
+ const checkState = () => {
1570
+ switch (state) {
1571
+ case "domcontentloaded":
1572
+ return this._loadState.domContentFired;
1573
+ case "load":
1574
+ return this._loadState.loadFired;
1575
+ case "networkidle":
1576
+ return this._loadState.networkIdle;
1577
+ case "commit":
1578
+ return this._loadState.domContentFired;
1579
+ default:
1580
+ return true;
1581
+ }
1582
+ };
1583
+ if (checkState()) return;
1584
+ return new Promise((resolve, reject) => {
1585
+ const timer = setTimeout(() => {
1586
+ reject(new Error(`waitForLoadState('${state}') timeout after ${timeout}ms`));
1587
+ }, timeout);
1588
+ const check = () => {
1589
+ if (checkState()) {
1590
+ clearTimeout(timer);
1591
+ resolve();
1592
+ } else {
1593
+ setTimeout(check, 50);
1594
+ }
1595
+ };
1596
+ check();
1597
+ });
1598
+ }
1599
+ async waitForTimeout(ms) {
1600
+ await new Promise((resolve) => {
1601
+ const timer = setTimeout(resolve, ms);
1602
+ if (typeof timer.unref === "function") timer.unref();
1603
+ });
1604
+ }
1605
+ async waitForSelector(selector, opts = {}) {
1606
+ const state = opts.state ?? "visible";
1607
+ const timeout = opts.timeout ?? 3e4;
1608
+ const deadline = Date.now() + timeout;
1609
+ while (Date.now() < deadline) {
1610
+ const exists = await this.evaluate(
1611
+ `(function() { const el = ${queryJS(selector)}; return !!el; })()`
1612
+ );
1613
+ if (state === "attached" && exists) return;
1614
+ if (state === "detached" && !exists) return;
1615
+ if (state === "visible" && exists) {
1616
+ const visible = await this.evaluate(
1617
+ `(function() { const el = ${queryJS(selector)}; if (!el) return false; const rect = el.getBoundingClientRect(); const style = window.getComputedStyle(el); return rect.width > 0 && rect.height > 0 && style.visibility !== 'hidden' && style.display !== 'none'; })()`
1618
+ );
1619
+ if (visible) return;
1620
+ }
1621
+ if (state === "hidden") {
1622
+ if (!exists) return;
1623
+ const visible = await this.evaluate(
1624
+ `(function() { const el = ${queryJS(selector)}; if (!el) return false; const rect = el.getBoundingClientRect(); const style = window.getComputedStyle(el); return rect.width > 0 && rect.height > 0 && style.visibility !== 'hidden' && style.display !== 'none'; })()`
1625
+ );
1626
+ if (!visible) return;
1627
+ }
1628
+ await this.waitForTimeout(100);
1629
+ }
1630
+ throw new Error(`waitForSelector('${selector}', state='${state}') timeout after ${timeout}ms`);
1631
+ }
1632
+ async waitForFunction(fn, opts = {}, ...args) {
1633
+ const timeout = opts.timeout ?? 3e4;
1634
+ const polling = opts.polling ?? 100;
1635
+ const deadline = Date.now() + timeout;
1636
+ const fnBody = typeof fn === "function" ? fn.toString() : fn;
1637
+ let lastError = null;
1638
+ while (Date.now() < deadline) {
1639
+ try {
1640
+ const result = await this.evaluate(
1641
+ `(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(", ") : ""})`
1642
+ );
1643
+ if (result) return result;
1644
+ } catch (err) {
1645
+ lastError = err instanceof Error ? err : new Error(errMsg(err));
1646
+ }
1647
+ const pollMs = typeof polling === "number" ? polling : 16;
1648
+ await this.waitForTimeout(pollMs);
1649
+ }
1650
+ const detail = lastError ? `
1651
+ Last error: ${lastError.message}` : "";
1652
+ throw new Error(`waitForFunction timeout after ${timeout}ms${detail}`);
1653
+ }
1654
+ url() {
1655
+ return this._url;
1656
+ }
1657
+ async title() {
1658
+ for (let i = 0; i < 20; i++) {
1659
+ try {
1660
+ this._title = await this.evaluate("document.title");
1661
+ if (this._title) return this._title;
1662
+ } catch {
1663
+ }
1664
+ await new Promise((r) => setTimeout(r, 50));
1665
+ }
1666
+ try {
1667
+ const info = await this._cdpSend("Target.getTargetInfo", { targetId: this._targetId });
1668
+ if (info?.title) {
1669
+ this._title = info.title;
1670
+ return this._title;
1671
+ }
1672
+ } catch {
1673
+ }
1674
+ return this._title;
1675
+ }
1676
+ async content() {
1677
+ return this.evaluate("document.documentElement.outerHTML");
1678
+ }
1679
+ // ── Evaluation ──────────────────────────────────────────────
1680
+ async evaluate(fn, ...args) {
1681
+ if (this._closed) throw new Error("Page is closed");
1682
+ this.conn.send("Page.handleJavaScriptDialog", { accept: false }, this.sessionId).catch(() => {
1683
+ });
1684
+ let expression;
1685
+ if (typeof fn === "string") {
1686
+ expression = fn;
1687
+ } else {
1688
+ const argStr = args.length > 0 ? `...${JSON.stringify(args)}` : "";
1689
+ expression = `(()=>{const __fn=(${fn.toString()});return __fn(${argStr});})()`;
1690
+ }
1691
+ const result = await this.conn.send("Runtime.evaluate", {
1692
+ expression,
1693
+ returnByValue: true,
1694
+ awaitPromise: true
1695
+ }, this.sessionId);
1696
+ if (result.exceptionDetails) {
1697
+ const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.exception?.value ?? result.exceptionDetails.text;
1698
+ throw new Error(`${detail}`);
1699
+ }
1700
+ return result.result?.value;
1701
+ }
1702
+ /**
1703
+ * 在指定 iframe 上下文中执行表达式(攻防 D16 能力建设,2026-08-19)。
1704
+ *
1705
+ * 双路径:
1706
+ * 1. 同进程 iframe —— Runtime.enable 收集 executionContextCreated,
1707
+ * 找到目标 frameId 的 contextId,用 contextId 定向执行;
1708
+ * 2. 跨域 OOPIF(独立 target)—— Target.setAutoAttach(flatten) 监听
1709
+ * attachedToTarget 中 type==='iframe' 的会话,用其 sessionId 执行。
1710
+ *
1711
+ * 这绕过了页面同源策略(那是页面 JS 的约束,CDP 是调试通道)——
1712
+ * 支付窗/验证码/第三方嵌入内容的读写都靠它。
1713
+ */
1714
+ async evaluateInFrame(urlIncludes, expression) {
1715
+ if (this._closed) throw new Error("Page is closed");
1716
+ const evalIn = async (sessionId, contextId) => {
1717
+ const params = { expression, returnByValue: true, awaitPromise: true };
1718
+ if (contextId !== void 0) params.contextId = contextId;
1719
+ const result = await this.conn.send("Runtime.evaluate", params, sessionId);
1720
+ if (result.exceptionDetails) {
1721
+ const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.exception?.value ?? result.exceptionDetails.text;
1722
+ throw new Error(`[frame ${urlIncludes}] ${detail}`);
1723
+ }
1724
+ return result.result?.value;
1725
+ };
1726
+ try {
1727
+ const tg = await this.conn.send("Target.getTargets", void 0);
1728
+ const hit2 = (tg.targetInfos || []).find((t) => t.type === "iframe" && (t.url || "").includes(urlIncludes));
1729
+ if (hit2) {
1730
+ const att = await this.conn.send("Target.attachToTarget", { targetId: hit2.targetId, flatten: true });
1731
+ return evalIn(att.sessionId);
1732
+ }
1733
+ } catch {
1734
+ }
1735
+ const tree = await this.conn.send("Page.getFrameTree", void 0, this.sessionId);
1736
+ const all = [];
1737
+ const walk = (node) => {
1738
+ all.push({ id: node.frame.id, url: node.frame.url });
1739
+ for (const child of node.childFrames || []) walk(child);
1740
+ };
1741
+ walk(tree.frameTree);
1742
+ const mainId = tree.frameTree?.frame?.id;
1743
+ const target = all.find((f) => f.id !== mainId && f.url.includes(urlIncludes));
1744
+ if (target) {
1745
+ const contexts = [];
1746
+ const onCtx = (raw) => {
1747
+ const c = raw?.context;
1748
+ if (c?.id && c?.auxData?.frameId) contexts.push({ id: c.id, frameId: c.auxData.frameId });
1749
+ };
1750
+ this.conn.on("Runtime.executionContextCreated", onCtx);
1751
+ try {
1752
+ await this.conn.send("Runtime.enable", void 0, this.sessionId).catch(() => {
1753
+ });
1754
+ await new Promise((r) => setTimeout(r, 400));
1755
+ } finally {
1756
+ this.conn.off("Runtime.executionContextCreated", onCtx);
1757
+ }
1758
+ const ctx = contexts.find((c) => c.frameId === target.id);
1759
+ if (ctx) return evalIn(this.sessionId, ctx.id);
1760
+ }
1761
+ const attached = [];
1762
+ const onAttach = (raw) => {
1763
+ const ev = raw;
1764
+ if (ev?.sessionId && ev.targetInfo?.type === "iframe") {
1765
+ attached.push({ sessionId: ev.sessionId, url: ev.targetInfo.url || "" });
1766
+ }
1767
+ };
1768
+ this.conn.on("Target.attachedToTarget", onAttach);
1769
+ try {
1770
+ await this.conn.send("Target.setAutoAttach", {
1771
+ autoAttach: true,
1772
+ waitForDebuggerOnStart: false,
1773
+ flatten: true
1774
+ }, this.sessionId);
1775
+ await new Promise((r) => setTimeout(r, 600));
1776
+ } finally {
1777
+ this.conn.off("Target.attachedToTarget", onAttach);
1778
+ this.conn.send("Target.setAutoAttach", { autoAttach: false, waitForDebuggerOnStart: false, flatten: true }, this.sessionId).catch(() => {
1779
+ });
1780
+ }
1781
+ const hit = attached.find((a) => a.url.includes(urlIncludes));
1782
+ if (!hit) {
1783
+ 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`);
1784
+ }
1785
+ return evalIn(hit.sessionId);
1786
+ }
1787
+ /** evaluateHandle — evaluates fn and returns a handle for element bounding box */
1788
+ async evaluateHandle(fn, ...args) {
1789
+ let expression;
1790
+ if (typeof fn === "string") {
1791
+ expression = fn;
1792
+ } else {
1793
+ const argStr = args.length > 0 ? `...${JSON.stringify(args)}` : "";
1794
+ 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;})()`;
1795
+ }
1796
+ const result = await this.conn.send("Runtime.evaluate", { expression, returnByValue: true }).catch(() => ({ result: { value: null } }));
1797
+ let box = null;
1798
+ try {
1799
+ box = JSON.parse(result.result?.value);
1800
+ } catch {
1801
+ }
1802
+ return {
1803
+ asElement: () => box ? { boundingBox: async () => box } : null
1804
+ };
1805
+ }
1806
+ async $eval(selector, fn, ...args) {
1807
+ const fnBody = typeof fn === "function" ? fn.toString() : fn;
1808
+ const selJSON = JSON.stringify(selector);
1809
+ const xpathPrefix = selector.startsWith("xpath=") ? JSON.stringify(selector.slice(6)) : "null";
1810
+ return this.evaluate(
1811
+ `(function(sel, xpathExpr, fnStr, ...evalArgs) {
1812
+ const el = xpathExpr
1813
+ ? document.evaluate(xpathExpr, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
1814
+ : document.querySelector(sel);
1815
+ if (!el) throw new Error('No element found for selector: ' + sel);
1816
+ const fn = new Function('return ' + fnStr)();
1817
+ return fn(el, ...evalArgs);
1818
+ })(${selJSON}, ${xpathPrefix}, ${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
1819
+ );
1820
+ }
1821
+ async $$eval(selector, fn, ...args) {
1822
+ const fnBody = typeof fn === "function" ? fn.toString() : fn;
1823
+ const selJSON = JSON.stringify(selector);
1824
+ const xpathPrefix = selector.startsWith("xpath=") ? JSON.stringify(selector.slice(6)) : "null";
1825
+ return this.evaluate(
1826
+ `(function(sel, xpathExpr, fnStr, ...evalArgs) {
1827
+ const els = xpathExpr
1828
+ ? (() => { 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; })()
1829
+ : Array.from(document.querySelectorAll(sel));
1830
+ const fn = new Function('return ' + fnStr)();
1831
+ return fn(els, ...evalArgs);
1832
+ })(${selJSON}, ${xpathPrefix}, ${JSON.stringify(fnBody)}${args.length > 0 ? ", " + args.map((a) => JSON.stringify(a)).join(", ") : ""})`
1833
+ );
1834
+ }
1835
+ // ── Locator ─────────────────────────────────────────────────
1836
+ locator(selector) {
1837
+ return new XBLocatorImpl(this, selector);
1838
+ }
1839
+ getByText(text, opts) {
1840
+ const escaped = text.replace(/'/g, "\\'");
1841
+ if (opts?.exact) {
1842
+ return this.locator(`xpath=//*[normalize-space(text())='${escaped}']`);
1843
+ }
1844
+ return this.locator(`xpath=//*[contains(text(),'${escaped}')]`);
1845
+ }
1846
+ getByRole(role, opts) {
1847
+ const ROLE_TO_TAGS = {
1848
+ button: ["button"],
1849
+ link: ["a[href]"],
1850
+ heading: ["h1", "h2", "h3", "h4", "h5", "h6"],
1851
+ textbox: ['input[type="text"]', "input:not([type])", "textarea"],
1852
+ checkbox: ['input[type="checkbox"]'],
1853
+ radio: ['input[type="radio"]'],
1854
+ searchbox: ['input[type="search"]'],
1855
+ combobox: ["select"],
1856
+ img: ["img"],
1857
+ navigation: ["nav"],
1858
+ article: ["article"],
1859
+ banner: ["header"],
1860
+ contentinfo: ["footer"],
1861
+ main: ["main"],
1862
+ complementary: ["aside"]
1863
+ };
1864
+ const tags = ROLE_TO_TAGS[role] || [];
1865
+ const tagSel = tags.length > 0 ? tags.join(",") + "," : "";
1866
+ let sel = `${tagSel}[role="${role}"]`;
1867
+ if (opts?.name) {
1868
+ sel += opts.exact ? `[aria-label="${opts.name}"]` : `[aria-label*="${opts.name}"]`;
1869
+ }
1870
+ return this.locator(sel);
1871
+ }
1872
+ getByLabel(label, opts) {
1873
+ const escaped = label.replace(/'/g, "\\'");
1874
+ const sel = opts?.exact ? `xpath=//*[@aria-label='${escaped}' or @id=//label[normalize-space(text())='${escaped}']/@for]` : `xpath=//*[contains(@aria-label,'${escaped}') or @id=//label[contains(text(),'${escaped}')]/@for]`;
1875
+ return this.locator(sel);
1876
+ }
1877
+ getByPlaceholder(text, opts) {
1878
+ return this.locator(
1879
+ opts?.exact ? `[placeholder="${text}"]` : `[placeholder*="${text}"]`
1880
+ );
1881
+ }
1882
+ getByTestId(id) {
1883
+ return this.locator(`[data-testid="${id}"]`);
1884
+ }
1885
+ getByAltText(text, opts) {
1886
+ return this.locator(opts?.exact ? `[alt="${text}"]` : `[alt*="${text}"]`);
1887
+ }
1888
+ getByTitle(title, opts) {
1889
+ return this.locator(
1890
+ opts?.exact ? `[title="${title}"]` : `[title*="${title}"]`
1891
+ );
1892
+ }
1893
+ // ── Interaction shortcuts ───────────────────────────────────
1894
+ async click(selector, opts = {}) {
1895
+ await this.locator(selector).click(opts);
1896
+ }
1897
+ async dblclick(selector, opts = {}) {
1898
+ await this.locator(selector).click({ ...opts, clickCount: 2 });
1899
+ }
1900
+ async fill(selector, value, opts = {}) {
1901
+ await this.locator(selector).fill(value, opts);
1902
+ }
1903
+ async press(selector, key, opts) {
1904
+ await this.locator(selector).press(key, opts);
1905
+ }
1906
+ async hover(selector, opts) {
1907
+ await this.locator(selector).hover(opts);
1908
+ }
1909
+ async type(selector, text, opts = {}) {
1910
+ await this.locator(selector).type(text, opts);
1911
+ }
1912
+ async check(selector, opts) {
1913
+ await this.locator(selector).check(opts);
1914
+ }
1915
+ async uncheck(selector, opts) {
1916
+ await this.locator(selector).uncheck(opts);
1917
+ }
1918
+ async selectOption(selector, value) {
1919
+ return this.locator(selector).selectOption(value);
1920
+ }
1921
+ // ── Convenience selectors ───────────────────────────────────
1922
+ async textContent(selector) {
1923
+ return this.evaluate(
1924
+ `(function() { const el = ${queryJS(selector)}; return el?.textContent ?? null; })()`
1925
+ );
1926
+ }
1927
+ async innerText(selector) {
1928
+ return this.evaluate(
1929
+ `(function() { const el = ${queryJS(selector)}; if (!el) throw new Error('Element not found'); return el.innerText; })()`
1930
+ );
1931
+ }
1932
+ async innerHTML(selector) {
1933
+ return this.evaluate(
1934
+ `(function() { const el = ${queryJS(selector)}; if (!el) throw new Error('Element not found'); return el.innerHTML; })()`
1935
+ );
1936
+ }
1937
+ async getAttribute(selector, name) {
1938
+ return this.evaluate(
1939
+ `(function() { const el = ${queryJS(selector)}; return el?.getAttribute(${JSON.stringify(name)}) ?? null; })()`
1940
+ );
1941
+ }
1942
+ // ── Query ───────────────────────────────────────────────────
1943
+ async $(selector) {
1944
+ const nodeId = await this.querySelector(selector);
1945
+ if (!nodeId) return null;
1946
+ return new XBElementHandleImpl(this, nodeId);
1947
+ }
1948
+ async $$(selector) {
1949
+ const nodeIds = await this.querySelectorAll(selector);
1950
+ return nodeIds.map((id) => new XBElementHandleImpl(this, id));
1951
+ }
1952
+ // ── Screen ──────────────────────────────────────────────────
1953
+ async screenshot(opts = {}) {
1954
+ const params = {
1955
+ format: opts.type ?? "png"
1956
+ };
1957
+ if (opts.quality !== void 0 && (opts.type === "jpeg" || !opts.type && opts.quality)) {
1958
+ params.quality = opts.quality;
1959
+ }
1960
+ if (opts.fullPage) {
1961
+ params.captureBeyondViewport = true;
1962
+ }
1963
+ if (opts.clip) {
1964
+ const clip = {
1965
+ x: Math.round(opts.clip.x),
1966
+ y: Math.round(opts.clip.y),
1967
+ width: Math.round(Math.max(1, opts.clip.width)),
1968
+ height: Math.round(Math.max(1, opts.clip.height)),
1969
+ scale: 1
1970
+ };
1971
+ params.clip = clip;
1972
+ }
1973
+ if (opts.omitBackground) {
1974
+ params.omitBackground = true;
1975
+ }
1976
+ const result = await this.conn.send(
1977
+ "Page.captureScreenshot",
1978
+ params,
1979
+ this.sessionId
1980
+ );
1981
+ return Buffer.from(result.data, "base64");
1982
+ }
1983
+ async pdf(opts = {}) {
1984
+ const params = {};
1985
+ if (opts.landscape !== void 0) params.landscape = opts.landscape;
1986
+ if (opts.printBackground !== void 0) params.printBackground = opts.printBackground;
1987
+ if (opts.scale !== void 0) params.scale = opts.scale;
1988
+ if (opts.format) params.paperFormat = opts.format;
1989
+ if (opts.preferCSSPageSize !== void 0) params.preferCSSPageSize = opts.preferCSSPageSize;
1990
+ if (opts.margin) {
1991
+ if (opts.margin.top) params.marginTop = parseFloat(opts.margin.top);
1992
+ if (opts.margin.bottom) params.marginBottom = parseFloat(opts.margin.bottom);
1993
+ if (opts.margin.left) params.marginLeft = parseFloat(opts.margin.left);
1994
+ if (opts.margin.right) params.marginRight = parseFloat(opts.margin.right);
1995
+ }
1996
+ const result = await this.conn.send("Page.printToPDF", params, this.sessionId);
1997
+ return Buffer.from(result.data, "base64");
1998
+ }
1999
+ viewportSize() {
2000
+ return this._viewportSize ?? null;
2001
+ }
2002
+ async setViewportSize(size) {
2003
+ await this.conn.send(
2004
+ "Emulation.setDeviceMetricsOverride",
2005
+ {
2006
+ width: size.width,
2007
+ height: size.height,
2008
+ deviceScaleFactor: 1,
2009
+ mobile: false
2010
+ },
2011
+ this.sessionId
2012
+ );
2013
+ this._viewportSize = size;
2014
+ }
2015
+ // ── Scripts ─────────────────────────────────────────────────
2016
+ async addInitScript(script) {
2017
+ await this.conn.send(
2018
+ "Page.addScriptToEvaluateOnNewDocument",
2019
+ { source: script },
2020
+ this.sessionId
2021
+ );
2022
+ }
2023
+ /** Internal: set user agent */
2024
+ async _setUserAgent(userAgent) {
2025
+ await this.conn.send(
2026
+ "Network.setUserAgentOverride",
2027
+ { userAgent },
2028
+ this.sessionId
2029
+ );
2030
+ }
2031
+ /** Internal: set extra HTTP headers */
2032
+ async _setExtraHTTPHeaders(headers) {
2033
+ await this.setExtraHTTPHeaders(headers);
2034
+ }
2035
+ async bringToFront() {
2036
+ await this.conn.send("Page.bringToFront", void 0, this.sessionId);
2037
+ }
2038
+ async setExtraHTTPHeaders(headers) {
2039
+ await this.conn.send("Network.setExtraHTTPHeaders", { headers }, this.sessionId);
2040
+ }
2041
+ // ── Events ──────────────────────────────────────────────────
2042
+ on(event, handler) {
2043
+ this._emitter.on(event, handler);
2044
+ }
2045
+ off(event, handler) {
2046
+ this._emitter.off(event, handler);
2047
+ }
2048
+ /**
2049
+ * Wait for a one-shot event (Playwright-compatible subset).
2050
+ * Used to listen for 'filechooser', 'dialog', 'popup', 'framenavigated', etc.
2051
+ */
2052
+ async waitForEvent(event, opts = {}) {
2053
+ const timeout = opts.timeout ?? 3e4;
2054
+ return new Promise((resolve, reject) => {
2055
+ const timer = setTimeout(() => {
2056
+ this._emitter.off(event, handler);
2057
+ reject(new Error(`waitForEvent('${event}') timeout after ${timeout}ms`));
2058
+ }, timeout);
2059
+ const handler = (...args) => {
2060
+ if (opts.predicate && !opts.predicate(...args)) return;
2061
+ clearTimeout(timer);
2062
+ this._emitter.off(event, handler);
2063
+ resolve(args.length === 1 ? args[0] : args);
2064
+ };
2065
+ this._emitter.on(event, handler);
2066
+ });
2067
+ }
2068
+ // ── Lifecycle ───────────────────────────────────────────────
2069
+ async close() {
2070
+ if (this._closed) return;
2071
+ this._closed = true;
2072
+ if (this.networkIdleTimer) {
2073
+ clearTimeout(this.networkIdleTimer);
2074
+ this.networkIdleTimer = null;
2075
+ }
2076
+ for (const unsub of this._subscriptions) {
2077
+ unsub();
2078
+ }
2079
+ this._subscriptions = [];
2080
+ await this._browserImpl._closeTarget(this._targetId).catch(() => {
2081
+ });
2082
+ await this._browserImpl._detachFromTarget(this.sessionId).catch(() => {
2083
+ });
2084
+ this._emitter.emit("close");
2085
+ }
2086
+ isClosed() {
2087
+ return this._closed;
2088
+ }
2089
+ context() {
2090
+ return this._contextImpl;
2091
+ }
2092
+ browser() {
2093
+ return this._browserImpl;
2094
+ }
2095
+ mainFrame() {
2096
+ return {
2097
+ url: () => this._url,
2098
+ name: () => "",
2099
+ isDetached: () => this._closed,
2100
+ page: () => this,
2101
+ evaluate: (fn, ...args) => this.evaluate(fn, ...args),
2102
+ $: (sel) => this.$(sel),
2103
+ $$: (sel) => this.$$(sel)
2104
+ };
2105
+ }
2106
+ frames() {
2107
+ return [this.mainFrame()];
2108
+ }
2109
+ /**
2110
+ * Discover all frames (main + iframes) via CDP Page.getFrameTree.
2111
+ * This is async because CDP doesn't maintain a frame list client-side.
2112
+ */
2113
+ async discoverFrames() {
2114
+ try {
2115
+ const result = await this.conn.send("Page.getFrameTree", void 0, this.sessionId);
2116
+ const frames = [];
2117
+ const collect = (node) => {
2118
+ const frame = {
2119
+ name: () => node.frame.name || "",
2120
+ url: () => node.frame.url,
2121
+ isDetached: () => false,
2122
+ page: () => this,
2123
+ evaluate: (fn, ...args) => this.evaluate(fn, ...args),
2124
+ $: (sel) => this.$(sel),
2125
+ $$: (sel) => this.$$(sel)
2126
+ };
2127
+ frames.push(frame);
2128
+ for (const child of node.childFrames || []) {
2129
+ collect({ frame: child.frame, childFrames: [] });
2130
+ }
2131
+ };
2132
+ collect(result.frameTree);
2133
+ return frames;
2134
+ } catch {
2135
+ return [this.mainFrame()];
2136
+ }
2137
+ }
2138
+ // ── CDP helpers exposed for locator/element ─────────────────
2139
+ /** Query a single element, returns CDP nodeId or 0 if not found */
2140
+ async querySelector(selector) {
2141
+ if (selector.startsWith("xpath=")) {
2142
+ const found = await this.evaluate(`
2143
+ (() => { const el = ${queryJS(selector)}; return !!el; })()
2144
+ `).catch(() => false);
2145
+ if (!found) return 0;
2146
+ try {
2147
+ const search = await this.conn.send(
2148
+ "DOM.performSearch",
2149
+ { query: selector.slice(6) },
2150
+ this.sessionId
2151
+ );
2152
+ if (search.nodeId) return search.nodeId;
2153
+ } catch {
2154
+ }
2155
+ return 1;
2156
+ }
2157
+ const withTimeout = (p, ms) => Promise.race([p, new Promise((r) => setTimeout(() => r(null), ms))]);
2158
+ const doc = await withTimeout(
2159
+ this.conn.send("DOM.getDocument", { depth: 0 }, this.sessionId),
2160
+ 8e3
2161
+ );
2162
+ if (!doc) return 0;
2163
+ const result = await withTimeout(
2164
+ this.conn.send(
2165
+ "DOM.querySelector",
2166
+ { nodeId: doc.root.nodeId, selector },
2167
+ this.sessionId
2168
+ ),
2169
+ 8e3
2170
+ );
2171
+ if (!result) return 0;
2172
+ return result.nodeId;
2173
+ }
2174
+ /** Query all matching elements, returns array of CDP nodeIds */
2175
+ async querySelectorAll(selector) {
2176
+ const doc = await this.conn.send(
2177
+ "DOM.getDocument",
2178
+ { depth: 0 },
2179
+ this.sessionId
2180
+ );
2181
+ const result = await this.conn.send(
2182
+ "DOM.querySelectorAll",
2183
+ { nodeId: doc.root.nodeId, selector },
2184
+ this.sessionId
2185
+ );
2186
+ return result.nodeIds ?? [];
2187
+ }
2188
+ /** Resolve a CDP nodeId to a RemoteObject for evaluate */
2189
+ async resolveNode(nodeId) {
2190
+ const result = await this.conn.send(
2191
+ "DOM.resolveNode",
2192
+ { nodeId },
2193
+ this.sessionId
2194
+ );
2195
+ return result.object.objectId;
2196
+ }
2197
+ /** Get the box model for a nodeId */
2198
+ async getBoxModel(nodeId) {
2199
+ try {
2200
+ const result = await this.conn.send("DOM.getBoxModel", { nodeId }, this.sessionId);
2201
+ const c = result.model?.content;
2202
+ if (!c || c.length < 8) return null;
2203
+ const x1 = c[0];
2204
+ const y1 = c[1];
2205
+ const x2 = c[4];
2206
+ const y2 = c[5];
2207
+ return {
2208
+ x: Math.min(x1, x2),
2209
+ y: Math.min(y1, y2),
2210
+ width: Math.abs(x2 - x1),
2211
+ height: Math.abs(y2 - y1)
2212
+ };
2213
+ } catch {
2214
+ return null;
2215
+ }
2216
+ }
2217
+ /** Call a function on a RemoteObject */
2218
+ async callFunctionOn(objectId, functionDeclaration, args = []) {
2219
+ const result = await this.conn.send("Runtime.callFunctionOn", {
2220
+ objectId,
2221
+ functionDeclaration,
2222
+ arguments: args.map((a) => ({ value: a })),
2223
+ returnByValue: true
2224
+ }, this.sessionId);
2225
+ if (result.exceptionDetails) {
2226
+ throw new Error(`CallFunctionOn error: ${result.exceptionDetails.text}`);
2227
+ }
2228
+ return result.result?.value;
2229
+ }
2230
+ /** Send a CDP command scoped to this page's session */
2231
+ async _cdpSend(method, params) {
2232
+ return this.conn.send(method, params, this.sessionId);
2233
+ }
2234
+ /**
2235
+ * 开启/关闭原生文件选择框拦截(CDP stateful 开关)。
2236
+ *
2237
+ * - enabled=true(执行期默认):点击上传按钮时不弹系统文件框,改发 Page.fileChooserOpened 事件,
2238
+ * page 的 'filechooser' 监听器拿到 chooser 后用 setFiles/setInputFiles 注入文件。
2239
+ * - enabled=false(录制期默认):真实文件选择框正常弹出,用户手动选文件;
2240
+ * 前端 input[type=file] 的 change 事件由 action signal 脚本捕获记录。
2241
+ *
2242
+ * 可多次调用切换状态(CDP 协议是 stateful 的)。
2243
+ */
2244
+ async setFileDialogInterception(enabled) {
2245
+ await this.conn.send("Page.setInterceptFileChooserDialog", { enabled }, this.sessionId).catch((e) => console.error("[XBPage] setInterceptFileChooserDialog failed:", errMsg(e)));
2246
+ }
2247
+ /** Subscribe to a CDP event on this page's session. Returns unsubscribe function. */
2248
+ _subscribe(event, handler) {
2249
+ return this.conn.subscribe(event, this.sessionId, handler);
2250
+ }
2251
+ // ── Private: Event Setup ────────────────────────────────────
2252
+ setupPageEvents() {
2253
+ this._subscriptions.push(
2254
+ this.conn.subscribe("Page.frameNavigated", this.sessionId, (params) => {
2255
+ const p = params;
2256
+ if (p.frame) {
2257
+ this._url = p.frame.url;
2258
+ }
2259
+ this._emit("framenavigated", this.mainFrame());
2260
+ })
2261
+ );
2262
+ this._subscriptions.push(
2263
+ this.conn.subscribe("Page.loadEventFired", this.sessionId, () => {
2264
+ this._loadState.loadFired = true;
2265
+ })
2266
+ );
2267
+ this._subscriptions.push(
2268
+ this.conn.subscribe("Page.domContentEventFired", this.sessionId, () => {
2269
+ this._loadState.domContentFired = true;
2270
+ })
2271
+ );
2272
+ this._subscriptions.push(
2273
+ this.conn.subscribe("Page.javascriptDialogOpening", this.sessionId, (params) => {
2274
+ const p = params;
2275
+ const dialog = {
2276
+ type: p.type,
2277
+ message: () => p.message,
2278
+ defaultValue: () => p.defaultValue,
2279
+ accept: async (text) => {
2280
+ await this.conn.send("Page.handleJavaScriptDialog", {
2281
+ accept: true,
2282
+ promptText: text
2283
+ }, this.sessionId);
2284
+ },
2285
+ dismiss: async () => {
2286
+ await this.conn.send("Page.handleJavaScriptDialog", {
2287
+ accept: false
2288
+ }, this.sessionId);
2289
+ }
2290
+ };
2291
+ this._emit("dialog", dialog);
2292
+ setTimeout(() => {
2293
+ this.conn.send("Page.handleJavaScriptDialog", { accept: false }, this.sessionId).catch(() => {
2294
+ });
2295
+ }, 0);
2296
+ })
2297
+ );
2298
+ this._subscriptions.push(
2299
+ this.conn.subscribe("Page.fileChooserOpened", this.sessionId, async (params) => {
2300
+ const p = params;
2301
+ let selector = "";
2302
+ try {
2303
+ const result = await this.conn.send("DOM.describeNode", { backendNodeId: p.backendNodeId }, this.sessionId);
2304
+ const attrs = result.node?.attributes || [];
2305
+ const idIdx = attrs.indexOf("id");
2306
+ if (idIdx >= 0) selector = "#" + attrs[idIdx + 1];
2307
+ } catch {
2308
+ }
2309
+ if (!selector) {
2310
+ try {
2311
+ const result = await this.conn.send("DOM.resolveNode", { backendNodeId: p.backendNodeId }, this.sessionId);
2312
+ const evalResult = await this.conn.send("Runtime.callFunctionOn", {
2313
+ objectId: result.objectId,
2314
+ functionDeclaration: 'function() { return this.id || this.name || "" }',
2315
+ returnByValue: true
2316
+ }, this.sessionId);
2317
+ if (evalResult.result?.value) selector = "#" + evalResult.result.value;
2318
+ } catch {
2319
+ }
2320
+ }
2321
+ const fileChooser = {
2322
+ selector,
2323
+ isMultiple: p.mode === "selectMultiple",
2324
+ setFiles: async (files) => {
2325
+ const fileArray = Array.isArray(files) ? files : [files];
2326
+ await this.setInputFiles(selector || 'input[type="file"]', fileArray);
2327
+ }
2328
+ };
2329
+ this._emit("filechooser", fileChooser);
2330
+ })
2331
+ );
2332
+ }
2333
+ setupNetworkEvents() {
2334
+ this._subscriptions.push(
2335
+ this.conn.subscribe("Network.requestWillBeSent", this.sessionId, (params) => {
2336
+ const p = params;
2337
+ this.inflightRequests.add(p.requestId);
2338
+ this._storeNetworkRequest(p.requestId, {
2339
+ url: p.request.url,
2340
+ method: p.request.method,
2341
+ headers: p.request.headers,
2342
+ postData: p.request.postData ?? null,
2343
+ resourceType: p.type
2344
+ });
2345
+ this._emit("request", createXBRequest(
2346
+ null,
2347
+ {
2348
+ requestId: p.requestId,
2349
+ url: p.request.url,
2350
+ method: p.request.method,
2351
+ headers: p.request.headers,
2352
+ postData: p.request.postData ?? null,
2353
+ resourceType: p.type
2354
+ }
2355
+ ));
2356
+ this.checkNetworkIdle();
2357
+ })
2358
+ );
2359
+ this._subscriptions.push(
2360
+ this.conn.subscribe("Network.responseReceived", this.sessionId, (params) => {
2361
+ const p = params;
2362
+ this._storeNetworkResponse(p.requestId, {
2363
+ status: p.response.status,
2364
+ url: p.response.url,
2365
+ headers: p.response.headers
2366
+ });
2367
+ this._emit("response", createXBResponse(
2368
+ { requestId: p.requestId, status: p.response.status, url: p.response.url, headers: p.response.headers },
2369
+ this.conn,
2370
+ this.sessionId
2371
+ ));
2372
+ })
2373
+ );
2374
+ this._subscriptions.push(
2375
+ this.conn.subscribe("Network.loadingFinished", this.sessionId, (params) => {
2376
+ const p = params;
2377
+ this.inflightRequests.delete(p.requestId);
2378
+ this._emit("requestfinished", p);
2379
+ this.checkNetworkIdle();
2380
+ })
2381
+ );
2382
+ this._subscriptions.push(
2383
+ this.conn.subscribe("Network.loadingFailed", this.sessionId, (params) => {
2384
+ const p = params;
2385
+ this.inflightRequests.delete(p.requestId);
2386
+ this.checkNetworkIdle();
2387
+ })
2388
+ );
2389
+ }
2390
+ setupConsoleEvents() {
2391
+ this._subscriptions.push(
2392
+ this.conn.subscribe("Runtime.consoleAPICalled", this.sessionId, (params) => {
2393
+ const p = params;
2394
+ const text = p.args.map((a) => {
2395
+ if (a.value !== void 0) return String(a.value);
2396
+ return a.description ?? "";
2397
+ }).join(" ");
2398
+ const location = p.stackTrace?.callFrames?.[0] ? {
2399
+ url: p.stackTrace.callFrames[0].url,
2400
+ lineNumber: p.stackTrace.callFrames[0].lineNumber,
2401
+ columnNumber: p.stackTrace.callFrames[0].columnNumber
2402
+ } : { url: "", lineNumber: 0, columnNumber: 0 };
2403
+ const msg = {
2404
+ type: () => p.type,
2405
+ text: () => text,
2406
+ location: () => location
2407
+ };
2408
+ this._emit("console", msg);
2409
+ })
2410
+ );
2411
+ }
2412
+ checkNetworkIdle() {
2413
+ if (this.inflightRequests.size === 0) {
2414
+ if (this.networkIdleTimer) clearTimeout(this.networkIdleTimer);
2415
+ this.networkIdleTimer = setTimeout(() => {
2416
+ if (this.inflightRequests.size === 0) {
2417
+ this._loadState.networkIdle = true;
2418
+ if (this.networkIdleResolve) {
2419
+ this.networkIdleResolve();
2420
+ this.networkIdleResolve = null;
2421
+ }
2422
+ }
2423
+ }, _XBPageImpl.NETWORK_IDLE_MS);
2424
+ } else {
2425
+ if (this.networkIdleTimer) {
2426
+ clearTimeout(this.networkIdleTimer);
2427
+ this.networkIdleTimer = null;
2428
+ }
2429
+ }
2430
+ }
2431
+ // ── Network Data Store (for waitForResponse/waitForRequest) ──
2432
+ _networkResponses = /* @__PURE__ */ new Map();
2433
+ _networkRequests = /* @__PURE__ */ new Map();
2434
+ _routeHandlers = [];
2435
+ _interceptionEnabled = false;
2436
+ /** Store network data — called by browser.ts installNetworkCapture or internal event handlers */
2437
+ _storeNetworkRequest(requestId, data) {
2438
+ this._networkRequests.set(requestId, { requestId, ...data });
2439
+ }
2440
+ _storeNetworkResponse(requestId, data) {
2441
+ this._networkResponses.set(requestId, { requestId, ...data });
2442
+ }
2443
+ // ── waitForResponse ─────────────────────────────────────────
2444
+ async waitForResponse(urlOrPredicate, opts = {}) {
2445
+ const timeout = opts.timeout ?? 3e4;
2446
+ const predicate = createResponsePredicate(urlOrPredicate);
2447
+ for (const [, data] of this._networkResponses) {
2448
+ const response = createXBResponse(data, this.conn, this.sessionId);
2449
+ if (predicate(response)) return response;
2450
+ }
2451
+ return new Promise((resolve, reject) => {
2452
+ const timer = setTimeout(() => {
2453
+ this._emitter.removeListener("response", handler);
2454
+ reject(new Error(`waitForResponse timed out after ${timeout}ms`));
2455
+ }, timeout);
2456
+ const handler = (params) => {
2457
+ let response;
2458
+ const respObj = params;
2459
+ if (respObj.response) {
2460
+ const data = {
2461
+ requestId: respObj.requestId || "",
2462
+ status: respObj.response.status || 0,
2463
+ url: respObj.response.url || "",
2464
+ headers: respObj.response.headers || {}
2465
+ };
2466
+ response = createXBResponse(data, this.conn, this.sessionId);
2467
+ } else if (typeof params.status === "function") {
2468
+ response = params;
2469
+ } else {
2470
+ return;
2471
+ }
2472
+ if (predicate(response)) {
2473
+ clearTimeout(timer);
2474
+ this._emitter.removeListener("response", handler);
2475
+ resolve(response);
2476
+ }
2477
+ };
2478
+ this._emitter.on("response", handler);
2479
+ });
2480
+ }
2481
+ // ── waitForRequest ──────────────────────────────────────────
2482
+ async waitForRequest(urlOrPredicate, opts = {}) {
2483
+ const timeout = opts.timeout ?? 3e4;
2484
+ const predicate = createRequestPredicate(urlOrPredicate);
2485
+ for (const [, data] of this._networkRequests) {
2486
+ const request = createXBRequest(this, data);
2487
+ if (predicate(request)) return request;
2488
+ }
2489
+ return new Promise((resolve, reject) => {
2490
+ const timer = setTimeout(() => {
2491
+ this._emitter.removeListener("request", handler);
2492
+ reject(new Error(`waitForRequest timed out after ${timeout}ms`));
2493
+ }, timeout);
2494
+ const handler = (params) => {
2495
+ let request;
2496
+ const reqObj = params;
2497
+ if (reqObj.request) {
2498
+ request = createXBRequest(this, {
2499
+ requestId: reqObj.requestId || "",
2500
+ url: reqObj.request.url || "",
2501
+ method: reqObj.request.method || "",
2502
+ headers: reqObj.request.headers || {},
2503
+ postData: reqObj.request.postData ?? null,
2504
+ resourceType: reqObj.type || ""
2505
+ });
2506
+ } else if (typeof params.url === "function") {
2507
+ request = params;
2508
+ } else {
2509
+ return;
2510
+ }
2511
+ if (predicate(request)) {
2512
+ clearTimeout(timer);
2513
+ this._emitter.removeListener("request", handler);
2514
+ resolve(request);
2515
+ }
2516
+ };
2517
+ this._emitter.on("request", handler);
2518
+ });
2519
+ }
2520
+ // ── waitForURL ──────────────────────────────────────────────
2521
+ async waitForURL(url, opts = {}) {
2522
+ const timeout = opts.timeout ?? 3e4;
2523
+ const checkFn = typeof url === "function" ? url : typeof url === "string" ? (current) => matchGlob(url, current) : (current) => url.test(current);
2524
+ if (checkFn(this._url)) return;
2525
+ return new Promise((resolve, reject) => {
2526
+ const timer = setTimeout(() => {
2527
+ this._emitter.removeListener("framenavigated", handler);
2528
+ reject(new Error(`waitForURL timed out after ${timeout}ms`));
2529
+ }, timeout);
2530
+ const handler = () => {
2531
+ if (checkFn(this._url)) {
2532
+ clearTimeout(timer);
2533
+ this._emitter.removeListener("framenavigated", handler);
2534
+ resolve();
2535
+ }
2536
+ };
2537
+ this._emitter.on("framenavigated", handler);
2538
+ });
2539
+ }
2540
+ // ── route / unroute ─────────────────────────────────────────
2541
+ async route(url, handler) {
2542
+ const regex = typeof url === "string" ? globToRegex(url) : url;
2543
+ this._routeHandlers.push({ pattern: String(url), regex, handler });
2544
+ if (!this._interceptionEnabled) {
2545
+ this._interceptionEnabled = true;
2546
+ await this.conn.send("Fetch.enable", {
2547
+ patterns: [{ urlPattern: "*", requestStage: "Request" }]
2548
+ }, this.sessionId);
2549
+ this._subscriptions.push(
2550
+ this.conn.subscribe("Fetch.requestPaused", this.sessionId, (params) => {
2551
+ this._handleRequestPaused(params);
2552
+ })
2553
+ );
2554
+ }
2555
+ }
2556
+ async unroute(url, handler) {
2557
+ const regex = typeof url === "string" ? globToRegex(url) : url;
2558
+ this._routeHandlers = this._routeHandlers.filter(
2559
+ (h) => !(regex.source === h.regex.source && (!handler || h.handler === handler))
2560
+ );
2561
+ if (this._routeHandlers.length === 0 && this._interceptionEnabled) {
2562
+ this._interceptionEnabled = false;
2563
+ await this.conn.send("Fetch.disable", void 0, this.sessionId).catch(() => {
2564
+ });
2565
+ }
2566
+ }
2567
+ async _handleRequestPaused(params) {
2568
+ const requestUrl = params.request.url;
2569
+ for (const { regex, handler } of this._routeHandlers) {
2570
+ if (regex.test(requestUrl)) {
2571
+ this._emit("request", createXBRequest(
2572
+ null,
2573
+ {
2574
+ requestId: params.requestId,
2575
+ url: params.request.url,
2576
+ method: params.request.method,
2577
+ headers: params.request.headers,
2578
+ postData: params.request.postData ?? null,
2579
+ resourceType: params.resourceType
2580
+ }
2581
+ ));
2582
+ const route = createXBRouteFetch(this.conn, this.sessionId, params, this._emitter);
2583
+ try {
2584
+ await handler(route);
2585
+ } catch {
2586
+ await this.conn.send("Fetch.continueRequest", {
2587
+ requestId: params.requestId
2588
+ }, this.sessionId).catch(() => {
2589
+ });
2590
+ }
2591
+ return;
2592
+ }
2593
+ }
2594
+ await this.conn.send("Fetch.continueRequest", {
2595
+ requestId: params.requestId
2596
+ }, this.sessionId).catch(() => {
2597
+ });
2598
+ }
2599
+ // ── setInputFiles ───────────────────────────────────────────
2600
+ async setInputFiles(selector, files) {
2601
+ const fileArr = Array.isArray(files) ? files : [files];
2602
+ const fileList = fileArr.map((f) => ({
2603
+ name: f.name,
2604
+ type: f.mimeType,
2605
+ dataBase64: f.buffer.toString("base64")
2606
+ }));
2607
+ await this.evaluate(`
2608
+ (function() {
2609
+ var selector = ${JSON.stringify(selector)};
2610
+ var input = ${queryJS(selector)};
2611
+ if (!input) throw new Error('Element not found: ' + selector);
2612
+
2613
+ var fileList = ${JSON.stringify(fileList)};
2614
+ var dt = new DataTransfer();
2615
+
2616
+ fileList.forEach(function(f) {
2617
+ var binary = atob(f.dataBase64);
2618
+ var bytes = new Uint8Array(binary.length);
2619
+ for (var i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
2620
+ var blob = new Blob([bytes], { type: f.type });
2621
+ var file = new File([blob], f.name, { type: f.type });
2622
+ dt.items.add(file);
2623
+ });
2624
+
2625
+ input.files = dt.files;
2626
+ input.dispatchEvent(new Event('input', { bubbles: true }));
2627
+ input.dispatchEvent(new Event('change', { bubbles: true }));
2628
+ })()
2629
+ `);
2630
+ }
2631
+ // ── dragAndDrop ─────────────────────────────────────────────
2632
+ async dragAndDrop(source, target) {
2633
+ const sourceRect = await this.evaluate(`
2634
+ (function() {
2635
+ const el = ${queryJS(source)};
2636
+ if (!el) throw new Error('Source not found: ${source}');
2637
+ el.scrollIntoView({ behavior: 'instant', block: 'center' });
2638
+ const r = el.getBoundingClientRect();
2639
+ return { x: r.x, y: r.y, width: r.width, height: r.height };
2640
+ })()
2641
+ `);
2642
+ const targetRect = await this.evaluate(`
2643
+ (function() {
2644
+ const el = ${queryJS(target)};
2645
+ if (!el) throw new Error('Target not found: ${target}');
2646
+ el.scrollIntoView({ behavior: 'instant', block: 'center' });
2647
+ const r = el.getBoundingClientRect();
2648
+ return { x: r.x, y: r.y, width: r.width, height: r.height };
2649
+ })()
2650
+ `);
2651
+ const sx = sourceRect.x + sourceRect.width / 2;
2652
+ const sy = sourceRect.y + sourceRect.height / 2;
2653
+ const tx = targetRect.x + targetRect.width / 2;
2654
+ const ty = targetRect.y + targetRect.height / 2;
2655
+ try {
2656
+ await this.conn.send("Input.dispatchDragEvent", {
2657
+ type: "dragStart",
2658
+ x: sx,
2659
+ y: sy,
2660
+ data: { items: [], dragOperations: ["copy", "move", "link"] }
2661
+ }, this.sessionId);
2662
+ await this.conn.send("Input.dispatchDragEvent", {
2663
+ type: "dragOver",
2664
+ x: tx,
2665
+ y: ty,
2666
+ data: { items: [], dragOperations: ["copy", "move", "link"] }
2667
+ }, this.sessionId);
2668
+ await this.conn.send("Input.dispatchDragEvent", {
2669
+ type: "drop",
2670
+ x: tx,
2671
+ y: ty,
2672
+ data: { items: [], dragOperations: ["copy", "move", "link"] }
2673
+ }, this.sessionId);
2674
+ await this.conn.send("Input.dispatchDragEvent", {
2675
+ type: "dragCancel",
2676
+ x: sx,
2677
+ y: sy,
2678
+ data: { items: [], dragOperations: ["copy", "move", "link"] }
2679
+ }, this.sessionId);
2680
+ } catch {
2681
+ await this.mouse.move(sx, sy);
2682
+ await this.mouse.down();
2683
+ await this.mouse.move(tx, ty, { steps: 10 });
2684
+ await this.mouse.up();
2685
+ }
2686
+ }
2687
+ // ── setOfflineMode ──────────────────────────────────────────
2688
+ async setOfflineMode(offline) {
2689
+ await this.conn.send("Network.emulateNetworkConditions", {
2690
+ offline,
2691
+ latency: 0,
2692
+ downloadThroughput: offline ? 0 : -1,
2693
+ uploadThroughput: offline ? 0 : -1
2694
+ }, this.sessionId);
2695
+ }
2696
+ };
2697
+
2698
+ // src/cdp-driver/cdp-session.ts
2699
+ var XBCDPSessionImpl = class {
2700
+ conn;
2701
+ sessionId;
2702
+ constructor(conn, sessionId) {
2703
+ this.conn = conn;
2704
+ this.sessionId = sessionId;
2705
+ }
2706
+ async send(method, params) {
2707
+ return this.conn.send(method, params, this.sessionId);
2708
+ }
2709
+ on(event, handler) {
2710
+ this.conn.on(event, (params, sid) => {
2711
+ if (sid === this.sessionId || !this.sessionId && !sid) {
2712
+ handler(params);
2713
+ }
2714
+ });
2715
+ }
2716
+ off(event, handler) {
2717
+ this.conn.off(event, handler);
2718
+ }
2719
+ async detach() {
2720
+ if (!this.sessionId) return;
2721
+ }
2722
+ };
2723
+
2724
+ // src/cdp-driver/context.ts
2725
+ var XBContextImpl = class {
2726
+ conn;
2727
+ _emitter = new EventEmitter2();
2728
+ _browser;
2729
+ contextId;
2730
+ _pages = [];
2731
+ closed = false;
2732
+ options;
2733
+ targetAttachedHandler = null;
2734
+ _initScripts = [];
2735
+ constructor(conn, contextId, browser, opts) {
2736
+ this.conn = conn;
2737
+ this.contextId = contextId;
2738
+ this._browser = browser;
2739
+ this.options = opts;
2740
+ this.setupAutoAttach();
2741
+ }
2742
+ async newPage() {
2743
+ if (this.closed) throw new Error("Context is closed");
2744
+ const { targetId } = await this._browser._createTarget(this.contextId);
2745
+ const sessionId = await this._browser._attachToTarget(targetId);
2746
+ const page = new XBPageImpl(this.conn, sessionId, targetId, this, this._browser);
2747
+ await page._init();
2748
+ this._pages.push(page);
2749
+ this.forwardPageEvents(page);
2750
+ if (this.options.viewport) {
2751
+ await page.setViewportSize(this.options.viewport).catch(() => {
2752
+ });
2753
+ }
2754
+ if (this.options.userAgent) {
2755
+ await page._setUserAgent(this.options.userAgent);
2756
+ }
2757
+ if (this.options.extraHTTPHeaders) {
2758
+ await page._setExtraHTTPHeaders(this.options.extraHTTPHeaders);
2759
+ }
2760
+ for (const script of this._initScripts) {
2761
+ await page.addInitScript(script);
2762
+ }
2763
+ return page;
2764
+ }
2765
+ pages() {
2766
+ return [...this._pages];
2767
+ }
2768
+ browser() {
2769
+ return this._browser;
2770
+ }
2771
+ async close() {
2772
+ if (this.closed) return;
2773
+ this.closed = true;
2774
+ for (const page of this._pages) {
2775
+ await page.close().catch(() => {
2776
+ });
2777
+ }
2778
+ this._pages = [];
2779
+ if (this.targetAttachedHandler) {
2780
+ this.conn.off("Target.attachedToTarget", this.targetAttachedHandler);
2781
+ this.targetAttachedHandler = null;
2782
+ }
2783
+ if (this.contextId && this.contextId !== "default") {
2784
+ await this.conn.send("Target.disposeBrowserContext", {
2785
+ browserContextId: this.contextId
2786
+ }).catch(() => {
2787
+ });
2788
+ }
2789
+ this._browser._removeContext(this.contextId);
2790
+ }
2791
+ async newCDPSession(page) {
2792
+ if (page instanceof XBPageImpl) {
2793
+ return new XBCDPSessionImpl(this.conn, page.sessionId);
2794
+ }
2795
+ return new XBCDPSessionImpl(this.conn);
2796
+ }
2797
+ async addInitScript(script) {
2798
+ this._initScripts.push(script);
2799
+ for (const page of this._pages) {
2800
+ await page.addInitScript(script);
2801
+ }
2802
+ }
2803
+ // ── Cookies ─────────────────────────────────────────────────
2804
+ async cookies(urls) {
2805
+ const urlList = typeof urls === "string" ? [urls] : urls;
2806
+ const params = urlList ? { urls: urlList } : void 0;
2807
+ try {
2808
+ const result = await this.conn.send("Storage.getCookies", params);
2809
+ return result.cookies;
2810
+ } catch {
2811
+ try {
2812
+ const result = await this.conn.send("Network.getCookies", params);
2813
+ return result.cookies;
2814
+ } catch {
2815
+ return [];
2816
+ }
2817
+ }
2818
+ }
2819
+ async addCookies(cookies) {
2820
+ const cdpCookies = cookies.map((c) => ({
2821
+ name: c.name,
2822
+ value: c.value,
2823
+ domain: c.domain,
2824
+ path: c.path || "/",
2825
+ expires: c.expires,
2826
+ httpOnly: c.httpOnly,
2827
+ secure: c.secure,
2828
+ sameSite: c.sameSite
2829
+ }));
2830
+ try {
2831
+ await this.conn.send("Storage.setCookies", { cookies: cdpCookies });
2832
+ } catch {
2833
+ await this.conn.send("Network.setCookies", { cookies: cdpCookies });
2834
+ }
2835
+ }
2836
+ async clearCookies() {
2837
+ try {
2838
+ await this.conn.send("Storage.clearCookies");
2839
+ } catch {
2840
+ await this.conn.send("Network.clearBrowserCookies");
2841
+ }
2842
+ }
2843
+ on(event, handler) {
2844
+ this._emitter.on(event, handler);
2845
+ }
2846
+ off(event, handler) {
2847
+ this._emitter.off(event, handler);
2848
+ }
2849
+ /**
2850
+ * Register a page that was attached to an existing target (discovered via
2851
+ * Target.getTargets). Used by XBBrowserImpl.discoverContexts() to wire up
2852
+ * pages from the user's existing browser session into the context wrapper
2853
+ * so they appear in `context.pages()` and can be reused by plugins.
2854
+ */
2855
+ _addDiscoveredPage(page) {
2856
+ const exists = this._pages.some((p) => p._targetId === page._targetId);
2857
+ if (exists) return;
2858
+ this._pages.push(page);
2859
+ this.forwardPageEvents(page);
2860
+ }
2861
+ // ── Private ─────────────────────────────────────────────────
2862
+ /** Forward page-level events (request, response, etc.) to context listeners */
2863
+ forwardPageEvents(page) {
2864
+ const forward = (event) => {
2865
+ page.on(event, (...args) => {
2866
+ this._emitter.emit(event, ...args);
2867
+ });
2868
+ };
2869
+ forward("request");
2870
+ forward("response");
2871
+ forward("requestfailed");
2872
+ forward("requestfinished");
2873
+ }
2874
+ setupAutoAttach() {
2875
+ this.targetAttachedHandler = (paramsRaw) => {
2876
+ const params = paramsRaw;
2877
+ if (this.contextId !== "default" && params.targetInfo.browserContextId !== this.contextId) return;
2878
+ if (params.targetInfo.type !== "page") return;
2879
+ const exists = this._pages.some(
2880
+ (p) => p._targetId === params.targetInfo.targetId
2881
+ );
2882
+ if (exists) return;
2883
+ const page = new XBPageImpl(
2884
+ this.conn,
2885
+ params.sessionId,
2886
+ params.targetInfo.targetId,
2887
+ this,
2888
+ this._browser
2889
+ );
2890
+ this.conn.send("Runtime.runIfWaitingForDebugger", void 0, params.sessionId).catch(() => {
2891
+ });
2892
+ page._init().then(async () => {
2893
+ for (const script of this._initScripts) {
2894
+ await page.addInitScript(script).catch(() => {
2895
+ });
2896
+ }
2897
+ this._pages.push(page);
2898
+ this.forwardPageEvents(page);
2899
+ this._emitter.emit("page", page);
2900
+ });
2901
+ };
2902
+ this.conn.on("Target.attachedToTarget", this.targetAttachedHandler);
2903
+ }
2904
+ };
2905
+
2906
+ // src/cdp-driver/browser.ts
2907
+ var XBBrowserImpl = class {
2908
+ conn;
2909
+ _emitter = new EventEmitter3();
2910
+ _contexts = /* @__PURE__ */ new Map();
2911
+ _disconnected = false;
2912
+ childProcess = null;
2913
+ tmpDir;
2914
+ _exitHandler = null;
2915
+ /**
2916
+ * Original CDP endpoint (HTTP or ws URL) used to construct this browser.
2917
+ * Used by discoverContexts() as a fallback to HTTP /json/list when
2918
+ * Target.getTargets doesn't return page-type targets (e.g. cdp-tunnel proxy).
2919
+ */
2920
+ cdpEndpoint;
2921
+ constructor(conn, childProcess, tmpDir, cdpEndpoint) {
2922
+ this.conn = conn;
2923
+ this.childProcess = childProcess ?? null;
2924
+ this.tmpDir = tmpDir;
2925
+ this.cdpEndpoint = cdpEndpoint;
2926
+ conn.on("disconnect", () => {
2927
+ this._disconnected = true;
2928
+ this._emitter.emit("disconnected");
2929
+ });
2930
+ if (this.childProcess) {
2931
+ this._exitHandler = () => {
2932
+ try {
2933
+ if (this.childProcess?.exitCode === null) {
2934
+ this.childProcess.kill("SIGKILL");
2935
+ }
2936
+ } catch {
2937
+ }
2938
+ if (this.tmpDir) {
2939
+ try {
2940
+ const { rmSync } = __require("fs");
2941
+ rmSync(this.tmpDir, { recursive: true, force: true });
2942
+ } catch {
2943
+ }
2944
+ }
2945
+ };
2946
+ process.on("exit", this._exitHandler);
2947
+ }
2948
+ }
2949
+ get disconnected() {
2950
+ return this._disconnected;
2951
+ }
2952
+ /** The underlying CDP connection (for advanced use) */
2953
+ get connection() {
2954
+ return this.conn;
2955
+ }
2956
+ async close() {
2957
+ if (this._disconnected) return;
2958
+ this._disconnected = true;
2959
+ for (const [, info] of this._contexts) {
2960
+ await info.context.close().catch(() => {
2961
+ });
2962
+ }
2963
+ this._contexts.clear();
2964
+ if (this._exitHandler) {
2965
+ process.removeListener("exit", this._exitHandler);
2966
+ this._exitHandler = null;
2967
+ }
2968
+ if (this.childProcess) {
2969
+ const { killChrome: killChrome2 } = await import("./launcher-L2JNDB2H.js");
2970
+ await killChrome2(this.childProcess, this.tmpDir);
2971
+ }
2972
+ await this.conn.close();
2973
+ this._emitter.emit("disconnected");
2974
+ }
2975
+ async newContext(opts = {}) {
2976
+ if (this._disconnected) {
2977
+ throw new Error("Browser is disconnected");
2978
+ }
2979
+ let contextId = "default";
2980
+ try {
2981
+ const result = await this.conn.send(
2982
+ "Target.createBrowserContext",
2983
+ { disposeOnDetach: true },
2984
+ void 0,
2985
+ 1e4
2986
+ // 10s timeout instead of default 30s
2987
+ );
2988
+ contextId = result.browserContextId;
2989
+ } catch {
2990
+ }
2991
+ const context = new XBContextImpl(this.conn, contextId, this, opts);
2992
+ context.on("page", (page) => {
2993
+ this._emitter.emit("page", page);
2994
+ });
2995
+ this._contexts.set(contextId, {
2996
+ contextId,
2997
+ context
2998
+ });
2999
+ if (this.childProcess) {
3000
+ this._enableAutoAttach().catch(() => {
3001
+ });
3002
+ }
3003
+ return context;
3004
+ }
3005
+ contexts() {
3006
+ return Array.from(this._contexts.values()).map((info) => info.context);
3007
+ }
3008
+ on(event, handler) {
3009
+ this._emitter.on(event, handler);
3010
+ }
3011
+ off(event, handler) {
3012
+ this._emitter.off(event, handler);
3013
+ }
3014
+ /** Called by context.close() to remove from registry */
3015
+ _removeContext(contextId) {
3016
+ this._contexts.delete(contextId);
3017
+ }
3018
+ // ── CDP helpers exposed for context/page ────────────────────
3019
+ /** Attach to a target and get a session ID for flat protocol */
3020
+ async _attachToTarget(targetId) {
3021
+ const result = await this.conn.send(
3022
+ "Target.attachToTarget",
3023
+ { targetId, flatten: true }
3024
+ );
3025
+ return result.sessionId;
3026
+ }
3027
+ /** Detach from a target session */
3028
+ async _detachFromTarget(sessionId) {
3029
+ await this.conn.send("Target.detachFromTarget", { sessionId });
3030
+ }
3031
+ /**
3032
+ * Derive the HTTP /json base URL from the original cdpEndpoint for use
3033
+ * as a fallback when Target.getTargets doesn't return page targets.
3034
+ * Supports both http:// and ws:// input formats.
3035
+ */
3036
+ _httpFallbackURL() {
3037
+ if (!this.cdpEndpoint) return void 0;
3038
+ if (this.cdpEndpoint.startsWith("http://") || this.cdpEndpoint.startsWith("https://")) {
3039
+ return this.cdpEndpoint;
3040
+ }
3041
+ if (this.cdpEndpoint.startsWith("ws://") || this.cdpEndpoint.startsWith("wss://")) {
3042
+ const url = this.cdpEndpoint.replace(/^ws/, "http");
3043
+ const slashIdx = url.indexOf("/", url.indexOf("//") + 2);
3044
+ return slashIdx >= 0 ? url.substring(0, slashIdx) : url;
3045
+ }
3046
+ return void 0;
3047
+ }
3048
+ /** Create a new page target within a browser context */
3049
+ async _createTarget(contextId, url = "about:blank") {
3050
+ const params = { url };
3051
+ if (contextId && contextId !== "default") {
3052
+ params.browserContextId = contextId;
3053
+ }
3054
+ return this.conn.send("Target.createTarget", params);
3055
+ }
3056
+ /** Close a target */
3057
+ async _closeTarget(targetId) {
3058
+ await this.conn.send("Target.closeTarget", { targetId });
3059
+ }
3060
+ /** Enable auto-attach for new targets */
3061
+ async _enableAutoAttach() {
3062
+ await this.conn.send("Target.setAutoAttach", {
3063
+ autoAttach: true,
3064
+ waitForDebuggerOnStart: false,
3065
+ flatten: true
3066
+ });
3067
+ }
3068
+ /**
3069
+ * Discover existing browser contexts and pages via Target.getTargets.
3070
+ *
3071
+ * For CDP tunnel connections (cdp-tunnel, attach scenarios), the
3072
+ * Target.attachedToTarget auto-attach flow is unreliable. Without this
3073
+ * call, `b.contexts()` would return [] and callers would fall back to
3074
+ * `b.newContext()` — which creates an isolated context with NO cookies
3075
+ * shared with the user's existing browser session (causing login failures).
3076
+ *
3077
+ * This method:
3078
+ * 1. Queries Target.getTargets to enumerate all page targets
3079
+ * 2. Groups them by browserContextId
3080
+ * 3. Attaches to each existing page via Target.attachToTarget
3081
+ * 4. Wraps the discovered pages in a XBContextImpl and registers it in
3082
+ * this._contexts so `contexts()` returns the user's actual contexts
3083
+ * 5. Enables Target.setAutoAttach for future pages
3084
+ *
3085
+ * No-op for self-launched browsers (they already populated contexts via
3086
+ * newContext() + childProcess-gated auto-attach).
3087
+ */
3088
+ async discoverContexts() {
3089
+ if (this._disconnected) return;
3090
+ let targetInfos = [];
3091
+ try {
3092
+ const result = await this.conn.send(
3093
+ "Target.getTargets"
3094
+ );
3095
+ targetInfos = result.targetInfos ?? [];
3096
+ } catch {
3097
+ return;
3098
+ }
3099
+ const pageTargets = targetInfos.filter((t) => t.type === "page");
3100
+ const httpFallbackUrl = this._httpFallbackURL();
3101
+ if (pageTargets.length === 0 && httpFallbackUrl) {
3102
+ console.log(`[discoverContexts] Target.getTargets returned ${targetInfos.length} targets (0 page type). Falling back to HTTP /json/list at ${httpFallbackUrl}`);
3103
+ try {
3104
+ const { getCDPTargets: getCDPTargets2 } = await import("./launcher-L2JNDB2H.js");
3105
+ const httpPages = await getCDPTargets2(httpFallbackUrl);
3106
+ console.log(`[discoverContexts] HTTP /json/list returned ${httpPages.length} pages`);
3107
+ for (const p of httpPages) {
3108
+ if (p.type !== "page") continue;
3109
+ if (!p.url || p.url.startsWith("chrome://") || p.url.startsWith("devtools://")) continue;
3110
+ targetInfos.push({
3111
+ targetId: p.id,
3112
+ type: "page",
3113
+ url: p.url,
3114
+ title: p.title
3115
+ });
3116
+ }
3117
+ console.log(`[discoverContexts] After HTTP fallback: ${targetInfos.length} total targets, ${targetInfos.filter((t) => t.type === "page").length} pages`);
3118
+ } catch (err) {
3119
+ console.log(`[discoverContexts] HTTP fallback failed: ${errMsg(err)}`);
3120
+ }
3121
+ }
3122
+ const pagesByContext = /* @__PURE__ */ new Map();
3123
+ for (const t of targetInfos) {
3124
+ if (t.type !== "page") continue;
3125
+ if (!t.url || t.url.startsWith("chrome://") || t.url.startsWith("devtools://")) {
3126
+ continue;
3127
+ }
3128
+ const ctxId = t.browserContextId || "default";
3129
+ if (!pagesByContext.has(ctxId)) pagesByContext.set(ctxId, []);
3130
+ pagesByContext.get(ctxId).push(t);
3131
+ }
3132
+ for (const [ctxId, pages] of pagesByContext) {
3133
+ if (this._contexts.has(ctxId)) continue;
3134
+ const context = new XBContextImpl(this.conn, ctxId, this, {});
3135
+ for (const p of pages) {
3136
+ try {
3137
+ const sessionId = await this._attachToTarget(p.targetId);
3138
+ const page = new XBPageImpl(this.conn, sessionId, p.targetId, context, this);
3139
+ await page._init();
3140
+ context._addDiscoveredPage(page);
3141
+ } catch {
3142
+ }
3143
+ }
3144
+ this._contexts.set(ctxId, { contextId: ctxId, context });
3145
+ }
3146
+ try {
3147
+ await this.conn.send("Target.setAutoAttach", {
3148
+ autoAttach: true,
3149
+ waitForDebuggerOnStart: false,
3150
+ flatten: true
3151
+ });
3152
+ } catch {
3153
+ }
3154
+ }
3155
+ };
3156
+
3157
+ // src/cdp-driver/connection.ts
3158
+ import { EventEmitter as EventEmitter4 } from "events";
3159
+ import { WebSocket } from "ws";
3160
+ var CDPConnection = class extends EventEmitter4 {
3161
+ ws;
3162
+ nextId = 1;
3163
+ pending = /* @__PURE__ */ new Map();
3164
+ closed = false;
3165
+ closeReason = null;
3166
+ /** Default session ID for flat session protocol (Target.attachToTarget) */
3167
+ defaultSessionId;
3168
+ constructor(wsOrUrl, sessionId) {
3169
+ super();
3170
+ this.setMaxListeners(0);
3171
+ this.defaultSessionId = sessionId;
3172
+ if (typeof wsOrUrl === "string") {
3173
+ const wsOptions = /^wss:\/\/\d+\.\d+\.\d+\.\d+/.test(wsOrUrl) ? { rejectUnauthorized: false } : void 0;
3174
+ this.ws = new WebSocket(wsOrUrl, wsOptions);
3175
+ } else {
3176
+ this.ws = wsOrUrl;
3177
+ }
3178
+ this.bindWebSocket();
3179
+ this.startKeepalive();
3180
+ }
3181
+ /** Send periodic WS pings to prevent idle-timeout disconnects (e.g. CF's 100s).
3182
+ * Also detects dead connections: if a pong isn't received within 10s of a
3183
+ * ping, the connection is considered dead and forcibly closed. */
3184
+ keepaliveTimer = null;
3185
+ pongTimer = null;
3186
+ startKeepalive() {
3187
+ this.ws.on("pong", () => {
3188
+ if (this.pongTimer) {
3189
+ clearTimeout(this.pongTimer);
3190
+ this.pongTimer = null;
3191
+ }
3192
+ });
3193
+ this.keepaliveTimer = setInterval(() => {
3194
+ if (this.ws.readyState === WebSocket.OPEN) {
3195
+ if (!this.pongTimer) {
3196
+ this.pongTimer = setTimeout(() => {
3197
+ if (!this.closed) {
3198
+ this.closed = true;
3199
+ this.closeReason = "keepalive timeout (no pong in 10s)";
3200
+ try {
3201
+ this.ws.terminate();
3202
+ } catch {
3203
+ }
3204
+ for (const [, pending] of this.pending) {
3205
+ clearTimeout(pending.timeout);
3206
+ pending.reject(new Error("Connection dead: keepalive timeout"));
3207
+ }
3208
+ this.pending.clear();
3209
+ this.emit("disconnect");
3210
+ }
3211
+ }, 1e4);
3212
+ }
3213
+ this.ws.ping?.();
3214
+ } else if (this.closed) {
3215
+ if (this.keepaliveTimer) clearInterval(this.keepaliveTimer);
3216
+ this.keepaliveTimer = null;
3217
+ }
3218
+ }, 3e4);
3219
+ }
3220
+ /** Wait for the connection to be fully open */
3221
+ async ready() {
3222
+ if (this.ws.readyState === WebSocket.OPEN) return;
3223
+ if (this.ws.readyState === WebSocket.CLOSED || this.ws.readyState === WebSocket.CLOSING) {
3224
+ throw new Error(`WebSocket already closed: ${this.closeReason ?? "unknown"}`);
3225
+ }
3226
+ return new Promise((resolve, reject) => {
3227
+ const onOpen = () => {
3228
+ this.ws.off("error", onError);
3229
+ resolve();
3230
+ };
3231
+ const onError = (err) => {
3232
+ this.ws.off("open", onOpen);
3233
+ reject(err);
3234
+ };
3235
+ this.ws.once("open", onOpen);
3236
+ this.ws.once("error", onError);
3237
+ });
3238
+ }
3239
+ /** Is the underlying WebSocket alive? */
3240
+ get isOpen() {
3241
+ return !this.closed && this.ws.readyState === WebSocket.OPEN;
3242
+ }
3243
+ /**
3244
+ * Send a CDP command and await its response.
3245
+ *
3246
+ * @param method — CDP domain.method (e.g. "Page.navigate")
3247
+ * @param params — method parameters
3248
+ * @param sessionId — optional flat session ID for sub-targets
3249
+ * @param timeoutMs — response timeout (default: 30s)
3250
+ * @returns the `result` field from the CDP response
3251
+ */
3252
+ async send(method, params, sessionId, timeoutMs = 3e4) {
3253
+ if (this.closed) {
3254
+ throw new Error(`CDP connection closed: ${this.closeReason ?? "unknown"}`);
3255
+ }
3256
+ if (!this.isOpen) {
3257
+ throw new Error(`CDP connection not open (state: ${this.ws.readyState})`);
3258
+ }
3259
+ const id = this.nextId++;
3260
+ const sid = sessionId ?? this.defaultSessionId;
3261
+ const message = { id, method };
3262
+ if (params !== void 0) message.params = params;
3263
+ if (sid !== void 0) message.sessionId = sid;
3264
+ return new Promise((resolve, reject) => {
3265
+ const timeout = setTimeout(() => {
3266
+ this.pending.delete(id);
3267
+ reject(new Error(`CDP timeout: ${method} (${timeoutMs}ms)`));
3268
+ }, timeoutMs);
3269
+ this.pending.set(id, {
3270
+ resolve: (v) => {
3271
+ clearTimeout(timeout);
3272
+ this.pending.delete(id);
3273
+ resolve(v);
3274
+ },
3275
+ reject: (err) => {
3276
+ clearTimeout(timeout);
3277
+ this.pending.delete(id);
3278
+ reject(err);
3279
+ },
3280
+ method,
3281
+ timeout
3282
+ });
3283
+ const data = JSON.stringify(message);
3284
+ try {
3285
+ this.ws.send(data);
3286
+ } catch (err) {
3287
+ clearTimeout(timeout);
3288
+ this.pending.delete(id);
3289
+ reject(new Error(`CDP send failed: ${method} \u2014 ${err instanceof Error ? err.message : String(err)}`));
3290
+ }
3291
+ });
3292
+ }
3293
+ /**
3294
+ * Subscribe to a CDP event.
3295
+ *
3296
+ * @param event — full event name (e.g. "Page.frameNavigated")
3297
+ * @param handler — called with the event params
3298
+ * @param sessionId — optional session filter
3299
+ */
3300
+ on(event, handler) {
3301
+ return super.on(event, handler);
3302
+ }
3303
+ once(event, handler) {
3304
+ return super.once(event, handler);
3305
+ }
3306
+ /** Remove an event listener */
3307
+ off(event, handler) {
3308
+ super.off(event, handler);
3309
+ return this;
3310
+ }
3311
+ /**
3312
+ * Subscribe to a CDP event for a specific session.
3313
+ * Returns an unsubscribe function.
3314
+ */
3315
+ subscribe(event, sessionId, handler) {
3316
+ const wrapper = (params, sid) => {
3317
+ if (sid === sessionId || !sessionId && !sid) handler(params);
3318
+ };
3319
+ this.on(event, wrapper);
3320
+ return () => this.off(event, wrapper);
3321
+ }
3322
+ /** Close the WebSocket */
3323
+ async close() {
3324
+ if (this.closed) return;
3325
+ this.closed = true;
3326
+ this.closeReason = "closed by caller";
3327
+ if (this.keepaliveTimer) {
3328
+ clearInterval(this.keepaliveTimer);
3329
+ this.keepaliveTimer = null;
3330
+ }
3331
+ if (this.pongTimer) {
3332
+ clearTimeout(this.pongTimer);
3333
+ this.pongTimer = null;
3334
+ }
3335
+ for (const [id, pending] of this.pending) {
3336
+ clearTimeout(pending.timeout);
3337
+ pending.reject(new Error(`Connection closed: ${pending.method}`));
3338
+ this.pending.delete(id);
3339
+ }
3340
+ if (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING) {
3341
+ this.ws.close(1e3, "normal closure");
3342
+ }
3343
+ }
3344
+ /** Set the default session ID for flat protocol */
3345
+ setDefaultSessionId(sid) {
3346
+ this.defaultSessionId = sid;
3347
+ }
3348
+ // ── Private ─────────────────────────────────────────────────
3349
+ bindWebSocket() {
3350
+ this.ws.on("message", (raw) => {
3351
+ let msg;
3352
+ try {
3353
+ msg = JSON.parse(raw.toString());
3354
+ } catch {
3355
+ return;
3356
+ }
3357
+ if (msg.id !== void 0) {
3358
+ const pending = this.pending.get(msg.id);
3359
+ if (!pending) return;
3360
+ if (msg.error) {
3361
+ pending.reject(new CDPProtocolError(msg.error.code, msg.error.message, pending.method));
3362
+ } else {
3363
+ pending.resolve(msg.result ?? {});
3364
+ }
3365
+ return;
3366
+ }
3367
+ if (msg.method) {
3368
+ this.emit(msg.method, msg.params ?? {}, msg.sessionId);
3369
+ this.emit("*", msg.method, msg.params ?? {}, msg.sessionId);
3370
+ }
3371
+ });
3372
+ this.ws.on("close", (code, reason) => {
3373
+ if (this.closed) return;
3374
+ this.closed = true;
3375
+ this.closeReason = `WebSocket closed: ${code} ${reason?.toString() ?? ""}`.trim();
3376
+ if (this.keepaliveTimer) {
3377
+ clearInterval(this.keepaliveTimer);
3378
+ this.keepaliveTimer = null;
3379
+ }
3380
+ for (const [id, pending] of this.pending) {
3381
+ clearTimeout(pending.timeout);
3382
+ pending.reject(new Error(`Connection closed: ${pending.method}`));
3383
+ this.pending.delete(id);
3384
+ }
3385
+ this.emit("disconnect");
3386
+ });
3387
+ this.ws.on("error", (err) => {
3388
+ if (this.closed) return;
3389
+ this.emit("ws-error", err);
3390
+ });
3391
+ }
3392
+ };
3393
+ var CDPProtocolError = class extends Error {
3394
+ code;
3395
+ method;
3396
+ data;
3397
+ constructor(code, message, method, data) {
3398
+ super(`CDP error [${code}] in ${method}: ${message}`);
3399
+ this.name = "CDPProtocolError";
3400
+ this.code = code;
3401
+ this.method = method;
3402
+ this.data = data;
3403
+ }
3404
+ };
3405
+
3406
+ // src/cdp-driver/wait.ts
3407
+ async function waitForNetworkIdle(conn, sessionId, opts = {}) {
3408
+ const idleTime = opts.idleTime ?? 500;
3409
+ const timeout = opts.timeout ?? 3e4;
3410
+ const maxInflight = opts.maxInflight ?? 0;
3411
+ return new Promise((resolve, reject) => {
3412
+ let inflight = 0;
3413
+ let idleTimer = null;
3414
+ let timeoutTimer = null;
3415
+ let unsub1 = null;
3416
+ let unsub2 = null;
3417
+ let unsub3 = null;
3418
+ const cleanup = () => {
3419
+ if (unsub1) unsub1();
3420
+ if (unsub2) unsub2();
3421
+ if (unsub3) unsub3();
3422
+ if (idleTimer) clearTimeout(idleTimer);
3423
+ if (timeoutTimer) clearTimeout(timeoutTimer);
3424
+ };
3425
+ const checkIdle = () => {
3426
+ if (inflight <= maxInflight) {
3427
+ if (!idleTimer) {
3428
+ idleTimer = setTimeout(() => {
3429
+ cleanup();
3430
+ resolve();
3431
+ }, idleTime);
3432
+ }
3433
+ } else {
3434
+ if (idleTimer) {
3435
+ clearTimeout(idleTimer);
3436
+ idleTimer = null;
3437
+ }
3438
+ }
3439
+ };
3440
+ const onRequest = () => {
3441
+ inflight++;
3442
+ if (idleTimer) {
3443
+ clearTimeout(idleTimer);
3444
+ idleTimer = null;
3445
+ }
3446
+ };
3447
+ const onFinish = () => {
3448
+ inflight = Math.max(0, inflight - 1);
3449
+ checkIdle();
3450
+ };
3451
+ const onFail = () => {
3452
+ inflight = Math.max(0, inflight - 1);
3453
+ checkIdle();
3454
+ };
3455
+ timeoutTimer = setTimeout(() => {
3456
+ cleanup();
3457
+ reject(new Error(`waitForNetworkIdle timeout after ${timeout}ms`));
3458
+ }, timeout);
3459
+ unsub1 = conn.subscribe("Network.requestWillBeSent", sessionId, onRequest);
3460
+ unsub2 = conn.subscribe("Network.loadingFinished", sessionId, onFinish);
3461
+ unsub3 = conn.subscribe("Network.loadingFailed", sessionId, onFail);
3462
+ checkIdle();
3463
+ });
3464
+ }
3465
+
3466
+ // src/cdp-driver/index.ts
3467
+ async function launch(options = {}) {
3468
+ let wsEndpoint;
3469
+ let childProcess;
3470
+ let tmpDir;
3471
+ if (options.cdpEndpoint) {
3472
+ wsEndpoint = await connectToCDP(options.cdpEndpoint);
3473
+ } else {
3474
+ const result = await launchChrome({
3475
+ executablePath: options.executablePath,
3476
+ headless: options.headless,
3477
+ args: options.args,
3478
+ userDataDir: options.userDataDir,
3479
+ timeout: options.timeout,
3480
+ env: options.env
3481
+ });
3482
+ wsEndpoint = result.wsEndpoint;
3483
+ childProcess = result.process;
3484
+ tmpDir = result.tmpDir;
3485
+ }
3486
+ const conn = new CDPConnection(wsEndpoint);
3487
+ await conn.ready();
3488
+ const httpEndpoint = options.cdpEndpoint && !options.cdpEndpoint.startsWith("ws") ? options.cdpEndpoint : void 0;
3489
+ const browser = new XBBrowserImpl(conn, childProcess, tmpDir, httpEndpoint);
3490
+ return { browser, wsEndpoint };
3491
+ }
3492
+
3493
+ export {
3494
+ XBMouseImpl,
3495
+ XBKeyboardImpl,
3496
+ waitForActionable,
3497
+ checkActionable,
3498
+ scrollIntoView,
3499
+ XBLocatorImpl,
3500
+ XBElementHandleImpl,
3501
+ XBPageImpl,
3502
+ XBCDPSessionImpl,
3503
+ XBContextImpl,
3504
+ XBBrowserImpl,
3505
+ CDPConnection,
3506
+ CDPProtocolError,
3507
+ waitForNetworkIdle,
3508
+ launch
3509
+ };