profiler-md 0.1.1 → 0.1.3

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,15 @@
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";
8
+ import convertSourceMap from "convert-source-map";
6
9
  import meow from "meow";
7
10
  import picomatch from "picomatch";
8
11
  import { Profile } from "pprof-format";
12
+ import { SourceMapConsumer } from "source-map-js";
9
13
  import plur from "plur";
10
14
  import prettyBytes from "pretty-bytes";
11
15
  import prettyMilliseconds from "pretty-ms";
@@ -34,16 +38,136 @@ var DynamicTypedArray = class {
34
38
  }
35
39
  };
36
40
 
41
+ //#endregion
42
+ //#region src/helpers/markdown.ts
43
+ const formatHeading = (level, content) => `${`#`.repeat(level)} ${content}`;
44
+ const formatTable = (headers, rows) => {
45
+ const headerContents = headers.map((header) => typeof header === `string` ? header : header.content);
46
+ const allRows = [headerContents, ...rows];
47
+ const widths = headerContents.map((_, columnIndex) => Math.max(...allRows.map((row) => row[columnIndex]?.length ?? 0)));
48
+ const isRight = (index) => typeof headers[index] !== `string` && headers[index]?.align === `right`;
49
+ const alignCell = (cell, index) => isRight(index) ? cell.padStart(widths[index]) : cell.padEnd(widths[index]);
50
+ const formatRow = (row) => `| ${row.map((cell, index) => alignCell(cell, index)).join(` | `)} |`;
51
+ const separator = `| ${widths.map((width, index) => isRight(index) ? `${`-`.repeat(width - 1)}:` : `-`.repeat(width)).join(` | `)} |`;
52
+ return [
53
+ formatRow(headerContents),
54
+ separator,
55
+ ...rows.map(formatRow)
56
+ ].join(`\n`);
57
+ };
58
+ const inlineCode = (text) => {
59
+ const longestBacktickRun = Math.max(0, ...Array.from(text.matchAll(/`+/gu), (match) => match[0].length));
60
+ const fence = `\``.repeat(longestBacktickRun + 1);
61
+ return `${fence}${text.startsWith(`\``) || text.endsWith(`\``) ? ` ${text} ` : text}${fence}`;
62
+ };
63
+
64
+ //#endregion
65
+ //#region src/location.ts
66
+ /**
67
+ * Converts a {@link ProfileLocationInput} or a {@link ProfileLocation} or
68
+ * returns undefined if it's not a valid location.
69
+ */
70
+ const makeProfileLocation = ({ urlOrPath, line, column }) => {
71
+ if (!urlOrPath) return;
72
+ const fileReference = makeFileReference(urlOrPath);
73
+ if (fileReference.type !== `absolute`) return;
74
+ return {
75
+ url: fileReference.url,
76
+ line,
77
+ column
78
+ };
79
+ };
80
+ const makeFileReference = (urlOrPath) => {
81
+ if (urlOrPath.startsWith(`/`)) try {
82
+ return {
83
+ type: `absolute`,
84
+ url: new URL(`file://${urlOrPath}`)
85
+ };
86
+ } catch {
87
+ return {
88
+ type: `relative`,
89
+ path: urlOrPath
90
+ };
91
+ }
92
+ if (!urlOrPath.includes(`:`)) return {
93
+ type: `relative`,
94
+ path: urlOrPath
95
+ };
96
+ try {
97
+ return {
98
+ type: `absolute`,
99
+ url: new URL(urlOrPath)
100
+ };
101
+ } catch {
102
+ return {
103
+ type: `relative`,
104
+ path: urlOrPath
105
+ };
106
+ }
107
+ };
108
+ const formatProfileLocation = (location, options) => {
109
+ const { cwd } = options;
110
+ if (!location) return inlineCode(`<native>`);
111
+ location = sourceMapProfileLocation(location, options);
112
+ let path;
113
+ if (location.url.protocol === `file:`) {
114
+ path = location.url.pathname;
115
+ if (cwd !== void 0 && path.startsWith(cwd)) path = path.slice(cwd.length);
116
+ } else path = location.url.href;
117
+ if (location.line !== void 0) {
118
+ path += `:${location.line}`;
119
+ if (location.column !== void 0) path += `:${location.column}`;
120
+ }
121
+ return path || inlineCode(`<native>`);
122
+ };
123
+
124
+ //#endregion
125
+ //#region src/source-map.ts
126
+ const normalizeSourceMaps = (sourceMaps) => {
127
+ if (Array.isArray(sourceMaps)) sourceMaps = Object.fromEntries(sourceMaps.flatMap((sourceMap) => sourceMap.file ? [[sourceMap.file, sourceMap]] : []));
128
+ return Object.entries(sourceMaps).map(([urlOrPath, sourceMap]) => ({
129
+ consumer: new SourceMapConsumer(sourceMap),
130
+ location: makeFileReference(urlOrPath)
131
+ }));
132
+ };
133
+ const sourceMapProfileLocation = (location, { cwd, sourceMaps }) => {
134
+ 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}`));
135
+ if (!sourceMap) return location;
136
+ let mappedPosition;
137
+ try {
138
+ mappedPosition = sourceMap.consumer.originalPositionFor({
139
+ line: location.line ?? 1,
140
+ column: (location.column ?? 1) - 1
141
+ });
142
+ } catch {
143
+ return location;
144
+ }
145
+ if (!mappedPosition.source) return location;
146
+ const mappedLocation = makeFileReference(mappedPosition.source);
147
+ if (mappedLocation.type === `absolute`) return {
148
+ url: mappedLocation.url,
149
+ line: mappedPosition.line,
150
+ column: mappedPosition.column + 1
151
+ };
152
+ if (!cwd) return location;
153
+ return makeProfileLocation({
154
+ urlOrPath: cwd + mappedLocation.path,
155
+ line: mappedPosition.line,
156
+ column: mappedPosition.column + 1
157
+ }) ?? location;
158
+ };
159
+
37
160
  //#endregion
38
161
  //#region src/options.ts
39
- const normalizeProfileToMdOptions = ({ topN = 20, includeEntry = defaultIncludeEntry, isThirdPartyEntry = defaultIsThirdPartyEntry, cwd } = {}) => {
162
+ const normalizeProfileToMdOptions = ({ topN = 20, includeEntry = defaultIncludeEntry, isThirdPartyEntry = defaultIsThirdPartyEntry, cwd, sourceMaps } = {}) => {
40
163
  if (cwd === void 0 && typeof process !== `undefined`) cwd = process.cwd();
41
164
  if (cwd != null && !cwd.endsWith(`/`)) cwd = `${cwd}/`;
42
165
  return {
43
166
  topN,
44
167
  includeEntry: cacheEntryFunction(includeEntry),
45
168
  isThirdPartyEntry: cacheEntryFunction(isThirdPartyEntry),
46
- cwd: cwd ?? void 0
169
+ cwd: cwd ?? void 0,
170
+ sourceMaps: normalizeSourceMaps(sourceMaps ?? [])
47
171
  };
48
172
  };
49
173
  const cacheEntryFunction = (func) => {
@@ -95,112 +219,62 @@ let conjunctionFormatter;
95
219
  //#endregion
96
220
  //#region src/helpers/heap.ts
97
221
  var MaxHeap = class {
222
+ #keys;
223
+ #values;
224
+ /** Indices into {@link MaxHeap#keys} and {@link MaxHeap#values}. */
98
225
  #heap;
99
226
  #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);
227
+ constructor(values, select) {
228
+ const count = values.length;
229
+ const heap = new Int32Array(count);
230
+ const keys = new Float64Array(count);
231
+ for (let i = 0; i < count; i++) {
232
+ heap[i] = i;
233
+ keys[i] = select(values[i]);
234
+ }
235
+ this.#keys = keys;
236
+ this.#values = values;
237
+ this.#heap = heap;
238
+ this.#size = count;
239
+ for (let i = Math.floor(count / 2) - 1; i >= 0; i--) this.#siftDown(i);
109
240
  }
110
241
  get length() {
111
242
  return this.#size;
112
243
  }
113
244
  pop() {
114
245
  if (this.#size === 0) return;
115
- const max = this.#heap[0][1];
246
+ const maxIndex = this.#heap[0];
116
247
  this.#heap[0] = this.#heap[--this.#size];
117
248
  this.#siftDown(0);
118
- return max;
249
+ return this.#values[maxIndex];
119
250
  }
120
- #siftDown(i) {
251
+ #siftDown(index) {
121
252
  while (true) {
122
- let largest = 2 * i + 1;
253
+ let largest = 2 * index + 1;
123
254
  if (largest >= this.#size) break;
124
255
  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;
256
+ if (right < this.#size) {
257
+ const leftKey = this.#keys[this.#heap[largest]];
258
+ const rightKey = this.#keys[this.#heap[right]];
259
+ if (rightKey > leftKey || rightKey === leftKey && this.#heap[right] < this.#heap[largest]) largest = right;
260
+ }
261
+ const largestKey = this.#keys[this.#heap[largest]];
262
+ const indexKey = this.#keys[this.#heap[index]];
263
+ if (largestKey < indexKey || largestKey === indexKey && this.#heap[largest] > this.#heap[index]) break;
264
+ const tmp = this.#heap[index];
265
+ this.#heap[index] = this.#heap[largest];
266
+ this.#heap[largest] = tmp;
267
+ index = largest;
129
268
  }
130
269
  }
131
270
  };
132
- const selectTopN = (values, topN, compare) => {
271
+ const selectTopN = (values, topN, select) => {
133
272
  if (topN === 0) return [];
134
- if (values.length <= topN) return values.toSorted((value1, value2) => compare(value2, value1));
135
- const heap = new MaxHeap(values, compare);
273
+ if (values.length <= topN) return values.toSorted((value1, value2) => select(value2) - select(value1));
274
+ const heap = new MaxHeap(values, select);
136
275
  return Array.from({ length: topN }, () => heap.pop());
137
276
  };
138
277
 
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
278
  //#endregion
205
279
  //#region src/profile/summarize.ts
206
280
  var ProfileBuilder = class {
@@ -511,7 +585,7 @@ const formatHottestFunctions = (metricIndex, profile, options) => {
511
585
  ].join(`\n\n`);
512
586
  };
513
587
  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]);
588
+ const hottestFunctions = selectTopN(profile.functions.filter((func) => options.includeEntry(func) && func.selfValues[metricIndex] > 0), options.topN, (func) => func.selfValues[metricIndex]);
515
589
  const subsectionOptions = {
516
590
  ...options,
517
591
  headingLevel: options.headingLevel + 2
@@ -553,7 +627,7 @@ const formatHottestSelfFunctions = (metricIndex, profile, options) => {
553
627
  };
554
628
  const formatHottestLines = (metricIndex, func, profile, options) => {
555
629
  const selfValue = func.selfValues[metricIndex];
556
- const hottestLines = selectTopN([...func.lineToMetrics], Math.ceil(options.topN / 4), ([, metrics1], [, metrics2]) => metrics1.values[metricIndex] - metrics2.values[metricIndex]);
630
+ const hottestLines = selectTopN([...func.lineToMetrics], Math.ceil(options.topN / 4), ([, metrics]) => metrics.values[metricIndex]);
557
631
  const metric = profile.metrics[metricIndex];
558
632
  return [formatHeading(options.headingLevel, `${inlineCode(func.name)} (${formatProfileLocation(func.location, options)})`), formatTable([
559
633
  {
@@ -582,7 +656,7 @@ const formatHottestLines = (metricIndex, func, profile, options) => {
582
656
  };
583
657
  const formatHottestCallers = (metricIndex, func, profile, options) => {
584
658
  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]);
659
+ 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
660
  if (hottestCallers.length === 0) return;
587
661
  const metric = profile.metrics[metricIndex];
588
662
  return [formatHeading(options.headingLevel, `${inlineCode(func.name)} (${formatProfileLocation(func.location, options)})`), formatTable([
@@ -610,7 +684,7 @@ const formatHottestCallers = (metricIndex, func, profile, options) => {
610
684
  };
611
685
  const formatHottestTotalFunctions = (metricIndex, profile, options) => {
612
686
  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]);
687
+ const hottestFunctions = selectTopN(profile.functions.filter((func) => options.includeEntry(func) && func.totalValues[metricIndex] > 0), options.topN, (func) => func.totalValues[metricIndex]);
614
688
  const subsectionOptions = {
615
689
  ...options,
616
690
  headingLevel: options.headingLevel + 2
@@ -649,7 +723,7 @@ const formatHottestTotalFunctions = (metricIndex, profile, options) => {
649
723
  };
650
724
  const formatHottestCallees = (metricIndex, func, profile, options) => {
651
725
  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]);
726
+ 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
727
  if (hottestCallees.length === 0) return;
654
728
  const metric = profile.metrics[metricIndex];
655
729
  const metricName = metricDisplayName(metric);
@@ -681,7 +755,7 @@ const formatHottestCallStacks = (metricIndex, profile, options) => {
681
755
  const hottestCallStacks = selectTopN(profile.callStacks.map((callStack) => ({
682
756
  ...callStack,
683
757
  frames: callStack.frames.filter(options.includeEntry)
684
- })).filter((callStack) => callStack.frames.length > 1), options.topN, (callStack1, callStack2) => callStack1.selfValues[metricIndex] - callStack2.selfValues[metricIndex]);
758
+ })).filter((callStack) => callStack.frames.length > 1), options.topN, (callStack) => callStack.selfValues[metricIndex]);
685
759
  if (hottestCallStacks.length === 0) return;
686
760
  const metric = profile.metrics[metricIndex];
687
761
  const metricName = metricDisplayName(metric);
@@ -1291,7 +1365,7 @@ const formatLargestConstructors = (snapshot, options) => [
1291
1365
  ].join(`\n\n`);
1292
1366
  const formatLargestSelfSizeConstructors = (snapshot, options) => {
1293
1367
  const { totalSize, constructors } = snapshot;
1294
- const largestConstructors = selectTopN(constructors.filter(options.includeEntry), options.topN, (constructor1, constructor2) => constructor1.selfSize - constructor2.selfSize);
1368
+ const largestConstructors = selectTopN(constructors.filter(options.includeEntry), options.topN, (constructor) => constructor.selfSize);
1295
1369
  const largestInstanceSections = largestConstructors.map((constructor) => formatLargestSelfSizeConstructorInstances(constructor, snapshot, options)).filter((section) => section !== void 0);
1296
1370
  return [
1297
1371
  `### Self size`,
