chrome-devtools-mcp 1.9.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 (64) hide show
  1. package/build/src/BrowserManager.js +401 -0
  2. package/build/src/McpContext.js +5 -5
  3. package/build/src/McpPage.js +107 -3
  4. package/build/src/McpResponse.js +68 -3
  5. package/build/src/ToolHandler.js +172 -118
  6. package/build/src/bin/chrome-devtools-mcp-main.js +11 -6
  7. package/build/src/bin/chrome-devtools.js +6 -12
  8. package/build/src/collectors/PageCollector.js +66 -3
  9. package/build/src/config/browser-options.js +2 -0
  10. package/build/src/config/category-options.js +13 -4
  11. package/build/src/config/cli-commands.js +26 -0
  12. package/build/src/config/cli-options.js +32 -0
  13. package/build/src/config/mcp-options.js +40 -1
  14. package/build/src/devtools/DevToolsCommentBridge.js +91 -0
  15. package/build/src/formatters/CommentFormatter.js +82 -0
  16. package/build/src/formatters/CssFormatter.js +812 -0
  17. package/build/src/index.js +53 -72
  18. package/build/src/processors/ChunkedTraceParser.js +361 -0
  19. package/build/src/processors/PerformanceTrace.js +60 -13
  20. package/build/src/telemetry/ClearcutLogger.js +91 -34
  21. package/build/src/telemetry/metricsRegistry.js +3 -0
  22. package/build/src/telemetry/persistence.js +17 -7
  23. package/build/src/telemetry/transformation.js +53 -4
  24. package/build/src/telemetry/types.js +1 -0
  25. package/build/src/third_party/THIRD_PARTY_NOTICES +685 -131
  26. package/build/src/third_party/bundled-packages.json +6 -3
  27. package/build/src/third_party/devtools-formatter-worker.js +136 -5
  28. package/build/src/third_party/devtools-heap-snapshot-worker.js +567 -6
  29. package/build/src/third_party/index.js +54945 -35497
  30. package/build/src/third_party/issue-descriptions/webInstallManifestMissingId.md +3 -0
  31. package/build/src/third_party/issue-descriptions/webInstallManifestMissingNameOrShortName.md +3 -0
  32. package/build/src/third_party/issue-descriptions/webInstallManifestParsingOrNetworkError.md +3 -0
  33. package/build/src/third_party/issue-descriptions/webInstallNoManifest.md +3 -0
  34. package/build/src/third_party/issue-descriptions/webInstallStartUrlInvalid.md +3 -0
  35. package/build/src/tools/ToolDefinition.js +13 -21
  36. package/build/src/tools/comments.js +169 -0
  37. package/build/src/tools/console.js +3 -3
  38. package/build/src/tools/css.js +45 -0
  39. package/build/src/tools/emulation.js +5 -5
  40. package/build/src/tools/extensions.js +10 -10
  41. package/build/src/tools/input.js +159 -87
  42. package/build/src/tools/lighthouse.js +18 -7
  43. package/build/src/tools/memory.js +26 -26
  44. package/build/src/tools/network.js +4 -4
  45. package/build/src/tools/pages.js +14 -14
  46. package/build/src/tools/performance.js +6 -6
  47. package/build/src/tools/pwa.js +8 -8
  48. package/build/src/tools/screencast.js +4 -4
  49. package/build/src/tools/screenshot.js +2 -2
  50. package/build/src/tools/script.js +7 -7
  51. package/build/src/tools/slim/tools.js +5 -5
  52. package/build/src/tools/snapshot.js +4 -4
  53. package/build/src/tools/thirdPartyDeveloper.js +4 -4
  54. package/build/src/tools/tools.js +6 -9
  55. package/build/src/tools/webmcp.js +4 -4
  56. package/build/src/types.js +4 -1
  57. package/build/src/utils/WaitForHelper.js +14 -8
  58. package/build/src/utils/logger.js +7 -6
  59. package/build/src/version.js +1 -1
  60. package/package.json +8 -5
  61. package/skills/chrome-devtools/SKILL.md +2 -1
  62. package/skills/chrome-devtools-cli/SKILL.md +2 -0
  63. package/build/src/browser.js +0 -233
  64. package/build/src/third_party/issue-descriptions/cookieExcludeBlockedWithinRelatedWebsiteSet.md +0 -4
@@ -1,3 +1,5 @@
1
+ import * as Fs from 'node:fs';
2
+ import * as Url from 'node:url';
1
3
  import * as WorkerThreads from 'node:worker_threads';
2
4
 
3
5
  // Copyright 2020 The Chromium Authors
@@ -120,6 +122,55 @@ class WebWorker {
120
122
  });
121
123
  }
122
124
  }
