profiler-md 0.0.1 → 0.1.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.
package/dist/cli.mjs CHANGED
@@ -1,18 +1,144 @@
1
1
  #!/usr/bin/env node
2
2
  import { createWriteStream } from "node:fs";
3
3
  import { readFile } from "node:fs/promises";
4
- import { extname } from "node:path";
4
+ import { promisify } from "node:util";
5
+ import { brotliDecompress, gunzip } from "node:zlib";
5
6
  import meow from "meow";
6
7
  import picomatch from "picomatch";
8
+ import { Profile } from "pprof-format";
9
+ import plur from "plur";
7
10
  import prettyBytes from "pretty-bytes";
8
11
  import prettyMilliseconds from "pretty-ms";
9
12
 
10
- //#region src/internal/markdown.ts
11
- const inlineCode = (text) => {
12
- const longestBacktickRun = Math.max(0, ...Array.from(text.matchAll(/`+/gu), (match) => match[0].length));
13
- const fence = `\``.repeat(longestBacktickRun + 1);
14
- return `${fence}${text.startsWith(`\``) || text.endsWith(`\``) ? ` ${text} ` : text}${fence}`;
13
+ //#region src/helpers/array.ts
14
+ /**
15
+ * A {@link TypedArray} wrapper that's growable.
16
+ *
17
+ * It's mainly useful when the indices are sequential IDs that arrive out of
18
+ * order and with the maximum unknown.
19
+ */
20
+ var DynamicTypedArray = class {
21
+ #array;
22
+ #arrayConstructor;
23
+ constructor(initialArray) {
24
+ this.#array = initialArray;
25
+ this.#arrayConstructor = initialArray.constructor;
26
+ }
27
+ ensureCapacity(minLength) {
28
+ if (minLength > this.#array.length) {
29
+ const grown = new this.#arrayConstructor(Math.max(minLength, this.#array.length * 2));
30
+ grown.set(this.#array);
31
+ this.#array = grown;
32
+ }
33
+ return this.#array;
34
+ }
35
+ };
36
+
37
+ //#endregion
38
+ //#region src/options.ts
39
+ const normalizeProfileToMdOptions = ({ topN = 20, includeEntry = defaultIncludeEntry, isThirdPartyEntry = defaultIsThirdPartyEntry, cwd } = {}) => {
40
+ if (cwd === void 0 && typeof process !== `undefined`) cwd = process.cwd();
41
+ if (cwd != null && !cwd.endsWith(`/`)) cwd = `${cwd}/`;
42
+ return {
43
+ topN,
44
+ includeEntry: cacheEntryFunction(includeEntry),
45
+ isThirdPartyEntry: cacheEntryFunction(isThirdPartyEntry),
46
+ cwd: cwd ?? void 0
47
+ };
48
+ };
49
+ const cacheEntryFunction = (func) => {
50
+ const cache = new DynamicTypedArray(new Uint8Array(256));
51
+ return (entry) => {
52
+ const { id } = entry;
53
+ const array = cache.ensureCapacity(id + 1);
54
+ const value = array[id];
55
+ if (value !== 0) return value === 2;
56
+ const result = func(entry);
57
+ array[id] = result ? 2 : 1;
58
+ return result;
59
+ };
60
+ };
61
+ /**
62
+ * Returns whether to include the given entry in the Markdown output.
63
+ *
64
+ * Excludes synthetic profile data and redundant internals by default.
65
+ */
66
+ const defaultIncludeEntry = ({ name, location }) => {
67
+ if (name === `(root)` || name === `(module)`) return false;
68
+ if (!location && (name === `ModuleWrap` || name.startsWith(`system /`) || name.startsWith(`Node /`)) || location?.url.protocol === `node:` && location.url.pathname.startsWith(`internal/`)) return false;
69
+ return true;
70
+ };
71
+ /**
72
+ * Returns whether the given entry points to third-party code.
73
+ *
74
+ * Excludes `node_modules` only by default.
75
+ */
76
+ const defaultIsThirdPartyEntry = (entry) => !!entry.location?.url.pathname.includes(`/node_modules/`);
77
+
78
+ //#endregion
79
+ //#region src/helpers/format.ts
80
+ const formatCount = (count, unit) => count.toLocaleString(`en-US`) + (unit ? ` ${plur(unit, count)}` : ``);
81
+ const formatMilliseconds = (milliseconds) => prettyMilliseconds(milliseconds, {
82
+ secondsDecimalDigits: 2,
83
+ millisecondsDecimalDigits: 1,
84
+ unitCount: 2
85
+ });
86
+ const formatMicrosecondsExact = (microseconds) => `${microseconds.toFixed(1)}µs`;
87
+ const formatBytes = (bytes) => prettyBytes(bytes, { nonBreakingSpace: true });
88
+ const formatPercent = (fraction) => `${(fraction * 100).toFixed(1)}%`;
89
+ const formatConjunction = (strings) => (conjunctionFormatter ??= new Intl.ListFormat(`en`, {
90
+ style: `long`,
91
+ type: `conjunction`
92
+ })).format(strings);
93
+ let conjunctionFormatter;
94
+
95
+ //#endregion
96
+ //#region src/helpers/heap.ts
97
+ var MaxHeap = class {
98
+ #heap;
99
+ #size;
100
+ #compare;
101
+ constructor(values, compare) {
102
+ this.#heap = [...values.entries()];
103
+ this.#size = this.#heap.length;
104
+ this.#compare = ([index1, value1], [index2, value2]) => {
105
+ const result = compare(value1, value2);
106
+ return result === 0 ? index2 - index1 : result;
107
+ };
108
+ for (let i = Math.floor(this.#size / 2) - 1; i >= 0; i--) this.#siftDown(i);
109
+ }
110
+ get length() {
111
+ return this.#size;
112
+ }
113
+ pop() {
114
+ if (this.#size === 0) return;
115
+ const max = this.#heap[0][1];
116
+ this.#heap[0] = this.#heap[--this.#size];
117
+ this.#siftDown(0);
118
+ return max;
119
+ }
120
+ #siftDown(i) {
121
+ while (true) {
122
+ let largest = 2 * i + 1;
123
+ if (largest >= this.#size) break;
124
+ const right = largest + 1;
125
+ if (right < this.#size && this.#compare(this.#heap[right], this.#heap[largest]) > 0) largest = right;
126
+ if (this.#compare(this.#heap[largest], this.#heap[i]) <= 0) break;
127
+ [this.#heap[i], this.#heap[largest]] = [this.#heap[largest], this.#heap[i]];
128
+ i = largest;
129
+ }
130
+ }
131
+ };
132
+ const selectTopN = (values, topN, compare) => {
133
+ if (topN === 0) return [];
134
+ if (values.length <= topN) return values.toSorted((value1, value2) => compare(value2, value1));
135
+ const heap = new MaxHeap(values, compare);
136
+ return Array.from({ length: topN }, () => heap.pop());
15
137
  };
138
+
139
+ //#endregion
140
+ //#region src/helpers/markdown.ts
141
+ const formatHeading = (level, content) => `${`#`.repeat(level)} ${content}`;
16
142
  const formatTable = (headers, rows) => {
17
143
  const headerContents = headers.map((header) => typeof header === `string` ? header : header.content);
18
144
  const allRows = [headerContents, ...rows];
@@ -27,178 +153,383 @@ const formatTable = (headers, rows) => {
27
153
  ...rows.map(formatRow)
28
154
  ].join(`\n`);
29
155
  };
156
+ const inlineCode = (text) => {
157
+ const longestBacktickRun = Math.max(0, ...Array.from(text.matchAll(/`+/gu), (match) => match[0].length));
158
+ const fence = `\``.repeat(longestBacktickRun + 1);
159
+ return `${fence}${text.startsWith(`\``) || text.endsWith(`\``) ? ` ${text} ` : text}${fence}`;
160
+ };
30
161
 
31
162
  //#endregion
32
- //#region src/v8/common.ts
33
- /**
34
- * Returns whether to include the given call frame in the Markdown output.
35
- *
36
- * This is the default value for {@link V8ProfileToMdOptions.includeCallFrame}.
37
- *
38
- * It makes reasonable assumptions about which call frames are uninteresting to
39
- * display. For example, Node internals related to ESM loading are excluded.
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;
45
- return true;
46
- };
163
+ //#region src/location.ts
47
164
  /**
48
- * Returns whether the given URL points to third-party code.
49
- *
50
- * This is the default value for {@link V8ProfileToMdOptions.isThirdPartyURL}.
51
- *
52
- * Excludes `node_modules` only by default.
165
+ * Converts a {@link ProfileLocationInput} or a {@link ProfileLocation} or
166
+ * returns undefined if it's not a valid location.
53
167
  */
54
- const defaultIsThirdPartyURL = (url) => url.pathname.includes(`/node_modules/`);
55
- const normalizeV8ProfileToMdOptions = ({ topN = 20, includeCallFrame = defaultIncludeCallFrame, isThirdPartyURL = defaultIsThirdPartyURL, cwd } = {}) => {
56
- if (cwd === void 0 && typeof process !== `undefined`) cwd = process.cwd();
57
- if (cwd != null && !cwd.endsWith(`/`)) cwd = `${cwd}/`;
58
- const includeCallFrameCache = /* @__PURE__ */ new Map();
59
- const isThirdPartyUrlCache = /* @__PURE__ */ new Map();
60
- return {
61
- topN,
62
- includeCallFrame: (node) => {
63
- let result = includeCallFrameCache.get(node.id);
64
- if (result !== void 0) return result;
65
- result = includeCallFrame(toPublicCallFrame(node.callFrame));
66
- includeCallFrameCache.set(node.id, result);
67
- return result;
68
- },
69
- isThirdPartyURL: (url) => {
70
- const { href } = url;
71
- let result = isThirdPartyUrlCache.get(href);
72
- if (result !== void 0) return result;
73
- result = isThirdPartyURL(url);
74
- isThirdPartyUrlCache.set(href, result);
75
- return result;
76
- },
77
- cwd: cwd ?? void 0
78
- };
79
- };
80
- const toPublicCallFrame = (callFrame) => {
81
- let url;
82
- try {
83
- url = new URL(callFrame.url);
84
- } 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);
168
+ const makeProfileLocation = ({ urlOrPath, line, column }) => {
169
+ if (!urlOrPath) return;
170
+ if (urlOrPath.startsWith(`/`)) try {
171
+ return {
172
+ url: new URL(`file://${urlOrPath}`),
173
+ line,
174
+ column
175
+ };
94
176
  } catch {
95
- return url || void 0;
177
+ return;
96
178
  }