@@ -1348,7 +1422,7 @@ const formatLargestSelfSizeConstructorInstances = (constructor, { retainerPathOf
1348
1422
  };
1349
1423
  const formatLargestRetainedSizeConstructors = (snapshot, options) => {
1350
1424
  const { totalSize, constructors } = snapshot;
1351
- const largestConstructors = selectTopN(constructors.filter(options.includeEntry), options.topN, (constructor1, constructor2) => constructor1.retainedSize - constructor2.retainedSize);
1425
+ const largestConstructors = selectTopN(constructors.filter(options.includeEntry), options.topN, (constructor) => constructor.retainedSize);
1352
1426
  const largestInstanceSections = largestConstructors.map((constructor) => formatLargestRetainedSizeConstructorInstances(constructor, snapshot, options)).filter((section) => section !== void 0);
1353
1427
  return [
1354
1428
  `### Retained size`,
@@ -1404,7 +1478,7 @@ const formatLargestRetainedSizeConstructorInstances = (constructor, { retainerPa
1404
1478
  ]))].join(`\n\n`);
1405
1479
  };
1406
1480
  const selectLargestInstancesByRetainerPath = (instances, sizeOf, retainerPathOf, topN) => {
1407
- const heap = new MaxHeap(instances, (instance1, instance2) => sizeOf(instance1) - sizeOf(instance2));
1481
+ const heap = new MaxHeap(instances, sizeOf);
1408
1482
  const pathToGroup = /* @__PURE__ */ new Map();
1409
1483
  while (heap.length > 0 && pathToGroup.size < topN) {
1410
1484
  const instance = heap.pop();
@@ -1430,7 +1504,7 @@ const formatLargestClosures = (snapshot, options) => {
1430
1504
  const largestClosures = selectTopN(closures.filter((closure) => options.includeEntry({
1431
1505
  ...closure,
1432
1506
  id: closure.largestInstanceId
1433
- })), options.topN, (closure1, closure2) => closure1.retainedSize - closure2.retainedSize);
1507
+ })), options.topN, (closure) => closure.retainedSize);
1434
1508
  const retainedSections = largestClosures.map((closure) => formatClosureRetainedObjects(closure, snapshot, options)).filter((section) => section !== void 0);
