chrome-devtools-mcp 1.10.1 → 1.12.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 (103) hide show
  1. package/README.md +72 -20
  2. package/build/src/BrowserManager.js +155 -27
  3. package/build/src/McpContext.js +598 -200
  4. package/build/src/McpPage.js +513 -131
  5. package/build/src/McpResponse.js +291 -116
  6. package/build/src/McpWorker.js +66 -0
  7. package/build/src/SlimMcpResponse.js +5 -1
  8. package/build/src/TextSnapshot.js +40 -20
  9. package/build/src/ToolHandler.js +306 -147
  10. package/build/src/bin/chrome-devtools-mcp-main.js +13 -10
  11. package/build/src/bin/chrome-devtools-mcp.js +1 -1
  12. package/build/src/bin/chrome-devtools.js +34 -44
  13. package/build/src/collectors/PageCollector.js +13 -9
  14. package/build/src/collectors/ServiceWorkerCollector.js +20 -13
  15. package/build/src/collectors/constants.js +7 -0
  16. package/build/src/config/ConfigLocator.js +70 -0
  17. package/build/src/config/ConfigParser.js +159 -0
  18. package/build/src/config/ConfigWatcher.js +94 -0
  19. package/build/src/config/ServerConfig.js +251 -0
  20. package/build/src/config/browser-options.js +15 -17
  21. package/build/src/config/category-options.js +15 -30
  22. package/build/src/config/cli-commands.js +165 -5
  23. package/build/src/config/cli-options.js +441 -58
  24. package/build/src/config/mcp-options.js +212 -264
  25. package/build/src/config/puppeteer-options.js +67 -0
  26. package/build/src/config/tool-options.js +60 -0
  27. package/build/src/daemon/client.js +84 -44
  28. package/build/src/daemon/daemon.js +59 -45
  29. package/build/src/daemon/utils.js +46 -12
  30. package/build/src/devtools/DevToolsCommentBridge.js +71 -11
  31. package/build/src/devtools/DevtoolsUtils.js +52 -15
  32. package/build/src/devtools/McpHostBindingAdapter.js +0 -1
  33. package/build/src/formatters/CommentFormatter.js +4 -13
  34. package/build/src/formatters/ConsoleFormatter.js +29 -2
  35. package/build/src/formatters/CssFormatter.js +3 -2
  36. package/build/src/formatters/HeapSnapshotFormatter.js +111 -57
  37. package/build/src/formatters/IssueFormatter.js +33 -32
  38. package/build/src/formatters/NetworkFormatter.js +62 -22
  39. package/build/src/formatters/RemoteObjectFormatter.js +231 -0
  40. package/build/src/formatters/SnapshotFormatter.js +44 -7
  41. package/build/src/index.js +285 -88
  42. package/build/src/processors/ChunkedTraceParser.js +11 -11
  43. package/build/src/processors/HeapSnapshotManager.js +455 -156
  44. package/build/src/processors/PerformanceTrace.js +9 -9
  45. package/build/src/telemetry/ClearcutLogger.js +1 -1
  46. package/build/src/telemetry/transformation.js +7 -11
  47. package/build/src/telemetry/watchdog/main.js +1 -1
  48. package/build/src/third_party/THIRD_PARTY_NOTICES +399 -689
  49. package/build/src/third_party/bundled-packages.json +7 -8
  50. package/build/src/third_party/cli.js +9239 -0
  51. package/build/src/third_party/devtools-formatter-worker.js +4299 -2517
  52. package/build/src/third_party/devtools-heap-snapshot-worker.js +1298 -22
  53. package/build/src/third_party/index.js +132003 -146852
  54. package/build/src/third_party/issue-descriptions/cookieWarnMetadataGrantRead.md +0 -1
  55. package/build/src/third_party/issue-descriptions/cookieWarnMetadataGrantReadOptOut.md +5 -0
  56. package/build/src/third_party/issue-descriptions/cookieWarnMetadataGrantSet.md +0 -1
  57. package/build/src/third_party/issue-descriptions/cookieWarnMetadataGrantSetOptOut.md +5 -0
  58. package/build/src/third_party/issue-descriptions/deprecation.md +1 -1
  59. package/build/src/third_party/issue-descriptions/genericGeolocationPromptWithoutUserGesture.md +5 -0
  60. package/build/src/third_party/issue-descriptions/sriValidationFailedIntegrityMismatch.md +2 -0
  61. package/build/src/third_party/lighthouse-devtools-mcp-bundle.js +54576 -52174
  62. package/build/src/tools/ToolDefinition.js +102 -12
  63. package/build/src/tools/comments.js +62 -4
  64. package/build/src/tools/console.js +6 -4
  65. package/build/src/tools/css.js +5 -2
  66. package/build/src/tools/emulation.js +22 -8
  67. package/build/src/tools/extensions.js +5 -0
  68. package/build/src/tools/input.js +29 -9
  69. package/build/src/tools/lighthouse.js +136 -12
  70. package/build/src/tools/memory.js +166 -59
  71. package/build/src/tools/network.js +5 -4
  72. package/build/src/tools/pages.js +52 -7
  73. package/build/src/tools/performance.js +28 -7
  74. package/build/src/tools/pwa.js +7 -0
  75. package/build/src/tools/screencast.js +74 -33
  76. package/build/src/tools/screenshot.js +52 -21
  77. package/build/src/tools/script.js +125 -40
  78. package/build/src/tools/slim/tools.js +27 -13
  79. package/build/src/tools/snapshot.js +13 -3
  80. package/build/src/tools/thirdPartyDeveloper.js +9 -5
  81. package/build/src/tools/tools.js +35 -22
  82. package/build/src/tools/webmcp.js +11 -6
  83. package/build/src/types.js +11 -0
  84. package/build/src/utils/TaskRunner.js +136 -0
  85. package/build/src/utils/WaitForHelper.js +15 -2
  86. package/build/src/utils/bytes.js +2 -12
  87. package/build/src/utils/check-for-updates.js +2 -2
  88. package/build/src/utils/disclaimers.js +27 -0
  89. package/build/src/utils/errorHandling.js +20 -0
  90. package/build/src/utils/keyboard.js +14 -2
  91. package/build/src/utils/logger.js +84 -5
  92. package/build/src/utils/resourceType.js +27 -0
  93. package/build/src/utils/text.js +44 -0
  94. package/build/src/utils/timeout.js +14 -0
  95. package/build/src/utils/url.js +140 -3
  96. package/build/src/version.js +1 -1
  97. package/package.json +16 -11
  98. package/skills/a11y-debugging/SKILL.md +7 -12
  99. package/skills/chrome-devtools/SKILL.md +2 -2
  100. package/skills/chrome-devtools-cli/SKILL.md +18 -15
  101. package/skills/cookie-debugging/SKILL.md +8 -5
  102. package/skills/debug-optimize-lcp/SKILL.md +1 -1
  103. package/skills/troubleshooting/SKILL.md +5 -6
