chrome-devtools-mcp 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +15 -0
  2. package/build/src/HeapSnapshotManager.js +23 -13
  3. package/build/src/McpContext.js +174 -365
  4. package/build/src/McpPage.js +242 -31
  5. package/build/src/McpResponse.js +113 -67
  6. package/build/src/PageCollector.js +48 -122
  7. package/build/src/TextSnapshot.js +20 -2
  8. package/build/src/ToolHandler.js +13 -3
  9. package/build/src/WaitForHelper.js +18 -8
  10. package/build/src/bin/chrome-devtools-cli-options.js +25 -1
  11. package/build/src/bin/chrome-devtools-mcp-cli-options.js +15 -6
  12. package/build/src/bin/chrome-devtools-mcp-main.js +2 -2
  13. package/build/src/browser.js +1 -1
  14. package/build/src/daemon/client.js +33 -3
  15. package/build/src/daemon/daemon.js +2 -1
  16. package/build/src/daemon/utils.js +1 -1
  17. package/build/src/devtools/DevtoolsUtils.js +2 -63
  18. package/build/src/{issue-descriptions.js → devtools/issueDescriptions.js} +2 -2
  19. package/build/src/formatters/IssueFormatter.js +2 -2
  20. package/build/src/index.js +12 -3
  21. package/build/src/telemetry/ClearcutLogger.js +1 -1
  22. package/build/src/telemetry/WatchdogClient.js +1 -1
  23. package/build/src/telemetry/metricsRegistry.js +2 -9
  24. package/build/src/telemetry/persistence.js +1 -1
  25. package/build/src/telemetry/transformation.js +20 -0
  26. package/build/src/telemetry/watchdog/ClearcutSender.js +1 -1
  27. package/build/src/telemetry/watchdog/main.js +1 -1
  28. package/build/src/third_party/THIRD_PARTY_NOTICES +13 -249
  29. package/build/src/third_party/bundled-packages.json +2 -3
  30. package/build/src/third_party/index.js +1527 -1514
  31. package/build/src/third_party/lighthouse-devtools-mcp-bundle.js +3082 -6343
  32. package/build/src/tools/emulation.js +2 -2
  33. package/build/src/tools/extensions.js +1 -1
  34. package/build/src/tools/input.js +17 -8
  35. package/build/src/tools/lighthouse.js +1 -1
  36. package/build/src/tools/memory.js +16 -2
  37. package/build/src/tools/network.js +4 -4
  38. package/build/src/tools/pages.js +21 -89
  39. package/build/src/tools/performance.js +2 -2
  40. package/build/src/tools/script.js +3 -0
  41. package/build/src/tools/snapshot.js +2 -2
  42. package/build/src/tools/thirdPartyDeveloper.js +1 -1
  43. package/build/src/tools/webmcp.js +1 -1
  44. package/build/src/trace-processing/parse.js +1 -1
  45. package/build/src/{logger.js → utils/logger.js} +1 -1
  46. package/build/src/{polyfill.js → utils/polyfill.js} +1 -1
  47. package/build/src/version.js +1 -1
  48. package/package.json +9 -5
  49. package/skills/memory-leak-debugging/SKILL.md +22 -14
  50. package/build/src/utils/types.js +0 -7
  51. /package/build/src/{Mutex.js → utils/Mutex.js} +0 -0
@@ -10,9 +10,10 @@ import { NetworkFormatter } from './formatters/NetworkFormatter.js';
10
10
  import { SnapshotFormatter } from './formatters/SnapshotFormatter.js';
11
11
  import { UncaughtError } from './PageCollector.js';
12
12
  import { TextSnapshot } from './TextSnapshot.js';
13
- import { DevTools, getToonEncode } from './third_party/index.js';
14
- import { handleDialog } from './tools/pages.js';
13
+ import { DevTools, getToonEncode, getGcfEncode, } from './third_party/index.js';
14
+ import { handleDialog, listPages } from './tools/pages.js';
15
15
  import { getInsightOutput, getTraceSummary } from './trace-processing/parse.js';
16
+ import { stableIdSymbol } from './utils/id.js';
16
17
  import { paginate } from './utils/pagination.js';
