chrome-devtools-mcp 1.8.0 → 1.10.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 (72) hide show
  1. package/README.md +20 -908
  2. package/build/src/BrowserManager.js +401 -0
  3. package/build/src/McpContext.js +43 -26
  4. package/build/src/McpPage.js +112 -4
  5. package/build/src/McpResponse.js +68 -3
  6. package/build/src/ToolHandler.js +184 -160
  7. package/build/src/bin/chrome-devtools-mcp-main.js +12 -7
  8. package/build/src/bin/chrome-devtools.js +6 -12
  9. package/build/src/collectors/PageCollector.js +66 -3
  10. package/build/src/config/browser-options.js +125 -0
  11. package/build/src/config/category-options.js +89 -0
  12. package/build/src/config/cli-commands.js +26 -0
  13. package/build/src/config/cli-options.js +34 -2
  14. package/build/src/config/mcp-options.js +86 -147
  15. package/build/src/daemon/utils.js +6 -0
  16. package/build/src/devtools/DevToolsCommentBridge.js +91 -0
  17. package/build/src/devtools/DevtoolsUtils.js +27 -21
  18. package/build/src/formatters/CommentFormatter.js +82 -0
  19. package/build/src/formatters/CssFormatter.js +812 -0
  20. package/build/src/formatters/NetworkFormatter.js +5 -2
  21. package/build/src/index.js +175 -128
  22. package/build/src/processors/ChunkedTraceParser.js +361 -0
  23. package/build/src/processors/PerformanceTrace.js +60 -13
  24. package/build/src/telemetry/ClearcutLogger.js +95 -37
  25. package/build/src/telemetry/metricsRegistry.js +3 -0
  26. package/build/src/telemetry/persistence.js +17 -7
  27. package/build/src/telemetry/transformation.js +53 -4
  28. package/build/src/telemetry/types.js +1 -0
  29. package/build/src/third_party/THIRD_PARTY_NOTICES +687 -133
  30. package/build/src/third_party/bundled-packages.json +6 -3
  31. package/build/src/third_party/devtools-formatter-worker.js +158 -5
  32. package/build/src/third_party/devtools-heap-snapshot-worker.js +589 -6
  33. package/build/src/third_party/index.js +59173 -38013
  34. package/build/src/third_party/issue-descriptions/webInstallManifestMissingId.md +3 -0
  35. package/build/src/third_party/issue-descriptions/webInstallManifestMissingNameOrShortName.md +3 -0
  36. package/build/src/third_party/issue-descriptions/webInstallManifestParsingOrNetworkError.md +3 -0
  37. package/build/src/third_party/issue-descriptions/webInstallNoManifest.md +3 -0
  38. package/build/src/third_party/issue-descriptions/webInstallStartUrlInvalid.md +3 -0
  39. package/build/src/tools/ToolDefinition.js +28 -21
  40. package/build/src/tools/categories.js +0 -6
  41. package/build/src/tools/comments.js +169 -0
  42. package/build/src/tools/console.js +3 -3
  43. package/build/src/tools/css.js +45 -0
  44. package/build/src/tools/emulation.js +5 -5
  45. package/build/src/tools/extensions.js +10 -10
  46. package/build/src/tools/input.js +159 -87
  47. package/build/src/tools/lighthouse.js +18 -7
  48. package/build/src/tools/memory.js +26 -26
  49. package/build/src/tools/network.js +5 -5
  50. package/build/src/tools/pages.js +34 -19
  51. package/build/src/tools/performance.js +7 -6
  52. package/build/src/tools/pwa.js +8 -8
  53. package/build/src/tools/screencast.js +5 -4
  54. package/build/src/tools/screenshot.js +2 -2
  55. package/build/src/tools/script.js +8 -7
  56. package/build/src/tools/slim/tools.js +45 -37
  57. package/build/src/tools/snapshot.js +4 -4
  58. package/build/src/tools/thirdPartyDeveloper.js +4 -4
  59. package/build/src/tools/tools.js +6 -9
  60. package/build/src/tools/webmcp.js +4 -4
  61. package/build/src/types.js +4 -1
  62. package/build/src/utils/WaitForHelper.js +26 -9
  63. package/build/src/utils/logger.js +7 -6
  64. package/build/src/utils/url.js +73 -0
  65. package/build/src/version.js +1 -1
  66. package/package.json +9 -6
  67. package/skills/chrome-devtools/SKILL.md +2 -1
  68. package/skills/chrome-devtools-cli/SKILL.md +3 -7
  69. package/skills/cookie-debugging/SKILL.md +149 -0
  70. package/skills/memory-leak-debugging/SKILL.md +4 -0
  71. package/build/src/browser.js +0 -244
  72. package/build/src/third_party/issue-descriptions/cookieExcludeBlockedWithinRelatedWebsiteSet.md +0 -4
