@pyrokine/mcp-chrome 3.1.0 → 3.1.2

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 (108) hide show
  1. package/README.md +599 -307
  2. package/README_zh.md +526 -341
  3. package/dist/cdp/client.d.ts +1 -0
  4. package/dist/cdp/client.d.ts.map +1 -1
  5. package/dist/cdp/client.js +16 -8
  6. package/dist/cdp/client.js.map +1 -1
  7. package/dist/core/browser-driver.d.ts +2 -1
  8. package/dist/core/browser-driver.d.ts.map +1 -1
  9. package/dist/core/browser-driver.js.map +1 -1
  10. package/dist/core/browser-events.d.ts +9 -3
  11. package/dist/core/browser-events.d.ts.map +1 -1
  12. package/dist/core/browser-events.js +365 -195
  13. package/dist/core/browser-events.js.map +1 -1
  14. package/dist/core/challenge-page.d.ts.map +1 -1
  15. package/dist/core/challenge-page.js +6 -1
  16. package/dist/core/challenge-page.js.map +1 -1
  17. package/dist/core/error-sanitizer.d.ts.map +1 -1
  18. package/dist/core/error-sanitizer.js +2 -1
  19. package/dist/core/error-sanitizer.js.map +1 -1
  20. package/dist/core/errors.d.ts.map +1 -1
  21. package/dist/core/errors.js +7 -3
  22. package/dist/core/errors.js.map +1 -1
  23. package/dist/core/file-upload.js +1 -1
  24. package/dist/core/file-upload.js.map +1 -1
  25. package/dist/core/locator.d.ts +1 -0
  26. package/dist/core/locator.d.ts.map +1 -1
  27. package/dist/core/locator.js +19 -11
  28. package/dist/core/locator.js.map +1 -1
  29. package/dist/core/os-mouse.d.ts +1 -0
  30. package/dist/core/os-mouse.d.ts.map +1 -1
  31. package/dist/core/os-mouse.js +10 -4
  32. package/dist/core/os-mouse.js.map +1 -1
  33. package/dist/core/session.d.ts +4 -3
  34. package/dist/core/session.d.ts.map +1 -1
  35. package/dist/core/session.js +164 -75
  36. package/dist/core/session.js.map +1 -1
  37. package/dist/core/unified-session.d.ts +10 -5
  38. package/dist/core/unified-session.d.ts.map +1 -1
  39. package/dist/core/unified-session.js +138 -59
  40. package/dist/core/unified-session.js.map +1 -1
  41. package/dist/core/utils.d.ts +5 -1
  42. package/dist/core/utils.d.ts.map +1 -1
  43. package/dist/core/utils.js +8 -2
  44. package/dist/core/utils.js.map +1 -1
  45. package/dist/extension/bridge.d.ts +3 -3
  46. package/dist/extension/bridge.d.ts.map +1 -1
  47. package/dist/extension/bridge.js +58 -17
  48. package/dist/extension/bridge.js.map +1 -1
  49. package/dist/extension/http-server.d.ts +1 -0
  50. package/dist/extension/http-server.d.ts.map +1 -1
  51. package/dist/extension/http-server.js +14 -14
  52. package/dist/extension/http-server.js.map +1 -1
  53. package/dist/index.js +2 -1
  54. package/dist/index.js.map +1 -1
  55. package/dist/tools/browser-event-output.js.map +1 -1
  56. package/dist/tools/challenge.d.ts +1 -0
  57. package/dist/tools/challenge.d.ts.map +1 -1
  58. package/dist/tools/challenge.js +113 -17
  59. package/dist/tools/challenge.js.map +1 -1
  60. package/dist/tools/cookies.d.ts.map +1 -1
  61. package/dist/tools/cookies.js +2 -1
  62. package/dist/tools/cookies.js.map +1 -1
  63. package/dist/tools/diagnostics.d.ts.map +1 -1
  64. package/dist/tools/diagnostics.js +2 -1
  65. package/dist/tools/diagnostics.js.map +1 -1
  66. package/dist/tools/evaluate.d.ts.map +1 -1
  67. package/dist/tools/evaluate.js +4 -2
  68. package/dist/tools/evaluate.js.map +1 -1
  69. package/dist/tools/extract.d.ts.map +1 -1
  70. package/dist/tools/extract.js +152 -58
  71. package/dist/tools/extract.js.map +1 -1
  72. package/dist/tools/input.d.ts.map +1 -1
  73. package/dist/tools/input.js +225 -86
  74. package/dist/tools/input.js.map +1 -1
  75. package/dist/tools/logs.js +1 -1
  76. package/dist/tools/logs.js.map +1 -1
  77. package/dist/tools/manage.d.ts.map +1 -1
  78. package/dist/tools/manage.js +18 -8
  79. package/dist/tools/manage.js.map +1 -1
  80. package/dist/tools/network-sanitizer.d.ts +1 -0
  81. package/dist/tools/network-sanitizer.d.ts.map +1 -1
  82. package/dist/tools/network-sanitizer.js +23 -9
  83. package/dist/tools/network-sanitizer.js.map +1 -1
  84. package/dist/tools/page-context.d.ts +1 -1
  85. package/dist/tools/page-context.d.ts.map +1 -1
  86. package/dist/tools/page-context.js +2 -1
  87. package/dist/tools/page-context.js.map +1 -1
  88. package/dist/tools/png.d.ts.map +1 -1
  89. package/dist/tools/png.js +12 -3
  90. package/dist/tools/png.js.map +1 -1
  91. package/dist/tools/post-condition.d.ts.map +1 -1
  92. package/dist/tools/post-condition.js +57 -33
  93. package/dist/tools/post-condition.js.map +1 -1
  94. package/dist/tools/schema.d.ts +1 -1
  95. package/dist/tools/schema.d.ts.map +1 -1
  96. package/dist/tools/target-diagnostics.d.ts.map +1 -1
  97. package/dist/tools/target-diagnostics.js +53 -33
  98. package/dist/tools/target-diagnostics.js.map +1 -1
  99. package/dist/tools/wait.d.ts.map +1 -1
  100. package/dist/tools/wait.js +4 -4
  101. package/dist/tools/wait.js.map +1 -1
  102. package/extension/dist/assets/{content.ts-BAMOcF3R.js → content.ts-C9QgtUYe.js} +1 -1
  103. package/extension/dist/assets/{content.ts-loader-4F9a1EWZ.js → content.ts-loader-yqB_P8vu.js} +1 -1
  104. package/extension/dist/assets/{index.ts-B79g2ikq.js → index.ts-DBFNh8mZ.js} +8650 -8195
  105. package/extension/dist/assets/{page-scripts-CSxn58h1.js → page-scripts-BjqQ0zXt.js} +1 -1
  106. package/extension/dist/manifest.json +4 -4
  107. package/extension/dist/service-worker-loader.js +1 -1
  108. package/package.json +5 -5
