profiler-md 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -1,11 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
  import { createWriteStream } from "node:fs";
3
- import { readFile } from "node:fs/promises";
3
+ import { glob, readFile } from "node:fs/promises";
4
+ import { dirname, resolve } from "node:path";
5
+ import { pathToFileURL } from "node:url";
4
6
  import { promisify } from "node:util";
5
7
  import { brotliDecompress, gunzip } from "node:zlib";
6
8
  import meow from "meow";
7
9
  import picomatch from "picomatch";
8
10
  import { Profile } from "pprof-format";
11
+ import { SourceMapConsumer } from "source-map-js";
9
12
  import plur from "plur";
10
13
  import prettyBytes from "pretty-bytes";
11
14
  import prettyMilliseconds from "pretty-ms";
@@ -34,16 +37,136 @@ var DynamicTypedArray = class {
34
37
  }
35
38
  };
36
39
 
40
+ //#endregion
41
+ //#region src/helpers/markdown.ts
42
+ const formatHeading = (level, content) => `${`#`.repeat(level)} ${content}`;
43
+ const formatTable = (headers, rows) => {
44
+ const headerContents = headers.map((header) => typeof header === `string` ? header : header.content);
45
+ const allRows = [headerContents, ...rows];
46
+ const widths = headerContents.map((_, columnIndex) => Math.max(...allRows.map((row) => row[columnIndex]?.length ?? 0)));
47
+ const isRight = (index) => typeof headers[index] !== `string` && headers[index]?.align === `right`;
48
+ const alignCell = (cell, index) => isRight(index) ? cell.padStart(widths[index]) : cell.padEnd(widths[index]);
49
+ const formatRow = (row) => `| ${row.map((cell, index) => alignCell(cell, index)).join(` | `)} |`;
50
+ const separator = `| ${widths.map((width, index) => isRight(index) ? `${`-`.repeat(width - 1)}:` : `-`.repeat(width)).join(` | `)} |`;
51
+ return [
52
+ formatRow(headerContents),
53
+ separator,
54
+ ...rows.map(formatRow)
55
+ ].join(`\n`);
56
+ };
57
+ const inlineCode = (text) => {
58
+ const longestBacktickRun = Math.max(0, ...Array.from(text.matchAll(/`+/gu), (match) => match[0].length));
59
+ const fence = `\``.repeat(longestBacktickRun + 1);
60
+ return `${fence}${text.startsWith(`\``) || text.endsWith(`\``) ? ` ${text} ` : text}${fence}`;
61
+ };
62
+
63
+ //#endregion
64
+ //#region src/location.ts
65
+ /**
66
+ * Converts a {@link ProfileLocationInput} or a {@link ProfileLocation} or
67
+ * returns undefined if it's not a valid location.
68
+ */
69
+ const makeProfileLocation = ({ urlOrPath, line, column }) => {
70
+ if (!urlOrPath) return;
71
+ const fileReference = makeFileReference(urlOrPath);
72
+ if (fileReference.type !== `absolute`) return;
73
+ return {
74
+ url: fileReference.url,
75
+ line,
76
+ column
77
+ };
78
+ };
79
+ const makeFileReference = (urlOrPath) => {
80
+ if (urlOrPath.startsWith(`/`)) try {
81
+ return {
82
+ type: `absolute`,
83
+ url: new URL(`file://${urlOrPath}`)
84
+ };
85
+ } catch {
86
+ return {
87
+ type: `relative`,
88
+ path: urlOrPath
89
+ };
90
+ }
91
+ if (!urlOrPath.includes(`:`)) return {
92
+ type: `relative`,
93
+ path: urlOrPath
94
+ };
95
+ try {
96
+ return {
97
+ type: `absolute`,
98
+ url: new URL(urlOrPath)
99
+ };
100
+ } catch {
101
+ return {
102
+ type: `relative`,
103
+ path: urlOrPath
104
+ };
105
+ }
106
+ };
107
+ const formatProfileLocation = (location, options) => {
108
+ const { cwd } = options;
109
+ if (!location) return inlineCode(`<native>`);
110
+ location = sourceMapProfileLocation(location, options);
111
+ let path;
112
+ if (location.url.protocol === `file:`) {
113
+ path = location.url.pathname;
114
+ if (cwd !== void 0 && path.startsWith(cwd)) path = path.slice(cwd.length);
115
+ } else path = location.url.href;
116
+ if (location.line !== void 0) {
117
+ path += `:${location.line}`;
118
+ if (location.column !== void 0) path += `:${location.column}`;
119
+ }
120
+ return path || inlineCode(`<native>`);
121
+ };
122
+
123
+ //#endregion
124
+ //#region src/source-map.ts
125
+ const normalizeSourceMaps = (sourceMaps) => {
126
+ if (Array.isArray(sourceMaps)) sourceMaps = Object.fromEntries(sourceMaps.flatMap((sourceMap) => sourceMap.file ? [[sourceMap.file, sourceMap]] : []));
127
+ return Object.entries(sourceMaps).map(([urlOrPath, sourceMap]) => ({
128
+ consumer: new SourceMapConsumer(sourceMap),
129
+ location: makeFileReference(urlOrPath)
130
+ }));
131
+ };
132
+ const sourceMapProfileLocation = (location, { cwd, sourceMaps }) => {
133
+ const sourceMap = sourceMaps.find((sourceMap) => sourceMap.location.type === `absolute` && sourceMap.location.url.href === location.url.href) ?? sourceMaps.find((sourceMap) => sourceMap.location.type === `relative` && location.url.pathname.endsWith(`/${sourceMap.location.path}`));
134
+ if (!sourceMap) return location;
135
+ let mappedPosition;
136
+ try {
137
+ mappedPosition = sourceMap.consumer.originalPositionFor({
138
+ line: location.line ?? 1,
139
+ column: (location.column ?? 1) - 1
140
+ });
141
+ } catch {
142
+ return location;
143
+ }
144
+ if (!mappedPosition.source) return location;
145
+ const mappedLocation = makeFileReference(mappedPosition.source);
146
+ if (mappedLocation.type === `absolute`) return {
147
+ url: mappedLocation.url,
148
+ line: mappedPosition.line,
149
+ column: mappedPosition.column + 1
150
+ };
151
+ if (!cwd) return location;
152
+ return makeProfileLocation({
153
+ urlOrPath: cwd + mappedLocation.path,
154
+ line: mappedPosition.line,
155
+ column: mappedPosition.column + 1
156
+ }) ?? location;
157
+ };
158
+
37
159
  //#endregion