@@ -6,46 +6,83 @@
6
6
  import { logger } from '../utils/logger.js';
7
7
  const DEFAULT_DEBOUNCE_MS = 200;
8
8
  /**
9
- * Manages the bidirectional bridge between DevTools frontend comments
10
- * and the MCP server notification system.
9
+ * Manages the bridge between DevTools frontend comments and the MCP server.
10
+ * Comment events are debounced and delivered to callers that wait for them
11
+ * through `waitForCommentEvent`.
11
12
  */
12
13
  export class DevToolsCommentBridge {
13
- #onNotification;
14
14
  #debounceMs;
15
15
  #commentDebounceTimer;
16
16
  #attachedPages = new Set();
17
+ #commentWaiters = new Set();
17
18
  constructor(options) {
18
- this.#onNotification = options?.onNotification;
19
19
  this.#debounceMs = options?.debounceMs ?? DEFAULT_DEBOUNCE_MS;
20
20
  }
21
21
  isAttached(devtoolsPage) {
22
22
  return this.#attachedPages.has(devtoolsPage);
23
23
  }
24
+ /**
25
+ * Attaches to the DevTools page if it exposes the CD4A bridge.
26
+ *
27
+ * Returns false if the bridge does not exist, e.g., because the connected
28
+ * Chrome version does not support DevTools comments or the feature is
29
+ * disabled, or if the comment event binding could not be installed.
30
+ * Negative results are not cached so that a DevTools window that has not
31
+ * finished loading yet is checked again on the next call.
32
+ */
24
33
  async attach(devtoolsPage) {
25
34
  if (this.#attachedPages.has(devtoolsPage)) {
26
- return;
35
+ return true;
36
+ }
37
+ try {
38
+ const hasBridge = await devtoolsPage.evaluate(() => {
39
+ return Boolean(window.universe?.cd4aBridge);
40
+ });
41
+ if (!hasBridge) {
42
+ return false;
43
+ }
44
+ }
45
+ catch (e) {
46
+ logger?.('DevToolsCommentBridge: evaluate failed', e);
47
+ return false;
27
48
  }
28
- this.#attachedPages.add(devtoolsPage);
29
49
  try {
30
50
  await devtoolsPage.exposeFunction('__onDevToolsCommentEvent', () => {
31
51
  this.#handleCommentEvent();
32
52
  });
33
53
  }
34
54
  catch (e) {
55
+ // The binding may already exist, e.g., exposed by a previous bridge.
56
+ // Whether it is usable is checked in the page below.
35
57
  logger?.('DevToolsCommentBridge: exposeFunction already bound or failed', e);
36
58
  }
59
+ let attached = false;
37
60
  try {
38
- await devtoolsPage.evaluate(() => {
61
+ attached = await devtoolsPage.evaluate(() => {
62
+ const cd4aBridge = window.universe?.cd4aBridge;
63
+ if (!cd4aBridge ||
64
+ typeof window.__onDevToolsCommentEvent !== 'function') {
65
+ return false;
66
+ }
67
+ if (window.__onDevToolsCommentListener) {
68
+ cd4aBridge.removeEventListener('CommentThreadsChanged', window.__onDevToolsCommentListener);
69
+ }
39
70
  window.__onDevToolsCommentListener = () => {
40
71
  window.__onDevToolsCommentEvent?.();
41
72
  };
42
- window.universe?.cd4aBridge?.addEventListener('CommentThreadsChanged', window.__onDevToolsCommentListener);
43
- window.universe?.cd4aBridge?.setAgentAttached(true);
73
+ cd4aBridge.addEventListener('CommentThreadsChanged', window.__onDevToolsCommentListener);
74
+ cd4aBridge.setAgentAttached(true);
75
+ return true;
44
76
  });
45
77
  }
46
78
  catch (e) {
47
79
  logger?.('DevToolsCommentBridge: evaluate failed', e);
48
80
  }
81
+ if (!attached) {
82
+ return false;
83
+ }
84
+ this.#attachedPages.add(devtoolsPage);
85
+ return true;
49
86
  }
50
87
  async getComments(devtoolsPage) {
51
88
  return await devtoolsPage.evaluate(() => {
@@ -53,24 +90,47 @@ export class DevToolsCommentBridge {
53
90
  return window.universe?.cd4aBridge?.getCommentThreads() ?? [];
54
91
  });
55
92
  }
93
+ /**
94
+ * Resolves `true` on the next debounced comment event, or `false` when
95
+ * `timeoutMs` elapses or the bridge is disposed first.
96
+ */
97
+ waitForCommentEvent(timeoutMs) {
98
+ return new Promise(resolve => {
99
+ const settle = (changed) => {
100
+ clearTimeout(timer);
101
+ this.#commentWaiters.delete(settle);
102
+ resolve(changed);
103
+ };
104
+ const timer = setTimeout(() => {
105
+ settle(false);
106
+ }, timeoutMs);
107
+ this.#commentWaiters.add(settle);
108
+ });
109
+ }
56
110
  #handleCommentEvent() {
57
111
  if (this.#commentDebounceTimer) {
58
112
  clearTimeout(this.#commentDebounceTimer);
59
113
  }
60
114
  this.#commentDebounceTimer = setTimeout(() => {
61
- this.#onNotification?.('DevTools comment threads updated');
115
+ this.#notifyCommentWaiters(true);
62
116
  }, this.#debounceMs);
63
117
  }
118
+ #notifyCommentWaiters(changed) {
119
+ for (const waiter of [...this.#commentWaiters]) {
120
+ waiter(changed);
121
+ }
122
+ }
64
123
  dispose() {
65
124
  if (this.#commentDebounceTimer) {
66
125
  clearTimeout(this.#commentDebounceTimer);
67
126
  this.#commentDebounceTimer = undefined;
68
127
  }
128
+ this.#notifyCommentWaiters(false);
69
129
  for (const page of this.#attachedPages) {
70
130
  try {
71
131
  const result = page.evaluate(() => {
72
132
  if (window.__onDevToolsCommentListener) {
73
- window.universe?.cd4aBridge?.removeEventListener?.('CommentThreadsChanged', window.__onDevToolsCommentListener);
133
+ window.universe?.cd4aBridge?.removeEventListener('CommentThreadsChanged', window.__onDevToolsCommentListener);
74
134
  delete window.__onDevToolsCommentListener;
75
135
  }
76
136
  window.universe?.cd4aBridge?.setAgentAttached(false);
@@ -3,7 +3,7 @@
3
3
  * Copyright 2025 Google LLC
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
- import { DevTools } from '../third_party/index.js';
6
+ import { DevTools, } from '../third_party/index.js';
7
7
  import { McpHostBindingAdapter } from './McpHostBindingAdapter.js';
8
8
  /**
9
9
  * A mock implementation of an issues manager that only implements the methods
@@ -153,14 +153,14 @@ export class SymbolizedError {
153
153
  }
154
154
  static async fromDetails(opts) {
155
155
  const message = SymbolizedError.#getMessage(opts.details);
156
- if (!opts.includeStackAndCause || !opts.devTools) {
156
+ if (!opts.includeStackAndCause || (!opts.devTools && !opts.session)) {
157
157
  return new SymbolizedError(message, opts.resolvedStackTraceForTesting, opts.resolvedCauseForTesting);
158
158
  }
159
159
  let stackTrace;
160
160
  if (opts.resolvedStackTraceForTesting) {
161
161
  stackTrace = opts.resolvedStackTraceForTesting;
162
162
  }
163
- else if (opts.details.stackTrace) {
163
+ else if (opts.devTools && opts.details.stackTrace) {
164
164
  try {
165
165
  stackTrace = await createStackTrace(opts.devTools, opts.details.stackTrace, opts.targetId);
166
166
  }
@@ -176,12 +176,13 @@ export class SymbolizedError {
176
176
  }
177
177
  else if (opts.details.exception) {
178
178
  try {
179
- const causeRemoteObj = await SymbolizedError.#lookupCause(opts.devTools, opts.details.exception, opts.targetId);
179
+ const causeRemoteObj = await SymbolizedError.#lookupCause(opts.devTools, opts.details.exception, opts.targetId, opts.session);
180
180
  if (causeRemoteObj) {
181
181
  cause = await SymbolizedError.fromError({
182
182
  devTools: opts.devTools,
183
183
  error: causeRemoteObj,
184
184
  targetId: opts.targetId,
185
+ session: opts.session,
185
186
  });
186
187
  }
187
188
  }
@@ -192,12 +193,13 @@ export class SymbolizedError {
192
193
  return new SymbolizedError(message, stackTrace, cause);
193
194
  }
194
195
  static async fromError(opts) {
195
- const details = await SymbolizedError.#getExceptionDetails(opts.devTools, opts.error, opts.targetId);
196
+ const details = await SymbolizedError.#getExceptionDetails(opts.devTools, opts.error, opts.targetId, opts.session);
196
197
  if (details) {
197
- return SymbolizedError.fromDetails({
198
+ return await SymbolizedError.fromDetails({
198
199
  details,
199
200
  devTools: opts.devTools,
200
201
  targetId: opts.targetId,
202
+ session: opts.session,
201
203
  includeStackAndCause: true,
202
204
  });
203
205
  }
@@ -207,18 +209,41 @@ export class SymbolizedError {
207
209
  // For Runtime.exceptionThrown with a present exception object, `details.text` will be "Uncaught" and
208
210
  // we have to manually parse out the error text from the exception description.
209
211
  // In the case of Runtime.getExceptionDetails, `details.text` has the Error.message.
210
- if (details.text === 'Uncaught' && details.exception) {
211
- return ('Uncaught ' +
212
+ // Unhandled promise rejections work the same way, with
213
+ // "Uncaught (in promise)" as `details.text` and the rejection reason as
214
+ // the exception.
215
+ if ((details.text === 'Uncaught' ||
216
+ details.text === 'Uncaught (in promise)') &&
217
+ details.exception) {
218
+ return (details.text +
219
+ ' ' +
212
220
  SymbolizedError.#getMessageFromException(details.exception));
213
221
  }
214
222
  return details.text;
215
223
  }
216
224
  static #getMessageFromException(error) {
217
- const messageWithRest = error.description?.split('\n at ', 2) ?? [];
225
+ if (error.description === undefined) {
226
+ // Primitive values, e.g. `Promise.reject('reason')`, have no description.
227
+ if (error.unserializableValue !== undefined) {
228
+ return error.unserializableValue;
229
+ }
230
+ return error.value === undefined ? '' : String(error.value);
231
+ }
232
+ const messageWithRest = error.description.split('\n at ', 2);
218
233
  return messageWithRest[0] ?? '';
219
234
  }
220
- static async #getExceptionDetails(devTools, error, targetId) {
221
- if (!devTools || (error.type !== 'object' && error.subtype !== 'error')) {
235
+ static async #getExceptionDetails(devTools, error, targetId, session) {
236
+ if (error.type !== 'object' && error.subtype !== 'error') {
237
+ return null;
238
+ }
239
+ if (session) {
240
+ if (!error.objectId) {
241
+ return null;
242
+ }
243
+ const { exceptionDetails } = await session.send('Runtime.getExceptionDetails', { errorObjectId: error.objectId });
244
+ return exceptionDetails ?? null;
245
+ }
246
+ if (!devTools) {
222
247
  return null;
223
248
  }
224
249
  const targetManager = devTools.universe.context.get(DevTools.TargetManager);
@@ -228,8 +253,20 @@ export class SymbolizedError {
228
253
  const model = target.model(DevTools.RuntimeModel);
229
254
  return ((await model.getExceptionDetails(error.objectId)) ?? null);
230
255
  }
231
- static async #lookupCause(devTools, error, targetId) {
232
- if (!devTools || (error.type !== 'object' && error.subtype !== 'error')) {
256
+ static async #lookupCause(devTools, error, targetId, session) {
257
+ if (error.type !== 'object' && error.subtype !== 'error') {
258
+ return null;
259
+ }
260
+ if (session) {
261
+ if (!error.objectId) {
262
+ return null;
263
+ }
264
+ const { result } = await session.send('Runtime.getProperties', {
265
+ objectId: error.objectId,
266
+ });
267
+ return result.find(prop => prop.name === 'cause')?.value ?? null;
268
+ }
269
+ if (!devTools) {
233
270
  return null;
234
271
  }
235
272
  const targetManager = devTools.universe.context.get(DevTools.TargetManager);
@@ -252,7 +289,7 @@ export async function createStackTraceForConsoleMessage(devTools, consoleMessage
252
289
  const message = consoleMessage;
253
290
  const rawStackTrace = message._rawStackTrace();
254
291
  if (rawStackTrace) {
255
- return createStackTrace(devTools, rawStackTrace, message._targetId());
292
+ return await createStackTrace(devTools, rawStackTrace, message._targetId());
256
293
  }
257
294
  return undefined;
258
295
  }
@@ -282,7 +319,7 @@ export async function createStackTrace(devTools, rawStackTrace, targetId) {
282
319
  .catch()));
283
320
  const binding = devTools.universe.context.get(DevTools.DebuggerWorkspaceBinding);
284
321
  // DevTools uses branded types for ScriptId and others. Casting the puppeteer protocol type to the DevTools protocol type is safe.
285
- return binding.createStackTraceFromProtocolRuntime(rawStackTrace, target);
322
+ return await binding.createStackTraceFromProtocolRuntime(rawStackTrace, target);
286
323
  }
287
324
  // Waits indefinitely for the script so pair it with Promise.race.
288
325
  async function waitForScript(model, scriptId, signal) {
@@ -3,7 +3,6 @@
3
3
  * Copyright 2026 Google LLC
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
- /* eslint-disable @typescript-eslint/no-empty-function */
7
6
  import { DevTools } from '../third_party/index.js';
8
7
  /**
9
8
  * BaseClass that is noop or throws for methods.
@@ -9,16 +9,10 @@ function formatCommentThread(thread) {
9
9
  `- Comment: ${thread.text}`,
10
10
  ];
11
11
  if (thread.elementUid) {
12
- lines.push(`- Target element (snapshot UID): ${thread.elementUid}`);
12
+ lines.push(`- Related element uid: ${thread.elementUid}`);
13
13
  }
14
14
  if (thread.reqid !== undefined) {
15
- lines.push(`- Network request ID (reqid): ${thread.reqid}`);
16
- }
17
- if (thread.editor) {
18
- const location = thread.editor.filePath
19
- ? `${thread.editor.filePath}:${thread.editor.lineNumber}`
20
- : `line ${thread.editor.lineNumber}`;
21
- lines.push(`- Editor location: ${location}`);
15
+ lines.push(`- Related network reqid: ${thread.reqid}`);
22
16
  }
23
17
  return lines.join('\n');
24
18
  }
@@ -44,8 +38,8 @@ export class CommentFormatter {
44
38
  for (const thread of threads) {
45
39
  let elementUid;
46
40
  const resolveBackendNodeId = options?.resolveBackendNodeId;
47
- if (thread.backendNodeId !== undefined && resolveBackendNodeId) {
48
- elementUid = await resolveBackendNodeId(thread.backendNodeId);
41
+ if (thread.node?.backendNodeId !== undefined && resolveBackendNodeId) {
42
+ elementUid = await resolveBackendNodeId(thread.node.backendNodeId);
49
43
  }
50
44
  let reqid;
51
45
  const resolveCdpRequestId = options?.resolveCdpRequestId;
@@ -62,9 +56,6 @@ export class CommentFormatter {
62
56
  if (reqid !== undefined) {
63
57
  item.reqid = reqid;
64
58
  }
65
- if (thread.editor) {
66
- item.editor = thread.editor;
67
- }
68
59
  structuredThreads.push(item);
69
60
  }
70
61
  return new CommentFormatter(structuredThreads);
@@ -6,6 +6,19 @@
6
6
  import { createStackTraceForConsoleMessage, SymbolizedError, } from '../devtools/DevtoolsUtils.js';
7
7
  import { UncaughtError } from '../collectors/PageCollector.js';
8
8
  import * as DevTools from '../third_party/index.js';
9
+ import { formatRemoteObject } from './RemoteObjectFormatter.js';
10
+ // JSON.stringify prints Map, Set, functions and DOM nodes as `{}`, and throws
11
+ // on symbols and cyclic objects. Those are formatted from their preview.
12
+ function isJsonLike(remoteObject) {
13
+ if (remoteObject.type === 'object') {
14
+ return (remoteObject.subtype === undefined ||
15
+ remoteObject.subtype === 'array' ||
16
+ remoteObject.subtype === 'null');
17
+ }
18
+ return (remoteObject.type !== 'function' &&
19
+ remoteObject.type !== 'symbol' &&
20
+ remoteObject.type !== 'bigint');
21
+ }
9
22
  export class ConsoleFormatter {
10
23
  #id;
11
24
  #type;
@@ -47,6 +60,7 @@ export class ConsoleFormatter {
47
60
  devTools: options?.devTools,
48
61
  details: msg.details,
49
62
  targetId: msg.targetId,
63
+ session: msg.session,
50
64
  includeStackAndCause: options?.fetchDetailedData || options?.fetchStackTrace,
51
65
  resolvedStackTraceForTesting: options?.resolvedStackTraceForTesting,
52
66
  resolvedCauseForTesting: options?.resolvedCauseForTesting,
@@ -78,7 +92,20 @@ export class ConsoleFormatter {
78
92
  targetId: msg._targetId(),
79
93
  });
80
94
  }
81
- return await arg.jsonValue();
95
+ if (!isJsonLike(remoteObject)) {
96
+ return formatRemoteObject(remoteObject);
97
+ }
98
+ try {
99
+ return await arg.jsonValue();
100
+ }
101
+ catch (error) {
102
+ // JSON can't represent the value (for example, a cyclic object)
103
+ // or the page is gone; the preview still describes it.
104
+ if (remoteObject.preview) {
105
+ return formatRemoteObject(remoteObject);
106
+ }
107
+ throw error;
108
+ }
82
109
  }
83
110
  catch {
84
111
  return `<error: Argument ${i} is no longer available>`;
@@ -295,7 +322,7 @@ function formatAsyncFragment(fragment, formatter) {
295
322
  }
296
323
  const separatorLineLength = 40;
297
324
  const prefix = `--- ${fragment.description || 'async'} `;
298
- const separator = prefix + '-'.repeat(separatorLineLength - prefix.length);
325
+ const separator = prefix + '-'.repeat(Math.max(0, separatorLineLength - prefix.length));
299
326
  return [separator, ...formattedFrames];
300
327
  }
301
328
  function formatFrame(frame) {
@@ -133,8 +133,9 @@ function createContainerQueryAncestor(containerQuery, containerDetails) {
133
133
  };
134
134
  }
135
135
  /**
136
- * Collects enclosing ancestor rules (@media, @container, @supports, @layer,
137
- * @scope, @starting-style, @navigation, and CSS nesting) for a style rule.
136
+ * Collects enclosing ancestor rules (`@media`, `@container`, `@supports`,
137
+ * `@layer`, `@scope`, `@starting-style`, `@navigation`, and CSS nesting) for a
138
+ * style rule.
138
139
  */
139
140
  function collectAncestorRules(rule, containerDetails) {
140
141
  if (!rule.ruleTypes || rule.ruleTypes.length === 0) {
@@ -4,8 +4,48 @@
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
6
  import { DevTools } from '../third_party/index.js';
7
- import { stableIdSymbol } from '../utils/id.js';
7
+ import { truncateText } from '../utils/text.js';
8
8
  const { formatBytesToKb } = DevTools.I18n.ByteUtilities;
9
+ export const MAX_NAME_LENGTH = 100;
10
+ /**
11
+ * Renders a name for single-line output: the name is truncated to
12
+ * `maxNameLength` and line breaks are always escaped.
13
+ */
14
+ export function formatName(name, options) {
15
+ return truncateValue(name, options.maxNameLength)
16
+ .replaceAll('\r', '\\r')
17
+ .replaceAll('\n', '\\n');
18
+ }
19
+ /**
20
+ * Truncates `value` to `maxLength`, appending an ellipsis if it was cut off.
21
+ */
22
+ function truncateValue(value, maxLength = MAX_NAME_LENGTH) {
23
+ return truncateText(value, maxLength);
24
+ }
25
+ /**
26
+ * Flattens the analysis into the contexts matching `options`, ranked descending
27
+ * by their dead-field retained-size score across all scopes.
28
+ */
29
+ export function collectRankedContexts(analysis, options = {}) {
30
+ const { min = 0, max } = options.retainedSize ?? {};
31
+ const contexts = [];
32
+ for (const scope of analysis.scopes) {
33
+ if (options.scopeInfoNodeId !== undefined &&
34
+ scope.scopeInfoNodeId !== options.scopeInfoNodeId) {
35
+ continue;
36
+ }
37
+ for (const context of scope.contexts) {
38
+ const score = context.deadFieldsRetainedSizeSum;
39
+ if (score < min || (max !== undefined && score > max)) {
40
+ continue;
41
+ }
42
+ contexts.push({ scope, context });
43
+ }
44
+ }
45
+ contexts.sort((left, right) => right.context.deadFieldsRetainedSizeSum -
46
+ left.context.deadFieldsRetainedSizeSum);
47
+ return contexts;
48
+ }
9
49
  export function isNodeLike(item) {
10
50
  return (typeof item === 'object' && item !== null && 'id' in item && 'name' in item);
11
51
  }
@@ -21,11 +61,7 @@ export function isEdgeLike(item) {
21
61
  'name' in item.node);
22
62
  }
23
63
  export class HeapSnapshotFormatter {
24
- #aggregates;
25
- constructor(aggregates) {
26
- this.#aggregates = aggregates;
27
- }
28
- static formatNodes(items) {
64
+ static formatNodes(items, options) {
29
65
  const lines = [];
30
66
  if (items.length > 0) {
31
67
  const firstItem = items[0];
@@ -38,19 +74,19 @@ export class HeapSnapshotFormatter {
38
74
  }
39
75
  for (const item of items) {
40
76
  if (isNodeLike(item)) {
41
- lines.push(`${item.id},${item.name},${item.type},${item.distance},${formatBytesToKb(item.selfSize)},${formatBytesToKb(item.retainedSize)}`);
77
+ lines.push(`${item.id},${formatName(item.name, options)},${item.type},${item.distance},${formatBytesToKb(item.selfSize)},${formatBytesToKb(item.retainedSize)}`);
42
78
  }
43
79
  else if (isEdgeLike(item)) {
44
- lines.push(`${item.name},${item.type},${item.node.id},${item.node.name},${formatBytesToKb(item.node.selfSize)},${formatBytesToKb(item.node.retainedSize)}`);
80
+ lines.push(`${formatName(item.name, options)},${item.type},${item.node.id},${formatName(item.node.name, options)},${formatBytesToKb(item.node.selfSize)},${formatBytesToKb(item.node.retainedSize)}`);
45
81
  }
46
82
  }
47
83
  return lines.join('\n');
48
84
  }
49
- static formatRetainingPaths(retainingPaths) {
85
+ static formatRetainingPaths(retainingPaths, options) {
50
86
  const lines = [];
51
87
  function formatEdge(edge, depth) {
52
88
  const indent = ' '.repeat(depth);
53
- lines.push(`${indent}<- @${edge.nodeId} ${edge.nodeName} via ${edge.edgeType} ${edge.edgeName} (distance: ${edge.distance})`);
89
+ lines.push(`${indent}<- @${edge.nodeId} ${formatName(edge.nodeName, options)} via ${edge.edgeType} ${formatName(edge.edgeName, options)} (distance: ${edge.distance})`);
54
90
  for (const child of edge.children) {
55
91
  formatEdge(child, depth + 1);
56
92
  }
@@ -60,30 +96,31 @@ export class HeapSnapshotFormatter {
60
96
  }
61
97
  return lines.join('\n');
62
98
  }
63
- static formatDominators(dominators) {
99
+ static formatDominators(dominators, options) {
64
100
  const lines = [];
65
101
  lines.push('nodeId,nodeName,selfSize,retainedSize');
66
102
  for (const node of dominators) {
67
- lines.push(`${node.nodeId},${node.nodeName},${formatBytesToKb(node.selfSize)},${formatBytesToKb(node.retainedSize)}`);
103
+ lines.push(`${node.nodeId},${formatName(node.nodeName, options)},${formatBytesToKb(node.selfSize)},${formatBytesToKb(node.retainedSize)}`);
68
104
  }
69
105
  return lines.join('\n');
70
106
  }
71
- static formatDuplicateStrings(groups) {
107
+ static formatDuplicateStrings(groups, options) {
72
108
  const lines = [];
73
109
  lines.push('value,count,totalSelfSize,totalRetainedSize,truncated,nodeIds');
74
110
  for (const group of groups) {
75
111
  const nodeIds = group.nodes.map(n => `@${n.id}`).join(' ');
76
112
  const truncated = group.truncated ?? false;
77
- lines.push(`${JSON.stringify(group.value)},${group.count},${formatBytesToKb(group.totalSelfSize)},${formatBytesToKb(group.totalRetainedSize)},${truncated},${nodeIds}`);
113
+ const displayValue = truncateValue(group.value, options.maxNameLength);
114
+ lines.push(`${JSON.stringify(displayValue)},${group.count},${formatBytesToKb(group.totalSelfSize)},${formatBytesToKb(group.totalRetainedSize)},${truncated},${nodeIds}`);
78
115
  }
79
116
  return lines.join('\n');
80
117
  }
81
- static formatNativeContextSizes(sizes) {
118
+ static formatNativeContextSizes(sizes, options) {
82
119
  const lines = [];
83
120
  lines.push('nodeId,nodeName,selfSize,retainedSize,attributedSize');
84
121
  const sortedContexts = [...sizes.nativeContexts].sort((a, b) => b.attributedSize - a.attributedSize);
85
122
  for (const nc of sortedContexts) {
86
- lines.push(`${nc.nodeId},${nc.nodeName},${formatBytesToKb(nc.selfSize)},${formatBytesToKb(nc.retainedSize)},${formatBytesToKb(nc.attributedSize)}`);
123
+ lines.push(`${nc.nodeId},${formatName(nc.nodeName, options)},${formatBytesToKb(nc.selfSize)},${formatBytesToKb(nc.retainedSize)},${formatBytesToKb(nc.attributedSize)}`);
87
124
  }
88
125
  lines.push(`Shared Size: ${formatBytesToKb(sizes.sharedSize)}`);
89
126
  lines.push(`Unattributed Size: ${formatBytesToKb(sizes.noAttributionSize)}`);
@@ -97,62 +134,40 @@ export class HeapSnapshotFormatter {
97
134
  lines.push(`Total size: ${formatBytesToKb(summary.totalSize)}`);
98
135
  return lines.join('\n');
99
136
  }
100
- #getSortedAggregates() {
101
- return Object.values(this.#aggregates).sort((a, b) => b.maxRet - a.maxRet);
102
- }
103
- toString() {
104
- const sorted = this.#getSortedAggregates();
137
+ static formatAggregates(aggregates, options) {
105
138
  const lines = [];
106
- lines.push('id,name,count,selfSize,retainedSize');
107
- for (const info of sorted) {
108
- const id = info[stableIdSymbol] ?? '';
109
- lines.push(`${id},${info.name},${info.count},${formatBytesToKb(info.self)},${formatBytesToKb(info.maxRet)}`);
139
+ lines.push('id,className,count,selfSize,retainedSize');
140
+ for (const info of aggregates) {
141
+ lines.push(`${info.id},${formatName(info.className, options)},${info.count},${formatBytesToKb(info.selfSize)},${formatBytesToKb(info.retainedSize)}`);
110
142
  }
111
143
  return lines.join('\n');
112
144
  }
113
- toJSON() {
114
- const sorted = this.#getSortedAggregates();
115
- return sorted.map(info => ({
116
- id: info[stableIdSymbol],
117
- className: info.name,
118
- count: info.count,
119
- selfSize: formatBytesToKb(info.self),
120
- retainedSize: formatBytesToKb(info.maxRet),
121
- }));
122
- }
123
- static sort(aggregates) {
124
- return Object.entries(aggregates).sort((a, b) => b[1].maxRet - a[1].maxRet);
125
- }
126
- static formatDiffSummary(diffs) {
145
+ static formatDiffSummary(diffs, options) {
127
146
  const lines = [];
128
147
  lines.push('index,className,addedCount,removedCount,countDelta,addedSize,removedSize,sizeDelta');
129
- let index = 0;
130
148
  for (const diff of diffs) {
131
- lines.push(`${index},${diff.className},${diff.addedCount},${diff.removedCount},${diff.countDelta},${formatBytesToKb(diff.addedSize)},${formatBytesToKb(diff.removedSize)},${formatBytesToKb(diff.sizeDelta)}`);
132
- index++;
149
+ lines.push(`${diff.index},${formatName(diff.className, options)},${diff.addedCount},${diff.removedCount},${diff.countDelta},${formatBytesToKb(diff.addedSize)},${formatBytesToKb(diff.removedSize)},${formatBytesToKb(diff.sizeDelta)}`);
133
150
  }
134
151
  return lines.join('\n');
135
152
  }
136
- static formatDiffDetails(diff) {
137
- const lines = [];
138
- lines.push(`${diff.className}: # new: ${diff.addedCount}, # deleted: ${diff.removedCount}, # delta: ${formatSignedCount(diff.countDelta)}, alloc size: ${formatSignedSize(diff.addedSize)}, freed size: ${formatSignedSize(diff.removedSize)}, size delta: ${formatSignedSize(diff.sizeDelta)}`);
139
- const addedIds = diff.addedIds;
140
- const addedSelfSizes = diff.addedSelfSizes;
141
- const deletedIds = diff.deletedIds;
142
- const deletedSelfSizes = diff.deletedSelfSizes;
143
- lines.push(`Objects:`);
144
- for (let i = 0; i < addedIds.length; i++) {
145
- lines.push(` + @${addedIds[i]} (self_size: ${formatBytesToKb(addedSelfSizes[i])})`);
146
- }
147
- for (let i = 0; i < deletedIds.length; i++) {
148
- lines.push(` - @${deletedIds[i]} (self_size: ${formatBytesToKb(deletedSelfSizes[i])})`);
153
+ static formatDiffTotals(totals) {
154
+ return `Total: ${formatDiffCounts(totals)}`;
155
+ }
156
+ static formatDetailedClassDiffHeader(diff, options) {
157
+ return `${formatName(diff.className, options)}: ${formatDiffCounts(diff)}`;
158
+ }
159
+ static formatDetailedClassDiffObjects(objects) {
160
+ const lines = ['Objects:'];
161
+ for (const object of objects) {
162
+ const sign = object.change === 'added' ? '+' : '-';
163
+ lines.push(` ${sign} @${object.id} (self_size: ${formatBytesToKb(object.selfSize)})`);
149
164
  }
150
165
  return lines.join('\n');
151
166
  }
152
- static formatObjectInfo(info) {
167
+ static formatObjectInfo(info, options) {
153
168
  const lines = [
154
169
  `id: @${info.id}`,
155
- `name: ${info.name}`,
170
+ `name: ${formatName(info.name, options)}`,
156
171
  `type: ${info.type}`,
157
172
  `detachedness: ${formatDOMLinkState(info.detachedness)}`,
158
173
  `selfSize: ${formatBytesToKb(info.selfSize)}`,
@@ -163,6 +178,42 @@ export class HeapSnapshotFormatter {
163
178
  ];
164
179
  return lines.join('\n');
165
180
  }
181
+ static formatContextAnalysis(report, options) {
182
+ const lines = [];
183
+ if (report.contexts.length === 0) {
184
+ lines.push('No live contexts with dead fields were found.');
185
+ }
186
+ for (const { scope, context } of report.contexts) {
187
+ if (lines.length > 0) {
188
+ lines.push('');
189
+ }
190
+ lines.push(`#### Context @${context.contextNodeId} in \`${formatScopeName(scope, options)}\` — ${formatBytesToKb(context.deadFieldsRetainedSizeSum)}`, `Script @${scope.scriptNodeId}, ScopeInfo @${scope.scopeInfoNodeId}, offsets ${scope.scopeStart}-${scope.scopeEnd}, ${formatCount(scope.contextFieldCount, 'context field')}`);
191
+ for (const field of context.deadFields) {
192
+ lines.push(`- \`${formatName(field.name, options)}\` (${formatName(field.valueName, options)} @${field.valueNodeId}) — ${formatBytesToKb(field.retainedSize)}`);
193
+ }
194
+ }
195
+ if (report.scriptsWithoutScopes.length > 0) {
196
+ lines.push('', 'Scripts without scope metadata could not be analyzed:');
197
+ for (const script of report.scriptsWithoutScopes) {
198
+ const scriptName = script.scriptName
199
+ ? formatName(script.scriptName, options)
200
+ : `script @${script.scriptNodeId}`;
201
+ lines.push(`- \`${scriptName}\` (@${script.scriptNodeId}) — ${formatCount(script.contextCount, 'context')}`);
202
+ }
203
+ }
204
+ return lines.join('\n');
205
+ }
206
+ }
207
+ function formatCount(count, singular) {
208
+ return `${count} ${singular}${count === 1 ? '' : 's'}`;
209
+ }
210
+ function formatScopeName(scope, options) {
211
+ const scriptName = scope.scriptName
212
+ ? formatName(scope.scriptName, options)
213
+ : `script @${scope.scriptNodeId}`;
214
+ return scope.scopeName
215
+ ? `${formatName(scope.scopeName, options)} (${scriptName})`
216
+ : scriptName;
166
217
  }
167
218
  function formatDOMLinkState(state) {
168
219
  switch (state) {
@@ -182,4 +233,7 @@ function formatSignedSize(bytes) {
182
233
  const formatted = formatBytesToKb(bytes);
183
234
  return bytes > 0 ? `+${formatted}` : formatted;
184
235
  }
236
+ function formatDiffCounts(counts) {
237
+ return `# new: ${counts.addedCount}, # deleted: ${counts.removedCount}, # delta: ${formatSignedCount(counts.countDelta)}, alloc size: ${formatSignedSize(counts.addedSize)}, freed size: ${formatSignedSize(counts.removedSize)}, size delta: ${formatSignedSize(counts.sizeDelta)}`;
238
+ }
185
239
  //# sourceMappingURL=HeapSnapshotFormatter.js.map