profiler-md 0.9.0 → 0.9.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.
@@ -37,7 +37,7 @@ import convertSourceMap from "convert-source-map";
37
37
  * a failure is a bug in this package. The exception is a parser failing on an
38
38
  * error it did not classify, which is either an input violating the format in
39
39
  * a way the parser does not check or a parser bug. That failure throws a
40
- * `ProfilerMdError` too, and `mayBeParserBug` identifies it.
40
+ * `ProfilerMdError` too, and `unclassifiedParseFailures` identifies it.
41
41
  */
42
42
  var ProfilerMdError = class extends Error {
43
43
  constructor(message, options) {
@@ -356,6 +356,11 @@ const sourceReferenceToSourceLocation = (sourceReference, { line, column } = {})
356
356
  column
357
357
  });
358
358
  /**
359
+ * Rewrites {@link location}'s source reference with {@link normalize}, keeping
360
+ * its position.
361
+ */
362
+ const normalizeSourceLocation = (location, normalize) => sourceReferenceToSourceLocation(normalize(location), location);
363
+ /**
359
364
  * Whether a base URL can be inferred from {@link location}: an absolute
360
365
  * location with a hierarchical path. Excludes opaque-path URLs like `node:fs`,
361
366
  * whose pathname is not rooted and so names no directory.
@@ -1230,7 +1235,7 @@ const getBuiltinNames = () => {
1230
1235
  const names = /* @__PURE__ */ new Set();
1231
1236
  const addMethodNames = (object) => {
1232
1237
  if (!object) return;
1233
- for (const key of Object.getOwnPropertyNames(object)) if (typeof Object.getOwnPropertyDescriptor(object, key)?.value === `function`) names.add(key);
1238
+ for (const key of Reflect.ownKeys(object)) if (typeof Object.getOwnPropertyDescriptor(object, key)?.value === `function`) names.add(typeof key === `symbol` ? `[${key.description}]` : key);
1234
1239
  };
1235
1240
  for (const name of Object.keys(globals.builtin)) {
1236
1241
  const value = globalThis[name];
@@ -1349,6 +1354,13 @@ const JQUERY_EXPANDO = /^jQuery\d+$/u;
1349
1354
 
1350
1355
  // src/origins/jsc.ts
1351
1356
  /**
1357
+ * Categorizes a regular expression JavaScriptCore names by its literal,
1358
+ * `/source/flags`, with no location, as `regexp`. A function the program defines
1359
+ * has a location.
1360
+ */
1361
+ const jscRegExpCategory = ({ name, location }) => !location && name && REGEXP_LITERAL.test(name) ? `regexp` : void 0;
1362
+ const REGEXP_LITERAL = /^\/.+\/[dgimsuvy]*$/su;
1363
+ /**
1352
1364
  * The heap snapshot category of a constructor named {@link name} when
1353
1365
  * JavaScriptCore allocated it: an executable or code block the engine compiled
1354
1366
  * to, a scope it allocated on the heap, or one of the objects it implements
@@ -1417,7 +1429,7 @@ const bunOriginSpec = {
1417
1429
  `v8-heap-snapshot`
1418
1430
  ],
1419
1431
  isMarkerEntry: ({ name, location }) => location === void 0 && name !== void 0 && (JSC_MODULE_LOADER_BUILTINS.has(name) || BUN_RUNTIME_CLASSES.has(name)),
1420
- categorizeEntry: (entry) => javaScriptCategory(entry) ?? protocolCategory(entry, `stdlib`, BUN_STDLIB_PROTOCOLS) ?? `ours`,
1432
+ categorizeEntry: (entry) => jscRegExpCategory(entry) ?? javaScriptCategory(entry) ?? protocolCategory(entry, `stdlib`, BUN_STDLIB_PROTOCOLS) ?? `ours`,
1421
1433
  categorizeHeapSnapshotConstructor: (name) => jscConstructorCategory(name) ?? javaScriptConstructorCategory(name),
1422
1434
  matchHeapSnapshotEdgeName: javaScriptMatchHeapSnapshotEdgeName
1423
1435
  };
@@ -1508,6 +1520,11 @@ const warnUnmatchedMetrics = (side, metrics, logger) => {
1508
1520
  if (metrics.length > 0) logger.warn?.(`diff omits metrics only the ${side} side measures, got: ${formatConjunction(metrics.map((metric) => metric.phrases.pastParticipleVerbPhrase))}`);
1509
1521
  };
1510
1522
  /**
1523
+ * The metric both sides of a diff share, or `null` when either side lacks one
1524
+ * or the two differ.
1525
+ */
1526
+ const matchDiffedMetric = (base, current) => base && current && metricsEqual(base, current) ? base : null;
1527
+ /**
1511
1528
  * Returns whether two metrics measure the same thing in the same unit, and rank
1512
1529
  * a change in it the same way.
1513
1530
  *
@@ -1634,6 +1651,16 @@ const ALLOCATED_HEAP_METRIC = metricWithPhrases(BYTES_METRIC, {
1634
1651
  pastTenseVerb: `allocated`,
1635
1652
  pastParticipleVerbPhrase: `bytes allocated`
1636
1653
  });
1654
+ /**
1655
+ * Bytes a sampling heap profiler reports, which it may limit to the objects
1656
+ * still alive, by options the profile does not record.
1657
+ */
1658
+ const SAMPLED_HEAP_METRIC = metricWithPhrases(BYTES_METRIC, {
1659
+ titleNoun: `heap`,
1660
+ columnNoun: `size`,
1661
+ pastTenseVerb: `recorded`,
1662
+ pastParticipleVerbPhrase: `bytes recorded`
1663
+ });
1637
1664
  /** Bytes allocated and still retained when the profile was captured. */
1638
1665
  const RETAINED_HEAP_METRIC = metricWithPhrases(BYTES_METRIC, {
1639
1666
  titleNoun: `retained heap`,
@@ -1799,7 +1826,11 @@ const NAME_PHRASES = /* @__PURE__ */ new Map([[`time`, new Map([
1799
1826
  [`block_time`, LOCK_CONTENTION_TIME_METRIC.phrases],
1800
1827
  [`delay`, CONTENTION_TIME_METRIC.phrases],
1801
1828
  [`wall`, WALL_TIME_METRIC.phrases]
1802
- ])], [`size`, /* @__PURE__ */ new Map([[`alloc_space`, ALLOCATED_HEAP_METRIC.phrases], [`inuse_space`, RETAINED_HEAP_METRIC.phrases]])]]);
1829
+ ])], [`size`, /* @__PURE__ */ new Map([
1830
+ [`alloc_space`, ALLOCATED_HEAP_METRIC.phrases],
1831
+ [`inuse_space`, RETAINED_HEAP_METRIC.phrases],
1832
+ [`space`, SAMPLED_HEAP_METRIC.phrases]
1833
+ ])]]);
1803
1834
 
1804
1835
  // src/modalities/trace/gc.ts