@@ -155,6 +155,8 @@ export class BrowserEventController {
155
155
  sequence = 0;
156
156
  entries = new Map();
157
157
  requests = new Map();
158
+ socketRefs = new Map();
159
+ streamSocketRefs = new WeakMap();
158
160
  extras = new Map();
159
161
  pauses = new Map();
160
162
  bodies = new Map();
@@ -175,6 +177,7 @@ export class BrowserEventController {
175
177
  fetchConfig = Promise.resolve();
176
178
  active = true;
177
179
  documentRevision = 0;
180
+ downloadGeneration = 0;
178
181
  downloadBodies = new Map();
179
182
  downloadWaiters = new Set();
180
183
  cleanupFailures = [];
@@ -205,6 +208,8 @@ export class BrowserEventController {
205
208
  !p.frame?.parentId &&
206
209
  sessionId === this.identity.nativeSessionId) {
207
210
  this.documentRevision++;
211
+ this.socketRefs.clear();
212
+ this.downloadBodies.clear();
208
213
  void this.abortPending('navigation');
209
214
  this.challenged.clear();
210
215
  if (this.dialog) {
@@ -213,6 +218,23 @@ export class BrowserEventController {
213
218
  }
214
219
  }
215
220
  else if (method === 'Page.frameNavigated') {
221
+ if (sessionId !== this.identity.nativeSessionId) {
222
+ for (const key of this.socketRefs.keys()) {
223
+ if (key.startsWith(this.key('', sessionId))) {
224
+ this.socketRefs.delete(key);
225
+ }
226
+ }
227
+ }
228
+ for (const [frameId, candidates] of this.downloadBodies) {
229
+ const remaining = candidates.filter((candidate) => candidate.frameId !== p.frame?.id &&
230
+ (sessionId === this.identity.nativeSessionId || candidate.sessionId !== sessionId));
231
+ if (remaining.length) {
232
+ this.downloadBodies.set(frameId, remaining);
233
+ }
234
+ else {
235
+ this.downloadBodies.delete(frameId);
236
+ }
237
+ }
216
238
  for (const pause of this.pauses.values()) {
217
239
  if ((p.frame?.id && pause.frameId === p.frame.id) ||
218
240
  (sessionId !== this.identity.nativeSessionId && pause.sessionId === sessionId)) {
@@ -289,12 +311,21 @@ export class BrowserEventController {
289
311
  }
290
312
  }
291
313
  else if (this.capture.has('stream') && /^Network\.(?:webSocket|eventSource)/.test(method)) {
314
+ const socketKey = this.key(p.requestId, sessionId);
315
+ const socketCreated = method === 'Network.webSocketCreated';
316
+ const socketRef = !socketCreated && method.startsWith('Network.webSocket') ? this.socketRefs.get(socketKey) : undefined;
317
+ const request = this.latest(p.requestId, sessionId);
318
+ const requestRef = socketRef !== undefined
319
+ ? this.entries.get(socketRef)?.requestRef
320
+ : socketCreated && request?.url !== p.url
321
+ ? undefined
322
+ : request?.ref;
292
323
  const data = p.response?.payloadData ?? p.data;
293
324
  const dataText = typeof data === 'string' ? data : undefined;
294
325
  const encoded = dataText === undefined ? undefined : new TextEncoder().encode(dataText);
295
326
  const truncated = (encoded?.length ?? 0) > MAX_MESSAGE;
296
327
  const message = truncated ? new TextDecoder().decode(encoded.subarray(0, MAX_MESSAGE)) : dataText;
297
- this.make('stream', {
328
+ const entry = this.make('stream', {
298
329
  ...p,
299
330
  response: p.response ? { ...p.response, payloadData: message } : undefined,
300
331
  data: message,
@@ -308,9 +339,18 @@ export class BrowserEventController {
308
339
  ? 'received'
309
340
  : 'lifecycle',
310
341
  sessionId,
311
- requestRef: this.latest(p.requestId, sessionId)?.ref,
342
+ requestRef,
312
343
  sequence: this.sequence + 1,
313
344
  });
345
+ if (socketCreated) {
346
+ this.socketRefs.set(socketKey, entry.ref);
347
+ }
348
+ else if (socketRef !== undefined) {
349
+ this.streamSocketRefs.set(entry, socketRef);
350
+ }
351
+ if (method === 'Network.webSocketClosed') {
352
+ this.socketRefs.delete(socketKey);
353
+ }
314
354
  }
315
355
  else if (method === 'Fetch.requestPaused') {
316
356
  void this.onPaused(p, sessionId).catch((e) => {
@@ -330,8 +370,12 @@ export class BrowserEventController {
330
370
  if (existing) {
331
371
  return;
332
372
  }
333
- const candidates = p.frameId ? (this.downloadBodies.get(p.frameId) ?? []) : [];
334
- const captured = candidates.length === 1 && candidates[0].url === p.url ? candidates[0] : undefined;
373
+ const candidates = (p.frameId ? (this.downloadBodies.get(p.frameId) ?? []) : []).filter((candidate) => candidate.generation === this.downloadGeneration &&
374
+ candidate.documentRevision === this.documentRevision &&
375
+ candidate.sessionId === (sessionId ?? this.identity.nativeSessionId));
376
+ const candidate = candidates.length === 1 && candidates[0].url === p.url ? candidates[0] : undefined;
377
+ const source = candidate && this.entries.get(candidate.ref);
378
+ const captured = candidate && source && !source.abortReason && this.bodies.has(candidate.ref) ? candidate : undefined;
335
379
  const entry = this.make('download', {
336
380
  ...p,
337
381
  sessionId,
@@ -381,11 +425,15 @@ export class BrowserEventController {
381
425
  this.dialogWaiters.delete(rejectDialog);
382
426
  }
383
427
  }
384
- async command(action, command, signal) {
385
- signal?.throwIfAborted();
386
- if (!this.active) {
387
- throw new Error('Browser event session is closed');
388
- }
428
+ async command(action, command, signal, assertActive) {
429
+ const assertRequestActive = () => {
430
+ assertActive?.();
431
+ signal?.throwIfAborted();
432
+ if (!this.active) {
433
+ throw new Error('Browser event session is closed');
434
+ }
435
+ };
436
+ assertRequestActive();
389
437
  if (action === 'read') {
390
438
  return this.read(command);
391
439
  }
@@ -428,6 +476,9 @@ export class BrowserEventController {
428
476
  if (action === 'networkCapture') {
429
477
  if (op === 'start') {
430
478
  this.capture = new Set(command.include ?? []);
479
+ if (!this.capture.has('stream')) {
480
+ this.socketRefs.clear();
481
+ }
431
482
  await this.send('Network.enable', {
432
483
  maxTotalBufferSize: MAX_BYTES,
433
484
  maxResourceBufferSize: MAX_BODY,
@@ -436,73 +487,84 @@ export class BrowserEventController {
436
487
  }
437
488
  else {
438
489
  this.capture.clear();
490
+ this.socketRefs.clear();
439
491
  }
440
492
  return this.status();
441
493
  }
442
494
  if (action === 'route') {
443
- if (op === 'add') {
444
- if (this.routes.size >= 100) {
445
- throw new Error('Route limit reached (100); remove unused rules');
446
- }
447
- const rule = this.make('route', { urlPattern: command.urlPattern, stage: command.stage ?? 'Request' });
448
- this.routes.set(rule.ref, {
449
- urlPattern: String(command.urlPattern),
450
- stage: String(command.stage ?? 'Request'),
451
- });
452
- try {
453
- await this.configureFetch();
454
- }
455
- catch (e) {
456
- this.routes.delete(rule.ref);
457
- throw e;
458
- }
459
- return { ...this.status(), rule: redact(rule) };
495
+ if (op !== 'add' && op !== 'remove') {
496
+ return this.resolvePause(command);
460
497
  }
461
- if (op === 'remove') {
498
+ return this.queueFetch(async () => {
499
+ if (op === 'add') {
500
+ if (this.routes.size >= 100) {
501
+ throw new Error('Route limit reached (100); remove unused rules');
502
+ }
503
+ const rule = this.make('route', {
504
+ urlPattern: command.urlPattern,
505
+ stage: command.stage ?? 'Request',
506
+ });
507
+ this.routes.set(rule.ref, {
508
+ urlPattern: String(command.urlPattern),
509
+ stage: String(command.stage ?? 'Request'),
510
+ });
511
+ try {
512
+ await this.configureFetch(assertRequestActive);
513
+ }
514
+ catch (e) {
515
+ this.routes.delete(rule.ref);
516
+ throw e;
517
+ }
518
+ return { ...this.status(), rule: redact(rule) };
519
+ }
462
520
  this.require(command.ref, 'route');
463
521
  this.routes.delete(command.ref);
464
522
  await Promise.all([...this.pauses.values()]
465
523
  .filter((pause) => pause.ruleRef === command.ref)
466
524
  .map((pause) => this.abortOne(pause, 'route removed')));
467
- await this.configureFetch();
525
+ await this.configureFetch(assertRequestActive);
468
526
  return this.status();
469
- }
470
- return this.resolvePause(command);
527
+ }, assertRequestActive);
471
528
  }
472
529
  if (action === 'httpAuth') {
473
- if (op === 'set') {
474
- const scope = command.scope;
475
- const origin = new URL(scope.origin).origin;
476
- if (origin !== scope.origin) {
477
- throw new Error('Authentication scope must be an exact origin without path or credentials');
530
+ return this.queueFetch(async () => {
531
+ if (op === 'set') {
532
+ const scope = command.scope;
533
+ const origin = new URL(scope.origin).origin;
534
+ if (origin !== scope.origin) {
535
+ throw new Error('Authentication scope must be an exact origin without path or credentials');
536
+ }
537
+ this.credentials = {
538
+ ...scope,
539
+ origin,
540
+ username: String(command.username),
541
+ password: String(command.password),
542
+ };
478
543
  }
479
- this.credentials = {
480
- ...scope,
481
- origin,
482
- username: String(command.username),
483
- password: String(command.password),
484
- };
485
- }
486
- else {
487
- this.credentials = undefined;
488
- await this.abortPending('authentication cleared', 'auth');
489
- }
490
- await this.configureFetch();
491
- return this.status();
544
+ else {
545
+ this.credentials = undefined;
546
+ await this.abortPending('authentication cleared', 'auth');
547
+ }
548
+ await this.configureFetch(assertRequestActive);
549
+ return this.status();
550
+ }, assertRequestActive);
492
551
  }
493
552
  if (action === 'download') {
494
- if (op === 'watch') {
495
- this.downloading = true;
496
- this.downloadPattern = String(command.urlPattern ?? '*');
497
- await this.send('Page.enable');
498
- await this.configureFetch();
499
- return this.status();
500
- }
501
- if (op === 'stop') {
502
- this.downloading = false;
503
- await this.abortPending('download observation stopped', 'download-capture');
504
- await this.configureFetch();
505
- return this.status();
553
+ if (op === 'watch' || op === 'stop') {
554
+ return this.queueFetch(async () => {
555
+ this.downloadGeneration++;
556
+ this.downloadBodies.clear();
557
+ this.downloading = op === 'watch';
558
+ if (op === 'watch') {
559
+ this.downloadPattern = String(command.urlPattern ?? '*');
560
+ await this.send('Page.enable');
561
+ }
562
+ else {
563
+ await this.abortPending('download observation stopped', 'download-capture');
564
+ }
565
+ await this.configureFetch(assertRequestActive);
566
+ return this.status();
567
+ }, assertRequestActive);
506
568
  }
507
569
  const entry = this.require(command.ref, 'download');
508
570
  if (op === 'wait') {
@@ -512,10 +574,15 @@ export class BrowserEventController {
512
574
  throw new Error(`Download state is ${entry.state}; original file is not complete`);
513
575
  }
514
576
  const body = typeof entry.bodyRef === 'string' ? this.bodies.get(entry.bodyRef) : undefined;
515
- if (!body) {
516
- throw new Error(String(entry.artifactReason ?? 'Original download bytes expired or were evicted'));
577
+ if (!body || !this.hasDownloadBody(entry)) {
578
+ throw new Error(String(entry.artifactReason ?? 'Original download bytes unavailable, expired or evicted'));
517
579
  }
518
- return { ...this.status(), download: redact(entry), payload: body, bytes: bytes(body) };
580
+ return {
581
+ ...this.status(),
582
+ download: redact({ ...entry, artifact: 'available', artifactReason: undefined }),
583
+ payload: body,
584
+ bytes: bytes(body),
585
+ };
519
586
  }
520
587
  throw new Error('Unsupported browser event action');
521
588
  }
@@ -523,94 +590,135 @@ export class BrowserEventController {
523
590
  await Promise.all([...this.pauses.values()].filter((p) => !kind || p.kind === kind).map((p) => this.abortOne(p, reason)));
524
591
  }
525
592
  async suspend(reason) {
526
- this.credentials = undefined;
527
- this.rawAuthentication = false;
528
- this.dialogWatching = false;
529
- this.capture.clear();
530
- this.downloading = false;
531
- await this.abortPending(reason);
532
- const unresolved = [...this.pauses.values()];
533
- if (unresolved.length) {
534
- return {
535
- ...this.status(),
536
- suspended: false,
537
- reason,
538
- unresolved: unresolved.map((p) => ({ ref: p.ref, state: p.state, cleanupError: p.cleanupError })),
539
- };
540
- }
541
- this.routes.clear();
542
- await this.configureFetch();
543
- return { ...this.status(), suspended: true, reason };
593
+ return this.queueFetch(async () => {
594
+ this.credentials = undefined;
595
+ this.rawAuthentication = false;
596
+ this.dialogWatching = false;
597
+ this.capture.clear();
598
+ this.socketRefs.clear();
599
+ this.downloading = false;
600
+ this.downloadGeneration++;
601
+ this.downloadBodies.clear();
602
+ await this.abortPending(reason);
603
+ const unresolved = [...this.pauses.values()];
604
+ if (unresolved.length) {
605
+ return {
606
+ ...this.status(),
607
+ suspended: false,
608
+ reason,
609
+ unresolved: unresolved.map((p) => ({
610
+ ref: p.ref,
611
+ state: p.state,
612
+ cleanupError: p.cleanupError,
613
+ })),
614
+ };
615
+ }
616
+ this.routes.clear();
617
+ await this.configureFetch();
618
+ return { ...this.status(), suspended: true, reason };
619
+ });
544
620
  }
545
621
  async dispose(reason) {
546
- const result = await this.suspend(reason);
547
- if (result.suspended === false) {
548
- throw Object.assign(new Error('Browser event cleanup outcome unknown'), { context: result });
549
- }
550
- this.active = false;
551
- this.entries.clear();
552
- this.bodies.clear();
553
- this.requests.clear();
554
- this.extras.clear();
555
- this.challenged.clear();
556
- this.downloadBodies.clear();
557
- this.cleanupFailures = [];
558
- this.bodyBytes = 0;
559
- for (const reject of this.dialogWaiters) {
560
- reject(new Error(reason));
561
- }
562
- this.dialogWaiters.clear();
563
- this.notifyDownloads();
564
- return result;
565
- }
566
- async rawFetch(method, params = {}) {
567
- if (method === 'Fetch.enable') {
568
- const patterns = params.patterns;
569
- for (const [key, rule] of this.routes) {
570
- if (rule.raw) {
571
- this.routes.delete(key);
572
- }
622
+ const disposed = this.suspend(reason).then((result) => {
623
+ if (result.suspended === false) {
624
+ throw Object.assign(new Error('Browser event cleanup outcome unknown'), { context: result });
573
625
  }
574
- if ((patterns?.length ?? 1) + this.routes.size > 100) {
575
- throw new Error('Route limit reached (100)');
576
- }
577
- const rule = this.make('route', { raw: true });
578
- for (const [index, p] of (patterns ?? [{}]).entries()) {
579
- this.routes.set(`${rule.ref}/${index}`, {
580
- urlPattern: p.urlPattern ?? '*',
581
- stage: p.requestStage ?? 'Request',
582
- raw: true,
583
- });
584
- }
585
- this.rawAuthentication = params.handleAuthRequests === true;
586
- this.fetchEnabled = true;
587
- const combined = [...this.routes.values()].map((rule) => ({
588
- urlPattern: rule.urlPattern,
589
- requestStage: rule.stage,
590
- }));
591
- if (this.downloading) {
592
- combined.push({ urlPattern: this.downloadPattern, requestStage: 'Response' });
593
- }
594
- if (this.credentials) {
595
- combined.push({ urlPattern: '*', requestStage: 'Request' });
596
- }
597
- return this.send(method, {
598
- ...params,
599
- patterns: combined,
600
- handleAuthRequests: !!this.credentials || this.rawAuthentication,
601
- });
602
- }
603
- if (method === 'Fetch.disable') {
604
- await this.abortPending('raw Fetch.disable');
605
- if (this.pauses.size) {
606
- throw new Error('Fetch cleanup incomplete; debugger remains attached');
626
+ this.active = false;
627
+ this.entries.clear();
628
+ this.bodies.clear();
629
+ this.requests.clear();
630
+ this.extras.clear();
631
+ this.challenged.clear();
632
+ this.downloadBodies.clear();
633
+ this.cleanupFailures = [];
634
+ this.bodyBytes = 0;
635
+ // 进行中的原生命令沿用自身的完成、取消与超时结果
636
+ this.dialogWaiters.clear();
637
+ this.notifyDownloads();
638
+ return result;
639
+ });
640
+ this.fetchConfig = disposed;
641
+ return disposed;
642
+ }
643
+ async rawFetch(method, params = {}, assertActive) {
644
+ const assertRequestActive = () => {
645
+ assertActive?.();
646
+ if (!this.active) {
647
+ throw new Error('Browser event session is closed');
607
648
  }
608
- this.routes.clear();
609
- this.credentials = undefined;
610
- this.rawAuthentication = false;
611
- this.downloading = false;
612
- this.fetchEnabled = false;
613
- return this.send(method, params);
649
+ };
650
+ assertActive?.();
651
+ if (method === 'Fetch.enable' || method === 'Fetch.disable') {
652
+ return this.queueFetch(async () => {
653
+ const previous = {
654
+ routes: this.routes,
655
+ credentials: this.credentials,
656
+ rawAuthentication: this.rawAuthentication,
657
+ downloading: this.downloading,
658
+ fetchEnabled: this.fetchEnabled,
659
+ };
660
+ let nativeParams = params;
661
+ if (method === 'Fetch.enable') {
662
+ const patterns = params.patterns;
663
+ const routes = new Map([...this.routes].filter(([, rule]) => !rule.raw));
664
+ if ((patterns?.length ?? 1) + routes.size > 100) {
665
+ throw new Error('Route limit reached (100)');
666
+ }
667
+ const rule = this.make('route', { raw: true });
668
+ for (const [index, p] of (patterns ?? [{}]).entries()) {
669
+ routes.set(`${rule.ref}/${index}`, {
670
+ urlPattern: p.urlPattern ?? '*',
671
+ stage: p.requestStage ?? 'Request',
672
+ raw: true,
673
+ });
674
+ }
675
+ this.routes = routes;
676
+ this.rawAuthentication = params.handleAuthRequests === true;
677
+ this.fetchEnabled = true;
678
+ const combined = [...this.routes.values()].map((rule) => ({
679
+ urlPattern: rule.urlPattern,
680
+ requestStage: rule.stage,
681
+ }));
682
+ if (this.downloading) {
683
+ combined.push({ urlPattern: this.downloadPattern, requestStage: 'Response' });
684
+ }
685
+ if (this.credentials) {
686
+ combined.push({ urlPattern: '*', requestStage: 'Request' });
687
+ }
688
+ nativeParams = {
689
+ ...params,
690
+ patterns: combined,
691
+ handleAuthRequests: !!this.credentials || this.rawAuthentication,
692
+ };
693
+ }
694
+ else {
695
+ await this.abortPending('raw Fetch.disable');
696
+ if (this.pauses.size) {
697
+ throw new Error('Fetch cleanup incomplete; debugger remains attached');
698
+ }
699
+ this.routes = new Map();
700
+ this.credentials = undefined;
701
+ this.rawAuthentication = false;
702
+ this.downloading = false;
703
+ this.fetchEnabled = false;
704
+ }
705
+ const configured = { routes: this.routes, rawAuthentication: this.rawAuthentication };
706
+ if (method === 'Fetch.enable') {
707
+ // Events from either configuration can precede the native acknowledgement.
708
+ this.routes = new Map([...previous.routes, ...configured.routes]);
709
+ this.rawAuthentication ||= previous.rawAuthentication;
710
+ }
711
+ try {
712
+ assertRequestActive();
713
+ const result = await this.send(method, nativeParams);
714
+ Object.assign(this, configured);
715
+ return result;
716
+ }
717
+ catch (error) {
718
+ Object.assign(this, this.nativeRefusal(error).refused ? previous : configured);
719
+ throw error;
720
+ }
721
+ }, assertRequestActive);
614
722
  }
615
723
  const candidates = [...this.pauses.values()].filter((p) => p.requestId === params.requestId);
616
724
  if (candidates.length > 1) {
@@ -726,6 +834,13 @@ export class BrowserEventController {
726
834
  }
727
835
  return entry;
728
836
  }
837
+ hasDownloadBody(entry) {
838
+ if (typeof entry.bodyRef !== 'string' || !this.bodies.has(entry.bodyRef)) {
839
+ return false;
840
+ }
841
+ const capture = this.entries.get(entry.bodyRef);
842
+ return capture?.kind === 'download-capture' && capture.state === 'resolved' && !capture.abortReason;
843
+ }
729
844
  saveBody(ref, payload) {
730
845
  const length = bytes(payload);
731
846
  if (length >= MAX_BODY) {
@@ -753,7 +868,7 @@ export class BrowserEventController {
753
868
  }
754
869
  return this.requests.get(this.key(requestId, sessionId))?.at(-1);
755
870
  }
756
- nativeFailure(entry, error) {
871
+ nativeRefusal(error) {
757
872
  const context = error
758
873
  ?.context;
759
874
  const message = this.failure(error);
@@ -773,15 +888,24 @@ export class BrowserEventController {
773
888
  }
774
889
  }
775
890
  const fromPage = getErrorSource(error) === 'page';
891
+ return {
892
+ refused: !fromPage &&
893
+ (context?.actionExecuted === false ||
894
+ error?.actionExecuted === false ||
895
+ [-32601, -32602].includes(code ?? 0)),
896
+ expired: !fromPage && code === -32602 && nativeMessage === 'Invalid InterceptionId.',
897
+ };
898
+ }
899
+ nativeFailure(entry, error) {
900
+ const { refused, expired } = this.nativeRefusal(error);
776
901
  clearTimeout(entry.timer);
777
- entry.error = message;
778
- if (!fromPage && code === -32602 && nativeMessage === 'Invalid InterceptionId.') {
902
+ entry.error = this.failure(error);
903
+ if (expired) {
779
904
  entry.state = 'expired';
780
905
  entry.reason = 'Native interception no longer exists';
781
906
  this.pauses.delete(entry.ref);
782
907
  return;
783
908
  }
784
- const refused = !fromPage && (context?.actionExecuted === false || [-32601, -32602].includes(code ?? 0));
785
909
  entry.state = refused ? 'pending' : 'unknown';
786
910
  const remaining = entry.timestamp + PAUSE_TTL - Date.now();
787
911
  if (refused && remaining > 0) {
@@ -881,41 +1005,47 @@ export class BrowserEventController {
881
1005
  })),
882
1006
  };
883
1007
  }
884
- async configureFetch() {
885
- this.fetchConfig = this.fetchConfig
1008
+ queueFetch(operation, assertActive) {
1009
+ const configured = this.fetchConfig
886
1010
  .catch(() => { })
887
- .then(async () => {
888
- // A body read owns its pause until getResponseBody completes, including stop/cleanup.
889
- await Promise.all([...this.pauses.values()].map((p) => p.bodyRead));
890
- if ([...this.pauses.values()].some((p) => p.state === 'unknown')) {
891
- throw new Error('Fetch cleanup outcome is unknown; configuration and debugger attachment are preserved');
892
- }
893
- const patterns = [...this.routes.values()].map((r) => ({
894
- urlPattern: r.urlPattern,
895
- requestStage: r.stage,
896
- }));
897
- if (this.downloading) {
898
- patterns.push({ urlPattern: this.downloadPattern, requestStage: 'Response' });
899
- }
900
- if (this.credentials || (this.rawAuthentication && patterns.length === 0)) {
901
- patterns.push({ urlPattern: '*', requestStage: 'Request' });
902
- }
903
- if (patterns.length || this.credentials || this.rawAuthentication) {
904
- await this.send('Fetch.enable', {
905
- patterns,
906
- handleAuthRequests: !!this.credentials || this.rawAuthentication,
907
- });
908
- this.fetchEnabled = true;
909
- }
910
- else if (this.fetchEnabled) {
911
- if (this.pauses.size) {
912
- throw new Error('Fetch cleanup is incomplete; pending requests and debugger attachment are preserved');
913
- }
914
- await this.send('Fetch.disable');
915
- this.fetchEnabled = false;
916
- }
1011
+ .then(() => {
1012
+ assertActive?.();
1013
+ return operation();
917
1014
  });
918
- await this.fetchConfig;
1015
+ this.fetchConfig = configured;
1016
+ return configured;
1017
+ }
1018
+ async configureFetch(assertActive) {
1019
+ // A body read owns its pause until getResponseBody completes, including stop/cleanup.
1020
+ await Promise.all([...this.pauses.values()].map((p) => p.bodyRead));
1021
+ assertActive?.();
1022
+ if ([...this.pauses.values()].some((p) => p.state === 'unknown')) {
1023
+ throw new Error('Fetch cleanup outcome is unknown; configuration and debugger attachment are preserved');
1024
+ }
1025
+ const patterns = [...this.routes.values()].map((r) => ({
1026
+ urlPattern: r.urlPattern,
1027
+ requestStage: r.stage,
1028
+ }));
1029
+ if (this.downloading) {
1030
+ patterns.push({ urlPattern: this.downloadPattern, requestStage: 'Response' });
1031
+ }
1032
+ if (this.credentials || (this.rawAuthentication && patterns.length === 0)) {
1033
+ patterns.push({ urlPattern: '*', requestStage: 'Request' });
1034
+ }
1035
+ if (patterns.length || this.credentials || this.rawAuthentication) {
1036
+ await this.send('Fetch.enable', {
1037
+ patterns,
1038
+ handleAuthRequests: !!this.credentials || this.rawAuthentication,
1039
+ });
1040
+ this.fetchEnabled = true;
1041
+ }
1042
+ else if (this.fetchEnabled) {
1043
+ if (this.pauses.size) {
1044
+ throw new Error('Fetch cleanup is incomplete; pending requests and debugger attachment are preserved');
1045
+ }
1046
+ await this.send('Fetch.disable');
1047
+ this.fetchEnabled = false;
1048
+ }
919
1049
  }
920
1050
  async onPaused(p, sessionId) {
921
1051
  const stage = p.responseStatusCode !== undefined || p.responseErrorReason !== undefined ? 'Response' : 'Request';
@@ -945,6 +1075,20 @@ export class BrowserEventController {
945
1075
  networkRef: this.latest(p.networkId, sessionId)?.ref,
946
1076
  });
947
1077
  this.pauses.set(entry.ref, entry);
1078
+ const generation = this.downloadGeneration;
1079
+ const documentRevision = this.documentRevision;
1080
+ if (this.downloading && attachment && p.frameId && matches(p.request.url, this.downloadPattern)) {
1081
+ const candidates = this.downloadBodies.get(p.frameId) ?? [];
1082
+ candidates.push({
1083
+ ref: entry.ref,
1084
+ frameId: p.frameId,
1085
+ url: p.request.url,
1086
+ sessionId: sessionId ?? this.identity.nativeSessionId,
1087
+ generation,
1088
+ documentRevision,
1089
+ });
1090
+ this.downloadBodies.set(p.frameId, candidates.slice(-MAX_ENTRIES));
1091
+ }
948
1092
  entry.timer = setTimeout(() => {
949
1093
  void this.abortOne(entry, 'pause timeout');
950
1094
  }, PAUSE_TTL);
@@ -958,11 +1102,10 @@ export class BrowserEventController {
958
1102
  throw new Error('Download exceeds the original body budget');
959
1103
  }
960
1104
  const body = (await this.send('Fetch.getResponseBody', native, sessionId));
961
- this.saveBody(entry.ref, { encoding: body.base64Encoded ? 'base64' : 'utf8', data: body.body });
962
- if (p.frameId) {
963
- const candidates = this.downloadBodies.get(p.frameId) ?? [];
964
- candidates.push({ ref: entry.ref, frameId: p.frameId, url: p.request.url });
965
- this.downloadBodies.set(p.frameId, candidates.slice(-MAX_ENTRIES));
1105
+ if (!this.downloading ||
1106
+ generation !== this.downloadGeneration ||
1107
+ documentRevision !== this.documentRevision) {
1108
+ entry.abortReason ??= 'download capture identity changed';
966
1109
  }
967
1110
  if (entry.abortReason) {
968
1111
  await this.send('Fetch.failRequest', { ...native, errorReason: 'Aborted' }, sessionId);
@@ -970,6 +1113,7 @@ export class BrowserEventController {
970
1113
  entry.reason = entry.abortReason;
971
1114
  }
972
1115
  else {
1116
+ this.saveBody(entry.ref, { encoding: body.base64Encoded ? 'base64' : 'utf8', data: body.body });
973
1117
  await this.send('Fetch.continueResponse', native, sessionId);
974
1118
  entry.state = 'resolved';
975
1119
  }
@@ -1200,10 +1344,27 @@ export class BrowserEventController {
1200
1344
  if (selected && selected.kind !== kind) {
1201
1345
  throw new Error('Browser event ref kind does not match the requested view');
1202
1346
  }
1203
- const entries = [...this.entries.values()].filter((e) => e.kind === kind &&
1204
- (!selected || e.ref === selected.ref) &&
1205
- (!options.urlPattern ||
1206
- matches(String(e.url ?? e.request?.url ?? ''), options.urlPattern)));
1347
+ const entries = [...this.entries.values()].filter((e) => {
1348
+ if (e.kind !== kind || (selected && e.ref !== selected.ref)) {
1349
+ return false;
1350
+ }
1351
+ if (!options.urlPattern) {
1352
+ return true;
1353
+ }
1354
+ const parent = e.kind === 'stream' && typeof e.requestRef === 'string' ? this.entries.get(e.requestRef) : undefined;
1355
+ const socketRef = this.streamSocketRefs.get(e);
1356
+ const socket = socketRef === undefined ? undefined : this.entries.get(socketRef);
1357
+ const url = e.url ??
1358
+ e.request?.url ??
1359
+ (socketRef !== undefined
1360
+ ? socket?.nativeMethod === 'Network.webSocketCreated'
1361
+ ? socket.url
1362
+ : undefined
1363
+ : parent?.kind === 'request'
1364
+ ? parent.url
1365
+ : undefined);
1366
+ return (e.kind !== 'stream' || typeof url === 'string') && matches(String(url ?? ''), options.urlPattern);
1367
+ });
1207
1368
  const logs = entries.slice(-(options.limit ?? 100)).map((e) => {
1208
1369
  if (kind === 'request' && view === 'summary') {
1209
1370
  return redact({
@@ -1231,7 +1392,8 @@ export class BrowserEventController {
1231
1392
  : {}),
1232
1393
  ...(kind === 'download'
1233
1394
  ? {
1234
- artifact: typeof e.bodyRef === 'string' && this.bodies.has(e.bodyRef) ? 'available' : 'unavailable',
1395
+ artifact: this.hasDownloadBody(e) ? 'available' : 'unavailable',
1396
+ artifactReason: this.hasDownloadBody(e) ? undefined : e.artifactReason,
1235
1397
  }
1236
1398
  : {}),
1237
1399
  });
@@ -1283,7 +1445,15 @@ export class BrowserEventController {
1283
1445
  abort();
1284
1446
  }
1285
1447
  });
1286
- return { ...this.status(), download: redact(entry) };
1448
+ const available = this.hasDownloadBody(entry);
1449
+ return {
1450
+ ...this.status(),
1451
+ download: redact({
1452
+ ...entry,
1453
+ artifact: available ? 'available' : 'unavailable',
1454
+ artifactReason: available ? undefined : entry.artifactReason,
1455
+ }),
1456
+ };
1287
1457
  }
1288
1458
  }
1289
1459
  export const BROWSER_EVENT_METHODS = [