38
160
  //#region src/options.ts
39
- const normalizeProfileToMdOptions = ({ topN = 20, includeEntry = defaultIncludeEntry, isThirdPartyEntry = defaultIsThirdPartyEntry, cwd } = {}) => {
161
+ const normalizeProfileToMdOptions = ({ topN = 20, includeEntry = defaultIncludeEntry, isThirdPartyEntry = defaultIsThirdPartyEntry, cwd, sourceMaps } = {}) => {
40
162
  if (cwd === void 0 && typeof process !== `undefined`) cwd = process.cwd();
41
163
  if (cwd != null && !cwd.endsWith(`/`)) cwd = `${cwd}/`;
42
164
  return {
43
165
  topN,
44
166
  includeEntry: cacheEntryFunction(includeEntry),
45
167
  isThirdPartyEntry: cacheEntryFunction(isThirdPartyEntry),
46
- cwd: cwd ?? void 0
168
+ cwd: cwd ?? void 0,
169
+ sourceMaps: normalizeSourceMaps(sourceMaps ?? [])
47
170
  };
48
171
  };
49
172
  const cacheEntryFunction = (func) => {
@@ -95,112 +218,62 @@ let conjunctionFormatter;
95
218
  //#endregion
96
219
  //#region src/helpers/heap.ts
97
220
  var MaxHeap = class {
221
+ #keys;
222
+ #values;
223
+ /** Indices into {@link MaxHeap#keys} and {@link MaxHeap#values}. */
98
224
  #heap;
99
225
  #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);
226
+ constructor(values, select) {
227
+ const count = values.length;
228
+ const heap = new Int32Array(count);
229
+ const keys = new Float64Array(count);
230
+ for (let i = 0; i < count; i++) {
231
+ heap[i] = i;
232
+ keys[i] = select(values[i]);
233
+ }
234
+ this.#keys = keys;
235
+ this.#values = values;
236
+ this.#heap = heap;
237
+ this.#size = count;
238
+ for (let i = Math.floor(count / 2) - 1; i >= 0; i--) this.#siftDown(i);
109
239
  }
110
240
  get length() {
111
241
  return this.#size;
112
242
  }
113
243
  pop() {
114
244
  if (this.#size === 0) return;
115
- const max = this.#heap[0][1];
245
+ const maxIndex = this.#heap[0];
116
246
  this.#heap[0] = this.#heap[--this.#size];
117
247
  this.#siftDown(0);
118
- return max;
248
+ return this.#values[maxIndex];
119
249
  }
120
- #siftDown(i) {
250
+ #siftDown(index) {
121
251
  while (true) {
122
- let largest = 2 * i + 1;
252
+ let largest = 2 * index + 1;
123
253
  if (largest >= this.#size) break;
124
254
  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;
255
+ if (right < this.#size) {
256
+ const leftKey = this.#keys[this.#heap[largest]];
257
+ const rightKey = this.#keys[this.#heap[right]];
258
+ if (rightKey > leftKey || rightKey === leftKey && this.#heap[right] < this.#heap[largest]) largest = right;
259
+ }
260
+ const largestKey = this.#keys[this.#heap[largest]];
261
+ const indexKey = this.#keys[this.#heap[index]];
262
+ if (largestKey < indexKey || largestKey === indexKey && this.#heap[largest] > this.#heap[index]) break;
263
+ const tmp = this.#heap[index];
264
+ this.#heap[index] = this.#heap[largest];
265
+ this.#heap[largest] = tmp;
266
+ index = largest;
129
267
  }
130
268
  }
131
269
  };
132
- const selectTopN = (values, topN, compare) => {
270
+ const selectTopN = (values, topN, select) => {
133
271
  if (topN === 0) return [];
134
- if (values.length <= topN) return values.toSorted((value1, value2) => compare(value2, value1));
135
- const heap = new MaxHeap(values, compare);
272
+ if (values.length <= topN) return values.toSorted((value1, value2) => select(value2) - select(value1));
273
+ const heap = new MaxHeap(values, select);
136
274
  return Array.from({ length: topN }, () => heap.pop());
137
275
  };
138
276
 
139
- //#endregion
140
- //#region src/helpers/markdown.ts
141
- const formatHeading = (level, content) => `${`#`.repeat(level)} ${content}`;
142
- const formatTable = (headers, rows) => {
143
- const headerContents = headers.map((header) => typeof header === `string` ? header : header.content);
144
- const allRows = [headerContents, ...rows];
145
- const widths = headerContents.map((_, columnIndex) => Math.max(...allRows.map((row) => row[columnIndex]?.length ?? 0)));
146
- const isRight = (index) => typeof headers[index] !== `string` && headers[index]?.align === `right`;
147
- const alignCell = (cell, index) => isRight(index) ? cell.padStart(widths[index]) : cell.padEnd(widths[index]);
148
- const formatRow = (row) => `| ${row.map((cell, index) => alignCell(cell, index)).join(` | `)} |`;
149
- const separator = `| ${widths.map((width, index) => isRight(index) ? `${`-`.repeat(width - 1)}:` : `-`.repeat(width)).join(` | `)} |`;
150
- return [
151
- formatRow(headerContents),
152
- separator,
153
- ...rows.map(formatRow)
154
- ].join(`\n`);
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
- };
161
-
162
- //#endregion
163
- //#region src/location.ts
164
- /**
165
- * Converts a {@link ProfileLocationInput} or a {@link ProfileLocation} or
166
- * returns undefined if it's not a valid location.
167
- */
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
- };
176
- } catch {
177
- return;
178
- }
179
- if (!urlOrPath.includes(`:`)) return;
180
- try {
181
- return {
182
- url: new URL(urlOrPath),
183
- line,
184
- column
185
- };
186
- } catch {
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
277
  //#endregion
205
278
  //#region src/profile/summarize.ts
206
279
  var ProfileBuilder = class {
@@ -511,7 +584,7 @@ const formatHottestFunctions = (metricIndex, profile, options) => {
511
584
  ].join(`\n\n`);
512
585
  };
513
586
  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]);
587
+ const hottestFunctions = selectTopN(profile.functions.filter((func) => options.includeEntry(func) && func.selfValues[metricIndex] > 0), options.topN, (func) => func.selfValues[metricIndex]);
515
588
  const subsectionOptions = {
516
589
  ...options,
517
590
  headingLevel: options.headingLevel + 2
@@ -553,7 +626,7 @@ const formatHottestSelfFunctions = (metricIndex, profile, options) => {
553
626
  };
554
627
  const formatHottestLines = (metricIndex, func, profile, options) => {
555
628
  const selfValue = func.selfValues[metricIndex];
556
- const hottestLines = selectTopN([...func.lineToMetrics], Math.ceil(options.topN / 4), ([, metrics1], [, metrics2]) => metrics1.values[metricIndex] - metrics2.values[metricIndex]);
629
+ const hottestLines = selectTopN([...func.lineToMetrics], Math.ceil(options.topN / 4), ([, metrics]) => metrics.values[metricIndex]);
557
630
  const metric = profile.metrics[metricIndex];
558
631
  return [formatHeading(options.headingLevel, `${inlineCode(func.name)} (${formatProfileLocation(func.location, options)})`), formatTable([
559
632
  {
@@ -582,7 +655,7 @@ const formatHottestLines = (metricIndex, func, profile, options) => {
582
655
  };
583
656
  const formatHottestCallers = (metricIndex, func, profile, options) => {
584
657
  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]);
658
+ const hottestCallers = selectTopN([...func.callerIdToMetrics.values()].filter((entry) => options.includeEntry(entry.caller) && entry.selfValues[metricIndex] > 0), Math.ceil(options.topN / 4), (entry) => entry.selfValues[metricIndex]);
586
659
  if (hottestCallers.length === 0) return;
587
660
  const metric = profile.metrics[metricIndex];
588
661
  return [formatHeading(options.headingLevel, `${inlineCode(func.name)} (${formatProfileLocation(func.location, options)})`), formatTable([
@@ -610,7 +683,7 @@ const formatHottestCallers = (metricIndex, func, profile, options) => {
610
683
  };
611
684
  const formatHottestTotalFunctions = (metricIndex, profile, options) => {
612
685
  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]);
686
+ const hottestFunctions = selectTopN(profile.functions.filter((func) => options.includeEntry(func) && func.totalValues[metricIndex] > 0), options.topN, (func) => func.totalValues[metricIndex]);
614
687
  const subsectionOptions = {
615
688
  ...options,
616
689
  headingLevel: options.headingLevel + 2
@@ -649,7 +722,7 @@ const formatHottestTotalFunctions = (metricIndex, profile, options) => {
649
722
  };
650
723
  const formatHottestCallees = (metricIndex, func, profile, options) => {
651
724
  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]);
725
+ const hottestCallees = selectTopN([...func.calleeIdToMetrics.values()].filter((entry) => options.includeEntry(entry.callee) && entry.totalValues[metricIndex] > 0), Math.ceil(options.topN / 4), (entry) => entry.totalValues[metricIndex]);
653
726
  if (hottestCallees.length === 0) return;
654
727
  const metric = profile.metrics[metricIndex];
655
728
  const metricName = metricDisplayName(metric);
@@ -681,7 +754,7 @@ const formatHottestCallStacks = (metricIndex, profile, options) => {
681
754
  const hottestCallStacks = selectTopN(profile.callStacks.map((callStack) => ({
682
755
  ...callStack,
683
756
  frames: callStack.frames.filter(options.includeEntry)
684
- })).filter((callStack) => callStack.frames.length > 1), options.topN, (callStack1, callStack2) => callStack1.selfValues[metricIndex] - callStack2.selfValues[metricIndex]);
757
+ })).filter((callStack) => callStack.frames.length > 1), options.topN, (callStack) => callStack.selfValues[metricIndex]);
685
758
  if (hottestCallStacks.length === 0) return;
686
759
  const metric = profile.metrics[metricIndex];
687
760
  const metricName = metricDisplayName(metric);
@@ -940,6 +1013,8 @@ const detectPprof = (data) => {
940
1013
  * - Node.js's [`pprof`](https://www.npmjs.com/package/pprof) npm package
941
1014
  * - Python's [`py-spy`](https://github.com/benfred/py-spy)
942
1015
  * - Rust's [`pprof-rs`](https://github.com/tikv/pprof-rs)
1016
+ * - Java/Kotlin's [`async-profiler`](https://github.com/async-profiler/async-profiler)
1017
+ * - C/C++'s [`gperftools`](https://github.com/gperftools/gperftools) (via `pprof --proto`)
943
1018
  */
944
1019
  const pprofToMd = (data, options) => pprofToMdInternal(parsePprof(data), options);
945
1020
  const pprofToMdInternal = (pprof, options) => {
@@ -1044,6 +1119,8 @@ const detectSpeedscopeProfile = (json) => {
1044
1119
  * - [rbspy](https://rbspy.github.io) for Ruby
1045
1120
  * - [py-spy](https://github.com/benfred/py-spy) for Python (`--format speedscope`)
1046
1121
  * - [pprof-rs](https://github.com/tikv/pprof-rs) for Rust
1122
+ * - [async-profiler](https://github.com/async-profiler/async-profiler) for Java/Kotlin (`-o speedscope`)
1123
+ * - [phpspy](https://github.com/adsr/phpspy) for PHP (`--output-format=speedscope`)
1047
1124
  */
1048
1125
  const speedscopeProfileToMd = (data, options) => speedscopeProfileToMdInternal(parseSpeedscopeProfile(data), options);
1049
1126
  const speedscopeProfileToMdInternal = (profile, options) => {
@@ -1287,7 +1364,7 @@ const formatLargestConstructors = (snapshot, options) => [
1287
1364
  ].join(`\n\n`);
1288
1365
  const formatLargestSelfSizeConstructors = (snapshot, options) => {
1289
1366
  const { totalSize, constructors } = snapshot;
1290
- const largestConstructors = selectTopN(constructors.filter(options.includeEntry), options.topN, (constructor1, constructor2) => constructor1.selfSize - constructor2.selfSize);
1367
+ const largestConstructors = selectTopN(constructors.filter(options.includeEntry), options.topN, (constructor) => constructor.selfSize);
1291
1368
  const largestInstanceSections = largestConstructors.map((constructor) => formatLargestSelfSizeConstructorInstances(constructor, snapshot, options)).filter((section) => section !== void 0);
1292
1369
  return [
1293
1370
  `### Self size`,
@@ -1344,7 +1421,7 @@ const formatLargestSelfSizeConstructorInstances = (constructor, { retainerPathOf
1344
1421
  };
1345
1422
  const formatLargestRetainedSizeConstructors = (snapshot, options) => {
1346
1423
  const { totalSize, constructors } = snapshot;
1347
- const largestConstructors = selectTopN(constructors.filter(options.includeEntry), options.topN, (constructor1, constructor2) => constructor1.retainedSize - constructor2.retainedSize);
1424
+ const largestConstructors = selectTopN(constructors.filter(options.includeEntry), options.topN, (constructor) => constructor.retainedSize);
1348
1425
  const largestInstanceSections = largestConstructors.map((constructor) => formatLargestRetainedSizeConstructorInstances(constructor, snapshot, options)).filter((section) => section !== void 0);
1349
1426
  return [
1350
1427
  `### Retained size`,
@@ -1400,7 +1477,7 @@ const formatLargestRetainedSizeConstructorInstances = (constructor, { retainerPa
1400
1477
  ]))].join(`\n\n`);
1401
1478
  };
1402
1479
  const selectLargestInstancesByRetainerPath = (instances, sizeOf, retainerPathOf, topN) => {
1403
- const heap = new MaxHeap(instances, (instance1, instance2) => sizeOf(instance1) - sizeOf(instance2));
1480
+ const heap = new MaxHeap(instances, sizeOf);
1404
1481
  const pathToGroup = /* @__PURE__ */ new Map();
1405
1482
  while (heap.length > 0 && pathToGroup.size < topN) {
1406
1483
  const instance = heap.pop();
@@ -1426,7 +1503,7 @@ const formatLargestClosures = (snapshot, options) => {
1426
1503
  const largestClosures = selectTopN(closures.filter((closure) => options.includeEntry({
1427
1504
  ...closure,
1428
1505
  id: closure.largestInstanceId
1429
- })), options.topN, (closure1, closure2) => closure1.retainedSize - closure2.retainedSize);
1506
+ })), options.topN, (closure) => closure.retainedSize);
1430
1507
  const retainedSections = largestClosures.map((closure) => formatClosureRetainedObjects(closure, snapshot, options)).filter((section) => section !== void 0);
1431
1508
  return [
1432
1509
  `## Largest closures`,
@@ -1473,7 +1550,7 @@ const formatClosureRetainedObjects = (closure, { retainedNodesOf, retainerPathOf
1473
1550
  seen[node.id] = 1;
1474
1551
  if (options.includeEntry(node)) allRetainedNodes.push(node);
1475
1552
  }
1476
- const retainedNodes = selectTopN(allRetainedNodes, Math.ceil(options.topN / 4), (node1, node2) => node1.selfSize - node2.selfSize);
1553
+ const retainedNodes = selectTopN(allRetainedNodes, Math.ceil(options.topN / 4), (node) => node.selfSize);
1477
1554
  if (retainedNodes.length === 0) return;
1478
1555
  return [`#### ${inlineCode(closure.name)} (${formatProfileLocation(closure.location, options)})`, formatTable([
1479
1556
  {
@@ -1508,7 +1585,7 @@ const formatLargestStrings = ({ totalSize, strings, retainerPathOf }, options) =
1508
1585
  },
1509
1586
  `Value`,
1510
1587
  `Path`
1511
- ], selectTopN(strings, options.topN, (string1, string2) => string1.selfSize - string2.selfSize).map((string) => [
1588
+ ], selectTopN(strings, options.topN, (string) => string.selfSize).map((string) => [
1512
1589
  formatPercent(string.selfSize / totalSize),
1513
1590
  formatBytes(string.selfSize),
1514
1591
  inlineCode(string.name),
@@ -1691,7 +1768,7 @@ const computeNodeAdjacencyGraph = ({ snapshot: { node_count: nodeCount }, nodes,
1691
1768
  offsetToPredecessorEdgeIndex
1692
1769
  };
1693
1770
  };
1694
- const computeNodeOrdinalToLocation = ({ nodes, edges, strings, locations }, { ordinalToSuccessorStartOffset, offsetToSuccessorEdgeIndex }, { nodeFieldCount, nodeTypeOffset, nodeNameOffset, nodeTypeClosure, edgeNameOrIndexOffset, edgeToNodeOffset, locationFieldCount, locationScriptIdOffset, locationObjectIndexOffset, locationLineOffset, locationColumnOffset }) => {
1771
+ const computeNodeOrdinalToLocation = ({ snapshot: { node_count: nodeCount }, nodes, edges, strings, locations }, { ordinalToSuccessorStartOffset, offsetToSuccessorEdgeIndex }, { nodeFieldCount, nodeTypeOffset, nodeNameOffset, nodeTypeClosure, edgeNameOrIndexOffset, edgeToNodeOffset, locationFieldCount, locationScriptIdOffset, locationObjectIndexOffset, locationLineOffset, locationColumnOffset }) => {
1695
1772
  const namedEdgeToNodeIndex = (nodeIndex, targetEdgeName) => {
1696
1773
  const nodeOrdinal = nodeIndex / nodeFieldCount;
1697
1774
  const successorStartOffset = ordinalToSuccessorStartOffset[nodeOrdinal];
@@ -1717,7 +1794,7 @@ const computeNodeOrdinalToLocation = ({ nodes, edges, strings, locations }, { or
1717
1794
  if (!location) continue;
1718
1795
  scriptIdToFileLocation.set(scriptId, location);
1719
1796
  }
1720
- const nodeOrdinalToLocation = [];
1797
+ const nodeOrdinalToLocation = Array.from({ length: nodeCount });
1721
1798
  const fileLocationToUrl = /* @__PURE__ */ new Map();
1722
1799
  for (let locationIndex = 0; locationIndex < locations.length; locationIndex += locationFieldCount) {
1723
1800
  const scriptId = locations[locationIndex + locationScriptIdOffset];
@@ -2060,6 +2137,7 @@ const detectV8HeapSnapshot = (json) => {
2060
2137
  * function is undefined for invalid snapshots.
2061
2138
  *
2062
2139
  * You can generate a V8 heap snapshot in several ways:
2140
+ * - [`node --heapsnapshot-near-heap-limit=1`](https://nodejs.org/api/cli.html#heapsnapshot-near-heap-limitmax-count)
2063
2141
  * - [`node --heapsnapshot-signal`](https://nodejs.org/api/cli.html#--heapsnapshot-signalsignal)
2064
2142
  * - [`bun --heap-prof`](https://bun.com/docs/project/benchmarking#heap-profiling)
2065
2143
  * - [`v8.writeHeapSnapshot()`](https://nodejs.org/api/v8.html#v8writeheapsnapshotfilename)
@@ -2115,12 +2193,14 @@ const cli = meow(`
2115
2193
 
2116
2194
  Options:
2117
2195
  -t, --type <type> Profile type, auto-detected from content if omitted
2118
- [${profileConverters.map(({ type }) => type).join(`|`)}]
2196
+ [${profileConverters.map(({ type }) => type).sort().join(`|`)}]
2119
2197
  -o, --output <file> Output file (default: - for stdout)
2120
2198
  --top-n <n> Number of top entries to show (default: 20)
2121
2199
  --cwd <path> Working directory for relative file paths in output
2122
2200
  --third-party <glob> Mark URLs matching this glob as third-party
2123
2201
  (repeatable; default: node_modules)
2202
+ --source-maps <glob> Apply source maps matching this glob to profile
2203
+ locations (repeatable)
2124
2204
  --help Show this help message
2125
2205
  `, {
2126
2206
  importMeta: import.meta,
@@ -2141,6 +2221,11 @@ const cli = meow(`
2141
2221
  type: `string`,
2142
2222
  isMultiple: true,
2143
2223
  default: []
2224
+ },
2225
+ sourceMaps: {
2226
+ type: `string`,
2227
+ isMultiple: true,
2228
+ default: []
2144
2229
  }
2145
2230
  }
2146
2231
  });
@@ -2152,7 +2237,7 @@ const decompressData = async (data, filePath) => {
2152
2237
  return data;
2153
2238
  };
2154
2239
  try {
2155
- const { input: [filePath], flags: { output: outputPath, type: profileType, topN, cwd, thirdParty } } = cli;
2240
+ const { input: [filePath], flags: { output: outputPath, type: profileType, topN, cwd, thirdParty, sourceMaps: sourceMapPatterns } } = cli;
2156
2241
  let forcedProfileConverter;
2157
2242
  if (profileType !== void 0) {
2158
2243
  forcedProfileConverter = profileConverters.find((format) => format.type === profileType);
@@ -2180,11 +2265,21 @@ try {
2180
2265
  process.stderr.write(`error: failed to decompress input: ${message}\n`);
2181
2266
  process.exit(1);
2182
2267
  }
2183
- const thirdPartyMatchers = thirdParty.map((glob) => picomatch(glob, { dot: true }));
2268
+ const thirdPartyMatchers = thirdParty.map((pattern) => picomatch(pattern, { dot: true }));
2269
+ const isThirdPartyEntry = thirdPartyMatchers.length > 0 ? (entry) => defaultIsThirdPartyEntry(entry) || !!entry.location && thirdPartyMatchers.some((match) => match(entry.location.url.pathname)) : void 0;
2270
+ const sourceMapPaths = (await Promise.all(sourceMapPatterns.map((pattern) => Array.fromAsync(glob(pattern))))).flat();
2184
2271
  const options = {
2185
2272
  topN,
2186
2273
  cwd,
2187
- isThirdPartyEntry: thirdPartyMatchers.length > 0 ? (entry) => defaultIsThirdPartyEntry(entry) || !!entry.location && thirdPartyMatchers.some((match) => match(entry.location.url.pathname)) : void 0
2274
+ isThirdPartyEntry,
2275
+ sourceMaps: await Promise.all(sourceMapPaths.map(async (path) => {
2276
+ const sourceMap = JSON.parse(await readFile(path, `utf8`));
2277
+ if (sourceMap.sourceRoot) return sourceMap;
2278
+ return {
2279
+ ...sourceMap,
2280
+ sources: sourceMap.sources.map((source) => makeFileReference(source).type === `absolute` ? source : new URL(source, pathToFileURL(resolve(dirname(path)))).href)
2281
+ };
2282
+ }))
2188
2283
  };
2189
2284
  let markdown;
2190
2285
  if (forcedProfileConverter) markdown = forcedProfileConverter.toMd(data, options);
package/dist/index.d.mts CHANGED
@@ -1,3 +1,4 @@
1
+ import { RawSourceMap as SourceMap } from "source-map-js";
1
2
  //#region src/location.d.ts
2
3
  /** A {@link URL} to a file, potentially with line and column information. */
3
4
  type ProfileLocation = {
@@ -53,6 +54,16 @@ type ProfileToMdOptions = {
53
54
  * absolute.
54
55
  */
55
56
  cwd?: string | null;
57
+ /**
58
+ * Source maps to apply when rendering profile locations.
59
+ *
60
+ * Accepts either a list of raw source map objects, or a record mapping
61
+ * generated file URLs or absolute/relative paths to raw source map objects.
62
+ *
63
+ * When a list is provided, the generated file is inferred from each source
64
+ * map's `file` field (and optionally `sourceRoot`).
65
+ */
66
+ sourceMaps?: SourceMap[] | Record<string, SourceMap>;
56
67
  };
57
68
  /**
58
69
  * Returns whether to include the given entry in the Markdown output.
@@ -82,6 +93,8 @@ declare const defaultIsThirdPartyEntry: (entry: ProfileEntry) => boolean;
82
93
  * - Node.js's [`pprof`](https://www.npmjs.com/package/pprof) npm package
83
94
  * - Python's [`py-spy`](https://github.com/benfred/py-spy)
84
95
  * - Rust's [`pprof-rs`](https://github.com/tikv/pprof-rs)
96
+ * - Java/Kotlin's [`async-profiler`](https://github.com/async-profiler/async-profiler)
97
+ * - C/C++'s [`gperftools`](https://github.com/gperftools/gperftools) (via `pprof --proto`)
85
98
  */
86
99
  declare const pprofToMd: (data: Uint8Array, options?: ProfileToMdOptions) => string;
87
100
  //#endregion
@@ -97,6 +110,8 @@ declare const pprofToMd: (data: Uint8Array, options?: ProfileToMdOptions) => str
97
110
  * - [rbspy](https://rbspy.github.io) for Ruby
98
111
  * - [py-spy](https://github.com/benfred/py-spy) for Python (`--format speedscope`)
99
112
  * - [pprof-rs](https://github.com/tikv/pprof-rs) for Rust
113
+ * - [async-profiler](https://github.com/async-profiler/async-profiler) for Java/Kotlin (`-o speedscope`)
114
+ * - [phpspy](https://github.com/adsr/phpspy) for PHP (`--output-format=speedscope`)
100
115
  */
101
116
  declare const speedscopeProfileToMd: (data: string | Uint8Array, options?: ProfileToMdOptions) => string;
102
117
  //#endregion
@@ -151,6 +166,7 @@ declare const v8HeapProfileToMd: (data: string | Uint8Array, options?: ProfileTo
151
166
  * function is undefined for invalid snapshots.
152
167
  *
153
168
  * You can generate a V8 heap snapshot in several ways:
169
+ * - [`node --heapsnapshot-near-heap-limit=1`](https://nodejs.org/api/cli.html#heapsnapshot-near-heap-limitmax-count)
154
170
  * - [`node --heapsnapshot-signal`](https://nodejs.org/api/cli.html#--heapsnapshot-signalsignal)
155
171
  * - [`bun --heap-prof`](https://bun.com/docs/project/benchmarking#heap-profiling)
156
172
  * - [`v8.writeHeapSnapshot()`](https://nodejs.org/api/v8.html#v8writeheapsnapshotfilename)
@@ -162,4 +178,4 @@ declare const v8HeapProfileToMd: (data: string | Uint8Array, options?: ProfileTo
162
178
  */
163
179
  declare const v8HeapSnapshotToMd: (data: string | Uint8Array, options?: ProfileToMdOptions) => string;
164
180
  //#endregion
165
- export { type ProfileEntry, type ProfileToMdOptions, defaultIncludeEntry, defaultIsThirdPartyEntry, pprofToMd, speedscopeProfileToMd, v8CpuProfileToMd, v8HeapProfileToMd, v8HeapSnapshotToMd };
181
+ export { type ProfileEntry, type ProfileToMdOptions, type SourceMap, defaultIncludeEntry, defaultIsThirdPartyEntry, pprofToMd, speedscopeProfileToMd, v8CpuProfileToMd, v8HeapProfileToMd, v8HeapSnapshotToMd };