@@ -3,68 +3,89 @@
3
3
  * Copyright 2026 Google LLC
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
+ var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
7
+ if (value !== null && value !== void 0) {
8
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
9
+ var dispose, inner;
10
+ if (async) {
11
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
12
+ dispose = value[Symbol.asyncDispose];
13
+ }
14
+ if (dispose === void 0) {
15
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
16
+ dispose = value[Symbol.dispose];
17
+ if (async) inner = dispose;
18
+ }
19
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
20
+ if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
21
+ env.stack.push({ value: value, dispose: dispose, async: async });
22
+ }
23
+ else if (async) {
24
+ env.stack.push({ async: true });
25
+ }
26
+ return value;
27
+ };
28
+ var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
29
+ return function (env) {
30
+ function fail(e) {
31
+ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
32
+ env.hasError = true;
33
+ }
34
+ var r, s = 0;
35
+ function next() {
36
+ while (r = env.stack.pop()) {
37
+ try {
38
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
39
+ if (r.dispose) {
40
+ var result = r.dispose.call(r.value);
41
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
42
+ }
43
+ else s |= 1;
44
+ }
45
+ catch (e) {
46
+ fail(e);
47
+ }
48
+ }
49
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
50
+ if (env.hasError) throw env.error;
51
+ }
52
+ return next();
53
+ };
54
+ })(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
55
+ var e = new Error(message);
56
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
57
+ });
6
58
  import { McpResponse } from './McpResponse.js';
7
59
  import { SlimMcpResponse } from './SlimMcpResponse.js';
8
60
  import { ClearcutLogger } from './telemetry/ClearcutLogger.js';
9
- import { bucketizeLatency, buildContext } from './telemetry/transformation.js';
10
61
  import { zod } from './third_party/index.js';
11
- import { labels, OFF_BY_DEFAULT_CATEGORIES } from './tools/categories.js';
12
- import { pageIdSchema } from './tools/ToolDefinition.js';
62
+ import { labels } from './tools/categories.js';
63
+ import { categoryToFlagName } from './config/category-options.js';
13
64
  import { logger } from './utils/logger.js';
14
65
  import { fileURLToPath, pathToFileURL } from 'node:url';
15
66
  import { isLocalhost } from './utils/url.js';
16
- export function buildFlag(category) {
17
- return `category${category.charAt(0).toUpperCase() + category.slice(1)}`;
18
- }
19
67
  function buildDisabledMessage(toolName, flag, categoryLabel) {
20
68
  const reason = categoryLabel
21
69
  ? `is in category ${categoryLabel} which`
22
- : `requires experimental feature ${flag} and`;
70
+ : `requires ${flag.startsWith('--experimental') ? 'experimental feature' : 'flag'} ${flag} and`;
23
71
  return `Tool ${toolName} ${reason} is currently disabled. Enable it by running chrome-devtools start ${flag}=true. For more information check the README.`;
24
72
  }
