profiler-md 0.1.1 → 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);
@@ -1291,7 +1364,7 @@ const formatLargestConstructors = (snapshot, options) => [
1291
1364
  ].join(`\n\n`);
1292
1365
  const formatLargestSelfSizeConstructors = (snapshot, options) => {
1293
1366
  const { totalSize, constructors } = snapshot;
1294
- 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);
1295
1368
  const largestInstanceSections = largestConstructors.map((constructor) => formatLargestSelfSizeConstructorInstances(constructor, snapshot, options)).filter((section) => section !== void 0);
1296
1369
  return [
1297
1370
  `### Self size`,
@@ -1348,7 +1421,7 @@ const formatLargestSelfSizeConstructorInstances = (constructor, { retainerPathOf
1348
1421
  };
1349
1422
  const formatLargestRetainedSizeConstructors = (snapshot, options) => {
1350
1423
  const { totalSize, constructors } = snapshot;
1351
- 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);
1352
1425
  const largestInstanceSections = largestConstructors.map((constructor) => formatLargestRetainedSizeConstructorInstances(constructor, snapshot, options)).filter((section) => section !== void 0);
1353
1426
  return [
1354
1427
  `### Retained size`,
@@ -1404,7 +1477,7 @@ const formatLargestRetainedSizeConstructorInstances = (constructor, { retainerPa
1404
1477
  ]))].join(`\n\n`);
1405
1478
  };
1406
1479
  const selectLargestInstancesByRetainerPath = (instances, sizeOf, retainerPathOf, topN) => {
1407
- const heap = new MaxHeap(instances, (instance1, instance2) => sizeOf(instance1) - sizeOf(instance2));
1480
+ const heap = new MaxHeap(instances, sizeOf);
1408
1481
  const pathToGroup = /* @__PURE__ */ new Map();
1409
1482
  while (heap.length > 0 && pathToGroup.size < topN) {
1410
1483
  const instance = heap.pop();
@@ -1430,7 +1503,7 @@ const formatLargestClosures = (snapshot, options) => {
1430
1503
  const largestClosures = selectTopN(closures.filter((closure) => options.includeEntry({
1431
1504
  ...closure,
1432
1505
  id: closure.largestInstanceId
1433
- })), options.topN, (closure1, closure2) => closure1.retainedSize - closure2.retainedSize);
1506
+ })), options.topN, (closure) => closure.retainedSize);
1434
1507
  const retainedSections = largestClosures.map((closure) => formatClosureRetainedObjects(closure, snapshot, options)).filter((section) => section !== void 0);
1435
1508
  return [
1436
1509
  `## Largest closures`,
@@ -1477,7 +1550,7 @@ const formatClosureRetainedObjects = (closure, { retainedNodesOf, retainerPathOf
1477
1550
  seen[node.id] = 1;
1478
1551
  if (options.includeEntry(node)) allRetainedNodes.push(node);
1479
1552
  }
1480
- 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);
1481
1554
  if (retainedNodes.length === 0) return;
1482
1555
  return [`#### ${inlineCode(closure.name)} (${formatProfileLocation(closure.location, options)})`, formatTable([
1483
1556
  {
@@ -1512,7 +1585,7 @@ const formatLargestStrings = ({ totalSize, strings, retainerPathOf }, options) =
1512
1585
  },
1513
1586
  `Value`,
1514
1587
  `Path`
1515
- ], selectTopN(strings, options.topN, (string1, string2) => string1.selfSize - string2.selfSize).map((string) => [
1588
+ ], selectTopN(strings, options.topN, (string) => string.selfSize).map((string) => [
1516
1589
  formatPercent(string.selfSize / totalSize),
1517
1590
  formatBytes(string.selfSize),
1518
1591
  inlineCode(string.name),
@@ -1695,7 +1768,7 @@ const computeNodeAdjacencyGraph = ({ snapshot: { node_count: nodeCount }, nodes,
1695
1768
  offsetToPredecessorEdgeIndex
1696
1769
  };
1697
1770
  };
1698
- 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 }) => {
1699
1772
  const namedEdgeToNodeIndex = (nodeIndex, targetEdgeName) => {
1700
1773
  const nodeOrdinal = nodeIndex / nodeFieldCount;
1701
1774
  const successorStartOffset = ordinalToSuccessorStartOffset[nodeOrdinal];
@@ -1721,7 +1794,7 @@ const computeNodeOrdinalToLocation = ({ nodes, edges, strings, locations }, { or
1721
1794
  if (!location) continue;
1722
1795
  scriptIdToFileLocation.set(scriptId, location);
1723
1796
  }
1724
- const nodeOrdinalToLocation = [];
1797
+ const nodeOrdinalToLocation = Array.from({ length: nodeCount });
1725
1798
  const fileLocationToUrl = /* @__PURE__ */ new Map();
1726
1799
  for (let locationIndex = 0; locationIndex < locations.length; locationIndex += locationFieldCount) {
1727
1800
  const scriptId = locations[locationIndex + locationScriptIdOffset];
@@ -2126,6 +2199,8 @@ const cli = meow(`
2126
2199
  --cwd <path> Working directory for relative file paths in output
2127
2200
  --third-party <glob> Mark URLs matching this glob as third-party
2128
2201
  (repeatable; default: node_modules)
2202
+ --source-maps <glob> Apply source maps matching this glob to profile
2203
+ locations (repeatable)
2129
2204
  --help Show this help message
2130
2205
  `, {
2131
2206
  importMeta: import.meta,
@@ -2146,6 +2221,11 @@ const cli = meow(`
2146
2221
  type: `string`,
2147
2222
  isMultiple: true,
2148
2223
  default: []
2224
+ },
2225
+ sourceMaps: {
2226
+ type: `string`,
2227
+ isMultiple: true,
2228
+ default: []
2149
2229
  }
2150
2230
  }
2151
2231
  });
@@ -2157,7 +2237,7 @@ const decompressData = async (data, filePath) => {
2157
2237
  return data;
2158
2238
  };
2159
2239
  try {
2160
- 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;
2161
2241
  let forcedProfileConverter;
2162
2242
  if (profileType !== void 0) {
2163
2243
  forcedProfileConverter = profileConverters.find((format) => format.type === profileType);
@@ -2185,11 +2265,21 @@ try {
2185
2265
  process.stderr.write(`error: failed to decompress input: ${message}\n`);
2186
2266
  process.exit(1);
2187
2267
  }
2188
- 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();
2189
2271
  const options = {
2190
2272
  topN,
2191
2273
  cwd,
2192
- 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
+ }))
2193
2283
  };
2194
2284
  let markdown;
2195
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.
@@ -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 };