profiler-md 0.8.0 → 0.8.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.
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import { JumboJSON } from "jumbo-json";
3
- import { gfmTableToMarkdown } from "mdast-util-gfm-table";
4
- import { toMarkdown } from "mdast-util-to-markdown";
5
2
  import { SourceMapConsumer } from "source-map-js";
6
3
  import plur from "plur";
7
4
  import prettyBytes from "pretty-bytes";
8
5
  import prettyMilliseconds from "pretty-ms";
6
+ import { gfmTableToMarkdown } from "mdast-util-gfm-table";
7
+ import { toMarkdown } from "mdast-util-to-markdown";
9
8
  import { Profile } from "pprof-format";
9
+ import { JumboJSON } from "jumbo-json";
10
10
  import globals from "globals";
11
11
  import { formatDocPage, getDocPage, runParser } from "@optique/core";
12
12
  import { object, or, tuple } from "@optique/core/constructs";
@@ -20,30 +20,14 @@ import { path } from "@optique/run";
20
20
  import { access, constants, glob, readFile, stat } from "node:fs/promises";
21
21
  import { Ansis } from "ansis";
22
22
  import { createReadStream, createWriteStream, openAsBlob } from "node:fs";
23
+ import { dirname, resolve } from "node:path";
23
24
  import { spawn } from "node:child_process";
24
25
  import { blob } from "node:stream/consumers";
25
26
  import { pipeline } from "node:stream/promises";
26
27
  import { createBrotliDecompress, createGunzip } from "node:zlib";
27
- import { dirname, resolve } from "node:path";
28
28
  import { pathToFileURL } from "node:url";
29
29
  import convertSourceMap from "convert-source-map";
30
30
 
31
- //#region src/error.ts
32
- /**
33
- * Thrown when a caller's input or options are unusable: an unrecognized
34
- * format, a malformed profile, an invalid option.
35
- *
36
- * A failure the caller cannot fix throws a plain `Error` instead, because such
37
- * a failure is a bug in this package.
38
- */
39
- var ProfilerMdError = class extends Error {
40
- constructor(message, options) {
41
- super(message, options);
42
- this.name = "ProfilerMdError";
43
- }
44
- };
45
-
46
- //#endregion
47
31
  //#region src/helpers/bytes.ts