17
18
  export function replaceHtmlElementsWithUids(schema) {
18
19
  if (typeof schema === 'boolean') {
@@ -172,6 +173,7 @@ export class McpResponse {
172
173
  #redactNetworkHeaders = true;
173
174
  #error;
174
175
  #attachedWaitForResult;
176
+ #reconnectNotice = false;
175
177
  get #deviceScope() {
176
178
  return this.#page?.viewport?.isMobile ? 'PHONE' : 'DESKTOP';
177
179
  }
@@ -184,6 +186,13 @@ export class McpResponse {
184
186
  setRedactNetworkHeaders(value) {
185
187
  this.#redactNetworkHeaders = value;
186
188
  }
189
+ /**
190
+ * Surfaces a one-time note that the browser reconnected and page ids changed.
191
+ * Set by the tool handler when the context reports a pending reconnect notice.
192
+ */
193
+ setReconnectNotice() {
194
+ this.#reconnectNotice = true;
195
+ }
187
196
  attachDevToolsData(data) {
188
197
  this.#devToolsData = data;
189
198
  }
@@ -218,7 +227,7 @@ export class McpResponse {
218
227
  }
219
228
  this.#networkRequestsOptions = {
220
229
  include: value,
221
- pagination: options?.pageSize || options?.pageIdx
230
+ pagination: options?.pageSize !== undefined || options?.pageIdx !== undefined
222
231
  ? {
223
232
  pageSize: options.pageSize,
224
233
  pageIdx: options.pageIdx,
@@ -236,7 +245,7 @@ export class McpResponse {
236
245
  }
237
246
  this.#consoleDataOptions = {
238
247
  include: value,
239
- pagination: options?.pageSize || options?.pageIdx
248
+ pagination: options?.pageSize !== undefined || options?.pageIdx !== undefined
240
249
  ? {
241
250
  pageSize: options.pageSize,
242
251
  pageIdx: options.pageIdx,
@@ -309,11 +318,11 @@ export class McpResponse {
309
318
  attachWaitForResult(result) {
310
319
  this.#attachedWaitForResult = result;
311
320
  }
312
- setHeapSnapshotAggregates(aggregates, options) {
321
+ setHeapSnapshotAggregates(aggregateData, options) {
313
322
  this.#heapSnapshotOptions = {
314
323
  ...this.#heapSnapshotOptions,
315
324
  include: true,
316
- aggregates,
325
+ aggregateData,
317
326
  pagination: options,
318
327
  };
319
328
  }
@@ -384,7 +393,7 @@ export class McpResponse {
384
393
  get listWebMcpTools() {
385
394
  return this.#listWebMcpTools;
386
395
  }
387
- async handle(toolName, context, useToon = false) {
396
+ async handle(toolName, context, dataFormat = 'default') {
388
397
  if (this.#includePages) {
389
398
  await context.createPagesSnapshot();
390
399
  }
@@ -417,10 +426,10 @@ export class McpResponse {
417
426
  if (!this.#page) {
418
427
  throw new Error(`Response must have an McpPage`);
419
428
  }
420
- const request = context.getNetworkRequestById(this.#page, this.#attachedNetworkRequestId);
429
+ const request = this.#page.getNetworkRequestById(this.#attachedNetworkRequestId);
421
430
  const formatter = await NetworkFormatter.from(request, {
422
431
  requestId: this.#attachedNetworkRequestId,
423
- requestIdResolver: req => context.getNetworkRequestStableId(req),
432
+ requestIdResolver: req => this.getNetworkRequestStableId(req),
424
433
  fetchData: true,
425
434
  requestFilePath: this.#attachedNetworkRequestOptions?.requestFilePath,
426
435
  responseFilePath: this.#attachedNetworkRequestOptions?.responseFilePath,
@@ -434,11 +443,11 @@ export class McpResponse {
434
443
  if (!this.#page) {
435
444
  throw new Error(`Response must have an McpPage`);
436
445
  }
437
- const message = context.getConsoleMessageById(this.#page, this.#attachedConsoleMessageId);
446
+ const message = this.#page.getConsoleMessageById(this.#attachedConsoleMessageId);
438
447
  const consoleMessageStableId = this.#attachedConsoleMessageId;
439
448
  if ('args' in message || message instanceof UncaughtError) {
440
449
  const consoleMessage = message;
441
- const devTools = context.getDevToolsUniverse(this.#page);
450
+ const devTools = this.#page.devtoolsUniverse;
442
451
  detailedConsoleMessage = await ConsoleFormatter.from(consoleMessage, {
443
452
  id: consoleMessageStableId,
444
453
  fetchDetailedData: true,
@@ -448,8 +457,8 @@ export class McpResponse {
448
457
  else if (message instanceof DevTools.AggregatedIssue) {
449
458
  const formatter = new IssueFormatter(message, {
450
459
  id: consoleMessageStableId,
451
- requestIdResolver: context.resolveCdpRequestId.bind(context, this.#page),
452
- elementIdResolver: this.#page.resolveCdpElementId.bind(this.#page),
460
+ requestIdResolver: this.#page.resolveCdpRequestId.bind(this.#page),
461
+ elementIdResolver: this.#page.textSnapshot?.resolveCdpElementId.bind(this.#page.textSnapshot),
453
462
  });
454
463
  if (!formatter.isValid()) {
455
464
  throw new Error("Can't provide details for the msgid " + consoleMessageStableId);
@@ -488,7 +497,7 @@ export class McpResponse {
488
497
  if (!page) {
489
498
  throw new Error(`Response must have an McpPage`);
490
499
  }
491
- messages = context.getConsoleData(page, this.#consoleDataOptions.includePreservedMessages);
500
+ messages = page.getConsoleData(this.#consoleDataOptions.includePreservedMessages);
492
501
  }
493
502
  if (this.#consoleDataOptions.types?.length) {
494
503
  const normalizedTypes = new Set(this.#consoleDataOptions.types);
@@ -503,16 +512,13 @@ export class McpResponse {
503
512
  });
504
513
  }
505
514
  consoleMessages = (await Promise.all(messages.map(async (item) => {
506
- const consoleMessageStableId = context.getConsoleMessageStableId(item);
515
+ const consoleMessageStableId = this.getConsoleMessageStableId(item);
507
516
  if ('args' in item || item instanceof UncaughtError) {
508
517
  const consoleMessage = item;
509
- const devTools = page
510
- ? context.getDevToolsUniverse(page)
511
- : null;
512
518
  return await ConsoleFormatter.from(consoleMessage, {
513
519
  id: consoleMessageStableId,
514
520
  fetchDetailedData: false,
515
- devTools: devTools ?? undefined,
521
+ devTools: page ? page.devtoolsUniverse : undefined,
516
522
  });
517
523
  }
518
524
  if (item instanceof DevTools.AggregatedIssue) {
@@ -532,7 +538,7 @@ export class McpResponse {
532
538
  if (!this.#page) {
533
539
  throw new Error(`Response must have an McpPage`);
534
540
  }
535
- let requests = context.getNetworkRequests(this.#page, this.#networkRequestsOptions?.includePreservedRequests);
541
+ let requests = this.#page.getNetworkRequests(this.#networkRequestsOptions?.includePreservedRequests);
536
542
  // Apply resource type filtering if specified
537
543
  if (this.#networkRequestsOptions.resourceTypes?.length) {
538
544
  const normalizedTypes = new Set(this.#networkRequestsOptions.resourceTypes);
@@ -543,8 +549,8 @@ export class McpResponse {
543
549
  }
544
550
  if (requests.length) {
545
551
  networkRequests = await Promise.all(requests.map(request => NetworkFormatter.from(request, {
546
- requestId: context.getNetworkRequestStableId(request),
547
- selectedInDevToolsUI: context.getNetworkRequestStableId(request) ===
552
+ requestId: this.getNetworkRequestStableId(request),
553
+ selectedInDevToolsUI: this.getNetworkRequestStableId(request) ===
548
554
  this.#networkRequestsOptions?.networkRequestIdInDevToolsUI,
549
555
  fetchData: false,
550
556
  saveFile: (data, filename, extension) => context.saveFile(data, filename, extension),
@@ -565,23 +571,45 @@ export class McpResponse {
565
571
  thirdPartyDeveloperTools,
566
572
  webmcpTools,
567
573
  errorMessage: this.#error?.message,
568
- }, useToon);
574
+ }, dataFormat);
575
+ }
576
+ getConsoleMessageStableId(message) {
577
+ return message[stableIdSymbol] ?? -1;
569
578
  }
570
- async format(toolName, context, data, useToon) {
579
+ getNetworkRequestStableId(request) {
580
+ return request[stableIdSymbol] ?? -1;
581
+ }
582
+ async format(toolName, context, data, dataFormat = 'default') {
571
583
  const structuredContent = {};
572
- let toonEncode;
573
- if (useToon) {
584
+ // Resolve the compact encoder based on the chosen format
585
+ let compactEncode;
586
+ if (dataFormat === 'toon') {
574
587
  try {
575
- toonEncode = await getToonEncode();
588
+ compactEncode = await getToonEncode();
576
589
  }
577
590
  catch {
578
- throw new Error('The `@toon-format/toon` package is required to use the experimental TOON format. ' +
591
+ throw new Error('The `@toon-format/toon` package is required to use --experimentalDataFormat=toon. ' +
579
592
  'Make sure the peer dependency is installed:\n' +
580
- '- For npx: npx --package chrome-devtools-mcp@latest --package @toon-format/toon@latest chrome-devtools-mcp --experimentalToonFormat\n' +
593
+ '- For npx: npx --package chrome-devtools-mcp@latest --package @toon-format/toon@latest chrome-devtools-mcp --experimentalDataFormat=toon\n' +
581
594
  '- For npm: npm install @toon-format/toon (add -g if installed globally)');
582
595
  }
583
596
  }
597
+ else if (dataFormat === 'gcf') {
598
+ try {
599
+ compactEncode = await getGcfEncode();
600
+ }
601
+ catch {
602
+ throw new Error('The `@blackwell-systems/gcf` package is required to use --experimentalDataFormat=gcf. ' +
603
+ 'Make sure the peer dependency is installed:\n' +
604
+ '- For npx: npx --package chrome-devtools-mcp@latest --package @blackwell-systems/gcf@latest chrome-devtools-mcp --experimentalDataFormat=gcf\n' +
605
+ '- For npm: npm install @blackwell-systems/gcf (add -g if installed globally)');
606
+ }
607
+ }
584
608
  const response = [];
609
+ if (this.#reconnectNotice) {
610
+ structuredContent.reconnected = true;
611
+ response.push(`Note: the browser was restarted or reconnected since the last call. Page ids have changed. Call ${listPages().name} to see open pages.`);
612
+ }
585
613
  if (this.#textResponseLines.length) {
586
614
  structuredContent.message = this.#textResponseLines.join('\n');
587
615
  response.push(...this.#textResponseLines);
@@ -642,29 +670,40 @@ Call ${handleDialog.name} to handle it before continuing.`);
642
670
  }
643
671
  if (this.#includePages) {
644
672
  const allPages = context.getPages();
645
- const { regularPages, extensionPages } = allPages.reduce((acc, page) => {
646
- if (page.url().startsWith('chrome-extension://')) {
647
- acc.extensionPages.push(page);
673
+ const { regularPages, extensionPages } = allPages.reduce((acc, mcpPage) => {
674
+ if (mcpPage.pptrPage.url().startsWith('chrome-extension://')) {
675
+ acc.extensionPages.push(mcpPage);
648
676
  }
649
677
  else {
650
- acc.regularPages.push(page);
678
+ acc.regularPages.push(mcpPage);
651
679
  }
652
680
  return acc;
653
681
  }, { regularPages: [], extensionPages: [] });
682
+ const selectionFallback = context.getSelectedPageFallback();
683
+ if (selectionFallback) {
684
+ let selectedPageId;
685
+ try {
686
+ selectedPageId = context.getSelectedMcpPage().id;
687
+ }
688
+ catch {
689
+ selectedPageId = undefined;
690
+ }
691
+ response.push(`Note: the previously selected page ${selectionFallback.wasClosed ? 'was closed' : 'is no longer listed'}.${selectedPageId !== undefined ? ` Page ${selectedPageId} is now selected.` : ''}`);
692
+ }
654
693
  if (regularPages.length) {
655
694
  const parts = [`## Pages`];
656
695
  const structuredPages = [];
657
- for (const page of regularPages) {
658
- const isolatedContextName = context.getIsolatedContextName(page);
696
+ for (const mcpPage of regularPages) {
697
+ const isolatedContextName = mcpPage.isolatedContextName;
659
698
  const contextLabel = isolatedContextName
660
699
  ? ` isolatedContext=${isolatedContextName}`
661
700
  : '';
662
- const title = await fetchPageTitle(page);
701
+ const title = await fetchPageTitle(mcpPage.pptrPage);
663
702
  const pageLabel = title
664
- ? `${truncateTitle(title)} (${page.url()})`
665
- : page.url();
666
- parts.push(`${context.getPageId(page)}: ${pageLabel}${context.isPageSelected(page) ? ' [selected]' : ''}${contextLabel}`);
667
- structuredPages.push(createStructuredPage(page, context, title));
703
+ ? `${truncateTitle(title)} (${mcpPage.pptrPage.url()})`
704
+ : mcpPage.pptrPage.url();
705
+ parts.push(`${mcpPage.id}: ${pageLabel}${context.isPageSelected(mcpPage) ? ' [selected]' : ''}${contextLabel}`);
706
+ structuredPages.push(createStructuredPage(mcpPage, context, title));
668
707
  }
669
708
  response.push(...parts);
670
709
  structuredContent.pages = structuredPages;
@@ -673,17 +712,17 @@ Call ${handleDialog.name} to handle it before continuing.`);
673
712
  if (extensionPages.length) {
674
713
  response.push(`## Extension Pages`);
675
714
  const structuredExtensionPages = [];
676
- for (const page of extensionPages) {
677
- const isolatedContextName = context.getIsolatedContextName(page);
715
+ for (const mcpPage of extensionPages) {
716
+ const isolatedContextName = mcpPage.isolatedContextName;
678
717
  const contextLabel = isolatedContextName
679
718
  ? ` isolatedContext=${isolatedContextName}`
680
719
  : '';
681
- const title = await fetchPageTitle(page);
720
+ const title = await fetchPageTitle(mcpPage.pptrPage);
682
721
  const pageLabel = title
683
- ? `${truncateTitle(title)} (${page.url()})`
684
- : page.url();
685
- response.push(`${context.getPageId(page)}: ${pageLabel}${context.isPageSelected(page) ? ' [selected]' : ''}${contextLabel}`);
686
- structuredExtensionPages.push(createStructuredPage(page, context, title));
722
+ ? `${truncateTitle(title)} (${mcpPage.pptrPage.url()})`
723
+ : mcpPage.pptrPage.url();
724
+ response.push(`${mcpPage.id}: ${pageLabel}${context.isPageSelected(mcpPage) ? ' [selected]' : ''}${contextLabel}`);
725
+ structuredExtensionPages.push(createStructuredPage(mcpPage, context, title));
687
726
  }
688
727
  structuredContent.extensionPages = structuredExtensionPages;
689
728
  }
@@ -759,8 +798,8 @@ Call ${handleDialog.name} to handle it before continuing.`);
759
798
  else {
760
799
  structuredContent.snapshot = data.snapshot.toJSON();
761
800
  response.push('## Latest page snapshot');
762
- response.push(useToon && toonEncode
763
- ? toonEncode(structuredContent.snapshot)
801
+ response.push(compactEncode
802
+ ? compactEncode(structuredContent.snapshot)
764
803
  : data.snapshot.toString());
765
804
  }
766
805
  }
@@ -778,17 +817,24 @@ Call ${handleDialog.name} to handle it before continuing.`);
778
817
  structuredContent.heapSnapshot = structuredContent.heapSnapshot || {};
779
818
  structuredContent.heapSnapshot.staticData = staticData;
780
819
  }
781
- const aggregates = this.#heapSnapshotOptions.aggregates;
782
- if (aggregates) {
783
- const sortedEntries = HeapSnapshotFormatter.sort(aggregates);
820
+ const aggregateData = this.#heapSnapshotOptions.aggregateData;
821
+ if (aggregateData) {
822
+ const sortedEntries = HeapSnapshotFormatter.sort(aggregateData.aggregates);
784
823
  const paginationData = this.#dataWithPagination(sortedEntries, this.#heapSnapshotOptions.pagination);
824
+ response.push(`Objects: ${aggregateData.objectCount}`);
825
+ response.push(`Total shallow size: ${DevTools.I18n.ByteUtilities.formatBytesToKb(aggregateData.totalSelfSize)}`);
826
+ structuredContent.heapSnapshot = structuredContent.heapSnapshot || {};
827
+ structuredContent.heapSnapshot.aggregateStats = {
828
+ objectCount: aggregateData.objectCount,
829
+ totalSelfSize: aggregateData.totalSelfSize,
830
+ };
785
831
  structuredContent.pagination = paginationData.pagination;
786
832
  response.push(...paginationData.info);
787
833
  const paginatedRecord = Object.fromEntries(paginationData.items);
788
834
  const formatter = new HeapSnapshotFormatter(paginatedRecord);
789
835
  structuredContent.heapSnapshotData = formatter.toJSON();
790
- response.push(useToon && toonEncode
791
- ? toonEncode(structuredContent.heapSnapshotData)
836
+ response.push(compactEncode
837
+ ? compactEncode(structuredContent.heapSnapshotData)
792
838
  : formatter.toString());
793
839
  }
794
840
  const nodes = this.#heapSnapshotOptions.nodes;
@@ -844,16 +890,16 @@ Call ${handleDialog.name} to handle it before continuing.`);
844
890
  const classDiffs = this.#heapSnapshotOptions.classDiffs;
845
891
  if (classDiffs) {
846
892
  response.push('### Heap Snapshot Diff');
847
- response.push(useToon && toonEncode
848
- ? toonEncode(classDiffs)
893
+ response.push(compactEncode
894
+ ? compactEncode(classDiffs)
849
895
  : HeapSnapshotFormatter.formatDiffSummary(classDiffs));
850
896
  structuredContent.heapSnapshotClassDiffs = classDiffs;
851
897
  }
852
898
  const detailedClassDiff = this.#heapSnapshotOptions.detailedClassDiff;
853
899
  if (detailedClassDiff) {
854
900
  response.push('### Heap Snapshot Detailed Diff');
855
- response.push(useToon && toonEncode
856
- ? toonEncode(detailedClassDiff)
901
+ response.push(compactEncode
902
+ ? compactEncode(detailedClassDiff)
857
903
  : HeapSnapshotFormatter.formatDiffDetails(detailedClassDiff));
858
904
  structuredContent.heapSnapshotDetailedClassDiff = detailedClassDiff;
859
905
  }
@@ -938,8 +984,8 @@ Call ${handleDialog.name} to handle it before continuing.`);
938
984
  response.push(...paginationData.info);
939
985
  if (data.networkRequests) {
940
986
  structuredContent.networkRequests = paginationData.items.map(i => i.toJSON());
941
- response.push(...(useToon && toonEncode
942
- ? [toonEncode(structuredContent.networkRequests)]
987
+ response.push(...(compactEncode
988
+ ? [compactEncode(structuredContent.networkRequests)]
943
989
  : paginationData.items.map(i => i.toString())));
944
990
  }
945
991
  }
@@ -956,8 +1002,8 @@ Call ${handleDialog.name} to handle it before continuing.`);
956
1002
  structuredContent.pagination = paginationData.pagination;
957
1003
  structuredContent.consoleMessages = paginationData.items.map(item => item.toJSON());
958
1004
  response.push(...paginationData.info);
959
- if (useToon && toonEncode) {
960
- response.push(toonEncode(structuredContent.consoleMessages));
1005
+ if (compactEncode) {
1006
+ response.push(compactEncode(structuredContent.consoleMessages));
961
1007
  }
962
1008
  else {
963
1009
  response.push(...paginationData.items.map(item => item.toString()));
@@ -1032,14 +1078,14 @@ async function fetchPageTitle(page) {
1032
1078
  new Promise(resolve => setTimeout(() => resolve(''), 1000)),
1033
1079
  ]);
1034
1080
  }
1035
- function createStructuredPage(page, context, rawTitle) {
1036
- const isolatedContextName = context.getIsolatedContextName(page);
1081
+ function createStructuredPage(mcpPage, context, rawTitle) {
1082
+ const isolatedContextName = mcpPage.isolatedContextName;
1037
1083
  const title = truncateTitle(rawTitle);
1038
1084
  const entry = {
1039
- id: context.getPageId(page),
1040
- url: page.url(),
1085
+ id: mcpPage.id,
1086
+ url: mcpPage.pptrPage.url(),
1041
1087
  title,
1042
- selected: context.isPageSelected(page),
1088
+ selected: context.isPageSelected(mcpPage),
1043
1089
  };
1044
1090
  if (isolatedContextName) {
1045
1091
  entry.isolatedContext = isolatedContextName;
@@ -4,9 +4,9 @@
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
6
  import { FakeIssuesManager } from './devtools/DevtoolsUtils.js';
7
- import { logger } from './logger.js';
8
7
  import { DevTools } from './third_party/index.js';
9
8
  import { createIdGenerator, stableIdSymbol, } from './utils/id.js';
9
+ import { logger } from './utils/logger.js';
10
10
  export class UncaughtError {
11
11
  details;
12
12
  targetId;
@@ -16,113 +16,55 @@ export class UncaughtError {
16
16
  }
17
17
  }
18
18
  export class PageCollector {
19
- #browser;
20
- #listenersInitializer;
21
- #listeners = new WeakMap();
19
+ pptrPage;
20
+ #listeners;
22
21
  maxNavigationSaved = 3;
23
22
  /**
24
23
  * This maps a Page to a list of navigations with a sub-list
25
24
  * of all collected resources.
26
25
  * The newer navigations come first.
27
26
  */
28
- storage = new WeakMap();
29
- constructor(browser, listeners) {
30
- this.#browser = browser;
31
- this.#listenersInitializer = listeners;
32
- }
33
- async init(pages) {
34
- for (const page of pages) {
35
- this.addPage(page);
36
- }
37
- this.#browser.on('targetcreated', this.#onTargetCreated);
38
- this.#browser.on('targetdestroyed', this.#onTargetDestroyed);
39
- }
40
- dispose() {
41
- this.#browser.off('targetcreated', this.#onTargetCreated);
42
- this.#browser.off('targetdestroyed', this.#onTargetDestroyed);
43
- }
44
- #onTargetCreated = async (target) => {
45
- try {
46
- const page = await target.page();
47
- if (!page) {
48
- return;
49
- }
50
- this.addPage(page);
51
- }
52
- catch (err) {
53
- logger?.('Error getting a page for a target onTargetCreated', err);
54
- }
55
- };
56
- #onTargetDestroyed = async (target) => {
57
- try {
58
- const page = await target.page();
59
- if (!page) {
60
- return;
61
- }
62
- this.cleanupPageDestroyed(page);
63
- }
64
- catch (err) {
65
- logger?.('Error getting a page for a target onTargetDestroyed', err);
66
- }
67
- };
68
- addPage(page) {
69
- this.#initializePage(page);
70
- }
71
- #initializePage(page) {
72
- if (this.storage.has(page)) {
73
- return;
74
- }
27
+ storage = [[]];
28
+ constructor(page, listeners) {
29
+ this.pptrPage = page;
75
30
  const idGenerator = createIdGenerator();
76
- const storedLists = [[]];
77
- this.storage.set(page, storedLists);
78
- const listeners = this.#listenersInitializer(value => {
31
+ const listenerMap = listeners(value => {
79
32
  const withId = value;
80
33
  withId[stableIdSymbol] = idGenerator();
81
- const navigations = this.storage.get(page) ?? [[]];
82
- navigations[0].push(withId);
34
+ this.storage[0].push(withId);
83
35
  });
84
- listeners['framenavigated'] = (frame) => {
36
+ listenerMap['framenavigated'] = (frame) => {
85
37
  // Only split the storage on main frame navigation
86
- if (frame !== page.mainFrame()) {
38
+ if (frame !== this.pptrPage.mainFrame()) {
87
39
  return;
88
40
  }
89
- this.splitAfterNavigation(page);
41
+ this.splitAfterNavigation();
90
42
  };
91
- for (const [name, listener] of Object.entries(listeners)) {
92
- page.on(name, listener);
43
+ for (const [name, listener] of Object.entries(listenerMap)) {
44
+ this.pptrPage.on(name, listener);
93
45
  }
94
- this.#listeners.set(page, listeners);
46
+ this.#listeners = listenerMap;
95
47
  }
96
- splitAfterNavigation(page) {
97
- const navigations = this.storage.get(page);
98
- if (!navigations) {
99
- return;
100
- }
101
- // Add the latest navigation first
102
- navigations.unshift([]);
103
- navigations.splice(this.maxNavigationSaved);
104
- }
105
- cleanupPageDestroyed(page) {
106
- const listeners = this.#listeners.get(page);
107
- if (listeners) {
108
- for (const [name, listener] of Object.entries(listeners)) {
109
- page.off(name, listener);
48
+ dispose() {
49
+ if (this.#listeners) {
50
+ for (const [name, listener] of Object.entries(this.#listeners)) {
51
+ this.pptrPage.off(name, listener);
110
52
  }
111
53
  }
112
- this.storage.delete(page);
113
54
  }
114
- getData(page, includePreservedData) {
115
- const navigations = this.storage.get(page);
116
- if (!navigations) {
117
- return [];
118
- }
55
+ splitAfterNavigation() {
56
+ // Add the latest navigation first
57
+ this.storage.unshift([]);
58
+ this.storage.splice(this.maxNavigationSaved);
59
+ }
60
+ getData(includePreservedData) {
119
61
  if (!includePreservedData) {
120
- return navigations[0];
62
+ return this.storage[0];
121
63
  }
122
64
  const data = [];
123
65
  for (let index = this.maxNavigationSaved; index >= 0; index--) {
124
- if (navigations[index]) {
125
- data.push(...navigations[index]);
66
+ if (this.storage[index]) {
67
+ data.push(...this.storage[index]);
126
68
  }
127
69
  }
128
70
  return data;
@@ -130,23 +72,15 @@ export class PageCollector {
130
72
  getIdForResource(resource) {
131
73
  return resource[stableIdSymbol] ?? -1;
132
74
  }
133
- getById(page, stableId) {
134
- const navigations = this.storage.get(page);
135
- if (!navigations) {
136
- throw new Error('No requests found for selected page');
137
- }
138
- const item = this.find(page, item => item[stableIdSymbol] === stableId);
75
+ getById(stableId) {
76
+ const item = this.find(item => item[stableIdSymbol] === stableId);
139
77
  if (!item) {
140
78
  throw new Error('Request not found for selected page');
141
79
  }
142
80
  return item;
143
81
  }
144
- find(page, filter) {
145
- const navigations = this.storage.get(page);
146
- if (!navigations) {
147
- return;
148
- }
149
- for (const navigation of navigations) {
82
+ find(filter) {
83
+ for (const navigation of this.storage) {
150
84
  const item = navigation.find(filter);
151
85
  if (item) {
152
86
  return item;
@@ -156,19 +90,15 @@ export class PageCollector {
156
90
  }
157
91
  }
158
92
  export class ConsoleCollector extends PageCollector {
159
- #subscribedPages = new WeakMap();
160
- addPage(page) {
161
- super.addPage(page);
162
- if (!this.#subscribedPages.has(page)) {
163
- const subscriber = new PageEventSubscriber(page);
164
- this.#subscribedPages.set(page, subscriber);
165
- void subscriber.subscribe();
166
- }
93
+ #subscriber;
94
+ constructor(page, listeners) {
95
+ super(page, listeners);
96
+ this.#subscriber = new PageEventSubscriber(this.pptrPage);
97
+ this.#subscriber.subscribe();
167
98
  }
168
- cleanupPageDestroyed(page) {
169
- super.cleanupPageDestroyed(page);
170
- this.#subscribedPages.get(page)?.unsubscribe();
171
- this.#subscribedPages.delete(page);
99
+ dispose() {
100
+ super.dispose();
101
+ this.#subscriber?.unsubscribe();
172
102
  }
173
103
  }
174
104
  class PageEventSubscriber {
@@ -194,7 +124,7 @@ class PageEventSubscriber {
194
124
  this.#issueAggregator = new DevTools.IssueAggregator(this.#issueManager);
195
125
  this.#issueAggregator.addEventListener("AggregatedIssueUpdated" /* DevTools.IssueAggregatorEvents.AGGREGATED_ISSUE_UPDATED */, this.#onAggregatedIssue);
196
126
  }
197
- async subscribe() {
127
+ subscribe() {
198
128
  this.#resetIssueAggregator();
199
129
  this.#page.on('framenavigated', this.#onFrameNavigated);
200
130
  this.#page.on('issue', this.#onIssueAdded);
@@ -261,23 +191,19 @@ class PageEventSubscriber {
261
191
  };
262
192
  }
263
193
  export class NetworkCollector extends PageCollector {
264
- constructor(browser, listeners = collect => {
194
+ constructor(page, listeners = collect => {
265
195
  return {
266
196
  request: req => {
267
197
  collect(req);
268
198
  },
269
199
  };
270
200
  }) {
271
- super(browser, listeners);
201
+ super(page, listeners);
272
202
  }
273
- splitAfterNavigation(page) {
274
- const navigations = this.storage.get(page) ?? [];
275
- if (!navigations) {
276
- return;
277
- }
278
- const requests = navigations[0];
203
+ splitAfterNavigation() {
204
+ const requests = this.storage[0];
279
205
  const lastRequestIdx = requests.findLastIndex(request => {
280
- return request.frame() === page.mainFrame()
206
+ return request.frame() === this.pptrPage.mainFrame()
281
207
  ? request.isNavigationRequest()
282
208
  : false;
283
209
  });
@@ -286,12 +212,12 @@ export class NetworkCollector extends PageCollector {
286
212
  // Keep the reference
287
213
  if (lastRequestIdx !== -1) {
288
214
  const fromCurrentNavigation = requests.splice(lastRequestIdx);
289
- navigations.unshift(fromCurrentNavigation);
215
+ this.storage.unshift(fromCurrentNavigation);
290
216
  }
291
217
  else {
292
- navigations.unshift([]);
218
+ this.storage.unshift([]);
293
219
  }
294
- navigations.splice(this.maxNavigationSaved);
220
+ this.storage.splice(this.maxNavigationSaved);
295
221
  }
296
222
  }
297
223
  //# sourceMappingURL=PageCollector.js.map