97
- if (urlObject.protocol !== `file:`) return url || void 0;
98
- let path = urlObject.pathname;
99
- if (cwd !== void 0 && path.startsWith(cwd)) path = path.slice(cwd.length);
100
- return path;
101
- };
102
- const categorizeCallFrame = (callFrame, { isThirdPartyURL }) => {
103
- if (!callFrame.url) {
104
- const { functionName } = callFrame;
105
- if (functionName.startsWith(`(`) && functionName.endsWith(`)`)) return functionName.slice(1, -1);
106
- if (functionName.startsWith(`RegExp: `)) return `regexp`;
107
- return `native`;
108
- }
109
- let urlObject;
179
+ if (!urlOrPath.includes(`:`)) return;
110
180
  try {
111
- urlObject = new URL(callFrame.url);
181
+ return {
182
+ url: new URL(urlOrPath),
183
+ line,
184
+ column
185
+ };
112
186
  } catch {
113
- return `native`;
187
+ return;
188
+ }
189
+ };
190
+ const formatProfileLocation = (location, { cwd }) => {
191
+ if (!location) return inlineCode(`<native>`);
192
+ let path;
193
+ if (location.url.protocol === `file:`) {
194
+ path = location.url.pathname;
195
+ if (cwd !== void 0 && path.startsWith(cwd)) path = path.slice(cwd.length);
196
+ } else path = location.url.href;
197
+ if (location.line !== void 0) {
198
+ path += `:${location.line}`;
199
+ if (location.column !== void 0) path += `:${location.column}`;
200
+ }
201
+ return path || inlineCode(`<native>`);
202
+ };
203
+
204
+ //#endregion
205
+ //#region src/profile/summarize.ts
206
+ var ProfileBuilder = class {
207
+ #metrics;
208
+ #functionKey;
209
+ #functionInput;
210
+ #options;
211
+ #totalSampleCount;
212
+ #totalValues;
213
+ #categoryToMetrics;
214
+ #keyToCallStack;
215
+ #keyToFunction;
216
+ #idToFunction;
217
+ #functionIdToLastSeenSampleCount;
218
+ #frameIndexToFramePairKey;
219
+ constructor({ metrics, functionKey, functionInput }, options) {
220
+ this.#metrics = metrics;
221
+ this.#functionKey = functionKey;
222
+ this.#functionInput = functionInput;
223
+ this.#options = options;
224
+ this.#totalSampleCount = 0;
225
+ this.#totalValues = new Float64Array(this.#metrics.length);
226
+ this.#categoryToMetrics = /* @__PURE__ */ new Map();
227
+ this.#keyToCallStack = /* @__PURE__ */ new Map();
228
+ this.#keyToFunction = /* @__PURE__ */ new Map();
229
+ this.#idToFunction = [];
230
+ this.#functionIdToLastSeenSampleCount = new DynamicTypedArray(new Uint32Array(1));
231
+ this.#frameIndexToFramePairKey = new DynamicTypedArray(new Int32Array(64));
232
+ }
233
+ /** Adds a single profile sample. */
234
+ addSample({ values, nodes, line }) {
235
+ if (nodes.length === 0) return;
236
+ const callStack = this.#getOrCreateCallStack(nodes);
237
+ const callee = callStack.frames[0];
238
+ const caller = callStack.frames[1];
239
+ let categoryMetrics = this.#categoryToMetrics.get(callee.category);
240
+ if (!categoryMetrics) {
241
+ categoryMetrics = {
242
+ sampleCount: 0,
243
+ values: new Float64Array(this.#metrics.length)
244
+ };
245
+ this.#categoryToMetrics.set(callee.category, categoryMetrics);
246
+ }
247
+ let callerMetrics;
248
+ if (caller) {
249
+ callerMetrics = callee.callerIdToMetrics.get(caller.id);
250
+ if (!callerMetrics) {
251
+ callerMetrics = {
252
+ caller,
253
+ selfSampleCount: 0,
254
+ selfValues: new Float64Array(this.#metrics.length)
255
+ };
256
+ callee.callerIdToMetrics.set(caller.id, callerMetrics);
257
+ }
258
+ }
259
+ let lineMetrics;
260
+ if (line !== void 0) {
261
+ lineMetrics = callee.lineToMetrics.get(line);
262
+ if (!lineMetrics) {
263
+ lineMetrics = {
264
+ sampleCount: 0,
265
+ values: new Float64Array(this.#metrics.length)
266
+ };
267
+ callee.lineToMetrics.set(line, lineMetrics);
268
+ }
269
+ }
270
+ this.#totalSampleCount++;
271
+ categoryMetrics.sampleCount++;
272
+ callStack.selfSampleCount++;
273
+ callee.selfSampleCount++;
274
+ if (callerMetrics) callerMetrics.selfSampleCount++;
275
+ if (lineMetrics) lineMetrics.sampleCount++;
276
+ for (let i = 0; i < values.length; i++) {
277
+ this.#totalValues[i] += values[i];
278
+ categoryMetrics.values[i] += values[i];
279
+ callStack.selfValues[i] += values[i];
280
+ callee.selfValues[i] += values[i];
281
+ if (callerMetrics) callerMetrics.selfValues[i] += values[i];
282
+ if (lineMetrics) lineMetrics.values[i] += values[i];
283
+ }
284
+ const funcCount = this.#keyToFunction.size;
285
+ const functionIdToLastSeenSampleCount = this.#functionIdToLastSeenSampleCount.ensureCapacity(funcCount);
286
+ for (const func of callStack.frames) {
287
+ if (functionIdToLastSeenSampleCount[func.id] === this.#totalSampleCount) continue;
288
+ functionIdToLastSeenSampleCount[func.id] = this.#totalSampleCount;
289
+ func.totalSampleCount++;
290
+ for (let i = 0; i < values.length; i++) func.totalValues[i] += values[i];
291
+ }
292
+ const maxFramePairCount = callStack.frames.length - 1;
293
+ const frameIndexToFramePairKey = this.#frameIndexToFramePairKey.ensureCapacity(maxFramePairCount);
294
+ let seenFramePairCount = 0;
295
+ for (let i = 0; i < maxFramePairCount; i++) {
296
+ const callee = callStack.frames[i];
297
+ const caller = callStack.frames[i + 1];
298
+ const pairKey = caller.id * funcCount + callee.id;
299
+ let pairAlreadySeen = false;
300
+ for (let j = 0; j < seenFramePairCount; j++) if (frameIndexToFramePairKey[j] === pairKey) {
301
+ pairAlreadySeen = true;
302
+ break;
303
+ }
304
+ if (pairAlreadySeen) continue;
305
+ frameIndexToFramePairKey[seenFramePairCount++] = pairKey;
306
+ let calleeMetrics = caller.calleeIdToMetrics.get(callee.id);
307
+ if (!calleeMetrics) {
308
+ calleeMetrics = {
309
+ callee,
310
+ totalSampleCount: 0,
311
+ totalValues: new Float64Array(this.#metrics.length)
312
+ };
313
+ caller.calleeIdToMetrics.set(callee.id, calleeMetrics);
314
+ }
315
+ calleeMetrics.totalSampleCount++;
316
+ for (let i = 0; i < values.length; i++) calleeMetrics.totalValues[i] += values[i];
317
+ }
318
+ }
319
+ addLineMetrics({ node, lines }) {
320
+ const func = this.#getOrCreateFunction(node);
321
+ for (const { line, sampleCount, values } of lines) {
322
+ let lineMetrics = func.lineToMetrics.get(line);
323
+ if (!lineMetrics) {
324
+ lineMetrics = {
325
+ sampleCount: 0,
326
+ values: new Float64Array(this.#metrics.length)
327
+ };
328
+ func.lineToMetrics.set(line, lineMetrics);
329
+ }
330
+ lineMetrics.sampleCount += sampleCount;
331
+ for (let i = 0; i < values.length; i++) lineMetrics.values[i] += values[i];
332
+ }
333
+ }
334
+ #getOrCreateCallStack(nodes) {
335
+ const frames = nodes.map((node) => this.#getOrCreateFunction(node));
336
+ const key = frames.map((frame) => frame.id).join(`,`);
337
+ let callStack = this.#keyToCallStack.get(key);
338
+ if (callStack) return callStack;
339
+ callStack = {
340
+ frames,
341
+ selfSampleCount: 0,
342
+ selfValues: new Float64Array(this.#metrics.length)
343
+ };
344
+ this.#keyToCallStack.set(key, callStack);
345
+ return callStack;
346
+ }
347
+ #getOrCreateFunction(node) {
348
+ let func = this.#idToFunction[node.id];
349
+ if (func) return func;
350
+ const key = this.#functionKey(node);
351
+ func = this.#keyToFunction.get(key);
352
+ if (func) {
353
+ this.#idToFunction[node.id] = func;
354
+ return func;
355
+ }
356
+ const { name: nameInput, location: locationInput } = this.#functionInput(node);
357
+ const entry = {
358
+ id: this.#keyToFunction.size,
359
+ name: nameInput || `(anonymous)`,
360
+ location: locationInput ? makeProfileLocation(locationInput) : void 0
361
+ };
362
+ func = {
363
+ ...entry,
364
+ category: categorizeFunction(entry, this.#options),
365
+ selfSampleCount: 0,
366
+ totalSampleCount: 0,
367
+ selfValues: new Float64Array(this.#metrics.length),
368
+ totalValues: new Float64Array(this.#metrics.length),
369
+ lineToMetrics: /* @__PURE__ */ new Map(),
370
+ callerIdToMetrics: /* @__PURE__ */ new Map(),
371
+ calleeIdToMetrics: /* @__PURE__ */ new Map()
372
+ };
373
+ this.#idToFunction[node.id] = func;
374
+ this.#keyToFunction.set(key, func);
375
+ return func;
376
+ }
377
+ build() {
378
+ const samplingIntervals = new Float64Array(this.#metrics.length);
379
+ for (let i = 0; i < samplingIntervals.length; i++) samplingIntervals[i] = this.#totalValues[i] / this.#totalSampleCount;
380
+ const functions = [...this.#keyToFunction.values()];
381
+ const callStacks = [...this.#keyToCallStack.values()];
382
+ return {
383
+ metrics: this.#metrics,
384
+ totalSampleCount: this.#totalSampleCount,
385
+ totalValues: this.#totalValues,
386
+ samplingIntervals,
387
+ categoryToMetrics: this.#categoryToMetrics,
388
+ functions,
389
+ callStacks
390
+ };
114
391
  }
115
- if (urlObject.protocol !== `file:`) return `native`;
116
- return isThirdPartyURL(urlObject) ? `third-party` : `ours`;
117
392
  };
393
+ const categorizeFunction = (entry, { isThirdPartyEntry }) => {
394
+ const { name, location } = entry;
395
+ if (name.startsWith(`(`) && name.endsWith(`)`) && !name.startsWith(`(anonymous`)) return name.slice(1, -1);
396
+ if (name.startsWith(`RegExp: `)) return `regexp`;
397
+ if (!location || location.url.protocol === `node:`) return `native`;
398
+ return isThirdPartyEntry(entry) ? `third-party` : `ours`;
399
+ };
400
+ /**
401
+ * Returns the list of callers of {@link callStacks} that is the longest common
402
+ * suffix of their frames, except it never returns a call stack as long as one
403
+ * of the input call stacks.
404
+ *
405
+ * This behavior is so that it's safe to remove that suffix from any of the call
406
+ * stacks and end up with a non-empty call stack to render.
407
+ */
118
408
  const findCommonCallStack = (callStacks) => {
119
409
  if (callStacks.length <= 1) return [];
120
- const minLength = Math.min(...callStacks.map((callStack) => callStack.nodes.length));
121
- const firstNodes = callStacks[0].nodes;
410
+ const minLength = Math.min(...callStacks.map((cs) => cs.frames.length));
411
+ const firstFrames = callStacks[0].frames;
122
412
  let suffixLength = 0;
123
413
  for (let i = 1; i < minLength; i++) {
124
- const suffix = firstNodes.slice(-i).map((node) => callFrameKey(node.callFrame));
125
- if (callStacks.every((callStack) => callStack.nodes.slice(-i).every((node, j) => callFrameKey(node.callFrame) === suffix[j]))) suffixLength = i;
414
+ const suffix = firstFrames.slice(-i).map((frame) => frame.id);
415
+ if (callStacks.every((callStack) => callStack.frames.slice(-i).every((frame, j) => frame.id === suffix[j]))) suffixLength = i;
126
416
  else break;
127
417
  }
128
- return suffixLength > 0 ? firstNodes.slice(-suffixLength) : [];
129
- };
130
- const formatCallStack = (callStack) => callStack.map(({ callFrame, functionName, location }, index) => {
131
- const name = inlineCode(functionName);
132
- if (!callFrame.url) return name;
133
- const previousUrl = callStack[index - 1]?.callFrame.url;
134
- return `${name} (${callFrame.url === previousUrl ? `${callFrame.lineNumber + 1}:${callFrame.columnNumber + 1}` : location ?? inlineCode(`<native>`)})`;
135
- }).join(` ← `);
136
- const callFrameKey = ({ functionName, url, lineNumber, columnNumber }) => `${functionName}|${url}|${lineNumber}|${columnNumber}`;
137
- /** Returns the full call stack for a node (bottom-up). */
138
- const getSummarizedCallStack = (graph, rawNodeId) => {
139
- const stack = [];
140
- let currentRawNodeId = rawNodeId;
141
- do {
142
- const node = graph.rawIdToSummarizedNode.get(currentRawNodeId);
143
- stack.push(node);
144
- currentRawNodeId = graph.rawIdToParentRawId.get(currentRawNodeId);
145
- } while (currentRawNodeId !== void 0);
146
- return stack;
418
+ return suffixLength > 0 ? firstFrames.slice(-suffixLength) : [];
147
419
  };
148
420
 
149
421
  //#endregion
150
- //#region src/internal/format.ts
151
- const formatCount = (count, unit) => count.toLocaleString(`en-US`) + (unit ? ` ${unit}${count === 1 ? `` : `s`}` : ``);
152
- const formatMicroseconds = (microseconds) => prettyMilliseconds(microseconds / 1e3, {
153
- secondsDecimalDigits: 2,
154
- millisecondsDecimalDigits: 1,
155
- unitCount: 2
156
- });
157
- const formatMicrosecondsExact = (microseconds) => `${microseconds.toFixed(1)}µs`;
158
- const formatBytes = (bytes) => prettyBytes(bytes, { nonBreakingSpace: true });
159
- const formatPercent = (fraction) => `${(fraction * 100).toFixed(1)}%`;
160
-
161
- //#endregion
162
- //#region src/v8/cpu-profile/format.ts
163
- const formatSummarizedProfile$1 = (profile, options) => `${[
164
- `# CPU profile`,
165
- formatOverallProfileSummary$1(profile),
166
- formatHottestFunctions$1(profile, options),
167
- formatHottestCallStacks$1(profile, options)
168
- ].filter(Boolean).join(`\n\n`)}\n`;
169
- const formatOverallProfileSummary$1 = ({ totalTime, totalSampleCount, samplingInterval, callFrameCategoryToStats }) => {
170
- const hottestCallFrameCategories = [...callFrameCategoryToStats].sort(([, stats1], [, stats2]) => stats2.time - stats1.time);
171
- return [`Took ${formatMicroseconds(totalTime)} over ${formatCount(totalSampleCount, `sample`)} (${formatMicrosecondsExact(samplingInterval)} per sample).`, formatTable([
422
+ //#region src/profile/format.ts
423
+ const formatProfile = (profile, options) => {
424
+ const headingLevel = 1;
425
+ return `${[
426
+ formatHeading(headingLevel, formatTitle(profile)),
427
+ formatOverallSummary$1(profile),
428
+ formatMetricSections(profile, {
429
+ ...options,
430
+ headingLevel: headingLevel + 1
431
+ })
432
+ ].join(`\n\n`)}\n`;
433
+ };
434
+ const formatTitle = (profile) => capitalizeFirst(`${formatConjunction(profile.metrics.map(metricTitleName))} profile`);
435
+ const metricTitleName = (metric) => {
436
+ switch (metric.type) {
437
+ case `time`: return `CPU`;
438
+ case `size`: return `heap`;
439
+ case `custom`: return metric.name;
440
+ }
441
+ };
442
+ const formatOverallSummary$1 = (profile) => `${formatSummaryLine(profile)}\n\n${formatCategoryTable(profile)}`;
443
+ const formatSummaryLine = ({ metrics, totalSampleCount, totalValues, samplingIntervals }) => {
444
+ const totalsSummary = capitalizeFirst(formatConjunction(metrics.map((metric, index) => `${metricPastTenseVerb(metric)} ${formatValue(totalValues[index], metric)}`)));
445
+ const samplingIntervalsSummary = `(${formatConjunction(Array.from(samplingIntervals, (interval, index) => formatSamplingInterval(interval, metrics[index])))} per sample)`;
446
+ return `${totalsSummary} over ${formatCount(totalSampleCount, `sample`)} ${samplingIntervalsSummary}.`;
447
+ };
448
+ const formatCategoryTable = ({ metrics, totalValues, categoryToMetrics }) => {
449
+ const hottestCategories = [...categoryToMetrics].sort(([, metrics1], [, metrics2]) => metrics2.values[0] - metrics1.values[0]);
450
+ return formatTable([
172
451
  `Category`,
173
- `%`,
174
- `Time`,
175
- `Samples`
176
- ], hottestCallFrameCategories.map(([category, { time, sampleCount }]) => [
452
+ {
453
+ content: `%`,
454
+ align: `right`
455
+ },
456
+ ...metrics.map((metric) => ({
457
+ content: capitalizeFirst(metricDisplayName(metric)),
458
+ align: `right`
459
+ })),
460
+ {
461
+ content: `Samples`,
462
+ align: `right`
463
+ }
464
+ ], hottestCategories.map(([category, { values, sampleCount }]) => [
177
465
  category,
178
- formatPercent(time / totalTime),
179
- formatMicroseconds(time),
466
+ formatPercent(values[0] / totalValues[0]),
467
+ ...metrics.map((metric, index) => formatValue(values[index], metric)),
180
468
  formatCount(sampleCount)
181
- ]))].join(`\n\n`);
469
+ ]));
182
470
  };
183
- const formatHottestFunctions$1 = (profile, options) => [
184
- `## Hottest functions`,
185
- formatHottestSelfTimeFunctions(profile, options),
186
- formatHottestTotalTimeFunctions(profile, options)
187
- ].join(`\n\n`);
188
- const formatHottestSelfTimeFunctions = ({ totalTime, nodes }, options) => {
189
- const hottestSelfTimeNodes = nodes.filter(options.includeCallFrame).sort((node1, node2) => node2.selfTime - node1.selfTime).slice(0, options.topN);
190
- const hottestLinesSections = hottestSelfTimeNodes.filter((node) => node.lineToStats.size > 0).map((node) => formatHottestLines(node, options));
191
- const hottestCallerSections = hottestSelfTimeNodes.map((node) => formatHottestCallers$1(node, options)).filter((section) => section !== void 0);
471
+ const metricPastTenseVerb = (metric) => {
472
+ switch (metric.type) {
473
+ case `time`: return `took`;
474
+ case `size`: return `allocated`;
475
+ case `custom`: return `recorded`;
476
+ }
477
+ };
478
+ const formatSamplingInterval = (samplingInterval, metric) => {
479
+ switch (metric.type) {
480
+ case `time`: return formatMicrosecondsExact(samplingInterval * 1e3 * metric.milliseconds);
481
+ case `size`: return formatBytes(samplingInterval * metric.bytes);
482
+ case `custom`: return formatCount(samplingInterval, metric.unit);
483
+ }
484
+ };
485
+ const formatMetricSections = (profile, options) => profile.metrics.flatMap((metric, index) => {
486
+ const sections = [];
487
+ let sectionOptions = options;
488
+ if (profile.metrics.length > 1) {
489
+ sections.push(formatHeading(options.headingLevel, capitalizeFirst(metricDisplayName(metric))));
490
+ sectionOptions = {
491
+ ...options,
492
+ headingLevel: options.headingLevel + 1
493
+ };
494
+ }
495
+ const callStacksSection = formatHottestCallStacks(index, profile, sectionOptions);
496
+ return [
497
+ ...sections,
498
+ formatHottestFunctions(index, profile, sectionOptions),
499
+ ...callStacksSection === void 0 ? [] : [callStacksSection]
500
+ ];
501
+ }).join(`\n\n`);
502
+ const formatHottestFunctions = (metricIndex, profile, options) => {
503
+ const subsectionOptions = {
504
+ ...options,
505
+ headingLevel: options.headingLevel + 1
506
+ };
507
+ return [
508
+ formatHeading(options.headingLevel, `Hottest functions`),
509
+ formatHottestSelfFunctions(metricIndex, profile, subsectionOptions),
510
+ formatHottestTotalFunctions(metricIndex, profile, subsectionOptions)
511
+ ].join(`\n\n`);
512
+ };
513
+ const formatHottestSelfFunctions = (metricIndex, profile, options) => {
514
+ const hottestFunctions = selectTopN(profile.functions.filter((func) => options.includeEntry(func) && func.selfValues[metricIndex] > 0), options.topN, (function1, function2) => function1.selfValues[metricIndex] - function2.selfValues[metricIndex]);
515
+ const subsectionOptions = {
516
+ ...options,
517
+ headingLevel: options.headingLevel + 2
518
+ };
519
+ const hottestLinesSections = hottestFunctions.filter((func) => func.lineToMetrics.size > 0).map((func) => formatHottestLines(metricIndex, func, profile, subsectionOptions));
520
+ const hottestCallersSections = hottestFunctions.map((func) => formatHottestCallers(metricIndex, func, profile, subsectionOptions)).filter((section) => section !== void 0);
521
+ const metric = profile.metrics[metricIndex];
522
+ const metricName = metricDisplayName(metric);
192
523
  return [
193
- `### Self time`,
194
- `Functions ranked by time in the function body, excluding callees.`,
524
+ formatHeading(options.headingLevel, `Self ${metricName}`),
525
+ `Functions ranked by ${metricPastParticipleVerbPhrase(metric)} directly in the function body, excluding callees.`,
195
526
  formatTable([
196
527
  {
197
528
  content: `%`,
198
529
  align: `right`
199
530
  },
200
531
  {
201
- content: `Time`,
532
+ content: capitalizeFirst(metricName),
202
533
  align: `right`
203
534
  },
204
535
  {
@@ -207,28 +538,30 @@ const formatHottestSelfTimeFunctions = ({ totalTime, nodes }, options) => {
207
538
  },
208
539
  `Function`,
209
540
  `Location`
210
- ], hottestSelfTimeNodes.map(({ functionName, location, selfTime, selfSampleCount }) => [
211
- formatPercent(selfTime / totalTime),
212
- formatMicroseconds(selfTime),
213
- formatCount(selfSampleCount),
214
- inlineCode(functionName),
215
- location ?? inlineCode(`<native>`)
541
+ ], hottestFunctions.map((func) => [
542
+ formatPercent(func.selfValues[metricIndex] / profile.totalValues[metricIndex]),
543
+ formatValue(func.selfValues[metricIndex], metric),
544
+ formatCount(func.selfSampleCount),
545
+ inlineCode(func.name),
546
+ formatProfileLocation(func.location, options)
216
547
  ])),
217
- ...hottestLinesSections.length > 0 ? [`#### Lines`, `Lines ranked by contribution to each function's self time.`] : [],
548
+ ...hottestLinesSections.length > 0 ? [formatHeading(options.headingLevel + 1, `Lines`), `Lines ranked by contribution to each function's self ${metricName}.`] : [],
218
549
  ...hottestLinesSections,
219
- ...hottestCallerSections.length > 0 ? [`#### Callers`, `Callers ranked by contribution to each function's self time. Caller attribution may be imprecise due to V8 JIT inlining.`] : [],
220
- ...hottestCallerSections
550
+ ...hottestCallersSections.length > 0 ? [formatHeading(options.headingLevel + 1, `Callers`), `Callers ranked by contribution to each function's self ${metricName}. Caller attribution may be imprecise due to inlining.`] : [],
551
+ ...hottestCallersSections
221
552
  ].join(`\n\n`);
222
553
  };
223
- const formatHottestLines = (node, { topN }) => {
224
- 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([
554
+ const formatHottestLines = (metricIndex, func, profile, options) => {
555
+ const selfValue = func.selfValues[metricIndex];
556
+ const hottestLines = selectTopN([...func.lineToMetrics], Math.ceil(options.topN / 4), ([, metrics1], [, metrics2]) => metrics1.values[metricIndex] - metrics2.values[metricIndex]);
557
+ const metric = profile.metrics[metricIndex];
558
+ return [formatHeading(options.headingLevel, `${inlineCode(func.name)} (${formatProfileLocation(func.location, options)})`), formatTable([
226
559
  {
227
560
  content: `%`,
228
561
  align: `right`
229
562
  },
230
563
  {
231
- content: `Time`,
564
+ content: capitalizeFirst(metricDisplayName(metric)),
232
565
  align: `right`
233
566
  },
234
567
  {
@@ -236,23 +569,29 @@ const formatHottestLines = (node, { topN }) => {
236
569
  align: `right`
237
570
  },
238
571
  `Location`
239
- ], hottestLines.map(([line, { time, sampleCount }]) => [
240
- formatPercent(time / node.selfTime),
241
- formatMicroseconds(time),
242
- formatCount(sampleCount),
243
- `${node.fileLocation}:${line + 1}`
572
+ ], hottestLines.map(([line, stats]) => [
573
+ formatPercent(stats.values[metricIndex] / selfValue),
574
+ formatValue(stats.values[metricIndex], metric),
575
+ formatCount(stats.sampleCount),
576
+ func.location ? formatProfileLocation({
577
+ ...func.location,
578
+ line,
579
+ column: void 0
580
+ }, options) : String(line)
244
581
  ]))].join(`\n\n`);
245
582
  };
246
- 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));
248
- if (hottestCallerSelfTimes.length === 0) return;
249
- return [`##### ${inlineCode(node.functionName)} (${node.location ?? inlineCode(`<native>`)})`, formatTable([
583
+ const formatHottestCallers = (metricIndex, func, profile, options) => {
584
+ const selfValue = func.selfValues[metricIndex];
585
+ const hottestCallers = selectTopN([...func.callerIdToMetrics.values()].filter((entry) => options.includeEntry(entry.caller) && entry.selfValues[metricIndex] > 0), Math.ceil(options.topN / 4), (entry1, entry2) => entry1.selfValues[metricIndex] - entry2.selfValues[metricIndex]);
586
+ if (hottestCallers.length === 0) return;
587
+ const metric = profile.metrics[metricIndex];
588
+ return [formatHeading(options.headingLevel, `${inlineCode(func.name)} (${formatProfileLocation(func.location, options)})`), formatTable([
250
589
  {
251
590
  content: `%`,
252
591
  align: `right`
253
592
  },
254
593
  {
255
- content: `Time`,
594
+ content: capitalizeFirst(metricDisplayName(metric)),
256
595
  align: `right`
257
596
  },
258
597
  {
@@ -261,27 +600,34 @@ const formatHottestCallers$1 = (node, options) => {
261
600
  },
262
601
  `Caller`,
263
602
  `Location`
264
- ], hottestCallerSelfTimes.map(({ caller, selfTime, selfSampleCount }) => [
265
- formatPercent(selfTime / node.selfTime),
266
- formatMicroseconds(selfTime),
603
+ ], hottestCallers.map(({ caller, selfValues, selfSampleCount }) => [
604
+ formatPercent(selfValues[metricIndex] / selfValue),
605
+ formatValue(selfValues[metricIndex], metric),
267
606
  formatCount(selfSampleCount),
268
- inlineCode(caller.functionName),
269
- caller.location ?? inlineCode(`<native>`)
607
+ inlineCode(caller.name),
608
+ formatProfileLocation(caller.location, options)
270
609
  ]))].join(`\n\n`);
271
610
  };
272
- const formatHottestTotalTimeFunctions = ({ totalTime, nodes }, options) => {
273
- const hottestTotalTimeNodes = nodes.filter(options.includeCallFrame).sort((node1, node2) => node2.totalTime - node1.totalTime).slice(0, options.topN);
274
- const hottestCalleeSections = hottestTotalTimeNodes.map((node) => formatHottestCallees$1(node, options)).filter((section) => section !== void 0);
611
+ const formatHottestTotalFunctions = (metricIndex, profile, options) => {
612
+ const totalValue = profile.totalValues[metricIndex];
613
+ const hottestFunctions = selectTopN(profile.functions.filter((func) => options.includeEntry(func) && func.totalValues[metricIndex] > 0), options.topN, (func1, func2) => func1.totalValues[metricIndex] - func2.totalValues[metricIndex]);
614
+ const subsectionOptions = {
615
+ ...options,
616
+ headingLevel: options.headingLevel + 2
617
+ };
618
+ const calleeSections = hottestFunctions.map((func) => formatHottestCallees(metricIndex, func, profile, subsectionOptions)).filter((section) => section !== void 0);
619
+ const metric = profile.metrics[metricIndex];
620
+ const metricName = metricDisplayName(metric);
275
621
  return [
276
- `### Total time`,
277
- `Functions ranked by total time in the function and all its callees.`,
622
+ formatHeading(options.headingLevel, `Total ${metricName}`),
623
+ `Functions ranked by total ${metricPastParticipleVerbPhrase(metric)} in the function and all its callees.`,
278
624
  formatTable([
279
625
  {
280
626
  content: `%`,
281
627
  align: `right`
282
628
  },
283
629
  {
284
- content: `Time`,
630
+ content: capitalizeFirst(metricName),
285
631
  align: `right`
286
632
  },
287
633
  {
@@ -290,27 +636,30 @@ const formatHottestTotalTimeFunctions = ({ totalTime, nodes }, options) => {
290
636
  },
291
637
  `Function`,
292
638
  `Location`
293
- ], hottestTotalTimeNodes.map((node) => [
294
- formatPercent(node.totalTime / totalTime),
295
- formatMicroseconds(node.totalTime),
296
- formatCount(node.totalSampleCount),
297
- inlineCode(node.functionName),
298
- node.location ?? inlineCode(`<native>`)
639
+ ], hottestFunctions.map((func) => [
640
+ formatPercent(func.totalValues[metricIndex] / totalValue),
641
+ formatValue(func.totalValues[metricIndex], metric),
642
+ formatCount(func.totalSampleCount),
643
+ inlineCode(func.name),
644
+ formatProfileLocation(func.location, options)
299
645
  ])),
300
- ...hottestCalleeSections.length > 0 ? [`#### Callees`, `Callees ranked by contribution to each function's total time. Callee attribution may be imprecise due to V8 JIT inlining.`] : [],
301
- ...hottestCalleeSections
646
+ ...calleeSections.length > 0 ? [formatHeading(options.headingLevel + 1, `Callees`), `Callees ranked by contribution to each function's total ${metricName}. Callee attribution may be imprecise due to inlining.`] : [],
647
+ ...calleeSections
302
648
  ].join(`\n\n`);
303
649
  };
304
- 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));
306
- if (hottestCalleeTotalTimes.length === 0) return;
307
- return [`##### ${inlineCode(node.functionName)} (${node.location ?? inlineCode(`<native>`)})`, formatTable([
650
+ const formatHottestCallees = (metricIndex, func, profile, options) => {
651
+ const totalValue = func.totalValues[metricIndex];
652
+ const hottestCallees = selectTopN([...func.calleeIdToMetrics.values()].filter((entry) => options.includeEntry(entry.callee) && entry.totalValues[metricIndex] > 0), Math.ceil(options.topN / 4), (entry1, entry2) => entry1.totalValues[metricIndex] - entry2.totalValues[metricIndex]);
653
+ if (hottestCallees.length === 0) return;
654
+ const metric = profile.metrics[metricIndex];
655
+ const metricName = metricDisplayName(metric);
656
+ return [formatHeading(options.headingLevel, `${inlineCode(func.name)} (${formatProfileLocation(func.location, options)})`), formatTable([
308
657
  {
309
658
  content: `%`,
310
659
  align: `right`
311
660
  },
312
661
  {
313
- content: `Time`,
662
+ content: capitalizeFirst(metricName),
314
663
  align: `right`
315
664
  },
316
665
  {
@@ -319,32 +668,35 @@ const formatHottestCallees$1 = (node, options) => {
319
668
  },
320
669
  `Callee`,
321
670
  `Location`
322
- ], hottestCalleeTotalTimes.map(({ callee, totalTime, totalSampleCount }) => [
323
- formatPercent(totalTime / node.totalTime),
324
- formatMicroseconds(totalTime),
671
+ ], hottestCallees.map(({ callee, totalValues, totalSampleCount }) => [
672
+ formatPercent(totalValues[metricIndex] / totalValue),
673
+ formatValue(totalValues[metricIndex], metric),
325
674
  formatCount(totalSampleCount),
326
- inlineCode(callee.functionName),
327
- callee.location ?? inlineCode(`<native>`)
675
+ inlineCode(callee.name),
676
+ formatProfileLocation(callee.location, options)
328
677
  ]))].join(`\n\n`);
329
678
  };
330
- const formatHottestCallStacks$1 = ({ totalTime, callStacks }, options) => {
331
- const hottestCallStacks = callStacks.map((callStack) => ({
679
+ const formatHottestCallStacks = (metricIndex, profile, options) => {
680
+ const totalValue = profile.totalValues[metricIndex];
681
+ const hottestCallStacks = selectTopN(profile.callStacks.map((callStack) => ({
332
682
  ...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);
683
+ frames: callStack.frames.filter(options.includeEntry)
684
+ })).filter((callStack) => callStack.frames.length > 1), options.topN, (callStack1, callStack2) => callStack1.selfValues[metricIndex] - callStack2.selfValues[metricIndex]);
335
685
  if (hottestCallStacks.length === 0) return;
686
+ const metric = profile.metrics[metricIndex];
687
+ const metricName = metricDisplayName(metric);
336
688
  const commonCallStack = findCommonCallStack(hottestCallStacks);
337
689
  return [
338
- `## Hottest call stacks`,
339
- `Call stacks ranked by time spent in their top frame.`,
340
- ...commonCallStack.length > 0 ? [`Common call stack: ${formatCallStack(commonCallStack)}`] : [],
690
+ formatHeading(options.headingLevel, `Hottest call stacks`),
691
+ `Call stacks ranked by ${metricPastParticipleVerbPhrase(metric)} in their top frame.`,
692
+ ...commonCallStack.length > 0 ? [`Common call stack: ${formatCallStack(commonCallStack, options)}`] : [],
341
693
  formatTable([
342
694
  {
343
695
  content: `%`,
344
696
  align: `right`
345
697
  },
346
698
  {
347
- content: `Time`,
699
+ content: capitalizeFirst(metricName),
348
700
  align: `right`
349
701
  },
350
702
  {
@@ -352,514 +704,527 @@ const formatHottestCallStacks$1 = ({ totalTime, callStacks }, options) => {
352
704
  align: `right`
353
705
  },
354
706
  `Call stack`
355
- ], hottestCallStacks.map(({ nodes, selfTime, selfSampleCount }) => [
356
- formatPercent(selfTime / totalTime),
357
- formatMicroseconds(selfTime),
707
+ ], hottestCallStacks.map(({ frames, selfValues, selfSampleCount }) => [
708
+ formatPercent(selfValues[metricIndex] / totalValue),
709
+ formatValue(selfValues[metricIndex], metric),
358
710
  formatCount(selfSampleCount),
359
- formatCallStack(commonCallStack.length > 0 ? nodes.slice(0, -commonCallStack.length) : nodes)
711
+ formatCallStack(commonCallStack.length > 0 ? frames.slice(0, -commonCallStack.length) : frames, options)
360
712
  ]))
361
713
  ].join(`\n\n`);
362
714
  };
363
-
364
- //#endregion
365
- //#region src/v8/cpu-profile/parse.ts
366
- const parseProfile$1 = (data) => JSON.parse(data);
367
-
368
- //#endregion
369
- //#region src/v8/cpu-profile/summarize.ts
370
- const summarizeProfile$1 = (profile, options) => {
371
- const graph = computeProfileGraph$1(profile, options);
372
- const totalTime = profile.endTime - profile.startTime;
373
- const totalSampleCount = profile.samples.length;
374
- const samplingInterval = totalTime / totalSampleCount;
375
- const nodes = [...graph.keyToSummarizedNode.values()];
376
- const rawNodeIdToSummarizedCallStack = /* @__PURE__ */ new Map();
377
- const keyToSummarizedCallStack = /* @__PURE__ */ new Map();
378
- const callFrameCategoryToStats = /* @__PURE__ */ new Map();
379
- for (let index = 0; index < profile.samples.length; index++) {
380
- const rawNodeId = profile.samples[index];
381
- const timeDelta = profile.timeDeltas[index];
382
- const node = graph.rawIdToSummarizedNode.get(rawNodeId);
383
- if (!node) continue;
384
- 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);
391
- }
392
- }
393
- let summarizedCallStack = rawNodeIdToSummarizedCallStack.get(rawNodeId);
394
- if (!summarizedCallStack) {
395
- const callStack = getSummarizedCallStack(graph, rawNodeId);
396
- const key = callStack.map((node) => callFrameKey(node.callFrame)).join(`,`);
397
- summarizedCallStack = keyToSummarizedCallStack.get(key);
398
- if (!summarizedCallStack) {
399
- summarizedCallStack = {
400
- nodes: callStack,
401
- selfTime: 0,
402
- selfSampleCount: 0
403
- };
404
- keyToSummarizedCallStack.set(key, summarizedCallStack);
405
- }
406
- rawNodeIdToSummarizedCallStack.set(rawNodeId, summarizedCallStack);
407
- }
408
- summarizedCallStack.selfTime += timeDelta;
409
- summarizedCallStack.selfSampleCount++;
410
- 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++;
416
- }
417
- const caller = callStack[1];
418
- if (caller) {
419
- let callerSelfTime = node.callerIdToStats.get(caller.id);
420
- if (!callerSelfTime) {
421
- callerSelfTime = {
422
- caller,
423
- selfTime: 0,
424
- selfSampleCount: 0
425
- };
426
- node.callerIdToStats.set(caller.id, callerSelfTime);
427
- }
428
- callerSelfTime.selfTime += timeDelta;
429
- callerSelfTime.selfSampleCount++;
430
- }
431
- const seenCallerCalleePairs = /* @__PURE__ */ new Set();
432
- for (let i = 0; i < callStack.length - 1; i++) {
433
- const callee = callStack[i];
434
- const caller = callStack[i + 1];
435
- const pair = `${caller.id},${callee.id}`;
436
- if (seenCallerCalleePairs.has(pair)) continue;
437
- seenCallerCalleePairs.add(pair);
438
- let calleeTotalTime = caller.calleeIdToStats.get(callee.id);
439
- if (!calleeTotalTime) {
440
- calleeTotalTime = {
441
- callee,
442
- totalTime: 0,
443
- totalSampleCount: 0
444
- };
445
- caller.calleeIdToStats.set(callee.id, calleeTotalTime);
446
- }
447
- calleeTotalTime.totalTime += timeDelta;
448
- calleeTotalTime.totalSampleCount++;
449
- }
450
- let categoryStats = callFrameCategoryToStats.get(node.category);
451
- if (!categoryStats) {
452
- categoryStats = {
453
- time: 0,
454
- sampleCount: 0
455
- };
456
- callFrameCategoryToStats.set(node.category, categoryStats);
457
- }
458
- categoryStats.time += timeDelta;
459
- categoryStats.sampleCount++;
715
+ const formatCallStack = (nodes, options) => nodes.map((node, index) => {
716
+ const name = inlineCode(node.name);
717
+ if (!node.location) return name;
718
+ const previousHref = nodes[index - 1]?.location?.url.href;
719
+ if (!previousHref || node.location.url.href !== previousHref) return `${name} (${formatProfileLocation(node.location, options)})`;
720
+ const { line, column } = node.location;
721
+ if (line === void 0) return name;
722
+ return `${name} (${line}${column === void 0 ? `` : `:${column}`})`;
723
+ }).join(` ← `);
724
+ const metricPastParticipleVerbPhrase = (metric) => {
725
+ switch (metric.type) {
726
+ case `time`: return `time spent`;
727
+ case `size`: return `bytes allocated`;
728
+ case `custom`: return `${metricDisplayName(metric)} recorded`;
460
729
  }
461
- return {
462
- totalTime,
463
- totalSampleCount,
464
- samplingInterval,
465
- callFrameCategoryToStats,
466
- nodes,
467
- callStacks: [...keyToSummarizedCallStack.values()]
468
- };
469
730
  };
470
- const computeProfileGraph$1 = (profile, options) => {
471
- const rawIdToRawNode = /* @__PURE__ */ new Map();
472
- const rawIdToSummarizedNode = /* @__PURE__ */ new Map();
473
- const keyToSummarizedNode = /* @__PURE__ */ new Map();
474
- const rawIdToParentRawId = /* @__PURE__ */ new Map();
475
- 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
- const key = callFrameKey(node.callFrame);
479
- let summarizedNode = keyToSummarizedNode.get(key);
480
- if (!summarizedNode) {
481
- const { functionName, url, lineNumber, columnNumber } = node.callFrame;
482
- const fileLocation = formatURL(url, options);
483
- summarizedNode = {
484
- id: node.id,
485
- callFrame: node.callFrame,
486
- functionName: functionName || `(anonymous)`,
487
- fileLocation,
488
- location: fileLocation ? `${fileLocation}:${lineNumber + 1}:${columnNumber + 1}` : void 0,
489
- category: categorizeCallFrame(node.callFrame, options),
490
- selfSampleCount: 0,
491
- totalSampleCount: 0,
492
- lineToStats: /* @__PURE__ */ new Map(),
493
- selfTime: 0,
494
- totalTime: 0,
495
- callerIdToStats: /* @__PURE__ */ new Map(),
496
- calleeIdToStats: /* @__PURE__ */ new Map()
497
- };
498
- keyToSummarizedNode.set(key, summarizedNode);
499
- }
500
- rawIdToSummarizedNode.set(node.id, summarizedNode);
501
- 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);
511
- }
512
- stats.sampleCount += tick.ticks;
513
- }
514
- if (node.children) for (const childId of node.children) {
515
- if (rawIdToParentRawId.has(childId)) throw new Error(`Unexpected node ID with multiple parent IDs: ${childId}`);
516
- rawIdToParentRawId.set(childId, node.id);
517
- }
731
+ const metricDisplayName = (metric) => {
732
+ switch (metric.type) {
733
+ case `time`:
734
+ case `size`: return metric.type;
735
+ case `custom`: return metric.name;
518
736
  }
519
- return {
520
- rawIdToRawNode,
521
- rawIdToSummarizedNode,
522
- keyToSummarizedNode,
523
- rawIdToParentRawId
524
- };
525
737
  };
526
-
527
- //#endregion
528
- //#region src/v8/cpu-profile/index.ts
529
- /**
530
- * Converts the given V8 CPU profile to Markdown.
531
- *
532
- * It is assumed that {@link data} is a valid profile. The behavior of this
533
- * function is undefined for invalid profiles.
534
- *
535
- * You can generate a V8 CPU profile in several ways:
536
- * - [`node --cpu-prof`](https://nodejs.org/api/cli.html#cpu-prof)
537
- * - [`deno --cpu-prof`](https://docs.deno.com/runtime/fundamentals/debugging/#cpu-profiling)
538
- * - [`bun --cpu-prof`](https://bun.com/docs/project/benchmarking#cpu-profiling)
539
- *
540
- * Lower the sampling interval to capture more granular data.
541
- */
542
- const v8CpuProfileToMd = (data, options) => {
543
- const normalizedOptions = normalizeV8ProfileToMdOptions(options);
544
- return formatSummarizedProfile$1(summarizeProfile$1(parseProfile$1(data), normalizedOptions), normalizedOptions);
738
+ const formatValue = (value, metric) => {
739
+ switch (metric.type) {
740
+ case `time`: return formatMilliseconds(value * metric.milliseconds);
741
+ case `size`: return formatBytes(value * metric.bytes);
742
+ case `custom`: return formatCount(value, metric.unit);
743
+ }
545
744
  };
745
+ const capitalizeFirst = (string) => string.length === 0 ? string : string[0].toUpperCase() + string.slice(1);
546
746
 
547
747
  //#endregion
548
- //#region src/v8/heap-profile/format.ts
549
- const formatSummarizedProfile = (profile, options) => `${[
550
- `# Heap profile`,
551
- formatOverallProfileSummary(profile),
552
- formatHottestFunctions(profile, options),
553
- formatHottestCallStacks(profile, options)
554
- ].filter(Boolean).join(`\n\n`)}\n`;
555
- const formatOverallProfileSummary = ({ totalSize, sampleCount, samplingInterval, callFrameCategoryToStats }) => {
556
- const hottestCallFrameCategories = [...callFrameCategoryToStats].sort(([, stats1], [, stats2]) => stats2.size - stats1.size);
557
- return [`Allocated ${formatBytes(totalSize)} over ${formatCount(sampleCount, `sample`)} (${formatBytes(samplingInterval)} per sample).`, formatTable([
558
- `Category`,
559
- `%`,
560
- `Size`,
561
- `Samples`
562
- ], hottestCallFrameCategories.map(([category, { size, sampleCount }]) => [
563
- category,
564
- formatPercent(size / totalSize),
565
- formatBytes(size),
566
- formatCount(sampleCount)
567
- ]))].join(`\n\n`);
748
+ //#region src/profile/metric.ts
749
+ const determineMetric = ({ name, unit }) => METRICS.get(unit.toLowerCase()) ?? {
750
+ type: `custom`,
751
+ name,
752
+ unit
568
753
  };
569
- const formatHottestFunctions = (profile, options) => [
570
- `## Hottest functions`,
571
- formatHottestSelfSizeFunctions(profile, options),
572
- formatHottestTotalSizeFunctions(profile, options)
573
- ].join(`\n\n`);
574
- const formatHottestSelfSizeFunctions = ({ totalSize, nodes }, options) => {
575
- const hottestSelfSizeNodes = nodes.filter(options.includeCallFrame).sort((node1, node2) => node2.selfSize - node1.selfSize).slice(0, options.topN);
576
- const hottestCallerSections = hottestSelfSizeNodes.map((node) => formatHottestCallers(node, options)).filter((section) => section !== void 0);
577
- return [
578
- `### Self size`,
579
- `Functions ranked by bytes allocated directly in the function body, excluding callees.`,
580
- formatTable([
581
- {
582
- content: `%`,
583
- align: `right`
584
- },
585
- {
586
- content: `Size`,
587
- align: `right`
588
- },
589
- {
590
- content: `Samples`,
591
- align: `right`
592
- },
593
- `Function`,
594
- `Location`
595
- ], hottestSelfSizeNodes.map(({ functionName, location, selfSize, selfSampleCount }) => [
596
- formatPercent(selfSize / totalSize),
597
- formatBytes(selfSize),
598
- formatCount(selfSampleCount),
599
- inlineCode(functionName),
600
- location ?? inlineCode(`<native>`)
601
- ])),
602
- ...hottestCallerSections.length > 0 ? [`#### Callers`, `Callers ranked by contribution to each function's self size.`] : [],
603
- ...hottestCallerSections
604
- ].join(`\n\n`);
754
+ const NANOSECONDS = {
755
+ type: `time`,
756
+ milliseconds: 1e-6
605
757
  };
606
- 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));
608
- if (hottestCallers.length === 0) return;
609
- return [`##### ${inlineCode(node.functionName)} (${node.location ?? inlineCode(`<native>`)})`, formatTable([
610
- {
611
- content: `%`,
612
- align: `right`
613
- },
614
- {
615
- content: `Size`,
616
- align: `right`
617
- },
618
- {
619
- content: `Samples`,
620
- align: `right`
621
- },
622
- `Caller`,
623
- `Location`
624
- ], hottestCallers.map(({ caller, selfSize, selfSampleCount }) => [
625
- formatPercent(selfSize / node.selfSize),
626
- formatBytes(selfSize),
627
- formatCount(selfSampleCount),
628
- inlineCode(caller.functionName),
629
- caller.location ?? inlineCode(`<native>`)
630
- ]))].join(`\n\n`);
758
+ const MICROSECONDS = {
759
+ type: `time`,
760
+ milliseconds: .001
631
761
  };
632
- const formatHottestTotalSizeFunctions = ({ totalSize, nodes }, options) => {
633
- const hottestTotalSizeNodes = nodes.filter(options.includeCallFrame).sort((node1, node2) => node2.totalSize - node1.totalSize).slice(0, options.topN);
634
- const hottestCalleeSections = hottestTotalSizeNodes.map((node) => formatHottestCallees(node, options)).filter((section) => section !== void 0);
635
- return [
636
- `### Total size`,
637
- `Functions ranked by total bytes allocated in the function and all its callees.`,
638
- formatTable([
639
- {
640
- content: `%`,
641
- align: `right`
642
- },
643
- {
644
- content: `Size`,
645
- align: `right`
646
- },
647
- {
648
- content: `Samples`,
649
- align: `right`
650
- },
651
- `Function`,
652
- `Location`
653
- ], hottestTotalSizeNodes.map(({ functionName, location, totalSize: nodeTotal, totalSampleCount }) => [
654
- formatPercent(nodeTotal / totalSize),
655
- formatBytes(nodeTotal),
656
- formatCount(totalSampleCount),
657
- inlineCode(functionName),
658
- location ?? inlineCode(`<native>`)
659
- ])),
660
- ...hottestCalleeSections.length > 0 ? [`#### Callees`, `Callees ranked by contribution to each function's total size.`] : [],
661
- ...hottestCalleeSections
662
- ].join(`\n\n`);
762
+ const MILLISECONDS = {
763
+ type: `time`,
764
+ milliseconds: 1
663
765
  };
664
- 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));
666
- if (hottestCallees.length === 0) return;
667
- return [`##### ${inlineCode(node.functionName)} (${node.location ?? inlineCode(`<native>`)})`, formatTable([
668
- {
669
- content: `%`,
670
- align: `right`
671
- },
672
- {
673
- content: `Size`,
674
- align: `right`
675
- },
676
- {
677
- content: `Samples`,
678
- align: `right`
679
- },
680
- `Callee`,
681
- `Location`
682
- ], hottestCallees.map(({ callee, totalSize, totalSampleCount }) => [
683
- formatPercent(totalSize / node.totalSize),
684
- formatBytes(totalSize),
685
- formatCount(totalSampleCount),
686
- inlineCode(callee.functionName),
687
- callee.location ?? inlineCode(`<native>`)
688
- ]))].join(`\n\n`);
766
+ const SECONDS = {
767
+ type: `time`,
768
+ milliseconds: 1e3
689
769
  };
690
- const formatHottestCallStacks = (profile, options) => {
691
- const hottestCallStacks = profile.callStacks.map((callStack) => ({
692
- ...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);
695
- if (hottestCallStacks.length === 0) return;
696
- const commonCallStack = findCommonCallStack(hottestCallStacks);
697
- return [
698
- `## Hottest call stacks`,
699
- `Call stacks ranked by bytes allocated in their top frame.`,
700
- ...commonCallStack.length > 0 ? [`Common call stack: ${formatCallStack(commonCallStack)}`] : [],
701
- formatTable([
702
- {
703
- content: `%`,
704
- align: `right`
705
- },
706
- {
707
- content: `Size`,
708
- align: `right`
709
- },
710
- {
711
- content: `Samples`,
712
- align: `right`
713
- },
714
- `Call stack`
715
- ], hottestCallStacks.map(({ nodes, selfSize, selfSampleCount }) => [
716
- formatPercent(selfSize / profile.totalSize),
717
- formatBytes(selfSize),
718
- formatCount(selfSampleCount),
719
- formatCallStack(commonCallStack.length > 0 ? nodes.slice(0, -commonCallStack.length) : nodes)
720
- ]))
721
- ].join(`\n\n`);
770
+ const BYTES = {
771
+ type: `size`,
772
+ bytes: 1
773
+ };
774
+ const KILOBYTES = {
775
+ type: `size`,
776
+ bytes: 1024
722
777
  };
778
+ const MEGABYTES = {
779
+ type: `size`,
780
+ bytes: 1 << 20
781
+ };
782
+ const GIGABYTES = {
783
+ type: `size`,
784
+ bytes: 1 << 30
785
+ };
786
+ const METRICS = new Map([
787
+ [`nanoseconds`, NANOSECONDS],
788
+ [`nanosecond`, NANOSECONDS],
789
+ [`nanos`, NANOSECONDS],
790
+ [`ns`, NANOSECONDS],
791
+ [`microseconds`, MICROSECONDS],
792
+ [`microsecond`, MICROSECONDS],
793
+ [`micros`, MICROSECONDS],
794
+ [`us`, MICROSECONDS],
795
+ [`μs`, MICROSECONDS],
796
+ [`milliseconds`, MILLISECONDS],
797
+ [`millisecond`, MILLISECONDS],
798
+ [`millis`, MILLISECONDS],
799
+ [`ms`, MILLISECONDS],
800
+ [`seconds`, SECONDS],
801
+ [`second`, SECONDS],
802
+ [`secs`, SECONDS],
803
+ [`sec`, SECONDS],
804
+ [`s`, SECONDS],
805
+ [`bytes`, BYTES],
806
+ [`byte`, BYTES],
807
+ [`b`, BYTES],
808
+ [`kilobytes`, KILOBYTES],
809
+ [`kilobyte`, KILOBYTES],
810
+ [`kbytes`, KILOBYTES],
811
+ [`kbyte`, KILOBYTES],
812
+ [`kb`, KILOBYTES],
813
+ [`megabytes`, MEGABYTES],
814
+ [`megabyte`, MEGABYTES],
815
+ [`mbytes`, MEGABYTES],
816
+ [`mbyte`, MEGABYTES],
817
+ [`mb`, MEGABYTES],
818
+ [`gigabytes`, GIGABYTES],
819
+ [`gigabyte`, GIGABYTES],
820
+ [`gbytes`, GIGABYTES],
821
+ [`gbyte`, GIGABYTES],
822
+ [`gb`, GIGABYTES],
823
+ [`none`, {
824
+ type: `custom`,
825
+ name: `count`,
826
+ unit: `count`
827
+ }]
828
+ ]);
723
829
 
724
830
  //#endregion
725
- //#region src/v8/heap-profile/parse.ts
726
- const parseProfile = (data) => JSON.parse(data);
831
+ //#region src/formats/pprof/format.ts
832
+ const formatPprof = (profile, options) => formatProfile(profile, options);
727
833
 
728
834
  //#endregion
729
- //#region src/v8/heap-profile/summarize.ts
730
- const summarizeProfile = (profile, options) => {
731
- const graph = computeProfileGraph(profile, options);
732
- const totalSize = profile.samples.reduce((sum, sample) => sum + sample.size, 0);
733
- const sampleCount = profile.samples.length;
734
- const samplingInterval = totalSize / sampleCount;
735
- const rawNodeIdToSummarizedCallStack = /* @__PURE__ */ new Map();
736
- const keyToSummarizedCallStack = /* @__PURE__ */ new Map();
737
- const callFrameCategoryToStats = /* @__PURE__ */ new Map();
738
- for (const { size, nodeId } of profile.samples) {
739
- const node = graph.rawIdToSummarizedNode.get(nodeId);
740
- if (!node) continue;
741
- node.selfSize += size;
742
- node.selfSampleCount++;
743
- let summarizedCallStack = rawNodeIdToSummarizedCallStack.get(nodeId);
744
- if (!summarizedCallStack) {
745
- const callStack = getSummarizedCallStack(graph, nodeId);
746
- const key = callStack.map((node) => callFrameKey(node.callFrame)).join(`,`);
747
- summarizedCallStack = keyToSummarizedCallStack.get(key);
748
- if (!summarizedCallStack) {
749
- summarizedCallStack = {
750
- nodes: callStack,
751
- selfSize: 0,
752
- selfSampleCount: 0
753
- };
754
- keyToSummarizedCallStack.set(key, summarizedCallStack);
755
- }
756
- rawNodeIdToSummarizedCallStack.set(nodeId, summarizedCallStack);
757
- }
758
- summarizedCallStack.selfSize += size;
759
- summarizedCallStack.selfSampleCount++;
760
- 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++;
766
- }
767
- const caller = callStack[1];
768
- if (caller) {
769
- let callerStats = node.callerIdToStats.get(caller.id);
770
- if (!callerStats) {
771
- callerStats = {
772
- caller,
773
- selfSize: 0,
774
- selfSampleCount: 0
775
- };
776
- node.callerIdToStats.set(caller.id, callerStats);
835
+ //#region src/formats/pprof/parse.ts
836
+ const parsePprof = (data) => parsePprofInternal(Profile.decode(data));
837
+ const parsePprofInternal = (profile) => {
838
+ const { strings } = profile.stringTable;
839
+ const valueTypes = profile.sampleType.map(({ type, unit }) => ({
840
+ type: strings[Number(type)] ?? ``,
841
+ unit: strings[Number(unit)] ?? ``
842
+ }));
843
+ const functionIdToIndex = [];
844
+ const functions = [];
845
+ for (const func of profile.function) {
846
+ const id = Number(func.id);
847
+ functionIdToIndex[id] = functions.length;
848
+ functions.push({
849
+ id,
850
+ name: strings[Number(func.name)] ?? ``,
851
+ systemName: strings[Number(func.systemName)] ?? ``,
852
+ filename: strings[Number(func.filename)] ?? ``,
853
+ startLine: Number(func.startLine)
854
+ });
855
+ }
856
+ const locationIdToIndex = [];
857
+ const locations = [];
858
+ for (const location of profile.location) {
859
+ const id = Number(location.id);
860
+ locationIdToIndex[id] = locations.length;
861
+ locations.push({
862
+ id,
863
+ lines: location.line.map(({ functionId, line }) => ({
864
+ functionId: functionIdToIndex[Number(functionId)],
865
+ line: Number(line)
866
+ }))
867
+ });
868
+ }
869
+ return {
870
+ valueTypes,
871
+ samples: profile.sample.map(({ locationId, value }) => ({
872
+ locationIds: locationId.map((id) => locationIdToIndex[Number(id)]),
873
+ values: value.map(Number)
874
+ })),
875
+ locations,
876
+ functions
877
+ };
878
+ };
879
+
880
+ //#endregion
881
+ //#region src/formats/pprof/summarize.ts
882
+ const summarizePprof = ({ valueTypes, samples, locations, functions }, options) => {
883
+ const nonCountValueTypes = [...valueTypes.entries()].filter(([, valueType]) => valueType.unit.toLowerCase() !== `count`);
884
+ const profileBuilder = new ProfileBuilder({
885
+ metrics: nonCountValueTypes.map(([, valueType]) => determineMetric({
886
+ name: valueType.type,
887
+ unit: valueType.unit
888
+ })),
889
+ functionKey: (func) => func.id,
890
+ functionInput: (func) => ({
891
+ name: func.name || func.systemName,
892
+ location: {
893
+ urlOrPath: func.filename,
894
+ line: func.startLine > 0 ? func.startLine : void 0
777
895
  }
778
- callerStats.selfSize += size;
779
- callerStats.selfSampleCount++;
780
- }
781
- const seenCallerCalleePairs = /* @__PURE__ */ new Set();
782
- for (let i = 0; i < callStack.length - 1; i++) {
783
- const callee = callStack[i];
784
- const caller = callStack[i + 1];
785
- const pair = `${caller.id},${callee.id}`;
786
- if (seenCallerCalleePairs.has(pair)) continue;
787
- seenCallerCalleePairs.add(pair);
788
- let calleeStats = caller.calleeIdToStats.get(callee.id);
789
- if (!calleeStats) {
790
- calleeStats = {
791
- callee,
792
- totalSize: 0,
793
- totalSampleCount: 0
794
- };
795
- caller.calleeIdToStats.set(callee.id, calleeStats);
896
+ })
897
+ }, options);
898
+ for (const sample of samples) {
899
+ const { locationIds, values } = sample;
900
+ const nodes = [];
901
+ let calleeLine;
902
+ for (const locationId of locationIds) {
903
+ const location = locations[locationId];
904
+ for (const { functionId, line } of location.lines) {
905
+ nodes.push(functions[functionId]);
906
+ calleeLine ??= line;
796
907
  }
797
- calleeStats.totalSize += size;
798
- calleeStats.totalSampleCount++;
799
- }
800
- let categoryStats = callFrameCategoryToStats.get(node.category);
801
- if (!categoryStats) {
802
- categoryStats = {
803
- size: 0,
804
- sampleCount: 0
805
- };
806
- callFrameCategoryToStats.set(node.category, categoryStats);
807
908
  }
808
- categoryStats.size += size;
809
- categoryStats.sampleCount++;
909
+ if (nodes.length === 0) continue;
910
+ profileBuilder.addSample({
911
+ values: nonCountValueTypes.map(([index]) => values[index]),
912
+ nodes,
913
+ line: calleeLine
914
+ });
915
+ }
916
+ return profileBuilder.build();
917
+ };
918
+
919
+ //#endregion
920
+ //#region src/formats/pprof/index.ts
921
+ const detectPprof = (data) => {
922
+ if (data.length === 0) return;
923
+ let profile;
924
+ try {
925
+ profile = Profile.decode(data);
926
+ } catch {
927
+ return;
810
928
  }
929
+ if (profile.stringTable.strings[0] !== ``) return;
930
+ return parsePprofInternal(profile);
931
+ };
932
+ /**
933
+ * Converts the given pprof to Markdown.
934
+ *
935
+ * It is assumed that {@link data} is a valid pprof (raw protobuf). The behavior
936
+ * of this function is undefined for invalid profiles.
937
+ *
938
+ * pprof can be generated by many tools, including:
939
+ * - Go's [`runtime/pprof`](https://pkg.go.dev/runtime/pprof) package
940
+ * - Node.js's [`pprof`](https://www.npmjs.com/package/pprof) npm package
941
+ * - Python's [`py-spy`](https://github.com/benfred/py-spy)
942
+ * - Rust's [`pprof-rs`](https://github.com/tikv/pprof-rs)
943
+ */
944
+ const pprofToMd = (data, options) => pprofToMdInternal(parsePprof(data), options);
945
+ const pprofToMdInternal = (pprof, options) => {
946
+ const normalizedOptions = normalizeProfileToMdOptions(options);
947
+ return formatPprof(summarizePprof(pprof, normalizedOptions), normalizedOptions);
948
+ };
949
+
950
+ //#endregion
951
+ //#region src/formats/speedscope/format.ts
952
+ const formatSpeedscope = (profile, options) => formatProfile(profile, options);
953
+
954
+ //#endregion
955
+ //#region src/helpers/json.ts
956
+ const parseJson = (data) => JSON.parse(data);
957
+
958
+ //#endregion
959
+ //#region src/formats/speedscope/parse.ts
960
+ const parseSpeedscopeProfile = (data) => parseJson(data);
961
+
962
+ //#endregion
963
+ //#region src/formats/speedscope/summarize.ts
964
+ const summarizeSpeedscopeProfile = (profile, options) => {
965
+ const nodes = profile.shared.frames.map((frame, id) => ({
966
+ ...frame,
967
+ id
968
+ }));
969
+ return profile.profiles.map((profile) => profile.type === `sampled` ? summarizeSampled(profile, nodes, options) : summarizeEvented(profile, nodes, options));
970
+ };
971
+ const summarizeSampled = (profile, nodes, options) => {
972
+ const profileBuilder = makeProfileBuilder(profile.unit, options);
973
+ for (let index = 0; index < profile.samples.length; index++) {
974
+ const weight = profile.weights[index];
975
+ if (weight <= 0) continue;
976
+ const sampleNodes = profile.samples[index].map((frameIndex) => nodes[frameIndex]).reverse();
977
+ if (sampleNodes.length === 0) continue;
978
+ profileBuilder.addSample({
979
+ values: [weight],
980
+ nodes: sampleNodes
981
+ });
982
+ }
983
+ return profileBuilder.build();
984
+ };
985
+ const summarizeEvented = (profile, nodes, options) => {
986
+ const builder = makeProfileBuilder(profile.unit, options);
987
+ const stack = [];
988
+ const emitTopSelfTime = (at) => {
989
+ if (stack.length === 0) return;
990
+ const top = stack.at(-1);
991
+ const selfTime = at - top.lastChildClosed;
992
+ if (selfTime <= 0) return;
993
+ builder.addSample({
994
+ values: [selfTime],
995
+ nodes: stack.map((entry) => entry.node).reverse()
996
+ });
997
+ top.lastChildClosed = at;
998
+ };
999
+ for (const event of profile.events) if (event.type === `O`) {
1000
+ emitTopSelfTime(event.at);
1001
+ stack.push({
1002
+ node: nodes[event.frame],
1003
+ lastChildClosed: event.at
1004
+ });
1005
+ } else {
1006
+ emitTopSelfTime(event.at);
1007
+ stack.pop();
1008
+ if (stack.length > 0) stack.at(-1).lastChildClosed = event.at;
1009
+ }
1010
+ return builder.build();
1011
+ };
1012
+ const makeProfileBuilder = (unit, options) => new ProfileBuilder({
1013
+ metrics: [determineMetric({
1014
+ name: unit,
1015
+ unit
1016
+ })],
1017
+ functionKey: (node) => node.id,
1018
+ functionInput: (node) => ({
1019
+ name: node.name,
1020
+ location: node.file ? {
1021
+ urlOrPath: node.file,
1022
+ line: node.line,
1023
+ column: node.col
1024
+ } : void 0
1025
+ })
1026
+ }, options);
1027
+
1028
+ //#endregion
1029
+ //#region src/formats/speedscope/index.ts
1030
+ const detectSpeedscopeProfile = (json) => {
1031
+ if (typeof json !== `object` || json === null) return;
1032
+ const object = json;
1033
+ if (object.$schema !== `https://www.speedscope.app/file-format-schema.json` || !Array.isArray(object.profiles) || typeof object.shared !== `object` || object.shared === null) return;
1034
+ return json;
1035
+ };
1036
+ /**
1037
+ * Converts the given speedscope profile to Markdown.
1038
+ *
1039
+ * It is assumed that {@link data} is a valid speedscope JSON file. The behavior
1040
+ * of this function is undefined for invalid profiles.
1041
+ *
1042
+ * Speedscope profiles can be generated by many tools, including:
1043
+ * - [speedscope](https://www.speedscope.app) (drag and drop any supported profile)
1044
+ * - [rbspy](https://rbspy.github.io) for Ruby
1045
+ * - [py-spy](https://github.com/benfred/py-spy) for Python (`--format speedscope`)
1046
+ * - [pprof-rs](https://github.com/tikv/pprof-rs) for Rust
1047
+ */
1048
+ const speedscopeProfileToMd = (data, options) => speedscopeProfileToMdInternal(parseSpeedscopeProfile(data), options);
1049
+ const speedscopeProfileToMdInternal = (profile, options) => {
1050
+ const normalizedOptions = normalizeProfileToMdOptions(options);
1051
+ return summarizeSpeedscopeProfile(profile, normalizedOptions).map((profile) => formatSpeedscope(profile, normalizedOptions)).join(`\n\n`);
1052
+ };
1053
+
1054
+ //#endregion
1055
+ //#region src/formats/v8/cpu-profile/format.ts
1056
+ const formatV8CpuProfile = (profile, options) => formatProfile(profile, options);
1057
+
1058
+ //#endregion
1059
+ //#region src/formats/v8/cpu-profile/parse.ts
1060
+ const parseV8CpuProfile = (data) => parseJson(data);
1061
+
1062
+ //#endregion
1063
+ //#region src/formats/v8/common.ts
1064
+ const callFrameKey = ({ functionName, url, lineNumber, columnNumber }) => `${functionName}|${url}|${lineNumber}|${columnNumber}`;
1065
+ const callFrameFunctionInput = (callFrame) => {
1066
+ const { functionName, url, lineNumber, columnNumber } = callFrame;
811
1067
  return {
812
- totalSize,
813
- sampleCount,
814
- samplingInterval,
815
- callFrameCategoryToStats,
816
- nodes: [...graph.keyToSummarizedNode.values()],
817
- callStacks: [...keyToSummarizedCallStack.values()]
1068
+ name: functionName,
1069
+ location: url ? {
1070
+ urlOrPath: url,
1071
+ line: lineNumber + 1,
1072
+ column: columnNumber + 1
1073
+ } : void 0
818
1074
  };
819
1075
  };
820
- const computeProfileGraph = (profile, options) => {
821
- const rawIdToSummarizedNode = /* @__PURE__ */ new Map();
822
- const keyToSummarizedNode = /* @__PURE__ */ new Map();
823
- const rawIdToParentRawId = /* @__PURE__ */ new Map();
824
- const stack = [{ node: profile.head }];
825
- do {
826
- const { node, parentId } = stack.pop();
827
- const key = callFrameKey(node.callFrame);
828
- let summarizedNode = keyToSummarizedNode.get(key);
829
- if (!summarizedNode) {
830
- const { functionName, url, lineNumber, columnNumber } = node.callFrame;
831
- const fileLocation = formatURL(url, options);
832
- summarizedNode = {
833
- id: node.id,
834
- callFrame: node.callFrame,
835
- functionName: functionName || `(anonymous)`,
836
- location: fileLocation ? `${fileLocation}:${lineNumber + 1}:${columnNumber + 1}` : void 0,
837
- category: categorizeCallFrame(node.callFrame, options),
838
- selfSize: 0,
839
- totalSize: 0,
840
- selfSampleCount: 0,
841
- totalSampleCount: 0,
842
- callerIdToStats: /* @__PURE__ */ new Map(),
843
- calleeIdToStats: /* @__PURE__ */ new Map()
844
- };
845
- keyToSummarizedNode.set(key, summarizedNode);
1076
+
1077
+ //#endregion
1078
+ //#region src/formats/v8/cpu-profile/summarize.ts
1079
+ const summarizeV8CpuProfile = (profile, options) => {
1080
+ const profileBuilder = new ProfileBuilder({
1081
+ metrics: [MICROSECONDS],
1082
+ functionKey: (node) => callFrameKey(node.callFrame),
1083
+ functionInput: (node) => callFrameFunctionInput(node.callFrame)
1084
+ }, options);
1085
+ const idToIndex = [];
1086
+ for (let index = 0; index < profile.nodes.length; index++) {
1087
+ const node = profile.nodes[index];
1088
+ idToIndex[node.id] = index;
1089
+ node.id = index;
1090
+ }
1091
+ const indexToParentIndex = new Int32Array(profile.nodes.length).fill(-1);
1092
+ for (const node of profile.nodes) if (node.children) for (const childId of node.children) {
1093
+ const childIndex = idToIndex[childId];
1094
+ if (childIndex === void 0) continue;
1095
+ indexToParentIndex[childIndex] = node.id;
1096
+ }
1097
+ const indexToSelfTime = new Float64Array(profile.nodes.length);
1098
+ for (let index = 0; index < profile.samples.length; index++) {
1099
+ const nodeIndex = idToIndex[profile.samples[index]];
1100
+ if (nodeIndex === void 0) continue;
1101
+ const node = profile.nodes[nodeIndex];
1102
+ const timeDelta = profile.timeDeltas[index];
1103
+ indexToSelfTime[nodeIndex] += timeDelta;
1104
+ const nodes = [];
1105
+ let currentNode = node;
1106
+ while (true) {
1107
+ nodes.push(currentNode);
1108
+ const parentIndex = indexToParentIndex[currentNode.id];
1109
+ if (parentIndex === -1) break;
1110
+ currentNode = profile.nodes[parentIndex];
846
1111
  }
847
- rawIdToSummarizedNode.set(node.id, summarizedNode);
848
- if (parentId !== void 0) rawIdToParentRawId.set(node.id, parentId);
1112
+ profileBuilder.addSample({
1113
+ values: [timeDelta],
1114
+ nodes
1115
+ });
1116
+ }
1117
+ for (const node of profile.nodes) {
1118
+ if (!node.positionTicks) continue;
1119
+ const selfTime = indexToSelfTime[node.id];
1120
+ profileBuilder.addLineMetrics({
1121
+ node,
1122
+ lines: node.positionTicks.map(({ line, ticks }) => ({
1123
+ line,
1124
+ sampleCount: ticks,
1125
+ values: [Math.round(selfTime * ticks / node.hitCount)]
1126
+ }))
1127
+ });
1128
+ }
1129
+ return profileBuilder.build();
1130
+ };
1131
+
1132
+ //#endregion
1133
+ //#region src/formats/v8/cpu-profile/index.ts
1134
+ const detectV8CpuProfile = (json) => {
1135
+ if (typeof json !== `object` || json === null) return;
1136
+ const object = json;
1137
+ if (!Array.isArray(object.nodes) || !Array.isArray(object.timeDeltas)) return;
1138
+ return json;
1139
+ };
1140
+ /**
1141
+ * Converts the given V8 CPU profile to Markdown.
1142
+ *
1143
+ * It is assumed that {@link data} is a valid profile. The behavior of this
1144
+ * function is undefined for invalid profiles.
1145
+ *
1146
+ * You can generate a V8 CPU profile in several ways:
1147
+ * - [`node --cpu-prof`](https://nodejs.org/api/cli.html#cpu-prof)
1148
+ * - [`deno run --cpu-prof`](https://docs.deno.com/runtime/fundamentals/debugging/#cpu-profiling)
1149
+ * - [`bun --cpu-prof`](https://bun.com/docs/project/benchmarking#cpu-profiling)
1150
+ * (NOTE: output was incorrect until
1151
+ * [v1.3.13](https://bun.com/blog/bun-v1.3.13#node-js-compatibility-improvements))
1152
+ * - [`node --inspect`](https://nodejs.org/api/debugger.html#v8-inspector-integration-for-nodejs),
1153
+ * [`deno run --inspect`](https://docs.deno.com/runtime/fundamentals/debugging/#--inspect),
1154
+ * or [`bun --inspect`](https://bun.com/docs/runtime/debugger#inspect) with
1155
+ * [Chrome DevTools](https://developer.chrome.com/docs/devtools/performance/nodejs)
1156
+ * - [Chrome DevTools directly](https://developer.chrome.com/docs/devtools/performance#record)
1157
+ *
1158
+ * Lower the sampling interval to capture more granular data.
1159
+ */
1160
+ const v8CpuProfileToMd = (data, options) => v8CpuProfileToMdInternal(parseV8CpuProfile(data), options);
1161
+ const v8CpuProfileToMdInternal = (profile, options) => {
1162
+ const normalizedOptions = normalizeProfileToMdOptions(options);
1163
+ return formatV8CpuProfile(summarizeV8CpuProfile(profile, normalizedOptions), normalizedOptions);
1164
+ };
1165
+
1166
+ //#endregion
1167
+ //#region src/formats/v8/heap-profile/format.ts
1168
+ const formatV8HeapProfile = (profile, options) => formatProfile(profile, options);
1169
+
1170
+ //#endregion
1171
+ //#region src/formats/v8/heap-profile/parse.ts
1172
+ const parseV8HeapProfile = (data) => parseJson(data);
1173
+
1174
+ //#endregion
1175
+ //#region src/formats/v8/heap-profile/summarize.ts
1176
+ const summarizeV8HeapProfile = (profile, options) => {
1177
+ const profileBuilder = new ProfileBuilder({
1178
+ metrics: [BYTES],
1179
+ functionKey: (node) => callFrameKey(node.callFrame),
1180
+ functionInput: (node) => callFrameFunctionInput(node.callFrame)
1181
+ }, options);
1182
+ const flatNodes = [];
1183
+ const idToIndex = [];
1184
+ const indexToParentIndex = [];
1185
+ const stack = [{
1186
+ node: profile.head,
1187
+ parentIndex: -1
1188
+ }];
1189
+ do {
1190
+ const { node, parentIndex } = stack.pop();
1191
+ const index = flatNodes.length;
1192
+ idToIndex[node.id] = index;
1193
+ node.id = index;
1194
+ flatNodes.push(node);
1195
+ indexToParentIndex.push(parentIndex);
849
1196
  for (const child of node.children) stack.push({
850
1197
  node: child,
851
- parentId: node.id
1198
+ parentIndex: index
852
1199
  });
853
1200
  } while (stack.length > 0);
854
- return {
855
- rawIdToSummarizedNode,
856
- keyToSummarizedNode,
857
- rawIdToParentRawId
858
- };
1201
+ for (const { size, nodeId } of profile.samples) {
1202
+ const nodeIndex = idToIndex[nodeId];
1203
+ if (nodeIndex === void 0) continue;
1204
+ const nodes = [];
1205
+ let currentIndex = nodeIndex;
1206
+ while (true) {
1207
+ nodes.push(flatNodes[currentIndex]);
1208
+ const parentIndex = indexToParentIndex[currentIndex];
1209
+ if (parentIndex === -1) break;
1210
+ currentIndex = parentIndex;
1211
+ }
1212
+ profileBuilder.addSample({
1213
+ values: [size],
1214
+ nodes
1215
+ });
1216
+ }
1217
+ return profileBuilder.build();
859
1218
  };
860
1219
 
861
1220
  //#endregion
862
- //#region src/v8/heap-profile/index.ts
1221
+ //#region src/formats/v8/heap-profile/index.ts
1222
+ const detectV8HeapProfile = (json) => {
1223
+ if (typeof json !== `object` || json === null) return;
1224
+ const object = json;
1225
+ if (typeof object.head !== `object` || object.head === null || !Array.isArray(object.samples)) return;
1226
+ return json;
1227
+ };
863
1228
  /**
864
1229
  * Converts the given V8 sampling heap profile to Markdown.
865
1230
  *
@@ -868,26 +1233,33 @@ const computeProfileGraph = (profile, options) => {
868
1233
  *
869
1234
  * You can generate a V8 heap profile in several ways:
870
1235
  * - [`node --heap-prof`](https://nodejs.org/api/cli.html#--heap-prof)
871
- * - [`v8.writeHeapProfileSync()`](https://nodejs.org/api/v8.html#v8writeheapprofilesyncfilename)
1236
+ * - [`node --inspect`](https://nodejs.org/api/debugger.html#v8-inspector-integration-for-nodejs),
1237
+ * [`deno run --inspect`](https://docs.deno.com/runtime/fundamentals/debugging/#--inspect),
1238
+ * or [`bun --inspect`](https://bun.com/docs/runtime/debugger#inspect) with
1239
+ * [Chrome DevTools](https://developer.chrome.com/docs/devtools/memory-problems/allocation-profiler)
1240
+ * - [Chrome DevTools directly](https://developer.chrome.com/docs/devtools/memory-problems/allocation-profiler)
872
1241
  *
873
1242
  * Note that [`bun --heap-prof`](https://bun.com/docs/project/benchmarking#heap-profiling)
874
1243
  * generates a heap _snapshot_ on exit, not a heap _profile_.
875
1244
  */
876
- const v8HeapProfileToMd = (data, options) => {
877
- const normalizedOptions = normalizeV8ProfileToMdOptions(options);
878
- return formatSummarizedProfile(summarizeProfile(parseProfile(data), normalizedOptions), normalizedOptions);
1245
+ const v8HeapProfileToMd = (data, options) => v8HeapProfileToMdInternal(parseV8HeapProfile(data), options);
1246
+ const v8HeapProfileToMdInternal = (profile, options) => {
1247
+ const normalizedOptions = normalizeProfileToMdOptions(options);
1248
+ return formatV8HeapProfile(summarizeV8HeapProfile(profile, normalizedOptions), normalizedOptions);
879
1249
  };
880
1250
 
881
1251
  //#endregion
882
- //#region src/v8/heap-snapshot/format.ts
883
- const formatSummarizedSnapshot = (snapshot, options) => `${[
1252
+ //#region src/formats/v8/heap-snapshot/format.ts
1253
+ const formatV8HeapSnapshot = (snapshot, options) => `${[
884
1254
  `# Heap snapshot`,
885
1255
  formatOverallSummary(snapshot),
886
- formatLargestConstructors(snapshot, options)
1256
+ formatLargestConstructors(snapshot, options),
1257
+ formatLargestClosures(snapshot, options),
1258
+ formatLargestStrings(snapshot, options)
887
1259
  ].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([
1260
+ const formatOverallSummary = ({ totalSize, nodeCount, edgeCount, nodeCategoryToStats }) => {
1261
+ const hottestObjectCategories = [...nodeCategoryToStats].sort(([, stats1], [, stats2]) => stats2.size - stats1.size);
1262
+ return [`Allocated ${formatBytes(totalSize)} across ${formatCount(nodeCount)} objects and ${formatCount(edgeCount)} references.`, formatTable([
891
1263
  `Category`,
892
1264
  {
893
1265
  content: `%`,
@@ -901,11 +1273,11 @@ const formatOverallSummary = ({ totalSize, objectCount, referenceCount, objectCa
901
1273
  content: `Objects`,
902
1274
  align: `right`
903
1275
  }
904
- ], hottestObjectCategories.map(([type, { size, count }]) => [
1276
+ ], hottestObjectCategories.map(([type, { size, nodeCount: objectCount }]) => [
905
1277
  type,
906
1278
  formatPercent(size / totalSize),
907
1279
  formatBytes(size),
908
- formatCount(count)
1280
+ formatCount(objectCount)
909
1281
  ]))].join(`\n\n`);
910
1282
  };
911
1283
  const formatLargestConstructors = (snapshot, options) => [
@@ -913,9 +1285,10 @@ const formatLargestConstructors = (snapshot, options) => [
913
1285
  formatLargestSelfSizeConstructors(snapshot, options),
914
1286
  formatLargestRetainedSizeConstructors(snapshot, options)
915
1287
  ].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);
1288
+ const formatLargestSelfSizeConstructors = (snapshot, options) => {
1289
+ const { totalSize, constructors } = snapshot;
1290
+ const largestConstructors = selectTopN(constructors.filter(options.includeEntry), options.topN, (constructor1, constructor2) => constructor1.selfSize - constructor2.selfSize);
1291
+ const largestInstanceSections = largestConstructors.map((constructor) => formatLargestSelfSizeConstructorInstances(constructor, snapshot, options)).filter((section) => section !== void 0);
919
1292
  return [
920
1293
  `### Self size`,
921
1294
  `Constructors ranked by bytes allocated for their instances, excluding objects kept reachable by them.`,
@@ -939,16 +1312,16 @@ const formatLargestSelfSizeConstructors = ({ totalSize, constructors }, options)
939
1312
  formatBytes(constructor.selfSize),
940
1313
  formatCount(constructor.instances.length),
941
1314
  inlineCode(constructor.name),
942
- constructor.location ?? inlineCode(`<native>`)
1315
+ formatProfileLocation(constructor.location, options)
943
1316
  ])),
944
1317
  ...largestInstanceSections.length > 0 ? [`#### Instances`, `Instances ranked by contribution to each constructor's self size.`] : [],
945
1318
  ...largestInstanceSections
946
1319
  ].join(`\n\n`);
947
1320
  };
948
- const formatLargestSelfSizeConstructorInstances = (constructor, options) => {
949
- const largestInstances = constructor.instances.toSorted((instance1, instance2) => instance2.selfSize - instance1.selfSize).slice(0, Math.ceil(options.topN / 4));
950
- if (largestInstances.length === 0) return;
951
- return [`##### ${inlineCode(constructor.name)} (${constructor.location ?? inlineCode(`<native>`)})`, formatTable([
1321
+ const formatLargestSelfSizeConstructorInstances = (constructor, { retainerPathOf }, options) => {
1322
+ const largestInstanceGroups = selectLargestInstancesByRetainerPath(constructor.instances, (instance) => instance.selfSize, retainerPathOf, Math.ceil(options.topN / 4)).sort((group1, group2) => group2.selfSize - group1.selfSize);
1323
+ if (largestInstanceGroups.length === 0) return;
1324
+ return [`##### ${inlineCode(constructor.name)} (${formatProfileLocation(constructor.location, options)})`, formatTable([
952
1325
  {
953
1326
  content: `%`,
954
1327
  align: `right`
@@ -957,16 +1330,22 @@ const formatLargestSelfSizeConstructorInstances = (constructor, options) => {
957
1330
  content: `Size`,
958
1331
  align: `right`
959
1332
  },
1333
+ {
1334
+ content: `Instances`,
1335
+ align: `right`
1336
+ },
960
1337
  `Path`
961
- ], largestInstances.map((instance) => [
962
- formatPercent(instance.selfSize / constructor.selfSize),
963
- formatBytes(instance.selfSize),
964
- inlineCode(instance.retainerPath)
1338
+ ], largestInstanceGroups.map((group) => [
1339
+ formatPercent(group.selfSize / constructor.selfSize),
1340
+ formatBytes(group.selfSize),
1341
+ formatCount(group.instanceCount),
1342
+ inlineCode(group.retainerPath)
965
1343
  ]))].join(`\n\n`);
966
1344
  };
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);
1345
+ const formatLargestRetainedSizeConstructors = (snapshot, options) => {
1346
+ const { totalSize, constructors } = snapshot;
1347
+ const largestConstructors = selectTopN(constructors.filter(options.includeEntry), options.topN, (constructor1, constructor2) => constructor1.retainedSize - constructor2.retainedSize);
1348
+ const largestInstanceSections = largestConstructors.map((constructor) => formatLargestRetainedSizeConstructorInstances(constructor, snapshot, options)).filter((section) => section !== void 0);
970
1349
  return [
971
1350
  `### Retained size`,
972
1351
  `Constructors ranked by bytes allocated for their instances and all objects that would be freed if their instances were garbage collected.`,
@@ -979,22 +1358,27 @@ const formatLargestRetainedSizeConstructors = ({ totalSize, constructors }, opti
979
1358
  content: `Size`,
980
1359
  align: `right`
981
1360
  },
1361
+ {
1362
+ content: `Instances`,
1363
+ align: `right`
1364
+ },
982
1365
  `Constructor`,
983
1366
  `Location`
984
1367
  ], largestConstructors.map((constructor) => [
985
1368
  formatPercent(constructor.retainedSize / totalSize),
986
1369
  formatBytes(constructor.retainedSize),
1370
+ formatCount(constructor.instances.length),
987
1371
  inlineCode(constructor.name),
988
- constructor.location ?? inlineCode(`<native>`)
1372
+ formatProfileLocation(constructor.location, options)
989
1373
  ])),
990
1374
  ...largestInstanceSections.length > 0 ? [`#### Instances`, `Instances ranked by contribution to each constructor's retained size.`] : [],
991
1375
  ...largestInstanceSections
992
1376
  ].join(`\n\n`);
993
1377
  };
994
- const formatLargestRetainedSizeConstructorInstances = (constructor, options) => {
995
- const largestInstances = constructor.instances.toSorted((instance1, instance2) => instance2.retainedSize - instance1.retainedSize).slice(0, Math.ceil(options.topN / 4));
996
- if (largestInstances.length === 0) return;
997
- return [`##### ${inlineCode(constructor.name)} (${constructor.location ?? inlineCode(`<native>`)})`, formatTable([
1378
+ const formatLargestRetainedSizeConstructorInstances = (constructor, { retainerPathOf }, options) => {
1379
+ const largestInstanceGroups = selectLargestInstancesByRetainerPath(constructor.instances, (instance) => instance.retainedSize, retainerPathOf, Math.ceil(options.topN / 4)).sort((group1, group2) => group2.retainedSize - group1.retainedSize);
1380
+ if (largestInstanceGroups.length === 0) return;
1381
+ return [`##### ${inlineCode(constructor.name)} (${formatProfileLocation(constructor.location, options)})`, formatTable([
998
1382
  {
999
1383
  content: `%`,
1000
1384
  align: `right`
@@ -1003,219 +1387,417 @@ const formatLargestRetainedSizeConstructorInstances = (constructor, options) =>
1003
1387
  content: `Size`,
1004
1388
  align: `right`
1005
1389
  },
1390
+ {
1391
+ content: `Instances`,
1392
+ align: `right`
1393
+ },
1006
1394
  `Path`
1007
- ], largestInstances.map((instance) => [
1008
- formatPercent(instance.retainedSize / constructor.retainedSize),
1009
- formatBytes(instance.retainedSize),
1010
- inlineCode(instance.retainerPath)
1395
+ ], largestInstanceGroups.map((group) => [
1396
+ formatPercent(group.retainedSize / constructor.retainedSize),
1397
+ formatBytes(group.retainedSize),
1398
+ formatCount(group.instanceCount),
1399
+ inlineCode(group.retainerPath)
1011
1400
  ]))].join(`\n\n`);
1012
1401
  };
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;
1402
+ const selectLargestInstancesByRetainerPath = (instances, sizeOf, retainerPathOf, topN) => {
1403
+ const heap = new MaxHeap(instances, (instance1, instance2) => sizeOf(instance1) - sizeOf(instance2));
1404
+ const pathToGroup = /* @__PURE__ */ new Map();
1405
+ while (heap.length > 0 && pathToGroup.size < topN) {
1406
+ const instance = heap.pop();
1407
+ const retainerPath = retainerPathOf(instance.id);
1408
+ let group = pathToGroup.get(retainerPath);
1409
+ if (!group) {
1410
+ group = {
1411
+ retainerPath,
1412
+ instanceCount: 0,
1413
+ selfSize: 0,
1414
+ retainedSize: 0
1415
+ };
1416
+ pathToGroup.set(retainerPath, group);
1417
+ }
1418
+ group.instanceCount++;
1419
+ group.selfSize += instance.selfSize;
1420
+ group.retainedSize += instance.retainedSize;
1421
+ }
1422
+ return [...pathToGroup.values()];
1423
+ };
1424
+ const formatLargestClosures = (snapshot, options) => {
1425
+ const { totalSize, closures, retainerPathOf } = snapshot;
1426
+ const largestClosures = selectTopN(closures.filter((closure) => options.includeEntry({
1427
+ ...closure,
1428
+ id: closure.largestInstanceId
1429
+ })), options.topN, (closure1, closure2) => closure1.retainedSize - closure2.retainedSize);
1430
+ const retainedSections = largestClosures.map((closure) => formatClosureRetainedObjects(closure, snapshot, options)).filter((section) => section !== void 0);
1431
+ return [
1432
+ `## Largest closures`,
1433
+ `Closures ranked by bytes that would be freed if the closure were garbage collected.`,
1434
+ formatTable([
1435
+ {
1436
+ content: `%`,
1437
+ align: `right`
1438
+ },
1439
+ {
1440
+ content: `Retained`,
1441
+ align: `right`
1442
+ },
1443
+ {
1444
+ content: `Instances`,
1445
+ align: `right`
1446
+ },
1447
+ {
1448
+ content: `Paths`,
1449
+ align: `right`
1450
+ },
1451
+ `Name`,
1452
+ `Location`,
1453
+ `Example path`
1454
+ ], largestClosures.map((closure) => [
1455
+ formatPercent(closure.retainedSize / totalSize),
1456
+ formatBytes(closure.retainedSize),
1457
+ formatCount(closure.instanceIds.length),
1458
+ formatCount(new Set(closure.instanceIds.map(retainerPathOf)).size),
1459
+ inlineCode(closure.name),
1460
+ formatProfileLocation(closure.location, options),
1461
+ inlineCode(retainerPathOf(closure.largestInstanceId))
1462
+ ])),
1463
+ ...retainedSections.length > 0 ? [`### Retained`, `Objects ranked by contribution to each closure's retained size.`] : [],
1464
+ ...retainedSections
1465
+ ].join(`\n\n`);
1466
+ };
1467
+ const formatClosureRetainedObjects = (closure, { retainedNodesOf, retainerPathOf }, options) => {
1468
+ const instanceIdToSeen = new DynamicTypedArray(new Uint8Array(256));
1469
+ const allRetainedNodes = [];
1470
+ for (const instanceId of closure.instanceIds) for (const node of retainedNodesOf(instanceId)) {
1471
+ const seen = instanceIdToSeen.ensureCapacity(node.id + 1);
1472
+ if (seen[node.id]) continue;
1473
+ seen[node.id] = 1;
1474
+ if (options.includeEntry(node)) allRetainedNodes.push(node);
1475
+ }
1476
+ const retainedNodes = selectTopN(allRetainedNodes, Math.ceil(options.topN / 4), (node1, node2) => node1.selfSize - node2.selfSize);
1477
+ if (retainedNodes.length === 0) return;
1478
+ return [`#### ${inlineCode(closure.name)} (${formatProfileLocation(closure.location, options)})`, formatTable([
1479
+ {
1480
+ content: `%`,
1481
+ align: `right`
1482
+ },
1483
+ {
1484
+ content: `Self`,
1485
+ align: `right`
1486
+ },
1487
+ `Name`,
1488
+ `Path`
1489
+ ], retainedNodes.map((node) => [
1490
+ formatPercent(node.selfSize / closure.retainedSize),
1491
+ formatBytes(node.selfSize),
1492
+ inlineCode(node.name || `(unknown)`),
1493
+ inlineCode(retainerPathOf(node.id))
1494
+ ]))].join(`\n\n`);
1495
+ };
1496
+ const formatLargestStrings = ({ totalSize, strings, retainerPathOf }, options) => {
1497
+ return [
1498
+ `## Largest strings`,
1499
+ `Strings ranked by bytes allocated for them.`,
1500
+ formatTable([
1501
+ {
1502
+ content: `%`,
1503
+ align: `right`
1504
+ },
1505
+ {
1506
+ content: `Size`,
1507
+ align: `right`
1508
+ },
1509
+ `Value`,
1510
+ `Path`
1511
+ ], selectTopN(strings, options.topN, (string1, string2) => string1.selfSize - string2.selfSize).map((string) => [
1512
+ formatPercent(string.selfSize / totalSize),
1513
+ formatBytes(string.selfSize),
1514
+ inlineCode(string.name),
1515
+ inlineCode(retainerPathOf(string.id))
1516
+ ]))
1517
+ ].join(`\n\n`);
1021
1518
  };
1022
1519
 
1023
1520
  //#endregion
1024
- //#region src/v8/heap-snapshot/parse.ts
1025
- const parseSnapshot = (data) => JSON.parse(data);
1521
+ //#region src/formats/v8/heap-snapshot/parse.ts
1522
+ const parseV8HeapSnapshot = (data) => parseJson(data);
1026
1523
 
1027
1524
  //#endregion
1028
- //#region src/v8/heap-snapshot/summarize.ts
1029
- const summarizeSnapshot = (snapshot, options) => {
1030
- const { snapshot: { meta, node_count: objectCount, edge_count: referenceCount }, nodes, strings } = snapshot;
1525
+ //#region src/formats/v8/heap-snapshot/summarize.ts
1526
+ const summarizeV8HeapSnapshot = (snapshot, options) => {
1527
+ const { snapshot: { meta, node_count: nodeCount, edge_count: edgeCount }, nodes } = snapshot;
1031
1528
  const [nodeTypes] = meta.node_types;
1032
1529
  const fieldLayout = computeFieldLayout(meta);
1033
1530
  const nodeAdjacencyGraph = computeNodeAdjacencyGraph(snapshot, fieldLayout);
1034
- const nodeIndexToLocation = computeNodeIndexToLocation(snapshot, nodeAdjacencyGraph, fieldLayout, options);
1531
+ const nodeOrdinalToLocation = computeNodeOrdinalToLocation(snapshot, nodeAdjacencyGraph, fieldLayout);
1035
1532
  const immediateDominatorGraph = computeImmediateDominatorGraph(snapshot, nodeAdjacencyGraph);
1036
1533
  const nodeOrdinalToRetainedSize = computeNodeOrdinalToRetainedSize(snapshot, immediateDominatorGraph, fieldLayout);
1037
1534
  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++) {
1535
+ const nodeCategoryToStats = /* @__PURE__ */ new Map();
1536
+ const constructors = [];
1537
+ const nameToConstructorIndex = /* @__PURE__ */ new Map();
1538
+ const nodeOrdinalToConstructorIndex = new Int32Array(nodeCount).fill(-1);
1539
+ const closures = [];
1540
+ const keyToClosureIndex = /* @__PURE__ */ new Map();
1541
+ const nodeOrdinalToClosureIndex = new Int32Array(nodeCount).fill(-1);
1542
+ const strings = [];
1543
+ for (let nodeOrdinal = 0; nodeOrdinal < nodeCount; nodeOrdinal++) {
1042
1544
  const nodeIndex = nodeOrdinal * fieldLayout.nodeFieldCount;
1043
1545
  const selfSize = nodes[nodeIndex + fieldLayout.nodeSelfSizeOffset];
1044
1546
  totalSize += selfSize;
1045
1547
  const nodeType = nodes[nodeIndex + fieldLayout.nodeTypeOffset];
1046
1548
  const category = nodeTypes[nodeType];
1047
- let categoryStats = objectCategoryToSizeStats.get(category);
1549
+ let categoryStats = nodeCategoryToStats.get(category);
1048
1550
  if (!categoryStats) {
1049
1551
  categoryStats = {
1050
1552
  size: 0,
1051
- count: 0
1553
+ nodeCount: 0
1052
1554
  };
1053
- objectCategoryToSizeStats.set(category, categoryStats);
1555
+ nodeCategoryToStats.set(category, categoryStats);
1054
1556
  }
1055
1557
  categoryStats.size += selfSize;
1056
- categoryStats.count++;
1558
+ categoryStats.nodeCount++;
1057
1559
  switch (nodeType) {
1058
1560
  case fieldLayout.nodeTypeObject:
1059
1561
  case fieldLayout.nodeTypeNative: {
1060
- const name = strings[nodes[nodeIndex + fieldLayout.nodeNameOffset]];
1061
- let constructor = nameToConstructor.get(name);
1062
- if (!constructor) {
1562
+ const name = formatNodeLabel(nodeIndex, snapshot, fieldLayout, options);
1563
+ let constructorIndex = nameToConstructorIndex.get(name);
1564
+ let constructor;
1565
+ if (constructorIndex === void 0) {
1566
+ constructorIndex = constructors.length;
1063
1567
  constructor = {
1568
+ id: nodeOrdinal,
1064
1569
  name,
1065
1570
  location: void 0,
1066
1571
  selfSize: 0,
1067
1572
  retainedSize: 0,
1068
1573
  instances: []
1069
1574
  };
1070
- nameToConstructor.set(name, constructor);
1071
- }
1575
+ constructors.push(constructor);
1576
+ nameToConstructorIndex.set(name, constructorIndex);
1577
+ } else constructor = constructors[constructorIndex];
1072
1578
  constructor.selfSize += selfSize;
1073
- constructor.location ??= nodeIndexToLocation.get(nodeIndex);
1074
- let retainerPath;
1579
+ constructor.location ??= nodeOrdinalToLocation[nodeOrdinal];
1075
1580
  constructor.instances.push({
1581
+ id: nodeOrdinal,
1582
+ name: constructor.name,
1076
1583
  selfSize,
1077
1584
  retainedSize: nodeOrdinalToRetainedSize[nodeOrdinal],
1078
- get retainerPath() {
1079
- return retainerPath ??= computeRetainerPath(nodeOrdinal, snapshot, nodeAdjacencyGraph, nodeIndexToLocation, immediateDominatorGraph, fieldLayout);
1080
- }
1585
+ location: constructor.location
1081
1586
  });
1082
- nodeOrdinalToConstructor.set(nodeOrdinal, constructor);
1587
+ nodeOrdinalToConstructorIndex[nodeOrdinal] = constructorIndex;
1588
+ break;
1589
+ }
1590
+ case fieldLayout.nodeTypeClosure: {
1591
+ const name = formatNodeLabel(nodeIndex, snapshot, fieldLayout, options);
1592
+ const location = nodeOrdinalToLocation[nodeOrdinal];
1593
+ const key = `${name}|${location ? formatProfileLocation(location, options) : ``}`;
1594
+ const retainedSize = nodeOrdinalToRetainedSize[nodeOrdinal];
1595
+ let closureIndex = keyToClosureIndex.get(key);
1596
+ if (closureIndex === void 0) {
1597
+ closureIndex = closures.length;
1598
+ closures.push({
1599
+ name,
1600
+ location,
1601
+ retainedSize: 0,
1602
+ largestInstanceId: nodeOrdinal,
1603
+ instanceIds: []
1604
+ });
1605
+ keyToClosureIndex.set(key, closureIndex);
1606
+ }
1607
+ const closure = closures[closureIndex];
1608
+ closure.instanceIds.push(nodeOrdinal);
1609
+ if (retainedSize > nodeOrdinalToRetainedSize[closure.largestInstanceId]) closure.largestInstanceId = nodeOrdinal;
1610
+ nodeOrdinalToClosureIndex[nodeOrdinal] = closureIndex;
1083
1611
  break;
1084
1612
  }
1613
+ case fieldLayout.nodeTypeString:
1614
+ case fieldLayout.nodeTypeSlicedString:
1615
+ case fieldLayout.nodeTypeConcatenatedString:
1616
+ strings.push({
1617
+ id: nodeOrdinal,
1618
+ name: formatNodeLabel(nodeIndex, snapshot, fieldLayout, options),
1619
+ selfSize,
1620
+ retainedSize: selfSize
1621
+ });
1622
+ break;
1085
1623
  }
1086
1624
  }
1087
- attributeGroupRetainedSizes({
1088
- nodeOrdinalToRetainedSize,
1089
- ordinalToImmediateDominatorOrdinal: immediateDominatorGraph.ordinalToImmediateDominatorOrdinal,
1090
- nodeOrdinalToGroup: nodeOrdinalToConstructor
1091
- });
1092
- const constructors = [...nameToConstructor.values()];
1625
+ attributeGroupRetainedSizes(nodeOrdinalToRetainedSize, immediateDominatorGraph, nodeOrdinalToConstructorIndex, constructors);
1626
+ attributeGroupRetainedSizes(nodeOrdinalToRetainedSize, immediateDominatorGraph, nodeOrdinalToClosureIndex, closures);
1093
1627
  return {
1094
1628
  totalSize,
1095
- objectCount,
1096
- referenceCount,
1097
- objectCategoryToSizeStats,
1098
- constructors
1629
+ nodeCount,
1630
+ edgeCount,
1631
+ nodeCategoryToStats,
1632
+ constructors,
1633
+ closures,
1634
+ strings,
1635
+ retainerPathOf: (nodeOrdinal) => computeRetainerPath(nodeOrdinal, snapshot, nodeAdjacencyGraph, nodeOrdinalToLocation, immediateDominatorGraph, fieldLayout, options),
1636
+ retainedNodesOf: (nodeOrdinal) => computeRetainedNodes(nodeOrdinal, snapshot, nodeOrdinalToRetainedSize, immediateDominatorGraph, fieldLayout, options)
1099
1637
  };
1100
1638
  };
1101
1639
  const computeNodeAdjacencyGraph = ({ snapshot: { node_count: nodeCount }, nodes, edges }, fieldLayout) => {
1102
- const ordinalToSuccessors = Array.from({ length: nodeCount }, () => []);
1103
- const ordinalToPredecessors = Array.from({ length: nodeCount }, () => []);
1640
+ const ordinalToSuccessorCount = new Int32Array(nodeCount);
1641
+ const ordinalToPredecessorCount = new Int32Array(nodeCount);
1104
1642
  let nodeEdgesStartIndex = 0;
1105
1643
  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
- });
1644
+ const nodeEdgeCount = nodes[nodeOrdinal * fieldLayout.nodeFieldCount + fieldLayout.nodeEdgeCountOffset];
1645
+ for (let edgeOrdinal = 0; edgeOrdinal < nodeEdgeCount; edgeOrdinal++) {
1646
+ const edgeIndex = nodeEdgesStartIndex + edgeOrdinal * fieldLayout.edgeFieldCount;
1647
+ if (edges[edgeIndex + fieldLayout.edgeTypeOffset] === fieldLayout.edgeTypeWeak) continue;
1648
+ const successorOrdinal = edges[edgeIndex + fieldLayout.edgeToNodeOffset] / fieldLayout.nodeFieldCount;
1649
+ ordinalToSuccessorCount[nodeOrdinal]++;
1650
+ ordinalToPredecessorCount[successorOrdinal]++;
1651
+ }
1652
+ nodeEdgesStartIndex += nodeEdgeCount * fieldLayout.edgeFieldCount;
1653
+ }
1654
+ const ordinalToSuccessorStartOffset = new Int32Array(nodeCount + 1);
1655
+ const ordinalToPredecessorStartOffset = new Int32Array(nodeCount + 1);
1656
+ for (let i = 0; i < nodeCount; i++) {
1657
+ ordinalToSuccessorStartOffset[i + 1] = ordinalToSuccessorStartOffset[i] + ordinalToSuccessorCount[i];
1658
+ ordinalToPredecessorStartOffset[i + 1] = ordinalToPredecessorStartOffset[i] + ordinalToPredecessorCount[i];
1659
+ }
1660
+ const totalEdges = ordinalToSuccessorStartOffset[nodeCount];
1661
+ const offsetToSuccessorOrdinal = new Int32Array(totalEdges);
1662
+ const offsetToSuccessorEdgeIndex = new Int32Array(totalEdges);
1663
+ const offsetToPredecessorOrdinal = new Int32Array(totalEdges);
1664
+ const offsetToPredecessorEdgeIndex = new Int32Array(totalEdges);
1665
+ ordinalToSuccessorCount.fill(0);
1666
+ ordinalToPredecessorCount.fill(0);
1667
+ nodeEdgesStartIndex = 0;
1668
+ for (let nodeOrdinal = 0; nodeOrdinal < nodeCount; nodeOrdinal++) {
1669
+ const nodeEdgeCount = nodes[nodeOrdinal * fieldLayout.nodeFieldCount + fieldLayout.nodeEdgeCountOffset];
1670
+ for (let edgeOrdinal = 0; edgeOrdinal < nodeEdgeCount; edgeOrdinal++) {
1671
+ const edgeIndex = nodeEdgesStartIndex + edgeOrdinal * fieldLayout.edgeFieldCount;
1672
+ if (edges[edgeIndex + fieldLayout.edgeTypeOffset] === fieldLayout.edgeTypeWeak) continue;
1673
+ const successorOrdinal = edges[edgeIndex + fieldLayout.edgeToNodeOffset] / fieldLayout.nodeFieldCount;
1674
+ const successorOffset = ordinalToSuccessorStartOffset[nodeOrdinal] + ordinalToSuccessorCount[nodeOrdinal];
1675
+ offsetToSuccessorOrdinal[successorOffset] = successorOrdinal;
1676
+ offsetToSuccessorEdgeIndex[successorOffset] = edgeIndex;
1677
+ ordinalToSuccessorCount[nodeOrdinal]++;
1678
+ const predecessorOffset = ordinalToPredecessorStartOffset[successorOrdinal] + ordinalToPredecessorCount[successorOrdinal];
1679
+ offsetToPredecessorOrdinal[predecessorOffset] = nodeOrdinal;
1680
+ offsetToPredecessorEdgeIndex[predecessorOffset] = edgeIndex;
1681
+ ordinalToPredecessorCount[successorOrdinal]++;
1119
1682
  }
1120
- nodeEdgesStartIndex += edgeCount * fieldLayout.edgeFieldCount;
1683
+ nodeEdgesStartIndex += nodeEdgeCount * fieldLayout.edgeFieldCount;
1121
1684
  }
1122
1685
  return {
1123
- ordinalToSuccessors,
1124
- ordinalToPredecessors
1686
+ ordinalToSuccessorStartOffset,
1687
+ offsetToSuccessorOrdinal,
1688
+ offsetToSuccessorEdgeIndex,
1689
+ ordinalToPredecessorStartOffset,
1690
+ offsetToPredecessorOrdinal,
1691
+ offsetToPredecessorEdgeIndex
1125
1692
  };
1126
1693
  };
1127
- const computeNodeIndexToLocation = ({ nodes, edges, strings, locations }, nodeAdjacencyGraph, fieldLayout, options) => {
1128
- const followNamedEdge = (nodeIndex, targetEdgeName) => {
1129
- 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];
1694
+ const computeNodeOrdinalToLocation = ({ nodes, edges, strings, locations }, { ordinalToSuccessorStartOffset, offsetToSuccessorEdgeIndex }, { nodeFieldCount, nodeTypeOffset, nodeNameOffset, nodeTypeClosure, edgeNameOrIndexOffset, edgeToNodeOffset, locationFieldCount, locationScriptIdOffset, locationObjectIndexOffset, locationLineOffset, locationColumnOffset }) => {
1695
+ const namedEdgeToNodeIndex = (nodeIndex, targetEdgeName) => {
1696
+ const nodeOrdinal = nodeIndex / nodeFieldCount;
1697
+ const successorStartOffset = ordinalToSuccessorStartOffset[nodeOrdinal];
1698
+ const successorEndOffset = ordinalToSuccessorStartOffset[nodeOrdinal + 1];
1699
+ for (let successorOffset = successorStartOffset; successorOffset < successorEndOffset; successorOffset++) {
1700
+ const edgeIndex = offsetToSuccessorEdgeIndex[successorOffset];
1701
+ if (strings[edges[edgeIndex + edgeNameOrIndexOffset]] === targetEdgeName) return edges[edgeIndex + edgeToNodeOffset];
1702
+ }
1132
1703
  };
1133
1704
  const scriptIdToFileLocation = /* @__PURE__ */ new Map();
1134
- for (let locationIndex = 0; locationIndex < locations.length; locationIndex += fieldLayout.locationFieldCount) {
1135
- const scriptId = locations[locationIndex + fieldLayout.locationScriptIdOffset];
1705
+ for (let locationIndex = 0; locationIndex < locations.length; locationIndex += locationFieldCount) {
1706
+ const scriptId = locations[locationIndex + locationScriptIdOffset];
1136
1707
  if (scriptIdToFileLocation.has(scriptId)) continue;
1137
- const nodeIndex = locations[locationIndex + fieldLayout.locationObjectIndexOffset];
1138
- if (nodes[nodeIndex + fieldLayout.nodeTypeOffset] !== fieldLayout.nodeTypeClosure) continue;
1139
- const sharedNodeIndex = followNamedEdge(nodeIndex, `shared`);
1708
+ const nodeIndex = locations[locationIndex + locationObjectIndexOffset];
1709
+ if (nodes[nodeIndex + nodeTypeOffset] !== nodeTypeClosure) continue;
1710
+ const sharedNodeIndex = namedEdgeToNodeIndex(nodeIndex, `shared`);
1140
1711
  if (sharedNodeIndex === void 0) continue;
1141
- const scriptNodeIndex = followNamedEdge(sharedNodeIndex, `script`);
1712
+ const scriptNodeIndex = namedEdgeToNodeIndex(sharedNodeIndex, `script`);
1142
1713
  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);
1148
- if (fileLocation) scriptIdToFileLocation.set(scriptId, fileLocation);
1714
+ const locationNodeIndex = namedEdgeToNodeIndex(scriptNodeIndex, `name`);
1715
+ if (locationNodeIndex === void 0) continue;
1716
+ const location = strings[nodes[locationNodeIndex + nodeNameOffset]];
1717
+ if (!location) continue;
1718
+ scriptIdToFileLocation.set(scriptId, location);
1149
1719
  }
1150
- const nodeIndexToLocation = /* @__PURE__ */ new Map();
1151
- for (let locationIndex = 0; locationIndex < locations.length; locationIndex += fieldLayout.locationFieldCount) {
1152
- const scriptId = locations[locationIndex + fieldLayout.locationScriptIdOffset];
1720
+ const nodeOrdinalToLocation = [];
1721
+ const fileLocationToUrl = /* @__PURE__ */ new Map();
1722
+ for (let locationIndex = 0; locationIndex < locations.length; locationIndex += locationFieldCount) {
1723
+ const scriptId = locations[locationIndex + locationScriptIdOffset];
1153
1724
  const fileLocation = scriptIdToFileLocation.get(scriptId);
1154
1725
  if (!fileLocation) continue;
1155
- const nodeIndex = locations[locationIndex + fieldLayout.locationObjectIndexOffset];
1156
- const line = locations[locationIndex + fieldLayout.locationLineOffset];
1157
- const column = locations[locationIndex + fieldLayout.locationColumnOffset];
1158
- nodeIndexToLocation.set(nodeIndex, `${fileLocation}:${line + 1}:${column + 1}`);
1726
+ let url = fileLocationToUrl.get(fileLocation);
1727
+ if (url === void 0) {
1728
+ url = makeProfileLocation({ urlOrPath: fileLocation })?.url ?? null;
1729
+ fileLocationToUrl.set(fileLocation, url);
1730
+ }
1731
+ if (!url) continue;
1732
+ const nodeIndex = locations[locationIndex + locationObjectIndexOffset];
1733
+ const line = locations[locationIndex + locationLineOffset];
1734
+ const column = locations[locationIndex + locationColumnOffset];
1735
+ nodeOrdinalToLocation[nodeIndex / nodeFieldCount] = {
1736
+ url,
1737
+ line: line + 1,
1738
+ column: column + 1
1739
+ };
1159
1740
  }
1160
- return nodeIndexToLocation;
1741
+ return nodeOrdinalToLocation;
1161
1742
  };
1162
1743
  /**
1163
- * Computes the immediate dominators of every object.
1744
+ * Computes the immediate dominators of every node.
1164
1745
  *
1165
- * Weak edges are excluded because they don't keep objects alive.
1746
+ * Weak edges are excluded because they don't keep nodes alive.
1166
1747
  *
1167
1748
  * Uses the Lengauer-Tarjan dominator tree algorithm.
1168
1749
  *
1169
1750
  * @see https://en.wikipedia.org/wiki/Dominator_(graph_theory)
1170
1751
  * @see https://www.cs.princeton.edu/courses/archive/fall03/cs528/handouts/a%20fast%20algorithm%20for%20finding.pdf
1171
1752
  */
1172
- const computeImmediateDominatorGraph = (snapshot, { ordinalToSuccessors, ordinalToPredecessors }) => {
1753
+ const computeImmediateDominatorGraph = (snapshot, { ordinalToSuccessorStartOffset, offsetToSuccessorOrdinal, ordinalToPredecessorStartOffset, offsetToPredecessorOrdinal }) => {
1173
1754
  const { snapshot: { node_count: nodeCount } } = snapshot;
1174
- const ordinalToDfsIndex = new Int32Array(nodeCount).fill(-1);
1755
+ const ordinalToImmediateDominatorOrdinal = new Int32Array(nodeCount).fill(-1);
1175
1756
  const dfsIndexToOrdinal = new Int32Array(nodeCount);
1176
1757
  const ordinalToParentOrdinal = new Int32Array(nodeCount).fill(-1);
1758
+ const ordinalToDfsIndex = new Int32Array(nodeCount).fill(-1);
1177
1759
  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
1760
  ordinalToDfsIndex[0] = 0;
1183
- ordinalToSemidominatorDfsIndex[0] = 0;
1184
1761
  dfsIndexToOrdinal[0] = 0;
1762
+ const dfsStackOrdinals = new Int32Array(nodeCount);
1763
+ const dfsStackOffsets = new Int32Array(nodeCount);
1764
+ dfsStackOffsets[0] = ordinalToSuccessorStartOffset[0];
1185
1765
  let dfsIndex = 1;
1186
- const dfsStack = [{
1187
- nodeOrdinal: 0,
1188
- nextChildIndex: 0
1189
- }];
1766
+ let dfsStackSize = 1;
1190
1767
  do {
1191
- const frame = dfsStack.at(-1);
1192
- if (frame.nextChildIndex === ordinalToSuccessors[frame.nodeOrdinal].length) {
1193
- dfsStack.pop();
1768
+ const topOffset = dfsStackSize - 1;
1769
+ const nodeOrdinal = dfsStackOrdinals[topOffset];
1770
+ const nextOffset = dfsStackOffsets[topOffset];
1771
+ if (nextOffset === ordinalToSuccessorStartOffset[nodeOrdinal + 1]) {
1772
+ dfsStackSize--;
1194
1773
  continue;
1195
1774
  }
1196
- const childOrdinal = ordinalToSuccessors[frame.nodeOrdinal][frame.nextChildIndex].targetNodeOrdinal;
1197
- frame.nextChildIndex++;
1775
+ const childOrdinal = offsetToSuccessorOrdinal[nextOffset];
1776
+ dfsStackOffsets[topOffset]++;
1198
1777
  if (ordinalToDfsIndex[childOrdinal] !== -1) continue;
1199
- ordinalToParentOrdinal[childOrdinal] = frame.nodeOrdinal;
1778
+ ordinalToParentOrdinal[childOrdinal] = nodeOrdinal;
1200
1779
  ordinalToDfsIndex[childOrdinal] = dfsIndex;
1201
1780
  ordinalToSemidominatorDfsIndex[childOrdinal] = dfsIndex;
1202
1781
  dfsIndexToOrdinal[dfsIndex] = childOrdinal;
1203
1782
  dfsIndex++;
1204
- dfsStack.push({
1205
- nodeOrdinal: childOrdinal,
1206
- nextChildIndex: 0
1207
- });
1208
- } while (dfsStack.length > 0);
1783
+ dfsStackOrdinals[dfsStackSize] = childOrdinal;
1784
+ dfsStackOffsets[dfsStackSize] = ordinalToSuccessorStartOffset[childOrdinal];
1785
+ dfsStackSize++;
1786
+ } while (dfsStackSize > 0);
1209
1787
  const reachableCount = dfsIndex;
1788
+ const ancestorNodeOrdinalPath = new Int32Array(nodeCount);
1789
+ const ordinalToForestAncestorOrdinal = new Int32Array(nodeCount).fill(-1);
1790
+ const ordinalToMinSemiAncestorOrdinal = new Int32Array(nodeCount);
1791
+ for (let i = 0; i < nodeCount; i++) ordinalToMinSemiAncestorOrdinal[i] = i;
1210
1792
  const compressAncestorPath = (startNodeOrdinal) => {
1211
- const nodeOrdinalPath = [];
1793
+ let pathLength = 0;
1212
1794
  let nodeOrdinal = startNodeOrdinal;
1213
1795
  while (ordinalToForestAncestorOrdinal[nodeOrdinal] !== -1 && ordinalToForestAncestorOrdinal[ordinalToForestAncestorOrdinal[nodeOrdinal]] !== -1) {
1214
- nodeOrdinalPath.push(nodeOrdinal);
1796
+ ancestorNodeOrdinalPath[pathLength++] = nodeOrdinal;
1215
1797
  nodeOrdinal = ordinalToForestAncestorOrdinal[nodeOrdinal];
1216
1798
  }
1217
- for (let pathIndex = nodeOrdinalPath.length - 1; pathIndex >= 0; pathIndex--) {
1218
- const pathNodeOrdinal = nodeOrdinalPath[pathIndex];
1799
+ for (let pathIndex = pathLength - 1; pathIndex >= 0; pathIndex--) {
1800
+ const pathNodeOrdinal = ancestorNodeOrdinalPath[pathIndex];
1219
1801
  const ancestorOrdinal = ordinalToForestAncestorOrdinal[pathNodeOrdinal];
1220
1802
  if (ordinalToSemidominatorDfsIndex[ordinalToMinSemiAncestorOrdinal[ancestorOrdinal]] < ordinalToSemidominatorDfsIndex[ordinalToMinSemiAncestorOrdinal[pathNodeOrdinal]]) ordinalToMinSemiAncestorOrdinal[pathNodeOrdinal] = ordinalToMinSemiAncestorOrdinal[ancestorOrdinal];
1221
1803
  ordinalToForestAncestorOrdinal[pathNodeOrdinal] = ordinalToForestAncestorOrdinal[ancestorOrdinal];
@@ -1226,69 +1808,157 @@ const computeImmediateDominatorGraph = (snapshot, { ordinalToSuccessors, ordinal
1226
1808
  compressAncestorPath(nodeOrdinal);
1227
1809
  return ordinalToMinSemiAncestorOrdinal[nodeOrdinal];
1228
1810
  };
1811
+ const pendingHeadOrdinals = new Int32Array(nodeCount).fill(-1);
1812
+ const pendingNextOrdinals = new Int32Array(nodeCount).fill(-1);
1229
1813
  for (let dfsIndex = reachableCount - 1; dfsIndex >= 1; dfsIndex--) {
1230
1814
  const nodeOrdinal = dfsIndexToOrdinal[dfsIndex];
1231
- for (const { targetNodeOrdinal: predecessorOrdinal } of ordinalToPredecessors[nodeOrdinal]) {
1815
+ const predecessorStartOffset = ordinalToPredecessorStartOffset[nodeOrdinal];
1816
+ const predecessorEndOffset = ordinalToPredecessorStartOffset[nodeOrdinal + 1];
1817
+ for (let predecessorOffset = predecessorStartOffset; predecessorOffset < predecessorEndOffset; predecessorOffset++) {
1818
+ const predecessorOrdinal = offsetToPredecessorOrdinal[predecessorOffset];
1232
1819
  if (ordinalToDfsIndex[predecessorOrdinal] === -1) continue;
1233
1820
  const minAncestorOrdinal = minSemiAncestorOrdinal(predecessorOrdinal);
1234
1821
  if (ordinalToSemidominatorDfsIndex[minAncestorOrdinal] < ordinalToSemidominatorDfsIndex[nodeOrdinal]) ordinalToSemidominatorDfsIndex[nodeOrdinal] = ordinalToSemidominatorDfsIndex[minAncestorOrdinal];
1235
1822
  }
1236
- ordinalToPendingOrdinals[dfsIndexToOrdinal[ordinalToSemidominatorDfsIndex[nodeOrdinal]]].push(nodeOrdinal);
1823
+ const semiBucketOrdinal = dfsIndexToOrdinal[ordinalToSemidominatorDfsIndex[nodeOrdinal]];
1824
+ pendingNextOrdinals[nodeOrdinal] = pendingHeadOrdinals[semiBucketOrdinal];
1825
+ pendingHeadOrdinals[semiBucketOrdinal] = nodeOrdinal;
1237
1826
  ordinalToForestAncestorOrdinal[nodeOrdinal] = ordinalToParentOrdinal[nodeOrdinal];
1238
- for (const pendingOrdinal of ordinalToPendingOrdinals[ordinalToParentOrdinal[nodeOrdinal]]) {
1827
+ const parentOrdinal = ordinalToParentOrdinal[nodeOrdinal];
1828
+ let pendingOrdinal = pendingHeadOrdinals[parentOrdinal];
1829
+ pendingHeadOrdinals[parentOrdinal] = -1;
1830
+ while (pendingOrdinal !== -1) {
1831
+ const nextPending = pendingNextOrdinals[pendingOrdinal];
1239
1832
  const ancestorOrdinal = minSemiAncestorOrdinal(pendingOrdinal);
1240
- ordinalToImmediateDominatorOrdinal[pendingOrdinal] = ordinalToSemidominatorDfsIndex[ancestorOrdinal] < ordinalToSemidominatorDfsIndex[pendingOrdinal] ? ancestorOrdinal : ordinalToParentOrdinal[nodeOrdinal];
1833
+ ordinalToImmediateDominatorOrdinal[pendingOrdinal] = ordinalToSemidominatorDfsIndex[ancestorOrdinal] < ordinalToSemidominatorDfsIndex[pendingOrdinal] ? ancestorOrdinal : parentOrdinal;
1834
+ pendingOrdinal = nextPending;
1241
1835
  }
1242
- ordinalToPendingOrdinals[ordinalToParentOrdinal[nodeOrdinal]].length = 0;
1243
1836
  }
1244
1837
  for (let dfsIndex = 1; dfsIndex < reachableCount; dfsIndex++) {
1245
1838
  const nodeOrdinal = dfsIndexToOrdinal[dfsIndex];
1246
1839
  if (ordinalToImmediateDominatorOrdinal[nodeOrdinal] !== dfsIndexToOrdinal[ordinalToSemidominatorDfsIndex[nodeOrdinal]]) ordinalToImmediateDominatorOrdinal[nodeOrdinal] = ordinalToImmediateDominatorOrdinal[ordinalToImmediateDominatorOrdinal[nodeOrdinal]];
1247
1840
  }
1248
1841
  ordinalToImmediateDominatorOrdinal[0] = 0;
1842
+ const dominatorOrdinalToDominateeCount = new Int32Array(nodeCount);
1843
+ for (let nodeOrdinal = 1; nodeOrdinal < nodeCount; nodeOrdinal++) {
1844
+ const dominatorOrdinal = ordinalToImmediateDominatorOrdinal[nodeOrdinal];
1845
+ if (dominatorOrdinal !== -1) dominatorOrdinalToDominateeCount[dominatorOrdinal]++;
1846
+ }
1847
+ const immediateDominateeOrdinalToStartOffset = new Int32Array(nodeCount + 1);
1848
+ for (let offset = 0; offset < nodeCount; offset++) immediateDominateeOrdinalToStartOffset[offset + 1] = immediateDominateeOrdinalToStartOffset[offset] + dominatorOrdinalToDominateeCount[offset];
1849
+ const offsetToImmediateDominateeOrdinal = new Int32Array(immediateDominateeOrdinalToStartOffset[nodeCount]);
1850
+ dominatorOrdinalToDominateeCount.fill(0);
1851
+ for (let nodeOrdinal = 1; nodeOrdinal < nodeCount; nodeOrdinal++) {
1852
+ const dominatorOrdinal = ordinalToImmediateDominatorOrdinal[nodeOrdinal];
1853
+ if (dominatorOrdinal !== -1) {
1854
+ offsetToImmediateDominateeOrdinal[immediateDominateeOrdinalToStartOffset[dominatorOrdinal] + dominatorOrdinalToDominateeCount[dominatorOrdinal]] = nodeOrdinal;
1855
+ dominatorOrdinalToDominateeCount[dominatorOrdinal]++;
1856
+ }
1857
+ }
1249
1858
  return {
1859
+ dfsIndexToOrdinal,
1250
1860
  ordinalToImmediateDominatorOrdinal,
1251
- dfsIndexToOrdinal
1861
+ immediateDominateeOrdinalToStartOffset,
1862
+ offsetToImmediateDominateeOrdinal
1252
1863
  };
1253
1864
  };
1254
- const computeNodeOrdinalToRetainedSize = ({ nodes }, { ordinalToImmediateDominatorOrdinal, dfsIndexToOrdinal }, { nodeFieldCount, nodeSelfSizeOffset }) => {
1865
+ const computeNodeOrdinalToRetainedSize = ({ nodes }, { dfsIndexToOrdinal, ordinalToImmediateDominatorOrdinal }, { nodeFieldCount, nodeSelfSizeOffset }) => {
1255
1866
  const nodeOrdinalToRetainedSize = new Float64Array(ordinalToImmediateDominatorOrdinal.length);
1256
1867
  for (let nodeOrdinal = 0; nodeOrdinal < nodeOrdinalToRetainedSize.length; nodeOrdinal++) nodeOrdinalToRetainedSize[nodeOrdinal] = nodes[nodeOrdinal * nodeFieldCount + nodeSelfSizeOffset];
1257
1868
  for (let dfsIndex = dfsIndexToOrdinal.length - 1; dfsIndex >= 1; dfsIndex--) {
1258
- const dominatedNodeOrdinal = dfsIndexToOrdinal[dfsIndex];
1259
- nodeOrdinalToRetainedSize[ordinalToImmediateDominatorOrdinal[dominatedNodeOrdinal]] += nodeOrdinalToRetainedSize[dominatedNodeOrdinal];
1869
+ const dominateeOrdinal = dfsIndexToOrdinal[dfsIndex];
1870
+ nodeOrdinalToRetainedSize[ordinalToImmediateDominatorOrdinal[dominateeOrdinal]] += nodeOrdinalToRetainedSize[dominateeOrdinal];
1260
1871
  }
1261
1872
  return nodeOrdinalToRetainedSize;
1262
1873
  };
1263
- const computeRetainerPath = (nodeOrdinal, { snapshot: { meta: { node_types: [nodeTypes] } }, nodes, edges, strings }, { ordinalToPredecessors }, nodeIndexToLocation, { ordinalToImmediateDominatorOrdinal }, fieldLayout) => {
1874
+ const computeRetainerPath = (nodeOrdinal, snapshot, { ordinalToPredecessorStartOffset, offsetToPredecessorOrdinal, offsetToPredecessorEdgeIndex }, nodeOrdinalToLocation, { ordinalToImmediateDominatorOrdinal }, fieldLayout, options) => {
1875
+ const { nodes } = snapshot;
1264
1876
  const hops = [];
1265
1877
  while (true) {
1266
- const predecessors = ordinalToPredecessors[nodeOrdinal];
1267
- if (predecessors.length === 0) break;
1878
+ const predecessorStartOffset = ordinalToPredecessorStartOffset[nodeOrdinal];
1879
+ const predecessorEndOffset = ordinalToPredecessorStartOffset[nodeOrdinal + 1];
1880
+ if (predecessorStartOffset === predecessorEndOffset) break;
1268
1881
  const dominatorOrdinal = ordinalToImmediateDominatorOrdinal[nodeOrdinal];
1269
- const predecessor = predecessors.find(({ targetNodeOrdinal }) => targetNodeOrdinal === dominatorOrdinal);
1270
- if (!predecessor) {
1882
+ let predecessorOffset = -1;
1883
+ for (let offset = predecessorStartOffset; offset < predecessorEndOffset; offset++) if (offsetToPredecessorOrdinal[offset] === dominatorOrdinal) {
1884
+ predecessorOffset = offset;
1885
+ break;
1886
+ }
1887
+ if (predecessorOffset === -1) {
1271
1888
  nodeOrdinal = dominatorOrdinal;
1272
1889
  continue;
1273
1890
  }
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;
1891
+ const edgeIndex = offsetToPredecessorEdgeIndex[predecessorOffset];
1892
+ const edgeLabel = formatEdgeLabel(edgeIndex, snapshot, fieldLayout, options);
1893
+ const predecessorOrdinal = offsetToPredecessorOrdinal[predecessorOffset];
1894
+ const retainerIndex = predecessorOrdinal * fieldLayout.nodeFieldCount;
1279
1895
  const retainerType = nodes[retainerIndex + fieldLayout.nodeTypeOffset];
1280
- const retainerName = strings[nodes[retainerIndex + fieldLayout.nodeNameOffset]] || nodeTypes[retainerType];
1281
- const retainerLocation = nodeIndexToLocation.get(retainerIndex);
1896
+ const retainerLabel = formatNodeLabel(retainerIndex, snapshot, fieldLayout, options);
1897
+ const retainerLocation = nodeOrdinalToLocation[predecessorOrdinal];
1282
1898
  hops.push({
1283
- label: `${edgeLabel} ${retainerName}${retainerLocation ? ` (${retainerLocation})` : ``}`,
1284
- internal: retainerType === fieldLayout.nodeTypeSynthetic || retainerType === fieldLayout.nodeTypeHidden
1899
+ label: `${edgeLabel} ${retainerLabel}${retainerLocation ? ` (${formatProfileLocation(retainerLocation, options)})` : ``}`,
1900
+ internal: isInternalNodeType(retainerType, fieldLayout)
1285
1901
  });
1286
- nodeOrdinal = targetNodeOrdinal;
1902
+ nodeOrdinal = predecessorOrdinal;
1287
1903
  }
1288
1904
  while (hops.at(-1)?.internal) hops.pop();
1289
1905
  if (hops.length === 0) return `(GC root)`;
1290
1906
  return hops.map((hop) => hop.label).join(` ← `);
1291
1907
  };
1908
+ const computeRetainedNodes = (nodeOrdinal, snapshot, nodeOrdinalToRetainedSize, { immediateDominateeOrdinalToStartOffset, offsetToImmediateDominateeOrdinal }, fieldLayout, options) => {
1909
+ const { nodes } = snapshot;
1910
+ const retainedNodes = [];
1911
+ const dominateeOrdinals = [];
1912
+ const childStartOffset = immediateDominateeOrdinalToStartOffset[nodeOrdinal];
1913
+ const childEndOffset = immediateDominateeOrdinalToStartOffset[nodeOrdinal + 1];
1914
+ for (let offset = childStartOffset; offset < childEndOffset; offset++) dominateeOrdinals.push(offsetToImmediateDominateeOrdinal[offset]);
1915
+ while (dominateeOrdinals.length > 0) {
1916
+ const nodeOrdinal = dominateeOrdinals.pop();
1917
+ const nodeIndex = nodeOrdinal * fieldLayout.nodeFieldCount;
1918
+ const nodeType = nodes[nodeIndex + fieldLayout.nodeTypeOffset];
1919
+ if (!isInternalNodeType(nodeType, fieldLayout)) retainedNodes.push({
1920
+ id: nodeOrdinal,
1921
+ name: formatNodeLabel(nodeIndex, snapshot, fieldLayout, options),
1922
+ selfSize: nodes[nodeIndex + fieldLayout.nodeSelfSizeOffset],
1923
+ retainedSize: nodeOrdinalToRetainedSize[nodeOrdinal]
1924
+ });
1925
+ const dominateeStartOffset = immediateDominateeOrdinalToStartOffset[nodeOrdinal];
1926
+ const dominateeEndOffset = immediateDominateeOrdinalToStartOffset[nodeOrdinal + 1];
1927
+ for (let offset = dominateeStartOffset; offset < dominateeEndOffset; offset++) dominateeOrdinals.push(offsetToImmediateDominateeOrdinal[offset]);
1928
+ }
1929
+ return retainedNodes;
1930
+ };
1931
+ const isInternalNodeType = (nodeType, fieldLayout) => nodeType === fieldLayout.nodeTypeHidden || nodeType === fieldLayout.nodeTypeSynthetic;
1932
+ const formatEdgeLabel = (edgeIndex, { edges, strings }, fieldLayout, options) => {
1933
+ const edgeType = edges[edgeIndex + fieldLayout.edgeTypeOffset];
1934
+ const edgeNameOrIndex = edges[edgeIndex + fieldLayout.edgeNameOrIndexOffset];
1935
+ if (edgeType === fieldLayout.edgeTypeElement) return `[${edgeNameOrIndex}]`;
1936
+ const rawEdgeName = strings[edgeNameOrIndex];
1937
+ const edgeLocation = makeProfileLocation({ urlOrPath: rawEdgeName });
1938
+ return `.${edgeLocation ? formatProfileLocation(edgeLocation, options) : rawEdgeName}`;
1939
+ };
1940
+ const formatNodeLabel = (nodeIndex, { snapshot: { meta: { node_types: [nodeTypes] } }, nodes, strings }, fieldLayout, options) => {
1941
+ const nodeType = nodes[nodeIndex + fieldLayout.nodeTypeOffset];
1942
+ switch (nodeType) {
1943
+ case fieldLayout.nodeTypeString:
1944
+ case fieldLayout.nodeTypeSlicedString:
1945
+ case fieldLayout.nodeTypeConcatenatedString: {
1946
+ const string = strings[nodes[nodeIndex + fieldLayout.nodeNameOffset]];
1947
+ return formatString(string);
1948
+ }
1949
+ case fieldLayout.nodeTypeClosure: return strings[nodes[nodeIndex + fieldLayout.nodeNameOffset]] || `(anonymous)`;
1950
+ default: {
1951
+ const rawNodeName = strings[nodes[nodeIndex + fieldLayout.nodeNameOffset]] || nodeTypes[nodeType];
1952
+ const nodeLocation = makeProfileLocation({ urlOrPath: rawNodeName });
1953
+ return nodeLocation ? formatProfileLocation(nodeLocation, options) : rawNodeName;
1954
+ }
1955
+ }
1956
+ };
1957
+ const formatString = (string) => {
1958
+ if (string.length > MAX_STRING_LENGTH) string = `${string.slice(0, MAX_STRING_LENGTH - 1)}…`;
1959
+ return string.replaceAll(`\n`, `\\n`);
1960
+ };
1961
+ const MAX_STRING_LENGTH = 50;
1292
1962
  /**
1293
1963
  * Attributes retained sizes to groups of nodes without double-counting.
1294
1964
  *
@@ -1301,38 +1971,31 @@ const computeRetainerPath = (nodeOrdinal, { snapshot: { meta: { node_types: [nod
1301
1971
  * Inner instances are entirely contained within the outer one's retained set,
1302
1972
  * so they add nothing.
1303
1973
  */
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
- }];
1974
+ const attributeGroupRetainedSizes = (nodeOrdinalToRetainedSize, { immediateDominateeOrdinalToStartOffset, offsetToImmediateDominateeOrdinal }, nodeOrdinalToSummarizedNodeIndex, summarizedNodes) => {
1975
+ const nodeCount = nodeOrdinalToRetainedSize.length;
1976
+ const groupPathDepth = new Int32Array(summarizedNodes.length);
1977
+ const stack = new Int32Array(nodeCount * 2 + 1);
1978
+ stack[0] = 0;
1979
+ let topOffset = 1;
1315
1980
  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);
1981
+ const encodedNodeOrdinal = stack[--topOffset];
1982
+ if (encodedNodeOrdinal < 0) {
1983
+ const constructorIndex = nodeOrdinalToSummarizedNodeIndex[~encodedNodeOrdinal];
1984
+ if (constructorIndex !== -1) groupPathDepth[constructorIndex] = groupPathDepth[constructorIndex] - 1;
1320
1985
  continue;
1321
1986
  }
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
- });
1987
+ const nodeOrdinal = encodedNodeOrdinal;
1988
+ const summarizedNodeIndex = nodeOrdinalToSummarizedNodeIndex[nodeOrdinal];
1989
+ if (summarizedNodeIndex !== -1) {
1990
+ const depth = groupPathDepth[summarizedNodeIndex];
1991
+ if (depth === 0) summarizedNodes[summarizedNodeIndex].retainedSize += nodeOrdinalToRetainedSize[nodeOrdinal];
1992
+ groupPathDepth[summarizedNodeIndex] = depth + 1;
1993
+ stack[topOffset++] = ~nodeOrdinal;
1330
1994
  }
1331
- for (const childOrdinal of dominatorOrdinalToChildOrdinals[nodeOrdinal]) stack.push({
1332
- nodeOrdinal: childOrdinal,
1333
- entering: true
1334
- });
1335
- } while (stack.length > 0);
1995
+ const dominateeStartOffset = immediateDominateeOrdinalToStartOffset[nodeOrdinal];
1996
+ const dominateeEndOffset = immediateDominateeOrdinalToStartOffset[nodeOrdinal + 1];
1997
+ for (let offset = dominateeStartOffset; offset < dominateeEndOffset; offset++) stack[topOffset++] = offsetToImmediateDominateeOrdinal[offset];
1998
+ } while (topOffset > 0);
1336
1999
  };
1337
2000
  const computeFieldLayout = (meta) => {
1338
2001
  const { node_fields: nodeFields, node_types: [nodeTypes], edge_fields: edgeFields, edge_types: [edgeTypes], location_fields: locationFields } = meta;
@@ -1380,7 +2043,16 @@ const computeFieldLayout = (meta) => {
1380
2043
  const valueToIndex = (values) => new Map(values.map((value, index) => [value, index]));
1381
2044
 
1382
2045
  //#endregion
1383
- //#region src/v8/heap-snapshot/index.ts
2046
+ //#region src/formats/v8/heap-snapshot/index.ts
2047
+ const detectV8HeapSnapshot = (json) => {
2048
+ if (typeof json !== `object` || json === null) return;
2049
+ const { snapshot, edges } = json;
2050
+ if (typeof snapshot !== `object` || snapshot === null) return;
2051
+ const { meta } = snapshot;
2052
+ if (typeof meta !== `object` || meta === null || !Array.isArray(meta.node_fields)) return;
2053
+ if (!Array.isArray(edges)) return;
2054
+ return json;
2055
+ };
1384
2056
  /**
1385
2057
  * Converts the given V8 heap snapshot to Markdown.
1386
2058
  *
@@ -1389,43 +2061,67 @@ const valueToIndex = (values) => new Map(values.map((value, index) => [value, in
1389
2061
  *
1390
2062
  * You can generate a V8 heap snapshot in several ways:
1391
2063
  * - [`node --heapsnapshot-signal`](https://nodejs.org/api/cli.html#--heapsnapshot-signalsignal)
2064
+ * - [`bun --heap-prof`](https://bun.com/docs/project/benchmarking#heap-profiling)
1392
2065
  * - [`v8.writeHeapSnapshot()`](https://nodejs.org/api/v8.html#v8writeheapsnapshotfilename)
2066
+ * - [`node --inspect`](https://nodejs.org/api/debugger.html#v8-inspector-integration-for-nodejs),
2067
+ * [`deno run --inspect`](https://docs.deno.com/runtime/fundamentals/debugging/#--inspect),
2068
+ * or [`bun --inspect`](https://bun.com/docs/runtime/debugger#inspect) with
2069
+ * [Chrome DevTools](https://developer.chrome.com/docs/devtools/memory-problems/heap-snapshots)
2070
+ * - [Chrome DevTools directly](https://developer.chrome.com/docs/devtools/memory-problems/heap-snapshots)
1393
2071
  */
1394
- const v8HeapSnapshotToMd = (data, options) => {
1395
- const normalizedOptions = normalizeV8ProfileToMdOptions(options);
1396
- return formatSummarizedSnapshot(summarizeSnapshot(parseSnapshot(data), normalizedOptions), normalizedOptions);
2072
+ const v8HeapSnapshotToMd = (data, options) => v8HeapSnapshotToMdInternal(parseV8HeapSnapshot(data), options);
2073
+ const v8HeapSnapshotToMdInternal = (snapshot, options) => {
2074
+ const normalizedOptions = normalizeProfileToMdOptions(options);
2075
+ return formatV8HeapSnapshot(summarizeV8HeapSnapshot(snapshot, normalizedOptions), normalizedOptions);
1397
2076
  };
1398
2077
 
1399
2078
  //#endregion
1400
2079
  //#region src/cli.ts
1401
- const extensionToProfileConverter = new Map([
1402
- [`.cpuprofile`, {
2080
+ const jsonProfileConverters = [
2081
+ {
2082
+ type: `speedscope`,
2083
+ detect: detectSpeedscopeProfile,
2084
+ toMdInternal: speedscopeProfileToMdInternal,
2085
+ toMd: speedscopeProfileToMd
2086
+ },
2087
+ {
1403
2088
  type: `v8-cpu-profile`,
1404
- convert: v8CpuProfileToMd
1405
- }],
1406
- [`.heapprofile`, {
2089
+ detect: detectV8CpuProfile,
2090
+ toMdInternal: v8CpuProfileToMdInternal,
2091
+ toMd: v8CpuProfileToMd
2092
+ },
2093
+ {
1407
2094
  type: `v8-heap-profile`,
1408
- convert: v8HeapProfileToMd
1409
- }],
1410
- [`.heapsnapshot`, {
2095
+ detect: detectV8HeapProfile,
2096
+ toMdInternal: v8HeapProfileToMdInternal,
2097
+ toMd: v8HeapProfileToMd
2098
+ },
2099
+ {
1411
2100
  type: `v8-heap-snapshot`,
1412
- convert: v8HeapSnapshotToMd
1413
- }]
1414
- ]);
1415
- const profileTypeToConverter = new Map(Array.from(extensionToProfileConverter.values(), (profileConverter) => [profileConverter.type, profileConverter]));
2101
+ detect: detectV8HeapSnapshot,
2102
+ toMdInternal: v8HeapSnapshotToMdInternal,
2103
+ toMd: v8HeapSnapshotToMd
2104
+ }
2105
+ ];
2106
+ const binaryProfileConverters = [{
2107
+ type: `pprof`,
2108
+ detect: detectPprof,
2109
+ toMdInternal: pprofToMdInternal,
2110
+ toMd: pprofToMd
2111
+ }];
2112
+ const profileConverters = [...jsonProfileConverters, ...binaryProfileConverters];
1416
2113
  const cli = meow(`
1417
2114
  Usage: profiler-md [options] [file]
1418
2115
 
1419
2116
  Options:
1420
- -t, --type <type> Profile type (auto-detected from file extension by default)
2117
+ -t, --type <type> Profile type, auto-detected from content if omitted
2118
+ [${profileConverters.map(({ type }) => type).join(`|`)}]
1421
2119
  -o, --output <file> Output file (default: - for stdout)
1422
2120
  --top-n <n> Number of top entries to show (default: 20)
1423
2121
  --cwd <path> Working directory for relative file paths in output
1424
- --third-party <glob> Mark URLs matching this glob as third-party (repeatable; default: node_modules)
2122
+ --third-party <glob> Mark URLs matching this glob as third-party
2123
+ (repeatable; default: node_modules)
1425
2124
  --help Show this help message
1426
-
1427
- Supported profile types:
1428
- ${Array.from(extensionToProfileConverter, ([extension, { type }]) => ` *${extension} -> ${type}`).join(`\n`)}
1429
2125
  `, {
1430
2126
  importMeta: import.meta,
1431
2127
  allowUnknownFlags: false,
@@ -1448,28 +2144,25 @@ ${Array.from(extensionToProfileConverter, ([extension, { type }]) => ` *${ext
1448
2144
  }
1449
2145
  }
1450
2146
  });
2147
+ const gunzipAsync = promisify(gunzip);
2148
+ const brotliDecompressAsync = promisify(brotliDecompress);
2149
+ const decompressData = async (data, filePath) => {
2150
+ if (filePath?.endsWith(`.br`)) return brotliDecompressAsync(data);
2151
+ if (data[0] === 31 && data[1] === 139) return gunzipAsync(data);
2152
+ return data;
2153
+ };
1451
2154
  try {
1452
2155
  const { input: [filePath], flags: { output: outputPath, type: profileType, topN, cwd, thirdParty } } = cli;
1453
- let profileConverter;
2156
+ let forcedProfileConverter;
1454
2157
  if (profileType !== void 0) {
1455
- profileConverter = profileTypeToConverter.get(profileType);
1456
- if (!profileConverter) {
2158
+ forcedProfileConverter = profileConverters.find((format) => format.type === profileType);
2159
+ if (!forcedProfileConverter) {
1457
2160
  process.stderr.write(`error: unknown profile type "${profileType}"\nRun with --help to see supported types.\n`);
1458
2161
  process.exit(2);
1459
2162
  }
1460
- } else if (filePath) {
1461
- const extension = extname(filePath);
1462
- profileConverter = extensionToProfileConverter.get(extension);
1463
- if (!profileConverter) {
1464
- process.stderr.write(`error: unrecognized file extension "${extension}"\nUse --type to specify the profile type, or run with --help to see supported types.\n`);
1465
- process.exit(2);
1466
- }
1467
- } else if (process.stdin.isTTY) {
2163
+ } else if (!filePath && process.stdin.isTTY) {
1468
2164
  cli.showHelp(0);
1469
2165
  process.exit(0);
1470
- } else {
1471
- process.stderr.write(`error: --type is required when reading from stdin\nRun with --help to see supported types.\n`);
1472
- process.exit(2);
1473
2166
  }
1474
2167
  let data;
1475
2168
  if (filePath) try {
@@ -1480,12 +2173,45 @@ try {
1480
2173
  process.exit(1);
1481
2174
  }
1482
2175
  else data = Buffer.concat(await Array.fromAsync(process.stdin));
2176
+ try {
2177
+ data = await decompressData(data, filePath);
2178
+ } catch (error) {
2179
+ const message = error instanceof Error ? error.message : String(error);
2180
+ process.stderr.write(`error: failed to decompress input: ${message}\n`);
2181
+ process.exit(1);
2182
+ }
1483
2183
  const thirdPartyMatchers = thirdParty.map((glob) => picomatch(glob, { dot: true }));
1484
- const markdown = profileConverter.convert(data, {
2184
+ const options = {
1485
2185
  topN,
1486
2186
  cwd,
1487
- isThirdPartyURL: thirdPartyMatchers.length > 0 ? (url) => defaultIsThirdPartyURL(url) || thirdPartyMatchers.some((match) => match(url.pathname)) : void 0
1488
- });
2187
+ isThirdPartyEntry: thirdPartyMatchers.length > 0 ? (entry) => defaultIsThirdPartyEntry(entry) || !!entry.location && thirdPartyMatchers.some((match) => match(entry.location.url.pathname)) : void 0
2188
+ };
2189
+ let markdown;
2190
+ if (forcedProfileConverter) markdown = forcedProfileConverter.toMd(data, options);
2191
+ else {
2192
+ let json;
2193
+ try {
2194
+ json = parseJson(data);
2195
+ } catch {}
2196
+ if (json === void 0) for (const converter of binaryProfileConverters) {
2197
+ const parsed = converter.detect(data);
2198
+ if (parsed !== void 0) {
2199
+ markdown = converter.toMdInternal(parsed, options);
2200
+ break;
2201
+ }
2202
+ }
2203
+ else for (const converter of jsonProfileConverters) {
2204
+ const parsed = converter.detect(json);
2205
+ if (parsed !== void 0) {
2206
+ markdown = converter.toMdInternal(parsed, options);
2207
+ break;
2208
+ }
2209
+ }
2210
+ if (markdown === void 0) {
2211
+ process.stderr.write(`error: could not detect profile format from content\nUse --type to specify the format, or run with --help to see supported types.\n`);
2212
+ process.exit(2);
2213
+ }
2214
+ }
1489
2215
  let output;
1490
2216
  if (outputPath === `-`) output = process.stdout;
1491
2217
  else {