25
- function getCategoryStatus(category, serverArgs) {
26
- const categoryFlag = buildFlag(category);
27
- const flagValue = serverArgs[categoryFlag];
28
- const isDisabled = OFF_BY_DEFAULT_CATEGORIES.includes(category)
29
- ? !flagValue
30
- : flagValue === false;
31
- if (isDisabled) {
32
- return {
33
- categoryFlag,
34
- disabled: true,
35
- };
36
- }
37
- return {
38
- disabled: false,
39
- };
40
- }
41
- function getConditionStatus(condition, serverArgs) {
42
- if (condition && !serverArgs[condition]) {
43
- return { conditionFlag: condition, disabled: true };
44
- }
45
- return { disabled: false };
46
- }
47
73
  function getToolStatusInfo(tool, serverArgs) {
48
74
  const category = tool.annotations.category;
49
- const categoryCheck = getCategoryStatus(category, serverArgs);
50
- if (category && categoryCheck.disabled) {
51
- if (!categoryCheck.categoryFlag) {
52
- throw new Error('when the category is disabled there should always be a flag set');
75
+ if (category) {
76
+ const flag = categoryToFlagName(category);
77
+ if (!serverArgs[flag]) {
78
+ return {
79
+ disabled: true,
80
+ reason: buildDisabledMessage(tool.name, `--${flag}`, labels[category]),
81
+ };
53
82
  }
54
- return {
55
- disabled: true,
56
- reason: buildDisabledMessage(tool.name, `--${categoryCheck.categoryFlag}`, labels[category]),
57
- };
58
83
  }
59
84
  for (const condition of tool.annotations.conditions || []) {
60
- const conditionCheck = getConditionStatus(condition, serverArgs);
61
- if (conditionCheck.disabled) {
62
- if (!conditionCheck.conditionFlag) {
63
- throw new Error('when the condition is disabled there should always be a flag set');
64
- }
85
+ if (!serverArgs[condition]) {
65
86
  return {
66
87
  disabled: true,
67
- reason: buildDisabledMessage(tool.name, `--${conditionCheck.conditionFlag}`),
88
+ reason: buildDisabledMessage(tool.name, `--${condition}`),
68
89
  };
69
90
  }
70
91
  }
@@ -151,7 +172,7 @@ export class ToolHandler {
151
172
  toolMutex;
152
173
  inputSchema;
153
174
  registeredInputSchema;
154
- shouldRegister;
175
+ disabled;
155
176
  disabledReason;
156
177
  constructor(tool, serverArgs, getContext, toolMutex) {
157
178
  this.tool = tool;
@@ -160,139 +181,142 @@ export class ToolHandler {
160
181
  this.toolMutex = toolMutex;
161
182
  const { disabled, reason } = getToolStatusInfo(tool, serverArgs);
162
183
  this.disabledReason = reason;
163
- this.shouldRegister = !(disabled && !serverArgs.viaCli);
164
- this.inputSchema =
165
- 'pageScoped' in tool &&
166
- tool.pageScoped &&
167
- serverArgs.pageIdRouting &&
168
- !serverArgs.slim
169
- ? { ...pageIdSchema, ...tool.schema }
170
- : tool.schema;
171
- this.registeredInputSchema = zod.object(this.inputSchema).passthrough();
184
+ this.disabled = disabled && !serverArgs.viaCli;
185
+ this.inputSchema = tool.schema;
186
+ this.registeredInputSchema = zod.object(this.inputSchema).loose();
172
187
  }
173
188
  unknownArgumentNames(params) {
174
189
  return Object.keys(params).filter(key => !Object.hasOwn(this.inputSchema, key));
175
190
  }
176
- async handle(params) {
177
- if (this.disabledReason) {
178
- return {
179
- content: [
180
- {
181
- type: 'text',
182
- text: this.disabledReason,
183
- },
184
- ],
185
- isError: true,
186
- };
187
- }
188
- const unknownArgumentNames = this.unknownArgumentNames(params);
189
- if (unknownArgumentNames.length) {
190
- return {
191
- content: [
192
- {
193
- type: 'text',
194
- text: buildUnknownArgumentsMessage(this.tool.name, unknownArgumentNames, Object.keys(this.inputSchema)),
195
- },
196
- ],
197
- isError: true,
198
- };
199
- }
200
- const guard = await this.toolMutex.acquire();
201
- const startTime = Date.now();
202
- let success = false;
203
- let devToolsData;
204
- let pageUrl;
191
+ handle = async (params) => {
192
+ const env_1 = { stack: [], error: void 0, hasError: false };
205
193
  try {
206
- logger?.(`${this.tool.name} request: ${JSON.stringify(params, null, ' ')}`);
207
- const context = await this.getContext();
208
- logger?.(`${this.tool.name} context: resolved`);
209
- const response = this.serverArgs.slim
210
- ? new SlimMcpResponse(this.serverArgs)
211
- : new McpResponse(this.serverArgs);
212
- response.setRedactNetworkHeaders(this.serverArgs.redactNetworkHeaders);
213
- if (context.consumeReconnectNotice()) {
214
- response.setReconnectNotice();
194
+ const _guard = __addDisposableResource(env_1, await this.toolMutex.acquire(), false);
195
+ if (this.disabledReason) {
196
+ return {
197
+ content: [
198
+ {
199
+ type: 'text',
200
+ text: this.disabledReason,
201
+ },
202
+ ],
203
+ isError: true,
204
+ };
205
+ }
206
+ const unknownArgumentNames = this.unknownArgumentNames(params);
207
+ if (unknownArgumentNames.length) {
208
+ return {
209
+ content: [
210
+ {
211
+ type: 'text',
212
+ text: buildUnknownArgumentsMessage(this.tool.name, unknownArgumentNames, Object.keys(this.inputSchema)),
213
+ },
214
+ ],
215
+ isError: true,
216
+ };
215
217
  }
216
- let page;
218
+ const startTime = Date.now();
219
+ let success = false;
220
+ let devToolsData;
221
+ let pageUrl;
217
222
  try {
218
- await validateToolFiles(this.tool, params, context);
219
- if (isPageScopedTool(this.tool)) {
220
- const pageId = typeof params.pageId === 'number' ? params.pageId : undefined;
221
- page =
222
- this.serverArgs.pageIdRouting &&
223
- pageId !== undefined &&
224
- !this.serverArgs.slim
225
- ? context.getPageById(pageId)
226
- : context.getSelectedMcpPage();
227
- response.setPage(page);
228
- if (this.tool.blockedByDialog) {
229
- page.throwIfDialogOpen();
223
+ logger?.(`${this.tool.name} request: ${JSON.stringify(params, null, ' ')}`);
224
+ const context = await this.getContext();
225
+ logger?.(`${this.tool.name} context: resolved`);
226
+ const response = this.serverArgs.slim
227
+ ? new SlimMcpResponse(this.serverArgs)
228
+ : new McpResponse(this.serverArgs);
229
+ response.setRedactNetworkHeaders(this.serverArgs.redactNetworkHeaders);
230
+ if (context.consumeReconnectNotice()) {
231
+ response.setReconnectNotice();
232
+ }
233
+ let page;
234
+ try {
235
+ await validateToolFiles(this.tool, params, context);
236
+ if (isPageScopedTool(this.tool)) {
237
+ const pageId = typeof params.pageId === 'number' ? params.pageId : undefined;
238
+ page =
239
+ this.serverArgs.pageIdRouting &&
240
+ pageId !== undefined &&
241
+ !this.serverArgs.slim
242
+ ? context.getPageById(pageId)
243
+ : context.getSelectedMcpPage();
244
+ response.setPage(page);
245
+ if (this.tool.blockedByDialog) {
246
+ page.throwIfDialogOpen();
247
+ }
248
+ await this.tool.handler({
249
+ params,
250
+ page,
251
+ }, response, context);
252
+ }
253
+ else {
254
+ await this.tool.handler({
255
+ params,
256
+ }, response, context);
230
257
  }
231
- await this.tool.handler({
232
- params,
233
- page,
234
- }, response, context);
235
258
  }
236
- else {
237
- await this.tool.handler({
238
- params,
239
- }, response, context);
259
+ catch (err) {
260
+ response.setError(err);
261
+ }
262
+ devToolsData = await context.getDevToolsData(page);
263
+ pageUrl = context.getSelectedMcpPageUrl(page);
264
+ // Resolve data format: --experimentalDataFormat takes precedence, fall back to legacy --experimentalToonFormat
265
+ let dataFormat = 'default';
266
+ if (this.serverArgs.experimentalDataFormat) {
267
+ dataFormat = this.serverArgs.experimentalDataFormat;
268
+ }
269
+ else if (this.serverArgs.experimentalToonFormat) {
270
+ dataFormat = 'toon';
271
+ }
272
+ const { content, structuredContent } = await response.handle(context, dataFormat);
273
+ const result = {
274
+ content,
275
+ };
276
+ if (response.error) {
277
+ result.isError = true;
240
278
  }
279
+ success = true;
280
+ if (this.serverArgs.experimentalStructuredContent) {
281
+ result.structuredContent = structuredContent;
282
+ }
283
+ return result;
241
284
  }
242
285
  catch (err) {
243
- response.setError(err);
244
- }
245
- devToolsData = await context.getDevToolsData(page);
246
- pageUrl = context.getSelectedMcpPageUrl(page);
247
- // Resolve data format: --experimentalDataFormat takes precedence, fall back to legacy --experimentalToonFormat
248
- let dataFormat = 'default';
249
- if (this.serverArgs.experimentalDataFormat) {
250
- dataFormat = this.serverArgs.experimentalDataFormat;
251
- }
252
- else if (this.serverArgs.experimentalToonFormat) {
253
- dataFormat = 'toon';
254
- }
255
- const { content, structuredContent } = await response.handle(context, dataFormat);
256
- const result = {
257
- content,
258
- };
259
- if (response.error) {
260
- result.isError = true;
286
+ logger?.(`${this.tool.name} error:`, err, err?.stack);
287
+ let errorText = err && 'message' in err ? err.message : String(err);
288
+ if ('cause' in err && err.cause) {
289
+ errorText += `\nCause: ${err.cause.message}`;
290
+ }
291
+ return {
292
+ content: [
293
+ {
294
+ type: 'text',
295
+ text: errorText,
296
+ },
297
+ ],
298
+ isError: true,
299
+ };
261
300
  }
262
- success = true;
263
- if (this.serverArgs.experimentalStructuredContent) {
264
- result.structuredContent = structuredContent;
301
+ finally {
302
+ void ClearcutLogger.get()?.logToolInvocation({
303
+ toolName: this.tool.name,
304
+ params,
305
+ schema: this.inputSchema,
306
+ success,
307
+ latencyMs: Date.now() - startTime,
308
+ devToolsData,
309
+ pageUrl,
310
+ });
265
311
  }
266
- return result;
267
312
  }
268
- catch (err) {
269
- logger?.(`${this.tool.name} error:`, err, err?.stack);
270
- let errorText = err && 'message' in err ? err.message : String(err);
271
- if ('cause' in err && err.cause) {
272
- errorText += `\nCause: ${err.cause.message}`;
273
- }
274
- return {
275
- content: [
276
- {
277
- type: 'text',
278
- text: errorText,
279
- },
280
- ],
281
- isError: true,
282
- };
313
+ catch (e_1) {
314
+ env_1.error = e_1;
315
+ env_1.hasError = true;
283
316
  }
284
317
  finally {
285
- const context = buildContext(devToolsData, pageUrl);
286
- void ClearcutLogger.get()?.logToolInvocation({
287
- toolName: this.tool.name,
288
- params,
289
- schema: this.inputSchema,
290
- success,
291
- latencyMs: bucketizeLatency(Date.now() - startTime),
292
- context,
293
- });
294
- guard[Symbol.dispose]();
318
+ __disposeResources(env_1);
295
319
  }
296
- }
320
+ };
297
321
  }
298
322
  //# sourceMappingURL=ToolHandler.js.map
@@ -5,8 +5,8 @@
5
5
  */
6
6
  import '../utils/polyfill.js';
7
7
  import process from 'node:process';
8
- import { closeBrowser } from '../browser.js';
9
- import { createMcpServer, logDisclaimers } from '../index.js';
8
+ import { BrowserManager } from '../BrowserManager.js';
9
+ import { McpServer, logDisclaimers } from '../index.js';
10
10
  import { ClearcutLogger } from '../telemetry/ClearcutLogger.js';
11
11
  import { computeFlagUsage } from '../telemetry/flagUtils.js';
12
12
  import { StdioServerTransport } from '../third_party/index.js';
@@ -22,6 +22,13 @@ if (process.env['CHROME_DEVTOOLS_MCP_CRASH_ON_UNCAUGHT'] !== 'true') {
22
22
  logger?.('Unhandled promise rejection', promise, reason);
23
23
  });
24
24
  }
25
+ logger?.(`Starting Chrome DevTools MCP Server v${VERSION}`);
26
+ const browserManager = new BrowserManager(args, {
27
+ logFile,
28
+ });
29
+ const serverPromise = McpServer.from(args, {
30
+ browserManager,
31
+ });
25
32
  // Shutdown on stdin EOF (stdio MCP convention — the client closes the
26
33
  // transport to signal exit) and on standard termination signals. Without
27
34
  // this, an active Chrome subprocess keeps the Node event loop ref'd after
@@ -41,7 +48,8 @@ async function shutdown(reason) {
41
48
  logger?.('Shutdown timeout exceeded, forcing exit');
42
49
  process.exit(0);
43
50
  }, 5000).unref();
44
- await closeBrowser();
51
+ const server = await serverPromise;
52
+ await server.close();
45
53
  process.exit(0);
46
54
  }
47
55
  process.stdin.on('end', () => {
@@ -59,10 +67,7 @@ process.on('SIGINT', () => {
59
67
  process.on('SIGHUP', () => {
60
68
  void shutdown('SIGHUP');
61
69
  });
62
- logger?.(`Starting Chrome DevTools MCP Server v${VERSION}`);
63
- const { server } = await createMcpServer(args, {
64
- logFile,
65
- });
70
+ const server = await serverPromise;
66
71
  const transport = new StdioServerTransport();
67
72
  await server.connect(transport);
68
73
  logger?.('Chrome DevTools MCP Server connected');
@@ -12,6 +12,7 @@ import { logDisclaimers } from '../index.js';
12
12
  import { hideBin, yargs } from '../third_party/index.js';
13
13
  import { checkForUpdates } from '../utils/check-for-updates.js';
14
14
  import { VERSION } from '../version.js';
15
+ import { buildCommand } from '../config/cli-commands.js';
15
16
  import { commands } from '../config/cli-options.js';
16
17
  import { mcpOptions, parseArguments, getMcpOptionsForViaCli, } from '../config/mcp-options.js';
17
18
  await checkForUpdates('Run `npm install -g chrome-devtools-mcp@latest` and `chrome-devtools start` to update and restart the daemon.');
@@ -41,7 +42,7 @@ const y = yargs(hideBin(process.argv))
41
42
  .option('sessionId', {
42
43
  type: 'string',
43
44
  description: 'Session ID for daemon scoping',
44
- default: '',
45
+ default: process.env.CD4A_INTERNAL_DAEMON_SESSION_ID || '',
45
46
  hidden: true,
46
47
  coerce: (sessionId) => {
47
48
  assertValidSessionId(sessionId);
@@ -97,7 +98,7 @@ y.command('start', 'Start or restart chrome-devtools-mcp', y => y
97
98
  !argv.wsEndpoint) {
98
99
  argv.headless = true;
99
100
  }
100
- const args = serializeArgs(mcpOptions, argv);
101
+ const args = serializeArgs(getCliOptions(), argv);
101
102
  await start(args, argv.sessionId);
102
103
  process.exit(0);
103
104
  }).strict(); // Re-enable strict validation for other commands; this is applied to the yargs instance itself
@@ -135,16 +136,9 @@ y.command('stop', 'Stop chrome-devtools-mcp if any', y => y, async (argv) => {
135
136
  });
136
137
  for (const [commandName, commandDef] of Object.entries(commands)) {
137
138
  const args = commandDef.args;
138
- const requiredArgNames = Object.keys(args).filter(name => args[name].required);
139
- const optionalArgNames = Object.keys(args).filter(name => !args[name].required);
140
- let commandStr = commandName;
141
- for (const arg of requiredArgNames) {
142
- commandStr += ` <${arg}>`;
143
- }
144
- for (const arg of optionalArgNames) {
145
- commandStr += ` [--${arg}]`;
146
- }
147
- y.command(commandStr, commandDef.description, y => {
139
+ const { command, usage } = buildCommand(commandName, args);
140
+ y.command(command, commandDef.description, y => {
141
+ y.usage(usage);
148
142
  y.option('output-format', {
149
143
  choices: ['md', 'json'],
150
144
  default: 'md',
@@ -4,7 +4,7 @@
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
6
  import { FakeIssuesManager } from '../devtools/DevtoolsUtils.js';
7
- import { DevTools } from '../third_party/index.js';
7
+ import { DevTools, FrameEvent } from '../third_party/index.js';
8
8
  import { createIdGenerator, stableIdSymbol, } from '../utils/id.js';
9
9
  import { logger } from '../utils/logger.js';
10
10
  export class UncaughtError {
@@ -18,6 +18,8 @@ export class UncaughtError {
18
18
  export class PageCollector {
19
19
  pptrPage;
20
20
  #listeners;
21
+ #pendingSameDocumentNavigation = false;
22
+ #frameNavigatedWithinDocumentTarget;
21
23
  maxNavigationSaved = 3;
22
24
  /**
23
25
  * This maps a Page to a list of navigations with a sub-list
@@ -27,6 +29,7 @@ export class PageCollector {
27
29
  storage = [[]];
28
30
  constructor(page, listeners, maxResourcesPerNavigation) {
29
31
  this.pptrPage = page;
32
+ this.#attachFrameNavigatedWithinDocumentListener();
30
33
  const idGenerator = createIdGenerator();
31
34
  const listenerMap = listeners(value => {
32
35
  const withId = value;
@@ -42,6 +45,18 @@ export class PageCollector {
42
45
  if (frame !== this.pptrPage.mainFrame()) {
43
46
  return;
44
47
  }
48
+ // Re-attach the listener to the current main frame: a cross-document
49
+ // navigation may have replaced the frame object, so the reference
50
+ // captured at construction time would be stale.
51
+ this.#attachFrameNavigatedWithinDocumentListener();
52
+ // Same-document (SPA) navigations also emit `framenavigated`, but they
53
+ // must not rotate the retained history. Puppeteer emits
54
+ // `FrameNavigatedWithinDocument` right before `FrameNavigated` for such
55
+ // navigations, so consume the flag here to skip the split.
56
+ if (this.#pendingSameDocumentNavigation) {
57
+ this.#pendingSameDocumentNavigation = false;
58
+ return;
59
+ }
45
60
  this.splitAfterNavigation();
46
61
  };
47
62
  for (const [name, listener] of Object.entries(listenerMap)) {
@@ -50,12 +65,30 @@ export class PageCollector {
50
65
  this.#listeners = listenerMap;
51
66
  }
52
67
  dispose() {
68
+ this.#detachFrameNavigatedWithinDocumentListener();
53
69
  if (this.#listeners) {
54
70
  for (const [name, listener] of Object.entries(this.#listeners)) {
55
71
  this.pptrPage.off(name, listener);
56
72
  }
57
73
  }
58
74
  }
75
+ // Puppeteer emits this right before the page-level navigation event for
76
+ // same-document (SPA) navigations, which lets `framenavigated` skip the
77
+ // history rotation for those navigations.
78
+ #onFrameNavigatedWithinDocument = () => {
79
+ this.#pendingSameDocumentNavigation = true;
80
+ };
81
+ #attachFrameNavigatedWithinDocumentListener() {
82
+ this.#detachFrameNavigatedWithinDocumentListener();
83
+ this.#frameNavigatedWithinDocumentTarget = this.pptrPage.mainFrame();
84
+ this.#frameNavigatedWithinDocumentTarget.on(FrameEvent.FrameNavigatedWithinDocument, this.#onFrameNavigatedWithinDocument);
85
+ }
86
+ #detachFrameNavigatedWithinDocumentListener() {
87
+ if (this.#frameNavigatedWithinDocumentTarget) {
88
+ this.#frameNavigatedWithinDocumentTarget.off(FrameEvent.FrameNavigatedWithinDocument, this.#onFrameNavigatedWithinDocument);
89
+ this.#frameNavigatedWithinDocumentTarget = undefined;
90
+ }
91
+ }
59
92
  splitAfterNavigation() {
60
93
  // Add the latest navigation first
61
94
  this.storage.unshift([]);
@@ -94,9 +127,10 @@ export class PageCollector {
94
127
  }
95
128
  }
96
129
  export class ConsoleCollector extends PageCollector {
130
+ static MAX_MESSAGES_PER_NAVIGATION = 10_000;
97
131
  #subscriber;
98
- constructor(page, listeners) {
99
- super(page, listeners);
132
+ constructor(page, listeners, maxMessagesPerNavigation = ConsoleCollector.MAX_MESSAGES_PER_NAVIGATION) {
133
+ super(page, listeners, maxMessagesPerNavigation);
100
134
  this.#subscriber = new PageEventSubscriber(this.pptrPage);
101
135
  this.#subscriber.subscribe();
102
136
  }
@@ -113,6 +147,8 @@ class PageEventSubscriber {
113
147
  #page;
114
148
  #session;
115
149
  #targetId;
150
+ #pendingSameDocumentNavigation = false;
151
+ #frameNavigatedWithinDocumentTarget;
116
152
  constructor(page) {
117
153
  this.#page = page;
118
154
  // @ts-expect-error use existing CDP client (internal Puppeteer API).
@@ -133,10 +169,12 @@ class PageEventSubscriber {
133
169
  this.#page.on('framenavigated', this.#onFrameNavigated);
134
170
  this.#page.on('issue', this.#onIssueAdded);
135
171
  this.#session.on('Runtime.exceptionThrown', this.#onExceptionThrown);
172
+ this.#attachFrameNavigatedWithinDocumentListener();
136
173
  }
137
174
  unsubscribe() {
138
175
  this.#seenKeys.clear();
139
176
  this.#seenIssues.clear();
177
+ this.#detachFrameNavigatedWithinDocumentListener();
140
178
  this.#page.off('framenavigated', this.#onFrameNavigated);
141
179
  this.#page.off('issue', this.#onIssueAdded);
142
180
  this.#session.off('Runtime.exceptionThrown', this.#onExceptionThrown);
@@ -160,10 +198,35 @@ class PageEventSubscriber {
160
198
  if (frame !== frame.page().mainFrame()) {
161
199
  return;
162
200
  }
201
+ // Re-attach the listener to the current main frame: a cross-document
202
+ // navigation may have replaced the frame object, so the reference
203
+ // captured at construction time would be stale.
204
+ this.#attachFrameNavigatedWithinDocumentListener();
205
+ if (this.#pendingSameDocumentNavigation) {
206
+ this.#pendingSameDocumentNavigation = false;
207
+ return;
208
+ }
163
209
  this.#seenKeys.clear();
164
210
  this.#seenIssues.clear();
165
211
  this.#resetIssueAggregator();
166
212
  };
213
+ // Puppeteer emits this right before the page-level navigation event for
214
+ // same-document (SPA) navigations, which lets `framenavigated` skip the
215
+ // issue aggregation reset for those navigations.
216
+ #onFrameNavigatedWithinDocument = () => {
217
+ this.#pendingSameDocumentNavigation = true;
218
+ };
219
+ #attachFrameNavigatedWithinDocumentListener() {
220
+ this.#detachFrameNavigatedWithinDocumentListener();
221
+ this.#frameNavigatedWithinDocumentTarget = this.#page.mainFrame();
222
+ this.#frameNavigatedWithinDocumentTarget.on(FrameEvent.FrameNavigatedWithinDocument, this.#onFrameNavigatedWithinDocument);
223
+ }
224
+ #detachFrameNavigatedWithinDocumentListener() {
225
+ if (this.#frameNavigatedWithinDocumentTarget) {
226
+ this.#frameNavigatedWithinDocumentTarget.off(FrameEvent.FrameNavigatedWithinDocument, this.#onFrameNavigatedWithinDocument);
227
+ this.#frameNavigatedWithinDocumentTarget = undefined;
228
+ }
229
+ }
167
230
  #onIssueAdded = (inspectorIssue) => {
168
231
  try {
169
232
  // @ts-expect-error The types are missmatched but they