@pyrokine/mcp-chrome 2.4.4 → 3.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +495 -115
- package/README_zh.md +423 -128
- package/dist/anti-detection/injection.js +3 -3
- package/dist/cdp/client.d.ts +1 -1
- package/dist/cdp/client.d.ts.map +1 -1
- package/dist/cdp/client.js +18 -7
- package/dist/cdp/client.js.map +1 -1
- package/dist/cdp/launcher.d.ts +2 -3
- package/dist/cdp/launcher.d.ts.map +1 -1
- package/dist/cdp/launcher.js +84 -24
- package/dist/cdp/launcher.js.map +1 -1
- package/dist/core/auto-wait.d.ts +3 -3
- package/dist/core/auto-wait.d.ts.map +1 -1
- package/dist/core/auto-wait.js +45 -20
- package/dist/core/auto-wait.js.map +1 -1
- package/dist/core/browser-driver.d.ts +105 -15
- package/dist/core/browser-driver.d.ts.map +1 -1
- package/dist/core/browser-driver.js.map +1 -1
- package/dist/core/errors.d.ts +22 -4
- package/dist/core/errors.d.ts.map +1 -1
- package/dist/core/errors.js +90 -7
- package/dist/core/errors.js.map +1 -1
- package/dist/core/locator.d.ts +7 -0
- package/dist/core/locator.d.ts.map +1 -1
- package/dist/core/locator.js +54 -29
- package/dist/core/locator.js.map +1 -1
- package/dist/core/os-mouse.d.ts +15 -2
- package/dist/core/os-mouse.d.ts.map +1 -1
- package/dist/core/os-mouse.js +52 -8
- package/dist/core/os-mouse.js.map +1 -1
- package/dist/core/session.d.ts +39 -22
- package/dist/core/session.d.ts.map +1 -1
- package/dist/core/session.js +632 -153
- package/dist/core/session.js.map +1 -1
- package/dist/core/types.d.ts +2 -0
- package/dist/core/types.d.ts.map +1 -1
- package/dist/core/types.js.map +1 -1
- package/dist/core/unified-session.d.ts +105 -27
- package/dist/core/unified-session.d.ts.map +1 -1
- package/dist/core/unified-session.js +554 -138
- package/dist/core/unified-session.js.map +1 -1
- package/dist/core/utils.d.ts +5 -0
- package/dist/core/utils.d.ts.map +1 -1
- package/dist/core/utils.js +475 -54
- package/dist/core/utils.js.map +1 -1
- package/dist/extension/bridge.d.ts +49 -39
- package/dist/extension/bridge.d.ts.map +1 -1
- package/dist/extension/bridge.js +318 -131
- package/dist/extension/bridge.js.map +1 -1
- package/dist/extension/http-server.d.ts +3 -0
- package/dist/extension/http-server.d.ts.map +1 -1
- package/dist/extension/http-server.js +28 -2
- package/dist/extension/http-server.js.map +1 -1
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -1
- package/dist/tools/browse.d.ts.map +1 -1
- package/dist/tools/browse.js +248 -172
- package/dist/tools/browse.js.map +1 -1
- package/dist/tools/challenge.d.ts +1 -1
- package/dist/tools/challenge.d.ts.map +1 -1
- package/dist/tools/challenge.js +86 -51
- package/dist/tools/challenge.js.map +1 -1
- package/dist/tools/cookies.d.ts.map +1 -1
- package/dist/tools/cookies.js +5 -3
- package/dist/tools/cookies.js.map +1 -1
- package/dist/tools/diagnostics.d.ts +3 -3
- package/dist/tools/diagnostics.d.ts.map +1 -1
- package/dist/tools/diagnostics.js +13 -12
- package/dist/tools/diagnostics.js.map +1 -1
- package/dist/tools/evaluate.d.ts.map +1 -1
- package/dist/tools/evaluate.js +67 -26
- package/dist/tools/evaluate.js.map +1 -1
- package/dist/tools/extract.d.ts.map +1 -1
- package/dist/tools/extract.js +137 -197
- package/dist/tools/extract.js.map +1 -1
- package/dist/tools/input.d.ts +1 -1
- package/dist/tools/input.d.ts.map +1 -1
- package/dist/tools/input.js +445 -197
- package/dist/tools/input.js.map +1 -1
- package/dist/tools/logs.d.ts.map +1 -1
- package/dist/tools/logs.js +5 -5
- package/dist/tools/logs.js.map +1 -1
- package/dist/tools/manage.d.ts.map +1 -1
- package/dist/tools/manage.js +395 -86
- package/dist/tools/manage.js.map +1 -1
- package/dist/tools/page-context.d.ts +17 -0
- package/dist/tools/page-context.d.ts.map +1 -0
- package/dist/tools/page-context.js +103 -0
- package/dist/tools/page-context.js.map +1 -0
- package/dist/tools/png.d.ts +5 -0
- package/dist/tools/png.d.ts.map +1 -1
- package/dist/tools/png.js +84 -19
- package/dist/tools/png.js.map +1 -1
- package/dist/tools/post-condition.d.ts.map +1 -1
- package/dist/tools/post-condition.js +24 -7
- package/dist/tools/post-condition.js.map +1 -1
- package/dist/tools/schema.d.ts +9 -0
- package/dist/tools/schema.d.ts.map +1 -1
- package/dist/tools/schema.js +15 -0
- package/dist/tools/schema.js.map +1 -1
- package/dist/tools/target-diagnostics.d.ts +9 -1
- package/dist/tools/target-diagnostics.d.ts.map +1 -1
- package/dist/tools/target-diagnostics.js +89 -33
- package/dist/tools/target-diagnostics.js.map +1 -1
- package/dist/tools/wait.d.ts.map +1 -1
- package/dist/tools/wait.js +38 -32
- package/dist/tools/wait.js.map +1 -1
- package/extension/dist/assets/content.ts-loader-DUWbDHRS.js +13 -0
- package/extension/dist/assets/content.ts-qe6IB5DK.js +13 -0
- package/extension/dist/assets/{index.ts-Bqcu2qiN.js → index.ts-D7_LCUoV.js} +2477 -2201
- package/extension/dist/assets/page-scripts-D508WLkW.js +1378 -0
- package/extension/dist/assets/{popup.html-B81xccfq.js → popup.html-B-eVq48O.js} +54 -5
- package/extension/dist/manifest.json +4 -3
- package/extension/dist/service-worker-loader.js +1 -1
- package/extension/dist/src/popup/popup.html +11 -1
- package/package.json +16 -8
- package/scripts/start-chrome.ps1 +58 -0
- package/extension/dist/assets/content.ts-Cj_iiU2s.js +0 -25
package/dist/core/session.js
CHANGED
|
@@ -7,13 +7,16 @@
|
|
|
7
7
|
* - 页面状态
|
|
8
8
|
* - 日志收集
|
|
9
9
|
*/
|
|
10
|
+
import { randomUUID } from 'node:crypto';
|
|
10
11
|
import { BehaviorSimulator, getAntiDetectionScript } from '../anti-detection/index.js';
|
|
12
|
+
import { assertScreenshotBase64Budget, assertScreenshotBudget } from '../tools/png.js';
|
|
11
13
|
import { BrowserLauncher, CDPClient, getBrowserWSEndpoint, getTargets } from '../cdp/index.js';
|
|
12
14
|
import { AutoWait } from './auto-wait.js';
|
|
13
15
|
import { DriverCapabilityError, } from './browser-driver.js';
|
|
14
|
-
import { NavigationError, NavigationTimeoutError, SessionNotFoundError, TargetNotFoundError } from './errors.js';
|
|
16
|
+
import { CDPError, creationError, StructuredToolError, NavigationError, NavigationTimeoutError, PagePreconditionError, SessionNotFoundError, TargetNotFoundError, TimeoutError, } from './errors.js';
|
|
15
17
|
import { Locator } from './locator.js';
|
|
16
18
|
import { DEFAULT_TIMEOUT, extractCdpValue, formatCdpException, MODIFIER_KEYS, } from './types.js';
|
|
19
|
+
import { remainingNavigationTimeout, waitForNavigationQueue, withNavigationBudget } from './utils.js';
|
|
17
20
|
function wildcardSegmentMatches(value, segment, index) {
|
|
18
21
|
if (index + segment.length > value.length) {
|
|
19
22
|
return false;
|
|
@@ -73,6 +76,9 @@ class SessionManager {
|
|
|
73
76
|
sessionId = null;
|
|
74
77
|
currentTargetId = null;
|
|
75
78
|
state = null;
|
|
79
|
+
revisionEpoch = randomUUID();
|
|
80
|
+
revisions = new Map();
|
|
81
|
+
pendingPageCondition = null;
|
|
76
82
|
behaviorSimulator = new BehaviorSimulator();
|
|
77
83
|
stealthMode = 'safe';
|
|
78
84
|
/** 当前按下的修饰键位掩码 */
|
|
@@ -81,11 +87,13 @@ class SessionManager {
|
|
|
81
87
|
operationLock = Promise.resolve();
|
|
82
88
|
consoleLogs = [];
|
|
83
89
|
networkRequests = [];
|
|
90
|
+
targetLogs = new Map();
|
|
84
91
|
nextConsoleLogSequence = 0;
|
|
85
92
|
nextNetworkRequestSequence = 0;
|
|
86
93
|
challengeRequired = false;
|
|
87
94
|
runtimeEnabled = false;
|
|
88
95
|
mainFrameId = null;
|
|
96
|
+
mainFrameLoaderId = null;
|
|
89
97
|
requestMap = new Map();
|
|
90
98
|
// 监听器安装标志(防止重复安装)
|
|
91
99
|
listenersInstalled = false;
|
|
@@ -141,6 +149,7 @@ class SessionManager {
|
|
|
141
149
|
return {
|
|
142
150
|
...newTarget,
|
|
143
151
|
reused: true,
|
|
152
|
+
targetCreated: true,
|
|
144
153
|
};
|
|
145
154
|
}
|
|
146
155
|
return {
|
|
@@ -149,6 +158,7 @@ class SessionManager {
|
|
|
149
158
|
url: pageTarget.url,
|
|
150
159
|
title: pageTarget.title,
|
|
151
160
|
reused: true,
|
|
161
|
+
targetCreated: false,
|
|
152
162
|
};
|
|
153
163
|
}
|
|
154
164
|
catch {
|
|
@@ -216,10 +226,16 @@ class SessionManager {
|
|
|
216
226
|
/**
|
|
217
227
|
* 列出所有可用页面
|
|
218
228
|
*/
|
|
219
|
-
async listTargets() {
|
|
229
|
+
async listTargets(timeout) {
|
|
220
230
|
this.ensureConnected();
|
|
221
231
|
// 从 CDP 获取 targets
|
|
222
|
-
const { targetInfos } = (await this.
|
|
232
|
+
const { targetInfos } = (await this.sendBrowserCommand('Target.getTargets', undefined, timeout));
|
|
233
|
+
const liveIds = new Set(targetInfos.map((target) => target.targetId));
|
|
234
|
+
for (const targetId of this.targetLogs.keys()) {
|
|
235
|
+
if (!liveIds.has(targetId)) {
|
|
236
|
+
this.targetLogs.delete(targetId);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
223
239
|
return targetInfos
|
|
224
240
|
.filter((t) => t.type === 'page')
|
|
225
241
|
.map((t) => ({
|
|
@@ -228,7 +244,7 @@ class SessionManager {
|
|
|
228
244
|
url: t.url,
|
|
229
245
|
title: t.title,
|
|
230
246
|
type: t.type,
|
|
231
|
-
|
|
247
|
+
revision: `${this.revisionEpoch}:${this.revisions.get(t.targetId) ?? 0}`,
|
|
232
248
|
}));
|
|
233
249
|
}
|
|
234
250
|
/**
|
|
@@ -241,28 +257,33 @@ class SessionManager {
|
|
|
241
257
|
* 导航到 URL
|
|
242
258
|
*/
|
|
243
259
|
async navigate(url, options = {}) {
|
|
260
|
+
const deadline = Date.now() + (options.timeout ?? DEFAULT_TIMEOUT);
|
|
244
261
|
return this.withLock(async () => {
|
|
245
262
|
this.ensureSession();
|
|
246
|
-
const { wait = 'load'
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
263
|
+
const { wait = 'load' } = options;
|
|
264
|
+
const abortController = new AbortController();
|
|
265
|
+
const navigationWait = this.startNavigationWait(wait, remainingNavigationTimeout(deadline), abortController.signal, false);
|
|
266
|
+
navigationWait.promise.catch(() => { });
|
|
267
|
+
navigationWait.markActionStarted();
|
|
268
|
+
try {
|
|
269
|
+
const { frameId, loaderId, errorText } = (await this.send('Page.navigate', { url }, remainingNavigationTimeout(deadline)));
|
|
270
|
+
if (errorText) {
|
|
271
|
+
throw new NavigationError(url, errorText);
|
|
272
|
+
}
|
|
273
|
+
if (loaderId) {
|
|
274
|
+
navigationWait.setExpectedLoader(frameId, loaderId);
|
|
275
|
+
}
|
|
276
|
+
else {
|
|
277
|
+
navigationWait.setExpectedSameDocument(frameId);
|
|
278
|
+
}
|
|
258
279
|
}
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
280
|
+
catch (error) {
|
|
281
|
+
abortController.abort(error);
|
|
282
|
+
throw error;
|
|
262
283
|
}
|
|
263
|
-
|
|
264
|
-
await this.updateState();
|
|
265
|
-
});
|
|
284
|
+
await navigationWait.promise;
|
|
285
|
+
await this.updateState(remainingNavigationTimeout(deadline));
|
|
286
|
+
}, deadline);
|
|
266
287
|
}
|
|
267
288
|
/**
|
|
268
289
|
* 等待网络空闲(无进行中的请求且持续指定时间)
|
|
@@ -278,60 +299,71 @@ class SessionManager {
|
|
|
278
299
|
*/
|
|
279
300
|
async waitForNavigation(timeout = DEFAULT_TIMEOUT) {
|
|
280
301
|
this.ensureSession();
|
|
281
|
-
await this.waitForAnyEvent(['Page.loadEventFired', 'Page.navigatedWithinDocument'], timeout);
|
|
302
|
+
await this.waitForAnyEvent(['Page.loadEventFired', 'Page.navigatedWithinDocument', 'Page.frameNavigated'], timeout);
|
|
282
303
|
}
|
|
283
304
|
/**
|
|
284
305
|
* 后退
|
|
285
306
|
*/
|
|
286
307
|
async goBack(timeout = DEFAULT_TIMEOUT) {
|
|
308
|
+
const deadline = Date.now() + timeout;
|
|
287
309
|
return this.withLock(async () => {
|
|
288
310
|
this.ensureSession();
|
|
289
|
-
const { currentIndex, entries } = await this.send('Page.getNavigationHistory', undefined,
|
|
311
|
+
const { currentIndex, entries } = await this.send('Page.getNavigationHistory', undefined, remainingNavigationTimeout(deadline));
|
|
290
312
|
if (currentIndex <= 0) {
|
|
291
313
|
return { navigated: false };
|
|
292
314
|
}
|
|
293
|
-
//
|
|
294
|
-
const waitPromise = this.waitForAnyEvent(['Page.loadEventFired', 'Page.navigatedWithinDocument'],
|
|
315
|
+
// 跨文档加载、主 frame BFCache 恢复和同文档导航分别提供完成事件
|
|
316
|
+
const waitPromise = this.waitForAnyEvent(['Page.loadEventFired', 'Page.navigatedWithinDocument', 'Page.frameNavigated'], remainingNavigationTimeout(deadline));
|
|
295
317
|
// 预注册 rejection handler:若 send() 抛错导致 waitPromise 永远不被 await,
|
|
296
318
|
// 其 timer reject 不会成为 unhandled rejection(Node 20 默认会退出进程)
|
|
297
319
|
waitPromise.catch(() => { });
|
|
298
|
-
await this.send('Page.navigateToHistoryEntry', { entryId: entries[currentIndex - 1].id },
|
|
320
|
+
await this.send('Page.navigateToHistoryEntry', { entryId: entries[currentIndex - 1].id }, remainingNavigationTimeout(deadline));
|
|
299
321
|
await waitPromise;
|
|
300
|
-
await this.updateState();
|
|
322
|
+
await this.updateState(remainingNavigationTimeout(deadline));
|
|
301
323
|
return { navigated: true };
|
|
302
|
-
});
|
|
324
|
+
}, deadline);
|
|
303
325
|
}
|
|
304
326
|
/**
|
|
305
327
|
* 前进
|
|
306
328
|
*/
|
|
307
329
|
async goForward(timeout = DEFAULT_TIMEOUT) {
|
|
330
|
+
const deadline = Date.now() + timeout;
|
|
308
331
|
return this.withLock(async () => {
|
|
309
332
|
this.ensureSession();
|
|
310
|
-
const { currentIndex, entries } = await this.send('Page.getNavigationHistory', undefined,
|
|
333
|
+
const { currentIndex, entries } = await this.send('Page.getNavigationHistory', undefined, remainingNavigationTimeout(deadline));
|
|
311
334
|
if (currentIndex >= entries.length - 1) {
|
|
312
335
|
return { navigated: false };
|
|
313
336
|
}
|
|
314
|
-
//
|
|
315
|
-
const waitPromise = this.waitForAnyEvent(['Page.loadEventFired', 'Page.navigatedWithinDocument'],
|
|
337
|
+
// 跨文档加载、主 frame BFCache 恢复和同文档导航分别提供完成事件
|
|
338
|
+
const waitPromise = this.waitForAnyEvent(['Page.loadEventFired', 'Page.navigatedWithinDocument', 'Page.frameNavigated'], remainingNavigationTimeout(deadline));
|
|
316
339
|
waitPromise.catch(() => { });
|
|
317
|
-
await this.send('Page.navigateToHistoryEntry', { entryId: entries[currentIndex + 1].id },
|
|
340
|
+
await this.send('Page.navigateToHistoryEntry', { entryId: entries[currentIndex + 1].id }, remainingNavigationTimeout(deadline));
|
|
318
341
|
await waitPromise;
|
|
319
|
-
await this.updateState();
|
|
342
|
+
await this.updateState(remainingNavigationTimeout(deadline));
|
|
320
343
|
return { navigated: true };
|
|
321
|
-
});
|
|
344
|
+
}, deadline);
|
|
322
345
|
}
|
|
323
346
|
/**
|
|
324
347
|
* 刷新
|
|
325
348
|
*/
|
|
326
|
-
async reload(ignoreCache = false,
|
|
349
|
+
async reload(ignoreCache = false, waitUntil = 'load', timeout = DEFAULT_TIMEOUT) {
|
|
350
|
+
const deadline = Date.now() + timeout;
|
|
327
351
|
return this.withLock(async () => {
|
|
328
352
|
this.ensureSession();
|
|
329
|
-
const
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
353
|
+
const abortController = new AbortController();
|
|
354
|
+
const navigationWait = this.startNavigationWait(waitUntil, remainingNavigationTimeout(deadline), abortController.signal, true);
|
|
355
|
+
navigationWait.promise.catch(() => { });
|
|
356
|
+
navigationWait.markActionStarted();
|
|
357
|
+
try {
|
|
358
|
+
await this.send('Page.reload', { ignoreCache }, remainingNavigationTimeout(deadline));
|
|
359
|
+
}
|
|
360
|
+
catch (error) {
|
|
361
|
+
abortController.abort(error);
|
|
362
|
+
throw error;
|
|
363
|
+
}
|
|
364
|
+
await navigationWait.promise;
|
|
365
|
+
await this.updateState(remainingNavigationTimeout(deadline));
|
|
366
|
+
}, deadline);
|
|
335
367
|
}
|
|
336
368
|
/**
|
|
337
369
|
* 创建定位器
|
|
@@ -360,7 +392,7 @@ class SessionManager {
|
|
|
360
392
|
/**
|
|
361
393
|
* 鼠标移动
|
|
362
394
|
*/
|
|
363
|
-
async mouseMove(x, y) {
|
|
395
|
+
async mouseMove(x, y, timeout) {
|
|
364
396
|
this.ensureSession();
|
|
365
397
|
// 整数点位:避免 sub-pixel 渲染时坐标命中元素边界外的情况(与 Playwright 一致)
|
|
366
398
|
const ix = Math.round(x);
|
|
@@ -370,7 +402,7 @@ class SessionManager {
|
|
|
370
402
|
x: ix,
|
|
371
403
|
y: iy,
|
|
372
404
|
modifiers: this.modifiers,
|
|
373
|
-
});
|
|
405
|
+
}, timeout);
|
|
374
406
|
this.behaviorSimulator.setCurrentPosition({ x: ix, y: iy });
|
|
375
407
|
}
|
|
376
408
|
/**
|
|
@@ -422,15 +454,14 @@ class SessionManager {
|
|
|
422
454
|
* options.rawKeyDown=true 配合 options.autoRepeat=true 表示长按重复(与 Puppeteer 一致),
|
|
423
455
|
* 上层 unified-session 维护 pressedKeys Set 决定是否启用
|
|
424
456
|
*/
|
|
425
|
-
async keyDown(key, commands, options) {
|
|
457
|
+
async keyDown(key, commands, options, timeout) {
|
|
458
|
+
const deadline = timeout === undefined ? undefined : Date.now() + timeout;
|
|
426
459
|
this.ensureSession();
|
|
427
|
-
|
|
428
|
-
this.modifiers |= MODIFIER_KEYS[key];
|
|
429
|
-
}
|
|
460
|
+
const nextModifiers = MODIFIER_KEYS[key] ? this.modifiers | MODIFIER_KEYS[key] : this.modifiers;
|
|
430
461
|
const keyDefinition = getKeyDefinition(key);
|
|
431
462
|
const params = {
|
|
432
463
|
type: options?.rawKeyDown ? 'rawKeyDown' : 'keyDown',
|
|
433
|
-
modifiers:
|
|
464
|
+
modifiers: nextModifiers,
|
|
434
465
|
...keyDefinition,
|
|
435
466
|
};
|
|
436
467
|
if (commands && commands.length > 0) {
|
|
@@ -440,12 +471,17 @@ class SessionManager {
|
|
|
440
471
|
if (options?.autoRepeat) {
|
|
441
472
|
params.autoRepeat = true;
|
|
442
473
|
}
|
|
443
|
-
await this.send('Input.dispatchKeyEvent', params);
|
|
474
|
+
await this.send('Input.dispatchKeyEvent', params, timeout);
|
|
475
|
+
this.modifiers = nextModifiers;
|
|
476
|
+
if (deadline !== undefined) {
|
|
477
|
+
remainingNavigationTimeout(deadline);
|
|
478
|
+
}
|
|
444
479
|
}
|
|
445
480
|
/**
|
|
446
481
|
* 键盘释放
|
|
447
482
|
*/
|
|
448
|
-
async keyUp(key) {
|
|
483
|
+
async keyUp(key, timeout) {
|
|
484
|
+
const deadline = timeout === undefined ? undefined : Date.now() + timeout;
|
|
449
485
|
this.ensureSession();
|
|
450
486
|
const keyDefinition = getKeyDefinition(key);
|
|
451
487
|
const nextModifiers = MODIFIER_KEYS[key] ? this.modifiers & ~MODIFIER_KEYS[key] : this.modifiers;
|
|
@@ -453,14 +489,25 @@ class SessionManager {
|
|
|
453
489
|
type: 'keyUp',
|
|
454
490
|
modifiers: nextModifiers,
|
|
455
491
|
...keyDefinition,
|
|
456
|
-
});
|
|
492
|
+
}, timeout);
|
|
457
493
|
this.modifiers = nextModifiers;
|
|
494
|
+
if (deadline !== undefined) {
|
|
495
|
+
remainingNavigationTimeout(deadline);
|
|
496
|
+
}
|
|
458
497
|
}
|
|
459
498
|
/**
|
|
460
499
|
* 输入文本
|
|
461
500
|
*/
|
|
462
|
-
async type(text, delay = 0) {
|
|
501
|
+
async type(text, delay = 0, timeout = DEFAULT_TIMEOUT) {
|
|
463
502
|
this.ensureSession();
|
|
503
|
+
const deadline = Date.now() + timeout;
|
|
504
|
+
const remainingTimeout = () => {
|
|
505
|
+
const remaining = deadline - Date.now();
|
|
506
|
+
if (remaining <= 0) {
|
|
507
|
+
throw new TimeoutError('input timeout during typing');
|
|
508
|
+
}
|
|
509
|
+
return remaining;
|
|
510
|
+
};
|
|
464
511
|
// 归一化换行:\r\n 和 \r 都视作单个 \n
|
|
465
512
|
const normalized = text.replace(/\r\n?/g, '\n');
|
|
466
513
|
for (const char of normalized) {
|
|
@@ -473,36 +520,29 @@ class SessionManager {
|
|
|
473
520
|
nativeVirtualKeyCode: 13,
|
|
474
521
|
modifiers: this.modifiers,
|
|
475
522
|
};
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
...enterParams,
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
});
|
|
485
|
-
await this.send('Input.dispatchKeyEvent', {
|
|
486
|
-
type: 'keyUp',
|
|
487
|
-
...enterParams,
|
|
488
|
-
});
|
|
523
|
+
const keyDownTimeout = remainingTimeout();
|
|
524
|
+
try {
|
|
525
|
+
await this.send('Input.dispatchKeyEvent', { type: 'keyDown', ...enterParams }, keyDownTimeout);
|
|
526
|
+
await this.send('Input.dispatchKeyEvent', { type: 'char', text: '\r', ...enterParams }, remainingTimeout());
|
|
527
|
+
}
|
|
528
|
+
finally {
|
|
529
|
+
await this.send('Input.dispatchKeyEvent', { type: 'keyUp', ...enterParams }, Math.max(1, deadline - Date.now()));
|
|
530
|
+
}
|
|
489
531
|
}
|
|
490
532
|
else {
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
modifiers: this.modifiers,
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
modifiers: this.modifiers,
|
|
499
|
-
text: char,
|
|
500
|
-
});
|
|
533
|
+
const keyDownTimeout = remainingTimeout();
|
|
534
|
+
try {
|
|
535
|
+
await this.send('Input.dispatchKeyEvent', { type: 'keyDown', modifiers: this.modifiers, text: char }, keyDownTimeout);
|
|
536
|
+
}
|
|
537
|
+
finally {
|
|
538
|
+
await this.send('Input.dispatchKeyEvent', { type: 'keyUp', modifiers: this.modifiers, text: char }, Math.max(1, deadline - Date.now()));
|
|
539
|
+
}
|
|
501
540
|
}
|
|
502
541
|
if (delay > 0) {
|
|
503
|
-
await new Promise((r) => setTimeout(r, delay));
|
|
542
|
+
await new Promise((r) => setTimeout(r, Math.min(delay, remainingTimeout())));
|
|
504
543
|
}
|
|
505
544
|
}
|
|
545
|
+
remainingTimeout();
|
|
506
546
|
}
|
|
507
547
|
/**
|
|
508
548
|
* 触屏开始
|
|
@@ -556,6 +596,7 @@ class SessionManager {
|
|
|
556
596
|
catch {
|
|
557
597
|
throw new Error(`screenshot: 无法解析页面尺寸: ${result.value}`);
|
|
558
598
|
}
|
|
599
|
+
assertScreenshotBudget(width, height, scale ?? 1);
|
|
559
600
|
// 设置视口
|
|
560
601
|
await this.send('Emulation.setDeviceMetricsOverride', {
|
|
561
602
|
width,
|
|
@@ -565,6 +606,7 @@ class SessionManager {
|
|
|
565
606
|
});
|
|
566
607
|
try {
|
|
567
608
|
const { data } = (await this.send('Page.captureScreenshot', captureParams));
|
|
609
|
+
assertScreenshotBase64Budget(data);
|
|
568
610
|
return { data, format: effectiveFormat };
|
|
569
611
|
}
|
|
570
612
|
finally {
|
|
@@ -576,7 +618,19 @@ class SessionManager {
|
|
|
576
618
|
}
|
|
577
619
|
}
|
|
578
620
|
}
|
|
621
|
+
if (clip) {
|
|
622
|
+
assertScreenshotBudget(clip.width, clip.height, scale ?? 1);
|
|
623
|
+
}
|
|
624
|
+
else {
|
|
625
|
+
const metrics = (await this.send('Page.getLayoutMetrics'));
|
|
626
|
+
const viewport = metrics.cssVisualViewport ?? metrics.cssLayoutViewport;
|
|
627
|
+
if (!viewport) {
|
|
628
|
+
throw new Error('screenshot: 浏览器未返回 CSS 视口尺寸,未执行截图');
|
|
629
|
+
}
|
|
630
|
+
assertScreenshotBudget(viewport.clientWidth, viewport.clientHeight, 1);
|
|
631
|
+
}
|
|
579
632
|
const { data } = (await this.send('Page.captureScreenshot', captureParams));
|
|
633
|
+
assertScreenshotBase64Budget(data);
|
|
580
634
|
return { data, format: effectiveFormat };
|
|
581
635
|
}
|
|
582
636
|
/**
|
|
@@ -644,7 +698,10 @@ class SessionManager {
|
|
|
644
698
|
async getPageText(selector) {
|
|
645
699
|
this.ensureSession();
|
|
646
700
|
if (selector) {
|
|
647
|
-
return this.evaluate(`(s =>
|
|
701
|
+
return this.evaluate(`(s => {
|
|
702
|
+
const element = document.querySelector(s);
|
|
703
|
+
return element instanceof HTMLElement ? element.innerText : (element?.textContent ?? '');
|
|
704
|
+
})`, [selector]);
|
|
648
705
|
}
|
|
649
706
|
return this.evaluate('document.body.innerText');
|
|
650
707
|
}
|
|
@@ -728,7 +785,7 @@ class SessionManager {
|
|
|
728
785
|
el.getAttribute('placeholder') ||
|
|
729
786
|
el.textContent ||
|
|
730
787
|
''
|
|
731
|
-
).replace(
|
|
788
|
+
).replace(/\\s+/g, ' ').trim().slice(0, 160);
|
|
732
789
|
}
|
|
733
790
|
var selector = [
|
|
734
791
|
'button,a[href],input,textarea,select,[role]',
|
|
@@ -767,12 +824,12 @@ class SessionManager {
|
|
|
767
824
|
frames.push({
|
|
768
825
|
index,
|
|
769
826
|
frameId: node.frame.id,
|
|
770
|
-
parentFrameId: node.frame.parentId ?? parentFrameId,
|
|
827
|
+
parentFrameId: node.frame.parentId ?? parentFrameId ?? null,
|
|
771
828
|
url: node.frame.url,
|
|
772
|
-
title: index === 0 ? this.state?.title :
|
|
773
|
-
name: node.frame.name,
|
|
774
|
-
selector:
|
|
775
|
-
rect:
|
|
829
|
+
title: index === 0 ? (this.state?.title ?? null) : null,
|
|
830
|
+
name: node.frame.name ?? null,
|
|
831
|
+
selector: null,
|
|
832
|
+
rect: null,
|
|
776
833
|
mimeType: node.frame.mimeType,
|
|
777
834
|
});
|
|
778
835
|
for (const child of node.childFrames ?? []) {
|
|
@@ -843,6 +900,7 @@ class SessionManager {
|
|
|
843
900
|
feeds.push({href: l.href, type: l.getAttribute('type'), title: l.getAttribute('title') || undefined});
|
|
844
901
|
});
|
|
845
902
|
return {
|
|
903
|
+
url: location.href,
|
|
846
904
|
title: document.title,
|
|
847
905
|
description: meta('description'),
|
|
848
906
|
canonical: (document.querySelector('link[rel="canonical"]') || {}).href || undefined,
|
|
@@ -940,7 +998,7 @@ class SessionManager {
|
|
|
940
998
|
}
|
|
941
999
|
// ==================== IBrowserDriver: 输入(precise) ====================
|
|
942
1000
|
/** CDP 通用 inputKey 接口实现:直接转发 Input.dispatchKeyEvent,不维护 modifiers(由调用方提供) */
|
|
943
|
-
async inputKey(type, options = {}) {
|
|
1001
|
+
async inputKey(type, options = {}, timeout) {
|
|
944
1002
|
this.ensureSession();
|
|
945
1003
|
const params = { type };
|
|
946
1004
|
if (options.key !== undefined) {
|
|
@@ -973,11 +1031,15 @@ class SessionManager {
|
|
|
973
1031
|
if (options.commands && options.commands.length > 0) {
|
|
974
1032
|
params.commands = options.commands;
|
|
975
1033
|
}
|
|
976
|
-
await this.send('Input.dispatchKeyEvent', params);
|
|
1034
|
+
await this.send('Input.dispatchKeyEvent', params, timeout);
|
|
977
1035
|
}
|
|
978
1036
|
/** CDP 通用 inputMouse 接口实现:直接转发 Input.dispatchMouseEvent */
|
|
979
|
-
async inputMouse(type, x, y, options = {}) {
|
|
1037
|
+
async inputMouse(type, x, y, options = {}, timeout) {
|
|
1038
|
+
const deadline = timeout === undefined ? undefined : Date.now() + timeout;
|
|
980
1039
|
this.ensureSession();
|
|
1040
|
+
if (deadline !== undefined) {
|
|
1041
|
+
remainingNavigationTimeout(deadline);
|
|
1042
|
+
}
|
|
981
1043
|
const params = {
|
|
982
1044
|
type,
|
|
983
1045
|
x: Math.round(x),
|
|
@@ -998,7 +1060,39 @@ class SessionManager {
|
|
|
998
1060
|
if (options.modifiers !== undefined) {
|
|
999
1061
|
params.modifiers = options.modifiers;
|
|
1000
1062
|
}
|
|
1001
|
-
|
|
1063
|
+
if (type === 'mousePressed' && options.releaseAfterPress) {
|
|
1064
|
+
const cdp = this.cdp;
|
|
1065
|
+
const sessionId = this.sessionId ?? undefined;
|
|
1066
|
+
let failed = false;
|
|
1067
|
+
let failure;
|
|
1068
|
+
try {
|
|
1069
|
+
await withNavigationBudget(() => this.send('Input.dispatchMouseEvent', params, deadline === undefined ? undefined : remainingNavigationTimeout(deadline)), deadline);
|
|
1070
|
+
}
|
|
1071
|
+
catch (error) {
|
|
1072
|
+
failed = true;
|
|
1073
|
+
failure = error;
|
|
1074
|
+
}
|
|
1075
|
+
finally {
|
|
1076
|
+
try {
|
|
1077
|
+
await cdp.send('Input.dispatchMouseEvent', { ...params, type: 'mouseReleased' }, sessionId, 1000);
|
|
1078
|
+
}
|
|
1079
|
+
catch (error) {
|
|
1080
|
+
if (failed) {
|
|
1081
|
+
console.warn('[MCP] 鼠标释放清理失败,请检查原目标会话的鼠标状态');
|
|
1082
|
+
}
|
|
1083
|
+
else {
|
|
1084
|
+
failed = true;
|
|
1085
|
+
failure = error;
|
|
1086
|
+
}
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
if (failed) {
|
|
1090
|
+
throw failure;
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
else {
|
|
1094
|
+
await this.send('Input.dispatchMouseEvent', params, timeout);
|
|
1095
|
+
}
|
|
1002
1096
|
// mouseMoved 同步坐标到 BehaviorSimulator,与 mouseMove 方法保持一致
|
|
1003
1097
|
if (type === 'mouseMoved') {
|
|
1004
1098
|
this.behaviorSimulator.setCurrentPosition({ x: Math.round(x), y: Math.round(y) });
|
|
@@ -1010,8 +1104,8 @@ class SessionManager {
|
|
|
1010
1104
|
await this.dispatchTouch({ type, touchPoints });
|
|
1011
1105
|
}
|
|
1012
1106
|
/** CDP inputType 接口实现:直接复用现有 type 方法 */
|
|
1013
|
-
inputType(text, delay = 0) {
|
|
1014
|
-
return this.type(text, delay);
|
|
1107
|
+
inputType(text, delay = 0, timeout) {
|
|
1108
|
+
return this.type(text, delay, timeout);
|
|
1015
1109
|
}
|
|
1016
1110
|
// ==================== IBrowserDriver: Stealth(CDP 不支持) ====================
|
|
1017
1111
|
stealthKey(_key, _type, _modifiers) {
|
|
@@ -1044,14 +1138,73 @@ class SessionManager {
|
|
|
1044
1138
|
await this.attachToTarget(targetId);
|
|
1045
1139
|
await this.activateTarget(targetId);
|
|
1046
1140
|
}
|
|
1141
|
+
async activatePageWithAffected(targetId) {
|
|
1142
|
+
return this.withLock(async () => {
|
|
1143
|
+
const before = (await this.listTargets()).find((target) => target.targetId === targetId);
|
|
1144
|
+
if (!before) {
|
|
1145
|
+
throw new TargetNotFoundError(targetId);
|
|
1146
|
+
}
|
|
1147
|
+
if (this.pendingPageCondition) {
|
|
1148
|
+
const condition = this.pendingPageCondition;
|
|
1149
|
+
await this.assertPageCondition(targetId, condition.expectedUrl, condition.expectedRevision);
|
|
1150
|
+
this.pendingPageCondition = null;
|
|
1151
|
+
}
|
|
1152
|
+
await this.activateTarget(targetId);
|
|
1153
|
+
const after = (await this.listTargets()).find((target) => target.targetId === targetId);
|
|
1154
|
+
if (!after) {
|
|
1155
|
+
throw new TargetNotFoundError(targetId);
|
|
1156
|
+
}
|
|
1157
|
+
return { targetId, before, after };
|
|
1158
|
+
});
|
|
1159
|
+
}
|
|
1047
1160
|
/** IBrowserDriver 接口:选择操作目标(attach 即可) */
|
|
1048
|
-
async selectPage(targetId) {
|
|
1049
|
-
|
|
1161
|
+
async selectPage(targetId, timeout) {
|
|
1162
|
+
const deadline = timeout === undefined ? undefined : Date.now() + timeout;
|
|
1163
|
+
await this.withLock(() => this.attachToTargetInternal(targetId, deadline), deadline);
|
|
1050
1164
|
}
|
|
1051
1165
|
/** IBrowserDriver 接口:获取当前操作目标 ID */
|
|
1052
1166
|
getCurrentTargetId() {
|
|
1053
1167
|
return this.currentTargetId;
|
|
1054
1168
|
}
|
|
1169
|
+
async deselectPage(timeout) {
|
|
1170
|
+
const deadline = timeout === undefined ? undefined : Date.now() + timeout;
|
|
1171
|
+
try {
|
|
1172
|
+
if (this.sessionId && this.cdp?.isConnected) {
|
|
1173
|
+
await this.cdp.send('Target.detachFromTarget', { sessionId: this.sessionId }, undefined, deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
finally {
|
|
1177
|
+
this.clearAttachedTargetState();
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
async getPageSnapshot(targetId, timeout) {
|
|
1181
|
+
this.ensureConnected();
|
|
1182
|
+
const { targetInfo } = await this.sendBrowserCommand('Target.getTargetInfo', { targetId }, timeout);
|
|
1183
|
+
if (targetInfo.type !== 'page' || targetInfo.targetId !== targetId) {
|
|
1184
|
+
throw new TargetNotFoundError(targetId);
|
|
1185
|
+
}
|
|
1186
|
+
return {
|
|
1187
|
+
targetId,
|
|
1188
|
+
url: targetInfo.url ?? '',
|
|
1189
|
+
revision: `${this.revisionEpoch}:${this.revisions.get(targetId) ?? 0}`,
|
|
1190
|
+
};
|
|
1191
|
+
}
|
|
1192
|
+
setPageCondition(condition) {
|
|
1193
|
+
this.pendingPageCondition = condition;
|
|
1194
|
+
}
|
|
1195
|
+
async assertPageCondition(targetId, expectedUrl, expectedRevision, timeout) {
|
|
1196
|
+
const snapshot = await this.getPageSnapshot(targetId, timeout);
|
|
1197
|
+
if ((expectedUrl !== undefined && snapshot.url !== expectedUrl) ||
|
|
1198
|
+
(expectedRevision !== undefined && snapshot.revision !== expectedRevision)) {
|
|
1199
|
+
throw new PagePreconditionError({
|
|
1200
|
+
targetId,
|
|
1201
|
+
expectedUrl: expectedUrl ?? null,
|
|
1202
|
+
expectedRevision: expectedRevision ?? null,
|
|
1203
|
+
actualUrl: snapshot.url,
|
|
1204
|
+
actualRevision: snapshot.revision,
|
|
1205
|
+
});
|
|
1206
|
+
}
|
|
1207
|
+
}
|
|
1055
1208
|
/** IBrowserDriver 接口:设置当前操作目标 ID(attach 到指定 target) */
|
|
1056
1209
|
setCurrentTargetId(targetId) {
|
|
1057
1210
|
// CDP 路径不支持同步 setCurrentTargetId(attach 是异步的);
|
|
@@ -1087,12 +1240,30 @@ class SessionManager {
|
|
|
1087
1240
|
* tabId 在 CDP 模式下忽略(CDP 单 session 概念不区分 tab);
|
|
1088
1241
|
* browser-level 域(Target/Browser/SystemInfo/DeviceAccess/IO)走 sendBrowserCommand
|
|
1089
1242
|
*/
|
|
1090
|
-
debuggerSend(method, params, _tabId, timeout) {
|
|
1243
|
+
async debuggerSend(method, params, _tabId, timeout) {
|
|
1091
1244
|
const domain = method.split('.')[0];
|
|
1092
1245
|
const browserLevelDomains = ['Target', 'Browser', 'SystemInfo', 'DeviceAccess', 'IO'];
|
|
1093
1246
|
if (browserLevelDomains.includes(domain)) {
|
|
1247
|
+
if (this.pendingPageCondition) {
|
|
1248
|
+
throw new DriverCapabilityError('浏览器级 CDP 命令不支持页面条件,未执行动作');
|
|
1249
|
+
}
|
|
1094
1250
|
return this.sendBrowserCommand(method, params);
|
|
1095
1251
|
}
|
|
1252
|
+
if (this.pendingPageCondition) {
|
|
1253
|
+
const condition = this.pendingPageCondition;
|
|
1254
|
+
if (condition.targetId !== this.currentTargetId) {
|
|
1255
|
+
throw new PagePreconditionError({ targetId: condition.targetId, actualTargetId: this.currentTargetId });
|
|
1256
|
+
}
|
|
1257
|
+
await this.assertPageCondition(condition.targetId, condition.expectedUrl, condition.expectedRevision);
|
|
1258
|
+
this.pendingPageCondition = null;
|
|
1259
|
+
if (this.currentTargetId &&
|
|
1260
|
+
method !== 'Runtime.evaluate' &&
|
|
1261
|
+
method !== 'Runtime.callFunctionOn' &&
|
|
1262
|
+
!method.startsWith('Input.') &&
|
|
1263
|
+
!method.startsWith('Emulation.')) {
|
|
1264
|
+
this.revisions.set(this.currentTargetId, (this.revisions.get(this.currentTargetId) ?? 0) + 1);
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1096
1267
|
return this.send(method, params, timeout);
|
|
1097
1268
|
}
|
|
1098
1269
|
/**
|
|
@@ -1234,7 +1405,7 @@ class SessionManager {
|
|
|
1234
1405
|
const CDP_MARGIN = 5000;
|
|
1235
1406
|
const sendTimeout = timeout !== undefined ? timeout + CDP_MARGIN : undefined;
|
|
1236
1407
|
// 有参数时使用 callFunctionOn:避免大 payload 字符串拼接,参数通过协议结构化传递
|
|
1237
|
-
if (args
|
|
1408
|
+
if (args !== undefined) {
|
|
1238
1409
|
const { result: globalResult } = (await this.send('Runtime.evaluate', {
|
|
1239
1410
|
expression: 'globalThis',
|
|
1240
1411
|
returnByValue: false,
|
|
@@ -1317,10 +1488,26 @@ class SessionManager {
|
|
|
1317
1488
|
*
|
|
1318
1489
|
* IBrowserDriver 接口:可选 url 参数,url 提供时新建后立即导航
|
|
1319
1490
|
*/
|
|
1320
|
-
async newPage(url,
|
|
1491
|
+
async newPage(url, timeout, options = {}) {
|
|
1492
|
+
if (Object.values(options).some((value) => value !== undefined)) {
|
|
1493
|
+
throw new DriverCapabilityError('CDP 模式不支持 Chrome UI 的 newPage 配置参数,未创建页面;请使用 Extension 模式');
|
|
1494
|
+
}
|
|
1321
1495
|
const target = await this.withLock(async () => this.newPageInternal());
|
|
1322
1496
|
if (url) {
|
|
1323
|
-
|
|
1497
|
+
try {
|
|
1498
|
+
await this.navigate(url, { timeout });
|
|
1499
|
+
}
|
|
1500
|
+
catch (error) {
|
|
1501
|
+
throw creationError(error, {
|
|
1502
|
+
action: 'newPage',
|
|
1503
|
+
createdTargetId: target.targetId,
|
|
1504
|
+
targetId: target.targetId,
|
|
1505
|
+
managed: false,
|
|
1506
|
+
actionExecuted: true,
|
|
1507
|
+
actionStatus: 'partial',
|
|
1508
|
+
failureStage: 'navigation',
|
|
1509
|
+
});
|
|
1510
|
+
}
|
|
1324
1511
|
return {
|
|
1325
1512
|
targetId: target.targetId,
|
|
1326
1513
|
url: this.state?.url ?? url,
|
|
@@ -1347,17 +1534,31 @@ class SessionManager {
|
|
|
1347
1534
|
* 关闭页面
|
|
1348
1535
|
*/
|
|
1349
1536
|
async closePage(targetId) {
|
|
1537
|
+
if (!targetId) {
|
|
1538
|
+
throw new TargetNotFoundError('targetId is required');
|
|
1539
|
+
}
|
|
1350
1540
|
return this.withLock(async () => {
|
|
1351
1541
|
this.ensureConnected();
|
|
1352
|
-
const
|
|
1353
|
-
if (!
|
|
1354
|
-
throw new TargetNotFoundError(
|
|
1542
|
+
const targets = await this.listTargets();
|
|
1543
|
+
if (!targets.some((target) => target.targetId === targetId)) {
|
|
1544
|
+
throw new TargetNotFoundError(targetId);
|
|
1545
|
+
}
|
|
1546
|
+
const id = targetId;
|
|
1547
|
+
if (this.pendingPageCondition) {
|
|
1548
|
+
const condition = this.pendingPageCondition;
|
|
1549
|
+
await this.assertPageCondition(id, condition.expectedUrl, condition.expectedRevision);
|
|
1550
|
+
this.pendingPageCondition = null;
|
|
1551
|
+
}
|
|
1552
|
+
const result = (await this.cdp.send('Target.closeTarget', { targetId: id }));
|
|
1553
|
+
if (!result.success) {
|
|
1554
|
+
throw new TargetNotFoundError(targetId);
|
|
1355
1555
|
}
|
|
1356
|
-
|
|
1556
|
+
this.revisions.delete(id);
|
|
1357
1557
|
// 如果关闭的是当前页面,清除会话状态
|
|
1358
1558
|
if (id === this.currentTargetId) {
|
|
1359
1559
|
this.clearAttachedTargetState();
|
|
1360
1560
|
}
|
|
1561
|
+
this.targetLogs.delete(id);
|
|
1361
1562
|
});
|
|
1362
1563
|
}
|
|
1363
1564
|
/**
|
|
@@ -1384,12 +1585,12 @@ class SessionManager {
|
|
|
1384
1585
|
getState() {
|
|
1385
1586
|
return this.state;
|
|
1386
1587
|
}
|
|
1387
|
-
async getLiveState() {
|
|
1588
|
+
async getLiveState(timeout) {
|
|
1388
1589
|
if (!this.currentTargetId) {
|
|
1389
1590
|
return this.state;
|
|
1390
1591
|
}
|
|
1391
1592
|
this.ensureConnected();
|
|
1392
|
-
const { targetInfo } = await this.sendBrowserCommand('Target.getTargetInfo', { targetId: this.currentTargetId });
|
|
1593
|
+
const { targetInfo } = await this.sendBrowserCommand('Target.getTargetInfo', { targetId: this.currentTargetId }, timeout);
|
|
1393
1594
|
this.state = {
|
|
1394
1595
|
url: targetInfo.url ?? '',
|
|
1395
1596
|
title: targetInfo.title ?? '',
|
|
@@ -1410,17 +1611,40 @@ class SessionManager {
|
|
|
1410
1611
|
* 多步操作(type 循环、fullPage 截图等)的 await 间隙可能被 close() 打断,
|
|
1411
1612
|
* ensureSession() 确保在当前 tick 内 this.cdp 非空
|
|
1412
1613
|
*/
|
|
1413
|
-
send(method, params, timeout) {
|
|
1614
|
+
async send(method, params, timeout) {
|
|
1615
|
+
const deadline = timeout === undefined ? undefined : Date.now() + timeout;
|
|
1414
1616
|
this.ensureSession();
|
|
1415
|
-
|
|
1617
|
+
const mutation = method === 'Page.navigate' ||
|
|
1618
|
+
method === 'Page.navigateToHistoryEntry' ||
|
|
1619
|
+
method === 'Page.reload' ||
|
|
1620
|
+
method === 'Runtime.evaluate' ||
|
|
1621
|
+
method === 'Runtime.callFunctionOn' ||
|
|
1622
|
+
method.startsWith('Input.') ||
|
|
1623
|
+
method.startsWith('Emulation.');
|
|
1624
|
+
const condition = mutation ? this.pendingPageCondition : null;
|
|
1625
|
+
if (condition) {
|
|
1626
|
+
if (condition.targetId !== this.currentTargetId) {
|
|
1627
|
+
throw new PagePreconditionError({
|
|
1628
|
+
targetId: condition.targetId,
|
|
1629
|
+
actualTargetId: this.currentTargetId,
|
|
1630
|
+
});
|
|
1631
|
+
}
|
|
1632
|
+
await this.assertPageCondition(condition.targetId, condition.expectedUrl, condition.expectedRevision, timeout);
|
|
1633
|
+
this.pendingPageCondition = null;
|
|
1634
|
+
}
|
|
1635
|
+
const remaining = deadline === undefined ? undefined : remainingNavigationTimeout(deadline);
|
|
1636
|
+
if (mutation && this.currentTargetId) {
|
|
1637
|
+
this.revisions.set(this.currentTargetId, (this.revisions.get(this.currentTargetId) ?? 0) + 1);
|
|
1638
|
+
}
|
|
1639
|
+
return this.cdp.send(method, params, this.sessionId ?? undefined, remaining);
|
|
1416
1640
|
}
|
|
1417
1641
|
/**
|
|
1418
1642
|
* 发送 browser-level CDP 命令(不携带 sessionId)
|
|
1419
1643
|
* 用于 Target.*、Browser.* 等浏览器级命令
|
|
1420
1644
|
*/
|
|
1421
|
-
sendBrowserCommand(method, params) {
|
|
1645
|
+
sendBrowserCommand(method, params, timeout) {
|
|
1422
1646
|
this.ensureConnected();
|
|
1423
|
-
return this.cdp.send(method, params);
|
|
1647
|
+
return this.cdp.send(method, params, undefined, timeout);
|
|
1424
1648
|
}
|
|
1425
1649
|
/**
|
|
1426
1650
|
* 派发 CDP Input.dispatchTouchEvent,临时启用 touch 模拟避免命令挂起
|
|
@@ -1439,13 +1663,189 @@ class SessionManager {
|
|
|
1439
1663
|
}
|
|
1440
1664
|
}
|
|
1441
1665
|
}
|
|
1442
|
-
/**
|
|
1443
|
-
|
|
1444
|
-
* 预先注册避免 Page.navigate 返回和监听器注册之间遗漏早期请求
|
|
1445
|
-
*/
|
|
1446
|
-
startNetworkIdleWatcher(timeout, idleTime = 500) {
|
|
1666
|
+
/** 在触发导航前注册相应等待器,并按主 frame loader 过滤生命周期事件 */
|
|
1667
|
+
startNavigationWait(wait, timeout, signal, bindFromFrameNavigation) {
|
|
1447
1668
|
this.ensureSession();
|
|
1448
|
-
|
|
1669
|
+
const cdp = this.cdp;
|
|
1670
|
+
const sessionId = this.sessionId;
|
|
1671
|
+
const baselineLoaderId = this.mainFrameLoaderId;
|
|
1672
|
+
const lifecycleName = wait === 'domcontentloaded' ? 'DOMContentLoaded' : wait === 'load' ? 'load' : 'networkIdle';
|
|
1673
|
+
const seenLifecycle = new Set();
|
|
1674
|
+
const seenSameDocumentFrames = new Set();
|
|
1675
|
+
const sameDocumentPendingRequests = new Set();
|
|
1676
|
+
let actionStarted = false;
|
|
1677
|
+
let expectedFrameId = null;
|
|
1678
|
+
let expectedLoaderId = null;
|
|
1679
|
+
let expectedSameDocumentFrameId = null;
|
|
1680
|
+
let sameDocumentIdleTimer = null;
|
|
1681
|
+
let settled = false;
|
|
1682
|
+
let finish = () => { };
|
|
1683
|
+
let fail = () => { };
|
|
1684
|
+
const lifecycleKey = (frameId, loaderId, name) => JSON.stringify([frameId, loaderId, name]);
|
|
1685
|
+
const completeIfSeen = () => {
|
|
1686
|
+
if (expectedFrameId !== null &&
|
|
1687
|
+
expectedLoaderId !== null &&
|
|
1688
|
+
seenLifecycle.has(lifecycleKey(expectedFrameId, expectedLoaderId, lifecycleName))) {
|
|
1689
|
+
finish();
|
|
1690
|
+
}
|
|
1691
|
+
};
|
|
1692
|
+
const checkSameDocumentIdle = () => {
|
|
1693
|
+
if (settled ||
|
|
1694
|
+
expectedSameDocumentFrameId === null ||
|
|
1695
|
+
!seenSameDocumentFrames.has(expectedSameDocumentFrameId)) {
|
|
1696
|
+
return;
|
|
1697
|
+
}
|
|
1698
|
+
if (sameDocumentPendingRequests.size > 0) {
|
|
1699
|
+
if (sameDocumentIdleTimer !== null) {
|
|
1700
|
+
clearTimeout(sameDocumentIdleTimer);
|
|
1701
|
+
sameDocumentIdleTimer = null;
|
|
1702
|
+
}
|
|
1703
|
+
return;
|
|
1704
|
+
}
|
|
1705
|
+
if (sameDocumentIdleTimer === null) {
|
|
1706
|
+
sameDocumentIdleTimer = setTimeout(() => finish(), 500);
|
|
1707
|
+
}
|
|
1708
|
+
};
|
|
1709
|
+
const completeSameDocumentIfSeen = () => {
|
|
1710
|
+
if (expectedSameDocumentFrameId === null || !seenSameDocumentFrames.has(expectedSameDocumentFrameId)) {
|
|
1711
|
+
return;
|
|
1712
|
+
}
|
|
1713
|
+
if (wait === 'networkidle') {
|
|
1714
|
+
checkSameDocumentIdle();
|
|
1715
|
+
}
|
|
1716
|
+
else {
|
|
1717
|
+
finish();
|
|
1718
|
+
}
|
|
1719
|
+
};
|
|
1720
|
+
const setExpectedLoader = (frameId, loaderId) => {
|
|
1721
|
+
if (settled || !loaderId) {
|
|
1722
|
+
return;
|
|
1723
|
+
}
|
|
1724
|
+
expectedSameDocumentFrameId = null;
|
|
1725
|
+
if (sameDocumentIdleTimer !== null) {
|
|
1726
|
+
clearTimeout(sameDocumentIdleTimer);
|
|
1727
|
+
sameDocumentIdleTimer = null;
|
|
1728
|
+
}
|
|
1729
|
+
expectedFrameId = frameId;
|
|
1730
|
+
expectedLoaderId = loaderId;
|
|
1731
|
+
completeIfSeen();
|
|
1732
|
+
};
|
|
1733
|
+
const setExpectedSameDocument = (frameId) => {
|
|
1734
|
+
if (settled) {
|
|
1735
|
+
return;
|
|
1736
|
+
}
|
|
1737
|
+
expectedSameDocumentFrameId = frameId;
|
|
1738
|
+
completeSameDocumentIfSeen();
|
|
1739
|
+
};
|
|
1740
|
+
const promise = new Promise((resolve, reject) => {
|
|
1741
|
+
const cleanup = () => {
|
|
1742
|
+
clearTimeout(timeoutId);
|
|
1743
|
+
if (sameDocumentIdleTimer !== null) {
|
|
1744
|
+
clearTimeout(sameDocumentIdleTimer);
|
|
1745
|
+
sameDocumentIdleTimer = null;
|
|
1746
|
+
}
|
|
1747
|
+
signal?.removeEventListener('abort', onAbort);
|
|
1748
|
+
cdp.offEvent('Page.frameNavigated', onFrameNavigated);
|
|
1749
|
+
cdp.offEvent('Page.lifecycleEvent', onLifecycleEvent);
|
|
1750
|
+
cdp.offEvent('Page.navigatedWithinDocument', onNavigatedWithinDocument);
|
|
1751
|
+
cdp.offEvent('Network.requestWillBeSent', onRequestStarted);
|
|
1752
|
+
cdp.offEvent('Network.loadingFinished', onRequestFinished);
|
|
1753
|
+
cdp.offEvent('Network.loadingFailed', onRequestFinished);
|
|
1754
|
+
cdp.removeListener('disconnected', onDisconnected);
|
|
1755
|
+
};
|
|
1756
|
+
finish = () => {
|
|
1757
|
+
if (settled) {
|
|
1758
|
+
return;
|
|
1759
|
+
}
|
|
1760
|
+
settled = true;
|
|
1761
|
+
cleanup();
|
|
1762
|
+
resolve();
|
|
1763
|
+
};
|
|
1764
|
+
fail = (error) => {
|
|
1765
|
+
if (settled) {
|
|
1766
|
+
return;
|
|
1767
|
+
}
|
|
1768
|
+
settled = true;
|
|
1769
|
+
cleanup();
|
|
1770
|
+
reject(error);
|
|
1771
|
+
};
|
|
1772
|
+
const onFrameNavigated = (params, eventSessionId) => {
|
|
1773
|
+
if (!actionStarted || !bindFromFrameNavigation || eventSessionId !== sessionId) {
|
|
1774
|
+
return;
|
|
1775
|
+
}
|
|
1776
|
+
const frame = params.frame;
|
|
1777
|
+
if (frame?.id && !frame.parentId && frame.loaderId && frame.loaderId !== baselineLoaderId) {
|
|
1778
|
+
setExpectedLoader(frame.id, frame.loaderId);
|
|
1779
|
+
}
|
|
1780
|
+
};
|
|
1781
|
+
const onLifecycleEvent = (params, eventSessionId) => {
|
|
1782
|
+
if (!actionStarted || eventSessionId !== sessionId) {
|
|
1783
|
+
return;
|
|
1784
|
+
}
|
|
1785
|
+
const event = params;
|
|
1786
|
+
if (!event.frameId || !event.loaderId || !event.name) {
|
|
1787
|
+
return;
|
|
1788
|
+
}
|
|
1789
|
+
seenLifecycle.add(lifecycleKey(event.frameId, event.loaderId, event.name));
|
|
1790
|
+
completeIfSeen();
|
|
1791
|
+
};
|
|
1792
|
+
const onNavigatedWithinDocument = (params, eventSessionId) => {
|
|
1793
|
+
if (!actionStarted || eventSessionId !== sessionId) {
|
|
1794
|
+
return;
|
|
1795
|
+
}
|
|
1796
|
+
const frameId = params.frameId;
|
|
1797
|
+
if (frameId && frameId === this.mainFrameId) {
|
|
1798
|
+
seenSameDocumentFrames.add(frameId);
|
|
1799
|
+
completeSameDocumentIfSeen();
|
|
1800
|
+
}
|
|
1801
|
+
};
|
|
1802
|
+
const onRequestStarted = (params, eventSessionId) => {
|
|
1803
|
+
if (!actionStarted || eventSessionId !== sessionId) {
|
|
1804
|
+
return;
|
|
1805
|
+
}
|
|
1806
|
+
const requestId = params.requestId;
|
|
1807
|
+
if (requestId) {
|
|
1808
|
+
sameDocumentPendingRequests.add(requestId);
|
|
1809
|
+
checkSameDocumentIdle();
|
|
1810
|
+
}
|
|
1811
|
+
};
|
|
1812
|
+
const onRequestFinished = (params, eventSessionId) => {
|
|
1813
|
+
if (!actionStarted || eventSessionId !== sessionId) {
|
|
1814
|
+
return;
|
|
1815
|
+
}
|
|
1816
|
+
const requestId = params.requestId;
|
|
1817
|
+
if (requestId) {
|
|
1818
|
+
sameDocumentPendingRequests.delete(requestId);
|
|
1819
|
+
checkSameDocumentIdle();
|
|
1820
|
+
}
|
|
1821
|
+
};
|
|
1822
|
+
const onAbort = () => {
|
|
1823
|
+
fail(signal?.reason instanceof Error ? signal.reason : new Error('导航等待已取消'));
|
|
1824
|
+
};
|
|
1825
|
+
const onDisconnected = () => fail(new Error('CDP 连接已关闭'));
|
|
1826
|
+
const timeoutId = setTimeout(() => fail(new NavigationTimeoutError(wait, timeout)), timeout);
|
|
1827
|
+
cdp.onEvent('Page.frameNavigated', onFrameNavigated);
|
|
1828
|
+
cdp.onEvent('Page.lifecycleEvent', onLifecycleEvent);
|
|
1829
|
+
cdp.onEvent('Page.navigatedWithinDocument', onNavigatedWithinDocument);
|
|
1830
|
+
if (wait === 'networkidle') {
|
|
1831
|
+
cdp.onEvent('Network.requestWillBeSent', onRequestStarted);
|
|
1832
|
+
cdp.onEvent('Network.loadingFinished', onRequestFinished);
|
|
1833
|
+
cdp.onEvent('Network.loadingFailed', onRequestFinished);
|
|
1834
|
+
}
|
|
1835
|
+
cdp.once('disconnected', onDisconnected);
|
|
1836
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
1837
|
+
if (signal?.aborted) {
|
|
1838
|
+
onAbort();
|
|
1839
|
+
}
|
|
1840
|
+
});
|
|
1841
|
+
return {
|
|
1842
|
+
promise,
|
|
1843
|
+
markActionStarted: () => {
|
|
1844
|
+
actionStarted = true;
|
|
1845
|
+
},
|
|
1846
|
+
setExpectedLoader,
|
|
1847
|
+
setExpectedSameDocument,
|
|
1848
|
+
};
|
|
1449
1849
|
}
|
|
1450
1850
|
/**
|
|
1451
1851
|
* 核心网络空闲等待逻辑
|
|
@@ -1453,7 +1853,7 @@ class SessionManager {
|
|
|
1453
1853
|
* 捕获 cdp 引用防止 close() 并发置 null,用局部 Set 追踪请求避免污染成员变量
|
|
1454
1854
|
* close() 时通过 'disconnected' 信号立即 reject
|
|
1455
1855
|
*/
|
|
1456
|
-
buildNetworkIdlePromise(cdp, timeout, idleTime) {
|
|
1856
|
+
buildNetworkIdlePromise(cdp, timeout, idleTime, signal) {
|
|
1457
1857
|
const localPendingRequests = new Set();
|
|
1458
1858
|
const sessionId = this.sessionId;
|
|
1459
1859
|
return new Promise((resolve, reject) => {
|
|
@@ -1498,11 +1898,16 @@ class SessionManager {
|
|
|
1498
1898
|
if (timeoutTimer !== null) {
|
|
1499
1899
|
clearTimeout(timeoutTimer);
|
|
1500
1900
|
}
|
|
1901
|
+
signal?.removeEventListener('abort', onAbort);
|
|
1501
1902
|
cdp.offEvent('Network.requestWillBeSent', onRequestStart);
|
|
1502
1903
|
cdp.offEvent('Network.loadingFinished', onRequestEnd);
|
|
1503
1904
|
cdp.offEvent('Network.loadingFailed', onRequestEnd);
|
|
1504
1905
|
cdp.removeListener('disconnected', onDisconnected);
|
|
1505
1906
|
};
|
|
1907
|
+
const onAbort = () => {
|
|
1908
|
+
cleanup();
|
|
1909
|
+
reject(signal?.reason instanceof Error ? signal.reason : new Error('网络空闲等待已取消'));
|
|
1910
|
+
};
|
|
1506
1911
|
timeoutTimer = setTimeout(() => {
|
|
1507
1912
|
cleanup();
|
|
1508
1913
|
reject(new NavigationTimeoutError('networkidle', timeout));
|
|
@@ -1515,13 +1920,18 @@ class SessionManager {
|
|
|
1515
1920
|
cdp.onEvent('Network.requestWillBeSent', onRequestStart);
|
|
1516
1921
|
cdp.onEvent('Network.loadingFinished', onRequestEnd);
|
|
1517
1922
|
cdp.onEvent('Network.loadingFailed', onRequestEnd);
|
|
1923
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
1924
|
+
if (signal?.aborted) {
|
|
1925
|
+
onAbort();
|
|
1926
|
+
return;
|
|
1927
|
+
}
|
|
1518
1928
|
checkIdle();
|
|
1519
1929
|
});
|
|
1520
1930
|
}
|
|
1521
1931
|
/**
|
|
1522
1932
|
* 附加到指定页面(内部版本,不加锁,供 launch/connect 等已持锁方法调用)
|
|
1523
1933
|
*/
|
|
1524
|
-
async attachToTargetInternal(targetId) {
|
|
1934
|
+
async attachToTargetInternal(targetId, deadline) {
|
|
1525
1935
|
this.ensureConnected();
|
|
1526
1936
|
// 如果已经附加到同一个 target,跳过
|
|
1527
1937
|
if (this.currentTargetId === targetId && this.sessionId) {
|
|
@@ -1530,9 +1940,9 @@ class SessionManager {
|
|
|
1530
1940
|
// 如果有之前的 session,先分离
|
|
1531
1941
|
if (this.sessionId) {
|
|
1532
1942
|
try {
|
|
1533
|
-
await this.
|
|
1943
|
+
await this.sendBrowserCommand('Target.detachFromTarget', {
|
|
1534
1944
|
sessionId: this.sessionId,
|
|
1535
|
-
});
|
|
1945
|
+
}, deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
|
|
1536
1946
|
}
|
|
1537
1947
|
catch {
|
|
1538
1948
|
// 忽略分离错误
|
|
@@ -1540,14 +1950,17 @@ class SessionManager {
|
|
|
1540
1950
|
}
|
|
1541
1951
|
this.clearAttachedTargetState();
|
|
1542
1952
|
// 附加到目标
|
|
1543
|
-
const { sessionId } = (await this.
|
|
1953
|
+
const { sessionId } = (await this.sendBrowserCommand('Target.attachToTarget', {
|
|
1544
1954
|
targetId,
|
|
1545
1955
|
flatten: true,
|
|
1546
|
-
}));
|
|
1956
|
+
}, deadline === undefined ? undefined : remainingNavigationTimeout(deadline)));
|
|
1547
1957
|
this.sessionId = sessionId;
|
|
1548
1958
|
this.currentTargetId = targetId;
|
|
1959
|
+
const logs = this.targetLogs.get(targetId);
|
|
1960
|
+
this.consoleLogs = logs?.console ?? [];
|
|
1961
|
+
this.networkRequests = logs?.network ?? [];
|
|
1549
1962
|
// 初始化会话
|
|
1550
|
-
await this.initSession();
|
|
1963
|
+
await this.initSession(deadline);
|
|
1551
1964
|
}
|
|
1552
1965
|
/**
|
|
1553
1966
|
* 新建页面(内部版本,不加锁,供 launch 等已持锁方法调用)
|
|
@@ -1556,8 +1969,30 @@ class SessionManager {
|
|
|
1556
1969
|
this.ensureConnected();
|
|
1557
1970
|
const { targetId } = (await this.cdp.send('Target.createTarget', {
|
|
1558
1971
|
url: 'about:blank',
|
|
1972
|
+
}).catch((error) => {
|
|
1973
|
+
throw creationError(error, {
|
|
1974
|
+
action: 'newPage',
|
|
1975
|
+
createdTargetId: null,
|
|
1976
|
+
managed: null,
|
|
1977
|
+
actionExecuted: 'unknown',
|
|
1978
|
+
actionStatus: 'unknown',
|
|
1979
|
+
failureStage: 'create',
|
|
1980
|
+
});
|
|
1559
1981
|
}));
|
|
1560
|
-
|
|
1982
|
+
try {
|
|
1983
|
+
await this.attachToTargetInternal(targetId);
|
|
1984
|
+
}
|
|
1985
|
+
catch (error) {
|
|
1986
|
+
throw creationError(error, {
|
|
1987
|
+
action: 'newPage',
|
|
1988
|
+
createdTargetId: targetId,
|
|
1989
|
+
targetId,
|
|
1990
|
+
managed: false,
|
|
1991
|
+
actionExecuted: true,
|
|
1992
|
+
actionStatus: 'partial',
|
|
1993
|
+
failureStage: 'attach',
|
|
1994
|
+
});
|
|
1995
|
+
}
|
|
1561
1996
|
return {
|
|
1562
1997
|
targetId,
|
|
1563
1998
|
type: 'page',
|
|
@@ -1566,10 +2001,16 @@ class SessionManager {
|
|
|
1566
2001
|
};
|
|
1567
2002
|
}
|
|
1568
2003
|
clearAttachedTargetState() {
|
|
1569
|
-
this.
|
|
2004
|
+
if (this.currentTargetId) {
|
|
2005
|
+
this.targetLogs.set(this.currentTargetId, { console: this.consoleLogs, network: this.networkRequests });
|
|
2006
|
+
}
|
|
2007
|
+
this.consoleLogs = [];
|
|
2008
|
+
this.networkRequests = [];
|
|
2009
|
+
this.requestMap.clear();
|
|
1570
2010
|
this.challengeRequired = false;
|
|
1571
2011
|
this.runtimeEnabled = false;
|
|
1572
2012
|
this.mainFrameId = null;
|
|
2013
|
+
this.mainFrameLoaderId = null;
|
|
1573
2014
|
this.modifiers = 0;
|
|
1574
2015
|
this.sessionId = null;
|
|
1575
2016
|
this.currentTargetId = null;
|
|
@@ -1594,6 +2035,10 @@ class SessionManager {
|
|
|
1594
2035
|
this.launcher = null;
|
|
1595
2036
|
}
|
|
1596
2037
|
this.clearAttachedTargetState();
|
|
2038
|
+
this.targetLogs.clear();
|
|
2039
|
+
this.revisionEpoch = randomUUID();
|
|
2040
|
+
this.revisions.clear();
|
|
2041
|
+
this.pendingPageCondition = null;
|
|
1597
2042
|
this.behaviorSimulator.setCurrentPosition({ x: 0, y: 0 });
|
|
1598
2043
|
this.listenersInstalled = false;
|
|
1599
2044
|
this.connectedPort = 0;
|
|
@@ -1601,25 +2046,44 @@ class SessionManager {
|
|
|
1601
2046
|
/**
|
|
1602
2047
|
* 串行执行操作(防止并发竞态)
|
|
1603
2048
|
*/
|
|
1604
|
-
async withLock(fn) {
|
|
2049
|
+
async withLock(fn, deadline) {
|
|
1605
2050
|
const previousLock = this.operationLock;
|
|
1606
2051
|
let releaseLock;
|
|
1607
2052
|
this.operationLock = new Promise((resolve) => {
|
|
1608
2053
|
releaseLock = resolve;
|
|
1609
2054
|
});
|
|
2055
|
+
let acquired = false;
|
|
1610
2056
|
try {
|
|
1611
|
-
await previousLock;
|
|
2057
|
+
await waitForNavigationQueue(previousLock, deadline);
|
|
2058
|
+
acquired = true;
|
|
1612
2059
|
return await fn();
|
|
1613
2060
|
}
|
|
2061
|
+
catch (error) {
|
|
2062
|
+
if (deadline !== undefined) {
|
|
2063
|
+
const context = { actionExecuted: 'unknown', actionStatus: 'unknown', retryable: false };
|
|
2064
|
+
if (error instanceof CDPError && error.message.startsWith('CDP 命令超时: ')) {
|
|
2065
|
+
throw new StructuredToolError('TIMEOUT', error.message, '请回读实际页面,勿自动重放导航', context);
|
|
2066
|
+
}
|
|
2067
|
+
if (error instanceof TimeoutError || error instanceof NavigationTimeoutError) {
|
|
2068
|
+
Object.assign(error.context, context);
|
|
2069
|
+
}
|
|
2070
|
+
}
|
|
2071
|
+
throw error;
|
|
2072
|
+
}
|
|
1614
2073
|
finally {
|
|
1615
|
-
|
|
2074
|
+
if (acquired) {
|
|
2075
|
+
releaseLock();
|
|
2076
|
+
}
|
|
2077
|
+
else {
|
|
2078
|
+
void previousLock.then(releaseLock, releaseLock);
|
|
2079
|
+
}
|
|
1616
2080
|
}
|
|
1617
2081
|
}
|
|
1618
2082
|
/**
|
|
1619
2083
|
* 等待多个事件中的任一个触发
|
|
1620
2084
|
*
|
|
1621
|
-
*
|
|
1622
|
-
*
|
|
2085
|
+
* 监听当前 session 的加载完成、主 frame BFCache 恢复和同文档导航,
|
|
2086
|
+
* 接受完成事件后清理所有监听器和超时定时器
|
|
1623
2087
|
* close() 时通过 'disconnected' 信号立即 reject,不必等 timer 超时
|
|
1624
2088
|
*/
|
|
1625
2089
|
waitForAnyEvent(events, timeout) {
|
|
@@ -1648,10 +2112,22 @@ class SessionManager {
|
|
|
1648
2112
|
};
|
|
1649
2113
|
cdp.once('disconnected', onDisconnected);
|
|
1650
2114
|
for (const event of events) {
|
|
1651
|
-
const listener = (
|
|
2115
|
+
const listener = (params, eventSessionId) => {
|
|
1652
2116
|
if (eventSessionId !== sessionId) {
|
|
1653
2117
|
return;
|
|
1654
2118
|
}
|
|
2119
|
+
if (event === 'Page.frameNavigated') {
|
|
2120
|
+
const navigation = params;
|
|
2121
|
+
if (navigation.type !== 'BackForwardCacheRestore' ||
|
|
2122
|
+
navigation.frame?.id !== this.mainFrameId ||
|
|
2123
|
+
navigation.frame.parentId) {
|
|
2124
|
+
return;
|
|
2125
|
+
}
|
|
2126
|
+
}
|
|
2127
|
+
if (event === 'Page.navigatedWithinDocument' &&
|
|
2128
|
+
params.frameId !== this.mainFrameId) {
|
|
2129
|
+
return;
|
|
2130
|
+
}
|
|
1655
2131
|
cleanup();
|
|
1656
2132
|
resolve();
|
|
1657
2133
|
};
|
|
@@ -1663,27 +2139,30 @@ class SessionManager {
|
|
|
1663
2139
|
/**
|
|
1664
2140
|
* 初始化会话
|
|
1665
2141
|
*/
|
|
1666
|
-
async initSession() {
|
|
2142
|
+
async initSession(deadline) {
|
|
2143
|
+
const remaining = () => (deadline === undefined ? undefined : remainingNavigationTimeout(deadline));
|
|
1667
2144
|
// 启用必要的域
|
|
1668
2145
|
await Promise.all([
|
|
1669
|
-
this.send('Page.enable'),
|
|
1670
|
-
this.send('DOM.enable'),
|
|
1671
|
-
this.send('Network.enable'),
|
|
1672
|
-
this.send('Log.enable'),
|
|
2146
|
+
this.send('Page.enable', undefined, remaining()),
|
|
2147
|
+
this.send('DOM.enable', undefined, remaining()),
|
|
2148
|
+
this.send('Network.enable', undefined, remaining()),
|
|
2149
|
+
this.send('Log.enable', undefined, remaining()),
|
|
1673
2150
|
]);
|
|
1674
|
-
|
|
2151
|
+
await this.send('Page.setLifecycleEventsEnabled', { enabled: true }, remaining());
|
|
2152
|
+
const { frameTree } = await this.send('Page.getFrameTree', undefined, remaining());
|
|
1675
2153
|
this.mainFrameId = frameTree.frame.id;
|
|
2154
|
+
this.mainFrameLoaderId = frameTree.frame.loaderId ?? null;
|
|
1676
2155
|
// 根据 stealth 模式注入反检测脚本。不在当前文档 Runtime.evaluate,避免干扰 Cloudflare JS Challenge
|
|
1677
2156
|
if (this.stealthMode !== 'off') {
|
|
1678
2157
|
const script = getAntiDetectionScript(this.stealthMode);
|
|
1679
2158
|
await this.send('Page.addScriptToEvaluateOnNewDocument', {
|
|
1680
2159
|
source: script,
|
|
1681
|
-
});
|
|
2160
|
+
}, remaining());
|
|
1682
2161
|
}
|
|
1683
2162
|
// 监听事件
|
|
1684
2163
|
this.setupEventListeners();
|
|
1685
2164
|
// 更新状态
|
|
1686
|
-
await this.updateState();
|
|
2165
|
+
await this.updateState(remaining());
|
|
1687
2166
|
}
|
|
1688
2167
|
/**
|
|
1689
2168
|
* 设置事件监听(幂等,只安装一次)
|
|
@@ -1700,6 +2179,15 @@ class SessionManager {
|
|
|
1700
2179
|
const frame = params.frame;
|
|
1701
2180
|
if (frame?.id && !frame.parentId) {
|
|
1702
2181
|
this.mainFrameId = frame.id;
|
|
2182
|
+
this.mainFrameLoaderId = frame.loaderId ?? null;
|
|
2183
|
+
if (this.currentTargetId) {
|
|
2184
|
+
this.revisions.set(this.currentTargetId, (this.revisions.get(this.currentTargetId) ?? 0) + 1);
|
|
2185
|
+
}
|
|
2186
|
+
}
|
|
2187
|
+
});
|
|
2188
|
+
this.cdp.onEvent('Page.navigatedWithinDocument', (_params, eventSessionId) => {
|
|
2189
|
+
if (this.isCurrentSessionEvent(eventSessionId) && this.currentTargetId) {
|
|
2190
|
+
this.revisions.set(this.currentTargetId, (this.revisions.get(this.currentTargetId) ?? 0) + 1);
|
|
1703
2191
|
}
|
|
1704
2192
|
});
|
|
1705
2193
|
// 控制台日志
|
|
@@ -1743,28 +2231,17 @@ class SessionManager {
|
|
|
1743
2231
|
const p = params;
|
|
1744
2232
|
const request = this.requestMap.get(p.requestId);
|
|
1745
2233
|
if (request) {
|
|
1746
|
-
const { _monotonic, frameId, ...requestData } = request;
|
|
1747
2234
|
const challenge = isCloudflareChallenge(p.response.headers);
|
|
1748
|
-
if (
|
|
2235
|
+
if (request.type.toLowerCase() === 'document' && request.frameId === this.mainFrameId) {
|
|
1749
2236
|
// 仅新的主文档响应可以解除已知 Challenge,清空日志不能解除该状态
|
|
1750
2237
|
this.challengeRequired = challenge;
|
|
1751
2238
|
}
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
...requestData,
|
|
1755
|
-
status: p.response.status,
|
|
1756
|
-
challenge,
|
|
1757
|
-
duration: Math.round((p.timestamp - _monotonic) * 1000),
|
|
1758
|
-
});
|
|
1759
|
-
// 环形缓冲区:批量裁剪到 800 条,均摊 O(n) 开销
|
|
1760
|
-
if (this.networkRequests.length > SessionManager.MAX_LOG_ENTRIES) {
|
|
1761
|
-
this.networkRequests.splice(0, this.networkRequests.length - 800);
|
|
1762
|
-
}
|
|
1763
|
-
this.requestMap.delete(p.requestId);
|
|
2239
|
+
request.status = p.response.status;
|
|
2240
|
+
request.challenge = challenge;
|
|
1764
2241
|
}
|
|
1765
2242
|
});
|
|
1766
2243
|
// 网络请求失败时写入日志再清理 requestMap,防止 diagnostics 丢失失败请求
|
|
1767
|
-
|
|
2244
|
+
const finalizeRequest = (params, eventSessionId) => {
|
|
1768
2245
|
if (!this.isCurrentSessionEvent(eventSessionId)) {
|
|
1769
2246
|
return;
|
|
1770
2247
|
}
|
|
@@ -1785,13 +2262,15 @@ class SessionManager {
|
|
|
1785
2262
|
}
|
|
1786
2263
|
}
|
|
1787
2264
|
this.requestMap.delete(p.requestId);
|
|
1788
|
-
}
|
|
2265
|
+
};
|
|
2266
|
+
this.cdp.onEvent('Network.loadingFinished', finalizeRequest);
|
|
2267
|
+
this.cdp.onEvent('Network.loadingFailed', finalizeRequest);
|
|
1789
2268
|
}
|
|
1790
2269
|
/**
|
|
1791
2270
|
* 更新页面状态
|
|
1792
2271
|
*/
|
|
1793
|
-
async updateState() {
|
|
1794
|
-
await this.getLiveState();
|
|
2272
|
+
async updateState(timeout) {
|
|
2273
|
+
await this.getLiveState(timeout);
|
|
1795
2274
|
}
|
|
1796
2275
|
async ensureRuntimeEnabled() {
|
|
1797
2276
|
if (this.runtimeEnabled) {
|