1805
1836
  /**
@@ -1810,7 +1841,7 @@ const NAME_PHRASES = /* @__PURE__ */ new Map([[`time`, new Map([
1810
1841
  * The span records a `cause` attribute and the bytes it `reclaimed`. The heap's
1811
1842
  * level before and after it are gauge readings, at the span's start and end.
1812
1843
  */
1813
- const gcEvents = ({ span, pause, cause, heapUsedBefore, heapUsedAfter }) => {
1844
+ const gcEvents = ({ span, cause, heapUsedBefore, heapUsedAfter }) => {
1814
1845
  const attributes = [...span.attributes ?? []];
1815
1846
  if (cause !== void 0) attributes.push({
1816
1847
  key: `cause`,
@@ -1844,7 +1875,7 @@ const gcEvents = ({ span, pause, cause, heapUsedBefore, heapUsedAfter }) => {
1844
1875
  return {
1845
1876
  event: {
1846
1877
  ...span,
1847
- category: pause ? `garbage-collection-pause` : `garbage-collection`,
1878
+ category: `garbage-collection-pause`,
1848
1879
  attributes
1849
1880
  },
1850
1881
  readings
@@ -1859,8 +1890,8 @@ const gcEvents = ({ span, pause, cause, heapUsedBefore, heapUsedAfter }) => {
1859
1890
  * V8 names a collector scope that runs on a helper thread `BACKGROUND`. Every
1860
1891
  * other scope of a collection runs on the thread it stopped.
1861
1892
  */
1862
- const v8TraceEventCategory = ({ name, declaredCategories }) => {
1863
- if (declaredCategories?.includes(V8_GC_CATEGORY)) return name.startsWith(V8_GC_SCOPE_PREFIX) && !name.includes(`BACKGROUND`) ? `garbage-collection-pause` : `garbage-collection`;
1893
+ const v8TraceEventCategory = ({ type, name, declaredCategories }) => {
1894
+ if (declaredCategories?.includes(V8_GC_CATEGORY)) return type === `span` && name.startsWith(V8_GC_SCOPE_PREFIX) && !name.includes(`BACKGROUND`) ? `garbage-collection-pause` : `garbage-collection`;
1864
1895
  if (V8_GC_PAUSES.has(name)) return `garbage-collection-pause`;
1865
1896
  if (name === `V8.DeoptimizeCode`) return `compilation`;
1866
1897
  return declaredCategories?.includes(`v8.execute`) ? `script` : void 0;
@@ -1897,7 +1928,6 @@ const normalizeV8TraceEvent = (event) => {
1897
1928
  ...event,
1898
1929
  arguments: rest
1899
1930
  },
1900
- pause: true,
1901
1931
  cause: typeof type === `string` ? type : void 0,
1902
1932
  heapUsedBefore: typeof usedHeapSizeBefore === `number` ? usedHeapSizeBefore : void 0,
1903
1933
  heapUsedAfter: typeof usedHeapSizeAfter === `number` ? usedHeapSizeAfter : void 0
@@ -1929,9 +1959,18 @@ const chromeOriginSpec = {
1929
1959
  categorizeEntry: (entry) => v8JavaScriptCategory(entry) ?? protocolCategory(entry, `third-party`, [EXTENSION_PROTOCOL]) ?? `ours`,
1930
1960
  categorizeHeapSnapshotConstructor: javaScriptConstructorCategory,
1931
1961
  matchHeapSnapshotEdgeName: javaScriptMatchHeapSnapshotEdgeName,
1962
+ normalizeSourceReference: (reference) => reference.type === `relative` && V8_EXTENSION_SCRIPT.test(reference.path) ? {
1963
+ type: `logical`,
1964
+ name: reference.path
1965
+ } : reference,
1932
1966
  categorizeTraceEvent: v8TraceEventCategory,
1933
1967
  normalizeTraceEvent: normalizeV8TraceEvent
1934
1968
  };
1969
+ /**
1970
+ * The name of a V8 extension's script, which Chrome compiles into itself
1971
+ * (`v8/LoadTimes`, defining `chrome.loadTimes`), so it names no file.
1972
+ */
1973
+ const V8_EXTENSION_SCRIPT = /^v8\/[A-Za-z]+$/u;
1935
1974
  /** The protocol a browser extension's injected scripts load from. */
1936
1975
  const EXTENSION_PROTOCOL = `chrome-extension:`;
1937
1976
  /**
@@ -2143,6 +2182,7 @@ const eflambeOriginSpec = {
2143
2182
  normalizeStackFrame: (input) => {
2144
2183
  if (input.definition) return input;
2145
2184
  const name = input.name ?? ``;
2185
+ if (BEAM_PROCESS_ID.test(name)) return null;
2146
2186
  const colon = name.indexOf(`:`);
2147
2187
  if (colon <= 0) return input;
2148
2188
  let module = name.slice(0, colon);
@@ -2259,6 +2299,7 @@ const excimerOriginSpec = {
2259
2299
  id: `excimer`,
2260
2300
  title: `Excimer`,
2261
2301
  formats: [`collapsed`, `speedscope`],
2302
+ countMetric: (format) => format === `speedscope` ? null : void 0,
2262
2303
  isMarkerEntry: ({ name }) => name !== void 0 && (CLOSURE_FRAME.test(name) || FILE_SCOPE_FRAME.test(name) || name === TRUNCATION_FRAME),
2263
2304
  isOriginHint: (hint) => hint === `Excimer`,
2264
2305
  categorizeEntry: (entry) => vendorCategory(entry) ?? oursIfLocatedCategory(entry),
@@ -2275,11 +2316,17 @@ const excimerOriginSpec = {
2275
2316
  position: { line: Number(line) }
2276
2317
  } };
2277
2318
  }
2278
- if (definition) return input;
2279
- if (name.includes(`/`)) return { definition: {
2280
- type: `file`,
2281
- urlOrPath: name
2282
- } };
2319
+ if (definition) return definition.type === `file` && definition.urlOrPath === name ? {
2320
+ ...input,
2321
+ name: FILE_SCOPE_NAME
2322
+ } : input;
2323
+ if (name.includes(`/`)) return {
2324
+ name: FILE_SCOPE_NAME,
2325
+ definition: {
2326
+ type: `file`,
2327
+ urlOrPath: name
2328
+ }
2329
+ };
2283
2330
  const classSeparator = name.lastIndexOf(`::`);
2284
2331
  if (classSeparator !== -1) return {
2285
2332
  name: name.slice(classSeparator + 2),
@@ -2299,6 +2346,8 @@ const excimerOriginSpec = {
2299
2346
  };
2300
2347
  }
2301
2348
  };
2349
+ /** The name of a frame running a file's top-level code, which has no function. */
2350
+ const FILE_SCOPE_NAME = `(file scope)`;
2302
2351
  /**
2303
2352
  * An anonymous function, which Excimer names by its file and the line its
2304
2353
  * definition starts on: `{closure:/srv/app/Hooks.php(42)}`.
@@ -2426,8 +2475,15 @@ const goOriginSpec = {
2426
2475
  formats: [`pprof`],
2427
2476
  isMarkerEntry: (entry) => (entry.name?.startsWith(`runtime.`) ?? false) && isStdlibLocated(entry.location),
2428
2477
  matchEntry: matchEntryFromRules({ location: GO_LOCATION_MATCH_RULES }),
2429
- categorizeEntry: (entry) => goCollectorCategory(entry) ?? goDependencyCategory(entry) ?? locationlessCategory(entry) ?? goPackageCategory(entry)
2478
+ categorizeEntry: (entry) => lostStackCategory(entry) ?? goCollectorCategory(entry) ?? goDependencyCategory(entry) ?? locationlessCategory(entry) ?? goPackageCategory(entry),
2479
+ normalizeStackFrame: (input) => input.name === ZERO_PC_PLACEHOLDER ? null : input
2430
2480
  };
2481
+ const ZERO_PC_PLACEHOLDER = `0xffffffffffffffff`;
2482
+ /**
2483
+ * Categorizes the runtime's stand-ins for a stack it did not record, such as
2484
+ * `runtime._LostContendedRuntimeLock`, as `unknown`.
2485
+ */
2486
+ const lostStackCategory = ({ name, location }) => name?.startsWith(`runtime._Lost`) && isStdlibLocated(location) ? `unknown` : void 0;
2431
2487
  /**
2432
2488
  * Categorizes Go's collector as `garbage-collector`: the background mark
2433
2489
  * workers and their drain loops, the sweeper, and the assist path a goroutine
@@ -2695,6 +2751,7 @@ const COMPILER_ASSIGNED_ID_REGEX = /(?<kept>__(?:anon|struct|union|enum|opaque))
2695
2751
  const ZIG_NAME_MATCH_RULES = [[COMPILER_ASSIGNED_ID_REGEX, `$<kept>`]];
2696
2752
 
2697
2753
  // src/origins/native.ts
2754
+ const NATIVE_LOCATION_MATCH_RULES = [...RUST_LOCATION_MATCH_RULES, ...GO_LOCATION_MATCH_RULES];
2698
2755
  /**
2699
2756
  * Matches a native profiler's entry across profiles by each compiled language's
2700
2757
  * match rules. Each rule matches only a name or path that language's toolchain
@@ -2702,7 +2759,7 @@ const ZIG_NAME_MATCH_RULES = [[COMPILER_ASSIGNED_ID_REGEX, `$<kept>`]];
2702
2759
  */
2703
2760
  const nativeMatchEntry = matchEntryFromRules({
2704
2761
  name: ZIG_NAME_MATCH_RULES,
2705
- location: [...RUST_LOCATION_MATCH_RULES, ...GO_LOCATION_MATCH_RULES]
2762
+ location: NATIVE_LOCATION_MATCH_RULES
2706
2763
  });
2707
2764
  /**
2708
2765
  * Normalizes a native profiler's frame by each compiled language's conventions.
@@ -2926,7 +2983,7 @@ const nodePprofOriginSpec = {
2926
2983
  ...input.definition,
2927
2984
  position: {
2928
2985
  line: input.definition.position?.line ?? Number(line),
2929
- column: input.definition.position?.column ?? Number(column)
2986
+ column: input.definition.position?.column ?? (column === void 0 ? void 0 : Number(column))
2930
2987
  }
2931
2988
  } } : {}
2932
2989
  };
@@ -2934,7 +2991,7 @@ const nodePprofOriginSpec = {
2934
2991
  };
2935
2992
  const garbageCollectionCategory = ({ name }) => name === `Garbage Collection` ? `garbage-collector` : void 0;
2936
2993
  /** `dd-trace` packed anonymous frame name, e.g. `(anonymous:L#122135:C#9)`. */
2937
- const PACKED_ANONYMOUS = /^\(anonymous:L#(?<line>\d+):C#(?<column>\d+)\)$/u;
2994
+ const PACKED_ANONYMOUS = /^\(anonymous:L#(?<line>\d+)(?::C#(?<column>\d+))?\)$/u;
2938
2995
 
2939
2996
  // src/origins/specs/node.ts
2940
2997
  const nodeOriginSpec = {
@@ -3069,11 +3126,14 @@ const JULIA_LOCATION_MATCH_RULES = [[/(?<prefix>\/packages\/[^/]+\/)[0-9A-Za-z]{
3069
3126
  const pprofJlOriginSpec = {
3070
3127
  id: `pprof-jl`,
3071
3128
  formats: [`pprof`],
3129
+ countMetric: () => SAMPLES,
3072
3130
  isMarkerEntry: (entry) => juliaInstallCategory(entry) !== void 0,
3073
3131
  categorizeEntry: (entry) => juliaInstallCategory(entry) ?? juliaDepotPackageCategory(entry) ?? juliaRuntimeNativeCategory(entry) ?? juliaFilelessCodeCategory(entry) ?? locationlessCategory(entry) ?? `ours`,
3074
3132
  matchEntry: matchEntryFromRules({ location: JULIA_LOCATION_MATCH_RULES }),
3075
- normalizeStackFrame: (input) => input.name?.startsWith(`Alloc: `) === true ? null : dropPlaceholderPath$2(input)
3133
+ normalizeStackFrame: (input) => input.name?.startsWith(`Alloc: `) === true || input.name === ALLOCATION_RECORDING_HOOK ? null : dropPlaceholderPath$2(input)
3076
3134
  };
3135
+ /** The function in Julia's runtime that records a sampled allocation. */
3136
+ const ALLOCATION_RECORDING_HOOK = `maybe_record_alloc_to_profile`;
3077
3137
  /**
3078
3138
  * Categorizes frames from the Julia install's `share/julia/` tree (`Base`,
3079
3139
  * the standard library, and the compiler) as `stdlib`.
@@ -3285,6 +3345,7 @@ const pySpyOriginSpec = {
3285
3345
  isMarkerEntry: (entry) => FRAME.test(entry.name ?? ``) || pythonStdlibCategory(entry) !== void 0,
3286
3346
  isOriginHint: (hint) => hint.startsWith(`py-spy@`),
3287
3347
  categorizeEntry: categorizeCPythonEntry,
3348
+ matchEntry: matchEntryFromRules({ name: [[/^0x[0-9a-f]+$/u, `(unsymbolized)`]] }),
3288
3349
  normalizeStackFrame: (input, format) => dropPlaceholderLine(dropPlaceholderPath$1(normalizePackedStackFrame$1(normalizeSpeedscopeExecutingLine(input, format))))
3289
3350
  };
3290
3351
  /**
@@ -3358,6 +3419,10 @@ const RUBY_LOCATION_MATCH_RULES = [[/(?<prefix>\/gems\/[A-Za-z][\w.-]*?)-\d[^/]*
3358
3419
  * methods. Its `normalizeStackFrame` splits the name at the last ` - ` and reads
3359
3420
  * the `file:line` from the text after it, so a colon in the method name (e.g.
3360
3421
  * `<module:Foo>`) stays in the name.
3422
+ *
3423
+ * On Ruby 2.6 and later, rbspy records the last entry of a method's line table
3424
+ * for each of the method's frames, whichever line the frame was executing.
3425
+ * https://github.com/rbspy/rbspy/issues/409
3361
3426
  */
3362
3427
  const rbspyOriginSpec = {
3363
3428
  id: `rbspy`,
@@ -3368,6 +3433,7 @@ const rbspyOriginSpec = {
3368
3433
  `speedscope`
3369
3434
  ],
3370
3435
  isMarkerEntry: (entry) => isRbspyStackFrame(entry.name),
3436
+ countMetric: (format) => format === `callgrind` ? null : void 0,
3371
3437
  isOriginHint: (hint, format) => format === `speedscope` && hint.startsWith(`rbspy@`),
3372
3438
  matchEntry: matchEntryFromRules({
3373
3439
  name: RUBY_NAME_MATCH_RULES,
@@ -3481,7 +3547,10 @@ const systingOriginSpec = {
3481
3547
  formats: [`systing`],
3482
3548
  isMarkerEntry: (entry) => NATIVE_FRAME.test(entry.name ?? ``),
3483
3549
  categorizeEntry: (entry) => labelModuleCategory(entry) ?? pythonThirdPartyCategory(entry) ?? pythonStdlibCategory(entry) ?? zigStdlibCategory(entry) ?? systemDirectoryCategory(entry) ?? locationlessCategory(entry) ?? `ours`,
3484
- matchEntry: nativeMatchEntry,
3550
+ matchEntry: matchEntryFromRules({
3551
+ name: [...ZIG_NAME_MATCH_RULES, [/^0x[0-9a-f]+ (?<module>\([^()]*\))$/u, `unknown $<module>`]],
3552
+ location: NATIVE_LOCATION_MATCH_RULES
3553
+ }),
3485
3554
  normalizeStackFrame: (input) => nativeNormalizeStackFrame(unpackStackFrame(input))
3486
3555
  };
3487
3556
  /**
@@ -3504,7 +3573,7 @@ const unpackStackFrame = (input) => {
3504
3573
  if (input.definition) return input;
3505
3574
  const native = NATIVE_FRAME.exec(input.name ?? ``);
3506
3575
  if (native) {
3507
- const { func, inner } = native.groups;
3576
+ const { func, inner, address } = native.groups;
3508
3577
  const location = MODULE_LOCATION_LINE.exec(inner) ?? MODULE_LOCATION.exec(inner);
3509
3578
  if (location) {
3510
3579
  const { module, file, line } = location.groups;
@@ -3517,7 +3586,7 @@ const unpackStackFrame = (input) => {
3517
3586
  ...line === void 0 ? {} : { executing: { line: Number(line) } }
3518
3587
  };
3519
3588
  }
3520
- return { name: `${func} (${inner})` };
3589
+ return { name: `${func === UNSYMBOLIZED_NAME && !LABEL.test(inner) ? address : func} (${inner})` };
3521
3590
  }
3522
3591
  return unpackPythonFrame(input);
3523
3592
  };
@@ -3536,7 +3605,9 @@ const unpackStackFrame = (input) => {
3536
3605
  * data is untrusted input. No other supported profiler suffixes every frame
3537
3606
  * with `<0x…>`, so the trailing address marks a systing frame.
3538
3607
  */
3539
- const NATIVE_FRAME = /^(?<func>.+) \((?<inner>[^()]*[^()\s])\) <0x[0-9a-f]+>$/u;
3608
+ const NATIVE_FRAME = /^(?<func>.+) \((?<inner>[^()]*[^()\s])\) <(?<address>0x[0-9a-f]+)>$/u;
3609
+ /** What systing names a frame it could not symbolize. */
3610
+ const UNSYMBOLIZED_NAME = `unknown`;
3540
3611
  const MODULE_LOCATION_LINE = /^(?<module>.+) \[(?<file>[^\][:]+):(?<line>\d+)\]$/u;
3541
3612
  const MODULE_LOCATION = /^(?<module>.+) \[(?<file>[^\][:]+)\]$/u;
3542
3613
  /** A whole-module bracketed label, e.g. `[kernel]`. */
@@ -3708,6 +3779,15 @@ const originSpecs = [
3708
3779
  /** The spec of {@link origin}. */
3709
3780
  const originSpecOf = (origin) => originToSpec.get(origin);
3710
3781
  /**
3782
+ * What one unit of an input's count measures: the origin's answer where the
3783
+ * format's origins disagree, and {@link parsed}, the format's answer,
3784
+ * otherwise.
3785
+ */
3786
+ const resolveCountMetric = (parsed, { origin, format }) => {
3787
+ const originCountMetric = originSpecOf(origin).countMetric(format);
3788
+ return originCountMetric === void 0 ? parsed : originCountMetric;
3789
+ };
3790
+ /**
3711
3791
  * Whether two locations are one source under their origins' entry matches,
3712
3792
  * which strip only an identifier that differs per run or build, such as a
3713
3793
  * store hash or a runtime address. A caller's `matchEntry` can pair two
@@ -3850,6 +3930,7 @@ const resolveOriginSpec = (spec) => ({
3850
3930
  countMetric: spec.countMetric ?? (() => void 0),
3851
3931
  hasRuntimeInsertedArcs: spec.hasRuntimeInsertedArcs ?? (() => false),
3852
3932
  matchEntry: spec.matchEntry ?? (() => void 0),
3933
+ normalizeSourceReference: spec.normalizeSourceReference ?? ((reference) => reference),
3853
3934
  normalizeStackFrame: spec.normalizeStackFrame ?? ((frame) => frame),
3854
3935
  isTruncationMarker: spec.isTruncationMarker ?? (() => false),
3855
3936
  isOriginHint: (hint, format) => hint === spec.id || (spec.isOriginHint?.(hint, format) ?? false),
@@ -4293,7 +4374,7 @@ var StackFrameTable = class StackFrameTable {
4293
4374
  #functionTable;
4294
4375
  constructor(frames) {
4295
4376
  this.#frames = frames;
4296
- this.#functions = new StackFrameFunctions(frames, `definition`);
4377
+ this.#functions = new StackFrameFunctions(frames, `definition`, (reference) => reference);
4297
4378
  }
4298
4379
  /** Adds the raw frames to {@link detector}, once, until decided. */
4299
4380
  addToDetector(detector) {
@@ -4321,19 +4402,20 @@ var StackFrameTable = class StackFrameTable {
4321
4402
  return this.#functionTable;
4322
4403
  }
4323
4404
  #normalize(context) {
4324
- const { functionIdentity, isTruncationMarker, normalizeStackFrame } = originSpecOf(context.origin);
4325
- return new StackFrameFunctionTable(this.#frames.map((frame) => dropLocationName(frame, normalizeStackFrame(frame, context.format))), functionIdentity, (index) => isTruncationMarker(this.#frames[index], context.format));
4405
+ const { functionIdentity, isTruncationMarker, normalizeStackFrame, normalizeSourceReference } = originSpecOf(context.origin);
4406
+ const frames = this.#frames.map((frame) => dropLocationName(frame, normalizeStackFrame(frame, context.format)));
4407
+ return new StackFrameFunctionTable(frames, new StackFrameFunctions(frames, functionIdentity, normalizeSourceReference), (index) => isTruncationMarker(this.#frames[index]));
4326
4408
  }
4327
4409
  };
4328
4410
  /**
4329
4411
  * Drops the name of {@link normalized} when {@link frame}, the frame before
4330
- * normalization, is named with its own file reference, because such a frame
4331
- * has no function name. Unrelated profilers independently converged on this
4412
+ * normalization, is named with its own file reference and normalization kept
4413
+ * that name, because such a frame has no function name. Unrelated profilers independently converged on this
4332
4414
  * idiom (e.g. Excimer, rbspy), so it applies to every origin and format. Only a
4333
4415
  * file reference qualifies, because a function can share its logical
4334
4416
  * reference's name, like a method named after its class or module.
4335
4417
  */
4336
- const dropLocationName = (frame, normalized) => normalized && frame.name !== void 0 && frame.definition?.type === `file` && frame.name === frame.definition.urlOrPath ? {
4418
+ const dropLocationName = (frame, normalized) => normalized && frame.name !== void 0 && frame.definition?.type === `file` && frame.name === frame.definition.urlOrPath && normalized.name === frame.name ? {
4337
4419
  ...normalized,
4338
4420
  name: void 0
4339
4421
  } : normalized;
@@ -4351,9 +4433,9 @@ var StackFrameFunctionTable = class {
4351
4433
  #linelessFunctionKeys;
4352
4434
  /** Whether the raw frame at an index is the origin's truncation marker. */
4353
4435
  #isTruncationMarker;
4354
- constructor(frames, identity, isTruncationMarker) {
4436
+ constructor(frames, functions, isTruncationMarker) {
4355
4437
  this.#frames = frames;
4356
- this.#functions = new StackFrameFunctions(frames, identity);
4438
+ this.#functions = functions;
4357
4439
  this.#isTruncationMarker = isTruncationMarker;
4358
4440
  }
4359
4441
  /** Returns the frame's function, or `undefined` for a dropped frame. */
@@ -4382,9 +4464,11 @@ var StackFrameFunctionTable = class {
4382
4464
  return this.#isTruncationMarker(index);
4383
4465
  }
4384
4466
  };
4385
- const parseStackFrameFunction = (frame) => {
4386
- const identifying = identifyingReference(frame, `definition`);
4387
- return makeStackFrameFunction(frame, identifying, functionIdentityKey(frame.name, identifying));
4467
+ /** The function a frame with no name or location parses to. */
4468
+ const ANONYMOUS_STACK_FRAME_FUNCTION = {
4469
+ name: ANONYMOUS_FUNCTION_NAME,
4470
+ location: void 0,
4471
+ key: ``
4388
4472
  };
4389
4473
  /**
4390
4474
  * Each frame's function, memoized per frame index. Frames sharing an identity
@@ -4393,11 +4477,13 @@ const parseStackFrameFunction = (frame) => {
4393
4477
  var StackFrameFunctions = class {
4394
4478
  #frames;
4395
4479
  #identity;
4480
+ #normalizeSourceReference;
4396
4481
  #functions = [];
4397
4482
  #keyToFunction = /* @__PURE__ */ new Map();
4398
- constructor(frames, identity) {
4483
+ constructor(frames, identity, normalizeSourceReference) {
4399
4484
  this.#frames = frames;
4400
4485
  this.#identity = identity;
4486
+ this.#normalizeSourceReference = normalizeSourceReference;
4401
4487
  }
4402
4488
  /** Returns the frame's function, or `undefined` for a dropped frame. */
4403
4489
  get(index) {
@@ -4409,7 +4495,7 @@ var StackFrameFunctions = class {
4409
4495
  const key = functionIdentityKey(frame.name, identifying);
4410
4496
  func = this.#keyToFunction.get(key);
4411
4497
  if (!func) {
4412
- func = makeStackFrameFunction(frame, identifying, key);
4498
+ func = makeStackFrameFunction(frame, identifying, key, this.#normalizeSourceReference);
4413
4499
  this.#keyToFunction.set(key, func);
4414
4500
  }
4415
4501
  this.#functions[index] = func;
@@ -4418,11 +4504,14 @@ var StackFrameFunctions = class {
4418
4504
  }
4419
4505
  };
4420
4506
  const identifyingReference = (frame, identity) => identity === `call-site` ? frame.callSite : frame.definition;
4421
- const makeStackFrameFunction = (frame, identifying, key) => ({
4422
- name: frame.name || "(anonymous)",
4423
- location: makeSourceLocation(identifying, identifying?.position),
4424
- key
4425
- });
4507
+ const makeStackFrameFunction = (frame, identifying, key, normalizeSourceReference) => {
4508
+ const location = makeSourceLocation(identifying, identifying?.position);
4509
+ return {
4510
+ name: frame.name || "(anonymous)",
4511
+ location: location && normalizeSourceLocation(location, normalizeSourceReference),
4512
+ key
4513
+ };
4514
+ };
4426
4515
  /**
4427
4516
  * Resolves each frame's function to the aggregated function it adds to. A diff
4428
4517
  * side merges the functions with no definition line that share a match key and
@@ -4507,6 +4596,7 @@ var CallGraphAggregator = class {
4507
4596
  };
4508
4597
  var FunctionsAggregator = class {
4509
4598
  #metrics;
4599
+ #callCountMetric;
4510
4600
  #functions;
4511
4601
  /**
4512
4602
  * The normalized frames' functions. A parsed function's index into
@@ -4524,8 +4614,9 @@ var FunctionsAggregator = class {
4524
4614
  */
4525
4615
  #cycleArcs;
4526
4616
  #totalValues;
4527
- constructor({ metrics, functions }, frameFunctions, options, context) {
4617
+ constructor({ metrics, callCountMetric, functions }, frameFunctions, options, context) {
4528
4618
  this.#metrics = metrics;
4619
+ this.#callCountMetric = resolveCountMetric(callCountMetric, context);
4529
4620
  this.#functions = functions;
4530
4621
  this.#frameFunctions = frameFunctions;
4531
4622
  this.#options = options;
@@ -4551,7 +4642,7 @@ var FunctionsAggregator = class {
4551
4642
  return this.#functions.map((_, index) => {
4552
4643
  const frameFunction = this.#frameFunctions.function(index);
4553
4644
  const key = frameFunction?.key ?? ANONYMOUS_FUNCTION_KEY$1;
4554
- return this.#keyToFunction.get(key) ?? this.#registerFunction(key, frameFunction ?? parseStackFrameFunction({}));
4645
+ return this.#keyToFunction.get(key) ?? this.#registerFunction(key, frameFunction ?? ANONYMOUS_STACK_FRAME_FUNCTION);
4555
4646
  });
4556
4647
  }
4557
4648
  #registerFunction(key, { name, location }) {
@@ -4593,6 +4684,7 @@ var FunctionsAggregator = class {
4593
4684
  type: `call-graph`,
4594
4685
  context: this.#context,
4595
4686
  metrics: this.#metrics,
4687
+ callCountMetric: this.#callCountMetric,
4596
4688
  totalValues: this.#totalValues,
4597
4689
  categoryToMetrics: this.#categorize(functions),
4598
4690
  functions
@@ -4736,9 +4828,9 @@ const raiseValues = (target, values) => {
4736
4828
  * position with several candidates at one cost pairs with the nearest.
4737
4829
  *
4738
4830
  * `offsetChangeCost` is the cost of a pair whose offset differs from the
4739
- * previous pair's, {@link OFFSET_CHANGE_COST} by default. A higher cost
4740
- * requires longer runs at a new offset. It must be a multiple of half a unit,
4741
- * like {@link UNPAIRED_COST}, so that ties are broken by offsets alone.
4831
+ * previous pair's. A higher cost requires longer runs at a new offset. It must
4832
+ * be a multiple of half a unit, like {@link UNPAIRED_COST}, so that ties are
4833
+ * broken by offsets alone.
4742
4834
  *
4743
4835
  * It compares only the positions, so the pairing is a guess whenever several
4744
4836
  * edit histories produce the same positions.
@@ -4752,7 +4844,7 @@ const raiseValues = (target, values) => {
4752
4844
  * Returns the index of the current position paired with each base position, or
4753
4845
  * `-1` for a base position left unpaired.
4754
4846
  */
4755
- const alignPositions = (base, current, { offsetChangeCost = OFFSET_CHANGE_COST } = {}) => {
4847
+ const alignPositions = (base, current, { offsetChangeCost }) => {
4756
4848
  assertStrictlyIncreasing(base);
4757
4849
  assertStrictlyIncreasing(current);
4758
4850
  if (2 * offsetChangeCost % 1 !== 0) throw new Error(`offsetChangeCost must be a multiple of 0.5, got: ${offsetChangeCost}`);
@@ -4776,17 +4868,6 @@ const alignPositions = (base, current, { offsetChangeCost = OFFSET_CHANGE_COST }
4776
4868
  }
4777
4869
  };
4778
4870
  const UNPAIRED_COST = 2;
4779
- /**
4780
- * The cost of a pair whose offset differs from the previous pair's.
4781
- *
4782
- * It is between one and two unpaired positions' cost. A run of pairs at a new
4783
- * offset takes one change to enter and one to leave, so the alignment starts a
4784
- * new offset only for a run of at least two pairs, or for a run that ends the
4785
- * lists, which it never leaves. A lower cost pairs a lone position whose
4786
- * offset neither adjacent position shares, and a higher one requires longer
4787
- * runs.
4788
- */
4789
- const OFFSET_CHANGE_COST = 3.5;
4790
4871
  const assertStrictlyIncreasing = (positions) => {
4791
4872
  for (let index = 1; index < positions.length; index++) if (!(positions[index - 1] < positions[index])) throw new Error(`positions must be strictly increasing, got: ${positions[index - 1]} before ${positions[index]}`);
4792
4873
  };
@@ -4927,7 +5008,7 @@ const backwardFrontier = (base, current, { lowestDiagonal, highestDiagonal }, co
4927
5008
  *
4928
5009
  * An alignment's cost excludes the unpaired positions after its last pair, as
4929
5010
  * `cost - UNPAIRED_COST * (row + column)`. A pair extends any alignment before
4930
- * it for its offset's cost less `2 * UNPAIRED_COST`, plus `OFFSET_CHANGE_COST`
5011
+ * it for its offset's cost less `2 * UNPAIRED_COST`, plus `offsetChange`
4931
5012
  * when the offsets differ. Offsets are equal only for pairs in increasing rows
4932
5013
  * and columns, because both lists are strictly increasing.
4933
5014
  */
@@ -5706,6 +5787,7 @@ const diffAggregatedCallGraphs = (base, current, options) => {
5706
5787
  base,
5707
5788
  current,
5708
5789
  metrics,
5790
+ callCountMetric: matchDiffedMetric(base.callCountMetric, current.callCountMetric),
5709
5791
  categoryToMetrics: matchDiffedMaps(base.categoryToMetrics, current.categoryToMetrics),
5710
5792
  functions,
5711
5793
  functionIdIndexes: functionIdIndexes(functions)
@@ -6842,21 +6924,11 @@ const selfDescriptionOf = (metric) => `${metric.phrases.pastParticipleVerbPhrase
6842
6924
  const directionTitle = (type, metric) => `${capitalizeFirst(type)} ${metric.phrases.columnNoun}`;
6843
6925
 
6844
6926
  // src/modalities/call-graph/table.ts
6845
- /**
6846
- * The columns of a Callers or Callees table, with a `Calls` column when any
6847
- * arc in the graph recorded a call count.
6848
- */
6849
- const arcColumns = (measure, entity, hasCallCounts, options) => [
6850
- ...measureColumns(measure),
6851
- ...hasCallCounts ? [{
6852
- header: {
6853
- content: `Calls`,
6854
- align: `right`
6855
- },
6856
- cellOf: (row) => countCell(row.callCount)
6857
- }] : [],
6858
- ...functionNameColumns(entity, options)
6859
- ];
6927
+ /** The columns of a Callers or Callees table. */
6928
+ const arcColumns = (measure, entity, callCountMetric, options) => [...measureColumns({
6929
+ ...measure,
6930
+ countMetric: callCountMetric
6931
+ }), ...functionNameColumns(entity, options)];
6860
6932
 
6861
6933
  // src/modalities/call-graph/format.ts
6862
6934
  const formatCallGraph = (graph, options) => {
@@ -6868,7 +6940,6 @@ const formatCallGraph = (graph, options) => {
6868
6940
  showsAnyEntry: (showEntry) => graph.functions.some((func) => showEntry(func, graph.context)),
6869
6941
  entities: `function`
6870
6942
  });
6871
- const hasCallCounts = graphHasCallCounts(graph);
6872
6943
  return [
6873
6944
  heading(headingLevel, formatTitle(graph.metrics)),
6874
6945
  paragraph(formatSummaryLine$2(graph)),
@@ -6885,7 +6956,7 @@ const formatCallGraph = (graph, options) => {
6885
6956
  headingLevel: sectionHeadingLevel,
6886
6957
  formatBreakdowns: (breakdown) => formatHottestArcSections({
6887
6958
  ...breakdown,
6888
- hasCallCounts
6959
+ callCountMetric: graph.callCountMetric
6889
6960
  })
6890
6961
  });
6891
6962
  })
@@ -6917,11 +6988,11 @@ const formatCategoryTable$2 = (graph) => {
6917
6988
  })))];
6918
6989
  };
6919
6990
  /** The Callers and Callees sections of a ranking whose direction has arcs. */
6920
- const formatHottestArcSections = ({ measure, direction, funcs, context, hasCallCounts, options, headingLevel }) => direction.arcs.flatMap((arcs) => formatSectionGroup([heading(headingLevel, `${arcs.entity}s`), paragraph(arcSectionDescription(arcs.entity, measure.metric, `with the largest`))], funcs.flatMap((func) => formatHottestArcs({
6991
+ const formatHottestArcSections = ({ measure, direction, funcs, callCountMetric, context, options, headingLevel }) => direction.arcs.flatMap((arcs) => formatSectionGroup([heading(headingLevel, `${arcs.entity}s`), paragraph(arcSectionDescription(arcs.entity, measure.metric, `with the largest`))], funcs.flatMap((func) => formatHottestArcs({
6921
6992
  measure,
6922
6993
  func,
6923
6994
  arcs,
6924
- hasCallCounts,
6995
+ callCountMetric,
6925
6996
  context,
6926
6997
  options,
6927
6998
  headingLevel: headingLevel + 1
@@ -6930,10 +7001,10 @@ const formatHottestArcSections = ({ measure, direction, funcs, context, hasCallC
6930
7001
  * The Callers or Callees subsection for one function: its incoming or outgoing
6931
7002
  * arcs ranked by the arcs' recorded total values.
6932
7003
  */
6933
- const formatHottestArcs = ({ measure, func, arcs, hasCallCounts, context, options, headingLevel }) => {
7004
+ const formatHottestArcs = ({ measure, func, arcs, callCountMetric, context, options, headingLevel }) => {
6934
7005
  const hottestArcs = selectTopN(arcs.rowsOf(func, measure).map(([, row]) => row).filter((row) => options.showEntry(row.func, context) && row.value > 0).toArray(), breakdownLimit(options), ({ value }) => value);
6935
7006
  if (hottestArcs.length === 0) return [];
6936
- return [formatFunctionHeading(headingLevel, func, options), formatTable(arcColumns(measure, arcs.entity, hasCallCounts, options), hottestArcs)];
7007
+ return [formatFunctionHeading(headingLevel, func, options), formatTable(arcColumns(measure, arcs.entity, callCountMetric, options), hottestArcs)];
6937
7008
  };
6938
7009
  const formatCallGraphDiff = (diff, options) => {
6939
7010
  const headingLevel = 1;
@@ -6947,7 +7018,6 @@ const formatCallGraphDiff = (diff, options) => {
6947
7018
  entities: `function`
6948
7019
  });
6949
7020
  const shownFunctions = diff.functions.filter((func) => showDiffEntity(func, diff, sectionOptions.showEntry));
6950
- const hasCallCounts = graphHasCallCounts(diff.base) && graphHasCallCounts(diff.current);
6951
7021
  return [
6952
7022
  heading(headingLevel, `${formatTitle(measures.map(({ metric }) => metric))} diff`),
6953
7023
  paragraph(formatDiffSummaryLine$3(diff)),
@@ -6966,8 +7036,7 @@ const formatCallGraphDiff = (diff, options) => {
6966
7036
  formatDiffBreakdowns: (breakdown) => formatDiffArcSections({
6967
7037
  ...breakdown,
6968
7038
  diff,
6969
- matchFunctionIds,
6970
- hasCallCounts
7039
+ matchFunctionIds
6971
7040
  })
6972
7041
  });
6973
7042
  })
@@ -7025,15 +7094,14 @@ const formatDiffArcSections = (args) => args.direction.arcs.flatMap((arcs) => fo
7025
7094
  * The Callers or Callees subsection for one function: its arcs whose recorded
7026
7095
  * total values changed the most either way.
7027
7096
  */
7028
- const formatDiffFunctionArcs = ({ diff, matchFunctionIds, measure, func, arcs, hasCallCounts, options, headingLevel }) => {
7097
+ const formatDiffFunctionArcs = ({ diff, matchFunctionIds, measure, func, arcs, options, headingLevel }) => {
7029
7098
  const changedArcs = selectLargestChanges(matchFunctionIds(func.base && arcs.rowsOf(func.base, measure.base), func.current && arcs.rowsOf(func.current, measure.current)).filter(({ base, current }) => showDiffEntity({
7030
7099
  base: base?.func,
7031
7100
  current: current?.func
7032
7101
  }, diff, options.showEntry)), breakdownLimit(options), ({ base, current }) => (current?.value ?? 0) - (base?.value ?? 0));
7033
7102
  if (changedArcs.length === 0) return [];
7034
- return [formatFunctionHeading(headingLevel, func, options), formatDiffTable(arcColumns(measure, arcs.entity, hasCallCounts, options), changedArcs)];
7103
+ return [formatFunctionHeading(headingLevel, func, options), formatDiffTable(arcColumns(measure, arcs.entity, diff.callCountMetric, options), changedArcs)];
7035
7104
  };
7036
- const graphHasCallCounts = (graph) => graph.functions.some((func) => func.calleeIdToMetrics.values().some(({ callCount }) => callCount > 0));
7037
7105
  const FUNCTION_RANKING$1 = {
7038
7106
  self: {
7039
7107
  type: `self`,
@@ -7051,18 +7119,16 @@ const FUNCTION_RANKING$1 = {
7051
7119
  entity: `Caller`,
7052
7120
  rowsOf: (func, measure) => func.callerIdToMetrics.entries().map(([id, { caller, callCount, totalValues }]) => [id, {
7053
7121
  func: caller,
7054
- callCount,
7055
7122
  value: measure.valueOf(totalValues, 0),
7056
- count: 0,
7123
+ count: callCount,
7057
7124
  total: totalValueOf$1(measure, func)
7058
7125
  }])
7059
7126
  }, {
7060
7127
  entity: `Callee`,
7061
7128
  rowsOf: (func, measure) => func.calleeIdToMetrics.entries().map(([id, { callee, callCount, totalValues }]) => [id, {
7062
7129
  func: callee,
7063
- callCount,
7064
7130
  value: measure.valueOf(totalValues, 0),
7065
- count: 0,
7131
+ count: callCount,
7066
7132
  total: totalValueOf$1(measure, func)
7067
7133
  }])
7068
7134
  }]
@@ -7173,7 +7239,7 @@ var CallStackProfileAggregator = class {
7173
7239
  aggregate(options, context, otherSide) {
7174
7240
  const { metrics, countMetric, frames, observations, lineMetrics } = this.#profile;
7175
7241
  const functions = StackFrameTable.for(frames).resolve(context);
7176
- const aggregator = new ObservationsAggregator(metrics, originSpecOf(context.origin).countMetric(context.format) ?? countMetric, functions, options, context, otherSide && otherSideFunctionKeys(otherSide));
7242
+ const aggregator = new ObservationsAggregator(metrics, resolveCountMetric(countMetric, context), functions, options, context, otherSide && otherSideFunctionKeys(otherSide));
7177
7243
  for (const observation of observations) aggregator.addObservation(observation);
7178
7244
  for (const lineMetric of lineMetrics ?? []) aggregator.addLineMetrics(lineMetric);
7179
7245
  return aggregator.aggregate();
@@ -7296,7 +7362,7 @@ var ObservationsAggregator = class {
7296
7362
  return callStack;
7297
7363
  }
7298
7364
  #getOrCreateAnonymousFunction() {
7299
- return this.#keyToFunction.get(ANONYMOUS_FUNCTION_KEY) ?? this.#registerFunction(ANONYMOUS_FUNCTION_KEY, parseStackFrameFunction({}));
7365
+ return this.#keyToFunction.get(ANONYMOUS_FUNCTION_KEY) ?? this.#registerFunction(ANONYMOUS_FUNCTION_KEY, ANONYMOUS_STACK_FRAME_FUNCTION);
7300
7366
  }
7301
7367
  #internCallStack(frames, truncated) {
7302
7368
  const key = this.#callStackKey;
@@ -7514,8 +7580,8 @@ const diffAggregatedCallStackProfiles = (base, current, options) => {
7514
7580
  * diff would then have nothing to rank.
7515
7581
  */
7516
7582
  const matchDiffedCountMetrics = (base, current, ranksByCount) => {
7517
- const { countMetric } = base;
7518
- if (countMetric && current.countMetric && metricsEqual(countMetric, current.countMetric)) return countMetric;
7583
+ const countMetric = matchDiffedMetric(base.countMetric, current.countMetric);
7584
+ if (countMetric) return countMetric;
7519
7585
  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)}`);
7520
7586
  return null;
7521
7587
  };
@@ -8613,8 +8679,7 @@ const formatCallStackProfile = (profile, options) => {
8613
8679
  ];
8614
8680
  };
8615
8681
  /**
8616
- * {@link options} with `showEntry` memoized by the profile's function IDs,
8617
- * along with whether it shows any of {@link profile}'s functions.
8682
+ * {@link options} with `showEntry` memoized by the profile's function IDs.
8618
8683
  *
8619
8684
  * The option's own per-entry cache is a `WeakMap`, whose lookup is too slow to
8620
8685
  * run once per stack frame. Function IDs are unique only within one profile,
@@ -9610,17 +9675,15 @@ var WorkBudget = class {
9610
9675
  if (this.#spent > this.#limit) throw new WorkBudgetExhaustedError();
9611
9676
  }
9612
9677
  /**
9613
- * Runs the computation unless the budget is exhausted, and returns whether it
9614
- * finished. A computation the budget stops keeps the effects it had.
9678
+ * Runs the computation unless the budget is exhausted. A computation the
9679
+ * budget stops keeps the effects it had.
9615
9680
  */
9616
9681
  run(compute) {
9617
- if (this.isExhausted) return false;
9682
+ if (this.isExhausted) return;
9618
9683
  try {
9619
9684
  compute();
9620
- return true;
9621
9685
  } catch (error) {
9622
- if (error instanceof WorkBudgetExhaustedError) return false;
9623
- throw error;
9686
+ if (!(error instanceof WorkBudgetExhaustedError)) throw error;
9624
9687
  }
9625
9688
  }
9626
9689
  };
@@ -10001,8 +10064,8 @@ const computePreorderIndexToEndIndex = (preorderIndexToDominatorIndex) => {
10001
10064
  * Aggregates one {@link HeapSnapshot}.
10002
10065
  *
10003
10066
  * The constructor computes everything that needs no origin, including the
10004
- * entries origin detection reads. {@link aggregate} categorizes under the
10005
- * resolved origin.
10067
+ * entries origin detection reads. {@link aggregate} normalizes locations and
10068
+ * categorizes under the resolved origin.
10006
10069
  */
10007
10070
  var HeapSnapshotAggregator = class {
10008
10071
  #nodeCount;
@@ -10157,6 +10220,10 @@ var HeapSnapshotAggregator = class {
10157
10220
  this.#entityCategorizer.addStringNode(categoryKey);
10158
10221
  }
10159
10222
  aggregate(options, context) {
10223
+ const { normalizeSourceReference } = originSpecOf(context.origin);
10224
+ const normalizeLocation = (location) => normalizeSourceLocation(location, normalizeSourceReference);
10225
+ this.#normalizeLocations(normalizeLocation);
10226
+ this.#retainerOf = normalizedRetainerOf(this.#retainerOf, normalizeLocation);
10160
10227
  const preorder = computeDominatorTreePreorder(this.#immediateDominatorGraph);
10161
10228
  const logLowerBound = once(() => options.logger.info?.(`retained sizes are lower bounds because the heap exceeded the work limit for nodes that instances retain only together`));
10162
10229
  this.#assignRetentions(preorder, logLowerBound);
@@ -10184,6 +10251,20 @@ var HeapSnapshotAggregator = class {
10184
10251
  };
10185
10252
  }
10186
10253
  /**
10254
+ * Normalizes the constructors' and functions' locations. An instance shares
10255
+ * its constructor's location, because a constructor groups nodes by name and
10256
+ * location.
10257
+ */
10258
+ #normalizeLocations(normalizeLocation) {
10259
+ for (const fn of this.#functions) if (fn.location) fn.location = normalizeLocation(fn.location);
10260
+ for (const constructor of this.#constructors) {
10261
+ if (!constructor.location) continue;
10262
+ const location = normalizeLocation(constructor.location);
10263
+ constructor.location = location;
10264
+ for (const instance of constructor.instances) instance.location = location;
10265
+ }
10266
+ }
10267
+ /**
10187
10268
  * Assigns the constructors' and functions' retentions from one pass, because
10188
10269
  * a node is an instance of at most one of them.
10189
10270
  */
@@ -10268,6 +10349,14 @@ const computeRetainerHop = (nodeOrdinal, { ordinalToPredecessorStartOffset, offs
10268
10349
  internal: isInternalNode(dominatorOrdinal)
10269
10350
  };
10270
10351
  };
10352
+ /** Wraps {@link retainerOf} to normalize each retainer's location. */
10353
+ const normalizedRetainerOf = (retainerOf, normalizeLocation) => (nodeOrdinal) => {
10354
+ const retainer = retainerOf(nodeOrdinal);
10355
+ return retainer.location ? {
10356
+ ...retainer,
10357
+ location: normalizeLocation(retainer.location)
10358
+ } : retainer;
10359
+ };
10271
10360
  const GC_ROOT_NAME = `(GC root)`;
10272
10361
  const SEVERAL_RETAINERS_EDGE = { type: `several-retainers` };
10273
10362
  /**
@@ -10278,7 +10367,7 @@ const entityLocation = ({ location, nameLocation }) => location ?? nameLocation;
10278
10367
  /** Identifies a node by its name and location. */
10279
10368
  const nodeKey = (name, location) => location ? `${name}|${sourceReferenceKind(location)}|${sourceReferenceId(location)}:${location.line}:${location.column}` : name;
10280
10369
  const formatRetainerLabel = (retainer, options) => `${formatRetainerName(retainer, options)}${retainer.location ? ` (${formatSourceLocation(retainer.location, options)})` : ``}`;
10281
- const formatRetainerName = ({ name, nameLocation }, options) => nameLocation ? formatSourceLocation(nameLocation, options) : name;
10370
+ const formatRetainerName = ({ name, nameLocation }, options) => nameLocation ? formatSourceLocation(nameLocation, options) : name ?? ``;
10282
10371
  const formatRetainerEdgeLabel = (edge, options) => formatRetainerEdge(edge, ({ name, nameLocation }) => nameLocation ? formatSourceLocation(nameLocation, options) : name);
10283
10372
  const formatRetainerEdge = (edge, propertyName) => {
10284
10373
  switch (edge.type) {
@@ -10659,8 +10748,7 @@ var RetainerPaths = class RetainerPaths {
10659
10748
  }
10660
10749
  while (hops.length > 0) {
10661
10750
  const { dominatorOrdinal, edge, internal } = hops.pop();
10662
- const isRestEmpty = path === RetainerPaths.ROOT && !this.#isWithinDominator;
10663
- if (keepsRetainerStep(internal, isRestEmpty)) {
10751
+ if (!(path === RetainerPaths.ROOT && !this.#isWithinDominator && internal)) {
10664
10752
  ordinalToRetainer[dominatorOrdinal] ??= snapshot.retainerOf(dominatorOrdinal);
10665
10753
  const retainer = ordinalToRetainer[dominatorOrdinal];
10666
10754
  ordinalToRetainerLabel[dominatorOrdinal] ??= formatRetainerLabel(retainer, this.options);
@@ -10819,13 +10907,6 @@ var RetainerPaths = class RetainerPaths {
10819
10907
  return located;
10820
10908
  }
10821
10909
  };
10822
- /**
10823
- * Whether a retainer path keeps a hop's step, given whether the hop's
10824
- * dominator is internal and whether the path from it outward is empty. A path
10825
- * drops its trailing steps through internal nodes, which are VM bookkeeping
10826
- * that never points to user code.
10827
- */
10828
- const keepsRetainerStep = (internal, isRestEmpty) => !(isRestEmpty && internal);
10829
10910
  const ANY_ELEMENT_EDGE = { type: `any-element` };
10830
10911
  const GC_ROOT_RETAINER = {
10831
10912
  id: 0,
@@ -11157,16 +11238,11 @@ const stringColumns = (hasValues) => [
11157
11238
  ];
11158
11239
  const entityColumns = (nameLabel, hasLocation, options) => [{
11159
11240
  header: nameLabel,
11160
- cellOf: (row) => codeCell(displayName(row.entity, options) || `(unknown)`)
11241
+ cellOf: (row) => codeCell(formatRetainerName(row.entity, options) || `(unknown)`)
11161
11242
  }, ...hasLocation ? [{
11162
11243
  header: `Location`,
11163
11244
  cellOf: (row) => locationCell(row.entity.location, options)
11164
11245
  }] : []];
11165
- /**
11166
- * An entity's displayed name: its URL-shaped name formatted relative to the
11167
- * base URL when it has one, and its raw name otherwise.
11168
- */
11169
- const displayName = (entity, options) => entity.nameLocation ? formatSourceLocation(entity.nameLocation, options) : entity.name;
11170
11246
 
11171
11247
  // src/modalities/heap-snapshot/format.ts
11172
11248
  const formatHeapSnapshot = (snapshot, options) => {
@@ -11332,7 +11408,6 @@ var ShownRetainerPaths = class ShownRetainerPaths {
11332
11408
  pathOf(snapshot) {
11333
11409
  return this.#paths.pathOfNodeIn(snapshot);
11334
11410
  }
11335
- /** Formats the retainer path of a node of {@link snapshot}. */
11336
11411
  ofNode(snapshot, nodeOrdinal) {
11337
11412
  return this.ofPath(snapshot.retainerOf(nodeOrdinal), this.pathOf(snapshot)(nodeOrdinal));
11338
11413
  }
@@ -11354,10 +11429,7 @@ var ShownRetainerPaths = class ShownRetainerPaths {
11354
11429
  */
11355
11430
  ofSteps(node, steps) {
11356
11431
  if (this.#recordings.length === 0) throw new Error(`retainer path formatted outside a recording`);
11357
- const nodeName = formatRetainerName({
11358
- ...node,
11359
- name: node.name ?? ``
11360
- }, this.#options) || `(unknown)`;
11432
+ const nodeName = formatRetainerName(node, this.#options) || `(unknown)`;
11361
11433
  return steps.length === 0 ? `${nodeName} ← ${GC_ROOT_NAME}` : steps.reduce((path, { edge, retainer }) => {
11362
11434
  for (const edgeTypes of this.#recordings) edgeTypes.add(edge.type);
11363
11435
  const edgeLabel = formatRetainerEdgeLabel(edge, this.#options);
@@ -11767,7 +11839,7 @@ const formatDiffEntitySections = ({ prose, ...args }) => formatDiffMeasureSectio
11767
11839
  improvement: BYTES_METRIC.improvement,
11768
11840
  selfValueNoun: `self size`
11769
11841
  });
11770
- const formatEntityHeading = (headingLevel, entity, hasLocation, options) => heading(headingLevel, hasLocation ? nameLocationPhrasing(displayName(entity, options), inlineCode(formatSourceLocation(entity.location, options))) : [inlineCode(displayName(entity, options))]);
11842
+ const formatEntityHeading = (headingLevel, entity, hasLocation, options) => heading(headingLevel, hasLocation ? nameLocationPhrasing(formatRetainerName(entity, options), inlineCode(formatSourceLocation(entity.location, options))) : [inlineCode(formatRetainerName(entity, options))]);
11771
11843
 
11772
11844
  // src/modalities/heap-snapshot/modality.ts
11773
11845
  const heapSnapshotModalitySpec = {
@@ -11872,7 +11944,7 @@ var EventsAggregator = class {
11872
11944
  this.#trace = trace;
11873
11945
  this.#context = context;
11874
11946
  const { normalizeTraceEvent, categorizeTraceEvent } = originSpecOf(context.origin);
11875
- this.#normalize = (event) => normalizeTraceEvent(event, context.format);
11947
+ this.#normalize = normalizeTraceEvent;
11876
11948
  this.#categorize = categorizeTraceEvent;
11877
11949
  this.#scale = trace.millisecondsPerTimeUnit;
11878
11950
  const nameToThread = /* @__PURE__ */ new Map();
@@ -12290,7 +12362,7 @@ const diffAggregatedTraces = (base, current, options) => ({
12290
12362
  base,
12291
12363
  current,
12292
12364
  categoryToStats: matchDiffedMaps(base.categoryToStats, current.categoryToStats),
12293
- threads: matchByName(base.threads, current.threads),
12365
+ threads: matchByKey(base.threads, current.threads, ({ name }) => name),
12294
12366
  spans: [false, true].flatMap((async) => matchEvents(base, current, ({ spans }) => spans.filter((span) => span.async === async), options)),
12295
12367
  instants: matchEvents(base, current, ({ instants }) => instants, options),
12296
12368
  gauges: matchGauges(base.gauges, current.gauges)
@@ -12310,8 +12382,6 @@ const matchEvents = (base, current, eventsOf, options) => matchDiffedInputEntrie
12310
12382
  * arrow between its two values would compare different quantities.
12311
12383
  */
12312
12384
  const matchGauges = (base, current) => matchByKey(base, current, ({ name, thread }) => `${thread ?? ``}\0${name}`).flatMap((diff) => diff.base && diff.current && !metricsEqual(diff.base.metric, diff.current.metric) ? [{ base: diff.base }, { current: diff.current }] : [diff]);
12313
- /** Pairs each side's values sharing a name, which is unique within a side. */
12314
- const matchByName = (base, current) => matchByKey(base, current, ({ name }) => name);
12315
12385
  /** Pairs each side's values sharing a key, which is unique within a side. */
12316
12386
  const matchByKey = (base, current, keyOf) => [...matchDiffedMaps(base.map((value) => [keyOf(value), value]), current.map((value) => [keyOf(value), value])).values()];
12317
12387
 
@@ -12711,6 +12781,11 @@ const totalCpuTime = (hasNesting) => ({
12711
12781
  neighbors: [],
12712
12782
  hasDetail: false
12713
12783
  });
12784
+ /** A span's mean and longest durations, nested in its own name or not. */
12785
+ const durationDistributionOf = (span) => ({
12786
+ mean: meanOf(span.summedTime, span.timedCount),
12787
+ max: span.maxTime
12788
+ });
12714
12789
  const ELAPSED_TIME = {
12715
12790
  title: `Elapsed time`,
12716
12791
  noun: `elapsed time`,
@@ -12718,17 +12793,12 @@ const ELAPSED_TIME = {
12718
12793
  valueOf: ({ totalTime }) => totalTime,
12719
12794
  time: {
12720
12795
  header: `Time`,
12721
- distributionOf: (span) => durationDistributionOf(span)
12796
+ distributionOf: durationDistributionOf
12722
12797
  },
12723
12798
  population: ASYNC_SPANS,
12724
12799
  neighbors: [PARENTS, CHILDREN],
12725
12800
  hasDetail: true
12726
12801
  };
12727
- /** A span's mean and longest durations, nested in its own name or not. */
12728
- const durationDistributionOf = (span) => ({
12729
- mean: meanOf(span.summedTime, span.timedCount),
12730
- max: span.maxTime
12731
- });
12732
12802
  const COUNT_DESCRIPTION = `occurrences recorded`;
12733
12803
  const spanCount = (population) => ({
12734
12804
  title: `Count`,
@@ -13265,7 +13335,7 @@ const formatDiffStatsTable = ({ event, entity, spanTotalOf, baseStats, currentSt
13265
13335
  };
13266
13336
  const largestStatsChanges = (keyToStats, hasTime, options) => selectLargestChanges([...keyToStats], breakdownLimit(options), ([, stats]) => statsChange(stats, hasTime));
13267
13337
  const statsChange = ({ base, current }, hasTime) => statsValue(current ?? EMPTY_STATS, hasTime) - statsValue(base ?? EMPTY_STATS, hasTime);
13268
- const formatDiffThreadSections = ({ events, share, indexes, options, headingLevel }) => formatSectionGroup([heading(headingLevel, `Threads`), paragraph(shareSentence(`Threads with the largest change in`, share))], events.flatMap((event) => Math.max(event.base?.threadIdToStats.size ?? 0, event.current?.threadIdToStats.size ?? 0) === 0 ? [] : formatDiffStatsTable({
13338
+ const formatDiffThreadSections = ({ events, share, indexes, options, headingLevel }) => formatSectionGroup([heading(headingLevel, `Threads`), paragraph(shareSentence(`Threads with the largest change in`, share))], events.flatMap((event) => formatDiffStatsTable({
13269
13339
  event,
13270
13340
  entity: `Thread`,
13271
13341
  baseStats: event.base && namedStats(event.base.threadIdToStats, indexes.base.threadName),
@@ -13684,16 +13754,12 @@ const matchesCallgrind = (bytes) => {
13684
13754
  let sawEvents = false;
13685
13755
  let sawPositionSpec = false;
13686
13756
  let index = 0;
13687
- try {
13688
- for (const line of decodeUtf8Lines(bytes)) {
13689
- if (index === 0 && line === `# callgrind format`) return true;
13690
- if (EVENTS_HEADER.test(line)) sawEvents = true;
13691
- else if (POSITION_SPEC.test(line)) sawPositionSpec = true;
13692
- if (sawEvents && sawPositionSpec) return true;
13693
- if (++index >= MAX_DETECTION_LINES) break;
13694
- }
13695
- } catch {
13696
- return false;
13757
+ for (const line of decodeUtf8Lines(bytes)) {
13758
+ if (index === 0 && line === `# callgrind format`) return true;
13759
+ if (EVENTS_HEADER.test(line)) sawEvents = true;
13760
+ else if (POSITION_SPEC.test(line)) sawPositionSpec = true;
13761
+ if (sawEvents && sawPositionSpec) return true;
13762
+ if (++index >= MAX_DETECTION_LINES) break;
13697
13763
  }
13698
13764
  return false;
13699
13765
  };
@@ -13765,6 +13831,13 @@ var FormatDetectError = class extends ProfilerMdError {
13765
13831
  * them, in detection order. Empty when the error is not a conversion error, or
13766
13832
  * when every wrapped error is a {@link FormatParseError}.
13767
13833
  *
13834
+ * A parse that throws a {@link FormatParseError} identified the violation. One
13835
+ * that throws anything else failed on an error it did not classify: either the
13836
+ * input violates the format in a way the parser does not check, or the parser
13837
+ * has a bug. The pipeline reports both as unusable input, because the parser's
13838
+ * input is the only variable on its code path. A caller whose input opens in
13839
+ * its profiler has the evidence that distinguishes the two.
13840
+ *
13768
13841
  * An error that only restates another, such as one naming the input a failure
13769
13842
  * came from, resolves to its cause.
13770
13843
  */
@@ -13948,7 +14021,6 @@ var CallgrindProfileBuilder = class {
13948
14021
  /** Maps the part's cost-line value positions onto global event indices. */
13949
14022
  #setPartEvents(rest) {
13950
14023
  const names = rest.split(/\s+/u).filter((name) => name.length > 0);
13951
- if (names.length === 0) throw new FormatParseError(`empty events header`);
13952
14024
  this.#partEventIndices = names.map((name) => this.#eventIndex(name));
13953
14025
  }
13954
14026
  #eventIndex(name) {
@@ -13975,7 +14047,6 @@ var CallgrindProfileBuilder = class {
13975
14047
  /** Declares the subposition columns cost lines start with. */
13976
14048
  #setPositions(rest) {
13977
14049
  const columns = rest.split(/\s+/u).filter((name) => name.length > 0);
13978
- if (columns.length === 0 || columns.some((column) => column !== `instr` && column !== `line`)) throw new FormatParseError(`invalid positions header, got: ${JSON.stringify(rest)}`);
13979
14050
  this.#subpositionCount = columns.length;
13980
14051
  this.#lineSubpositionIndex = columns.indexOf(`line`);
13981
14052
  this.#lastSubpositions = [];
@@ -14129,6 +14200,7 @@ var CallgrindProfileBuilder = class {
14129
14200
  type: `call-graph`,
14130
14201
  ...originHint === void 0 ? {} : { originHint },
14131
14202
  metrics: this.#eventNames.map((name) => callgrindEventMetric(name, this.#eventLongNames.get(name), this.#eventIndices.has(SYSTEM_CPU_TIME_EVENT))),
14203
+ callCountMetric: CALLS,
14132
14204
  frames: functions.map(callgrindStackFrame),
14133
14205
  functions: functions.map(callGraphFunction)
14134
14206
  }];
@@ -14293,6 +14365,8 @@ const sourceOf = (file) => file === `` || file === UNKNOWN ? void 0 : {
14293
14365
  urlOrPath: file
14294
14366
  };
14295
14367
  const UNKNOWN = `???`;
14368
+ /** What one unit of a `calls=` line's count measures. */
14369
+ const CALLS = countMetricOf(`call`, { improvement: `decrease` });
14296
14370
  const callGraphFunction = (func) => ({
14297
14371
  selfValues: func.selfValues,
14298
14372
  lineToValues: func.lineToValues,
@@ -14637,16 +14711,22 @@ var Eventlog = class {
14637
14711
  }
14638
14712
  /**
14639
14713
  * Yields one sample per tick the profiler recorded, skipping each sample
14640
- * that references a cost centre the log never defines.
14714
+ * that references a cost centre the log never defines or whose event ends
14715
+ * before its stack.
14641
14716
  *
14642
14717
  * Every sample measured the same interval, so they share one {@link values}
14643
14718
  * array rather than allocating a copy per tick. The aggregator only reads it.
14644
14719
  */
14645
14720
  *#observations(idToFrameIndex, values, recordTally) {
14646
14721
  let skippedSamples = 0;
14647
- samples: for (const { eventType, payload } of this.#events()) {
14722
+ let overrunSamples = 0;
14723
+ samples: for (const { eventType, payload, size } of this.#events()) {
14648
14724
  if (eventType !== TIME_PROFILE_SAMPLE) continue;
14649
- const depth = this.#sampleStackDepth(payload);
14725
+ const depth = size > SAMPLE_STACK_DEPTH ? this.#sampleStackDepth(payload) : void 0;
14726
+ if (depth === void 0 || SAMPLE_STACK + depth * COST_CENTRE_ID_SIZE > size) {
14727
+ overrunSamples++;
14728
+ continue;
14729
+ }
14650
14730
  const frameIndices = new Array(depth);
14651
14731
  for (let index = 0; index < depth; index++) {
14652
14732
  const frameIndex = idToFrameIndex[this.#sampleCostCentreId(payload, index)];
@@ -14662,6 +14742,7 @@ var Eventlog = class {
14662
14742
  };
14663
14743
  }
14664
14744
  recordTally.skipped(`sample`, `referencing a missing cost centre`, skippedSamples);
14745
+ recordTally.skipped(`sample`, `whose event ends before its stack`, overrunSamples);
14665
14746
  }
14666
14747
  /**
14667
14748
  * Yields every event in the log, then returns whether it reached the
@@ -14981,22 +15062,16 @@ var ObjectIdToOrdinal = class ObjectIdToOrdinal {
14981
15062
  #size = 0;
14982
15063
  /** Grows once the table passes this share of its capacity. */
14983
15064
  static #MAX_LOAD = .7;
14984
- constructor(initialCapacity = 4096) {
14985
- const capacity = nextPowerOfTwo(initialCapacity);
15065
+ constructor() {
15066
+ const capacity = 4096;
14986
15067
  this.#objectIds = new Float64Array(capacity);
14987
15068
  this.#ordinals = new Int32Array(capacity);
14988
- this.#mask = capacity - 1;
15069
+ this.#mask = 4095;
14989
15070
  }
14990
- /**
14991
- * Assigns {@link ordinal} to {@link objectId}, keeping the ordinal already
14992
- * assigned when the dump repeats an ID.
14993
- */
15071
+ /** Assigns {@link ordinal} to {@link objectId}. */
14994
15072
  set(objectId, ordinal) {
14995
15073
  let slot = hashObjectId(objectId) & this.#mask;
14996
- while (this.#objectIds[slot] !== 0) {
14997
- if (this.#objectIds[slot] === objectId) return;
14998
- slot = slot + 1 & this.#mask;
14999
- }
15074
+ while (this.#objectIds[slot] !== 0) slot = slot + 1 & this.#mask;
15000
15075
  this.#objectIds[slot] = objectId;
15001
15076
  this.#ordinals[slot] = ordinal;
15002
15077
  if (++this.#size > (this.#mask + 1) * ObjectIdToOrdinal.#MAX_LOAD) this.#grow();
@@ -15024,11 +15099,6 @@ var ObjectIdToOrdinal = class ObjectIdToOrdinal {
15024
15099
  }
15025
15100
  }
15026
15101
  };
15027
- const nextPowerOfTwo = (value) => {
15028
- let result = 1;
15029
- while (result < value) result *= 2;
15030
- return result;
15031
- };
15032
15102
  /**
15033
15103
  * Mixes an object ID's low and high 32 bits into a 32-bit slot hash.
15034
15104
  *
@@ -15882,7 +15952,7 @@ const recordCutOffChunk = (recordTally) => {
15882
15952
  recordTally.skipped(`chunk`, `cut off by the end of the input`);
15883
15953
  };
15884
15954
  const recordBytesAfterChunks = (recordTally, byteCount) => {
15885
- if (byteCount > 0) recordTally.skipped(`byte`, `not forming a chunk`, byteCount);
15955
+ recordTally.skipped(`byte`, `not forming a chunk`, byteCount);
15886
15956
  };
15887
15957
  const jfrToProfiles = ({ methods, stackTraces, events, isAsyncProfiler, metriclessKinds }) => {
15888
15958
  const frames = methods.map(methodToStackFrame);
@@ -15911,7 +15981,7 @@ const methodToStackFrame = (method) => ({
15911
15981
  } : void 0
15912
15982
  });
15913
15983
  /** One object sampled at allocation and still live when the recording ended. */
15914
- const OBJECTS = countMetricOf(`object`, { improvement: `decrease` });
15984
+ const SAMPLED_OBJECTS = countMetricOf(`sampled object`, { improvement: `decrease` });
15915
15985
  /** One acquisition of a contended monitor, or one park. */
15916
15986
  const CONTENTIONS = countMetricOf(`contention`, { improvement: `decrease` });
15917
15987
  /**
@@ -15923,9 +15993,10 @@ const CONTENTIONS = countMetricOf(`contention`, { improvement: `decrease` });
15923
15993
  * allocations since the previous one, a TLAB event stands for a whole TLAB
15924
15994
  * refill or for one allocation made outside a TLAB, and async-profiler's
15925
15995
  * `--alloc <bytes>` and `--nativemem <bytes>` set a sampling interval for the
15926
- * heap and `profiler.Malloc` events. Live-object and lock events each record
15927
- * one occurrence of what their kind names, so their rate is per object or per
15928
- * contention rather than per sample.
15996
+ * heap and `profiler.Malloc` events. Live-object events record only objects
15997
+ * sampled at allocation, up to a limit. Lock events each record one occurrence
15998
+ * of what their kind names, so their rate is per contention rather than per
15999
+ * sample.
15929
16000
  */
15930
16001
  const KINDS = [
15931
16002
  {
@@ -15941,7 +16012,7 @@ const KINDS = [
15941
16012
  {
15942
16013
  kind: `live`,
15943
16014
  metric: RETAINED_HEAP_METRIC,
15944
- countMetric: OBJECTS
16015
+ countMetric: SAMPLED_OBJECTS
15945
16016
  },
15946
16017
  {
15947
16018
  kind: `nativemem`,
@@ -16076,12 +16147,12 @@ var JfrParser = class {
16076
16147
  this.#view = new DataView(chunkBytes.buffer, chunkBytes.byteOffset, chunkBytes.byteLength);
16077
16148
  this.#position = 0;
16078
16149
  this.#frequency = this.#readInt64(FREQUENCY_FIELD) || NANOSECONDS_PER_SECOND;
16079
- const skipReason = this.#loadChunkTypes(0);
16150
+ const skipReason = this.#loadChunkTypes();
16080
16151
  if (skipReason !== void 0) {
16081
16152
  this.#recordTally.skipped(`chunk`, skipReason);
16082
16153
  return;
16083
16154
  }
16084
- const { pools, rawEvents } = this.#readChunkBody(0, chunkBytes.length);
16155
+ const { pools, rawEvents } = this.#readChunkBody();
16085
16156
  this.#resolve(pools, rawEvents);
16086
16157
  }
16087
16158
  /** Returns the recording accumulated from every parsed chunk. */
@@ -16110,10 +16181,10 @@ var JfrParser = class {
16110
16181
  * Returns why the chunk must be skipped, or `undefined` when its types
16111
16182
  * loaded.
16112
16183
  */
16113
- #loadChunkTypes(chunkStart) {
16184
+ #loadChunkTypes() {
16114
16185
  const chunkEnd = this.#bytes.length;
16115
- const metadataStart = chunkStart + this.#readInt64(chunkStart + METADATA_OFFSET_FIELD);
16116
- if (!(metadataStart >= chunkStart + CHUNK_HEADER_SIZE) || metadataStart >= chunkEnd) return NO_METADATA;
16186
+ const metadataStart = this.#readInt64(METADATA_OFFSET_FIELD);
16187
+ if (!(metadataStart >= CHUNK_HEADER_SIZE) || metadataStart >= chunkEnd) return NO_METADATA;
16117
16188
  this.#position = metadataStart;
16118
16189
  const size = this.#readVarint();
16119
16190
  this.#recordEnd = metadataStart + size;
@@ -16217,22 +16288,22 @@ var JfrParser = class {
16217
16288
  if (framesField === void 0 || frameType === void 0) return;
16218
16289
  const methodIndex = frameType.fields.findIndex((field) => field.name === `method`);
16219
16290
  const lineIndex = frameType.fields.findIndex((field) => field.name === `lineNumber`);
16220
- if (methodIndex === -1 || lineIndex === -1 || frameType.fields.some((field) => field.array)) return;
16291
+ if (methodIndex === -1 || lineIndex === -1 || frameType.fields.some((field) => field.array || field.kind !== FIELD_VARINT && field.kind !== FIELD_BYTE)) return;
16221
16292
  this.#stackTraceLayout = {
16222
16293
  framesField,
16223
16294
  truncatedField: type?.fields.find((field) => field.name === `truncated`),
16224
- frameFields: frameType.fields,
16225
16295
  methodIndex,
16226
16296
  lineIndex,
16227
- frameFieldKinds: frameType.fields.every((field) => field.kind === FIELD_VARINT || field.kind === FIELD_BYTE) ? Uint8Array.from(frameType.fields, (field) => field.kind) : void 0
16297
+ frameFieldKinds: Uint8Array.from(frameType.fields, (field) => field.kind)
16228
16298
  };
16229
16299
  }
16230
- #readChunkBody(chunkStart, chunkEnd) {
16300
+ #readChunkBody() {
16301
+ const chunkEnd = this.#bytes.length;
16231
16302
  const eventKinds = this.#eventKinds();
16232
16303
  const pools = /* @__PURE__ */ new Map();
16233
16304
  const rawEvents = [];
16234
16305
  const unreadableEventCounts = /* @__PURE__ */ new Map();
16235
- this.#position = chunkStart + CHUNK_HEADER_SIZE;
16306
+ this.#position = CHUNK_HEADER_SIZE;
16236
16307
  while (this.#position < chunkEnd) {
16237
16308
  const eventStart = this.#position;
16238
16309
  const size = this.#readVarint();
@@ -16338,11 +16409,9 @@ var JfrParser = class {
16338
16409
  return frames;
16339
16410
  }
16340
16411
  #readFrames(layout) {
16341
- const { frameFields, methodIndex, lineIndex, frameFieldKinds } = layout;
16342
- const length = this.#readLength(frameFields.length);
16343
- if (frameFieldKinds === void 0) return this.#readFramesGeneric(layout, length);
16412
+ const { methodIndex, lineIndex, frameFieldKinds: kinds } = layout;
16413
+ const length = this.#readLength(kinds.length);
16344
16414
  const bytes = this.#bytes;
16345
- const kinds = frameFieldKinds;
16346
16415
  const fieldCount = kinds.length;
16347
16416
  const methods = new Array(length);
16348
16417
  let leafLine = 0;
@@ -16380,30 +16449,6 @@ var JfrParser = class {
16380
16449
  truncated: false
16381
16450
  };
16382
16451
  }
16383
- /**
16384
- * Reads frames one field at a time through the generic single-value reader,
16385
- * for a frame type with a non-numeric field.
16386
- */
16387
- #readFramesGeneric({ frameFields, methodIndex, lineIndex }, length) {
16388
- const methods = [];
16389
- let leafLine = 0;
16390
- for (let i = 0; i < length; i++) {
16391
- let method = 0;
16392
- let lineNumber = 0;
16393
- for (let k = 0; k < frameFields.length; k++) {
16394
- const value = this.#readSingle(frameFields[k]);
16395
- if (k === methodIndex) method = value;
16396
- else if (k === lineIndex) lineNumber = value;
16397
- }
16398
- methods.push(method);
16399
- if (i === 0) leafLine = lineNumber;
16400
- }
16401
- return {
16402
- methods,
16403
- leafLine,
16404
- truncated: false
16405
- };
16406
- }
16407
16452
  #parseEvent(type, { kind, valueField, valueInTicks, countField, allocFamily }) {
16408
16453
  let stackKey = 0;
16409
16454
  let rawValue = 1;
@@ -16557,7 +16602,7 @@ var JfrParser = class {
16557
16602
  this.#events.push(event);
16558
16603
  }
16559
16604
  }
16560
- if (missingStackCount > 0) this.#recordTally.skipped(`event`, `referencing a missing stack trace`, missingStackCount);
16605
+ this.#recordTally.skipped(`event`, `referencing a missing stack trace`, missingStackCount);
16561
16606
  }
16562
16607
  #chunkResolver(pools) {
16563
16608
  return new ChunkResolver({
@@ -16725,7 +16770,7 @@ var UnreadableRecordError$1 = class extends Error {
16725
16770
  };
16726
16771
  const indexTypeIdsByName = (types) => {
16727
16772
  const typeIdsByName = /* @__PURE__ */ new Map();
16728
- for (const [id, type] of types) if (!typeIdsByName.has(type.name)) typeIdsByName.set(type.name, id);
16773
+ for (const [id, type] of types) typeIdsByName.set(type.name, id);
16729
16774
  return typeIdsByName;
16730
16775
  };
16731
16776
  const typesFromMetadata = (metadata) => {
@@ -19153,8 +19198,7 @@ var PerfFile = class {
19153
19198
  if (attrSize <= SECTION_SIZE) throw new FormatParseError(`attribute size leaves no room for an event attribute, got: ${attrSize}`);
19154
19199
  const count = Math.floor(section.size / attrSize);
19155
19200
  if (!count) throw new FormatParseError(`no recorded events`);
19156
- const trailingByteCount = section.size - count * attrSize;
19157
- if (trailingByteCount > 0) recordTally.skipped(`byte`, `after the last event attribute`, trailingByteCount);
19201
+ recordTally.skipped(`byte`, `after the last event attribute`, section.size - count * attrSize);
19158
19202
  const attrs = [this.#readAttr(section.offset, attrSize)];
19159
19203
  for (let index = 1; index < count; index++) attrs.push(this.#readAttr(section.offset + index * attrSize, attrSize));
19160
19204
  return attrs;
@@ -19241,7 +19285,7 @@ var PerfFile = class {
19241
19285
  features.set(feature, section);
19242
19286
  offset += SECTION_SIZE;
19243
19287
  }
19244
- if (skippedCount > 0) recordTally.skipped(`feature section`, `running past the end of the input`, skippedCount);
19288
+ recordTally.skipped(`feature section`, `running past the end of the input`, skippedCount);
19245
19289
  return features;
19246
19290
  }
19247
19291
  #section(descriptor) {
@@ -19736,8 +19780,10 @@ const metricsOf = (valueTypes) => ({
19736
19780
  * are where the frame was when sampled: the executing position in the leaf,
19737
19781
  * and the call site in a caller.
19738
19782
  *
19739
- * A location without lines is unsymbolized, and is one {@link PprofMapping}
19740
- * frame.
19783
+ * A location without lines, or whose line's function has neither a name nor a
19784
+ * file, is unsymbolized, and is one {@link PprofMapping} frame. gperftools'
19785
+ * `pprof` writes one nameless function for every address it could not
19786
+ * symbolize, so reading it as a function would merge them.
19741
19787
  *
19742
19788
  * A line whose function is absent from the table is dropped rather than
19743
19789
  * passing a reference to a missing function into aggregation. PProf.jl before
@@ -19759,7 +19805,7 @@ const parseStackFrames = (profile, string, recordTally) => {
19759
19805
  let missingFunctionLines = 0;
19760
19806
  let missingMappingLocations = 0;
19761
19807
  for (const location of profile.location) {
19762
- if (location.line.length === 0) {
19808
+ if (location.line.every(({ functionId }) => functionById.get(functionId)?.isUnsymbolized)) {
19763
19809
  const { mappingId } = location;
19764
19810
  let mapping = mappingById.get(mappingId);
19765
19811
  if (mapping === void 0) {
@@ -19799,6 +19845,9 @@ var PprofFunction = class {
19799
19845
  constructor(frame) {
19800
19846
  this.#frame = frame;
19801
19847
  }
19848
+ get isUnsymbolized() {
19849
+ return !this.#frame.name && !this.#frame.definition;
19850
+ }
19802
19851
  frameFor(executing, frames) {
19803
19852
  const lineKey = executing?.line ?? 0;
19804
19853
  let byColumn = this.#frames.get(lineKey);
@@ -19863,9 +19912,9 @@ const knownPprofLine = (line) => {
19863
19912
  * within it so an address interns without a composite key.
19864
19913
  *
19865
19914
  * A frame in a named file is named by its offset into the file, as `pprof`
19866
- * names it, because the offset is the same across runs. A frame in an anonymous mapping, such as JIT code, is named
19867
- * by its address, because the same offset into two anonymous mappings is two
19868
- * different pieces of code.
19915
+ * names it, because the offset is the same across runs. A frame in an
19916
+ * anonymous mapping, such as JIT code, is named by its address, because the
19917
+ * same offset into two anonymous mappings is two different pieces of code.
19869
19918
  */
19870
19919
  var PprofMapping = class {
19871
19920
  #source;
@@ -20015,14 +20064,9 @@ const sampledProfile = (frames, profile, recordTally) => {
20015
20064
  };
20016
20065
  function* sampledObservations(profile, frameCount, recordTally) {
20017
20066
  const sampleCount = Math.min(profile.samples.length, profile.weights.length);
20018
- let negativeWeightCount = 0;
20019
20067
  let missingFrameCount = 0;
20020
20068
  for (let index = 0; index < sampleCount; index++) {
20021
20069
  const weight = profile.weights[index];
20022
- if (weight < 0) {
20023
- negativeWeightCount++;
20024
- continue;
20025
- }
20026
20070
  const frameIndices = profile.samples[index];
20027
20071
  if (frameIndices.some((frame) => !isFrameIndex(frame, frameCount))) {
20028
20072
  missingFrameCount++;
@@ -20033,9 +20077,8 @@ function* sampledObservations(profile, frameCount, recordTally) {
20033
20077
  frameIndices: frameIndices.reverse()
20034
20078
  };
20035
20079
  }
20036
- if (missingFrameCount > 0) recordTally.skipped(`sample`, `referencing a missing frame`, missingFrameCount);
20037
- if (negativeWeightCount > 0) recordTally.skipped(`sample`, `with a negative weight`, negativeWeightCount);
20038
- if (sampleCount < profile.samples.length) recordTally.skipped(`sample`, `without a weight`, profile.samples.length - sampleCount);
20080
+ recordTally.skipped(`sample`, `referencing a missing frame`, missingFrameCount);
20081
+ recordTally.skipped(`sample`, `without a weight`, profile.samples.length - sampleCount);
20039
20082
  }
20040
20083
  const eventedProfile = (frames, profile) => {
20041
20084
  if (!Array.isArray(profile.events)) throw new FormatParseError(`events must be an array`);
@@ -20438,12 +20481,8 @@ var SystingProfileBuilder = class {
20438
20481
  };
20439
20482
  const NO_VALUES = [];
20440
20483
  const parseSystingHeader = (line) => {
20441
- const json = parseJson(line);
20442
- if (typeof json !== `object` || json === null || Array.isArray(json)) throw new FormatParseError(`header is not an object`);
20443
- const header = json;
20444
- const version = header.systing_profile_export;
20445
- if (!Number.isSafeInteger(version)) throw new FormatParseError(`header is missing the systing_profile_export version`);
20446
- if (version !== 1) throw new FormatParseError(`unsupported version ${version}, expected 1`);
20484
+ const header = parseJson(line);
20485
+ if (header?.systing_profile_export !== 1) throw new FormatParseError(`unsupported systing_profile_export, expected 1, got: ${JSON.stringify(header?.systing_profile_export)}`);
20447
20486
  const stackOrder = header.stack_order ?? `leaf_first`;
20448
20487
  if (stackOrder !== `leaf_first`) throw new FormatParseError(`unsupported stack order ${stackOrder}, expected leaf_first`);
20449
20488
  return header;
@@ -20557,8 +20596,8 @@ var TraceEventParser = class {
20557
20596
  };
20558
20597
  }
20559
20598
  #tallySkippedRecords() {
20560
- if (this.#unreadPhaseCount > 0) this.#recordTally.skipped(`event`, `in a phase this format's parser leaves unread`, this.#unreadPhaseCount);
20561
- if (this.#unbegunEndCount > 0) this.#recordTally.skipped(`end event`, `ending nothing begun`, this.#unbegunEndCount);
20599
+ this.#recordTally.skipped(`event`, `in a phase this format's parser leaves unread`, this.#unreadPhaseCount);
20600
+ this.#recordTally.skipped(`end event`, `ending nothing begun`, this.#unbegunEndCount);
20562
20601
  }
20563
20602
  /**
20564
20603
  * Names each thread and each counter series' gauge, and prefixes every name
@@ -20966,7 +21005,7 @@ function* cpuObservations(profile, idToIndex, indexToParentIndex, indexToSelfTim
20966
21005
  };
20967
21006
  }
20968
21007
  recordTally.skipped(`sample`, `referencing a missing node`, skippedSamples);
20969
- if (sampleCount < profile.samples.length) recordTally.skipped(`sample`, `without a time delta`, profile.samples.length - sampleCount);
21008
+ recordTally.skipped(`sample`, `without a time delta`, profile.samples.length - sampleCount);
20970
21009
  }
20971
21010
  function* cpuLineMetrics(profile, indexToSelfTime, recordTally) {
20972
21011
  let skippedTicks = 0;
@@ -21015,7 +21054,7 @@ const parseV8HeapProfile = (profile, recordTally) => {
21015
21054
  return [{
21016
21055
  type: `call-stack-profile`,
21017
21056
  frames: flatNodes.map(nodeToStackFrame),
21018
- metrics: [BYTES_METRIC],
21057
+ metrics: [SAMPLED_HEAP_METRIC],
21019
21058
  countMetric: SAMPLES,
21020
21059
  observations: heapObservations(profile, idToIndex, indexToParentIndex, recordTally)
21021
21060
  }];
@@ -21246,7 +21285,7 @@ const computeNodeAdjacencyGraph = ({ snapshot: { node_count: nodeCount }, nodes,
21246
21285
  nodeEdgesStartIndex += nodeEdgeCount * edgeFieldCount;
21247
21286
  }
21248
21287
  if (nodeEdgesStartIndex !== edges.length) throw new FormatParseError(`the nodes' edge counts sum to ${nodeEdgesStartIndex / edgeFieldCount} edges, got: ${totalEdgeCount}`);
21249
- if (skippedEdgeCount > 0) recordTally.skipped(`edge`, `pointing at no node`, skippedEdgeCount);
21288
+ recordTally.skipped(`edge`, `pointing at no node`, skippedEdgeCount);
21250
21289
  if (retainingEdgeCount < totalEdgeCount) {
21251
21290
  offsetToSuccessorOrdinal = offsetToSuccessorOrdinal.slice(0, retainingEdgeCount);
21252
21291
  offsetToSuccessorEdgeIndex = offsetToSuccessorEdgeIndex.slice(0, retainingEdgeCount);
@@ -21413,11 +21452,16 @@ const nodeName = (nodeOrdinal, { snapshot: { meta: { node_types: [nodeTypes] } }
21413
21452
  const name = strings[nodes[nodeIndex + fieldLayout.nodeNameOffset]] || nodeTypes[nodeType];
21414
21453
  return {
21415
21454
  name,
21416
- nameLocation: absoluteFileReference(name)
21455
+ nameLocation: CPP_QUALIFIED_NAME.test(name) ? void 0 : absoluteFileReference(name)
21417
21456
  };
21418
21457
  }
21419
21458
  }
21420
21459
  };
21460
+ /**
21461
+ * A C++ class name such as `modulemap::Entry`, which also parses as a URL with
21462
+ * the scheme `modulemap:`.
21463
+ */
21464
+ const CPP_QUALIFIED_NAME = /^[^/]*::/u;
21421
21465
  const formatString = (string) => {
21422
21466
  if (string.length > MAX_STRING_LENGTH) string = `${string.slice(0, MAX_STRING_LENGTH - 1)}…`;
21423
21467
  return string.replaceAll(`\n`, String.raw`\n`);
@@ -21444,7 +21488,7 @@ const v8HeapSnapshotFormatSpec = {
21444
21488
  const matchesWebKitTimelineRecording = (json) => {
21445
21489
  if (typeof json !== `object` || json === null) return false;
21446
21490
  const object = json;
21447
- if (object.version !== 1) return false;
21491
+ if (typeof object.version !== `number`) return false;
21448
21492
  if (typeof object.recording !== `object` || object.recording === null) return false;
21449
21493
  const recording = object.recording;
21450
21494
  if (Array.isArray(recording.samples)) {
@@ -21479,7 +21523,7 @@ const parseWebKitTimelineRecording = ({ recording: { samples, sampleStackTraces,
21479
21523
  });
21480
21524
  }
21481
21525
  }
21482
- if (skippedSamples > 0) recordTally.skipped(`sample`, `without a duration`, skippedSamples);
21526
+ recordTally.skipped(`sample`, `without a duration`, skippedSamples);
21483
21527
  return [{
21484
21528
  type: `call-stack-profile`,
21485
21529
  frames,
@@ -22104,17 +22148,9 @@ const binaryFormatSpecs = formatSpecs.filter((formatSpec) => formatSpec.type ===
22104
22148
  /**
22105
22149
  * Runs a format spec's detection and parse, recording a rejection instead of
22106
22150
  * throwing when the input matches the format but fails to parse.
22107
- *
22108
- * A `matches` that throws counts as no match, because it is a cheap prefilter
22109
- * that never validates the input.
22110
22151
  */
22111
22152
  const detectWithFormatSpec = (formatSpec, input, rejections, { logger }) => {
22112
- try {
22113
- if (!formatSpec.matches(input)) return;
22114
- } catch (error) {
22115
- logger.debug?.(`skipped ${formatSpec.id} because its detection threw: ${reasonOf(error)}`);
22116
- return;
22117
- }
22153
+ if (!formatSpec.matches(input)) return;
22118
22154
  try {
22119
22155
  return runParse(formatSpec, (recordTally) => formatSpec.parse(input, recordTally));
22120
22156
  } catch (error) {
@@ -22379,7 +22415,7 @@ const logFormat = (format, evidence, { logger }) => {
22379
22415
 
22380
22416
  // package.json
22381
22417
  var name = "profiler-md";
22382
- var version = "0.9.0";
22418
+ var version = "0.9.1";
22383
22419
  var description = "Converts performance profiles to human and LLM friendly Markdown.";
22384
22420
  var homepage = "https://github.com/TomerAberbach/profiler-md";
22385
22421
  var bugs = { "url": "https://github.com/TomerAberbach/profiler-md/issues" };
@@ -23305,60 +23341,159 @@ const WRITE_ERROR_REASONS = /* @__PURE__ */ new Map([
23305
23341
  const highlightMarkdown = async (markdown, { outputPath }) => {
23306
23342
  const ansis = makeAnsis({ isTTY: isTTYOutput(outputPath) });
23307
23343
  if (!ansis.isSupported()) return markdown;
23308
- const [highlighter, lineToIntensity] = await Promise.all([getHighlighter(), computeLineToIntensity(markdown)]);
23309
- const { tokens, fg } = highlighter.codeToTokens(markdown, {
23344
+ const [shiki, root] = await Promise.all([loadShiki(), parseMarkdown(markdown)]);
23345
+ const highlighter = getHighlighter(fenceLanguagesOf(root), shiki);
23346
+ const lineToIntensity = computeLineToIntensity(root);
23347
+ const { tokens, fg } = (await highlighter).codeToTokens(markdown, {
23310
23348
  lang: `markdown`,
23311
23349
  theme: `kindling`
23312
23350
  });
23313
23351
  return renderTokens(tokens, fg, lineToIntensity, ansis);
23314
23352
  };
23315
- const getHighlighter = () => highlighterPromise ??= createHighlighterCore();
23316
- let highlighterPromise = null;
23317
- const createHighlighterCore = async () => {
23318
- const markdown = import(`@shikijs/langs/markdown`);
23319
- const c = import(`@shikijs/langs/c`);
23320
- const go = import(`@shikijs/langs/go`);
23321
- const java = import(`@shikijs/langs/java`);
23322
- const js = import(`@shikijs/langs/js`);
23323
- const python = import(`@shikijs/langs/python`);
23324
- const rust = import(`@shikijs/langs/rust`);
23325
- const sh = import(`@shikijs/langs/sh`);
23326
- const toml = import(`@shikijs/langs/toml`);
23327
- const shikiCore = import(`@shikijs/core`);
23328
- const onigurumaEngine = import(`@shikijs/engine-oniguruma`);
23329
- const onigurumaEngineWasm = import(`@shikijs/engine-oniguruma/wasm-inlined`);
23330
- return (await shikiCore).createHighlighterCore({
23331
- langs: [
23332
- markdown,
23333
- c,
23334
- go,
23335
- java,
23336
- js,
23337
- python,
23338
- rust,
23339
- sh,
23340
- toml
23341
- ],
23342
- themes: [kindlingTheme],
23343
- engine: (await onigurumaEngine).createOnigurumaEngine(onigurumaEngineWasm)
23344
- });
23345
- };
23346
23353
  /**
23347
- * Recovers heat intensities by re-parsing the Markdown (which profiler-md
23348
- * itself serialized) with the inverse of the serializer, so escaped content
23349
- * (`\|`, variable-length code fences, etc.) decodes back to the original name
23350
- * and location strings and heading ↔ table keys agree by construction.
23354
+ * Parses Markdown that profiler-md itself serialized with the inverse of the
23355
+ * serializer, so escaped content (`\|`, variable-length code fences, etc.)
23356
+ * decodes back to the original strings.
23351
23357
  */
23352
- const computeLineToIntensity = async (markdown) => {
23358
+ const parseMarkdown = async (markdown) => {
23353
23359
  const [{ fromMarkdown }, { gfmTableFromMarkdown }, { gfmTable }] = await Promise.all([
23354
23360
  import(`mdast-util-from-markdown`),
23355
23361
  import(`mdast-util-gfm-table`),
23356
23362
  import(`micromark-extension-gfm-table`)
23357
23363
  ]);
23358
- const root = fromMarkdown(markdown, {
23364
+ return fromMarkdown(markdown, {
23359
23365
  extensions: [gfmTable()],
23360
23366
  mdastExtensions: [gfmTableFromMarkdown()]
23361
23367
  });
23368
+ };
23369
+ const getHighlighter = (fenceLanguages, shiki) => {
23370
+ const key = fenceLanguages.join(` `);
23371
+ let highlighter = languagesToHighlighter.get(key);
23372
+ if (highlighter === void 0) {
23373
+ highlighter = createHighlighterCore(fenceLanguages, shiki);
23374
+ languagesToHighlighter.set(key, highlighter);
23375
+ }
23376
+ return highlighter;
23377
+ };
23378
+ /**
23379
+ * Highlighters keyed by their sorted fence languages. A highlighter is never
23380
+ * extended with a language after it is created, because the Markdown grammar's
23381
+ * fence rules are fixed when it loads.
23382
+ */
23383
+ const languagesToHighlighter = /* @__PURE__ */ new Map();
23384
+ /** The sorted languages of {@link root}'s code fences that have a grammar. */
23385
+ const fenceLanguagesOf = (root) => {
23386
+ const languages = /* @__PURE__ */ new Set();
23387
+ const visit = (node) => {
23388
+ if (node.type === `code`) {
23389
+ if (node.lang && FENCE_LANGUAGES.has(node.lang)) languages.add(node.lang);
23390
+ } else if (FENCE_CONTAINER_TYPES.has(node.type)) for (const child of node.children) visit(child);
23391
+ };
23392
+ visit(root);
23393
+ return [...languages].sort();
23394
+ };
23395
+ /** The node types that can contain a code fence. */
23396
+ const FENCE_CONTAINER_TYPES = /* @__PURE__ */ new Set([
23397
+ `root`,
23398
+ `blockquote`,
23399
+ `list`,
23400
+ `listItem`
23401
+ ]);
23402
+ /**
23403
+ * Loads the modules every highlighter requires, so the load can start before
23404
+ * the fence languages are known.
23405
+ */
23406
+ const loadShiki = () => shikiPromise ??= importShiki();
23407
+ let shikiPromise = null;
23408
+ const importShiki = async () => {
23409
+ const [shikiCore, onigurumaEngine, onigurumaEngineWasm, markdown] = await Promise.all([
23410
+ import(`@shikijs/core`),
23411
+ import(`@shikijs/engine-oniguruma`),
23412
+ import(`@shikijs/engine-oniguruma/wasm-inlined`),
23413
+ import(`@shikijs/langs/markdown`)
23414
+ ]);
23415
+ return {
23416
+ shikiCore,
23417
+ onigurumaEngine,
23418
+ onigurumaEngineWasm,
23419
+ markdown
23420
+ };
23421
+ };
23422
+ const createHighlighterCore = async (fenceLanguages, { shikiCore, onigurumaEngine, onigurumaEngineWasm, markdown }) => {
23423
+ const grammars = await Promise.all(fenceLanguages.map((language) => FENCE_LANGUAGES.get(language)()));
23424
+ const fenceRules = fenceLanguages.map((language, i) => fenceRule(language, grammars[i].default.at(-1).scopeName));
23425
+ return shikiCore.createHighlighterCore({
23426
+ langs: [withFenceRules(markdown.default[0], fenceRules), ...grammars.flatMap(({ default: grammar }) => grammar.filter(({ scopeName }) => scopeName !== MARKDOWN_SCOPE_NAME))],
23427
+ themes: [kindlingTheme],
23428
+ engine: onigurumaEngine.createOnigurumaEngine(onigurumaEngineWasm),
23429
+ warnings: false
23430
+ });
23431
+ };
23432
+ const MARKDOWN_SCOPE_NAME = `text.html.markdown`;
23433
+ /**
23434
+ * The grammar of each code fence language the docs use, keyed as a fence
23435
+ * writes the language.
23436
+ */
23437
+ const FENCE_LANGUAGES = /* @__PURE__ */ new Map([
23438
+ [`c`, () => import(`@shikijs/langs/c`)],
23439
+ [`elixir`, () => import(`@shikijs/langs/elixir`)],
23440
+ [`erlang`, () => import(`@shikijs/langs/erlang`)],
23441
+ [`fortran`, () => import(`@shikijs/langs/fortran-free-form`)],
23442
+ [`go`, () => import(`@shikijs/langs/go`)],
23443
+ [`java`, () => import(`@shikijs/langs/java`)],
23444
+ [`js`, () => import(`@shikijs/langs/js`)],
23445
+ [`julia`, () => import(`@shikijs/langs/julia`)],
23446
+ [`php`, () => import(`@shikijs/langs/php`)],
23447
+ [`rust`, () => import(`@shikijs/langs/rust`)],
23448
+ [`sh`, () => import(`@shikijs/langs/sh`)],
23449
+ [`swift`, () => import(`@shikijs/langs/swift`)],
23450
+ [`toml`, () => import(`@shikijs/langs/toml`)],
23451
+ [`zig`, () => import(`@shikijs/langs/zig`)]
23452
+ ]);
23453
+ /**
23454
+ * A copy of the Markdown grammar {@link markdown} that tries
23455
+ * {@link fenceRules} before its own fence rules, which cover only some
23456
+ * languages.
23457
+ *
23458
+ * Shiki can also inject a rule into a grammar, but it discards the Markdown
23459
+ * grammar's injections when it reloads that grammar for a lazily embedded
23460
+ * language.
23461
+ */
23462
+ const withFenceRules = (markdown, fenceRules) => {
23463
+ const repository = { ...markdown.repository };
23464
+ repository.fenced_code_block = { patterns: [...fenceRules, ...repository.fenced_code_block.patterns] };
23465
+ return {
23466
+ ...markdown,
23467
+ repository
23468
+ };
23469
+ };
23470
+ /**
23471
+ * A fence rule for {@link language} embedding {@link scopeName}, written like
23472
+ * the Markdown grammar's own fence rules.
23473
+ */
23474
+ const fenceRule = (language, scopeName) => ({
23475
+ begin: `(^|\\G)(\\s*)(\`{3,}|~{3,})\\s*(?i:(${language})((\\s+|[,:?{])[^\`]*)?$)`,
23476
+ beginCaptures: {
23477
+ 3: { name: `punctuation.definition.markdown` },
23478
+ 4: { name: `fenced_code.block.language.markdown` },
23479
+ 5: { name: `fenced_code.block.language.attributes.markdown` }
23480
+ },
23481
+ end: String.raw`(^|\G)(\2|\s{0,3})(\3)\s*$`,
23482
+ endCaptures: { 3: { name: `punctuation.definition.markdown` } },
23483
+ name: `markup.fenced_code.block.markdown`,
23484
+ patterns: [{
23485
+ begin: String.raw`(^|\G)(\s*)(.*)`,
23486
+ contentName: `meta.embedded.block.${language}`,
23487
+ patterns: [{ include: scopeName }],
23488
+ while: `(^|\\G)(?!\\s*([\`~]{3,})\\s*$)`
23489
+ }]
23490
+ });
23491
+ /**
23492
+ * Recovers heat intensities from the parsed Markdown, whose escaped content
23493
+ * decodes back to the original name and location strings, so heading ↔ table
23494
+ * keys agree by construction.
23495
+ */
23496
+ const computeLineToIntensity = (root) => {
23362
23497
  const lineToIntensity = /* @__PURE__ */ new Map();
23363
23498
  const sections = [];
23364
23499
  const unranked = {
@@ -23672,7 +23807,6 @@ const renderToken = (token, themeFg, intensity, ansis) => {
23672
23807
  if (token.fontStyle & FONT_STYLE_BOLD) styled = ansis.bold(styled);
23673
23808
  if (token.fontStyle & FONT_STYLE_ITALIC) styled = ansis.italic(styled);
23674
23809
  if (token.fontStyle & FONT_STYLE_UNDERLINE) styled = ansis.underline(styled);
23675
- if (token.fontStyle & FONT_STYLE_STRIKETHROUGH) styled = ansis.strikethrough(styled);
23676
23810
  }
23677
23811
  return styled;
23678
23812
  };
@@ -23689,7 +23823,6 @@ const tintCool = ({ red, green, blue }, intensity) => ({
23689
23823
  const FONT_STYLE_ITALIC = 1;
23690
23824
  const FONT_STYLE_BOLD = 2;
23691
23825
  const FONT_STYLE_UNDERLINE = 4;
23692
- const FONT_STYLE_STRIKETHROUGH = 8;
23693
23826
 
23694
23827
  // src/cli/languages.ts
23695
23828
  const languages = new Map(languageMetas.map(([id, meta]) => [id, {
@@ -24165,14 +24298,14 @@ const parseSourceMap = (content, path, logger) => {
24165
24298
  return sourceMap;
24166
24299
  };
24167
24300
  /**
24168
- * Pre-resolves relative source paths against the map file's directory so that
24301
+ * Pre-resolves relative source paths against the map file's path so that
24169
24302
  * `source-map-js` returns absolute URLs.
24170
24303
  */
24171
24304
  const resolveSourceMapSources = (sourceMap, path) => {
24172
24305
  if (sourceMap.sourceRoot) return sourceMap;
24173
24306
  return {
24174
24307
  ...sourceMap,
24175
- sources: sourceMap.sources.map((source) => absoluteFileReference(source) ? source : new URL(source, pathToFileURL(resolve(dirname(path)))).href)
24308
+ sources: sourceMap.sources.map((source) => absoluteFileReference(source) ? source : new URL(source, pathToFileURL(resolve(path))).href)
24176
24309
  };
24177
24310
  };
24178
24311