48
32
  const streamToUint8Array = async (stream) => {
49
33
  const chunks = [];
@@ -282,93 +266,25 @@ const START_JSON_DOCUMENT_PREFIX_LENGTH = 16;
282
266
  const MAYBE_JSON_PREFIX_LENGTH = 1024;
283
267
 
284
268
  //#endregion
285
- //#region src/helpers/markdown.ts
286
- const text$1 = (value) => ({
287
- type: `text`,
288
- value: value.replaceAll(/\r(?!\n)/gu, ` `)
289
- });
290
- const inlineCode = (value) => ({
291
- type: `inlineCode`,
292
- value: value.replaceAll(/\r\n|[\r\n]/gu, ` `).replaceAll(`\\|`, `\\ |`)
293
- });
294
- const heading = (depth, children) => ({
295
- type: `heading`,
296
- depth,
297
- children: toPhrasing(children)
298
- });
299
- const paragraph = (children) => ({
300
- type: `paragraph`,
301
- children: toPhrasing(children)
302
- });
303
- const toPhrasing = (children) => typeof children === `string` ? [text$1(children)] : children;
269
+ //#region src/error.ts
304
270
  /**
305
- * Builds phrasing content from a template, turning literal segments and
306
- * interpolated strings into text nodes and splicing in interpolated nodes.
271
+ * Thrown when a caller's input or options are unusable: an unrecognized
272
+ * format, a malformed profile, an invalid option.
273
+ *
274
+ * A failure the caller cannot fix throws a plain `Error` instead, because such
275
+ * a failure is a bug in this package. The exception is a parser failing on an
276
+ * error it did not classify, which is either an input violating the format in
277
+ * a way the parser does not check or a parser bug. That failure throws a
278
+ * `ProfilerMdError` too, and `mayBeParserBug` identifies it.
307
279
  */
308
- const phrasing = (strings, ...values) => {
309
- const children = [];
310
- const push = (value) => {
311
- if (typeof value === `string`) {
312
- if (value) children.push(text$1(value));
313
- } else if (Array.isArray(value)) children.push(...value);
314
- else children.push(value);
315
- };
316
- for (const [index, string] of strings.entries()) {
317
- push(string);
318
- if (index < values.length) push(values[index]);
280
+ var ProfilerMdError = class extends Error {
281
+ constructor(message, options) {
282
+ super(message, options);
283
+ this.name = "ProfilerMdError";
319
284
  }
320
- return children;
321
- };
322
- /**
323
- * Phrasing for an entity heading: a code-span name followed by its
324
- * parenthesized location. {@link headingNameLocationKey} recovers the
325
- * {@link nameLocationKey} key from this shape, so entity headings must be
326
- * built through this helper for the CLI highlighter's heading ↔ table
327
- * matching to work.
328
- */
329
- const nameLocationPhrasing = (name, location) => phrasing`${inlineCode(name)} (${location})`;
330
- /** The key matching a {@link nameLocationPhrasing} heading to a table row. */
331
- const nameLocationKey = (name, location) => `${name} (${location})`;
332
- /**
333
- * Extracts the {@link nameLocationKey} key from a heading with the
334
- * {@link nameLocationPhrasing} shape, or returns null if the heading doesn't
335
- * have that shape.
336
- */
337
- const headingNameLocationKey = (heading) => {
338
- const nameIndex = heading.children.findIndex((child) => child.type === `inlineCode`);
339
- if (nameIndex === -1) return null;
340
- const name = nodeText(heading.children[nameIndex]);
341
- const after = heading.children.slice(nameIndex + 1).map(nodeText).join(``).trim();
342
- if (!after.startsWith(`(`) || !after.endsWith(`)`)) return null;
343
- return nameLocationKey(name, after.slice(1, -1));
344
285
  };
345
- /** The concatenated text content of a node's subtree. */
346
- const nodeText = (node) => {
347
- if (`value` in node && typeof node.value === `string`) return node.value;
348
- if (`children` in node && Array.isArray(node.children)) return node.children.map(nodeText).join(``);
349
- return ``;
350
- };
351
- /**
352
- * Prepends the given section header (a heading and any description) to
353
- * {@link sections}, or returns no sections if there are none.
354
- */
355
- const formatSectionGroup = (header, sections) => sections.length === 0 ? [] : [...header, ...sections];
356
- const table = (headers, rows) => ({
357
- type: `table`,
358
- align: headers.map((header) => typeof header !== `string` && header.align === `right` ? `right` : null),
359
- children: [tableRow(headers.map((header) => [text$1(typeof header === `string` ? header : header.content)])), ...rows.map(tableRow)]
360
- });
361
- const tableRow = (cells) => ({
362
- type: `tableRow`,
363
- children: cells.map((children) => ({
364
- type: `tableCell`,
365
- children
366
- }))
367
- });
368
- const mdastToMarkdown = (children) => toMarkdown({
369
- type: `root`,
370
- children
371
- }, { extensions: [gfmTableToMarkdown()] });
286
+ /** An error's message on one line, for embedding in another message. */
287
+ const reasonOf = (error) => (error instanceof Error ? error.message : String(error)).replaceAll(/\s+/gu, ` `).trim();
372
288
 
373
289
  //#endregion
374
290
  //#region src/source-map.ts
@@ -377,8 +293,14 @@ const normalizeSourceMaps = (sourceMaps) => {
377
293
  return Object.entries(sourceMaps).flatMap(([urlOrPath, sourceMap]) => {
378
294
  const fileReference = makeFileReference(urlOrPath);
379
295
  if (!fileReference) return [];
296
+ let consumer;
297
+ try {
298
+ consumer = new SourceMapConsumer(sourceMap);
299
+ } catch (error) {
300
+ throw new ProfilerMdError(`sourceMaps entry for ${urlOrPath} is an invalid source map: ${reasonOf(error)}`, { cause: error });
301
+ }
380
302
  return {
381
- consumer: new SourceMapConsumer(sourceMap),
303
+ consumer,
382
304
  fileReference
383
305
  };
384
306
  });
@@ -646,96 +568,6 @@ const commonSegmentPrefixLength = (segments1, segments2) => {
646
568
  return common;
647
569
  };
648
570
 
649
- //#endregion
650
- //#region src/helpers/graph.ts
651
- /**
652
- * Assigns each node its strongly connected component index via iterative
653
- * Tarjan. Nodes in one component are reachable from each other, so they form a
654
- * cycle.
655
- *
656
- * A node is an index into {@link nodeToEdges}, which contains its outgoing
657
- * edges, and {@link select} maps an edge to the node it points to.
658
- */
659
- const stronglyConnectedComponents = (nodeToEdges, select) => new ComponentSearch(nodeToEdges, select).search();
660
- /** One iterative Tarjan run over a graph's outgoing edges. */
661
- var ComponentSearch = class {
662
- #nodeToEdges;
663
- #select;
664
- /** Per node, its discovery index, or `-1` before it is reached. */
665
- #indices;
666
- /** Per node, the lowest discovery index reachable from it. */
667
- #lowLinks;
668
- #componentIndices;
669
- /** The nodes whose component is still open, and their membership. */
670
- #stack = [];
671
- #onStack;
672
- #nextIndex = 0;
673
- #nextComponent = 0;
674
- constructor(nodeToEdges, select) {
675
- const count = nodeToEdges.length;
676
- this.#nodeToEdges = nodeToEdges;
677
- this.#select = select;
678
- this.#indices = new Array(count).fill(-1);
679
- this.#lowLinks = new Array(count).fill(-1);
680
- this.#componentIndices = new Array(count).fill(-1);
681
- this.#onStack = new Array(count).fill(false);
682
- }
683
- search() {
684
- for (let start = 0; start < this.#nodeToEdges.length; start++) if (this.#indices[start] === -1) this.#searchFrom(start);
685
- return this.#componentIndices;
686
- }
687
- /** Traverses every unreached node reachable from {@link start}. */
688
- #searchFrom(start) {
689
- const traversal = [this.#discover(start)];
690
- while (traversal.length > 0) {
691
- const frame = traversal.at(-1);
692
- if (frame.nextEdge < frame.edges.length) {
693
- const target = this.#select(frame.edges[frame.nextEdge++]);
694
- if (this.#indices[target] === -1) traversal.push(this.#discover(target));
695
- else if (this.#onStack[target]) this.#lowerLink(frame.node, this.#indices[target]);
696
- continue;
697
- }
698
- traversal.pop();
699
- if (this.#lowLinks[frame.node] === this.#indices[frame.node]) this.#closeComponent(frame.node);
700
- const source = traversal.at(-1);
701
- if (source) this.#lowerLink(source.node, this.#lowLinks[frame.node]);
702
- }
703
- }
704
- /**
705
- * Records a node reached for the first time and returns its traversal frame,
706
- * which resumes partway through the edges after the traversal returns from a
707
- * target.
708
- */
709
- #discover(node) {
710
- this.#indices[node] = this.#nextIndex;
711
- this.#lowLinks[node] = this.#nextIndex;
712
- this.#nextIndex++;
713
- this.#stack.push(node);
714
- this.#onStack[node] = true;
715
- return {
716
- node,
717
- edges: this.#nodeToEdges[node],
718
- nextEdge: 0
719
- };
720
- }
721
- #lowerLink(node, lowLink) {
722
- this.#lowLinks[node] = Math.min(this.#lowLinks[node], lowLink);
723
- }
724
- /**
725
- * Assigns a component to {@link root} and to every node stacked above it, the
726
- * rest of the cycle it forms.
727
- */
728
- #closeComponent(root) {
729
- while (true) {
730
- const member = this.#stack.pop();
731
- this.#onStack[member] = false;
732
- this.#componentIndices[member] = this.#nextComponent;
733
- if (member === root) break;
734
- }
735
- this.#nextComponent++;
736
- }
737
- };
738
-
739
571
  //#endregion
740
572
  //#region src/formats/callgrind/matches.ts
741
573
  const matchesCallgrind = (bytes) => {
@@ -1135,6 +967,28 @@ var FormatDetectError = class extends ProfilerMdError {
1135
967
  this.errors = errors;
1136
968
  }
1137
969
  };
970
+ /**
971
+ * Thrown when the format the caller specified rejected the input.
972
+ *
973
+ * {@link FormatRejectionError.cause} is the error the format's parse threw.
974
+ */
975
+ var FormatRejectionError = class extends ProfilerMdError {
976
+ constructor(message, options) {
977
+ super(message, options);
978
+ this.name = "FormatRejectionError";
979
+ }
980
+ };
981
+ /**
982
+ * The errors a conversion error wraps that a parser threw without classifying
983
+ * them, in detection order. Empty when the error is not a conversion error, or
984
+ * when every wrapped error is a {@link FormatParseError}.
985
+ */
986
+ const unclassifiedParseFailures = (error) => {
987
+ if (error instanceof FormatDetectError) return error.errors.filter(isUnclassifiedParseFailure);
988
+ if (error instanceof FormatRejectionError) return isUnclassifiedParseFailure(error.cause) ? [error.cause] : [];
989
+ return [];
990
+ };
991
+ const isUnclassifiedParseFailure = (error) => !(error instanceof FormatParseError);
1138
992
 
1139
993
  //#endregion
1140
994
  //#region src/formats/callgrind/parse.ts
@@ -2446,42 +2300,131 @@ const selectTopN = (values, topN, select) => {
2446
2300
  };
2447
2301
 
2448
2302
  //#endregion
2449
- //#region src/modalities/table.ts
2450
- /**
2451
- * A right-aligned numeric cell formatted via {@link format}, with deltas
2452
- * formatted via {@link formatDelta} (defaults to {@link format}).
2453
- */
2454
- const numberCell = (value, format, formatDelta = format) => ({
2455
- type: `number`,
2456
- value,
2457
- format,
2458
- formatDelta
2459
- });
2460
- /** A right-aligned numeric cell formatted as a percent. */
2461
- const percentCell = (fraction) => numberCell(fraction, formatPercent);
2462
- /** A right-aligned numeric cell formatted as a count. */
2463
- const countCell = (count) => numberCell(count, formatCount);
2464
- /** A right-aligned numeric cell formatted as bytes. */
2465
- const bytesCell = (bytes) => numberCell(bytes, formatBytes, formatBytesDelta);
2466
- /** A left-aligned text cell. */
2467
- const textCell = (children) => ({
2303
+ //#region src/helpers/markdown.ts
2304
+ const text$1 = (value) => ({
2468
2305
  type: `text`,
2469
- children: typeof children === `string` ? [text$1(children)] : children
2306
+ value: value.replaceAll(/\r(?!\n)/gu, ` `)
2470
2307
  });
2471
- /** A left-aligned cell holding a single code span. */
2472
- const codeCell = (value) => textCell([inlineCode(value)]);
2473
- const formatTable = (columns, rows) => table(columns.map((column) => column.header), rows.map((row) => columns.map((column) => formatCell(column.cellOf(row)))));
2474
- const formatCell = (cell) => {
2475
- switch (cell.type) {
2476
- case `number`: return [text$1(cell.format(cell.value))];
2477
- case `text`: return cell.children;
2478
- }
2479
- };
2480
- /**
2481
- * Formats {@link rows} as a diff table, inserting `Change` and `Delta` columns
2482
- * derived from the {@link Column.primary} column at the
2483
- * {@link Column.changeDeltaBefore} column.
2484
- *
2308
+ const inlineCode = (value) => ({
2309
+ type: `inlineCode`,
2310
+ value: value.replaceAll(/\r\n|[\r\n]/gu, ` `).replaceAll(`\\|`, `\\ |`)
2311
+ });
2312
+ const heading = (depth, children) => ({
2313
+ type: `heading`,
2314
+ depth,
2315
+ children: toPhrasing(children)
2316
+ });
2317
+ const paragraph = (children) => ({
2318
+ type: `paragraph`,
2319
+ children: toPhrasing(children)
2320
+ });
2321
+ const toPhrasing = (children) => typeof children === `string` ? [text$1(children)] : children;
2322
+ /**
2323
+ * Builds phrasing content from a template, turning literal segments and
2324
+ * interpolated strings into text nodes and splicing in interpolated nodes.
2325
+ */
2326
+ const phrasing = (strings, ...values) => {
2327
+ const children = [];
2328
+ const push = (value) => {
2329
+ if (typeof value === `string`) {
2330
+ if (value) children.push(text$1(value));
2331
+ } else if (Array.isArray(value)) children.push(...value);
2332
+ else children.push(value);
2333
+ };
2334
+ for (const [index, string] of strings.entries()) {
2335
+ push(string);
2336
+ if (index < values.length) push(values[index]);
2337
+ }
2338
+ return children;
2339
+ };
2340
+ /**
2341
+ * Phrasing for an entity heading: a code-span name followed by its
2342
+ * parenthesized location. {@link headingNameLocationKey} recovers the
2343
+ * {@link nameLocationKey} key from this shape, so entity headings must be
2344
+ * built through this helper for the CLI highlighter's heading ↔ table
2345
+ * matching to work.
2346
+ */
2347
+ const nameLocationPhrasing = (name, location) => phrasing`${inlineCode(name)} (${location})`;
2348
+ /** The key matching a {@link nameLocationPhrasing} heading to a table row. */
2349
+ const nameLocationKey = (name, location) => `${name} (${location})`;
2350
+ /**
2351
+ * Extracts the {@link nameLocationKey} key from a heading with the
2352
+ * {@link nameLocationPhrasing} shape, or returns null if the heading doesn't
2353
+ * have that shape.
2354
+ */
2355
+ const headingNameLocationKey = (heading) => {
2356
+ const nameIndex = heading.children.findIndex((child) => child.type === `inlineCode`);
2357
+ if (nameIndex === -1) return null;
2358
+ const name = nodeText(heading.children[nameIndex]);
2359
+ const after = heading.children.slice(nameIndex + 1).map(nodeText).join(``).trim();
2360
+ if (!after.startsWith(`(`) || !after.endsWith(`)`)) return null;
2361
+ return nameLocationKey(name, after.slice(1, -1));
2362
+ };
2363
+ /** The concatenated text content of a node's subtree. */
2364
+ const nodeText = (node) => {
2365
+ if (`value` in node && typeof node.value === `string`) return node.value;
2366
+ if (`children` in node && Array.isArray(node.children)) return node.children.map(nodeText).join(``);
2367
+ return ``;
2368
+ };
2369
+ /**
2370
+ * Prepends the given section header (a heading and any description) to
2371
+ * {@link sections}, or returns no sections if there are none.
2372
+ */
2373
+ const formatSectionGroup = (header, sections) => sections.length === 0 ? [] : [...header, ...sections];
2374
+ const table = (headers, rows) => ({
2375
+ type: `table`,
2376
+ align: headers.map((header) => typeof header !== `string` && header.align === `right` ? `right` : null),
2377
+ children: [tableRow(headers.map((header) => [text$1(typeof header === `string` ? header : header.content)])), ...rows.map(tableRow)]
2378
+ });
2379
+ const tableRow = (cells) => ({
2380
+ type: `tableRow`,
2381
+ children: cells.map((children) => ({
2382
+ type: `tableCell`,
2383
+ children
2384
+ }))
2385
+ });
2386
+ const mdastToMarkdown = (children) => toMarkdown({
2387
+ type: `root`,
2388
+ children
2389
+ }, { extensions: [gfmTableToMarkdown()] });
2390
+
2391
+ //#endregion
2392
+ //#region src/modalities/table.ts
2393
+ /**
2394
+ * A right-aligned numeric cell formatted via {@link format}, with deltas
2395
+ * formatted via {@link formatDelta} (defaults to {@link format}).
2396
+ */
2397
+ const numberCell = (value, format, formatDelta = format) => ({
2398
+ type: `number`,
2399
+ value,
2400
+ format,
2401
+ formatDelta
2402
+ });
2403
+ /** A right-aligned numeric cell formatted as a percent. */
2404
+ const percentCell = (fraction) => numberCell(fraction, formatPercent);
2405
+ /** A right-aligned numeric cell formatted as a count. */
2406
+ const countCell = (count) => numberCell(count, formatCount);
2407
+ /** A right-aligned numeric cell formatted as bytes. */
2408
+ const bytesCell = (bytes) => numberCell(bytes, formatBytes, formatBytesDelta);
2409
+ /** A left-aligned text cell. */
2410
+ const textCell = (children) => ({
2411
+ type: `text`,
2412
+ children: typeof children === `string` ? [text$1(children)] : children
2413
+ });
2414
+ /** A left-aligned cell holding a single code span. */
2415
+ const codeCell = (value) => textCell([inlineCode(value)]);
2416
+ const formatTable = (columns, rows) => table(columns.map((column) => column.header), rows.map((row) => columns.map((column) => formatCell(column.cellOf(row)))));
2417
+ const formatCell = (cell) => {
2418
+ switch (cell.type) {
2419
+ case `number`: return [text$1(cell.format(cell.value))];
2420
+ case `text`: return cell.children;
2421
+ }
2422
+ };
2423
+ /**
2424
+ * Formats {@link rows} as a diff table, inserting `Change` and `Delta` columns
2425
+ * derived from the {@link Column.primary} column at the
2426
+ * {@link Column.changeDeltaBefore} column.
2427
+ *
2485
2428
  * The two sides' cells line up by column, so each numeric cell formats its own
2486
2429
  * `base → current` arrow and a missing side reads as `0`. Text cells take the
2487
2430
  * present side's content, with a preference for current.
@@ -9335,7 +9278,12 @@ const profileFieldWireTypes = [
9335
9278
  //#endregion
9336
9279
  //#region src/formats/pprof/parse.ts
9337
9280
  const parsePprof = (bytes) => {
9338
- const profile = Profile.decode(bytes);
9281
+ let profile;
9282
+ try {
9283
+ profile = Profile.decode(bytes);
9284
+ } catch (error) {
9285
+ throw new FormatParseError(`invalid protobuf encoding: ${reasonOf(error)}`, { cause: error });
9286
+ }
9339
9287
  const string = makeStringReader(profile);
9340
9288
  const originHint = pprofOriginHint(profile, string);
9341
9289
  const layouts = parseValueLayouts(profile, string);
@@ -9509,7 +9457,7 @@ const parseFunctionStackFrames = (profile, string) => {
9509
9457
  location: {
9510
9458
  type: `file`,
9511
9459
  urlOrPath: string(func.filename),
9512
- line: knownPprofLine(Number(func.startLine))
9460
+ line: knownPprofLine(func.startLine)
9513
9461
  }
9514
9462
  });
9515
9463
  }
@@ -9519,11 +9467,20 @@ const parseFunctionStackFrames = (profile, string) => {
9519
9467
  };
9520
9468
  };
9521
9469
  /**
9522
- * Normalizes a pprof line to `undefined` when unknown: proto3 has no field
9523
- * presence for scalars, so an unset `Function.start_line` or `Line.line`
9524
- * decodes to `0`.
9470
+ * Normalizes a pprof line to `undefined` when unknown.
9471
+ *
9472
+ * proto3 has no field presence for scalars, so an unset `Function.start_line`
9473
+ * or `Line.line` decodes to `0`.
9474
+ *
9475
+ * Some profilers (e.g. PProf.jl) write `-1` for an unknown line, which
9476
+ * `pprof-format` decodes as the unsigned 64-bit value, so a line is read back
9477
+ * as the signed integer the field is declared as.
9525
9478
  */
9526
- const knownPprofLine = (line) => line !== void 0 && line > 0 ? line : void 0;
9479
+ const knownPprofLine = (line) => {
9480
+ if (line === void 0) return;
9481
+ const signedLine = typeof line === `bigint` ? BigInt.asIntN(64, line) : line;
9482
+ return signedLine > 0 ? Number(signedLine) : void 0;
9483
+ };
9527
9484
  /**
9528
9485
  * Each location resolves to its frame indices and lines, dropping any frame
9529
9486
  * whose function is absent from the table (unsymbolized) rather than passing a
@@ -9535,7 +9492,7 @@ const resolveLocationStackFrames = (profile, frameIndexByFunctionId) => {
9535
9492
  const frame = frameIndexByFunctionId.get(functionId);
9536
9493
  return frame === void 0 ? [] : {
9537
9494
  frame,
9538
- line: Number(line)
9495
+ line
9539
9496
  };
9540
9497
  }));
9541
9498
  return framesByLocationId;
@@ -9737,6 +9694,127 @@ const decodeHeaderLine = (bytes) => {
9737
9694
  const NEWLINE = 10;
9738
9695
  let textDecoder;
9739
9696
 
9697
+ //#endregion
9698
+ //#region src/formats/parse.ts
9699
+ const parseAsFormatAsync = async (converter, data) => {
9700
+ try {
9701
+ return classifyLazyParseFailures(converter, converter.type === `json` ? converter.parse(await parseJsonAsync(data)) : await converter.parseAsync(guardStreamReads(dataToStream(data))));
9702
+ } catch (error) {
9703
+ rethrowInputReadFailure(error);
9704
+ throw toFormatRejectionError(converter, error);
9705
+ }
9706
+ };
9707
+ /**
9708
+ * Wraps each lazily consumed iterable of the parsed inputs, so an error the
9709
+ * parser throws while aggregation consumes it is classified the same way as
9710
+ * one it throws before returning.
9711
+ *
9712
+ * The wrapper is a plain iterator object, because a delegating generator costs
9713
+ * more per item.
9714
+ */
9715
+ const classifyLazyParseFailures = (converter, parsed) => {
9716
+ const toError = (error) => toFormatRejectionError(converter, error);
9717
+ return parsed.map((input) => {
9718
+ switch (input.type) {
9719
+ case `call-stack-profile`: return {
9720
+ ...input,
9721
+ observations: classifyIterableFailures(input.observations, toError),
9722
+ ...input.lineMetrics && { lineMetrics: classifyIterableFailures(input.lineMetrics, toError) }
9723
+ };
9724
+ case `call-graph`: return input;
9725
+ case `heap-snapshot`: return {
9726
+ ...input,
9727
+ nodes: classifyIterableFailures(input.nodes, toError)
9728
+ };
9729
+ }
9730
+ });
9731
+ };
9732
+ const classifyIterableFailures = (iterable, toError) => ({ [Symbol.iterator]: () => {
9733
+ const iterator = iterable[Symbol.iterator]();
9734
+ return {
9735
+ next: () => {
9736
+ try {
9737
+ return iterator.next();
9738
+ } catch (error) {
9739
+ throw toError(error);
9740
+ }
9741
+ },
9742
+ return: (value) => iterator.return?.(value) ?? {
9743
+ done: true,
9744
+ value: void 0
9745
+ }
9746
+ };
9747
+ } });
9748
+ /**
9749
+ * Decodes JSON, wrapping a decoding failure in a {@link FormatParseError}.
9750
+ *
9751
+ * A JSON format's parser cannot check anything before decoding succeeds, so a
9752
+ * decoding failure is the input's, however the decoder reports it. A failure to
9753
+ * read the data propagates as an {@link InputReadError} instead.
9754
+ */
9755
+ const parseJson = (data) => {
9756
+ try {
9757
+ return JumboJSON.parse(typeof data === `string` || ArrayBuffer.isView(data) || Array.isArray(data) ? data : guardIterableReads(data));
9758
+ } catch (error) {
9759
+ throw toInvalidJsonError(error);
9760
+ }
9761
+ };
9762
+ const parseJsonAsync = async (data) => {
9763
+ try {
9764
+ return await JumboJSON.parseAsync(guardStreamReads(dataToStream(data)), { sizeHint: data instanceof Blob ? data.size : void 0 });
9765
+ } catch (error) {
9766
+ throw toInvalidJsonError(error);
9767
+ }
9768
+ };
9769
+ const toInvalidJsonError = (error) => error instanceof InputReadError ? error : new FormatParseError(`invalid JSON: ${reasonOf(error)}`, { cause: error });
9770
+ /**
9771
+ * Thrown in place of an error the caller's data threw while a parser read it,
9772
+ * so a failure to read the data is told apart from a failure to parse it.
9773
+ */
9774
+ var InputReadError = class extends Error {
9775
+ constructor(cause) {
9776
+ super(`failed to read the input`, { cause });
9777
+ this.name = "InputReadError";
9778
+ }
9779
+ };
9780
+ /** Rethrows the error the caller's data threw, when the error stands in for one. */
9781
+ const rethrowInputReadFailure = (error) => {
9782
+ if (error instanceof InputReadError) throw error.cause;
9783
+ };
9784
+ function* guardIterableReads(iterable) {
9785
+ try {
9786
+ yield* iterable;
9787
+ } catch (error) {
9788
+ throw new InputReadError(error);
9789
+ }
9790
+ }
9791
+ const guardStreamReads = (stream) => {
9792
+ const reader = stream.getReader();
9793
+ return new ReadableStream({
9794
+ pull: async (controller) => {
9795
+ let result;
9796
+ try {
9797
+ result = await reader.read();
9798
+ } catch (error) {
9799
+ throw new InputReadError(error);
9800
+ }
9801
+ if (result.done) controller.close();
9802
+ else controller.enqueue(result.value);
9803
+ },
9804
+ cancel: (reason) => reader.cancel(reason)
9805
+ });
9806
+ };
9807
+ const dataToStream = (data) => data instanceof Blob ? data.stream() : data;
9808
+ const toFormatRejectionError = (converter, error) => new FormatRejectionError(describeParseFailure(converter, error), { cause: error });
9809
+ /**
9810
+ * A parse's failure as `<title>: <reason>`.
9811
+ *
9812
+ * A {@link FormatParseError}'s message states the violation the parser
9813
+ * identified. The parser did not classify any other error, so its reason is
9814
+ * `failed to parse the input: <message>`.
9815
+ */
9816
+ const describeParseFailure = (converter, error) => `${converter.title}: ${error instanceof FormatParseError ? reasonOf(error) : `failed to parse the input: ${reasonOf(error)}`}`;
9817
+
9740
9818
  //#endregion
9741
9819
  //#region src/formats/systing/parse.ts
9742
9820
  const parseSysting = (bytes) => {
@@ -9826,7 +9904,7 @@ var SystingProfileBuilder = class {
9826
9904
  }
9827
9905
  }
9828
9906
  #addRecord(line) {
9829
- const record = JSON.parse(line);
9907
+ const record = parseJson(line);
9830
9908
  if (!Array.isArray(record)) throw new FormatParseError(`record is not an array`);
9831
9909
  switch (record[0]) {
9832
9910
  case `f`: {
@@ -9919,12 +9997,7 @@ const cpuMetric = (header) => {
9919
9997
  * stack order is unsupported.
9920
9998
  */
9921
9999
  const parseSystingHeader = (line) => {
9922
- let json;
9923
- try {
9924
- json = JSON.parse(line);
9925
- } catch {
9926
- throw new FormatParseError(`header is not JSON`);
9927
- }
10000
+ const json = parseJson(line);
9928
10001
  if (typeof json !== `object` || json === null || Array.isArray(json)) throw new FormatParseError(`header is not an object`);
9929
10002
  const header = json;
9930
10003
  const version = header.systing_profile_export;
@@ -10386,7 +10459,7 @@ const formatRetainerEdgeLabel = (retainerOrdinal, edgeIndex, snapshot, fieldLayo
10386
10459
  const formatEdgeLabel = (edgeIndex, { edges, strings }, fieldLayout, options) => {
10387
10460
  const edgeType = edges[edgeIndex + fieldLayout.edgeTypeOffset];
10388
10461
  const edgeNameOrIndex = edges[edgeIndex + fieldLayout.edgeNameOrIndexOffset];
10389
- if (edgeType === fieldLayout.edgeTypeElement) return `[${edgeNameOrIndex}]`;
10462
+ if (edgeType === fieldLayout.edgeTypeElement) return Number.isSafeInteger(edgeNameOrIndex) ? `[${edgeNameOrIndex}]` : `[<unknown>]`;
10390
10463
  const rawEdgeName = strings[edgeNameOrIndex];
10391
10464
  const fileReference = rawEdgeName ? makeFileReference(rawEdgeName) : void 0;
10392
10465
  return `.${fileReference ? formatSourceLocation(fileReference, options) : rawEdgeName}`;
@@ -12520,80 +12593,300 @@ const makeFormatToOriginSpecs = () => {
12520
12593
  const formatToOriginSpecs = makeFormatToOriginSpecs();
12521
12594
 
12522
12595
  //#endregion
12523
- //#region src/modalities/stack-frame.ts
12524
- /**
12525
- * An input's distinct {@link StackFrame}s, owning everything derived
12526
- * from them: origin detection over the raw frames and, once the context is
12527
- * resolved, the {@link StackFrameFunctionTable} the frames resolve to.
12528
- *
12529
- * One table exists per frames array. Formats that yield multiple inputs
12530
- * sometimes share the frames; the table shares the derived data
12531
- * so each computation runs once, not once per input.
12532
- */
12533
- var StackFrameTable = class StackFrameTable {
12534
- /**
12535
- * A `WeakMap` rather than per-file state so sharing needs no extra
12536
- * parameter passed through the pipeline: each table is reclaimed with its
12537
- * frames array.
12538
- */
12539
- static #tables = /* @__PURE__ */ new WeakMap();
12540
- static for(frames) {
12541
- let table = StackFrameTable.#tables.get(frames);
12542
- if (!table) {
12543
- table = new StackFrameTable(frames);
12544
- StackFrameTable.#tables.set(frames, table);
12545
- }
12546
- return table;
12547
- }
12548
- #frames;
12549
- /** Per frame index, a lazily-filled cache of the frame's parsed function. */
12550
- #functions = [];
12551
- #detected = false;
12552
- #functionTable;
12553
- constructor(frames) {
12554
- this.#frames = frames;
12555
- }
12556
- /** Adds the raw frames to {@link detector}, once, until decided. */
12557
- addToDetector(detector) {
12558
- if (this.#detected) return;
12559
- this.#detected = true;
12560
- const { length } = this.#frames;
12561
- for (let index = 0; !detector.decided && index < length; index++) {
12562
- const { name, location } = this.#getOrCreateFunction(index);
12563
- detector.add({
12564
- id: index,
12565
- name,
12566
- location
12567
- });
12568
- }
12569
- }
12570
- #getOrCreateFunction(index) {
12571
- let func = this.#functions[index];
12572
- if (!func) {
12573
- func = parseStackFrameFunction(this.#frames[index]);
12574
- this.#functions[index] = func;
12575
- }
12576
- return func;
12577
- }
12578
- /**
12579
- * Returns the {@link StackFrameFunctionTable} the frames resolve to under
12580
- * {@link context}, normalizing them with the resolved origin on first call.
12581
- *
12582
- * Memoized without keying on the context: a frames array belongs to one file
12583
- * and is parsed fresh each conversion, so it never sees another context.
12584
- */
12585
- resolve(context) {
12586
- this.#functionTable ??= this.#normalize(context);
12587
- return this.#functionTable;
12588
- }
12589
- #normalize(context) {
12590
- return new StackFrameFunctionTable(this.#frames.map((frame) => normalizeStackFrameForContext(frame, context)));
12591
- }
12592
- };
12593
- /**
12594
- * An input's distinct frames normalized by the resolved origin, resolving a
12595
- * frame index to its {@link StackFrameFunction}.
12596
- */
12596
+ //#region src/options.ts
12597
+ const normalizeProfileInput = (input) => typeof input === `object` && input !== null && `data` in input ? {
12598
+ data: input.data,
12599
+ format: input.format,
12600
+ origin: input.origin
12601
+ } : {
12602
+ data: input,
12603
+ format: void 0,
12604
+ origin: void 0
12605
+ };
12606
+ /** Every category {@link FunctionCategory} allows. */
12607
+ const FUNCTION_CATEGORIES = [
12608
+ `ours`,
12609
+ `third-party`,
12610
+ `stdlib`,
12611
+ `native`,
12612
+ `unknown`,
12613
+ `garbage-collector`,
12614
+ `compiler`,
12615
+ `jit`,
12616
+ `regexp`,
12617
+ `kernel`,
12618
+ `idle`
12619
+ ];
12620
+ const normalizeProfileToMdOptions = ({ topN = 20, minCategoryShare = .01, baseURL, sourceMaps = [], matchEntry = defaultMatchEntry, categorizeFunctions = defaultCategorizeFunctions, showEntry = defaultShowEntry } = {}) => ({
12621
+ topN: normalizeTopN(topN),
12622
+ minCategoryShare: normalizeMinCategoryShare(minCategoryShare),
12623
+ baseURL: normalizeBaseURL(baseURL),
12624
+ sourceMaps: normalizeSourceMaps(sourceMaps),
12625
+ entryMatchKeys: cacheEntryFunction((entry, context) => entryMatchKeys(entry, context, matchEntry)),
12626
+ categorizeFunctions: (entries, context) => {
12627
+ const categories = categorizeFunctions(entries, context);
12628
+ if (categories.length !== entries.length) throw new ProfilerMdError(`categorizeFunctions must return one category per entry, aligned by index, got: ${categories.length} categories for ${entries.length} entries`);
12629
+ return categories;
12630
+ },
12631
+ showEntry: cacheEntryFunction(showEntry)
12632
+ });
12633
+ const normalizeTopN = (topN) => {
12634
+ if (!(Number.isSafeInteger(topN) && topN >= 0)) throw new ProfilerMdError(`topN must be a non-negative integer, got: ${topN}`);
12635
+ return topN;
12636
+ };
12637
+ const normalizeMinCategoryShare = (minCategoryShare) => {
12638
+ if (!(minCategoryShare >= 0 && minCategoryShare <= 1)) throw new ProfilerMdError(`minCategoryShare must be a fraction between 0 and 1, got: ${minCategoryShare}`);
12639
+ return minCategoryShare;
12640
+ };
12641
+ const normalizeBaseURL = (baseURL) => {
12642
+ if (baseURL === null) return;
12643
+ if (baseURL === `auto`) return `auto`;
12644
+ let url;
12645
+ if (baseURL === void 0) {
12646
+ if (typeof process !== `undefined`) url = new URL(`file://${process.cwd()}/`);
12647
+ } else if (typeof baseURL === `string`) {
12648
+ const fileReference = makeFileReference(baseURL);
12649
+ if (fileReference?.type !== `absolute`) throw new ProfilerMdError(`baseURL must be an absolute path or URL, got: ${baseURL}`);
12650
+ ({url} = fileReference);
12651
+ } else url = baseURL;
12652
+ if (url) url = ensureTrailingSlash(url);
12653
+ return url;
12654
+ };
12655
+ const ensureTrailingSlash = (url) => {
12656
+ if (url.pathname.endsWith(`/`)) return url;
12657
+ url = new URL(url.href);
12658
+ url.pathname += `/`;
12659
+ return url;
12660
+ };
12661
+ /** Returns an entry's diff match keys. */
12662
+ const entryMatchKeys = (entry, context, matchEntry) => {
12663
+ const match = matchEntry(entry, context);
12664
+ const name = match?.name ?? entry.name ?? ``;
12665
+ const location = match?.location ?? (entry.location ? sourceReferenceId(entry.location) : void 0);
12666
+ if (!location) return {
12667
+ name,
12668
+ nameAndLocation: name
12669
+ };
12670
+ return {
12671
+ name,
12672
+ nameAndLocation: `${name}\0${entry.location ? sourceReferenceKind(entry.location) : ``}\0${location}`
12673
+ };
12674
+ };
12675
+ const cacheEntryFunction = (func) => {
12676
+ const cache = /* @__PURE__ */ new WeakMap();
12677
+ return (entry, context) => {
12678
+ let cached = cache.get(entry);
12679
+ if (cached === void 0) {
12680
+ cached = func(entry, context);
12681
+ cache.set(entry, cached);
12682
+ }
12683
+ return cached;
12684
+ };
12685
+ };
12686
+ /**
12687
+ * The default {@link ProfileToMdOptions.matchEntry}.
12688
+ *
12689
+ * Applies the origin's match normalization to the entry, stripping the origin's
12690
+ * known run-varying identifiers (e.g. Rust build hashes for `pprof-rs`, JVM
12691
+ * runtime addresses for `jdk`), or `undefined` if the entry contains none.
12692
+ */
12693
+ const defaultMatchEntry = (entry, { origin }) => matchEntryForOrigin(entry, origin);
12694
+ /**
12695
+ * The default {@link ProfileToMdOptions.categorizeFunctions}.
12696
+ *
12697
+ * Applies the library's origin-aware categorization to each entry.
12698
+ */
12699
+ const defaultCategorizeFunctions = (entries, { origin }) => entries.map((entry) => categorizeEntryForOrigin(entry, origin));
12700
+ /**
12701
+ * Returns whether to include the given entry in the Markdown output.
12702
+ *
12703
+ * Excludes synthetic entries, which correspond to nothing in the profiled
12704
+ * program. Every function it ran is shown, and each ranking breaks down by
12705
+ * category, so a reader chooses which code to read.
12706
+ */
12707
+ const defaultShowEntry = (entry) => !isSyntheticEntry(entry);
12708
+ /**
12709
+ * Returns true if the entry is synthetic.
12710
+ *
12711
+ * The profiler invents these entries; they correspond to nothing that exists
12712
+ * in code or at runtime (e.g. a synthetic `(root)` node for heap snapshots).
12713
+ *
12714
+ * A heap snapshot node holding text takes the text as its name, so a string
12715
+ * whose value equals a synthetic name is not a synthetic entry.
12716
+ */
12717
+ const isSyntheticEntry = ({ name, category }) => !TEXT_CATEGORIES.has(category) && (name === `(root)` || name === `<root>` || name === `(module)`);
12718
+ /** The categories of a heap snapshot node named by the text it holds. */
12719
+ const TEXT_CATEGORIES = /* @__PURE__ */ new Set([
12720
+ `string`,
12721
+ `concatenated-string`,
12722
+ `sliced-string`
12723
+ ]);
12724
+
12725
+ //#endregion
12726
+ //#region src/helpers/graph.ts
12727
+ /**
12728
+ * Assigns each node its strongly connected component index via iterative
12729
+ * Tarjan. Nodes in one component are reachable from each other, so they form a
12730
+ * cycle.
12731
+ *
12732
+ * A node is an index into {@link nodeToEdges}, which contains its outgoing
12733
+ * edges, and {@link select} maps an edge to the node it points to.
12734
+ */
12735
+ const stronglyConnectedComponents = (nodeToEdges, select) => new ComponentSearch(nodeToEdges, select).search();
12736
+ /** One iterative Tarjan run over a graph's outgoing edges. */
12737
+ var ComponentSearch = class {
12738
+ #nodeToEdges;
12739
+ #select;
12740
+ /** Per node, its discovery index, or `-1` before it is reached. */
12741
+ #indices;
12742
+ /** Per node, the lowest discovery index reachable from it. */
12743
+ #lowLinks;
12744
+ #componentIndices;
12745
+ /** The nodes whose component is still open, and their membership. */
12746
+ #stack = [];
12747
+ #onStack;
12748
+ #nextIndex = 0;
12749
+ #nextComponent = 0;
12750
+ constructor(nodeToEdges, select) {
12751
+ const count = nodeToEdges.length;
12752
+ this.#nodeToEdges = nodeToEdges;
12753
+ this.#select = select;
12754
+ this.#indices = new Array(count).fill(-1);
12755
+ this.#lowLinks = new Array(count).fill(-1);
12756
+ this.#componentIndices = new Array(count).fill(-1);
12757
+ this.#onStack = new Array(count).fill(false);
12758
+ }
12759
+ search() {
12760
+ for (let start = 0; start < this.#nodeToEdges.length; start++) if (this.#indices[start] === -1) this.#searchFrom(start);
12761
+ return this.#componentIndices;
12762
+ }
12763
+ /** Traverses every unreached node reachable from {@link start}. */
12764
+ #searchFrom(start) {
12765
+ const traversal = [this.#discover(start)];
12766
+ while (traversal.length > 0) {
12767
+ const frame = traversal.at(-1);
12768
+ if (frame.nextEdge < frame.edges.length) {
12769
+ const target = this.#select(frame.edges[frame.nextEdge++]);
12770
+ if (this.#indices[target] === -1) traversal.push(this.#discover(target));
12771
+ else if (this.#onStack[target]) this.#lowerLink(frame.node, this.#indices[target]);
12772
+ continue;
12773
+ }
12774
+ traversal.pop();
12775
+ if (this.#lowLinks[frame.node] === this.#indices[frame.node]) this.#closeComponent(frame.node);
12776
+ const source = traversal.at(-1);
12777
+ if (source) this.#lowerLink(source.node, this.#lowLinks[frame.node]);
12778
+ }
12779
+ }
12780
+ /**
12781
+ * Records a node reached for the first time and returns its traversal frame,
12782
+ * which resumes partway through the edges after the traversal returns from a
12783
+ * target.
12784
+ */
12785
+ #discover(node) {
12786
+ this.#indices[node] = this.#nextIndex;
12787
+ this.#lowLinks[node] = this.#nextIndex;
12788
+ this.#nextIndex++;
12789
+ this.#stack.push(node);
12790
+ this.#onStack[node] = true;
12791
+ return {
12792
+ node,
12793
+ edges: this.#nodeToEdges[node],
12794
+ nextEdge: 0
12795
+ };
12796
+ }
12797
+ #lowerLink(node, lowLink) {
12798
+ this.#lowLinks[node] = Math.min(this.#lowLinks[node], lowLink);
12799
+ }
12800
+ /**
12801
+ * Assigns a component to {@link root} and to every node stacked above it, the
12802
+ * rest of the cycle it forms.
12803
+ */
12804
+ #closeComponent(root) {
12805
+ while (true) {
12806
+ const member = this.#stack.pop();
12807
+ this.#onStack[member] = false;
12808
+ this.#componentIndices[member] = this.#nextComponent;
12809
+ if (member === root) break;
12810
+ }
12811
+ this.#nextComponent++;
12812
+ }
12813
+ };
12814
+
12815
+ //#endregion
12816
+ //#region src/modalities/stack-frame.ts
12817
+ /**
12818
+ * An input's distinct {@link StackFrame}s, owning everything derived
12819
+ * from them: origin detection over the raw frames and, once the context is
12820
+ * resolved, the {@link StackFrameFunctionTable} the frames resolve to.
12821
+ *
12822
+ * One table exists per frames array. Formats that yield multiple inputs
12823
+ * sometimes share the frames; the table shares the derived data
12824
+ * so each computation runs once, not once per input.
12825
+ */
12826
+ var StackFrameTable = class StackFrameTable {
12827
+ /**
12828
+ * A `WeakMap` rather than per-file state so sharing needs no extra
12829
+ * parameter passed through the pipeline: each table is reclaimed with its
12830
+ * frames array.
12831
+ */
12832
+ static #tables = /* @__PURE__ */ new WeakMap();
12833
+ static for(frames) {
12834
+ let table = StackFrameTable.#tables.get(frames);
12835
+ if (!table) {
12836
+ table = new StackFrameTable(frames);
12837
+ StackFrameTable.#tables.set(frames, table);
12838
+ }
12839
+ return table;
12840
+ }
12841
+ #frames;
12842
+ /** Per frame index, a lazily-filled cache of the frame's parsed function. */
12843
+ #functions = [];
12844
+ #detected = false;
12845
+ #functionTable;
12846
+ constructor(frames) {
12847
+ this.#frames = frames;
12848
+ }
12849
+ /** Adds the raw frames to {@link detector}, once, until decided. */
12850
+ addToDetector(detector) {
12851
+ if (this.#detected) return;
12852
+ this.#detected = true;
12853
+ const { length } = this.#frames;
12854
+ for (let index = 0; !detector.decided && index < length; index++) {
12855
+ const { name, location } = this.#getOrCreateFunction(index);
12856
+ detector.add({
12857
+ id: index,
12858
+ name,
12859
+ location
12860
+ });
12861
+ }
12862
+ }
12863
+ #getOrCreateFunction(index) {
12864
+ let func = this.#functions[index];
12865
+ if (!func) {
12866
+ func = parseStackFrameFunction(this.#frames[index]);
12867
+ this.#functions[index] = func;
12868
+ }
12869
+ return func;
12870
+ }
12871
+ /**
12872
+ * Returns the {@link StackFrameFunctionTable} the frames resolve to under
12873
+ * {@link context}, normalizing them with the resolved origin on first call.
12874
+ *
12875
+ * Memoized without keying on the context: a frames array belongs to one file
12876
+ * and is parsed fresh each conversion, so it never sees another context.
12877
+ */
12878
+ resolve(context) {
12879
+ this.#functionTable ??= this.#normalize(context);
12880
+ return this.#functionTable;
12881
+ }
12882
+ #normalize(context) {
12883
+ return new StackFrameFunctionTable(this.#frames.map((frame) => normalizeStackFrameForContext(frame, context)));
12884
+ }
12885
+ };
12886
+ /**
12887
+ * An input's distinct frames normalized by the resolved origin, resolving a
12888
+ * frame index to its {@link StackFrameFunction}.
12889
+ */
12597
12890
  var StackFrameFunctionTable = class {
12598
12891
  /**
12599
12892
  * A `null` slot is a frame the origin dropped (a pseudo-frame, not a
@@ -13348,56 +13641,6 @@ const formatDiffDirectionFunctions$1 = ({ diff, measure, categories, options, he
13348
13641
  });
13349
13642
  };
13350
13643
 
13351
- //#endregion
13352
- //#region src/modalities/call-stack-profile/diff.ts
13353
- /**
13354
- * What one count of both profiles measures. The diff reports it only when the
13355
- * two count the same thing.
13356
- *
13357
- * Throws when the two count different things and share no metric, because the
13358
- * diff would then have nothing to rank.
13359
- */
13360
- const matchDiffedCountMetrics = (base, current, ranksByCount) => {
13361
- const { countMetric } = base;
13362
- if (countMetric && current.countMetric && metricsEqual(countMetric, current.countMetric)) return countMetric;
13363
- if (ranksByCount) throw new ProfilerMdError(`cannot diff profiles with no metrics in common that count different things, got: ${describeCounts(base, current)} and ${describeCounts(current, base)}`);
13364
- return null;
13365
- };
13366
- const describeCounts = ({ countMetric }, { countMetric: otherCountMetric }) => {
13367
- if (!countMetric) return `nothing`;
13368
- const { titleNoun, columnNoun } = countMetric.phrases;
13369
- return countMetric.type === `count` && columnNoun !== otherCountMetric?.phrases.columnNoun ? columnNoun : titleNoun;
13370
- };
13371
- /**
13372
- * Diffs {@link base} and {@link current} by matching up their metrics,
13373
- * functions, and categories.
13374
- *
13375
- * Throws if the profiles have no metrics in common.
13376
- */
13377
- const diffAggregatedCallStackProfiles = (base, current, options) => {
13378
- const metrics = matchDiffedMetrics(base.metrics, current.metrics);
13379
- if (metrics.length === 0 && (base.metrics.length > 0 || current.metrics.length > 0)) throw new ProfilerMdError(`cannot diff profiles with no metrics in common`);
13380
- const { entryMatchKeys } = options;
13381
- const functions = matchDiffedEntries(base.functions, current.functions, (func) => entryMatchKeys(func, base.context).nameAndLocation, (func) => entryMatchKeys(func, current.context).nameAndLocation).map(({ base: baseFunc, current: currentFunc }) => {
13382
- const { name, location, category } = currentFunc ?? baseFunc;
13383
- return {
13384
- name,
13385
- location,
13386
- category,
13387
- base: baseFunc,
13388
- current: currentFunc
13389
- };
13390
- });
13391
- return {
13392
- base,
13393
- current,
13394
- metrics,
13395
- countMetric: matchDiffedCountMetrics(base, current, metrics.length === 0),
13396
- categoryToMetrics: matchDiffedMaps(base.categoryToMetrics, current.categoryToMetrics),
13397
- functions
13398
- };
13399
- };
13400
-
13401
13644
  //#endregion
13402
13645
  //#region src/modalities/call-stack-profile/measure.ts
13403
13646
  /**
@@ -14378,255 +14621,131 @@ var ObservationsAggregator = class {
14378
14621
  };
14379
14622
  categoryToMetrics.set(category, metric);
14380
14623
  }
14381
- metric.count += func.selfCount;
14382
- for (let i = 0; i < func.selfValues.length; i++) metric.values[i] += func.selfValues[i];
14383
- }
14384
- return categoryToMetrics;
14385
- }
14386
- };
14387
- /**
14388
- * Key for the single shared anonymous function that stackless observations
14389
- * (empty {@link Observation.frameIndices}) are attributed to. A symbol so it
14390
- * can never collide with a {@link StackFrameFunction.key}. All stackless
14391
- * observations merge into one bucket because nothing distinguishes them.
14392
- */
14393
- const ANONYMOUS_FUNCTION_KEY = Symbol(`anonymous`);
14394
- /** Whether two frame lists reference the same functions in the same order. */
14395
- const sameStackFrameIds = (left, right) => {
14396
- if (left.length !== right.length) return false;
14397
- for (let i = 0; i < left.length; i++) if (left[i].id !== right[i].id) return false;
14398
- return true;
14399
- };
14400
-
14401
- //#endregion
14402
- //#region src/options.ts
14403
- const normalizeProfileInput = (input) => typeof input === `object` && input !== null && `data` in input ? {
14404
- data: input.data,
14405
- format: input.format,
14406
- origin: input.origin
14407
- } : {
14408
- data: input,
14409
- format: void 0,
14410
- origin: void 0
14411
- };
14412
- /** Every category {@link FunctionCategory} allows. */
14413
- const FUNCTION_CATEGORIES = [
14414
- `ours`,
14415
- `third-party`,
14416
- `stdlib`,
14417
- `native`,
14418
- `unknown`,
14419
- `garbage-collector`,
14420
- `compiler`,
14421
- `jit`,
14422
- `regexp`,
14423
- `kernel`,
14424
- `idle`
14425
- ];
14426
- const normalizeProfileToMdOptions = ({ topN = 20, minCategoryShare = .01, baseURL, sourceMaps = [], matchEntry = defaultMatchEntry, categorizeFunctions = defaultCategorizeFunctions, showEntry = defaultShowEntry } = {}) => ({
14427
- topN,
14428
- minCategoryShare: normalizeMinCategoryShare(minCategoryShare),
14429
- baseURL: normalizeBaseURL(baseURL),
14430
- sourceMaps: normalizeSourceMaps(sourceMaps),
14431
- entryMatchKeys: cacheEntryFunction((entry, context) => entryMatchKeys(entry, context, matchEntry)),
14432
- categorizeFunctions: (entries, context) => {
14433
- const categories = categorizeFunctions(entries, context);
14434
- if (categories.length !== entries.length) throw new ProfilerMdError(`categorizeFunctions must return one category per entry, aligned by index, got: ${categories.length} categories for ${entries.length} entries`);
14435
- return categories;
14436
- },
14437
- showEntry: cacheEntryFunction(showEntry)
14438
- });
14439
- const normalizeMinCategoryShare = (minCategoryShare) => {
14440
- if (!(minCategoryShare >= 0 && minCategoryShare <= 1)) throw new ProfilerMdError(`minCategoryShare must be a fraction between 0 and 1, got: ${minCategoryShare}`);
14441
- return minCategoryShare;
14442
- };
14443
- const normalizeBaseURL = (baseURL) => {
14444
- if (baseURL === null) return;
14445
- if (baseURL === `auto`) return `auto`;
14446
- let url;
14447
- if (baseURL === void 0) {
14448
- if (typeof process !== `undefined`) url = new URL(`file://${process.cwd()}/`);
14449
- } else if (typeof baseURL === `string`) {
14450
- const fileReference = makeFileReference(baseURL);
14451
- if (fileReference?.type !== `absolute`) throw new ProfilerMdError(`baseURL must be an absolute path or URL, got: ${baseURL}`);
14452
- ({url} = fileReference);
14453
- } else url = baseURL;
14454
- if (url) url = ensureTrailingSlash(url);
14455
- return url;
14456
- };
14457
- const ensureTrailingSlash = (url) => {
14458
- if (url.pathname.endsWith(`/`)) return url;
14459
- url = new URL(url.href);
14460
- url.pathname += `/`;
14461
- return url;
14462
- };
14463
- /** Returns an entry's diff match keys. */
14464
- const entryMatchKeys = (entry, context, matchEntry) => {
14465
- const match = matchEntry(entry, context);
14466
- const name = match?.name ?? entry.name ?? ``;
14467
- const location = match?.location ?? (entry.location ? sourceReferenceId(entry.location) : void 0);
14468
- if (!location) return {
14469
- name,
14470
- nameAndLocation: name
14471
- };
14472
- return {
14473
- name,
14474
- nameAndLocation: `${name}\0${entry.location ? sourceReferenceKind(entry.location) : ``}\0${location}`
14475
- };
14476
- };
14477
- const cacheEntryFunction = (func) => {
14478
- const cache = /* @__PURE__ */ new WeakMap();
14479
- return (entry, context) => {
14480
- let cached = cache.get(entry);
14481
- if (cached === void 0) {
14482
- cached = func(entry, context);
14483
- cache.set(entry, cached);
14624
+ metric.count += func.selfCount;
14625
+ for (let i = 0; i < func.selfValues.length; i++) metric.values[i] += func.selfValues[i];
14484
14626
  }
14485
- return cached;
14486
- };
14627
+ return categoryToMetrics;
14628
+ }
14487
14629
  };
14488
14630
  /**
14489
- * The default {@link ProfileToMdOptions.matchEntry}.
14490
- *
14491
- * Applies the origin's match normalization to the entry, stripping the origin's
14492
- * known run-varying identifiers (e.g. Rust build hashes for `pprof-rs`, JVM
14493
- * runtime addresses for `jdk`), or `undefined` if the entry contains none.
14494
- */
14495
- const defaultMatchEntry = (entry, { origin }) => matchEntryForOrigin(entry, origin);
14496
- /**
14497
- * The default {@link ProfileToMdOptions.categorizeFunctions}.
14498
- *
14499
- * Applies the library's origin-aware categorization to each entry.
14500
- */
14501
- const defaultCategorizeFunctions = (entries, { origin }) => entries.map((entry) => categorizeEntryForOrigin(entry, origin));
14502
- /**
14503
- * Returns whether to include the given entry in the Markdown output.
14504
- *
14505
- * Excludes synthetic entries, which correspond to nothing in the profiled
14506
- * program. Every function it ran is shown, and each ranking breaks down by
14507
- * category, so a reader chooses which code to read.
14508
- */
14509
- const defaultShowEntry = (entry) => !isSyntheticEntry(entry);
14510
- /**
14511
- * Returns true if the entry is synthetic.
14512
- *
14513
- * The profiler invents these entries; they correspond to nothing that exists
14514
- * in code or at runtime (e.g. a synthetic `(root)` node for heap snapshots).
14515
- *
14516
- * A heap snapshot node holding text takes the text as its name, so a string
14517
- * whose value equals a synthetic name is not a synthetic entry.
14631
+ * Key for the single shared anonymous function that stackless observations
14632
+ * (empty {@link Observation.frameIndices}) are attributed to. A symbol so it
14633
+ * can never collide with a {@link StackFrameFunction.key}. All stackless
14634
+ * observations merge into one bucket because nothing distinguishes them.
14518
14635
  */
14519
- const isSyntheticEntry = ({ name, category }) => !TEXT_CATEGORIES.has(category) && (name === `(root)` || name === `<root>` || name === `(module)`);
14520
- /** The categories of a heap snapshot node named by the text it holds. */
14521
- const TEXT_CATEGORIES = /* @__PURE__ */ new Set([
14522
- `string`,
14523
- `concatenated-string`,
14524
- `sliced-string`
14525
- ]);
14636
+ const ANONYMOUS_FUNCTION_KEY = Symbol(`anonymous`);
14637
+ /** Whether two frame lists reference the same functions in the same order. */
14638
+ const sameStackFrameIds = (left, right) => {
14639
+ if (left.length !== right.length) return false;
14640
+ for (let i = 0; i < left.length; i++) if (left[i].id !== right[i].id) return false;
14641
+ return true;
14642
+ };
14526
14643
 
14527
14644
  //#endregion
14528
- //#region src/formats/index.ts
14645
+ //#region src/modalities/call-stack-profile/diff.ts
14529
14646
  /**
14530
- * Asynchronously converts the given profile data to Markdown.
14647
+ * What one count of both profiles measures. The diff reports it only when the
14648
+ * two count the same thing.
14531
14649
  *
14532
- * See the [docs](https://github.com/TomerAberbach/profiler-md/blob/main/docs)
14533
- * for supported formats and generation instructions.
14650
+ * Throws when the two count different things and share no metric, because the
14651
+ * diff would then have nothing to rank.
14534
14652
  */
14535
- const profileToMdAsync = async (input, options = {}) => {
14536
- const normalizedOptions = normalizeProfileToMdOptions(options);
14537
- const aggregatedInputs = await aggregateInputAsync(input, normalizedOptions);
14538
- return formatAggregatedInputs(aggregatedInputs, normalizedOptions);
14653
+ const matchDiffedCountMetrics = (base, current, ranksByCount) => {
14654
+ const { countMetric } = base;
14655
+ if (countMetric && current.countMetric && metricsEqual(countMetric, current.countMetric)) return countMetric;
14656
+ if (ranksByCount) throw new ProfilerMdError(`cannot diff profiles with no metrics in common that count different things, got: ${describeCounts(base, current)} and ${describeCounts(current, base)}`);
14657
+ return null;
14658
+ };
14659
+ const describeCounts = ({ countMetric }, { countMetric: otherCountMetric }) => {
14660
+ if (!countMetric) return `nothing`;
14661
+ const { titleNoun, columnNoun } = countMetric.phrases;
14662
+ return countMetric.type === `count` && columnNoun !== otherCountMetric?.phrases.columnNoun ? columnNoun : titleNoun;
14539
14663
  };
14540
14664
  /**
14541
- * Asynchronously diffs the given base and current profile data, returning the
14542
- * difference as Markdown.
14543
- *
14544
- * Each side accepts the same input as {@link profileToMdAsync}.
14665
+ * Diffs {@link base} and {@link current} by matching up their metrics,
14666
+ * functions, and categories.
14545
14667
  *
14546
- * See the [docs](https://github.com/TomerAberbach/profiler-md/blob/main/docs)
14547
- * for supported formats and generation instructions.
14668
+ * Throws if the profiles have no metrics in common.
14548
14669
  */
14549
- const diffProfilesAsync = async (base, current, options = {}) => {
14550
- const normalizedOptions = normalizeProfileToMdOptions(options);
14551
- return formatAggregatedDiff(...await Promise.all([aggregateInputAsync(base, normalizedOptions), aggregateInputAsync(current, normalizedOptions)]), normalizedOptions);
14552
- };
14553
- const aggregateInputAsync = async (input, options) => {
14554
- const { data, format, origin } = normalizeProfileInput(input);
14555
- if (format) {
14556
- const converter = specifiedFormatConverter(format);
14557
- const context = makeContext(format, origin);
14558
- return converter.type === `json` ? aggregateJsonInput(converter, await JumboJSON.parseAsync(data), options, context) : aggregateBinaryInputAsync(converter, data instanceof Blob ? data.stream() : data, options, context);
14559
- }
14560
- const buffered = data instanceof Blob ? data : await streamToUint8Array(data);
14561
- let json;
14562
- let jsonError;
14563
- if (buffered instanceof Blob ? await maybeJsonAsync(buffered) : maybeJson(buffered)) try {
14564
- json = buffered instanceof Blob ? await JumboJSON.parseAsync(buffered) : JumboJSON.parse(buffered);
14565
- } catch (error) {
14566
- jsonError = (buffered instanceof Blob ? await startsJsonDocumentAsync(buffered) : startsJsonDocument(buffered)) ? error : void 0;
14567
- }
14568
- const rejections = [];
14569
- if (json !== void 0) {
14570
- const inputs = detectFromJson(json, options, origin, rejections);
14571
- if (inputs !== void 0) return inputs;
14572
- }
14573
- const bytes = buffered instanceof Blob ? await buffered.bytes() : buffered;
14574
- const inputs = detectFromBytes(bytes, options, origin, rejections);
14575
- if (inputs !== void 0) return inputs;
14576
- throw undetectedFormatError(rejections, jsonError);
14670
+ const diffAggregatedCallStackProfiles = (base, current, options) => {
14671
+ const metrics = matchDiffedMetrics(base.metrics, current.metrics);
14672
+ if (metrics.length === 0 && (base.metrics.length > 0 || current.metrics.length > 0)) throw new ProfilerMdError(`cannot diff profiles with no metrics in common`);
14673
+ const { entryMatchKeys } = options;
14674
+ const functions = matchDiffedEntries(base.functions, current.functions, (func) => entryMatchKeys(func, base.context).nameAndLocation, (func) => entryMatchKeys(func, current.context).nameAndLocation).map(({ base: baseFunc, current: currentFunc }) => {
14675
+ const { name, location, category } = currentFunc ?? baseFunc;
14676
+ return {
14677
+ name,
14678
+ location,
14679
+ category,
14680
+ base: baseFunc,
14681
+ current: currentFunc
14682
+ };
14683
+ });
14684
+ return {
14685
+ base,
14686
+ current,
14687
+ metrics,
14688
+ countMetric: matchDiffedCountMetrics(base, current, metrics.length === 0),
14689
+ categoryToMetrics: matchDiffedMaps(base.categoryToMetrics, current.categoryToMetrics),
14690
+ functions
14691
+ };
14577
14692
  };
14693
+
14694
+ //#endregion
14695
+ //#region src/formats/aggregate.ts
14578
14696
  /**
14579
- * The converter for a format the caller specified. Its parses report a
14580
- * rejection as that format's, so the caller receives the reason and the format
14581
- * that rejected the input.
14697
+ * Aggregates each parsed input through its modality's uniform pipeline.
14582
14698
  *
14583
- * Auto-detection uses the registry's converters directly, because it names
14584
- * each rejecting format when it reports the rejections together.
14699
+ * The origin is detected once across all inputs.
14585
14700
  */
14586
- const specifiedFormatConverter = (format) => {
14587
- const converter = formatConverters[format];
14588
- if (converter.type === `json`) return {
14589
- ...converter,
14590
- parse: (json) => rejectAsFormat(converter, () => converter.parse(json))
14591
- };
14592
- return {
14593
- ...converter,
14594
- parse: (bytes) => rejectAsFormat(converter, () => converter.parse(bytes)),
14595
- parseAsync: async (stream) => {
14596
- try {
14597
- return await converter.parseAsync(stream);
14598
- } catch (error) {
14599
- throw asFormatRejection(converter, error);
14600
- }
14701
+ const aggregateParsedInputs = (parsed, options, context) => {
14702
+ const aggregators = parsed.map((input) => {
14703
+ switch (input.type) {
14704
+ case `call-stack-profile`: return new CallStackProfileAggregator(input);
14705
+ case `call-graph`: return new CallGraphAggregator(input);
14706
+ case `heap-snapshot`: return new HeapSnapshotAggregator(input);
14601
14707
  }
14708
+ });
14709
+ const detector = new OriginDetector(context);
14710
+ for (const aggregator of aggregators) aggregator.detectOrigin(detector);
14711
+ const resolvedContext = {
14712
+ format: context.format,
14713
+ origin: detector.resolve()
14602
14714
  };
14603
- };
14604
- const rejectAsFormat = (converter, parse) => {
14605
- try {
14606
- return parse();
14607
- } catch (error) {
14608
- throw asFormatRejection(converter, error);
14609
- }
14715
+ return aggregators.map((aggregator) => aggregator.aggregate(options, resolvedContext));
14610
14716
  };
14611
14717
  /**
14612
- * Prefixes a {@link FormatParseError} with the format's title. Any other error
14613
- * passes through, because it reports a bug instead of an unusable input.
14718
+ * Builds the conversion context, which contains the resolved format and the
14719
+ * explicit origin (or `null` when none was given).
14614
14720
  */
14615
- const asFormatRejection = (converter, error) => error instanceof FormatParseError ? new ProfilerMdError(`${converter.title}: ${error.message}`, { cause: error }) : error;
14616
- const detectFromJson = (json, options, origin, rejections) => {
14721
+ const makeContext = (format, origin) => ({
14722
+ format,
14723
+ origin: origin ?? null
14724
+ });
14725
+
14726
+ //#endregion
14727
+ //#region src/formats/detect.ts
14728
+ const detectJsonFormat = (json, rejections) => {
14617
14729
  for (const [format, converter] of jsonFormatConverters) {
14618
- const parsed = detectWithConverter(converter, () => converter.matches(json), () => converter.parse(json), rejections);
14619
- if (parsed) return aggregateParsedInputs(parsed, options, makeContext(format, origin));
14730
+ const parsed = detectWithConverter(converter, json, rejections);
14731
+ if (parsed) return {
14732
+ format,
14733
+ parsed
14734
+ };
14620
14735
  }
14621
14736
  };
14622
- const formatConverterEntries = formats.map((format) => [format, formatConverters[format]]);
14623
- const jsonFormatConverters = formatConverterEntries.filter((entry) => entry[1].type === `json`);
14624
- const detectFromBytes = (bytes, options, origin, rejections) => {
14737
+ const detectBinaryFormat = (bytes, rejections) => {
14625
14738
  for (const [format, converter] of binaryFormatConverters) {
14626
- const parsed = detectWithConverter(converter, () => converter.matches(bytes), () => converter.parse(bytes), rejections);
14627
- if (parsed) return aggregateParsedInputs(parsed, options, makeContext(format, origin));
14739
+ const parsed = detectWithConverter(converter, bytes, rejections);
14740
+ if (parsed) return {
14741
+ format,
14742
+ parsed
14743
+ };
14628
14744
  }
14629
14745
  };
14746
+ const formatConverterEntries = formats.map((format) => [format, formatConverters[format]]);
14747
+ const jsonFormatConverters = formatConverterEntries.filter((entry) => entry[1].type === `json`);
14748
+ const binaryFormatConverters = formatConverterEntries.filter((entry) => entry[1].type === `binary`);
14630
14749
  /**
14631
14750
  * Runs a converter's detection and parse, recording a rejection instead of
14632
14751
  * throwing when the converter recognized the input but failed to parse it.
@@ -14634,14 +14753,14 @@ const detectFromBytes = (bytes, options, origin, rejections) => {
14634
14753
  * A `matches` that throws counts as no match, because it is a cheap prefilter
14635
14754
  * that never validates the input.
14636
14755
  */
14637
- const detectWithConverter = (converter, matches, parse, rejections) => {
14756
+ const detectWithConverter = (converter, input, rejections) => {
14638
14757
  try {
14639
- if (!matches()) return;
14758
+ if (!converter.matches(input)) return;
14640
14759
  } catch {
14641
14760
  return;
14642
14761
  }
14643
14762
  try {
14644
- return parse();
14763
+ return classifyLazyParseFailures(converter, converter.parse(input));
14645
14764
  } catch (error) {
14646
14765
  rejections.push({
14647
14766
  converter,
@@ -14650,38 +14769,6 @@ const detectWithConverter = (converter, matches, parse, rejections) => {
14650
14769
  return;
14651
14770
  }
14652
14771
  };
14653
- const aggregateJsonInput = (converter, json, options, context) => aggregateParsedInputs(converter.parse(json), options, context);
14654
- const aggregateBinaryInputAsync = async (converter, stream, options, context) => aggregateParsedInputs(await converter.parseAsync(stream), options, context);
14655
- /**
14656
- * Aggregates each parsed input through its modality's uniform pipeline.
14657
- *
14658
- * The origin is detected once across all inputs.
14659
- */
14660
- const aggregateParsedInputs = (parsed, options, context) => {
14661
- const aggregators = parsed.map((input) => {
14662
- switch (input.type) {
14663
- case `call-stack-profile`: return new CallStackProfileAggregator(input);
14664
- case `call-graph`: return new CallGraphAggregator(input);
14665
- case `heap-snapshot`: return new HeapSnapshotAggregator(input);
14666
- }
14667
- });
14668
- const detector = new OriginDetector(context);
14669
- for (const aggregator of aggregators) aggregator.detectOrigin(detector);
14670
- const resolvedContext = {
14671
- format: context.format,
14672
- origin: detector.resolve()
14673
- };
14674
- return aggregators.map((aggregator) => aggregator.aggregate(options, resolvedContext));
14675
- };
14676
- /**
14677
- * Builds the conversion context, which carries the resolved format and the
14678
- * explicit origin (or `null` when none was given).
14679
- */
14680
- const makeContext = (format, origin) => ({
14681
- format,
14682
- origin: origin ?? null
14683
- });
14684
- const binaryFormatConverters = formatConverterEntries.filter((entry) => entry[1].type === `binary`);
14685
14772
  /**
14686
14773
  * Reports why auto-detection resolved no format.
14687
14774
  *
@@ -14689,17 +14776,16 @@ const binaryFormatConverters = formatConverterEntries.filter((entry) => entry[1]
14689
14776
  * is that format and failed to parse. Several rejections name each format with
14690
14777
  * its reason. No rejection means no format recognized the input.
14691
14778
  */
14692
- const undetectedFormatError = (rejections, jsonError) => {
14779
+ const toUndetectedFormatError = (rejections, jsonError) => {
14693
14780
  const [rejection] = rejections;
14694
- if (rejections.length === 1) return new FormatDetectError(describeRejection(rejection), [rejection.error], { cause: rejection.error });
14695
- if (rejections.length > 1) return new FormatDetectError(`could not detect the profile format, rejected by: ${rejections.map((rejected) => describeRejection(rejected)).join(`, `)}`, rejections.map(({ error }) => error));
14696
- if (jsonError !== void 0) return new FormatDetectError(`could not detect the profile format, the input reads as JSON but failed to parse: ${reasonOf$1(jsonError)}`, [jsonError], { cause: jsonError });
14781
+ if (rejections.length === 1) return new FormatDetectError(describeParseFailure(rejection.converter, rejection.error), [rejection.error], { cause: rejection.error });
14782
+ if (rejections.length > 1) return new FormatDetectError(`could not detect the profile format, rejected by: ${rejections.map(({ converter, error }) => describeParseFailure(converter, error)).join(`, `)}`, rejections.map(({ error }) => error));
14783
+ if (jsonError !== void 0) return new FormatDetectError(`could not detect the profile format, the input reads as JSON but is ${reasonOf(jsonError)}`, [jsonError], { cause: jsonError });
14697
14784
  return new FormatDetectError(`could not detect the profile format, expected one of: ${formats.join(`, `)}`, []);
14698
14785
  };
14699
- /** A rejection as `<title>: <reason>`. */
14700
- const describeRejection = ({ converter, error }) => `${converter.title}: ${reasonOf$1(error)}`;
14701
- /** An error's message on one line, for embedding in another message. */
14702
- const reasonOf$1 = (error) => (error instanceof Error ? error.message : String(error)).replaceAll(/\s+/gu, ` `).trim();
14786
+
14787
+ //#endregion
14788
+ //#region src/formats/format.ts
14703
14789
  const formatAggregatedInputs = (inputs, options) => {
14704
14790
  const formattingOptions = makeFormattingProfileToMdOptions(options, inputs);
14705
14791
  const contents = inputs.flatMap((input) => {
@@ -14776,11 +14862,55 @@ const collectInferableURLs = (inputs, options) => {
14776
14862
  return urls;
14777
14863
  };
14778
14864
 
14865
+ //#endregion
14866
+ //#region src/formats/index.ts
14867
+ /**
14868
+ * Asynchronously converts the given profile data to Markdown.
14869
+ *
14870
+ * See the [docs](https://github.com/TomerAberbach/profiler-md/blob/main/docs)
14871
+ * for supported formats and generation instructions.
14872
+ */
14873
+ const profileToMdAsync = async (input, options = {}) => {
14874
+ const normalizedOptions = normalizeProfileToMdOptions(options);
14875
+ return formatAggregatedInputs(await aggregateInputAsync(input, normalizedOptions), normalizedOptions);
14876
+ };
14877
+ /**
14878
+ * Asynchronously diffs the given base and current profile data, returning the
14879
+ * difference as Markdown.
14880
+ *
14881
+ * Each side accepts the same input as {@link profileToMdAsync}.
14882
+ *
14883
+ * See the [docs](https://github.com/TomerAberbach/profiler-md/blob/main/docs)
14884
+ * for supported formats and generation instructions.
14885
+ */
14886
+ const diffProfilesAsync = async (base, current, options = {}) => {
14887
+ const normalizedOptions = normalizeProfileToMdOptions(options);
14888
+ return formatAggregatedDiff(...await Promise.all([aggregateInputAsync(base, normalizedOptions), aggregateInputAsync(current, normalizedOptions)]), normalizedOptions);
14889
+ };
14890
+ const aggregateInputAsync = async (input, options) => {
14891
+ const { data, format, origin } = normalizeProfileInput(input);
14892
+ if (format) return aggregateParsedInputs(await parseAsFormatAsync(formatConverters[format], data), options, makeContext(format, origin));
14893
+ const buffered = data instanceof Blob ? data : await streamToUint8Array(data);
14894
+ let json;
14895
+ let jsonError;
14896
+ if (buffered instanceof Blob ? await maybeJsonAsync(buffered) : maybeJson(buffered)) try {
14897
+ json = buffered instanceof Blob ? await parseJsonAsync(buffered) : parseJson(buffered);
14898
+ } catch (error) {
14899
+ rethrowInputReadFailure(error);
14900
+ jsonError = (buffered instanceof Blob ? await startsJsonDocumentAsync(buffered) : startsJsonDocument(buffered)) ? error : void 0;
14901
+ }
14902
+ const rejections = [];
14903
+ const detected = (json === void 0 ? void 0 : detectJsonFormat(json, rejections)) ?? detectBinaryFormat(buffered instanceof Blob ? await buffered.bytes() : buffered, rejections);
14904
+ if (!detected) throw toUndetectedFormatError(rejections, jsonError);
14905
+ return aggregateParsedInputs(detected.parsed, options, makeContext(detected.format, origin));
14906
+ };
14907
+
14779
14908
  //#endregion
14780
14909
  //#region package.json
14781
14910
  var name = "profiler-md";
14782
- var version = "0.8.0";
14911
+ var version = "0.8.1";
14783
14912
  var description = "Converts performance profiles to human and LLM friendly Markdown.";
14913
+ var bugs = { "url": "https://github.com/TomerAberbach/profiler-md/issues" };
14784
14914
 
14785
14915
  //#endregion
14786
14916
  //#region src/cli/languages.ts
@@ -14936,7 +15066,7 @@ const parseRegex = (pattern, flags) => {
14936
15066
  } catch (error) {
14937
15067
  return {
14938
15068
  success: false,
14939
- error: message`expected a valid regex, got: ${value(pattern)} (${text(error instanceof Error ? error.message : String(error))})`
15069
+ error: message`expected a valid regex, got: ${value(pattern)} (${text(reasonOf(error))})`
14940
15070
  };
14941
15071
  }
14942
15072
  };
@@ -15000,7 +15130,10 @@ const parser = object({
15000
15130
  format: map(optional(option(`-f`, `--format`, choice([AUTO, ...formats], { metavar: `FORMAT` }), { description: message`Input profile format (default: auto)` })), specified),
15001
15131
  origin: map(optional(option(`-r`, `--origin`, choice([AUTO, ...origins], { metavar: `ORIGIN` }), { description: message`Input profile origin (default: auto)` })), specified),
15002
15132
  output: withDefault(option(`-o`, `--output`, path({ metavar: `FILE` }), { description: message`Output file (default: - for stdout)` }), `-`),
15003
- topN: optional(option(`--top-n`, integer({ metavar: `N` }), { description: message`Entries to show per ranking, including category subsections (default: 20)` })),
15133
+ topN: optional(option(`--top-n`, integer({
15134
+ metavar: `N`,
15135
+ min: 0
15136
+ }), { description: message`Entries to show per ranking, including category subsections (default: 20)` })),
15004
15137
  minCategoryShare: optional(option(`--min-category-share`, float({
15005
15138
  metavar: `FRACTION`,
15006
15139
  min: 0,
@@ -15039,18 +15172,18 @@ const getHelpText = () => {
15039
15172
  return `${[
15040
15173
  formatDocPage(program.metadata.name, docPage, {
15041
15174
  termWidth,
15042
- maxWidth: process.stdout.columns ?? 80
15175
+ maxWidth: getMaxWidth()
15043
15176
  }),
15044
15177
  `Formats: ${formats.join(`, `)}`,
15045
15178
  `Origins: ${origins.join(`, `)}`,
15046
- `Function categories (--category, --hide-category, --show-category): ${FUNCTION_CATEGORIES.join(`, `)}`,
15047
- `Heap snapshot categories (--hide-category, --show-category): ${HEAP_SNAPSHOT_NODE_CATEGORIES.join(`, `)}`,
15179
+ `Function categories: ${FUNCTION_CATEGORIES.join(`, `)}`,
15180
+ `Heap snapshot categories: ${HEAP_SNAPSHOT_NODE_CATEGORIES.join(`, `)}`,
15048
15181
  `Languages: ${[...languages.entries()].map(([id, { aliases }]) => [id, ...aliases?.map((alias) => alias.id) ?? []].join(`/`)).join(`, `)}`
15049
15182
  ].join(`\n`)}\n`;
15050
15183
  };
15051
15184
  const parseArgs = () => runParser(parser, program.metadata.name, process.argv.slice(2), {
15052
15185
  colors: false,
15053
- maxWidth: process.stdout.columns ?? 80,
15186
+ maxWidth: getMaxWidth(),
15054
15187
  version: {
15055
15188
  value: version,
15056
15189
  option: true,
@@ -15065,6 +15198,8 @@ const parseArgs = () => runParser(parser, program.metadata.name, process.argv.sl
15065
15198
  },
15066
15199
  onError: () => process.exit(2)
15067
15200
  });
15201
+ const getMaxWidth = () => Math.max(MIN_WIDTH, process.stdout.columns || Number(process.env.COLUMNS) || 80);
15202
+ const MIN_WIDTH = 40;
15068
15203
 
15069
15204
  //#endregion
15070
15205
  //#region src/cli/error.ts
@@ -15079,16 +15214,24 @@ var CliError = class extends ProfilerMdError {
15079
15214
  const reportError = (error) => {
15080
15215
  if (error instanceof ProfilerMdError) {
15081
15216
  process.stderr.write(`error: ${error.message}\n`);
15217
+ const parseFailures = unclassifiedParseFailures(error);
15218
+ if (parseFailures.length > 0) process.stderr.write(bugReport(`If the input opens in its profiler, report this as a bug in ${name}:`, parseFailures));
15082
15219
  process.exit(error instanceof CliError ? error.exitCode : 1);
15083
15220
  }
15084
- if (error instanceof Error) {
15085
- process.stderr.write(error.stack ? `${error.stack}\n` : `error: ${error.message}\n`);
15086
- process.exit(1);
15087
- }
15088
- process.stderr.write(`error: ${String(error)}\n`);
15221
+ process.stderr.write(`error: ${reasonOf(error)}\n`);
15222
+ process.stderr.write(bugReport(`This is a bug in ${name}. Report it:`, [error]));
15089
15223
  process.exit(1);
15090
15224
  };
15091
- const reasonOf = (error) => error instanceof Error ? error.message : String(error);
15225
+ /** The bug report request that follows an error line, with the given traces. */
15226
+ const bugReport = (request, errors) => [
15227
+ request,
15228
+ `${bugs.url}/new`,
15229
+ `Include the command you ran, the input if you can share it, and this trace:`,
15230
+ ...errors.map(stackOf),
15231
+ ``
15232
+ ].join(`\n`);
15233
+ /** An error's stack trace, or its description when it has none. */
15234
+ const stackOf = (error) => error instanceof Error ? error.stack ?? `${error.name}: ${error.message}` : `error: ${String(error)}`;
15092
15235
 
15093
15236
  //#endregion
15094
15237
  //#region src/cli/ansis.ts
@@ -15108,22 +15251,50 @@ const makeAnsis = ({ isTTY }) => {
15108
15251
 
15109
15252
  //#endregion
15110
15253
  //#region src/cli/pager.ts
15111
- const openPager = async () => {
15254
+ /**
15255
+ * Opens the user's pager, or `less`, for stdout output. Returns `null` when an
15256
+ * empty `PAGER` opts out of paging or no pager spawns.
15257
+ *
15258
+ * A pager that fails before it shows anything would lose the output, so the
15259
+ * returned output writes to `fallback` when the pager exits with a non-zero
15260
+ * status.
15261
+ */
15262
+ const openPager = async (fallback) => {
15112
15263
  const raw = process.env.PAGER;
15113
15264
  if (raw?.trim() === ``) return null;
15114
15265
  const env = {
15115
- LESS: `FRSX -#6`,
15266
+ LESS: `FIRSX -#6`,
15116
15267
  ...process.env
15117
15268
  };
15118
15269
  const child = (raw === void 0 ? null : await trySpawn(raw, env)) ?? await trySpawn(`less`, env);
15119
15270
  if (!child) return null;
15120
15271
  return { write: async (text) => {
15121
- await new Promise((resolve) => {
15122
- child.stdin.write(text, () => child.stdin.end(resolve));
15123
- });
15124
- await waitForExit(child);
15272
+ const exitCode = await page(child, text);
15273
+ if (exitCode !== 0 && exitCode !== null) {
15274
+ process.stderr.write(`warning: pager exited with status ${exitCode}\n`);
15275
+ await fallback.write(text);
15276
+ }
15125
15277
  } };
15126
15278
  };
15279
+ /**
15280
+ * Writes the text to the pager and resolves to its exit status once it quits,
15281
+ * or `null` when a signal killed it.
15282
+ *
15283
+ * A terminal's Ctrl-C signals this process and the pager together. The pager
15284
+ * handles its own interrupt and keeps running, so exiting here would orphan
15285
+ * it on the terminal. This process ignores SIGINT while the pager runs, as
15286
+ * git does, so quitting the pager ends the run instead.
15287
+ */
15288
+ const page = async (child, text) => {
15289
+ process.on(`SIGINT`, ignoreSignal);
15290
+ try {
15291
+ const [exitCode] = await Promise.all([waitForExit(child), writeStdin(child, text)]);
15292
+ return exitCode;
15293
+ } finally {
15294
+ process.off(`SIGINT`, ignoreSignal);
15295
+ }
15296
+ };
15297
+ const ignoreSignal = () => {};
15127
15298
  const trySpawn = (command, env) => {
15128
15299
  const [bin, ...args] = command.trim().split(/\s+/u);
15129
15300
  if (!bin) return Promise.resolve(null);
@@ -15136,26 +15307,54 @@ const trySpawn = (command, env) => {
15136
15307
  env
15137
15308
  });
15138
15309
  return new Promise((resolve) => {
15139
- child.once(`spawn`, () => {
15140
- child.stdin.on(`error`, (error) => {
15141
- if (error.code !== `EPIPE`) throw error;
15142
- });
15143
- resolve(child);
15144
- });
15310
+ child.once(`spawn`, () => resolve(child));
15145
15311
  child.once(`error`, () => resolve(null));
15146
15312
  });
15147
15313
  };
15314
+ const writeStdin = (child, text) => new Promise((resolve, reject) => {
15315
+ const finish = (error) => {
15316
+ if (!error || error.code === `EPIPE` || error.code === `ECANCELED`) resolve();
15317
+ else reject(error);
15318
+ };
15319
+ child.stdin.on(`error`, finish);
15320
+ child.stdin.write(text, (error) => error ? finish(error) : child.stdin.end(finish));
15321
+ });
15322
+ /** Resolves to the pager's exit status, or `null` when a signal killed it. */
15148
15323
  const waitForExit = (child) => new Promise((resolve, reject) => {
15149
- child.once(`exit`, () => resolve());
15324
+ child.once(`exit`, (code) => resolve(code));
15150
15325
  child.once(`error`, reject);
15151
15326
  });
15152
15327
 
15153
15328
  //#endregion
15154
15329
  //#region src/cli/output.ts
15155
15330
  const writeOutput = async (text, outputPath, { pager }) => {
15156
- await ((pager && isTTYOutput(outputPath) ? await openPager() : null) ?? await openOutput(outputPath)).write(text);
15331
+ const output = await openOutput(outputPath);
15332
+ await ((pager && isTTYOutput(outputPath) ? await openPager(output) : null) ?? output).write(text);
15157
15333
  };
15158
15334
  const isTTYOutput = (outputPath) => outputPath === `-` && Boolean(process.stdout.isTTY);
15335
+ /**
15336
+ * Rejects an output path that cannot be written.
15337
+ *
15338
+ * A path must be a writable file, or absent from a writable directory. The
15339
+ * check creates no file.
15340
+ */
15341
+ const checkOutputPath = async (outputPath) => {
15342
+ if (outputPath === `-`) return;
15343
+ let isDirectory;
15344
+ try {
15345
+ isDirectory = (await stat(outputPath)).isDirectory();
15346
+ await access(outputPath, constants.W_OK);
15347
+ } catch (error) {
15348
+ if (errorCodeOf(error) !== `ENOENT`) throw writeError(outputPath, error);
15349
+ try {
15350
+ await access(dirname(outputPath), constants.W_OK);
15351
+ } catch (directoryError) {
15352
+ throw writeError(outputPath, directoryError);
15353
+ }
15354
+ return;
15355
+ }
15356
+ if (isDirectory) throw new CliError(`cannot write ${outputPath}: is a directory`, 1);
15357
+ };
15159
15358
  const openOutput = async (outputPath) => {
15160
15359
  if (outputPath === `-`) return { write: (text) => new Promise((resolve, reject) => {
15161
15360
  const finish = (error) => {
@@ -15177,6 +15376,7 @@ const writeError = (outputPath, error) => new CliError(`cannot write ${outputPat
15177
15376
  const errorCodeOf = (error) => error instanceof Error && `code` in error && typeof error.code === `string` ? error.code : void 0;
15178
15377
  const WRITE_ERROR_REASONS = /* @__PURE__ */ new Map([
15179
15378
  [`ENOENT`, `no such directory`],
15379
+ [`ENOTDIR`, `no such directory`],
15180
15380
  [`EISDIR`, `is a directory`],
15181
15381
  [`EACCES`, `permission denied`],
15182
15382
  [`EPERM`, `permission denied`]
@@ -15953,6 +16153,7 @@ try {
15953
16153
  const [basePath, currentPath] = typeof input === `string` || input === void 0 ? [input, void 0] : input;
15954
16154
  if (help !== void 0) await printHelpTopic(typeof help === `string` ? help : void 0, { pager });
15955
16155
  if (basePath === void 0 && process.stdin.isTTY) await printHelpTopic(void 0, { pager });
16156
+ await checkOutputPath(outputPath);
15956
16157
  const toInput = (data) => format || origin ? {
15957
16158
  data,
15958
16159
  format,