125
+ let lastScreenshotBlobUrl = null;
126
+ function revokeLastScreenshotUrl() {
127
+ if (lastScreenshotBlobUrl) {
128
+ URL.revokeObjectURL(lastScreenshotBlobUrl);
129
+ lastScreenshotBlobUrl = null;
130
+ }
131
+ }
132
+ async function saveScreenshot(options) {
133
+ const pageImage = new Image();
134
+ await new Promise((resolve, reject) => {
135
+ pageImage.onload = () => resolve();
136
+ pageImage.onerror = () => reject(new Error('Failed to load image for screenshot'));
137
+ pageImage.src = 'data:image/png;base64,' + options.base64Png;
138
+ });
139
+ let canvas;
140
+ if (options.clip) {
141
+ const scale = pageImage.naturalWidth / options.clip.screenRectWidth;
142
+ const screenRectWidth = options.clip.screenRectWidth * scale;
143
+ const screenRectHeight = options.clip.screenRectHeight * scale;
144
+ const contentLeft = options.clip.visiblePageRectLeft * scale;
145
+ const contentTop = options.clip.visiblePageRectTop * scale;
146
+ canvas = new OffscreenCanvas(Math.floor(screenRectWidth),
147
+ Math.min(1 << 14, Math.floor(screenRectHeight)));
148
+ const ctx = canvas.getContext('2d', { willReadFrequently: true });
149
+ if (!ctx) {
150
+ throw new Error('Could not get 2d context from canvas.');
151
+ }
152
+ ctx.imageSmoothingEnabled = false;
153
+ ctx.drawImage(pageImage, Math.floor(contentLeft), Math.floor(contentTop));
154
+ }
155
+ else {
156
+ canvas = new OffscreenCanvas(pageImage.naturalWidth, Math.min(1 << 14, Math.floor(pageImage.naturalHeight)));
157
+ const ctx = canvas.getContext('2d', { willReadFrequently: true });
158
+ if (!ctx) {
159
+ throw new Error('Could not get 2d context for base64 screenshot.');
160
+ }
161
+ ctx.imageSmoothingEnabled = false;
162
+ ctx.drawImage(pageImage, 0, 0);
163
+ }
164
+ revokeLastScreenshotUrl();
165
+ const link = document.createElement('a');
166
+ link.download = options.fileName + '.png';
167
+ const blob = await canvas.convertToBlob({ type: 'image/png' });
168
+ const blobUrl = URL.createObjectURL(blob);
169
+ lastScreenshotBlobUrl = blobUrl;
170
+ link.href = blobUrl;
171
+ link.click();
172
+ }
173
+ let cssEvaluationElement = null;
123
174
  const HOST_RUNTIME$2 = {
124
175
  createWorker(url) {
125
176
  return new WebWorker(url);
@@ -134,6 +185,44 @@ const HOST_RUNTIME$2 = {
134
185
  getLocalStorage() {
135
186
  return 'localStorage' in globalThis ? globalThis.localStorage : undefined;
136
187
  },
188
+ getCacheStorage() {
189
+ return 'caches' in globalThis ? globalThis.caches : undefined;
190
+ },
191
+ getDevicePixelRatio() {
192
+ return window.devicePixelRatio;
193
+ },
194
+ saveScreenshot,
195
+ revokeLastScreenshotUrl,
196
+ async loadTextFile(url) {
197
+ const response = await fetch(url);
198
+ return await response.text();
199
+ },
200
+ evaluateCSS(dataValue, customExpr) {
201
+ if (!cssEvaluationElement || !cssEvaluationElement.isConnected) {
202
+ cssEvaluationElement = document.getElementById('css-evaluation-element');
203
+ if (!cssEvaluationElement) {
204
+ cssEvaluationElement = document.createElement('div');
205
+ cssEvaluationElement.id = 'css-evaluation-element';
206
+ cssEvaluationElement.setAttribute('style', 'hidden: true; --evaluation: attr(data-custom-expr type(*))');
207
+ document.body.appendChild(cssEvaluationElement);
208
+ }
209
+ }
210
+ if (dataValue !== null) {
211
+ cssEvaluationElement.setAttribute('data-value', dataValue);
212
+ }
213
+ else {
214
+ cssEvaluationElement.removeAttribute('data-value');
215
+ }
216
+ cssEvaluationElement.setAttribute('data-custom-expr', customExpr);
217
+ return cssEvaluationElement.computedStyleMap().get('--evaluation')?.toString() ?? null;
218
+ },
219
+ removeCSSEvaluationElement() {
220
+ const element = cssEvaluationElement ?? document.getElementById('css-evaluation-element');
221
+ if (element) {
222
+ element.remove();
223
+ }
224
+ cssEvaluationElement = null;
225
+ },
137
226
  };
138
227
 
139
228
  var HostRuntime$1 = /*#__PURE__*/Object.freeze({
@@ -160,13 +249,15 @@ class NodeWorkerScope {
160
249
  }
161
250
  }
162
251
  class NodeWorker {
252
+ #worker;
163
253
  #workerPromise;
164
254
  #disposed = false;
165
255
  #rejectWorkerPromise;
166
256
  constructor(url) {
257
+ const worker = new WorkerThreads.Worker(new URL(url));
258
+ this.#worker = worker;
167
259
  this.#workerPromise = new Promise((resolve, reject) => {
168
260
  this.#rejectWorkerPromise = reject;
169
- const worker = new WorkerThreads.Worker(new URL(url));
170
261
  worker.once('message', (message) => {
171
262
  if (message === 'workerReady') {
172
263
  resolve(worker);
@@ -174,6 +265,7 @@ class NodeWorker {
174
265
  });
175
266
  worker.on('error', reject);
176
267
  });
268
+ this.#workerPromise.catch(() => { });
177
269
  }
178
270
  postMessage(message, transfer) {
179
271
  void this.#workerPromise.then(worker => {
@@ -184,7 +276,7 @@ class NodeWorker {
184
276
  }
185
277
  dispose() {
186
278
  this.#disposed = true;
187
- void this.#workerPromise.then(worker => worker.terminate());
279
+ void this.#worker.terminate();
188
280
  }
189
281
  terminate(immediately) {
190
282
  if (immediately) {
@@ -211,6 +303,30 @@ class NodeWorker {
211
303
  });
212
304
  }
213
305
  }
306
+ class NodeCacheEntry {
307
+ #entries = new Map();
308
+ async put(url, response) {
309
+ this.#entries.set(url, response.clone());
310
+ }
311
+ async match(url) {
312
+ return this.#entries.get(url)?.clone();
313
+ }
314
+ }
315
+ class NodeCacheStorage {
316
+ #caches = new Map();
317
+ async open(name) {
318
+ let cache = this.#caches.get(name);
319
+ if (!cache) {
320
+ cache = new NodeCacheEntry();
321
+ this.#caches.set(name, cache);
322
+ }
323
+ return cache;
324
+ }
325
+ async delete(name) {
326
+ return this.#caches.delete(name);
327
+ }
328
+ }
329
+ const nodeCacheStorage = new NodeCacheStorage();
214
330
  const HOST_RUNTIME$1 = {
215
331
  createWorker(url) {
216
332
  return new NodeWorker(url);
@@ -225,6 +341,21 @@ const HOST_RUNTIME$1 = {
225
341
  getLocalStorage() {
226
342
  return undefined;
227
343
  },
344
+ getCacheStorage() {
345
+ return nodeCacheStorage;
346
+ },
347
+ getDevicePixelRatio() {
348
+ return 1;
349
+ },
350
+ async saveScreenshot(_options) { },
351
+ revokeLastScreenshotUrl() { },
352
+ async loadTextFile(url) {
353
+ return await Fs.promises.readFile(Url.fileURLToPath(url), 'utf-8');
354
+ },
355
+ evaluateCSS(_dataValue, _customExpr) {
356
+ return null;
357
+ },
358
+ removeCSSEvaluationElement() { },
228
359
  };
229
360
 
230
361
  var HostRuntime = /*#__PURE__*/Object.freeze({
@@ -975,9 +1106,9 @@ class ColorConverter {
975
1106
  static xyzd65ToOklab(x, y, z) {
976
1107
  const xyzInput = new Vector3([x, y, z]);
977
1108
  const lmsIntermediate = XYZ_TO_LMS_MATRIX.multiply(xyzInput);
978
- lmsIntermediate.values[0] = Math.pow(lmsIntermediate.values[0], 1.0 / 3.0);
979
- lmsIntermediate.values[1] = Math.pow(lmsIntermediate.values[1], 1.0 / 3.0);
980
- lmsIntermediate.values[2] = Math.pow(lmsIntermediate.values[2], 1.0 / 3.0);
1109
+ lmsIntermediate.values[0] = Math.cbrt(lmsIntermediate.values[0]);
1110
+ lmsIntermediate.values[1] = Math.cbrt(lmsIntermediate.values[1]);
1111
+ lmsIntermediate.values[2] = Math.cbrt(lmsIntermediate.values[2]);
981
1112
  const labOutput = LMS_TO_OKLAB_MATRIX.multiply(lmsIntermediate);
982
1113
  return [labOutput.values[0], labOutput.values[1], labOutput.values[2]];
983
1114
  }
@@ -5904,6 +6035,9 @@ class HeapSnapshotProxy extends HeapSnapshotProxyObject {
5904
6035
  getObjectInfo(nodeIndex) {
5905
6036
  return this.callMethodPromise('getObjectInfo', nodeIndex);
5906
6037
  }
6038
+ analyzeContexts() {
6039
+ return this.callMethodPromise('analyzeContexts');
6040
+ }
5907
6041
  createEdgesProvider(nodeIndex, options) {
5908
6042
  return this.callFactoryMethod('createEdgesProvider', HeapSnapshotProviderProxy, nodeIndex, options);
5909
6043
  }
@@ -6283,6 +6417,418 @@ var AllocationProfile$1 = /*#__PURE__*/Object.freeze({
6283
6417
  TopDownAllocationNode: TopDownAllocationNode
6284
6418
  });
6285
6419
 
6420
+ // Copyright 2026 The Chromium Authors
6421
+ function analyzeContexts(snapshot) {
6422
+ const scopesByScript = parseEmbeddedScopes(snapshot);
6423
+ const scan = scanHeap(snapshot);
6424
+ const liveFunctionsByScript = buildLiveFunctions(snapshot, scan.liveClosures);
6425
+ const { scopes, scriptsWithoutScopes } = correlateContextsWithScopes(snapshot, scan, scopesByScript);
6426
+ const scopeAnalyses = classifyFields(snapshot, scopes, liveFunctionsByScript);
6427
+ return sortAndBuildResult(scopeAnalyses, scriptsWithoutScopes);
6428
+ }
6429
+ function parseEmbeddedScopes(snapshot) {
6430
+ const scopesByScript = new Map();
6431
+ const profile = snapshot.profile;
6432
+ const rawScopes = profile.scopes ?? [];
6433
+ const rawVars = profile.scope_context_vars ?? [];
6434
+ const rawUses = profile.scope_uses ?? [];
6435
+ const meta = profile.snapshot.meta;
6436
+ const scopeFields = meta.scope_fields ?? [];
6437
+ const varFields = meta.scope_context_var_fields ?? [];
6438
+ const useFields = meta.scope_use_fields ?? [];
6439
+ const scopeStride = scopeFields.length;
6440
+ const varStride = varFields.length;
6441
+ const useStride = useFields.length;
6442
+ if (scopeStride === 0) {
6443
+ return scopesByScript;
6444
+ }
6445
+ const scriptNodeIndexOffset = scopeFields.indexOf('script_node_index');
6446
+ const scopeIdOffset = scopeFields.indexOf('scope_id');
6447
+ const depthOffset = scopeFields.indexOf('depth');
6448
+ const varsCountOffset = scopeFields.indexOf('scope_context_vars_count');
6449
+ const usesCountOffset = scopeFields.indexOf('scope_uses_count');
6450
+ const varNameOffset = varFields.indexOf('name');
6451
+ const useDeclaringScopeIdOffset = useFields.indexOf('declaring_scope_id');
6452
+ const useSlotIndexOffset = useFields.indexOf('slot_index');
6453
+ const strings = snapshot.strings;
6454
+ let varOffset = 0;
6455
+ let currentScriptNodeIndex;
6456
+ const scopeStack = [];
6457
+ for (let i = 0; i < rawScopes.length; i += scopeStride) {
6458
+ const scriptNodeIndex = rawScopes[i + scriptNodeIndexOffset];
6459
+ const scopeId = rawScopes[i + scopeIdOffset];
6460
+ const depth = rawScopes[i + depthOffset];
6461
+ const varsCount = rawScopes[i + varsCountOffset];
6462
+ const variables = [];
6463
+ for (let j = 0; j < varsCount; ++j) {
6464
+ const nameIndex = rawVars[varOffset + j * varStride + varNameOffset];
6465
+ variables.push({
6466
+ name: strings[nameIndex],
6467
+ slotIndex: j,
6468
+ uses: [],
6469
+ });
6470
+ }
6471
+ varOffset += varsCount * varStride;
6472
+ const scope = {
6473
+ scriptNodeIndex,
6474
+ scopeId,
6475
+ children: [],
6476
+ variables,
6477
+ };
6478
+ if (currentScriptNodeIndex !== scriptNodeIndex) {
6479
+ currentScriptNodeIndex = scriptNodeIndex;
6480
+ scopeStack.length = 0;
6481
+ }
6482
+ if (depth > 0) {
6483
+ const parent = scopeStack[depth - 1];
6484
+ scope.parent = parent;
6485
+ parent.children.push(scope);
6486
+ }
6487
+ scopeStack[depth] = scope;
6488
+ scopeStack.length = depth + 1;
6489
+ let scriptScopes = scopesByScript.get(scriptNodeIndex);
6490
+ if (!scriptScopes) {
6491
+ scriptScopes = new Map();
6492
+ scopesByScript.set(scriptNodeIndex, scriptScopes);
6493
+ }
6494
+ scriptScopes.set(scopeId, scope);
6495
+ }
6496
+ let useOffset = 0;
6497
+ for (let i = 0; i < rawScopes.length; i += scopeStride) {
6498
+ const scriptNodeIndex = rawScopes[i + scriptNodeIndexOffset];
6499
+ const scopeId = rawScopes[i + scopeIdOffset];
6500
+ const usesCount = rawScopes[i + usesCountOffset];
6501
+ const scope = scopesByScript.get(scriptNodeIndex)?.get(scopeId);
6502
+ if (scope) {
6503
+ for (let j = 0; j < usesCount; ++j) {
6504
+ const declaringScopeId = rawUses[useOffset + j * useStride + useDeclaringScopeIdOffset];
6505
+ const slotIndex = rawUses[useOffset + j * useStride + useSlotIndexOffset];
6506
+ const declaringScope = scopesByScript.get(scriptNodeIndex)?.get(declaringScopeId);
6507
+ const variable = declaringScope?.variables[slotIndex];
6508
+ if (variable && !variable.uses.includes(scope)) {
6509
+ variable.uses.push(scope);
6510
+ }
6511
+ }
6512
+ }
6513
+ useOffset += usesCount * useStride;
6514
+ }
6515
+ return scopesByScript;
6516
+ }
6517
+ function scanHeap(snapshot) {
6518
+ const scripts = new Map();
6519
+ const contextNodes = [];
6520
+ const liveClosures = [];
6521
+ const scopeInfoScriptNodeIndexes = new Map();
6522
+ const node = snapshot.createNode();
6523
+ const nodes = snapshot.nodes;
6524
+ const nodeFieldCount = snapshot.nodeFieldCount;
6525
+ const nodeClosureType = snapshot.nodeClosureType;
6526
+ for (let nodeIndex = 0; nodeIndex < nodes.length; nodeIndex += nodeFieldCount) {
6527
+ node.nodeIndex = nodeIndex;
6528
+ const rawName = node.rawName();
6529
+ if (rawName.startsWith('system / Script')) {
6530
+ processScript(scripts, node);
6531
+ }
6532
+ else if (snapshot.isContextObject(node)) {
6533
+ processContext(contextNodes, node);
6534
+ }
6535
+ else if (node.rawType() === nodeClosureType) {
6536
+ processClosure(liveClosures, node);
6537
+ }
6538
+ else if (rawName.startsWith('system / SharedFunctionInfo')) {
6539
+ processSharedFunctionInfo(scopeInfoScriptNodeIndexes, node);
6540
+ }
6541
+ }
6542
+ return { scripts, contextNodes, liveClosures, scopeInfoScriptNodeIndexes };
6543
+ }
6544
+ function processScript(scripts, node) {
6545
+ const rawName = node.rawName();
6546
+ const scriptNodeIndex = node.nodeIndex;
6547
+ const scriptNamePrefix = 'system / Script / ';
6548
+ let name = rawName.startsWith(scriptNamePrefix) ? rawName.substring(scriptNamePrefix.length) : '';
6549
+ if (!name) {
6550
+ name = node.findInternalEdgeTarget('source_url')?.name() ?? '';
6551
+ }
6552
+ scripts.set(scriptNodeIndex, {
6553
+ name,
6554
+ nodeId: node.id(),
6555
+ });
6556
+ }
6557
+ function processContext(contextNodes, node) {
6558
+ const scopeInfoNodeIndex = node.findInternalEdgeTarget('scope_info')?.nodeIndex;
6559
+ if (scopeInfoNodeIndex === undefined) {
6560
+ return;
6561
+ }
6562
+ contextNodes.push({
6563
+ contextNodeIndex: node.nodeIndex,
6564
+ contextNodeId: node.id(),
6565
+ scopeInfoNodeIndex,
6566
+ });
6567
+ }
6568
+ function processClosure(liveClosures, node) {
6569
+ const sharedFunctionInfo = node.findInternalEdgeTarget('shared');
6570
+ const closureContext = node.findInternalEdgeTarget('context');
6571
+ if (!sharedFunctionInfo || !closureContext) {
6572
+ return;
6573
+ }
6574
+ const script = sharedFunctionInfo.findInternalEdgeTarget('script');
6575
+ if (!script) {
6576
+ return;
6577
+ }
6578
+ const scopeId = sharedFunctionInfo.findInternalEdgeTarget('scope_id')?.nodeValueAsInt();
6579
+ if (scopeId !== undefined) {
6580
+ liveClosures.push({
6581
+ contextNodeIndex: closureContext.nodeIndex,
6582
+ scriptNodeIndex: script.nodeIndex,
6583
+ scopeId,
6584
+ });
6585
+ }
6586
+ }
6587
+ function processSharedFunctionInfo(scopeInfoScriptNodeIndexes, node) {
6588
+ const scopeInfo = node.findInternalEdgeTarget('name_or_scope_info');
6589
+ const script = node.findInternalEdgeTarget('script');
6590
+ if (scopeInfo?.rawName() !== 'system / ScopeInfo' || !script?.rawName().startsWith('system / Script')) {
6591
+ return;
6592
+ }
6593
+ scopeInfoScriptNodeIndexes.set(scopeInfo.nodeIndex, script.nodeIndex);
6594
+ }
6595
+ function buildLiveFunctions(snapshot, liveClosures) {
6596
+ const liveFunctionsByScript = new Map();
6597
+ const node = snapshot.createNode();
6598
+ for (const closure of liveClosures) {
6599
+ let scriptFunctions = liveFunctionsByScript.get(closure.scriptNodeIndex);
6600
+ if (!scriptFunctions) {
6601
+ scriptFunctions = new Map();
6602
+ liveFunctionsByScript.set(closure.scriptNodeIndex, scriptFunctions);
6603
+ }
6604
+ let liveFunction = scriptFunctions.get(closure.scopeId);
6605
+ if (!liveFunction) {
6606
+ liveFunction = {
6607
+ contextNodeIndexes: new Set(),
6608
+ };
6609
+ scriptFunctions.set(closure.scopeId, liveFunction);
6610
+ }
6611
+ let contextNodeIndex = closure.contextNodeIndex;
6612
+ while (contextNodeIndex !== undefined && !liveFunction.contextNodeIndexes.has(contextNodeIndex)) {
6613
+ node.nodeIndex = contextNodeIndex;
6614
+ if (!snapshot.isContextObject(node)) {
6615
+ break;
6616
+ }
6617
+ liveFunction.contextNodeIndexes.add(contextNodeIndex);
6618
+ contextNodeIndex = node.findInternalEdgeTarget('previous')?.nodeIndex;
6619
+ }
6620
+ }
6621
+ return liveFunctionsByScript;
6622
+ }
6623
+ function correlateContextsWithScopes(snapshot, scan, scopesByScript) {
6624
+ const scriptsWithoutScopesByScript = new Map();
6625
+ const scopes = new Map();
6626
+ const node = snapshot.createNode();
6627
+ for (const context of scan.contextNodes) {
6628
+ const scopeInfoNodeIndex = context.scopeInfoNodeIndex;
6629
+ const existingScope = scopes.get(scopeInfoNodeIndex);
6630
+ if (existingScope) {
6631
+ const fieldValueNodeIndexes = [];
6632
+ node.nodeIndex = context.contextNodeIndex;
6633
+ for (const edges = node.edges(); edges.hasNext(); edges.next()) {
6634
+ const edge = edges.item();
6635
+ if (edge.type() === 'context') {
6636
+ fieldValueNodeIndexes.push(edge.nodeIndex());
6637
+ }
6638
+ }
6639
+ existingScope.contexts.push({
6640
+ contextNodeIndex: context.contextNodeIndex,
6641
+ contextNodeId: context.contextNodeId,
6642
+ fieldValueNodeIndexes,
6643
+ });
6644
+ continue;
6645
+ }
6646
+ node.nodeIndex = scopeInfoNodeIndex;
6647
+ const scopeId = node.findInternalEdgeTarget('scope_id')?.nodeValueAsInt();
6648
+ if (scopeId === undefined) {
6649
+ continue;
6650
+ }
6651
+ const scopeInfoNodeId = node.id();
6652
+ const scopeStart = node.findInternalEdgeTarget('start_position')?.nodeValueAsInt() ?? 0;
6653
+ const scopeEnd = node.findInternalEdgeTarget('end_position')?.nodeValueAsInt() ?? 0;
6654
+ const scopeName = node.findInternalEdgeTarget('function_name')?.name();
6655
+ const scriptNodeIndex = resolveScopeInfoScriptNodeIndex(snapshot, scan.scopeInfoScriptNodeIndexes, scopeInfoNodeIndex);
6656
+ const script = scriptNodeIndex !== undefined ? scan.scripts.get(scriptNodeIndex) : undefined;
6657
+ if (scriptNodeIndex === undefined || !script) {
6658
+ continue;
6659
+ }
6660
+ const existingScriptWithoutScopes = scriptsWithoutScopesByScript.get(scriptNodeIndex);
6661
+ if (existingScriptWithoutScopes) {
6662
+ existingScriptWithoutScopes.contextCount++;
6663
+ continue;
6664
+ }
6665
+ const embeddedScopes = scopesByScript.get(scriptNodeIndex);
6666
+ if (!embeddedScopes) {
6667
+ scriptsWithoutScopesByScript.set(scriptNodeIndex, {
6668
+ scriptNodeIndex,
6669
+ scriptNodeId: script.nodeId,
6670
+ scriptName: script.name,
6671
+ contextCount: 1,
6672
+ });
6673
+ continue;
6674
+ }
6675
+ const embeddedScope = embeddedScopes.get(scopeId);
6676
+ if (!embeddedScope) {
6677
+ continue;
6678
+ }
6679
+ const fieldNames = [];
6680
+ const fieldValueNodeIndexes = [];
6681
+ node.nodeIndex = context.contextNodeIndex;
6682
+ for (const edges = node.edges(); edges.hasNext(); edges.next()) {
6683
+ const edge = edges.item();
6684
+ if (edge.type() === 'context') {
6685
+ fieldNames.push(edge.name());
6686
+ fieldValueNodeIndexes.push(edge.nodeIndex());
6687
+ }
6688
+ }
6689
+ scopes.set(scopeInfoNodeIndex, {
6690
+ scopeInfoNodeIndex,
6691
+ scopeInfoNodeId,
6692
+ scriptNodeIndex,
6693
+ scriptNodeId: script.nodeId,
6694
+ scriptName: script.name,
6695
+ scopeName,
6696
+ scopeStart,
6697
+ scopeEnd,
6698
+ scope: embeddedScope,
6699
+ fieldNames,
6700
+ contexts: [{
6701
+ contextNodeIndex: context.contextNodeIndex,
6702
+ contextNodeId: context.contextNodeId,
6703
+ fieldValueNodeIndexes,
6704
+ }],
6705
+ });
6706
+ }
6707
+ return {
6708
+ scopes,
6709
+ scriptsWithoutScopes: [...scriptsWithoutScopesByScript.values()],
6710
+ };
6711
+ }
6712
+ function resolveScopeInfoScriptNodeIndex(snapshot, scopeInfoScriptNodeIndexes, scopeInfoNodeIndex) {
6713
+ if (scopeInfoScriptNodeIndexes.has(scopeInfoNodeIndex)) {
6714
+ return scopeInfoScriptNodeIndexes.get(scopeInfoNodeIndex);
6715
+ }
6716
+ const visited = [];
6717
+ const seen = new Set();
6718
+ const node = snapshot.createNode();
6719
+ let currentNodeIndex = scopeInfoNodeIndex;
6720
+ let scriptNodeIndex;
6721
+ while (!seen.has(currentNodeIndex)) {
6722
+ if (scopeInfoScriptNodeIndexes.has(currentNodeIndex)) {
6723
+ scriptNodeIndex = scopeInfoScriptNodeIndexes.get(currentNodeIndex);
6724
+ break;
6725
+ }
6726
+ seen.add(currentNodeIndex);
6727
+ visited.push(currentNodeIndex);
6728
+ node.nodeIndex = currentNodeIndex;
6729
+ const outerScopeInfo = node.findInternalEdgeTarget('outer_scope_info');
6730
+ if (!outerScopeInfo) {
6731
+ break;
6732
+ }
6733
+ currentNodeIndex = outerScopeInfo.nodeIndex;
6734
+ }
6735
+ for (const visitedNodeIndex of visited) {
6736
+ scopeInfoScriptNodeIndexes.set(visitedNodeIndex, scriptNodeIndex);
6737
+ }
6738
+ return scriptNodeIndex;
6739
+ }
6740
+ function classifyFields(snapshot, scopes, liveFunctionsByScript) {
6741
+ const scopeAnalyses = [];
6742
+ const node = snapshot.createNode();
6743
+ for (const scope of scopes.values()) {
6744
+ const scopeContexts = [];
6745
+ for (const context of scope.contexts) {
6746
+ let contextDeadFieldsRetainedSizeSum = 0;
6747
+ const deadFields = [];
6748
+ for (let fieldIndex = 0; fieldIndex < context.fieldValueNodeIndexes.length; ++fieldIndex) {
6749
+ const fieldName = scope.fieldNames[fieldIndex];
6750
+ const variable = scope.scope.variables.find(v => v.name === fieldName);
6751
+ if (!variable) {
6752
+ continue;
6753
+ }
6754
+ if (isVariableUsedInContext(liveFunctionsByScript, scope.scriptNodeIndex, context.contextNodeIndex, variable)) {
6755
+ continue;
6756
+ }
6757
+ const fieldValueNodeIndex = context.fieldValueNodeIndexes[fieldIndex];
6758
+ node.nodeIndex = fieldValueNodeIndex;
6759
+ const retainedSize = node.retainedSize();
6760
+ deadFields.push({
6761
+ name: fieldName,
6762
+ valueNodeIndex: fieldValueNodeIndex,
6763
+ valueNodeId: node.id(),
6764
+ valueName: node.name(),
6765
+ valueType: node.type(),
6766
+ selfSize: node.selfSize(),
6767
+ retainedSize,
6768
+ });
6769
+ contextDeadFieldsRetainedSizeSum += retainedSize;
6770
+ }
6771
+ if (deadFields.length === 0) {
6772
+ continue;
6773
+ }
6774
+ node.nodeIndex = context.contextNodeIndex;
6775
+ scopeContexts.push({
6776
+ contextNodeIndex: context.contextNodeIndex,
6777
+ contextNodeId: node.id(),
6778
+ retainedSize: node.retainedSize(),
6779
+ deadFieldsRetainedSizeSum: contextDeadFieldsRetainedSizeSum,
6780
+ deadFields,
6781
+ });
6782
+ }
6783
+ if (scopeContexts.length === 0) {
6784
+ continue;
6785
+ }
6786
+ scopeAnalyses.push({
6787
+ scopeInfoNodeIndex: scope.scopeInfoNodeIndex,
6788
+ scopeInfoNodeId: scope.scopeInfoNodeId,
6789
+ scriptNodeIndex: scope.scriptNodeIndex,
6790
+ scriptNodeId: scope.scriptNodeId,
6791
+ scriptName: scope.scriptName,
6792
+ scopeName: scope.scopeName,
6793
+ scopeStart: scope.scopeStart,
6794
+ scopeEnd: scope.scopeEnd,
6795
+ contextFieldCount: scope.fieldNames.length,
6796
+ contexts: scopeContexts,
6797
+ });
6798
+ }
6799
+ return scopeAnalyses;
6800
+ }
6801
+ function isVariableUsedInContext(liveFunctionsByScript, scriptNodeIndex, contextNodeIndex, variable) {
6802
+ const liveFunctionsByScopeId = liveFunctionsByScript.get(scriptNodeIndex);
6803
+ if (!liveFunctionsByScopeId) {
6804
+ return false;
6805
+ }
6806
+ for (const usingScope of variable.uses) {
6807
+ for (let curr = usingScope; curr; curr = curr.parent) {
6808
+ const liveFunction = liveFunctionsByScopeId.get(curr.scopeId);
6809
+ if (liveFunction?.contextNodeIndexes.has(contextNodeIndex)) {
6810
+ return true;
6811
+ }
6812
+ }
6813
+ }
6814
+ return false;
6815
+ }
6816
+ function sortAndBuildResult(scopeAnalyses, scriptsWithoutScopes) {
6817
+ const compareContexts = (left, right) => {
6818
+ return right.deadFieldsRetainedSizeSum - left.deadFieldsRetainedSizeSum || right.retainedSize - left.retainedSize ||
6819
+ left.contextNodeIndex - right.contextNodeIndex;
6820
+ };
6821
+ for (const scope of scopeAnalyses) {
6822
+ for (const context of scope.contexts) {
6823
+ context.deadFields.sort((left, right) => right.retainedSize - left.retainedSize);
6824
+ }
6825
+ scope.contexts.sort(compareContexts);
6826
+ }
6827
+ scopeAnalyses.sort((left, right) => compareContexts(left.contexts[0], right.contexts[0]));
6828
+ scriptsWithoutScopes.sort((left, right) => left.scriptNodeIndex - right.scriptNodeIndex);
6829
+ return { scopes: scopeAnalyses, scriptsWithoutScopes };
6830
+ }
6831
+
6286
6832
  // Copyright 2011 The Chromium Authors
6287
6833
  var _a;
6288
6834
  class HeapSnapshotEdge {
@@ -7097,7 +7643,7 @@ class HeapSnapshot {
7097
7643
  }
7098
7644
  this.#allocationProfile = new AllocationProfile(this.profile, liveObjects);
7099
7645
  }
7100
- this.#progress.updateStatus('Finished processing.');
7646
+ this.#progress.updateStatus('Finished processing');
7101
7647
  }
7102
7648
  nodeIndexForId(nodeId) {
7103
7649
  const nodesLength = this.nodes.length;
@@ -7129,6 +7675,9 @@ class HeapSnapshot {
7129
7675
  retainerCount: node.retainersCount(),
7130
7676
  };
7131
7677
  }
7678
+ analyzeContexts() {
7679
+ return analyzeContexts(this);
7680
+ }
7132
7681
  startInitStep1InSecondThread(secondWorker) {
7133
7682
  const resultsFromSecondWorker = new Promise((resolve, reject) => {
7134
7683
  const listener = (e) => {
@@ -10319,6 +10868,18 @@ class HeapSnapshotLoader {
10319
10868
  else {
10320
10869
  this.#snapshot.locations = [];
10321
10870
  }
10871
+ if (this.#snapshot.snapshot.meta.scope_fields) {
10872
+ const scopes = await this.#parseArray('"scopes"', 'Loading scopes…');
10873
+ this.#snapshot.scopes = scopes.asArrayOrFail();
10874
+ }
10875
+ if (this.#snapshot.snapshot.meta.scope_context_var_fields) {
10876
+ const scopeContextVars = await this.#parseArray('"scope_context_vars"', 'Loading scope context vars…');
10877
+ this.#snapshot.scope_context_vars = scopeContextVars.asArrayOrFail();
10878
+ }
10879
+ if (this.#snapshot.snapshot.meta.scope_use_fields) {
10880
+ const scopeUses = await this.#parseArray('"scope_uses"', 'Loading scope uses…');
10881
+ this.#snapshot.scope_uses = scopeUses.asArrayOrFail();
10882
+ }
10322
10883
  this.#progress.updateStatus('Loading strings…');
10323
10884
  const stringsTokenIndex = await this.#findToken('"strings"');
10324
10885
  const bracketIndex = await this.#findToken('[', stringsTokenIndex);