1435
1509
  return [
1436
1510
  `## Largest closures`,
@@ -1477,7 +1551,7 @@ const formatClosureRetainedObjects = (closure, { retainedNodesOf, retainerPathOf
1477
1551
  seen[node.id] = 1;
1478
1552
  if (options.includeEntry(node)) allRetainedNodes.push(node);
1479
1553
  }
1480
- const retainedNodes = selectTopN(allRetainedNodes, Math.ceil(options.topN / 4), (node1, node2) => node1.selfSize - node2.selfSize);
1554
+ const retainedNodes = selectTopN(allRetainedNodes, Math.ceil(options.topN / 4), (node) => node.selfSize);
1481
1555
  if (retainedNodes.length === 0) return;
1482
1556
  return [`#### ${inlineCode(closure.name)} (${formatProfileLocation(closure.location, options)})`, formatTable([
1483
1557
  {
@@ -1512,7 +1586,7 @@ const formatLargestStrings = ({ totalSize, strings, retainerPathOf }, options) =
1512
1586
  },
1513
1587
  `Value`,
1514
1588
  `Path`
1515
- ], selectTopN(strings, options.topN, (string1, string2) => string1.selfSize - string2.selfSize).map((string) => [
1589
+ ], selectTopN(strings, options.topN, (string) => string.selfSize).map((string) => [
1516
1590
  formatPercent(string.selfSize / totalSize),
1517
1591
  formatBytes(string.selfSize),
1518
1592
  inlineCode(string.name),
@@ -1695,7 +1769,7 @@ const computeNodeAdjacencyGraph = ({ snapshot: { node_count: nodeCount }, nodes,
1695
1769
  offsetToPredecessorEdgeIndex
1696
1770
  };
1697
1771
  };
1698
- const computeNodeOrdinalToLocation = ({ nodes, edges, strings, locations }, { ordinalToSuccessorStartOffset, offsetToSuccessorEdgeIndex }, { nodeFieldCount, nodeTypeOffset, nodeNameOffset, nodeTypeClosure, edgeNameOrIndexOffset, edgeToNodeOffset, locationFieldCount, locationScriptIdOffset, locationObjectIndexOffset, locationLineOffset, locationColumnOffset }) => {
1772
+ const computeNodeOrdinalToLocation = ({ snapshot: { node_count: nodeCount }, nodes, edges, strings, locations }, { ordinalToSuccessorStartOffset, offsetToSuccessorEdgeIndex }, { nodeFieldCount, nodeTypeOffset, nodeNameOffset, nodeTypeClosure, edgeNameOrIndexOffset, edgeToNodeOffset, locationFieldCount, locationScriptIdOffset, locationObjectIndexOffset, locationLineOffset, locationColumnOffset }) => {
1699
1773
  const namedEdgeToNodeIndex = (nodeIndex, targetEdgeName) => {
1700
1774
  const nodeOrdinal = nodeIndex / nodeFieldCount;
1701
1775
  const successorStartOffset = ordinalToSuccessorStartOffset[nodeOrdinal];
@@ -1721,7 +1795,7 @@ const computeNodeOrdinalToLocation = ({ nodes, edges, strings, locations }, { or
1721
1795
  if (!location) continue;
1722
1796
  scriptIdToFileLocation.set(scriptId, location);
1723
1797
  }
1724
- const nodeOrdinalToLocation = [];
1798
+ const nodeOrdinalToLocation = Array.from({ length: nodeCount });
1725
1799
  const fileLocationToUrl = /* @__PURE__ */ new Map();
1726
1800
  for (let locationIndex = 0; locationIndex < locations.length; locationIndex += locationFieldCount) {
1727
1801
  const scriptId = locations[locationIndex + locationScriptIdOffset];
@@ -2126,6 +2200,9 @@ const cli = meow(`
2126
2200
  --cwd <path> Working directory for relative file paths in output
2127
2201
  --third-party <glob> Mark URLs matching this glob as third-party
2128
2202
  (repeatable; default: node_modules)
2203
+ --source-maps <glob> Apply source maps matching this glob to profile
2204
+ locations; files may be source map JSON or contain
2205
+ inline source map comments (repeatable)
2129
2206
  --help Show this help message
2130
2207
  `, {
2131
2208
  importMeta: import.meta,
@@ -2146,18 +2223,34 @@ const cli = meow(`
2146
2223
  type: `string`,
2147
2224
  isMultiple: true,
2148
2225
  default: []
2226
+ },
2227
+ sourceMaps: {
2228
+ type: `string`,
2229
+ isMultiple: true,
2230
+ default: []
2149
2231
  }
2150
2232
  }
2151
2233
  });
2152
2234
  const gunzipAsync = promisify(gunzip);
2153
2235
  const brotliDecompressAsync = promisify(brotliDecompress);
2236
+ /**
2237
+ * Pre-resolves relative source paths against the map file's directory so that `source-map-js` returns
2238
+ * absolute URLs.
2239
+ */
2240
+ const resolveSourceMapSources = (sourceMap, path) => {
2241
+ if (sourceMap.sourceRoot) return sourceMap;
2242
+ return {
2243
+ ...sourceMap,
2244
+ sources: sourceMap.sources.map((source) => makeFileReference(source).type === `absolute` ? source : new URL(source, pathToFileURL(resolve(dirname(path)))).href)
2245
+ };
2246
+ };
2154
2247
  const decompressData = async (data, filePath) => {
2155
2248
  if (filePath?.endsWith(`.br`)) return brotliDecompressAsync(data);
2156
2249
  if (data[0] === 31 && data[1] === 139) return gunzipAsync(data);
2157
2250
  return data;
2158
2251
  };
2159
2252
  try {
2160
- const { input: [filePath], flags: { output: outputPath, type: profileType, topN, cwd, thirdParty } } = cli;
2253
+ const { input: [filePath], flags: { output: outputPath, type: profileType, topN, cwd, thirdParty, sourceMaps: sourceMapPatterns } } = cli;
2161
2254
  let forcedProfileConverter;
2162
2255
  if (profileType !== void 0) {
2163
2256
  forcedProfileConverter = profileConverters.find((format) => format.type === profileType);
@@ -2185,11 +2278,20 @@ try {
2185
2278
  process.stderr.write(`error: failed to decompress input: ${message}\n`);
2186
2279
  process.exit(1);
2187
2280
  }
2188
- const thirdPartyMatchers = thirdParty.map((glob) => picomatch(glob, { dot: true }));
2281
+ const thirdPartyMatchers = thirdParty.map((pattern) => picomatch(pattern, { dot: true }));
2282
+ const isThirdPartyEntry = thirdPartyMatchers.length > 0 ? (entry) => defaultIsThirdPartyEntry(entry) || !!entry.location && thirdPartyMatchers.some((match) => match(entry.location.url.pathname)) : void 0;
2283
+ const sourceMapPaths = (await Promise.all(sourceMapPatterns.map((pattern) => Array.fromAsync(glob(pattern))))).flat();
2189
2284
  const options = {
2190
2285
  topN,
2191
2286
  cwd,
2192
- isThirdPartyEntry: thirdPartyMatchers.length > 0 ? (entry) => defaultIsThirdPartyEntry(entry) || !!entry.location && thirdPartyMatchers.some((match) => match(entry.location.url.pathname)) : void 0
2287
+ isThirdPartyEntry,
2288
+ sourceMaps: await Promise.all(sourceMapPaths.map(async (path) => {
2289
+ const content = await readFile(path, `utf8`);
2290
+ const inlineSourceMap = convertSourceMap.fromSource(content)?.toObject();
2291
+ if (!inlineSourceMap) return resolveSourceMapSources(JSON.parse(content), path);
2292
+ inlineSourceMap.file ??= pathToFileURL(resolve(path)).href;
2293
+ return resolveSourceMapSources(inlineSourceMap, path);
2294
+ }))
2193
2295
  };
2194
2296
  let markdown;
2195
2297
  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.
@@ -167,4 +178,4 @@ declare const v8HeapProfileToMd: (data: string | Uint8Array, options?: ProfileTo
167
178
  */
168
179
  declare const v8HeapSnapshotToMd: (data: string | Uint8Array, options?: ProfileToMdOptions) => string;
169
180
  //#endregion
170
- 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 };