profiler-md 0.0.1

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 ADDED
@@ -0,0 +1,1513 @@
1
+ #!/usr/bin/env node
2
+ import { createWriteStream } from "node:fs";
3
+ import { readFile } from "node:fs/promises";
4
+ import { extname } from "node:path";
5
+ import meow from "meow";
6
+ import picomatch from "picomatch";
7
+ import prettyBytes from "pretty-bytes";
8
+ import prettyMilliseconds from "pretty-ms";
9
+
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}`;
15
+ };
16
+ const formatTable = (headers, rows) => {
17
+ const headerContents = headers.map((header) => typeof header === `string` ? header : header.content);
18
+ const allRows = [headerContents, ...rows];
19
+ const widths = headerContents.map((_, columnIndex) => Math.max(...allRows.map((row) => row[columnIndex]?.length ?? 0)));
20
+ const isRight = (index) => typeof headers[index] !== `string` && headers[index]?.align === `right`;
21
+ const alignCell = (cell, index) => isRight(index) ? cell.padStart(widths[index]) : cell.padEnd(widths[index]);
22
+ const formatRow = (row) => `| ${row.map((cell, index) => alignCell(cell, index)).join(` | `)} |`;
23
+ const separator = `| ${widths.map((width, index) => isRight(index) ? `${`-`.repeat(width - 1)}:` : `-`.repeat(width)).join(` | `)} |`;
24
+ return [
25
+ formatRow(headerContents),
26
+ separator,
27
+ ...rows.map(formatRow)
28
+ ].join(`\n`);
29
+ };
30
+
31
+ //#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
+ };
47
+ /**
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.
53
+ */
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);
94
+ } catch {
95
+ return url || void 0;
96
+ }
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;
110
+ try {
111
+ urlObject = new URL(callFrame.url);
112
+ } catch {
113
+ return `native`;
114
+ }
115
+ if (urlObject.protocol !== `file:`) return `native`;
116
+ return isThirdPartyURL(urlObject) ? `third-party` : `ours`;
117
+ };
118
+ const findCommonCallStack = (callStacks) => {
119
+ if (callStacks.length <= 1) return [];
120
+ const minLength = Math.min(...callStacks.map((callStack) => callStack.nodes.length));
121
+ const firstNodes = callStacks[0].nodes;
122
+ let suffixLength = 0;
123
+ 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;
126
+ else break;
127
+ }
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;
147
+ };
148
+
149
+ //#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([
172
+ `Category`,
173
+ `%`,
174
+ `Time`,
175
+ `Samples`
176
+ ], hottestCallFrameCategories.map(([category, { time, sampleCount }]) => [
177
+ category,
178
+ formatPercent(time / totalTime),
179
+ formatMicroseconds(time),
180
+ formatCount(sampleCount)
181
+ ]))].join(`\n\n`);
182
+ };
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);
192
+ return [
193
+ `### Self time`,
194
+ `Functions ranked by time in the function body, excluding callees.`,
195
+ formatTable([
196
+ {
197
+ content: `%`,
198
+ align: `right`
199
+ },
200
+ {
201
+ content: `Time`,
202
+ align: `right`
203
+ },
204
+ {
205
+ content: `Samples`,
206
+ align: `right`
207
+ },
208
+ `Function`,
209
+ `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>`)
216
+ ])),
217
+ ...hottestLinesSections.length > 0 ? [`#### Lines`, `Lines ranked by contribution to each function's self time.`] : [],
218
+ ...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
221
+ ].join(`\n\n`);
222
+ };
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([
226
+ {
227
+ content: `%`,
228
+ align: `right`
229
+ },
230
+ {
231
+ content: `Time`,
232
+ align: `right`
233
+ },
234
+ {
235
+ content: `Samples`,
236
+ align: `right`
237
+ },
238
+ `Location`
239
+ ], hottestLines.map(([line, { time, sampleCount }]) => [
240
+ formatPercent(time / node.selfTime),
241
+ formatMicroseconds(time),
242
+ formatCount(sampleCount),
243
+ `${node.fileLocation}:${line + 1}`
244
+ ]))].join(`\n\n`);
245
+ };
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([
250
+ {
251
+ content: `%`,
252
+ align: `right`
253
+ },
254
+ {
255
+ content: `Time`,
256
+ align: `right`
257
+ },
258
+ {
259
+ content: `Samples`,
260
+ align: `right`
261
+ },
262
+ `Caller`,
263
+ `Location`
264
+ ], hottestCallerSelfTimes.map(({ caller, selfTime, selfSampleCount }) => [
265
+ formatPercent(selfTime / node.selfTime),
266
+ formatMicroseconds(selfTime),
267
+ formatCount(selfSampleCount),
268
+ inlineCode(caller.functionName),
269
+ caller.location ?? inlineCode(`<native>`)
270
+ ]))].join(`\n\n`);
271
+ };
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);
275
+ return [
276
+ `### Total time`,
277
+ `Functions ranked by total time in the function and all its callees.`,
278
+ formatTable([
279
+ {
280
+ content: `%`,
281
+ align: `right`
282
+ },
283
+ {
284
+ content: `Time`,
285
+ align: `right`
286
+ },
287
+ {
288
+ content: `Samples`,
289
+ align: `right`
290
+ },
291
+ `Function`,
292
+ `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>`)
299
+ ])),
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
302
+ ].join(`\n\n`);
303
+ };
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([
308
+ {
309
+ content: `%`,
310
+ align: `right`
311
+ },
312
+ {
313
+ content: `Time`,
314
+ align: `right`
315
+ },
316
+ {
317
+ content: `Samples`,
318
+ align: `right`
319
+ },
320
+ `Callee`,
321
+ `Location`
322
+ ], hottestCalleeTotalTimes.map(({ callee, totalTime, totalSampleCount }) => [
323
+ formatPercent(totalTime / node.totalTime),
324
+ formatMicroseconds(totalTime),
325
+ formatCount(totalSampleCount),
326
+ inlineCode(callee.functionName),
327
+ callee.location ?? inlineCode(`<native>`)
328
+ ]))].join(`\n\n`);
329
+ };
330
+ const formatHottestCallStacks$1 = ({ totalTime, callStacks }, options) => {
331
+ const hottestCallStacks = callStacks.map((callStack) => ({
332
+ ...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);
335
+ if (hottestCallStacks.length === 0) return;
336
+ const commonCallStack = findCommonCallStack(hottestCallStacks);
337
+ 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)}`] : [],
341
+ formatTable([
342
+ {
343
+ content: `%`,
344
+ align: `right`
345
+ },
346
+ {
347
+ content: `Time`,
348
+ align: `right`
349
+ },
350
+ {
351
+ content: `Samples`,
352
+ align: `right`
353
+ },
354
+ `Call stack`
355
+ ], hottestCallStacks.map(({ nodes, selfTime, selfSampleCount }) => [
356
+ formatPercent(selfTime / totalTime),
357
+ formatMicroseconds(selfTime),
358
+ formatCount(selfSampleCount),
359
+ formatCallStack(commonCallStack.length > 0 ? nodes.slice(0, -commonCallStack.length) : nodes)
360
+ ]))
361
+ ].join(`\n\n`);
362
+ };
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++;
460
+ }
461
+ return {
462
+ totalTime,
463
+ totalSampleCount,
464
+ samplingInterval,
465
+ callFrameCategoryToStats,
466
+ nodes,
467
+ callStacks: [...keyToSummarizedCallStack.values()]
468
+ };
469
+ };
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
+ }
518
+ }
519
+ return {
520
+ rawIdToRawNode,
521
+ rawIdToSummarizedNode,
522
+ keyToSummarizedNode,
523
+ rawIdToParentRawId
524
+ };
525
+ };
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);
545
+ };
546
+
547
+ //#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`);
568
+ };
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`);
605
+ };
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`);
631
+ };
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`);
663
+ };
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`);
689
+ };
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`);
722
+ };
723
+
724
+ //#endregion
725
+ //#region src/v8/heap-profile/parse.ts
726
+ const parseProfile = (data) => JSON.parse(data);
727
+
728
+ //#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);
777
+ }
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);
796
+ }
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
+ }
808
+ categoryStats.size += size;
809
+ categoryStats.sampleCount++;
810
+ }
811
+ return {
812
+ totalSize,
813
+ sampleCount,
814
+ samplingInterval,
815
+ callFrameCategoryToStats,
816
+ nodes: [...graph.keyToSummarizedNode.values()],
817
+ callStacks: [...keyToSummarizedCallStack.values()]
818
+ };
819
+ };
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);
846
+ }
847
+ rawIdToSummarizedNode.set(node.id, summarizedNode);
848
+ if (parentId !== void 0) rawIdToParentRawId.set(node.id, parentId);
849
+ for (const child of node.children) stack.push({
850
+ node: child,
851
+ parentId: node.id
852
+ });
853
+ } while (stack.length > 0);
854
+ return {
855
+ rawIdToSummarizedNode,
856
+ keyToSummarizedNode,
857
+ rawIdToParentRawId
858
+ };
859
+ };
860
+
861
+ //#endregion
862
+ //#region src/v8/heap-profile/index.ts
863
+ /**
864
+ * Converts the given V8 sampling heap profile to Markdown.
865
+ *
866
+ * It is assumed that {@link data} is a valid profile. The behavior of this
867
+ * function is undefined for invalid profiles.
868
+ *
869
+ * You can generate a V8 heap profile in several ways:
870
+ * - [`node --heap-prof`](https://nodejs.org/api/cli.html#--heap-prof)
871
+ * - [`v8.writeHeapProfileSync()`](https://nodejs.org/api/v8.html#v8writeheapprofilesyncfilename)
872
+ *
873
+ * Note that [`bun --heap-prof`](https://bun.com/docs/project/benchmarking#heap-profiling)
874
+ * generates a heap _snapshot_ on exit, not a heap _profile_.
875
+ */
876
+ const v8HeapProfileToMd = (data, options) => {
877
+ const normalizedOptions = normalizeV8ProfileToMdOptions(options);
878
+ return formatSummarizedProfile(summarizeProfile(parseProfile(data), normalizedOptions), normalizedOptions);
879
+ };
880
+
881
+ //#endregion
882
+ //#region src/v8/heap-snapshot/format.ts
883
+ const formatSummarizedSnapshot = (snapshot, options) => `${[
884
+ `# Heap snapshot`,
885
+ formatOverallSummary(snapshot),
886
+ formatLargestConstructors(snapshot, options)
887
+ ].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([
891
+ `Category`,
892
+ {
893
+ content: `%`,
894
+ align: `right`
895
+ },
896
+ {
897
+ content: `Size`,
898
+ align: `right`
899
+ },
900
+ {
901
+ content: `Objects`,
902
+ align: `right`
903
+ }
904
+ ], hottestObjectCategories.map(([type, { size, count }]) => [
905
+ type,
906
+ formatPercent(size / totalSize),
907
+ formatBytes(size),
908
+ formatCount(count)
909
+ ]))].join(`\n\n`);
910
+ };
911
+ const formatLargestConstructors = (snapshot, options) => [
912
+ `## Largest constructors`,
913
+ formatLargestSelfSizeConstructors(snapshot, options),
914
+ formatLargestRetainedSizeConstructors(snapshot, options)
915
+ ].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);
919
+ return [
920
+ `### Self size`,
921
+ `Constructors ranked by bytes allocated for their instances, excluding objects kept reachable by them.`,
922
+ formatTable([
923
+ {
924
+ content: `%`,
925
+ align: `right`
926
+ },
927
+ {
928
+ content: `Size`,
929
+ align: `right`
930
+ },
931
+ {
932
+ content: `Instances`,
933
+ align: `right`
934
+ },
935
+ `Constructor`,
936
+ `Location`
937
+ ], largestConstructors.map((constructor) => [
938
+ formatPercent(constructor.selfSize / totalSize),
939
+ formatBytes(constructor.selfSize),
940
+ formatCount(constructor.instances.length),
941
+ inlineCode(constructor.name),
942
+ constructor.location ?? inlineCode(`<native>`)
943
+ ])),
944
+ ...largestInstanceSections.length > 0 ? [`#### Instances`, `Instances ranked by contribution to each constructor's self size.`] : [],
945
+ ...largestInstanceSections
946
+ ].join(`\n\n`);
947
+ };
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([
952
+ {
953
+ content: `%`,
954
+ align: `right`
955
+ },
956
+ {
957
+ content: `Size`,
958
+ align: `right`
959
+ },
960
+ `Path`
961
+ ], largestInstances.map((instance) => [
962
+ formatPercent(instance.selfSize / constructor.selfSize),
963
+ formatBytes(instance.selfSize),
964
+ inlineCode(instance.retainerPath)
965
+ ]))].join(`\n\n`);
966
+ };
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);
970
+ return [
971
+ `### Retained size`,
972
+ `Constructors ranked by bytes allocated for their instances and all objects that would be freed if their instances were garbage collected.`,
973
+ formatTable([
974
+ {
975
+ content: `%`,
976
+ align: `right`
977
+ },
978
+ {
979
+ content: `Size`,
980
+ align: `right`
981
+ },
982
+ `Constructor`,
983
+ `Location`
984
+ ], largestConstructors.map((constructor) => [
985
+ formatPercent(constructor.retainedSize / totalSize),
986
+ formatBytes(constructor.retainedSize),
987
+ inlineCode(constructor.name),
988
+ constructor.location ?? inlineCode(`<native>`)
989
+ ])),
990
+ ...largestInstanceSections.length > 0 ? [`#### Instances`, `Instances ranked by contribution to each constructor's retained size.`] : [],
991
+ ...largestInstanceSections
992
+ ].join(`\n\n`);
993
+ };
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([
998
+ {
999
+ content: `%`,
1000
+ align: `right`
1001
+ },
1002
+ {
1003
+ content: `Size`,
1004
+ align: `right`
1005
+ },
1006
+ `Path`
1007
+ ], largestInstances.map((instance) => [
1008
+ formatPercent(instance.retainedSize / constructor.retainedSize),
1009
+ formatBytes(instance.retainedSize),
1010
+ inlineCode(instance.retainerPath)
1011
+ ]))].join(`\n\n`);
1012
+ };
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;
1021
+ };
1022
+
1023
+ //#endregion
1024
+ //#region src/v8/heap-snapshot/parse.ts
1025
+ const parseSnapshot = (data) => JSON.parse(data);
1026
+
1027
+ //#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;
1031
+ const [nodeTypes] = meta.node_types;
1032
+ const fieldLayout = computeFieldLayout(meta);
1033
+ const nodeAdjacencyGraph = computeNodeAdjacencyGraph(snapshot, fieldLayout);
1034
+ const nodeIndexToLocation = computeNodeIndexToLocation(snapshot, nodeAdjacencyGraph, fieldLayout, options);
1035
+ const immediateDominatorGraph = computeImmediateDominatorGraph(snapshot, nodeAdjacencyGraph);
1036
+ const nodeOrdinalToRetainedSize = computeNodeOrdinalToRetainedSize(snapshot, immediateDominatorGraph, fieldLayout);
1037
+ 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++) {
1042
+ const nodeIndex = nodeOrdinal * fieldLayout.nodeFieldCount;
1043
+ const selfSize = nodes[nodeIndex + fieldLayout.nodeSelfSizeOffset];
1044
+ totalSize += selfSize;
1045
+ const nodeType = nodes[nodeIndex + fieldLayout.nodeTypeOffset];
1046
+ const category = nodeTypes[nodeType];
1047
+ let categoryStats = objectCategoryToSizeStats.get(category);
1048
+ if (!categoryStats) {
1049
+ categoryStats = {
1050
+ size: 0,
1051
+ count: 0
1052
+ };
1053
+ objectCategoryToSizeStats.set(category, categoryStats);
1054
+ }
1055
+ categoryStats.size += selfSize;
1056
+ categoryStats.count++;
1057
+ switch (nodeType) {
1058
+ case fieldLayout.nodeTypeObject:
1059
+ case fieldLayout.nodeTypeNative: {
1060
+ const name = strings[nodes[nodeIndex + fieldLayout.nodeNameOffset]];
1061
+ let constructor = nameToConstructor.get(name);
1062
+ if (!constructor) {
1063
+ constructor = {
1064
+ name,
1065
+ location: void 0,
1066
+ selfSize: 0,
1067
+ retainedSize: 0,
1068
+ instances: []
1069
+ };
1070
+ nameToConstructor.set(name, constructor);
1071
+ }
1072
+ constructor.selfSize += selfSize;
1073
+ constructor.location ??= nodeIndexToLocation.get(nodeIndex);
1074
+ let retainerPath;
1075
+ constructor.instances.push({
1076
+ selfSize,
1077
+ retainedSize: nodeOrdinalToRetainedSize[nodeOrdinal],
1078
+ get retainerPath() {
1079
+ return retainerPath ??= computeRetainerPath(nodeOrdinal, snapshot, nodeAdjacencyGraph, nodeIndexToLocation, immediateDominatorGraph, fieldLayout);
1080
+ }
1081
+ });
1082
+ nodeOrdinalToConstructor.set(nodeOrdinal, constructor);
1083
+ break;
1084
+ }
1085
+ }
1086
+ }
1087
+ attributeGroupRetainedSizes({
1088
+ nodeOrdinalToRetainedSize,
1089
+ ordinalToImmediateDominatorOrdinal: immediateDominatorGraph.ordinalToImmediateDominatorOrdinal,
1090
+ nodeOrdinalToGroup: nodeOrdinalToConstructor
1091
+ });
1092
+ const constructors = [...nameToConstructor.values()];
1093
+ return {
1094
+ totalSize,
1095
+ objectCount,
1096
+ referenceCount,
1097
+ objectCategoryToSizeStats,
1098
+ constructors
1099
+ };
1100
+ };
1101
+ const computeNodeAdjacencyGraph = ({ snapshot: { node_count: nodeCount }, nodes, edges }, fieldLayout) => {
1102
+ const ordinalToSuccessors = Array.from({ length: nodeCount }, () => []);
1103
+ const ordinalToPredecessors = Array.from({ length: nodeCount }, () => []);
1104
+ let nodeEdgesStartIndex = 0;
1105
+ 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
+ });
1119
+ }
1120
+ nodeEdgesStartIndex += edgeCount * fieldLayout.edgeFieldCount;
1121
+ }
1122
+ return {
1123
+ ordinalToSuccessors,
1124
+ ordinalToPredecessors
1125
+ };
1126
+ };
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];
1132
+ };
1133
+ const scriptIdToFileLocation = /* @__PURE__ */ new Map();
1134
+ for (let locationIndex = 0; locationIndex < locations.length; locationIndex += fieldLayout.locationFieldCount) {
1135
+ const scriptId = locations[locationIndex + fieldLayout.locationScriptIdOffset];
1136
+ 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`);
1140
+ if (sharedNodeIndex === void 0) continue;
1141
+ const scriptNodeIndex = followNamedEdge(sharedNodeIndex, `script`);
1142
+ 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);
1149
+ }
1150
+ const nodeIndexToLocation = /* @__PURE__ */ new Map();
1151
+ for (let locationIndex = 0; locationIndex < locations.length; locationIndex += fieldLayout.locationFieldCount) {
1152
+ const scriptId = locations[locationIndex + fieldLayout.locationScriptIdOffset];
1153
+ const fileLocation = scriptIdToFileLocation.get(scriptId);
1154
+ 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}`);
1159
+ }
1160
+ return nodeIndexToLocation;
1161
+ };
1162
+ /**
1163
+ * Computes the immediate dominators of every object.
1164
+ *
1165
+ * Weak edges are excluded because they don't keep objects alive.
1166
+ *
1167
+ * Uses the Lengauer-Tarjan dominator tree algorithm.
1168
+ *
1169
+ * @see https://en.wikipedia.org/wiki/Dominator_(graph_theory)
1170
+ * @see https://www.cs.princeton.edu/courses/archive/fall03/cs528/handouts/a%20fast%20algorithm%20for%20finding.pdf
1171
+ */
1172
+ const computeImmediateDominatorGraph = (snapshot, { ordinalToSuccessors, ordinalToPredecessors }) => {
1173
+ const { snapshot: { node_count: nodeCount } } = snapshot;
1174
+ const ordinalToDfsIndex = new Int32Array(nodeCount).fill(-1);
1175
+ const dfsIndexToOrdinal = new Int32Array(nodeCount);
1176
+ const ordinalToParentOrdinal = new Int32Array(nodeCount).fill(-1);
1177
+ 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
+ ordinalToDfsIndex[0] = 0;
1183
+ ordinalToSemidominatorDfsIndex[0] = 0;
1184
+ dfsIndexToOrdinal[0] = 0;
1185
+ let dfsIndex = 1;
1186
+ const dfsStack = [{
1187
+ nodeOrdinal: 0,
1188
+ nextChildIndex: 0
1189
+ }];
1190
+ do {
1191
+ const frame = dfsStack.at(-1);
1192
+ if (frame.nextChildIndex === ordinalToSuccessors[frame.nodeOrdinal].length) {
1193
+ dfsStack.pop();
1194
+ continue;
1195
+ }
1196
+ const childOrdinal = ordinalToSuccessors[frame.nodeOrdinal][frame.nextChildIndex].targetNodeOrdinal;
1197
+ frame.nextChildIndex++;
1198
+ if (ordinalToDfsIndex[childOrdinal] !== -1) continue;
1199
+ ordinalToParentOrdinal[childOrdinal] = frame.nodeOrdinal;
1200
+ ordinalToDfsIndex[childOrdinal] = dfsIndex;
1201
+ ordinalToSemidominatorDfsIndex[childOrdinal] = dfsIndex;
1202
+ dfsIndexToOrdinal[dfsIndex] = childOrdinal;
1203
+ dfsIndex++;
1204
+ dfsStack.push({
1205
+ nodeOrdinal: childOrdinal,
1206
+ nextChildIndex: 0
1207
+ });
1208
+ } while (dfsStack.length > 0);
1209
+ const reachableCount = dfsIndex;
1210
+ const compressAncestorPath = (startNodeOrdinal) => {
1211
+ const nodeOrdinalPath = [];
1212
+ let nodeOrdinal = startNodeOrdinal;
1213
+ while (ordinalToForestAncestorOrdinal[nodeOrdinal] !== -1 && ordinalToForestAncestorOrdinal[ordinalToForestAncestorOrdinal[nodeOrdinal]] !== -1) {
1214
+ nodeOrdinalPath.push(nodeOrdinal);
1215
+ nodeOrdinal = ordinalToForestAncestorOrdinal[nodeOrdinal];
1216
+ }
1217
+ for (let pathIndex = nodeOrdinalPath.length - 1; pathIndex >= 0; pathIndex--) {
1218
+ const pathNodeOrdinal = nodeOrdinalPath[pathIndex];
1219
+ const ancestorOrdinal = ordinalToForestAncestorOrdinal[pathNodeOrdinal];
1220
+ if (ordinalToSemidominatorDfsIndex[ordinalToMinSemiAncestorOrdinal[ancestorOrdinal]] < ordinalToSemidominatorDfsIndex[ordinalToMinSemiAncestorOrdinal[pathNodeOrdinal]]) ordinalToMinSemiAncestorOrdinal[pathNodeOrdinal] = ordinalToMinSemiAncestorOrdinal[ancestorOrdinal];
1221
+ ordinalToForestAncestorOrdinal[pathNodeOrdinal] = ordinalToForestAncestorOrdinal[ancestorOrdinal];
1222
+ }
1223
+ };
1224
+ const minSemiAncestorOrdinal = (nodeOrdinal) => {
1225
+ if (ordinalToForestAncestorOrdinal[nodeOrdinal] === -1) return nodeOrdinal;
1226
+ compressAncestorPath(nodeOrdinal);
1227
+ return ordinalToMinSemiAncestorOrdinal[nodeOrdinal];
1228
+ };
1229
+ for (let dfsIndex = reachableCount - 1; dfsIndex >= 1; dfsIndex--) {
1230
+ const nodeOrdinal = dfsIndexToOrdinal[dfsIndex];
1231
+ for (const { targetNodeOrdinal: predecessorOrdinal } of ordinalToPredecessors[nodeOrdinal]) {
1232
+ if (ordinalToDfsIndex[predecessorOrdinal] === -1) continue;
1233
+ const minAncestorOrdinal = minSemiAncestorOrdinal(predecessorOrdinal);
1234
+ if (ordinalToSemidominatorDfsIndex[minAncestorOrdinal] < ordinalToSemidominatorDfsIndex[nodeOrdinal]) ordinalToSemidominatorDfsIndex[nodeOrdinal] = ordinalToSemidominatorDfsIndex[minAncestorOrdinal];
1235
+ }
1236
+ ordinalToPendingOrdinals[dfsIndexToOrdinal[ordinalToSemidominatorDfsIndex[nodeOrdinal]]].push(nodeOrdinal);
1237
+ ordinalToForestAncestorOrdinal[nodeOrdinal] = ordinalToParentOrdinal[nodeOrdinal];
1238
+ for (const pendingOrdinal of ordinalToPendingOrdinals[ordinalToParentOrdinal[nodeOrdinal]]) {
1239
+ const ancestorOrdinal = minSemiAncestorOrdinal(pendingOrdinal);
1240
+ ordinalToImmediateDominatorOrdinal[pendingOrdinal] = ordinalToSemidominatorDfsIndex[ancestorOrdinal] < ordinalToSemidominatorDfsIndex[pendingOrdinal] ? ancestorOrdinal : ordinalToParentOrdinal[nodeOrdinal];
1241
+ }
1242
+ ordinalToPendingOrdinals[ordinalToParentOrdinal[nodeOrdinal]].length = 0;
1243
+ }
1244
+ for (let dfsIndex = 1; dfsIndex < reachableCount; dfsIndex++) {
1245
+ const nodeOrdinal = dfsIndexToOrdinal[dfsIndex];
1246
+ if (ordinalToImmediateDominatorOrdinal[nodeOrdinal] !== dfsIndexToOrdinal[ordinalToSemidominatorDfsIndex[nodeOrdinal]]) ordinalToImmediateDominatorOrdinal[nodeOrdinal] = ordinalToImmediateDominatorOrdinal[ordinalToImmediateDominatorOrdinal[nodeOrdinal]];
1247
+ }
1248
+ ordinalToImmediateDominatorOrdinal[0] = 0;
1249
+ return {
1250
+ ordinalToImmediateDominatorOrdinal,
1251
+ dfsIndexToOrdinal
1252
+ };
1253
+ };
1254
+ const computeNodeOrdinalToRetainedSize = ({ nodes }, { ordinalToImmediateDominatorOrdinal, dfsIndexToOrdinal }, { nodeFieldCount, nodeSelfSizeOffset }) => {
1255
+ const nodeOrdinalToRetainedSize = new Float64Array(ordinalToImmediateDominatorOrdinal.length);
1256
+ for (let nodeOrdinal = 0; nodeOrdinal < nodeOrdinalToRetainedSize.length; nodeOrdinal++) nodeOrdinalToRetainedSize[nodeOrdinal] = nodes[nodeOrdinal * nodeFieldCount + nodeSelfSizeOffset];
1257
+ for (let dfsIndex = dfsIndexToOrdinal.length - 1; dfsIndex >= 1; dfsIndex--) {
1258
+ const dominatedNodeOrdinal = dfsIndexToOrdinal[dfsIndex];
1259
+ nodeOrdinalToRetainedSize[ordinalToImmediateDominatorOrdinal[dominatedNodeOrdinal]] += nodeOrdinalToRetainedSize[dominatedNodeOrdinal];
1260
+ }
1261
+ return nodeOrdinalToRetainedSize;
1262
+ };
1263
+ const computeRetainerPath = (nodeOrdinal, { snapshot: { meta: { node_types: [nodeTypes] } }, nodes, edges, strings }, { ordinalToPredecessors }, nodeIndexToLocation, { ordinalToImmediateDominatorOrdinal }, fieldLayout) => {
1264
+ const hops = [];
1265
+ while (true) {
1266
+ const predecessors = ordinalToPredecessors[nodeOrdinal];
1267
+ if (predecessors.length === 0) break;
1268
+ const dominatorOrdinal = ordinalToImmediateDominatorOrdinal[nodeOrdinal];
1269
+ const predecessor = predecessors.find(({ targetNodeOrdinal }) => targetNodeOrdinal === dominatorOrdinal);
1270
+ if (!predecessor) {
1271
+ nodeOrdinal = dominatorOrdinal;
1272
+ continue;
1273
+ }
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;
1279
+ const retainerType = nodes[retainerIndex + fieldLayout.nodeTypeOffset];
1280
+ const retainerName = strings[nodes[retainerIndex + fieldLayout.nodeNameOffset]] || nodeTypes[retainerType];
1281
+ const retainerLocation = nodeIndexToLocation.get(retainerIndex);
1282
+ hops.push({
1283
+ label: `${edgeLabel} ${retainerName}${retainerLocation ? ` (${retainerLocation})` : ``}`,
1284
+ internal: retainerType === fieldLayout.nodeTypeSynthetic || retainerType === fieldLayout.nodeTypeHidden
1285
+ });
1286
+ nodeOrdinal = targetNodeOrdinal;
1287
+ }
1288
+ while (hops.at(-1)?.internal) hops.pop();
1289
+ if (hops.length === 0) return `(GC root)`;
1290
+ return hops.map((hop) => hop.label).join(` ← `);
1291
+ };
1292
+ /**
1293
+ * Attributes retained sizes to groups of nodes without double-counting.
1294
+ *
1295
+ * Summing per-node retained sizes across all instances of a group over-counts
1296
+ * when one instance dominates another from the same group (the dominated node's
1297
+ * memory is already included in the dominator's retained size).
1298
+ *
1299
+ * This function correctly attributes by doing a DFS of the dominator tree and
1300
+ * only crediting the outermost instance of each group on any root-to-leaf path.
1301
+ * Inner instances are entirely contained within the outer one's retained set,
1302
+ * so they add nothing.
1303
+ */
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
+ }];
1315
+ 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);
1320
+ continue;
1321
+ }
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
+ });
1330
+ }
1331
+ for (const childOrdinal of dominatorOrdinalToChildOrdinals[nodeOrdinal]) stack.push({
1332
+ nodeOrdinal: childOrdinal,
1333
+ entering: true
1334
+ });
1335
+ } while (stack.length > 0);
1336
+ };
1337
+ const computeFieldLayout = (meta) => {
1338
+ const { node_fields: nodeFields, node_types: [nodeTypes], edge_fields: edgeFields, edge_types: [edgeTypes], location_fields: locationFields } = meta;
1339
+ const nodeFieldToIndex = valueToIndex(nodeFields);
1340
+ const nodeTypeToIndex = valueToIndex(nodeTypes);
1341
+ const edgeFieldToIndex = valueToIndex(edgeFields);
1342
+ const locationFieldToIndex = valueToIndex(locationFields);
1343
+ const edgeTypeToIndex = valueToIndex(edgeTypes);
1344
+ return {
1345
+ nodeTypeOffset: nodeFieldToIndex.get(`type`),
1346
+ nodeNameOffset: nodeFieldToIndex.get(`name`),
1347
+ nodeSelfSizeOffset: nodeFieldToIndex.get(`self_size`),
1348
+ nodeEdgeCountOffset: nodeFieldToIndex.get(`edge_count`),
1349
+ nodeDetachednessOffset: nodeFieldToIndex.get(`detachedness`),
1350
+ nodeFieldCount: nodeFields.length,
1351
+ edgeTypeOffset: edgeFieldToIndex.get(`type`),
1352
+ edgeNameOrIndexOffset: edgeFieldToIndex.get(`name_or_index`),
1353
+ edgeToNodeOffset: edgeFieldToIndex.get(`to_node`),
1354
+ edgeFieldCount: edgeFields.length,
1355
+ locationObjectIndexOffset: locationFieldToIndex.get(`object_index`),
1356
+ locationScriptIdOffset: locationFieldToIndex.get(`script_id`),
1357
+ locationLineOffset: locationFieldToIndex.get(`line`),
1358
+ locationColumnOffset: locationFieldToIndex.get(`column`),
1359
+ locationFieldCount: locationFields.length,
1360
+ nodeTypeHidden: nodeTypeToIndex.get(`hidden`),
1361
+ nodeTypeArray: nodeTypeToIndex.get(`array`),
1362
+ nodeTypeString: nodeTypeToIndex.get(`string`),
1363
+ nodeTypeObject: nodeTypeToIndex.get(`object`),
1364
+ nodeTypeCode: nodeTypeToIndex.get(`code`),
1365
+ nodeTypeClosure: nodeTypeToIndex.get(`closure`),
1366
+ nodeTypeRegexp: nodeTypeToIndex.get(`regexp`),
1367
+ nodeTypeNumber: nodeTypeToIndex.get(`number`),
1368
+ nodeTypeNative: nodeTypeToIndex.get(`native`),
1369
+ nodeTypeSynthetic: nodeTypeToIndex.get(`synthetic`),
1370
+ nodeTypeConcatenatedString: nodeTypeToIndex.get(`concatenated string`),
1371
+ nodeTypeSlicedString: nodeTypeToIndex.get(`sliced string`),
1372
+ nodeTypeSymbol: nodeTypeToIndex.get(`symbol`),
1373
+ nodeTypeBigint: nodeTypeToIndex.get(`bigint`),
1374
+ nodeTypeObjectShape: nodeTypeToIndex.get(`object shape`),
1375
+ edgeTypeElement: edgeTypeToIndex.get(`element`),
1376
+ edgeTypeInternal: edgeTypeToIndex.get(`internal`),
1377
+ edgeTypeWeak: edgeTypeToIndex.get(`weak`)
1378
+ };
1379
+ };
1380
+ const valueToIndex = (values) => new Map(values.map((value, index) => [value, index]));
1381
+
1382
+ //#endregion
1383
+ //#region src/v8/heap-snapshot/index.ts
1384
+ /**
1385
+ * Converts the given V8 heap snapshot to Markdown.
1386
+ *
1387
+ * It is assumed that {@link data} is a valid snapshot. The behavior of this
1388
+ * function is undefined for invalid snapshots.
1389
+ *
1390
+ * You can generate a V8 heap snapshot in several ways:
1391
+ * - [`node --heapsnapshot-signal`](https://nodejs.org/api/cli.html#--heapsnapshot-signalsignal)
1392
+ * - [`v8.writeHeapSnapshot()`](https://nodejs.org/api/v8.html#v8writeheapsnapshotfilename)
1393
+ */
1394
+ const v8HeapSnapshotToMd = (data, options) => {
1395
+ const normalizedOptions = normalizeV8ProfileToMdOptions(options);
1396
+ return formatSummarizedSnapshot(summarizeSnapshot(parseSnapshot(data), normalizedOptions), normalizedOptions);
1397
+ };
1398
+
1399
+ //#endregion
1400
+ //#region src/cli.ts
1401
+ const extensionToProfileConverter = new Map([
1402
+ [`.cpuprofile`, {
1403
+ type: `v8-cpu-profile`,
1404
+ convert: v8CpuProfileToMd
1405
+ }],
1406
+ [`.heapprofile`, {
1407
+ type: `v8-heap-profile`,
1408
+ convert: v8HeapProfileToMd
1409
+ }],
1410
+ [`.heapsnapshot`, {
1411
+ type: `v8-heap-snapshot`,
1412
+ convert: v8HeapSnapshotToMd
1413
+ }]
1414
+ ]);
1415
+ const profileTypeToConverter = new Map(Array.from(extensionToProfileConverter.values(), (profileConverter) => [profileConverter.type, profileConverter]));
1416
+ const cli = meow(`
1417
+ Usage: profiler-md [options] [file]
1418
+
1419
+ Options:
1420
+ -t, --type <type> Profile type (auto-detected from file extension by default)
1421
+ -o, --output <file> Output file (default: - for stdout)
1422
+ --top-n <n> Number of top entries to show (default: 20)
1423
+ --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)
1425
+ --help Show this help message
1426
+
1427
+ Supported profile types:
1428
+ ${Array.from(extensionToProfileConverter, ([extension, { type }]) => ` *${extension} -> ${type}`).join(`\n`)}
1429
+ `, {
1430
+ importMeta: import.meta,
1431
+ allowUnknownFlags: false,
1432
+ flags: {
1433
+ type: {
1434
+ type: `string`,
1435
+ shortFlag: `t`
1436
+ },
1437
+ output: {
1438
+ type: `string`,
1439
+ shortFlag: `o`,
1440
+ default: `-`
1441
+ },
1442
+ topN: { type: `number` },
1443
+ cwd: { type: `string` },
1444
+ thirdParty: {
1445
+ type: `string`,
1446
+ isMultiple: true,
1447
+ default: []
1448
+ }
1449
+ }
1450
+ });
1451
+ try {
1452
+ const { input: [filePath], flags: { output: outputPath, type: profileType, topN, cwd, thirdParty } } = cli;
1453
+ let profileConverter;
1454
+ if (profileType !== void 0) {
1455
+ profileConverter = profileTypeToConverter.get(profileType);
1456
+ if (!profileConverter) {
1457
+ process.stderr.write(`error: unknown profile type "${profileType}"\nRun with --help to see supported types.\n`);
1458
+ process.exit(2);
1459
+ }
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) {
1468
+ cli.showHelp(0);
1469
+ 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
+ }
1474
+ let data;
1475
+ if (filePath) try {
1476
+ data = await readFile(filePath);
1477
+ } catch (error) {
1478
+ const message = error instanceof Error ? error.message : String(error);
1479
+ process.stderr.write(`error: ${message}\n`);
1480
+ process.exit(1);
1481
+ }
1482
+ else data = Buffer.concat(await Array.fromAsync(process.stdin));
1483
+ const thirdPartyMatchers = thirdParty.map((glob) => picomatch(glob, { dot: true }));
1484
+ const markdown = profileConverter.convert(data, {
1485
+ topN,
1486
+ cwd,
1487
+ isThirdPartyURL: thirdPartyMatchers.length > 0 ? (url) => defaultIsThirdPartyURL(url) || thirdPartyMatchers.some((match) => match(url.pathname)) : void 0
1488
+ });
1489
+ let output;
1490
+ if (outputPath === `-`) output = process.stdout;
1491
+ else {
1492
+ output = createWriteStream(outputPath);
1493
+ await new Promise((resolve, reject) => {
1494
+ output.once(`open`, () => resolve()).once(`error`, reject);
1495
+ });
1496
+ }
1497
+ await new Promise((resolve, reject) => {
1498
+ output.write(markdown, (error) => {
1499
+ if (error) reject(error);
1500
+ else if (output === process.stdout) resolve();
1501
+ else output.end(resolve);
1502
+ });
1503
+ });
1504
+ } catch (error) {
1505
+ if (error instanceof Error) {
1506
+ process.stderr.write(`error: ${error.message}\n`);
1507
+ if (error.stack) process.stderr.write(`${error.stack}\n`);
1508
+ } else process.stderr.write(`error: ${String(error)}\n`);
1509
+ process.exit(1);
1510
+ }
1511
+
1512
+ //#endregion
1513
+ export { };