profiler-md 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -31,17 +31,16 @@ const formatTable = (headers, rows) => {
31
31
  //#endregion
32
32
  //#region src/v8/common.ts
33
33
  /**
34
- * Returns whether to include the given call frame in the Markdown output.
34
+ * Returns whether to include the given row in the Markdown output.
35
35
  *
36
- * This is the default value for {@link V8ProfileToMdOptions.includeCallFrame}.
36
+ * This is the default value for {@link V8ProfileToMdOptions.includeRow}.
37
37
  *
38
- * It makes reasonable assumptions about which call frames are uninteresting to
38
+ * It makes reasonable assumptions about which rows are uninteresting to
39
39
  * display. For example, Node internals related to ESM loading are excluded.
40
40
  */
41
- const defaultIncludeCallFrame = (callFrame) => {
42
- const { functionName, url } = callFrame;
43
- if (functionName === `(root)`) return false;
44
- if (url?.protocol === `node:` && url.pathname.startsWith(`internal/`)) return false;
41
+ const defaultIncludeRow = ({ name, location }) => {
42
+ if (name === `(root)`) return false;
43
+ if (!location && (name === `ModuleWrap` || name.startsWith(`system /`) || name.startsWith(`Node /`)) || location?.startsWith(`node:internal/`)) return false;
45
44
  return true;
46
45
  };
47
46
  /**
@@ -52,18 +51,18 @@ const defaultIncludeCallFrame = (callFrame) => {
52
51
  * Excludes `node_modules` only by default.
53
52
  */
54
53
  const defaultIsThirdPartyURL = (url) => url.pathname.includes(`/node_modules/`);
55
- const normalizeV8ProfileToMdOptions = ({ topN = 20, includeCallFrame = defaultIncludeCallFrame, isThirdPartyURL = defaultIsThirdPartyURL, cwd } = {}) => {
54
+ const normalizeV8ProfileToMdOptions = ({ topN = 20, includeRow = defaultIncludeRow, isThirdPartyURL = defaultIsThirdPartyURL, cwd } = {}) => {
56
55
  if (cwd === void 0 && typeof process !== `undefined`) cwd = process.cwd();
57
56
  if (cwd != null && !cwd.endsWith(`/`)) cwd = `${cwd}/`;
58
- const includeCallFrameCache = /* @__PURE__ */ new Map();
57
+ const includeRowCache = /* @__PURE__ */ new Map();
59
58
  const isThirdPartyUrlCache = /* @__PURE__ */ new Map();
60
59
  return {
61
60
  topN,
62
- includeCallFrame: (node) => {
63
- let result = includeCallFrameCache.get(node.id);
61
+ includeRow: (row) => {
62
+ let result = includeRowCache.get(row.id);
64
63
  if (result !== void 0) return result;
65
- result = includeCallFrame(toPublicCallFrame(node.callFrame));
66
- includeCallFrameCache.set(node.id, result);
64
+ result = includeRow(row);
65
+ includeRowCache.set(row.id, result);
67
66
  return result;
68
67
  },
69
68
  isThirdPartyURL: (url) => {
@@ -77,25 +76,16 @@ const normalizeV8ProfileToMdOptions = ({ topN = 20, includeCallFrame = defaultIn
77
76
  cwd: cwd ?? void 0
78
77
  };
79
78
  };
80
- const toPublicCallFrame = (callFrame) => {
79
+ const formatLocation = (location, { cwd }) => {
81
80
  let url;
82
81
  try {
83
- url = new URL(callFrame.url);
82
+ url = new URL(location);
84
83
  } catch {}
85
- return {
86
- functionName: callFrame.functionName || void 0,
87
- url
88
- };
89
- };
90
- const formatURL = (url, { cwd }) => {
91
- let urlObject;
92
- try {
93
- urlObject = new URL(url);
94
- } catch {
95
- return url || void 0;
96
- }
97
- if (urlObject.protocol !== `file:`) return url || void 0;
98
- let path = urlObject.pathname;
84
+ let path;
85
+ if (url) {
86
+ if (url.protocol !== `file:`) return location || void 0;
87
+ path = url.pathname;
88
+ } else path = location;
99
89
  if (cwd !== void 0 && path.startsWith(cwd)) path = path.slice(cwd.length);
100
90
  return path;
101
91
  };
@@ -127,15 +117,15 @@ const findCommonCallStack = (callStacks) => {
127
117
  }
128
118
  return suffixLength > 0 ? firstNodes.slice(-suffixLength) : [];
129
119
  };
130
- const formatCallStack = (callStack) => callStack.map(({ callFrame, functionName, location }, index) => {
131
- const name = inlineCode(functionName);
120
+ const formatCallStack = (callStack) => callStack.map(({ callFrame, name, location }, index) => {
121
+ name = inlineCode(name);
132
122
  if (!callFrame.url) return name;
133
123
  const previousUrl = callStack[index - 1]?.callFrame.url;
134
124
  return `${name} (${callFrame.url === previousUrl ? `${callFrame.lineNumber + 1}:${callFrame.columnNumber + 1}` : location ?? inlineCode(`<native>`)})`;
135
125
  }).join(` ← `);
136
126
  const callFrameKey = ({ functionName, url, lineNumber, columnNumber }) => `${functionName}|${url}|${lineNumber}|${columnNumber}`;
137
127
  /** Returns the full call stack for a node (bottom-up). */
138
- const getSummarizedCallStack = (graph, rawNodeId) => {
128
+ const summarizeCallStack = (graph, rawNodeId) => {
139
129
  const stack = [];
140
130
  let currentRawNodeId = rawNodeId;
141
131
  do {
@@ -158,6 +148,38 @@ const formatMicrosecondsExact = (microseconds) => `${microseconds.toFixed(1)}µs
158
148
  const formatBytes = (bytes) => prettyBytes(bytes, { nonBreakingSpace: true });
159
149
  const formatPercent = (fraction) => `${(fraction * 100).toFixed(1)}%`;
160
150
 
151
+ //#endregion
152
+ //#region src/internal/heap.ts
153
+ const selectTopN = (values, topN, compare) => {
154
+ if (topN === 0) return [];
155
+ if (values.length <= topN) return values.toSorted(compare);
156
+ const stableCompare = ([index1, value1], [index2, value2]) => {
157
+ const result = compare(value1, value2);
158
+ return result === 0 ? index1 - index2 : result;
159
+ };
160
+ const heap = [...values.entries()];
161
+ for (let i = Math.floor(topN / 2) - 1; i >= 0; i--) siftDown(heap, i, topN, stableCompare);
162
+ for (let i = topN; i < values.length; i++) {
163
+ const candidate = [i, values[i]];
164
+ if (stableCompare(candidate, heap[0]) < 0) {
165
+ heap[0] = candidate;
166
+ siftDown(heap, 0, topN, stableCompare);
167
+ }
168
+ }
169
+ return heap.slice(0, topN).sort(stableCompare).map(([, value]) => value);
170
+ };
171
+ const siftDown = (heap, i, size, compare) => {
172
+ while (true) {
173
+ let minChild = 2 * i + 1;
174
+ if (minChild >= size) break;
175
+ const right = minChild + 1;
176
+ if (right < size && compare(heap[minChild], heap[right]) < 0) minChild = right;
177
+ if (compare(heap[i], heap[minChild]) >= 0) break;
178
+ [heap[i], heap[minChild]] = [heap[minChild], heap[i]];
179
+ i = minChild;
180
+ }
181
+ };
182
+
161
183
  //#endregion
162
184
  //#region src/v8/cpu-profile/format.ts
163
185
  const formatSummarizedProfile$1 = (profile, options) => `${[
@@ -186,7 +208,7 @@ const formatHottestFunctions$1 = (profile, options) => [
186
208
  formatHottestTotalTimeFunctions(profile, options)
187
209
  ].join(`\n\n`);
188
210
  const formatHottestSelfTimeFunctions = ({ totalTime, nodes }, options) => {
189
- const hottestSelfTimeNodes = nodes.filter(options.includeCallFrame).sort((node1, node2) => node2.selfTime - node1.selfTime).slice(0, options.topN);
211
+ const hottestSelfTimeNodes = selectTopN(nodes.filter(options.includeRow), options.topN, (node1, node2) => node2.selfTime - node1.selfTime);
190
212
  const hottestLinesSections = hottestSelfTimeNodes.filter((node) => node.lineToStats.size > 0).map((node) => formatHottestLines(node, options));
191
213
  const hottestCallerSections = hottestSelfTimeNodes.map((node) => formatHottestCallers$1(node, options)).filter((section) => section !== void 0);
192
214
  return [
@@ -207,11 +229,11 @@ const formatHottestSelfTimeFunctions = ({ totalTime, nodes }, options) => {
207
229
  },
208
230
  `Function`,
209
231
  `Location`
210
- ], hottestSelfTimeNodes.map(({ functionName, location, selfTime, selfSampleCount }) => [
232
+ ], hottestSelfTimeNodes.map(({ name, location, selfTime, selfSampleCount }) => [
211
233
  formatPercent(selfTime / totalTime),
212
234
  formatMicroseconds(selfTime),
213
235
  formatCount(selfSampleCount),
214
- inlineCode(functionName),
236
+ inlineCode(name),
215
237
  location ?? inlineCode(`<native>`)
216
238
  ])),
217
239
  ...hottestLinesSections.length > 0 ? [`#### Lines`, `Lines ranked by contribution to each function's self time.`] : [],
@@ -222,7 +244,7 @@ const formatHottestSelfTimeFunctions = ({ totalTime, nodes }, options) => {
222
244
  };
223
245
  const formatHottestLines = (node, { topN }) => {
224
246
  const hottestLines = [...node.lineToStats].sort(([, stats1], [, stats2]) => stats2.time - stats1.time).slice(0, Math.ceil(topN / 4));
225
- return [`##### ${inlineCode(node.functionName)} (${node.location ?? inlineCode(`<native>`)})`, formatTable([
247
+ return [`##### ${inlineCode(node.name)} (${node.location ?? inlineCode(`<native>`)})`, formatTable([
226
248
  {
227
249
  content: `%`,
228
250
  align: `right`
@@ -244,9 +266,9 @@ const formatHottestLines = (node, { topN }) => {
244
266
  ]))].join(`\n\n`);
245
267
  };
246
268
  const formatHottestCallers$1 = (node, options) => {
247
- const hottestCallerSelfTimes = [...node.callerIdToStats.values()].filter(({ caller }) => options.includeCallFrame(caller)).sort((caller1, caller2) => caller2.selfTime - caller1.selfTime).slice(0, Math.ceil(options.topN / 4));
269
+ const hottestCallerSelfTimes = [...node.callerIdToStats.values()].filter(({ caller }) => options.includeRow(caller)).sort((caller1, caller2) => caller2.selfTime - caller1.selfTime).slice(0, Math.ceil(options.topN / 4));
248
270
  if (hottestCallerSelfTimes.length === 0) return;
249
- return [`##### ${inlineCode(node.functionName)} (${node.location ?? inlineCode(`<native>`)})`, formatTable([
271
+ return [`##### ${inlineCode(node.name)} (${node.location ?? inlineCode(`<native>`)})`, formatTable([
250
272
  {
251
273
  content: `%`,
252
274
  align: `right`
@@ -265,12 +287,12 @@ const formatHottestCallers$1 = (node, options) => {
265
287
  formatPercent(selfTime / node.selfTime),
266
288
  formatMicroseconds(selfTime),
267
289
  formatCount(selfSampleCount),
268
- inlineCode(caller.functionName),
290
+ inlineCode(caller.name),
269
291
  caller.location ?? inlineCode(`<native>`)
270
292
  ]))].join(`\n\n`);
271
293
  };
272
294
  const formatHottestTotalTimeFunctions = ({ totalTime, nodes }, options) => {
273
- const hottestTotalTimeNodes = nodes.filter(options.includeCallFrame).sort((node1, node2) => node2.totalTime - node1.totalTime).slice(0, options.topN);
295
+ const hottestTotalTimeNodes = selectTopN(nodes.filter(options.includeRow), options.topN, (node1, node2) => node2.totalTime - node1.totalTime);
274
296
  const hottestCalleeSections = hottestTotalTimeNodes.map((node) => formatHottestCallees$1(node, options)).filter((section) => section !== void 0);
275
297
  return [
276
298
  `### Total time`,
@@ -294,7 +316,7 @@ const formatHottestTotalTimeFunctions = ({ totalTime, nodes }, options) => {
294
316
  formatPercent(node.totalTime / totalTime),
295
317
  formatMicroseconds(node.totalTime),
296
318
  formatCount(node.totalSampleCount),
297
- inlineCode(node.functionName),
319
+ inlineCode(node.name),
298
320
  node.location ?? inlineCode(`<native>`)
299
321
  ])),
300
322
  ...hottestCalleeSections.length > 0 ? [`#### Callees`, `Callees ranked by contribution to each function's total time. Callee attribution may be imprecise due to V8 JIT inlining.`] : [],
@@ -302,9 +324,9 @@ const formatHottestTotalTimeFunctions = ({ totalTime, nodes }, options) => {
302
324
  ].join(`\n\n`);
303
325
  };
304
326
  const formatHottestCallees$1 = (node, options) => {
305
- const hottestCalleeTotalTimes = [...node.calleeIdToStats.values()].filter(({ callee }) => options.includeCallFrame(callee)).sort((callee1, callee2) => callee2.totalTime - callee1.totalTime).slice(0, Math.ceil(options.topN / 4));
327
+ const hottestCalleeTotalTimes = [...node.calleeIdToStats.values()].filter(({ callee }) => options.includeRow(callee)).sort((callee1, callee2) => callee2.totalTime - callee1.totalTime).slice(0, Math.ceil(options.topN / 4));
306
328
  if (hottestCalleeTotalTimes.length === 0) return;
307
- return [`##### ${inlineCode(node.functionName)} (${node.location ?? inlineCode(`<native>`)})`, formatTable([
329
+ return [`##### ${inlineCode(node.name)} (${node.location ?? inlineCode(`<native>`)})`, formatTable([
308
330
  {
309
331
  content: `%`,
310
332
  align: `right`
@@ -323,15 +345,15 @@ const formatHottestCallees$1 = (node, options) => {
323
345
  formatPercent(totalTime / node.totalTime),
324
346
  formatMicroseconds(totalTime),
325
347
  formatCount(totalSampleCount),
326
- inlineCode(callee.functionName),
348
+ inlineCode(callee.name),
327
349
  callee.location ?? inlineCode(`<native>`)
328
350
  ]))].join(`\n\n`);
329
351
  };
330
352
  const formatHottestCallStacks$1 = ({ totalTime, callStacks }, options) => {
331
- const hottestCallStacks = callStacks.map((callStack) => ({
353
+ const hottestCallStacks = selectTopN(callStacks.map((callStack) => ({
332
354
  ...callStack,
333
- nodes: callStack.nodes.filter(options.includeCallFrame)
334
- })).filter((callStack) => callStack.nodes.length > 1).sort((callStack1, callStack2) => callStack2.selfTime - callStack1.selfTime).slice(0, options.topN);
355
+ nodes: callStack.nodes.filter(options.includeRow)
356
+ })).filter((callStack) => callStack.nodes.length > 1), options.topN, (callStack1, callStack2) => callStack2.selfTime - callStack1.selfTime);
335
357
  if (hottestCallStacks.length === 0) return;
336
358
  const commonCallStack = findCommonCallStack(hottestCallStacks);
337
359
  return [
@@ -376,24 +398,27 @@ const summarizeProfile$1 = (profile, options) => {
376
398
  const rawNodeIdToSummarizedCallStack = /* @__PURE__ */ new Map();
377
399
  const keyToSummarizedCallStack = /* @__PURE__ */ new Map();
378
400
  const callFrameCategoryToStats = /* @__PURE__ */ new Map();
401
+ const summarizedNodeCount = graph.keyToSummarizedNode.size;
402
+ const ordinalToIterationLastVisited = new Int32Array(summarizedNodeCount).fill(-1);
403
+ const pairOrdinalToIterationLastVisited = new Int32Array(summarizedNodeCount * summarizedNodeCount).fill(-1);
379
404
  for (let index = 0; index < profile.samples.length; index++) {
380
405
  const rawNodeId = profile.samples[index];
381
406
  const timeDelta = profile.timeDeltas[index];
382
407
  const node = graph.rawIdToSummarizedNode.get(rawNodeId);
383
408
  if (!node) continue;
384
409
  node.selfTime += timeDelta;
385
- const { positionTicks } = graph.rawIdToRawNode.get(rawNodeId);
386
- if (positionTicks) {
387
- const totalLineTicks = positionTicks.reduce((totalTicks, tick) => totalTicks + tick.ticks, 0);
388
- for (const tick of positionTicks) {
389
- const line = tick.line - 1;
390
- node.lineToStats.get(line).time += timeDelta * (tick.ticks / totalLineTicks);
410
+ const tickInfo = graph.rawIdToTickInfo.get(rawNodeId);
411
+ if (tickInfo) {
412
+ const { stats: tickStats, fractions: tickFractions } = tickInfo;
413
+ for (let i = 0; i < tickStats.length; i++) {
414
+ const tickStat = tickStats[i];
415
+ tickStat.time += timeDelta * tickFractions[i];
391
416
  }
392
417
  }
393
418
  let summarizedCallStack = rawNodeIdToSummarizedCallStack.get(rawNodeId);
394
419
  if (!summarizedCallStack) {
395
- const callStack = getSummarizedCallStack(graph, rawNodeId);
396
- const key = callStack.map((node) => callFrameKey(node.callFrame)).join(`,`);
420
+ const callStack = summarizeCallStack(graph, rawNodeId);
421
+ const key = callStack.map((node) => node.ordinal).join(`,`);
397
422
  summarizedCallStack = keyToSummarizedCallStack.get(key);
398
423
  if (!summarizedCallStack) {
399
424
  summarizedCallStack = {
@@ -408,11 +433,11 @@ const summarizeProfile$1 = (profile, options) => {
408
433
  summarizedCallStack.selfTime += timeDelta;
409
434
  summarizedCallStack.selfSampleCount++;
410
435
  const callStack = summarizedCallStack.nodes;
411
- const seenCallers = /* @__PURE__ */ new Set();
412
- for (const caller of callStack) if (!seenCallers.has(caller)) {
413
- seenCallers.add(caller);
414
- caller.totalTime += timeDelta;
415
- caller.totalSampleCount++;
436
+ for (const stackNode of callStack) {
437
+ if (ordinalToIterationLastVisited[stackNode.ordinal] === index) continue;
438
+ ordinalToIterationLastVisited[stackNode.ordinal] = index;
439
+ stackNode.totalTime += timeDelta;
440
+ stackNode.totalSampleCount++;
416
441
  }
417
442
  const caller = callStack[1];
418
443
  if (caller) {
@@ -428,13 +453,12 @@ const summarizeProfile$1 = (profile, options) => {
428
453
  callerSelfTime.selfTime += timeDelta;
429
454
  callerSelfTime.selfSampleCount++;
430
455
  }
431
- const seenCallerCalleePairs = /* @__PURE__ */ new Set();
432
456
  for (let i = 0; i < callStack.length - 1; i++) {
433
457
  const callee = callStack[i];
434
458
  const caller = callStack[i + 1];
435
- const pair = `${caller.id},${callee.id}`;
436
- if (seenCallerCalleePairs.has(pair)) continue;
437
- seenCallerCalleePairs.add(pair);
459
+ const pairOrdinal = caller.ordinal * summarizedNodeCount + callee.ordinal;
460
+ if (pairOrdinalToIterationLastVisited[pairOrdinal] === index) continue;
461
+ pairOrdinalToIterationLastVisited[pairOrdinal] = index;
438
462
  let calleeTotalTime = caller.calleeIdToStats.get(callee.id);
439
463
  if (!calleeTotalTime) {
440
464
  calleeTotalTime = {
@@ -468,22 +492,22 @@ const summarizeProfile$1 = (profile, options) => {
468
492
  };
469
493
  };
470
494
  const computeProfileGraph$1 = (profile, options) => {
471
- const rawIdToRawNode = /* @__PURE__ */ new Map();
472
495
  const rawIdToSummarizedNode = /* @__PURE__ */ new Map();
473
496
  const keyToSummarizedNode = /* @__PURE__ */ new Map();
474
497
  const rawIdToParentRawId = /* @__PURE__ */ new Map();
498
+ const rawIdToTickInfo = /* @__PURE__ */ new Map();
499
+ let nextOrdinal = 0;
475
500
  for (const node of profile.nodes) {
476
- if (rawIdToRawNode.has(node.id)) throw new Error(`Unexpected duplicate node ID: ${node.id}`);
477
- rawIdToRawNode.set(node.id, node);
478
501
  const key = callFrameKey(node.callFrame);
479
502
  let summarizedNode = keyToSummarizedNode.get(key);
480
503
  if (!summarizedNode) {
481
504
  const { functionName, url, lineNumber, columnNumber } = node.callFrame;
482
- const fileLocation = formatURL(url, options);
505
+ const fileLocation = formatLocation(url, options);
483
506
  summarizedNode = {
484
507
  id: node.id,
508
+ ordinal: nextOrdinal++,
485
509
  callFrame: node.callFrame,
486
- functionName: functionName || `(anonymous)`,
510
+ name: functionName || `(anonymous)`,
487
511
  fileLocation,
488
512
  location: fileLocation ? `${fileLocation}:${lineNumber + 1}:${columnNumber + 1}` : void 0,
489
513
  category: categorizeCallFrame(node.callFrame, options),
@@ -499,17 +523,29 @@ const computeProfileGraph$1 = (profile, options) => {
499
523
  }
500
524
  rawIdToSummarizedNode.set(node.id, summarizedNode);
501
525
  summarizedNode.selfSampleCount += node.hitCount;
502
- if (node.positionTicks) for (const tick of node.positionTicks) {
503
- const line = tick.line - 1;
504
- let stats = summarizedNode.lineToStats.get(line);
505
- if (!stats) {
506
- stats = {
507
- time: 0,
508
- sampleCount: 0
509
- };
510
- summarizedNode.lineToStats.set(line, stats);
526
+ if (node.positionTicks) {
527
+ const tickStats = [];
528
+ let totalTicks = 0;
529
+ for (const tick of node.positionTicks) {
530
+ const line = tick.line - 1;
531
+ let stats = summarizedNode.lineToStats.get(line);
532
+ if (!stats) {
533
+ stats = {
534
+ time: 0,
535
+ sampleCount: 0
536
+ };
537
+ summarizedNode.lineToStats.set(line, stats);
538
+ }
539
+ stats.sampleCount += tick.ticks;
540
+ totalTicks += tick.ticks;
541
+ tickStats.push(stats);
511
542
  }
512
- stats.sampleCount += tick.ticks;
543
+ const fractions = new Float64Array(node.positionTicks.length);
544
+ for (let i = 0; i < node.positionTicks.length; i++) fractions[i] = node.positionTicks[i].ticks / totalTicks;
545
+ rawIdToTickInfo.set(node.id, {
546
+ stats: tickStats,
547
+ fractions
548
+ });
513
549
  }
514
550
  if (node.children) for (const childId of node.children) {
515
551
  if (rawIdToParentRawId.has(childId)) throw new Error(`Unexpected node ID with multiple parent IDs: ${childId}`);
@@ -517,10 +553,10 @@ const computeProfileGraph$1 = (profile, options) => {
517
553
  }
518
554
  }
519
555
  return {
520
- rawIdToRawNode,
521
556
  rawIdToSummarizedNode,
522
557
  keyToSummarizedNode,
523
- rawIdToParentRawId
558
+ rawIdToParentRawId,
559
+ rawIdToTickInfo
524
560
  };
525
561
  };
526
562
 
@@ -572,7 +608,7 @@ const formatHottestFunctions = (profile, options) => [
572
608
  formatHottestTotalSizeFunctions(profile, options)
573
609
  ].join(`\n\n`);
574
610
  const formatHottestSelfSizeFunctions = ({ totalSize, nodes }, options) => {
575
- const hottestSelfSizeNodes = nodes.filter(options.includeCallFrame).sort((node1, node2) => node2.selfSize - node1.selfSize).slice(0, options.topN);
611
+ const hottestSelfSizeNodes = selectTopN(nodes.filter(options.includeRow), options.topN, (node1, node2) => node2.selfSize - node1.selfSize);
576
612
  const hottestCallerSections = hottestSelfSizeNodes.map((node) => formatHottestCallers(node, options)).filter((section) => section !== void 0);
577
613
  return [
578
614
  `### Self size`,
@@ -592,11 +628,11 @@ const formatHottestSelfSizeFunctions = ({ totalSize, nodes }, options) => {
592
628
  },
593
629
  `Function`,
594
630
  `Location`
595
- ], hottestSelfSizeNodes.map(({ functionName, location, selfSize, selfSampleCount }) => [
631
+ ], hottestSelfSizeNodes.map(({ name, location, selfSize, selfSampleCount }) => [
596
632
  formatPercent(selfSize / totalSize),
597
633
  formatBytes(selfSize),
598
634
  formatCount(selfSampleCount),
599
- inlineCode(functionName),
635
+ inlineCode(name),
600
636
  location ?? inlineCode(`<native>`)
601
637
  ])),
602
638
  ...hottestCallerSections.length > 0 ? [`#### Callers`, `Callers ranked by contribution to each function's self size.`] : [],
@@ -604,9 +640,9 @@ const formatHottestSelfSizeFunctions = ({ totalSize, nodes }, options) => {
604
640
  ].join(`\n\n`);
605
641
  };
606
642
  const formatHottestCallers = (node, options) => {
607
- const hottestCallers = [...node.callerIdToStats.values()].filter(({ caller }) => options.includeCallFrame(caller)).sort((entry1, entry2) => entry2.selfSize - entry1.selfSize).slice(0, Math.ceil(options.topN / 4));
643
+ const hottestCallers = [...node.callerIdToStats.values()].filter(({ caller }) => options.includeRow(caller)).sort((entry1, entry2) => entry2.selfSize - entry1.selfSize).slice(0, Math.ceil(options.topN / 4));
608
644
  if (hottestCallers.length === 0) return;
609
- return [`##### ${inlineCode(node.functionName)} (${node.location ?? inlineCode(`<native>`)})`, formatTable([
645
+ return [`##### ${inlineCode(node.name)} (${node.location ?? inlineCode(`<native>`)})`, formatTable([
610
646
  {
611
647
  content: `%`,
612
648
  align: `right`
@@ -625,12 +661,12 @@ const formatHottestCallers = (node, options) => {
625
661
  formatPercent(selfSize / node.selfSize),
626
662
  formatBytes(selfSize),
627
663
  formatCount(selfSampleCount),
628
- inlineCode(caller.functionName),
664
+ inlineCode(caller.name),
629
665
  caller.location ?? inlineCode(`<native>`)
630
666
  ]))].join(`\n\n`);
631
667
  };
632
668
  const formatHottestTotalSizeFunctions = ({ totalSize, nodes }, options) => {
633
- const hottestTotalSizeNodes = nodes.filter(options.includeCallFrame).sort((node1, node2) => node2.totalSize - node1.totalSize).slice(0, options.topN);
669
+ const hottestTotalSizeNodes = selectTopN(nodes.filter(options.includeRow), options.topN, (node1, node2) => node2.totalSize - node1.totalSize);
634
670
  const hottestCalleeSections = hottestTotalSizeNodes.map((node) => formatHottestCallees(node, options)).filter((section) => section !== void 0);
635
671
  return [
636
672
  `### Total size`,
@@ -650,11 +686,11 @@ const formatHottestTotalSizeFunctions = ({ totalSize, nodes }, options) => {
650
686
  },
651
687
  `Function`,
652
688
  `Location`
653
- ], hottestTotalSizeNodes.map(({ functionName, location, totalSize: nodeTotal, totalSampleCount }) => [
689
+ ], hottestTotalSizeNodes.map(({ name, location, totalSize: nodeTotal, totalSampleCount }) => [
654
690
  formatPercent(nodeTotal / totalSize),
655
691
  formatBytes(nodeTotal),
656
692
  formatCount(totalSampleCount),
657
- inlineCode(functionName),
693
+ inlineCode(name),
658
694
  location ?? inlineCode(`<native>`)
659
695
  ])),
660
696
  ...hottestCalleeSections.length > 0 ? [`#### Callees`, `Callees ranked by contribution to each function's total size.`] : [],
@@ -662,9 +698,9 @@ const formatHottestTotalSizeFunctions = ({ totalSize, nodes }, options) => {
662
698
  ].join(`\n\n`);
663
699
  };
664
700
  const formatHottestCallees = (node, options) => {
665
- const hottestCallees = [...node.calleeIdToStats.values()].filter(({ callee }) => options.includeCallFrame(callee)).sort((entry1, entry2) => entry2.totalSize - entry1.totalSize).slice(0, Math.ceil(options.topN / 4));
701
+ const hottestCallees = [...node.calleeIdToStats.values()].filter(({ callee }) => options.includeRow(callee)).sort((entry1, entry2) => entry2.totalSize - entry1.totalSize).slice(0, Math.ceil(options.topN / 4));
666
702
  if (hottestCallees.length === 0) return;
667
- return [`##### ${inlineCode(node.functionName)} (${node.location ?? inlineCode(`<native>`)})`, formatTable([
703
+ return [`##### ${inlineCode(node.name)} (${node.location ?? inlineCode(`<native>`)})`, formatTable([
668
704
  {
669
705
  content: `%`,
670
706
  align: `right`
@@ -683,15 +719,15 @@ const formatHottestCallees = (node, options) => {
683
719
  formatPercent(totalSize / node.totalSize),
684
720
  formatBytes(totalSize),
685
721
  formatCount(totalSampleCount),
686
- inlineCode(callee.functionName),
722
+ inlineCode(callee.name),
687
723
  callee.location ?? inlineCode(`<native>`)
688
724
  ]))].join(`\n\n`);
689
725
  };
690
726
  const formatHottestCallStacks = (profile, options) => {
691
- const hottestCallStacks = profile.callStacks.map((callStack) => ({
727
+ const hottestCallStacks = selectTopN(profile.callStacks.map((callStack) => ({
692
728
  ...callStack,
693
- nodes: callStack.nodes.filter(options.includeCallFrame)
694
- })).filter((callStack) => callStack.nodes.length > 1).sort((callStack1, callStack2) => callStack2.selfSize - callStack1.selfSize).slice(0, options.topN);
729
+ nodes: callStack.nodes.filter(options.includeRow)
730
+ })).filter((callStack) => callStack.nodes.length > 1), options.topN, (callStack1, callStack2) => callStack2.selfSize - callStack1.selfSize);
695
731
  if (hottestCallStacks.length === 0) return;
696
732
  const commonCallStack = findCommonCallStack(hottestCallStacks);
697
733
  return [
@@ -735,15 +771,18 @@ const summarizeProfile = (profile, options) => {
735
771
  const rawNodeIdToSummarizedCallStack = /* @__PURE__ */ new Map();
736
772
  const keyToSummarizedCallStack = /* @__PURE__ */ new Map();
737
773
  const callFrameCategoryToStats = /* @__PURE__ */ new Map();
738
- for (const { size, nodeId } of profile.samples) {
774
+ const summarizedNodeCount = graph.keyToSummarizedNode.size;
775
+ const ordinalToIterationLastVisited = new Int32Array(summarizedNodeCount).fill(-1);
776
+ const pairOrdinalToIterationLastVisited = new Int32Array(summarizedNodeCount * summarizedNodeCount).fill(-1);
777
+ for (const [index, { size, nodeId }] of profile.samples.entries()) {
739
778
  const node = graph.rawIdToSummarizedNode.get(nodeId);
740
779
  if (!node) continue;
741
780
  node.selfSize += size;
742
781
  node.selfSampleCount++;
743
782
  let summarizedCallStack = rawNodeIdToSummarizedCallStack.get(nodeId);
744
783
  if (!summarizedCallStack) {
745
- const callStack = getSummarizedCallStack(graph, nodeId);
746
- const key = callStack.map((node) => callFrameKey(node.callFrame)).join(`,`);
784
+ const callStack = summarizeCallStack(graph, nodeId);
785
+ const key = callStack.map((stackNode) => stackNode.ordinal).join(`,`);
747
786
  summarizedCallStack = keyToSummarizedCallStack.get(key);
748
787
  if (!summarizedCallStack) {
749
788
  summarizedCallStack = {
@@ -758,11 +797,11 @@ const summarizeProfile = (profile, options) => {
758
797
  summarizedCallStack.selfSize += size;
759
798
  summarizedCallStack.selfSampleCount++;
760
799
  const callStack = summarizedCallStack.nodes;
761
- const seenNodes = /* @__PURE__ */ new Set();
762
- for (const caller of callStack) if (!seenNodes.has(caller)) {
763
- seenNodes.add(caller);
764
- caller.totalSize += size;
765
- caller.totalSampleCount++;
800
+ for (const stackNode of callStack) {
801
+ if (ordinalToIterationLastVisited[stackNode.ordinal] === index) continue;
802
+ ordinalToIterationLastVisited[stackNode.ordinal] = index;
803
+ stackNode.totalSize += size;
804
+ stackNode.totalSampleCount++;
766
805
  }
767
806
  const caller = callStack[1];
768
807
  if (caller) {
@@ -778,13 +817,12 @@ const summarizeProfile = (profile, options) => {
778
817
  callerStats.selfSize += size;
779
818
  callerStats.selfSampleCount++;
780
819
  }
781
- const seenCallerCalleePairs = /* @__PURE__ */ new Set();
782
820
  for (let i = 0; i < callStack.length - 1; i++) {
783
821
  const callee = callStack[i];
784
822
  const caller = callStack[i + 1];
785
- const pair = `${caller.id},${callee.id}`;
786
- if (seenCallerCalleePairs.has(pair)) continue;
787
- seenCallerCalleePairs.add(pair);
823
+ const pairOrdinal = caller.ordinal * summarizedNodeCount + callee.ordinal;
824
+ if (pairOrdinalToIterationLastVisited[pairOrdinal] === index) continue;
825
+ pairOrdinalToIterationLastVisited[pairOrdinal] = index;
788
826
  let calleeStats = caller.calleeIdToStats.get(callee.id);
789
827
  if (!calleeStats) {
790
828
  calleeStats = {
@@ -821,6 +859,7 @@ const computeProfileGraph = (profile, options) => {
821
859
  const rawIdToSummarizedNode = /* @__PURE__ */ new Map();
822
860
  const keyToSummarizedNode = /* @__PURE__ */ new Map();
823
861
  const rawIdToParentRawId = /* @__PURE__ */ new Map();
862
+ let nextOrdinal = 0;
824
863
  const stack = [{ node: profile.head }];
825
864
  do {
826
865
  const { node, parentId } = stack.pop();
@@ -828,11 +867,12 @@ const computeProfileGraph = (profile, options) => {
828
867
  let summarizedNode = keyToSummarizedNode.get(key);
829
868
  if (!summarizedNode) {
830
869
  const { functionName, url, lineNumber, columnNumber } = node.callFrame;
831
- const fileLocation = formatURL(url, options);
870
+ const fileLocation = formatLocation(url, options);
832
871
  summarizedNode = {
833
872
  id: node.id,
873
+ ordinal: nextOrdinal++,
834
874
  callFrame: node.callFrame,
835
- functionName: functionName || `(anonymous)`,
875
+ name: functionName || `(anonymous)`,
836
876
  location: fileLocation ? `${fileLocation}:${lineNumber + 1}:${columnNumber + 1}` : void 0,
837
877
  category: categorizeCallFrame(node.callFrame, options),
838
878
  selfSize: 0,
@@ -883,11 +923,13 @@ const v8HeapProfileToMd = (data, options) => {
883
923
  const formatSummarizedSnapshot = (snapshot, options) => `${[
884
924
  `# Heap snapshot`,
885
925
  formatOverallSummary(snapshot),
886
- formatLargestConstructors(snapshot, options)
926
+ formatLargestConstructors(snapshot, options),
927
+ formatLargestClosures(snapshot, options),
928
+ formatLargestStrings(snapshot, options)
887
929
  ].filter(Boolean).join(`\n\n`)}\n`;
888
- const formatOverallSummary = ({ totalSize, objectCount, referenceCount, objectCategoryToSizeStats }) => {
889
- const hottestObjectCategories = [...objectCategoryToSizeStats].sort(([, stats1], [, stats2]) => stats2.size - stats1.size);
890
- return [`Allocated ${formatBytes(totalSize)} across ${formatCount(objectCount)} objects and ${formatCount(referenceCount)} references.`, formatTable([
930
+ const formatOverallSummary = ({ totalSize, nodeCount, edgeCount, nodeCategoryToStats }) => {
931
+ const hottestObjectCategories = [...nodeCategoryToStats].sort(([, stats1], [, stats2]) => stats2.size - stats1.size);
932
+ return [`Allocated ${formatBytes(totalSize)} across ${formatCount(nodeCount)} objects and ${formatCount(edgeCount)} references.`, formatTable([
891
933
  `Category`,
892
934
  {
893
935
  content: `%`,
@@ -901,11 +943,11 @@ const formatOverallSummary = ({ totalSize, objectCount, referenceCount, objectCa
901
943
  content: `Objects`,
902
944
  align: `right`
903
945
  }
904
- ], hottestObjectCategories.map(([type, { size, count }]) => [
946
+ ], hottestObjectCategories.map(([type, { size, nodeCount: objectCount }]) => [
905
947
  type,
906
948
  formatPercent(size / totalSize),
907
949
  formatBytes(size),
908
- formatCount(count)
950
+ formatCount(objectCount)
909
951
  ]))].join(`\n\n`);
910
952
  };
911
953
  const formatLargestConstructors = (snapshot, options) => [
@@ -913,9 +955,10 @@ const formatLargestConstructors = (snapshot, options) => [
913
955
  formatLargestSelfSizeConstructors(snapshot, options),
914
956
  formatLargestRetainedSizeConstructors(snapshot, options)
915
957
  ].join(`\n\n`);
916
- const formatLargestSelfSizeConstructors = ({ totalSize, constructors }, options) => {
917
- const largestConstructors = constructors.filter(defaultIncludeConstructor).sort((constructor1, constructor2) => constructor2.selfSize - constructor1.selfSize).slice(0, options.topN);
918
- const largestInstanceSections = largestConstructors.map((constructor) => formatLargestSelfSizeConstructorInstances(constructor, options)).filter((section) => section !== void 0);
958
+ const formatLargestSelfSizeConstructors = (snapshot, options) => {
959
+ const { totalSize, constructors } = snapshot;
960
+ const largestConstructors = selectTopN(constructors.filter(options.includeRow), options.topN, (constructor1, constructor2) => constructor2.selfSize - constructor1.selfSize);
961
+ const largestInstanceSections = largestConstructors.map((constructor) => formatLargestSelfSizeConstructorInstances(constructor, snapshot, options)).filter((section) => section !== void 0);
919
962
  return [
920
963
  `### Self size`,
921
964
  `Constructors ranked by bytes allocated for their instances, excluding objects kept reachable by them.`,
@@ -945,8 +988,8 @@ const formatLargestSelfSizeConstructors = ({ totalSize, constructors }, options)
945
988
  ...largestInstanceSections
946
989
  ].join(`\n\n`);
947
990
  };
948
- const formatLargestSelfSizeConstructorInstances = (constructor, options) => {
949
- const largestInstances = constructor.instances.toSorted((instance1, instance2) => instance2.selfSize - instance1.selfSize).slice(0, Math.ceil(options.topN / 4));
991
+ const formatLargestSelfSizeConstructorInstances = (constructor, { retainerPathOf }, options) => {
992
+ const largestInstances = selectTopN(constructor.instances, Math.ceil(options.topN / 4), (instance1, instance2) => instance2.selfSize - instance1.selfSize);
950
993
  if (largestInstances.length === 0) return;
951
994
  return [`##### ${inlineCode(constructor.name)} (${constructor.location ?? inlineCode(`<native>`)})`, formatTable([
952
995
  {
@@ -961,12 +1004,13 @@ const formatLargestSelfSizeConstructorInstances = (constructor, options) => {
961
1004
  ], largestInstances.map((instance) => [
962
1005
  formatPercent(instance.selfSize / constructor.selfSize),
963
1006
  formatBytes(instance.selfSize),
964
- inlineCode(instance.retainerPath)
1007
+ inlineCode(retainerPathOf(instance.id))
965
1008
  ]))].join(`\n\n`);
966
1009
  };
967
- const formatLargestRetainedSizeConstructors = ({ totalSize, constructors }, options) => {
968
- const largestConstructors = constructors.filter(defaultIncludeConstructor).sort((constructor1, constructor2) => constructor2.retainedSize - constructor1.retainedSize).slice(0, options.topN);
969
- const largestInstanceSections = largestConstructors.map((constructor) => formatLargestRetainedSizeConstructorInstances(constructor, options)).filter((section) => section !== void 0);
1010
+ const formatLargestRetainedSizeConstructors = (snapshot, options) => {
1011
+ const { totalSize, constructors } = snapshot;
1012
+ const largestConstructors = selectTopN(constructors.filter(options.includeRow), options.topN, (constructor1, constructor2) => constructor2.retainedSize - constructor1.retainedSize);
1013
+ const largestInstanceSections = largestConstructors.map((constructor) => formatLargestRetainedSizeConstructorInstances(constructor, snapshot, options)).filter((section) => section !== void 0);
970
1014
  return [
971
1015
  `### Retained size`,
972
1016
  `Constructors ranked by bytes allocated for their instances and all objects that would be freed if their instances were garbage collected.`,
@@ -979,11 +1023,16 @@ const formatLargestRetainedSizeConstructors = ({ totalSize, constructors }, opti
979
1023
  content: `Size`,
980
1024
  align: `right`
981
1025
  },
1026
+ {
1027
+ content: `Instances`,
1028
+ align: `right`
1029
+ },
982
1030
  `Constructor`,
983
1031
  `Location`
984
1032
  ], largestConstructors.map((constructor) => [
985
1033
  formatPercent(constructor.retainedSize / totalSize),
986
1034
  formatBytes(constructor.retainedSize),
1035
+ formatCount(constructor.instances.length),
987
1036
  inlineCode(constructor.name),
988
1037
  constructor.location ?? inlineCode(`<native>`)
989
1038
  ])),
@@ -991,8 +1040,8 @@ const formatLargestRetainedSizeConstructors = ({ totalSize, constructors }, opti
991
1040
  ...largestInstanceSections
992
1041
  ].join(`\n\n`);
993
1042
  };
994
- const formatLargestRetainedSizeConstructorInstances = (constructor, options) => {
995
- const largestInstances = constructor.instances.toSorted((instance1, instance2) => instance2.retainedSize - instance1.retainedSize).slice(0, Math.ceil(options.topN / 4));
1043
+ const formatLargestRetainedSizeConstructorInstances = (constructor, { retainerPathOf }, options) => {
1044
+ const largestInstances = selectTopN(constructor.instances, Math.ceil(options.topN / 4), (instance1, instance2) => instance2.retainedSize - instance1.retainedSize);
996
1045
  if (largestInstances.length === 0) return;
997
1046
  return [`##### ${inlineCode(constructor.name)} (${constructor.location ?? inlineCode(`<native>`)})`, formatTable([
998
1047
  {
@@ -1007,17 +1056,82 @@ const formatLargestRetainedSizeConstructorInstances = (constructor, options) =>
1007
1056
  ], largestInstances.map((instance) => [
1008
1057
  formatPercent(instance.retainedSize / constructor.retainedSize),
1009
1058
  formatBytes(instance.retainedSize),
1010
- inlineCode(instance.retainerPath)
1059
+ inlineCode(retainerPathOf(instance.id))
1011
1060
  ]))].join(`\n\n`);
1012
1061
  };
1013
- const defaultIncludeConstructor = (constructor) => {
1014
- const { name, location } = constructor;
1015
- if (name.startsWith(`system /`) || name.startsWith(`Node /`) || name.startsWith(`(`) && name.endsWith(`)`)) return false;
1016
- if (name === `ModuleWrap` && !location) return false;
1017
- if (name === `Generator` && location?.endsWith(`:1:1`)) return false;
1018
- if (name === `global`) return false;
1019
- if (location?.startsWith(`node:internal/`)) return false;
1020
- return true;
1062
+ const formatLargestClosures = (snapshot, options) => {
1063
+ const { totalSize, closures, retainerPathOf } = snapshot;
1064
+ const largestClosures = selectTopN(closures.filter(options.includeRow), options.topN, (closure1, closure2) => closure2.retainedSize - closure1.retainedSize);
1065
+ const retainedSections = largestClosures.map((closure) => formatClosureRetainedObjects(closure, snapshot, options)).filter((section) => section !== void 0);
1066
+ return [
1067
+ `## Largest closures`,
1068
+ `Closures ranked by bytes that would be freed if the closure were garbage collected.`,
1069
+ formatTable([
1070
+ {
1071
+ content: `%`,
1072
+ align: `right`
1073
+ },
1074
+ {
1075
+ content: `Retained`,
1076
+ align: `right`
1077
+ },
1078
+ `Name`,
1079
+ `Location`,
1080
+ `Path`
1081
+ ], largestClosures.map((closure) => [
1082
+ formatPercent(closure.retainedSize / totalSize),
1083
+ formatBytes(closure.retainedSize),
1084
+ inlineCode(closure.name),
1085
+ closure.location ?? inlineCode(`<unknown>`),
1086
+ inlineCode(retainerPathOf(closure.id))
1087
+ ])),
1088
+ ...retainedSections.length > 0 ? [`### Retained`, `Objects ranked by contribution to each closure's retained size.`] : [],
1089
+ ...retainedSections
1090
+ ].join(`\n\n`);
1091
+ };
1092
+ const formatClosureRetainedObjects = (closure, { retainedNodesOf, retainerPathOf }, options) => {
1093
+ const retainedNodes = selectTopN(retainedNodesOf(closure.id).filter(options.includeRow), Math.ceil(options.topN / 4), (node1, node2) => node2.selfSize - node1.selfSize);
1094
+ if (retainedNodes.length === 0) return;
1095
+ return [`#### ${inlineCode(closure.name)} (${closure.location ?? inlineCode(`<unknown>`)})`, formatTable([
1096
+ {
1097
+ content: `%`,
1098
+ align: `right`
1099
+ },
1100
+ {
1101
+ content: `Size`,
1102
+ align: `right`
1103
+ },
1104
+ `Name`,
1105
+ `Path`
1106
+ ], retainedNodes.map((node) => [
1107
+ formatPercent(node.selfSize / closure.retainedSize),
1108
+ formatBytes(node.selfSize),
1109
+ inlineCode(node.name || `(unknown)`),
1110
+ inlineCode(retainerPathOf(node.id))
1111
+ ]))].join(`\n\n`);
1112
+ };
1113
+ const formatLargestStrings = ({ totalSize, strings, retainerPathOf }, options) => {
1114
+ return [
1115
+ `## Largest strings`,
1116
+ `Strings ranked by bytes allocated for them.`,
1117
+ formatTable([
1118
+ {
1119
+ content: `%`,
1120
+ align: `right`
1121
+ },
1122
+ {
1123
+ content: `Size`,
1124
+ align: `right`
1125
+ },
1126
+ `Value`,
1127
+ `Location`
1128
+ ], selectTopN(strings, options.topN, (string1, string2) => string2.selfSize - string1.selfSize).map((string) => [
1129
+ formatPercent(string.selfSize / totalSize),
1130
+ formatBytes(string.selfSize),
1131
+ inlineCode(string.name),
1132
+ inlineCode(retainerPathOf(string.id))
1133
+ ]))
1134
+ ].join(`\n\n`);
1021
1135
  };
1022
1136
 
1023
1137
  //#endregion
@@ -1027,7 +1141,7 @@ const parseSnapshot = (data) => JSON.parse(data);
1027
1141
  //#endregion
1028
1142
  //#region src/v8/heap-snapshot/summarize.ts
1029
1143
  const summarizeSnapshot = (snapshot, options) => {
1030
- const { snapshot: { meta, node_count: objectCount, edge_count: referenceCount }, nodes, strings } = snapshot;
1144
+ const { snapshot: { meta, node_count: nodeCount, edge_count: edgeCount }, nodes } = snapshot;
1031
1145
  const [nodeTypes] = meta.node_types;
1032
1146
  const fieldLayout = computeFieldLayout(meta);
1033
1147
  const nodeAdjacencyGraph = computeNodeAdjacencyGraph(snapshot, fieldLayout);
@@ -1035,100 +1149,157 @@ const summarizeSnapshot = (snapshot, options) => {
1035
1149
  const immediateDominatorGraph = computeImmediateDominatorGraph(snapshot, nodeAdjacencyGraph);
1036
1150
  const nodeOrdinalToRetainedSize = computeNodeOrdinalToRetainedSize(snapshot, immediateDominatorGraph, fieldLayout);
1037
1151
  let totalSize = 0;
1038
- const objectCategoryToSizeStats = /* @__PURE__ */ new Map();
1039
- const nameToConstructor = /* @__PURE__ */ new Map();
1040
- const nodeOrdinalToConstructor = /* @__PURE__ */ new Map();
1041
- for (let nodeOrdinal = 0; nodeOrdinal < objectCount; nodeOrdinal++) {
1152
+ const nodeCategoryToStats = /* @__PURE__ */ new Map();
1153
+ const constructors = [];
1154
+ const nameToConstructorIndex = /* @__PURE__ */ new Map();
1155
+ const nodeOrdinalToConstructorIndex = new Int32Array(nodeCount).fill(-1);
1156
+ const closures = [];
1157
+ const strings = [];
1158
+ for (let nodeOrdinal = 0; nodeOrdinal < nodeCount; nodeOrdinal++) {
1042
1159
  const nodeIndex = nodeOrdinal * fieldLayout.nodeFieldCount;
1043
1160
  const selfSize = nodes[nodeIndex + fieldLayout.nodeSelfSizeOffset];
1044
1161
  totalSize += selfSize;
1045
1162
  const nodeType = nodes[nodeIndex + fieldLayout.nodeTypeOffset];
1046
1163
  const category = nodeTypes[nodeType];
1047
- let categoryStats = objectCategoryToSizeStats.get(category);
1164
+ let categoryStats = nodeCategoryToStats.get(category);
1048
1165
  if (!categoryStats) {
1049
1166
  categoryStats = {
1050
1167
  size: 0,
1051
- count: 0
1168
+ nodeCount: 0
1052
1169
  };
1053
- objectCategoryToSizeStats.set(category, categoryStats);
1170
+ nodeCategoryToStats.set(category, categoryStats);
1054
1171
  }
1055
1172
  categoryStats.size += selfSize;
1056
- categoryStats.count++;
1173
+ categoryStats.nodeCount++;
1057
1174
  switch (nodeType) {
1058
1175
  case fieldLayout.nodeTypeObject:
1059
1176
  case fieldLayout.nodeTypeNative: {
1060
- const name = strings[nodes[nodeIndex + fieldLayout.nodeNameOffset]];
1061
- let constructor = nameToConstructor.get(name);
1062
- if (!constructor) {
1177
+ const name = formatNodeLabel(nodeIndex, snapshot, fieldLayout, options);
1178
+ let constructorIndex = nameToConstructorIndex.get(name);
1179
+ let constructor;
1180
+ if (constructorIndex === void 0) {
1181
+ constructorIndex = constructors.length;
1063
1182
  constructor = {
1183
+ id: nodeOrdinal,
1064
1184
  name,
1065
1185
  location: void 0,
1066
1186
  selfSize: 0,
1067
1187
  retainedSize: 0,
1068
1188
  instances: []
1069
1189
  };
1070
- nameToConstructor.set(name, constructor);
1071
- }
1190
+ constructors.push(constructor);
1191
+ nameToConstructorIndex.set(name, constructorIndex);
1192
+ } else constructor = constructors[constructorIndex];
1072
1193
  constructor.selfSize += selfSize;
1073
1194
  constructor.location ??= nodeIndexToLocation.get(nodeIndex);
1074
- let retainerPath;
1075
1195
  constructor.instances.push({
1196
+ id: nodeOrdinal,
1197
+ name: constructor.name,
1076
1198
  selfSize,
1077
1199
  retainedSize: nodeOrdinalToRetainedSize[nodeOrdinal],
1078
- get retainerPath() {
1079
- return retainerPath ??= computeRetainerPath(nodeOrdinal, snapshot, nodeAdjacencyGraph, nodeIndexToLocation, immediateDominatorGraph, fieldLayout);
1080
- }
1200
+ location: constructor.location
1081
1201
  });
1082
- nodeOrdinalToConstructor.set(nodeOrdinal, constructor);
1202
+ nodeOrdinalToConstructorIndex[nodeOrdinal] = constructorIndex;
1083
1203
  break;
1084
1204
  }
1205
+ case fieldLayout.nodeTypeClosure:
1206
+ closures.push({
1207
+ id: nodeOrdinal,
1208
+ name: formatNodeLabel(nodeIndex, snapshot, fieldLayout, options),
1209
+ selfSize,
1210
+ retainedSize: nodeOrdinalToRetainedSize[nodeOrdinal],
1211
+ location: nodeIndexToLocation.get(nodeIndex)
1212
+ });
1213
+ break;
1214
+ case fieldLayout.nodeTypeString:
1215
+ case fieldLayout.nodeTypeSlicedString:
1216
+ case fieldLayout.nodeTypeConcatenatedString:
1217
+ strings.push({
1218
+ id: nodeOrdinal,
1219
+ name: formatNodeLabel(nodeIndex, snapshot, fieldLayout, options),
1220
+ selfSize,
1221
+ retainedSize: selfSize
1222
+ });
1223
+ break;
1085
1224
  }
1086
1225
  }
1087
- attributeGroupRetainedSizes({
1088
- nodeOrdinalToRetainedSize,
1089
- ordinalToImmediateDominatorOrdinal: immediateDominatorGraph.ordinalToImmediateDominatorOrdinal,
1090
- nodeOrdinalToGroup: nodeOrdinalToConstructor
1091
- });
1092
- const constructors = [...nameToConstructor.values()];
1226
+ attributeGroupRetainedSizes(nodeOrdinalToRetainedSize, immediateDominatorGraph, nodeOrdinalToConstructorIndex, constructors);
1093
1227
  return {
1094
1228
  totalSize,
1095
- objectCount,
1096
- referenceCount,
1097
- objectCategoryToSizeStats,
1098
- constructors
1229
+ nodeCount,
1230
+ edgeCount,
1231
+ nodeCategoryToStats,
1232
+ constructors,
1233
+ closures,
1234
+ strings,
1235
+ retainerPathOf: (nodeOrdinal) => computeRetainerPath(nodeOrdinal, snapshot, nodeAdjacencyGraph, nodeIndexToLocation, immediateDominatorGraph, fieldLayout, options),
1236
+ retainedNodesOf: (nodeOrdinal) => computeRetainedNodes(nodeOrdinal, snapshot, nodeOrdinalToRetainedSize, immediateDominatorGraph, fieldLayout, options)
1099
1237
  };
1100
1238
  };
1101
1239
  const computeNodeAdjacencyGraph = ({ snapshot: { node_count: nodeCount }, nodes, edges }, fieldLayout) => {
1102
- const ordinalToSuccessors = Array.from({ length: nodeCount }, () => []);
1103
- const ordinalToPredecessors = Array.from({ length: nodeCount }, () => []);
1240
+ const ordinalToSuccessorCount = new Int32Array(nodeCount);
1241
+ const ordinalToPredecessorCount = new Int32Array(nodeCount);
1104
1242
  let nodeEdgesStartIndex = 0;
1105
1243
  for (let nodeOrdinal = 0; nodeOrdinal < nodeCount; nodeOrdinal++) {
1106
- const edgeCount = nodes[nodeOrdinal * fieldLayout.nodeFieldCount + fieldLayout.nodeEdgeCountOffset];
1107
- for (let nodeEdgeOrdinal = 0; nodeEdgeOrdinal < edgeCount; nodeEdgeOrdinal++) {
1108
- const nodeEdgeIndex = nodeEdgesStartIndex + nodeEdgeOrdinal * fieldLayout.edgeFieldCount;
1109
- if (edges[nodeEdgeIndex + fieldLayout.edgeTypeOffset] === fieldLayout.edgeTypeWeak) continue;
1110
- const successorNodeOrdinal = edges[nodeEdgeIndex + fieldLayout.edgeToNodeOffset] / fieldLayout.nodeFieldCount;
1111
- ordinalToSuccessors[nodeOrdinal].push({
1112
- targetNodeOrdinal: successorNodeOrdinal,
1113
- edgeIndex: nodeEdgeIndex
1114
- });
1115
- ordinalToPredecessors[successorNodeOrdinal].push({
1116
- targetNodeOrdinal: nodeOrdinal,
1117
- edgeIndex: nodeEdgeIndex
1118
- });
1244
+ const nodeEdgeCount = nodes[nodeOrdinal * fieldLayout.nodeFieldCount + fieldLayout.nodeEdgeCountOffset];
1245
+ for (let edgeOrdinal = 0; edgeOrdinal < nodeEdgeCount; edgeOrdinal++) {
1246
+ const edgeIndex = nodeEdgesStartIndex + edgeOrdinal * fieldLayout.edgeFieldCount;
1247
+ if (edges[edgeIndex + fieldLayout.edgeTypeOffset] === fieldLayout.edgeTypeWeak) continue;
1248
+ const successorOrdinal = edges[edgeIndex + fieldLayout.edgeToNodeOffset] / fieldLayout.nodeFieldCount;
1249
+ ordinalToSuccessorCount[nodeOrdinal]++;
1250
+ ordinalToPredecessorCount[successorOrdinal]++;
1251
+ }
1252
+ nodeEdgesStartIndex += nodeEdgeCount * fieldLayout.edgeFieldCount;
1253
+ }
1254
+ const ordinalToSuccessorStartOffset = new Int32Array(nodeCount + 1);
1255
+ const ordinalToPredecessorStartOffset = new Int32Array(nodeCount + 1);
1256
+ for (let i = 0; i < nodeCount; i++) {
1257
+ ordinalToSuccessorStartOffset[i + 1] = ordinalToSuccessorStartOffset[i] + ordinalToSuccessorCount[i];
1258
+ ordinalToPredecessorStartOffset[i + 1] = ordinalToPredecessorStartOffset[i] + ordinalToPredecessorCount[i];
1259
+ }
1260
+ const totalEdges = ordinalToSuccessorStartOffset[nodeCount];
1261
+ const offsetToSuccessorOrdinal = new Int32Array(totalEdges);
1262
+ const offsetToSuccessorEdgeIndex = new Int32Array(totalEdges);
1263
+ const offsetToPredecessorOrdinal = new Int32Array(totalEdges);
1264
+ const offsetToPredecessorEdgeIndex = new Int32Array(totalEdges);
1265
+ ordinalToSuccessorCount.fill(0);
1266
+ ordinalToPredecessorCount.fill(0);
1267
+ nodeEdgesStartIndex = 0;
1268
+ for (let nodeOrdinal = 0; nodeOrdinal < nodeCount; nodeOrdinal++) {
1269
+ const nodeEdgeCount = nodes[nodeOrdinal * fieldLayout.nodeFieldCount + fieldLayout.nodeEdgeCountOffset];
1270
+ for (let edgeOrdinal = 0; edgeOrdinal < nodeEdgeCount; edgeOrdinal++) {
1271
+ const edgeIndex = nodeEdgesStartIndex + edgeOrdinal * fieldLayout.edgeFieldCount;
1272
+ if (edges[edgeIndex + fieldLayout.edgeTypeOffset] === fieldLayout.edgeTypeWeak) continue;
1273
+ const successorOrdinal = edges[edgeIndex + fieldLayout.edgeToNodeOffset] / fieldLayout.nodeFieldCount;
1274
+ const successorOffset = ordinalToSuccessorStartOffset[nodeOrdinal] + ordinalToSuccessorCount[nodeOrdinal];
1275
+ offsetToSuccessorOrdinal[successorOffset] = successorOrdinal;
1276
+ offsetToSuccessorEdgeIndex[successorOffset] = edgeIndex;
1277
+ ordinalToSuccessorCount[nodeOrdinal]++;
1278
+ const predecessorOffset = ordinalToPredecessorStartOffset[successorOrdinal] + ordinalToPredecessorCount[successorOrdinal];
1279
+ offsetToPredecessorOrdinal[predecessorOffset] = nodeOrdinal;
1280
+ offsetToPredecessorEdgeIndex[predecessorOffset] = edgeIndex;
1281
+ ordinalToPredecessorCount[successorOrdinal]++;
1119
1282
  }
1120
- nodeEdgesStartIndex += edgeCount * fieldLayout.edgeFieldCount;
1283
+ nodeEdgesStartIndex += nodeEdgeCount * fieldLayout.edgeFieldCount;
1121
1284
  }
1122
1285
  return {
1123
- ordinalToSuccessors,
1124
- ordinalToPredecessors
1286
+ ordinalToSuccessorStartOffset,
1287
+ offsetToSuccessorOrdinal,
1288
+ offsetToSuccessorEdgeIndex,
1289
+ ordinalToPredecessorStartOffset,
1290
+ offsetToPredecessorOrdinal,
1291
+ offsetToPredecessorEdgeIndex
1125
1292
  };
1126
1293
  };
1127
- const computeNodeIndexToLocation = ({ nodes, edges, strings, locations }, nodeAdjacencyGraph, fieldLayout, options) => {
1128
- const followNamedEdge = (nodeIndex, targetEdgeName) => {
1294
+ const computeNodeIndexToLocation = ({ nodes, edges, strings, locations }, { ordinalToSuccessorStartOffset, offsetToSuccessorEdgeIndex }, fieldLayout, options) => {
1295
+ const namedEdgeToNodeIndex = (nodeIndex, targetEdgeName) => {
1129
1296
  const nodeOrdinal = nodeIndex / fieldLayout.nodeFieldCount;
1130
- const successors = nodeAdjacencyGraph.ordinalToSuccessors[nodeOrdinal];
1131
- for (const { edgeIndex } of successors) if (strings[edges[edgeIndex + fieldLayout.edgeNameOrIndexOffset]] === targetEdgeName) return edges[edgeIndex + fieldLayout.edgeToNodeOffset];
1297
+ const successorStartOffset = ordinalToSuccessorStartOffset[nodeOrdinal];
1298
+ const successorEndOffset = ordinalToSuccessorStartOffset[nodeOrdinal + 1];
1299
+ for (let successorOffset = successorStartOffset; successorOffset < successorEndOffset; successorOffset++) {
1300
+ const edgeIndex = offsetToSuccessorEdgeIndex[successorOffset];
1301
+ if (strings[edges[edgeIndex + fieldLayout.edgeNameOrIndexOffset]] === targetEdgeName) return edges[edgeIndex + fieldLayout.edgeToNodeOffset];
1302
+ }
1132
1303
  };
1133
1304
  const scriptIdToFileLocation = /* @__PURE__ */ new Map();
1134
1305
  for (let locationIndex = 0; locationIndex < locations.length; locationIndex += fieldLayout.locationFieldCount) {
@@ -1136,15 +1307,15 @@ const computeNodeIndexToLocation = ({ nodes, edges, strings, locations }, nodeAd
1136
1307
  if (scriptIdToFileLocation.has(scriptId)) continue;
1137
1308
  const nodeIndex = locations[locationIndex + fieldLayout.locationObjectIndexOffset];
1138
1309
  if (nodes[nodeIndex + fieldLayout.nodeTypeOffset] !== fieldLayout.nodeTypeClosure) continue;
1139
- const sharedNodeIndex = followNamedEdge(nodeIndex, `shared`);
1310
+ const sharedNodeIndex = namedEdgeToNodeIndex(nodeIndex, `shared`);
1140
1311
  if (sharedNodeIndex === void 0) continue;
1141
- const scriptNodeIndex = followNamedEdge(sharedNodeIndex, `script`);
1312
+ const scriptNodeIndex = namedEdgeToNodeIndex(sharedNodeIndex, `script`);
1142
1313
  if (scriptNodeIndex === void 0) continue;
1143
- const urlNodeIndex = followNamedEdge(scriptNodeIndex, `name`);
1144
- if (urlNodeIndex === void 0) continue;
1145
- const url = strings[nodes[urlNodeIndex + fieldLayout.nodeNameOffset]];
1146
- if (!url) continue;
1147
- const fileLocation = formatURL(url, options);
1314
+ const locationNodeIndex = namedEdgeToNodeIndex(scriptNodeIndex, `name`);
1315
+ if (locationNodeIndex === void 0) continue;
1316
+ const location = strings[nodes[locationNodeIndex + fieldLayout.nodeNameOffset]];
1317
+ if (!location) continue;
1318
+ const fileLocation = formatLocation(location, options);
1148
1319
  if (fileLocation) scriptIdToFileLocation.set(scriptId, fileLocation);
1149
1320
  }
1150
1321
  const nodeIndexToLocation = /* @__PURE__ */ new Map();
@@ -1160,62 +1331,62 @@ const computeNodeIndexToLocation = ({ nodes, edges, strings, locations }, nodeAd
1160
1331
  return nodeIndexToLocation;
1161
1332
  };
1162
1333
  /**
1163
- * Computes the immediate dominators of every object.
1334
+ * Computes the immediate dominators of every node.
1164
1335
  *
1165
- * Weak edges are excluded because they don't keep objects alive.
1336
+ * Weak edges are excluded because they don't keep nodes alive.
1166
1337
  *
1167
1338
  * Uses the Lengauer-Tarjan dominator tree algorithm.
1168
1339
  *
1169
1340
  * @see https://en.wikipedia.org/wiki/Dominator_(graph_theory)
1170
1341
  * @see https://www.cs.princeton.edu/courses/archive/fall03/cs528/handouts/a%20fast%20algorithm%20for%20finding.pdf
1171
1342
  */
1172
- const computeImmediateDominatorGraph = (snapshot, { ordinalToSuccessors, ordinalToPredecessors }) => {
1343
+ const computeImmediateDominatorGraph = (snapshot, { ordinalToSuccessorStartOffset, offsetToSuccessorOrdinal, ordinalToPredecessorStartOffset, offsetToPredecessorOrdinal }) => {
1173
1344
  const { snapshot: { node_count: nodeCount } } = snapshot;
1174
- const ordinalToDfsIndex = new Int32Array(nodeCount).fill(-1);
1345
+ const ordinalToImmediateDominatorOrdinal = new Int32Array(nodeCount).fill(-1);
1175
1346
  const dfsIndexToOrdinal = new Int32Array(nodeCount);
1176
1347
  const ordinalToParentOrdinal = new Int32Array(nodeCount).fill(-1);
1348
+ const ordinalToDfsIndex = new Int32Array(nodeCount).fill(-1);
1177
1349
  const ordinalToSemidominatorDfsIndex = new Int32Array(nodeCount);
1178
- const ordinalToImmediateDominatorOrdinal = new Int32Array(nodeCount).fill(-1);
1179
- const ordinalToForestAncestorOrdinal = new Int32Array(nodeCount).fill(-1);
1180
- const ordinalToMinSemiAncestorOrdinal = Int32Array.from({ length: nodeCount }, (_, index) => index);
1181
- const ordinalToPendingOrdinals = Array.from({ length: nodeCount }, () => []);
1182
1350
  ordinalToDfsIndex[0] = 0;
1183
- ordinalToSemidominatorDfsIndex[0] = 0;
1184
1351
  dfsIndexToOrdinal[0] = 0;
1352
+ const dfsStackOrdinals = new Int32Array(nodeCount);
1353
+ const dfsStackOffsets = new Int32Array(nodeCount);
1354
+ dfsStackOffsets[0] = ordinalToSuccessorStartOffset[0];
1185
1355
  let dfsIndex = 1;
1186
- const dfsStack = [{
1187
- nodeOrdinal: 0,
1188
- nextChildIndex: 0
1189
- }];
1356
+ let dfsStackSize = 1;
1190
1357
  do {
1191
- const frame = dfsStack.at(-1);
1192
- if (frame.nextChildIndex === ordinalToSuccessors[frame.nodeOrdinal].length) {
1193
- dfsStack.pop();
1358
+ const topOffset = dfsStackSize - 1;
1359
+ const nodeOrdinal = dfsStackOrdinals[topOffset];
1360
+ const nextOffset = dfsStackOffsets[topOffset];
1361
+ if (nextOffset === ordinalToSuccessorStartOffset[nodeOrdinal + 1]) {
1362
+ dfsStackSize--;
1194
1363
  continue;
1195
1364
  }
1196
- const childOrdinal = ordinalToSuccessors[frame.nodeOrdinal][frame.nextChildIndex].targetNodeOrdinal;
1197
- frame.nextChildIndex++;
1365
+ const childOrdinal = offsetToSuccessorOrdinal[nextOffset];
1366
+ dfsStackOffsets[topOffset]++;
1198
1367
  if (ordinalToDfsIndex[childOrdinal] !== -1) continue;
1199
- ordinalToParentOrdinal[childOrdinal] = frame.nodeOrdinal;
1368
+ ordinalToParentOrdinal[childOrdinal] = nodeOrdinal;
1200
1369
  ordinalToDfsIndex[childOrdinal] = dfsIndex;
1201
1370
  ordinalToSemidominatorDfsIndex[childOrdinal] = dfsIndex;
1202
1371
  dfsIndexToOrdinal[dfsIndex] = childOrdinal;
1203
1372
  dfsIndex++;
1204
- dfsStack.push({
1205
- nodeOrdinal: childOrdinal,
1206
- nextChildIndex: 0
1207
- });
1208
- } while (dfsStack.length > 0);
1373
+ dfsStackOrdinals[dfsStackSize] = childOrdinal;
1374
+ dfsStackOffsets[dfsStackSize] = ordinalToSuccessorStartOffset[childOrdinal];
1375
+ dfsStackSize++;
1376
+ } while (dfsStackSize > 0);
1209
1377
  const reachableCount = dfsIndex;
1378
+ const ancestorNodeOrdinalPath = new Int32Array(nodeCount);
1379
+ const ordinalToForestAncestorOrdinal = new Int32Array(nodeCount).fill(-1);
1380
+ const ordinalToMinSemiAncestorOrdinal = Int32Array.from({ length: nodeCount }, (_, index) => index);
1210
1381
  const compressAncestorPath = (startNodeOrdinal) => {
1211
- const nodeOrdinalPath = [];
1382
+ let pathLength = 0;
1212
1383
  let nodeOrdinal = startNodeOrdinal;
1213
1384
  while (ordinalToForestAncestorOrdinal[nodeOrdinal] !== -1 && ordinalToForestAncestorOrdinal[ordinalToForestAncestorOrdinal[nodeOrdinal]] !== -1) {
1214
- nodeOrdinalPath.push(nodeOrdinal);
1385
+ ancestorNodeOrdinalPath[pathLength++] = nodeOrdinal;
1215
1386
  nodeOrdinal = ordinalToForestAncestorOrdinal[nodeOrdinal];
1216
1387
  }
1217
- for (let pathIndex = nodeOrdinalPath.length - 1; pathIndex >= 0; pathIndex--) {
1218
- const pathNodeOrdinal = nodeOrdinalPath[pathIndex];
1388
+ for (let pathIndex = pathLength - 1; pathIndex >= 0; pathIndex--) {
1389
+ const pathNodeOrdinal = ancestorNodeOrdinalPath[pathIndex];
1219
1390
  const ancestorOrdinal = ordinalToForestAncestorOrdinal[pathNodeOrdinal];
1220
1391
  if (ordinalToSemidominatorDfsIndex[ordinalToMinSemiAncestorOrdinal[ancestorOrdinal]] < ordinalToSemidominatorDfsIndex[ordinalToMinSemiAncestorOrdinal[pathNodeOrdinal]]) ordinalToMinSemiAncestorOrdinal[pathNodeOrdinal] = ordinalToMinSemiAncestorOrdinal[ancestorOrdinal];
1221
1392
  ordinalToForestAncestorOrdinal[pathNodeOrdinal] = ordinalToForestAncestorOrdinal[ancestorOrdinal];
@@ -1226,69 +1397,155 @@ const computeImmediateDominatorGraph = (snapshot, { ordinalToSuccessors, ordinal
1226
1397
  compressAncestorPath(nodeOrdinal);
1227
1398
  return ordinalToMinSemiAncestorOrdinal[nodeOrdinal];
1228
1399
  };
1400
+ const pendingHeadOrdinals = new Int32Array(nodeCount).fill(-1);
1401
+ const pendingNextOrdinals = new Int32Array(nodeCount).fill(-1);
1229
1402
  for (let dfsIndex = reachableCount - 1; dfsIndex >= 1; dfsIndex--) {
1230
1403
  const nodeOrdinal = dfsIndexToOrdinal[dfsIndex];
1231
- for (const { targetNodeOrdinal: predecessorOrdinal } of ordinalToPredecessors[nodeOrdinal]) {
1404
+ const predecessorStartOffset = ordinalToPredecessorStartOffset[nodeOrdinal];
1405
+ const predecessorEndOffset = ordinalToPredecessorStartOffset[nodeOrdinal + 1];
1406
+ for (let predecessorOffset = predecessorStartOffset; predecessorOffset < predecessorEndOffset; predecessorOffset++) {
1407
+ const predecessorOrdinal = offsetToPredecessorOrdinal[predecessorOffset];
1232
1408
  if (ordinalToDfsIndex[predecessorOrdinal] === -1) continue;
1233
1409
  const minAncestorOrdinal = minSemiAncestorOrdinal(predecessorOrdinal);
1234
1410
  if (ordinalToSemidominatorDfsIndex[minAncestorOrdinal] < ordinalToSemidominatorDfsIndex[nodeOrdinal]) ordinalToSemidominatorDfsIndex[nodeOrdinal] = ordinalToSemidominatorDfsIndex[minAncestorOrdinal];
1235
1411
  }
1236
- ordinalToPendingOrdinals[dfsIndexToOrdinal[ordinalToSemidominatorDfsIndex[nodeOrdinal]]].push(nodeOrdinal);
1412
+ const semiBucketOrdinal = dfsIndexToOrdinal[ordinalToSemidominatorDfsIndex[nodeOrdinal]];
1413
+ pendingNextOrdinals[nodeOrdinal] = pendingHeadOrdinals[semiBucketOrdinal];
1414
+ pendingHeadOrdinals[semiBucketOrdinal] = nodeOrdinal;
1237
1415
  ordinalToForestAncestorOrdinal[nodeOrdinal] = ordinalToParentOrdinal[nodeOrdinal];
1238
- for (const pendingOrdinal of ordinalToPendingOrdinals[ordinalToParentOrdinal[nodeOrdinal]]) {
1416
+ const parentOrdinal = ordinalToParentOrdinal[nodeOrdinal];
1417
+ let pendingOrdinal = pendingHeadOrdinals[parentOrdinal];
1418
+ pendingHeadOrdinals[parentOrdinal] = -1;
1419
+ while (pendingOrdinal !== -1) {
1420
+ const nextPending = pendingNextOrdinals[pendingOrdinal];
1239
1421
  const ancestorOrdinal = minSemiAncestorOrdinal(pendingOrdinal);
1240
- ordinalToImmediateDominatorOrdinal[pendingOrdinal] = ordinalToSemidominatorDfsIndex[ancestorOrdinal] < ordinalToSemidominatorDfsIndex[pendingOrdinal] ? ancestorOrdinal : ordinalToParentOrdinal[nodeOrdinal];
1422
+ ordinalToImmediateDominatorOrdinal[pendingOrdinal] = ordinalToSemidominatorDfsIndex[ancestorOrdinal] < ordinalToSemidominatorDfsIndex[pendingOrdinal] ? ancestorOrdinal : parentOrdinal;
1423
+ pendingOrdinal = nextPending;
1241
1424
  }
1242
- ordinalToPendingOrdinals[ordinalToParentOrdinal[nodeOrdinal]].length = 0;
1243
1425
  }
1244
1426
  for (let dfsIndex = 1; dfsIndex < reachableCount; dfsIndex++) {
1245
1427
  const nodeOrdinal = dfsIndexToOrdinal[dfsIndex];
1246
1428
  if (ordinalToImmediateDominatorOrdinal[nodeOrdinal] !== dfsIndexToOrdinal[ordinalToSemidominatorDfsIndex[nodeOrdinal]]) ordinalToImmediateDominatorOrdinal[nodeOrdinal] = ordinalToImmediateDominatorOrdinal[ordinalToImmediateDominatorOrdinal[nodeOrdinal]];
1247
1429
  }
1248
1430
  ordinalToImmediateDominatorOrdinal[0] = 0;
1431
+ const dominatorOrdinalToDominateeCount = new Int32Array(nodeCount);
1432
+ for (let nodeOrdinal = 1; nodeOrdinal < nodeCount; nodeOrdinal++) {
1433
+ const dominatorOrdinal = ordinalToImmediateDominatorOrdinal[nodeOrdinal];
1434
+ if (dominatorOrdinal !== -1) dominatorOrdinalToDominateeCount[dominatorOrdinal]++;
1435
+ }
1436
+ const immediateDominateeOrdinalToStartOffset = new Int32Array(nodeCount + 1);
1437
+ for (let offset = 0; offset < nodeCount; offset++) immediateDominateeOrdinalToStartOffset[offset + 1] = immediateDominateeOrdinalToStartOffset[offset] + dominatorOrdinalToDominateeCount[offset];
1438
+ const offsetToImmediateDominateeOrdinal = new Int32Array(immediateDominateeOrdinalToStartOffset[nodeCount]);
1439
+ dominatorOrdinalToDominateeCount.fill(0);
1440
+ for (let nodeOrdinal = 1; nodeOrdinal < nodeCount; nodeOrdinal++) {
1441
+ const dominatorOrdinal = ordinalToImmediateDominatorOrdinal[nodeOrdinal];
1442
+ if (dominatorOrdinal !== -1) {
1443
+ offsetToImmediateDominateeOrdinal[immediateDominateeOrdinalToStartOffset[dominatorOrdinal] + dominatorOrdinalToDominateeCount[dominatorOrdinal]] = nodeOrdinal;
1444
+ dominatorOrdinalToDominateeCount[dominatorOrdinal]++;
1445
+ }
1446
+ }
1249
1447
  return {
1448
+ dfsIndexToOrdinal,
1250
1449
  ordinalToImmediateDominatorOrdinal,
1251
- dfsIndexToOrdinal
1450
+ immediateDominateeOrdinalToStartOffset,
1451
+ offsetToImmediateDominateeOrdinal
1252
1452
  };
1253
1453
  };
1254
- const computeNodeOrdinalToRetainedSize = ({ nodes }, { ordinalToImmediateDominatorOrdinal, dfsIndexToOrdinal }, { nodeFieldCount, nodeSelfSizeOffset }) => {
1454
+ const computeNodeOrdinalToRetainedSize = ({ nodes }, { dfsIndexToOrdinal, ordinalToImmediateDominatorOrdinal }, { nodeFieldCount, nodeSelfSizeOffset }) => {
1255
1455
  const nodeOrdinalToRetainedSize = new Float64Array(ordinalToImmediateDominatorOrdinal.length);
1256
1456
  for (let nodeOrdinal = 0; nodeOrdinal < nodeOrdinalToRetainedSize.length; nodeOrdinal++) nodeOrdinalToRetainedSize[nodeOrdinal] = nodes[nodeOrdinal * nodeFieldCount + nodeSelfSizeOffset];
1257
1457
  for (let dfsIndex = dfsIndexToOrdinal.length - 1; dfsIndex >= 1; dfsIndex--) {
1258
- const dominatedNodeOrdinal = dfsIndexToOrdinal[dfsIndex];
1259
- nodeOrdinalToRetainedSize[ordinalToImmediateDominatorOrdinal[dominatedNodeOrdinal]] += nodeOrdinalToRetainedSize[dominatedNodeOrdinal];
1458
+ const dominateeOrdinal = dfsIndexToOrdinal[dfsIndex];
1459
+ nodeOrdinalToRetainedSize[ordinalToImmediateDominatorOrdinal[dominateeOrdinal]] += nodeOrdinalToRetainedSize[dominateeOrdinal];
1260
1460
  }
1261
1461
  return nodeOrdinalToRetainedSize;
1262
1462
  };
1263
- const computeRetainerPath = (nodeOrdinal, { snapshot: { meta: { node_types: [nodeTypes] } }, nodes, edges, strings }, { ordinalToPredecessors }, nodeIndexToLocation, { ordinalToImmediateDominatorOrdinal }, fieldLayout) => {
1463
+ const computeRetainerPath = (nodeOrdinal, snapshot, { ordinalToPredecessorStartOffset, offsetToPredecessorOrdinal, offsetToPredecessorEdgeIndex }, nodeIndexToLocation, { ordinalToImmediateDominatorOrdinal }, fieldLayout, options) => {
1464
+ const { nodes } = snapshot;
1264
1465
  const hops = [];
1265
1466
  while (true) {
1266
- const predecessors = ordinalToPredecessors[nodeOrdinal];
1267
- if (predecessors.length === 0) break;
1467
+ const predecessorStartOffset = ordinalToPredecessorStartOffset[nodeOrdinal];
1468
+ const predecessorEndOffset = ordinalToPredecessorStartOffset[nodeOrdinal + 1];
1469
+ if (predecessorStartOffset === predecessorEndOffset) break;
1268
1470
  const dominatorOrdinal = ordinalToImmediateDominatorOrdinal[nodeOrdinal];
1269
- const predecessor = predecessors.find(({ targetNodeOrdinal }) => targetNodeOrdinal === dominatorOrdinal);
1270
- if (!predecessor) {
1471
+ let predecessorOffset = -1;
1472
+ for (let offset = predecessorStartOffset; offset < predecessorEndOffset; offset++) if (offsetToPredecessorOrdinal[offset] === dominatorOrdinal) {
1473
+ predecessorOffset = offset;
1474
+ break;
1475
+ }
1476
+ if (predecessorOffset === -1) {
1271
1477
  nodeOrdinal = dominatorOrdinal;
1272
1478
  continue;
1273
1479
  }
1274
- const { targetNodeOrdinal, edgeIndex } = predecessor;
1275
- const edgeType = edges[edgeIndex + fieldLayout.edgeTypeOffset];
1276
- const edgeNameOrIndex = edges[edgeIndex + fieldLayout.edgeNameOrIndexOffset];
1277
- const edgeLabel = edgeType === fieldLayout.edgeTypeElement ? `[${edgeNameOrIndex}]` : `.${strings[edgeNameOrIndex]}`;
1278
- const retainerIndex = targetNodeOrdinal * fieldLayout.nodeFieldCount;
1480
+ const edgeIndex = offsetToPredecessorEdgeIndex[predecessorOffset];
1481
+ const edgeLabel = formatEdgeLabel(edgeIndex, snapshot, fieldLayout, options);
1482
+ const predecessorOrdinal = offsetToPredecessorOrdinal[predecessorOffset];
1483
+ const retainerIndex = predecessorOrdinal * fieldLayout.nodeFieldCount;
1279
1484
  const retainerType = nodes[retainerIndex + fieldLayout.nodeTypeOffset];
1280
- const retainerName = strings[nodes[retainerIndex + fieldLayout.nodeNameOffset]] || nodeTypes[retainerType];
1485
+ const retainerLabel = formatNodeLabel(retainerIndex, snapshot, fieldLayout, options);
1281
1486
  const retainerLocation = nodeIndexToLocation.get(retainerIndex);
1282
1487
  hops.push({
1283
- label: `${edgeLabel} ${retainerName}${retainerLocation ? ` (${retainerLocation})` : ``}`,
1284
- internal: retainerType === fieldLayout.nodeTypeSynthetic || retainerType === fieldLayout.nodeTypeHidden
1488
+ label: `${edgeLabel} ${retainerLabel}${retainerLocation ? ` (${retainerLocation})` : ``}`,
1489
+ internal: isInternalNodeType(retainerType, fieldLayout)
1285
1490
  });
1286
- nodeOrdinal = targetNodeOrdinal;
1491
+ nodeOrdinal = predecessorOrdinal;
1287
1492
  }
1288
1493
  while (hops.at(-1)?.internal) hops.pop();
1289
1494
  if (hops.length === 0) return `(GC root)`;
1290
1495
  return hops.map((hop) => hop.label).join(` ← `);
1291
1496
  };
1497
+ const computeRetainedNodes = (nodeOrdinal, snapshot, nodeOrdinalToRetainedSize, { immediateDominateeOrdinalToStartOffset, offsetToImmediateDominateeOrdinal }, fieldLayout, options) => {
1498
+ const { nodes } = snapshot;
1499
+ const retainedNodes = [];
1500
+ const dominateeOrdinals = [];
1501
+ const childStartOffset = immediateDominateeOrdinalToStartOffset[nodeOrdinal];
1502
+ const childEndOffset = immediateDominateeOrdinalToStartOffset[nodeOrdinal + 1];
1503
+ for (let offset = childStartOffset; offset < childEndOffset; offset++) dominateeOrdinals.push(offsetToImmediateDominateeOrdinal[offset]);
1504
+ while (dominateeOrdinals.length > 0) {
1505
+ const nodeOrdinal = dominateeOrdinals.pop();
1506
+ const nodeIndex = nodeOrdinal * fieldLayout.nodeFieldCount;
1507
+ const nodeType = nodes[nodeIndex + fieldLayout.nodeTypeOffset];
1508
+ if (!isInternalNodeType(nodeType, fieldLayout)) retainedNodes.push({
1509
+ id: nodeOrdinal,
1510
+ name: formatNodeLabel(nodeIndex, snapshot, fieldLayout, options),
1511
+ selfSize: nodes[nodeIndex + fieldLayout.nodeSelfSizeOffset],
1512
+ retainedSize: nodeOrdinalToRetainedSize[nodeOrdinal]
1513
+ });
1514
+ const dominateeStartOffset = immediateDominateeOrdinalToStartOffset[nodeOrdinal];
1515
+ const dominateeEndOffset = immediateDominateeOrdinalToStartOffset[nodeOrdinal + 1];
1516
+ for (let offset = dominateeStartOffset; offset < dominateeEndOffset; offset++) dominateeOrdinals.push(offsetToImmediateDominateeOrdinal[offset]);
1517
+ }
1518
+ return retainedNodes;
1519
+ };
1520
+ const isInternalNodeType = (nodeType, fieldLayout) => nodeType === fieldLayout.nodeTypeHidden || nodeType === fieldLayout.nodeTypeSynthetic;
1521
+ const formatEdgeLabel = (edgeIndex, { edges, strings }, fieldLayout, options) => {
1522
+ const edgeType = edges[edgeIndex + fieldLayout.edgeTypeOffset];
1523
+ const edgeNameOrIndex = edges[edgeIndex + fieldLayout.edgeNameOrIndexOffset];
1524
+ if (edgeType === fieldLayout.edgeTypeElement) return `[${edgeNameOrIndex}]`;
1525
+ const rawEdgeName = strings[edgeNameOrIndex];
1526
+ return `.${formatLocation(rawEdgeName, options) ?? rawEdgeName}`;
1527
+ };
1528
+ const formatNodeLabel = (nodeIndex, { snapshot: { meta: { node_types: [nodeTypes] } }, nodes, strings }, fieldLayout, options) => {
1529
+ const nodeType = nodes[nodeIndex + fieldLayout.nodeTypeOffset];
1530
+ switch (nodeType) {
1531
+ case fieldLayout.nodeTypeString:
1532
+ case fieldLayout.nodeTypeSlicedString:
1533
+ case fieldLayout.nodeTypeConcatenatedString: {
1534
+ const string = strings[nodes[nodeIndex + fieldLayout.nodeNameOffset]];
1535
+ return formatString(string);
1536
+ }
1537
+ case fieldLayout.nodeTypeClosure: return strings[nodes[nodeIndex + fieldLayout.nodeNameOffset]] || `(anonymous)`;
1538
+ default: {
1539
+ const rawNodeName = strings[nodes[nodeIndex + fieldLayout.nodeNameOffset]] || nodeTypes[nodeType];
1540
+ return formatLocation(rawNodeName, options) ?? rawNodeName;
1541
+ }
1542
+ }
1543
+ };
1544
+ const formatString = (string) => {
1545
+ if (string.length > MAX_STRING_LENGTH) string = `${string.slice(0, MAX_STRING_LENGTH - 1)}…`;
1546
+ return string.replaceAll(`\n`, `\\n`);
1547
+ };
1548
+ const MAX_STRING_LENGTH = 50;
1292
1549
  /**
1293
1550
  * Attributes retained sizes to groups of nodes without double-counting.
1294
1551
  *
@@ -1301,38 +1558,31 @@ const computeRetainerPath = (nodeOrdinal, { snapshot: { meta: { node_types: [nod
1301
1558
  * Inner instances are entirely contained within the outer one's retained set,
1302
1559
  * so they add nothing.
1303
1560
  */
1304
- const attributeGroupRetainedSizes = ({ nodeOrdinalToRetainedSize, ordinalToImmediateDominatorOrdinal, nodeOrdinalToGroup }) => {
1305
- const dominatorOrdinalToChildOrdinals = Array.from({ length: ordinalToImmediateDominatorOrdinal.length }, () => []);
1306
- for (let nodeOrdinal = 1; nodeOrdinal < ordinalToImmediateDominatorOrdinal.length; nodeOrdinal++) {
1307
- const dominatorOrdinal = ordinalToImmediateDominatorOrdinal[nodeOrdinal];
1308
- if (dominatorOrdinal !== -1) dominatorOrdinalToChildOrdinals[dominatorOrdinal].push(nodeOrdinal);
1309
- }
1310
- const groupPathDepth = /* @__PURE__ */ new Map();
1311
- const stack = [{
1312
- nodeOrdinal: 0,
1313
- entering: true
1314
- }];
1561
+ const attributeGroupRetainedSizes = (nodeOrdinalToRetainedSize, { immediateDominateeOrdinalToStartOffset, offsetToImmediateDominateeOrdinal }, nodeOrdinalToSummarizedNodeIndex, summarizedNodes) => {
1562
+ const nodeCount = nodeOrdinalToRetainedSize.length;
1563
+ const groupPathDepth = new Int32Array(summarizedNodes.length);
1564
+ const stack = new Int32Array(nodeCount * 2 + 1);
1565
+ stack[0] = 0;
1566
+ let topOffset = 1;
1315
1567
  do {
1316
- const { nodeOrdinal, entering } = stack.pop();
1317
- const group = nodeOrdinalToGroup.get(nodeOrdinal);
1318
- if (!entering) {
1319
- if (group) groupPathDepth.set(group, groupPathDepth.get(group) - 1);
1568
+ const encodedNodeOrdinal = stack[--topOffset];
1569
+ if (encodedNodeOrdinal < 0) {
1570
+ const constructorIndex = nodeOrdinalToSummarizedNodeIndex[~encodedNodeOrdinal];
1571
+ if (constructorIndex !== -1) groupPathDepth[constructorIndex] = groupPathDepth[constructorIndex] - 1;
1320
1572
  continue;
1321
1573
  }
1322
- if (group) {
1323
- const depth = groupPathDepth.get(group) ?? 0;
1324
- if (depth === 0) group.retainedSize += nodeOrdinalToRetainedSize[nodeOrdinal];
1325
- groupPathDepth.set(group, depth + 1);
1326
- stack.push({
1327
- nodeOrdinal,
1328
- entering: false
1329
- });
1574
+ const nodeOrdinal = encodedNodeOrdinal;
1575
+ const summarizedNodeIndex = nodeOrdinalToSummarizedNodeIndex[nodeOrdinal];
1576
+ if (summarizedNodeIndex !== -1) {
1577
+ const depth = groupPathDepth[summarizedNodeIndex];
1578
+ if (depth === 0) summarizedNodes[summarizedNodeIndex].retainedSize += nodeOrdinalToRetainedSize[nodeOrdinal];
1579
+ groupPathDepth[summarizedNodeIndex] = depth + 1;
1580
+ stack[topOffset++] = ~nodeOrdinal;
1330
1581
  }
1331
- for (const childOrdinal of dominatorOrdinalToChildOrdinals[nodeOrdinal]) stack.push({
1332
- nodeOrdinal: childOrdinal,
1333
- entering: true
1334
- });
1335
- } while (stack.length > 0);
1582
+ const dominateeStartOffset = immediateDominateeOrdinalToStartOffset[nodeOrdinal];
1583
+ const dominateeEndOffset = immediateDominateeOrdinalToStartOffset[nodeOrdinal + 1];
1584
+ for (let offset = dominateeStartOffset; offset < dominateeEndOffset; offset++) stack[topOffset++] = offsetToImmediateDominateeOrdinal[offset];
1585
+ } while (topOffset > 0);
1336
1586
  };
1337
1587
  const computeFieldLayout = (meta) => {
1338
1588
  const { node_fields: nodeFields, node_types: [nodeTypes], edge_fields: edgeFields, edge_types: [edgeTypes], location_fields: locationFields } = meta;