profiler-md 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,17 +1,20 @@
1
1
  #!/usr/bin/env node
2
- import { createWriteStream } from "node:fs";
3
- import { glob, readFile } from "node:fs/promises";
4
- import { dirname, resolve } from "node:path";
5
- import { pathToFileURL } from "node:url";
6
- import { promisify } from "node:util";
7
- import { brotliDecompress, gunzip } from "node:zlib";
8
2
  import meow from "meow";
9
- import picomatch from "picomatch";
10
3
  import { Profile } from "pprof-format";
11
4
  import { SourceMapConsumer } from "source-map-js";
12
5
  import plur from "plur";
13
6
  import prettyBytes from "pretty-bytes";
14
7
  import prettyMilliseconds from "pretty-ms";
8
+ import { glob, readFile } from "node:fs/promises";
9
+ import { Ansis } from "ansis";
10
+ import { createWriteStream } from "node:fs";
11
+ import { spawn } from "node:child_process";
12
+ import { promisify } from "node:util";
13
+ import { brotliDecompress, gunzip } from "node:zlib";
14
+ import { dirname, resolve } from "node:path";
15
+ import { pathToFileURL } from "node:url";
16
+ import convertSourceMap from "convert-source-map";
17
+ import picomatch from "picomatch";
15
18
 
16
19
  //#region src/helpers/array.ts
17
20
  /**
@@ -1008,13 +1011,8 @@ const detectPprof = (data) => {
1008
1011
  * It is assumed that {@link data} is a valid pprof (raw protobuf). The behavior
1009
1012
  * of this function is undefined for invalid profiles.
1010
1013
  *
1011
- * pprof can be generated by many tools, including:
1012
- * - Go's [`runtime/pprof`](https://pkg.go.dev/runtime/pprof) package
1013
- * - Node.js's [`pprof`](https://www.npmjs.com/package/pprof) npm package
1014
- * - Python's [`py-spy`](https://github.com/benfred/py-spy)
1015
- * - Rust's [`pprof-rs`](https://github.com/tikv/pprof-rs)
1016
- * - Java/Kotlin's [`async-profiler`](https://github.com/async-profiler/async-profiler)
1017
- * - C/C++'s [`gperftools`](https://github.com/gperftools/gperftools) (via `pprof --proto`)
1014
+ * See the [pprof docs](https://github.com/TomerAberbach/profiler-md/blob/main/docs/formats/pprof.md)
1015
+ * for supported tools and generation instructions (`profiler-md --help pprof`).
1018
1016
  */
1019
1017
  const pprofToMd = (data, options) => pprofToMdInternal(parsePprof(data), options);
1020
1018
  const pprofToMdInternal = (pprof, options) => {
@@ -1109,18 +1107,14 @@ const detectSpeedscopeProfile = (json) => {
1109
1107
  return json;
1110
1108
  };
1111
1109
  /**
1112
- * Converts the given speedscope profile to Markdown.
1110
+ * Converts the given Speedscope profile to Markdown.
1113
1111
  *
1114
- * It is assumed that {@link data} is a valid speedscope JSON file. The behavior
1112
+ * It is assumed that {@link data} is a valid Speedscope JSON file. The behavior
1115
1113
  * of this function is undefined for invalid profiles.
1116
1114
  *
1117
- * Speedscope profiles can be generated by many tools, including:
1118
- * - [speedscope](https://www.speedscope.app) (drag and drop any supported profile)
1119
- * - [rbspy](https://rbspy.github.io) for Ruby
1120
- * - [py-spy](https://github.com/benfred/py-spy) for Python (`--format speedscope`)
1121
- * - [pprof-rs](https://github.com/tikv/pprof-rs) for Rust
1122
- * - [async-profiler](https://github.com/async-profiler/async-profiler) for Java/Kotlin (`-o speedscope`)
1123
- * - [phpspy](https://github.com/adsr/phpspy) for PHP (`--output-format=speedscope`)
1115
+ * See the [Speedscope docs](https://github.com/TomerAberbach/profiler-md/blob/main/docs/formats/speedscope.md)
1116
+ * for supported tools and generation instructions
1117
+ * (`profiler-md --help speedscope`).
1124
1118
  */
1125
1119
  const speedscopeProfileToMd = (data, options) => speedscopeProfileToMdInternal(parseSpeedscopeProfile(data), options);
1126
1120
  const speedscopeProfileToMdInternal = (profile, options) => {
@@ -1220,19 +1214,9 @@ const detectV8CpuProfile = (json) => {
1220
1214
  * It is assumed that {@link data} is a valid profile. The behavior of this
1221
1215
  * function is undefined for invalid profiles.
1222
1216
  *
1223
- * You can generate a V8 CPU profile in several ways:
1224
- * - [`node --cpu-prof`](https://nodejs.org/api/cli.html#cpu-prof)
1225
- * - [`deno run --cpu-prof`](https://docs.deno.com/runtime/fundamentals/debugging/#cpu-profiling)
1226
- * - [`bun --cpu-prof`](https://bun.com/docs/project/benchmarking#cpu-profiling)
1227
- * (NOTE: output was incorrect until
1228
- * [v1.3.13](https://bun.com/blog/bun-v1.3.13#node-js-compatibility-improvements))
1229
- * - [`node --inspect`](https://nodejs.org/api/debugger.html#v8-inspector-integration-for-nodejs),
1230
- * [`deno run --inspect`](https://docs.deno.com/runtime/fundamentals/debugging/#--inspect),
1231
- * or [`bun --inspect`](https://bun.com/docs/runtime/debugger#inspect) with
1232
- * [Chrome DevTools](https://developer.chrome.com/docs/devtools/performance/nodejs)
1233
- * - [Chrome DevTools directly](https://developer.chrome.com/docs/devtools/performance#record)
1234
- *
1235
- * Lower the sampling interval to capture more granular data.
1217
+ * See the [V8 CPU profile docs](https://github.com/TomerAberbach/profiler-md/blob/main/docs/formats/v8-cpu-profile.md)
1218
+ * for supported runtimes and generation instructions
1219
+ * (`profiler-md --help v8-cpu-profile`).
1236
1220
  */
1237
1221
  const v8CpuProfileToMd = (data, options) => v8CpuProfileToMdInternal(parseV8CpuProfile(data), options);
1238
1222
  const v8CpuProfileToMdInternal = (profile, options) => {
@@ -1308,16 +1292,9 @@ const detectV8HeapProfile = (json) => {
1308
1292
  * It is assumed that {@link data} is a valid profile. The behavior of this
1309
1293
  * function is undefined for invalid profiles.
1310
1294
  *
1311
- * You can generate a V8 heap profile in several ways:
1312
- * - [`node --heap-prof`](https://nodejs.org/api/cli.html#--heap-prof)
1313
- * - [`node --inspect`](https://nodejs.org/api/debugger.html#v8-inspector-integration-for-nodejs),
1314
- * [`deno run --inspect`](https://docs.deno.com/runtime/fundamentals/debugging/#--inspect),
1315
- * or [`bun --inspect`](https://bun.com/docs/runtime/debugger#inspect) with
1316
- * [Chrome DevTools](https://developer.chrome.com/docs/devtools/memory-problems/allocation-profiler)
1317
- * - [Chrome DevTools directly](https://developer.chrome.com/docs/devtools/memory-problems/allocation-profiler)
1318
- *
1319
- * Note that [`bun --heap-prof`](https://bun.com/docs/project/benchmarking#heap-profiling)
1320
- * generates a heap _snapshot_ on exit, not a heap _profile_.
1295
+ * See the [V8 heap profile docs](https://github.com/TomerAberbach/profiler-md/blob/main/docs/formats/v8-heap-profile.md)
1296
+ * for supported runtimes and generation instructions
1297
+ * (`profiler-md --help v8-heap-profile`).
1321
1298
  */
1322
1299
  const v8HeapProfileToMd = (data, options) => v8HeapProfileToMdInternal(parseV8HeapProfile(data), options);
1323
1300
  const v8HeapProfileToMdInternal = (profile, options) => {
@@ -2136,16 +2113,9 @@ const detectV8HeapSnapshot = (json) => {
2136
2113
  * It is assumed that {@link data} is a valid snapshot. The behavior of this
2137
2114
  * function is undefined for invalid snapshots.
2138
2115
  *
2139
- * You can generate a V8 heap snapshot in several ways:
2140
- * - [`node --heapsnapshot-near-heap-limit=1`](https://nodejs.org/api/cli.html#heapsnapshot-near-heap-limitmax-count)
2141
- * - [`node --heapsnapshot-signal`](https://nodejs.org/api/cli.html#--heapsnapshot-signalsignal)
2142
- * - [`bun --heap-prof`](https://bun.com/docs/project/benchmarking#heap-profiling)
2143
- * - [`v8.writeHeapSnapshot()`](https://nodejs.org/api/v8.html#v8writeheapsnapshotfilename)
2144
- * - [`node --inspect`](https://nodejs.org/api/debugger.html#v8-inspector-integration-for-nodejs),
2145
- * [`deno run --inspect`](https://docs.deno.com/runtime/fundamentals/debugging/#--inspect),
2146
- * or [`bun --inspect`](https://bun.com/docs/runtime/debugger#inspect) with
2147
- * [Chrome DevTools](https://developer.chrome.com/docs/devtools/memory-problems/heap-snapshots)
2148
- * - [Chrome DevTools directly](https://developer.chrome.com/docs/devtools/memory-problems/heap-snapshots)
2116
+ * See the [V8 heap snapshot docs](https://github.com/TomerAberbach/profiler-md/blob/main/docs/formats/v8-heap-snapshot.md)
2117
+ * for supported runtimes and generation instructions
2118
+ * (`profiler-md --help v8-heap-snapshot`).
2149
2119
  */
2150
2120
  const v8HeapSnapshotToMd = (data, options) => v8HeapSnapshotToMdInternal(parseV8HeapSnapshot(data), options);
2151
2121
  const v8HeapSnapshotToMdInternal = (snapshot, options) => {
@@ -2154,61 +2124,178 @@ const v8HeapSnapshotToMdInternal = (snapshot, options) => {
2154
2124
  };
2155
2125
 
2156
2126
  //#endregion
2157
- //#region src/cli.ts
2158
- const jsonProfileConverters = [
2159
- {
2160
- type: `speedscope`,
2127
+ //#region src/cli/formats.ts
2128
+ const languages = new Map([
2129
+ [`c`, {
2130
+ name: `C`,
2131
+ formats: [`pprof`],
2132
+ aliases: [{
2133
+ id: `cpp`,
2134
+ name: `C++`
2135
+ }]
2136
+ }],
2137
+ [`go`, {
2138
+ name: `Go`,
2139
+ formats: [`pprof`]
2140
+ }],
2141
+ [`java`, {
2142
+ name: `Java`,
2143
+ formats: [`pprof`, `speedscope`],
2144
+ aliases: [{
2145
+ id: `kotlin`,
2146
+ name: `Kotlin`
2147
+ }]
2148
+ }],
2149
+ [`javascript`, {
2150
+ name: `JavaScript`,
2151
+ formats: [
2152
+ `v8-cpu-profile`,
2153
+ `v8-heap-profile`,
2154
+ `v8-heap-snapshot`,
2155
+ `pprof`,
2156
+ `speedscope`
2157
+ ],
2158
+ examples: {
2159
+ "v8-cpu-profile": [
2160
+ {
2161
+ filename: `node.cpuprofile`,
2162
+ label: `Node.js`
2163
+ },
2164
+ {
2165
+ filename: `deno.cpuprofile`,
2166
+ label: `Deno`
2167
+ },
2168
+ {
2169
+ filename: `bun.cpuprofile`,
2170
+ label: `Bun`
2171
+ }
2172
+ ],
2173
+ "v8-heap-profile": [{
2174
+ filename: `node.heapprofile`,
2175
+ label: `Node.js`
2176
+ }],
2177
+ "v8-heap-snapshot": [{
2178
+ filename: `node.heapsnapshot`,
2179
+ label: `Node.js`
2180
+ }],
2181
+ pprof: [{
2182
+ filename: `node.pprof`,
2183
+ label: `Node.js`
2184
+ }],
2185
+ speedscope: [{
2186
+ filename: `node.speedscope.json`,
2187
+ label: `Node.js`
2188
+ }]
2189
+ },
2190
+ aliases: [{
2191
+ id: `typescript`,
2192
+ name: `TypeScript`
2193
+ }]
2194
+ }],
2195
+ [`php`, {
2196
+ name: `PHP`,
2197
+ formats: [`speedscope`]
2198
+ }],
2199
+ [`python`, {
2200
+ name: `Python`,
2201
+ formats: [`pprof`, `speedscope`]
2202
+ }],
2203
+ [`ruby`, {
2204
+ name: `Ruby`,
2205
+ formats: [`speedscope`]
2206
+ }],
2207
+ [`rust`, {
2208
+ name: `Rust`,
2209
+ formats: [`pprof`, `speedscope`],
2210
+ examples: { pprof: [{
2211
+ filename: `rust1.pprof`,
2212
+ label: `1`
2213
+ }, {
2214
+ filename: `rust2.pprof`,
2215
+ label: `2`
2216
+ }] }
2217
+ }]
2218
+ ]);
2219
+ const languageAliasToPrimary = new Map([...languages.entries()].flatMap(([primaryId, { aliases }]) => aliases?.map(({ id }) => [id, primaryId]) ?? []));
2220
+ const formats = new Map([
2221
+ [`speedscope`, {
2222
+ name: `Speedscope`,
2223
+ kind: `json`,
2161
2224
  detect: detectSpeedscopeProfile,
2162
2225
  toMdInternal: speedscopeProfileToMdInternal,
2163
2226
  toMd: speedscopeProfileToMd
2164
- },
2165
- {
2166
- type: `v8-cpu-profile`,
2227
+ }],
2228
+ [`v8-cpu-profile`, {
2229
+ name: `V8 CPU profile`,
2230
+ kind: `json`,
2167
2231
  detect: detectV8CpuProfile,
2168
2232
  toMdInternal: v8CpuProfileToMdInternal,
2169
2233
  toMd: v8CpuProfileToMd
2170
- },
2171
- {
2172
- type: `v8-heap-profile`,
2234
+ }],
2235
+ [`v8-heap-profile`, {
2236
+ name: `V8 heap profile`,
2237
+ kind: `json`,
2173
2238
  detect: detectV8HeapProfile,
2174
2239
  toMdInternal: v8HeapProfileToMdInternal,
2175
2240
  toMd: v8HeapProfileToMd
2176
- },
2177
- {
2178
- type: `v8-heap-snapshot`,
2241
+ }],
2242
+ [`v8-heap-snapshot`, {
2243
+ name: `V8 heap snapshot`,
2244
+ kind: `json`,
2179
2245
  detect: detectV8HeapSnapshot,
2180
2246
  toMdInternal: v8HeapSnapshotToMdInternal,
2181
2247
  toMd: v8HeapSnapshotToMd
2182
- }
2183
- ];
2184
- const binaryProfileConverters = [{
2185
- type: `pprof`,
2186
- detect: detectPprof,
2187
- toMdInternal: pprofToMdInternal,
2188
- toMd: pprofToMd
2189
- }];
2190
- const profileConverters = [...jsonProfileConverters, ...binaryProfileConverters];
2248
+ }],
2249
+ [`pprof`, {
2250
+ name: `pprof`,
2251
+ kind: `binary`,
2252
+ detect: detectPprof,
2253
+ toMdInternal: pprofToMdInternal,
2254
+ toMd: pprofToMd
2255
+ }]
2256
+ ]);
2257
+
2258
+ //#endregion
2259
+ //#region src/cli/cli.ts
2260
+ const formatTopics = [...formats.keys()];
2261
+ const languageTopics = [...languages.entries()].flatMap(([id, { aliases }]) => [id, ...aliases?.map((alias) => alias.id) ?? []]);
2262
+ const topics = [...formatTopics, ...languageTopics];
2191
2263
  const cli = meow(`
2192
2264
  Usage: profiler-md [options] [file]
2265
+ profiler-md --help [format|language]
2193
2266
 
2194
2267
  Options:
2195
- -t, --type <type> Profile type, auto-detected from content if omitted
2196
- [${profileConverters.map(({ type }) => type).sort().join(`|`)}]
2268
+ -f, --format <format> Profile format, auto-detected from content if omitted
2197
2269
  -o, --output <file> Output file (default: - for stdout)
2198
2270
  --top-n <n> Number of top entries to show (default: 20)
2199
2271
  --cwd <path> Working directory for relative file paths in output
2200
2272
  --third-party <glob> Mark URLs matching this glob as third-party
2201
2273
  (repeatable; default: node_modules)
2202
2274
  --source-maps <glob> Apply source maps matching this glob to profile
2203
- locations (repeatable)
2204
- --help Show this help message
2275
+ locations; files may be source map JSON or contain
2276
+ inline source map comments (repeatable)
2277
+ --no-pager Disable paging of stdout output (default: paged when
2278
+ stdout is a TTY, using $PAGER or less)
2279
+ --color, --no-color Force-enable or force-disable ANSI syntax highlighting
2280
+ (default: auto, on when stdout is a TTY; honors
2281
+ NO_COLOR and FORCE_COLOR)
2282
+ --help [format|language] Show this help message or topic docs
2283
+
2284
+ Formats: ${formatTopics.join(`, `)}
2285
+ Languages: ${languageTopics.join(`, `)}
2205
2286
  `, {
2206
2287
  importMeta: import.meta,
2288
+ autoHelp: false,
2207
2289
  allowUnknownFlags: false,
2290
+ booleanDefault: void 0,
2208
2291
  flags: {
2209
- type: {
2292
+ help: {
2293
+ type: `boolean`,
2294
+ shortFlag: `h`
2295
+ },
2296
+ format: {
2210
2297
  type: `string`,
2211
- shortFlag: `t`
2298
+ shortFlag: `f`
2212
2299
  },
2213
2300
  output: {
2214
2301
  type: `string`,
@@ -2226,108 +2313,651 @@ const cli = meow(`
2226
2313
  type: `string`,
2227
2314
  isMultiple: true,
2228
2315
  default: []
2229
- }
2316
+ },
2317
+ pager: {
2318
+ type: `boolean`,
2319
+ default: true
2320
+ },
2321
+ color: { type: `boolean` }
2230
2322
  }
2231
2323
  });
2232
- const gunzipAsync = promisify(gunzip);
2233
- const brotliDecompressAsync = promisify(brotliDecompress);
2234
- const decompressData = async (data, filePath) => {
2235
- if (filePath?.endsWith(`.br`)) return brotliDecompressAsync(data);
2236
- if (data[0] === 31 && data[1] === 139) return gunzipAsync(data);
2237
- return data;
2324
+
2325
+ //#endregion
2326
+ //#region src/cli/error.ts
2327
+ var CliError = class extends Error {
2328
+ exitCode;
2329
+ constructor(message, exitCode) {
2330
+ super(message);
2331
+ this.name = "CliError";
2332
+ this.exitCode = exitCode;
2333
+ }
2238
2334
  };
2239
- try {
2240
- const { input: [filePath], flags: { output: outputPath, type: profileType, topN, cwd, thirdParty, sourceMaps: sourceMapPatterns } } = cli;
2241
- let forcedProfileConverter;
2242
- if (profileType !== void 0) {
2243
- forcedProfileConverter = profileConverters.find((format) => format.type === profileType);
2244
- if (!forcedProfileConverter) {
2245
- process.stderr.write(`error: unknown profile type "${profileType}"\nRun with --help to see supported types.\n`);
2246
- process.exit(2);
2247
- }
2248
- } else if (!filePath && process.stdin.isTTY) {
2249
- cli.showHelp(0);
2250
- process.exit(0);
2335
+ const reportError = (error) => {
2336
+ if (error instanceof CliError) {
2337
+ process.stderr.write(`error: ${error.message}\n`);
2338
+ process.exit(error.exitCode);
2251
2339
  }
2252
- let data;
2253
- if (filePath) try {
2254
- data = await readFile(filePath);
2255
- } catch (error) {
2256
- const message = error instanceof Error ? error.message : String(error);
2257
- process.stderr.write(`error: ${message}\n`);
2340
+ if (error instanceof Error) {
2341
+ process.stderr.write(`error: ${error.message}\n`);
2342
+ if (error.stack) process.stderr.write(`${error.stack}\n`);
2258
2343
  process.exit(1);
2259
2344
  }
2260
- else data = Buffer.concat(await Array.fromAsync(process.stdin));
2345
+ process.stderr.write(`error: ${String(error)}\n`);
2346
+ process.exit(1);
2347
+ };
2348
+
2349
+ //#endregion
2350
+ //#region src/cli/convert.ts
2351
+ const jsonFormats = [...formats.entries()].filter((entry) => entry[1].kind === `json`);
2352
+ const binaryFormats = [...formats.entries()].filter((entry) => entry[1].kind === `binary`);
2353
+ const requireFormat = (formatId) => {
2354
+ const format = formats.get(formatId);
2355
+ if (!format) throw new CliError(`unknown format "${formatId}"\nRun with --help to see supported formats.`, 2);
2356
+ return format;
2357
+ };
2358
+ const convertToMarkdown = (data, forcedFormat, options) => {
2359
+ if (forcedFormat) return forcedFormat.toMd(data, options);
2360
+ const markdown = autoDetectAndConvert(data, options);
2361
+ if (markdown === void 0) throw new CliError(`could not detect profile format from content\nUse --format to specify the format, or run with --help to see supported formats.`, 2);
2362
+ return markdown;
2363
+ };
2364
+ const autoDetectAndConvert = (data, options) => {
2365
+ let json;
2261
2366
  try {
2262
- data = await decompressData(data, filePath);
2263
- } catch (error) {
2264
- const message = error instanceof Error ? error.message : String(error);
2265
- process.stderr.write(`error: failed to decompress input: ${message}\n`);
2266
- process.exit(1);
2367
+ json = parseJson(data);
2368
+ } catch {}
2369
+ if (json === void 0) {
2370
+ for (const [, format] of binaryFormats) {
2371
+ const parsed = format.detect(data);
2372
+ if (parsed !== void 0) return format.toMdInternal(parsed, options);
2373
+ }
2374
+ return;
2267
2375
  }
2268
- const thirdPartyMatchers = thirdParty.map((pattern) => picomatch(pattern, { dot: true }));
2269
- const isThirdPartyEntry = thirdPartyMatchers.length > 0 ? (entry) => defaultIsThirdPartyEntry(entry) || !!entry.location && thirdPartyMatchers.some((match) => match(entry.location.url.pathname)) : void 0;
2270
- const sourceMapPaths = (await Promise.all(sourceMapPatterns.map((pattern) => Array.fromAsync(glob(pattern))))).flat();
2271
- const options = {
2272
- topN,
2273
- cwd,
2274
- isThirdPartyEntry,
2275
- sourceMaps: await Promise.all(sourceMapPaths.map(async (path) => {
2276
- const sourceMap = JSON.parse(await readFile(path, `utf8`));
2277
- if (sourceMap.sourceRoot) return sourceMap;
2278
- return {
2279
- ...sourceMap,
2280
- sources: sourceMap.sources.map((source) => makeFileReference(source).type === `absolute` ? source : new URL(source, pathToFileURL(resolve(dirname(path)))).href)
2281
- };
2282
- }))
2376
+ for (const [, format] of jsonFormats) {
2377
+ const parsed = format.detect(json);
2378
+ if (parsed !== void 0) return format.toMdInternal(parsed, options);
2379
+ }
2380
+ };
2381
+
2382
+ //#endregion
2383
+ //#region src/cli/pager.ts
2384
+ const openPager = async () => {
2385
+ const raw = process.env.PAGER;
2386
+ if (raw?.trim() === ``) return null;
2387
+ const env = {
2388
+ LESS: `FRSX -#6`,
2389
+ ...process.env
2283
2390
  };
2284
- let markdown;
2285
- if (forcedProfileConverter) markdown = forcedProfileConverter.toMd(data, options);
2286
- else {
2287
- let json;
2288
- try {
2289
- json = parseJson(data);
2290
- } catch {}
2291
- if (json === void 0) for (const converter of binaryProfileConverters) {
2292
- const parsed = converter.detect(data);
2293
- if (parsed !== void 0) {
2294
- markdown = converter.toMdInternal(parsed, options);
2295
- break;
2391
+ const child = (raw === void 0 ? null : await trySpawn(raw, env)) ?? await trySpawn(`less`, env);
2392
+ if (!child) return null;
2393
+ return { write: async (text) => {
2394
+ await new Promise((resolve) => {
2395
+ child.stdin.write(text, () => child.stdin.end(resolve));
2396
+ });
2397
+ await waitForExit(child);
2398
+ } };
2399
+ };
2400
+ const trySpawn = (command, env) => {
2401
+ const [bin, ...args] = command.trim().split(/\s+/u);
2402
+ if (!bin) return Promise.resolve(null);
2403
+ const child = spawn(bin, args, {
2404
+ stdio: [
2405
+ `pipe`,
2406
+ `inherit`,
2407
+ `inherit`
2408
+ ],
2409
+ env
2410
+ });
2411
+ return new Promise((resolve) => {
2412
+ child.once(`spawn`, () => {
2413
+ child.stdin.on(`error`, (error) => {
2414
+ if (error.code !== `EPIPE`) throw error;
2415
+ });
2416
+ resolve(child);
2417
+ });
2418
+ child.once(`error`, () => resolve(null));
2419
+ });
2420
+ };
2421
+ const waitForExit = (child) => new Promise((resolve, reject) => {
2422
+ child.once(`exit`, () => resolve());
2423
+ child.once(`error`, reject);
2424
+ });
2425
+
2426
+ //#endregion
2427
+ //#region src/cli/output.ts
2428
+ const writeOutput = async (text, outputPath, { pager }) => {
2429
+ await ((pager && isTTYOutput(outputPath) ? await openPager() : null) ?? await openOutput(outputPath)).write(text);
2430
+ };
2431
+ const isTTYOutput = (outputPath) => outputPath === `-` && Boolean(process.stdout.isTTY);
2432
+ const openOutput = async (outputPath) => {
2433
+ if (outputPath === `-`) return { write: (text) => new Promise((resolve, reject) => {
2434
+ process.stdout.write(text, (error) => error ? reject(error) : resolve());
2435
+ }) };
2436
+ const stream = createWriteStream(outputPath);
2437
+ await new Promise((resolve, reject) => {
2438
+ stream.once(`open`, () => resolve()).once(`error`, reject);
2439
+ });
2440
+ return { write: (text) => new Promise((resolve, reject) => {
2441
+ stream.write(text, (error) => error ? reject(error) : stream.end(resolve));
2442
+ }) };
2443
+ };
2444
+
2445
+ //#endregion
2446
+ //#region src/cli/color.ts
2447
+ const makeAnsis = (options) => new Ansis(resolveColorLevel(options));
2448
+ const resolveColorLevel = ({ outputPath, color }) => {
2449
+ let level = isTTYOutput(outputPath) ? ttyColorLevel() : 0;
2450
+ if (process.env.NO_COLOR !== void 0) level = 0;
2451
+ if (color === false) level = 0;
2452
+ else if (color === true) level = Math.max(level, 1);
2453
+ const forceLevel = parseForceColor(process.env.FORCE_COLOR);
2454
+ if (forceLevel !== null) level = forceLevel;
2455
+ return level;
2456
+ };
2457
+ const ttyColorLevel = () => {
2458
+ const depth = process.stdout.getColorDepth?.() ?? 1;
2459
+ if (depth >= 24) return 3;
2460
+ if (depth >= 8) return 2;
2461
+ return 1;
2462
+ };
2463
+ const parseForceColor = (value) => {
2464
+ if (!value) return null;
2465
+ switch (value) {
2466
+ case `0`:
2467
+ case `false`: return 0;
2468
+ case `2`: return 2;
2469
+ case `3`: return 3;
2470
+ default: return 1;
2471
+ }
2472
+ };
2473
+
2474
+ //#endregion
2475
+ //#region src/cli/theme-kindling.ts
2476
+ const darkSlate = `#2d353b`;
2477
+ const mutedSage = `#859289`;
2478
+ const warmSand = `#d3c6aa`;
2479
+ const dimAmber = `#7a6535`;
2480
+ const amberBrown = `#cb9d68`;
2481
+ const goldenAmber = `#dbbc7f`;
2482
+ const kindlingTheme = {
2483
+ name: `kindling`,
2484
+ displayName: `Kindling`,
2485
+ type: `dark`,
2486
+ fg: warmSand,
2487
+ bg: darkSlate,
2488
+ colors: {
2489
+ "editor.foreground": warmSand,
2490
+ "editor.background": darkSlate
2491
+ },
2492
+ settings: [
2493
+ {
2494
+ scope: `punctuation.definition.heading.markdown`,
2495
+ settings: { foreground: dimAmber }
2496
+ },
2497
+ {
2498
+ scope: [
2499
+ `heading.1.markdown`,
2500
+ `heading.2.markdown`,
2501
+ `heading.3.markdown`,
2502
+ `heading.4.markdown`,
2503
+ `heading.5.markdown`,
2504
+ `heading.6.markdown`
2505
+ ],
2506
+ settings: {
2507
+ foreground: goldenAmber,
2508
+ fontStyle: `bold`
2509
+ }
2510
+ },
2511
+ {
2512
+ scope: `markup.bold.markdown`,
2513
+ settings: {
2514
+ foreground: warmSand,
2515
+ fontStyle: `bold`
2516
+ }
2517
+ },
2518
+ {
2519
+ scope: `markup.italic.markdown`,
2520
+ settings: {
2521
+ foreground: warmSand,
2522
+ fontStyle: `italic`
2523
+ }
2524
+ },
2525
+ {
2526
+ scope: [
2527
+ `markup.inline.raw.string.markdown`,
2528
+ `markup.fenced_code.block.markdown`,
2529
+ `string.other.link.description.title.markdown`
2530
+ ],
2531
+ settings: { foreground: amberBrown }
2532
+ },
2533
+ {
2534
+ scope: `punctuation.definition.raw.markdown`,
2535
+ settings: { foreground: goldenAmber }
2536
+ },
2537
+ {
2538
+ scope: [
2539
+ `punctuation.definition.bold.markdown`,
2540
+ `punctuation.definition.italic.markdown`,
2541
+ `punctuation.definition.markdown`,
2542
+ `markup.quote.markdown`,
2543
+ `punctuation.definition.quote.begin.markdown`,
2544
+ `punctuation.definition.list.begin.markdown`,
2545
+ `punctuation.definition.table.markdown`,
2546
+ `punctuation.definition.link.markdown`
2547
+ ],
2548
+ settings: { foreground: mutedSage }
2549
+ },
2550
+ {
2551
+ scope: [
2552
+ `markup.list.unnumbered.markdown`,
2553
+ `markup.list.numbered.markdown`,
2554
+ `markup.table.markdown`
2555
+ ],
2556
+ settings: { foreground: warmSand }
2557
+ },
2558
+ {
2559
+ scope: `meta.separator.markdown`,
2560
+ settings: {
2561
+ foreground: mutedSage,
2562
+ fontStyle: `bold`
2563
+ }
2564
+ },
2565
+ {
2566
+ scope: `markup.underline.link.markdown`,
2567
+ settings: {
2568
+ foreground: amberBrown,
2569
+ fontStyle: `underline`
2570
+ }
2571
+ },
2572
+ {
2573
+ scope: `comment`,
2574
+ settings: {
2575
+ foreground: mutedSage,
2576
+ fontStyle: `italic`
2577
+ }
2578
+ },
2579
+ {
2580
+ scope: [
2581
+ `keyword`,
2582
+ `keyword.control`,
2583
+ `keyword.other`,
2584
+ `storage.type`,
2585
+ `storage.modifier`
2586
+ ],
2587
+ settings: { foreground: goldenAmber }
2588
+ },
2589
+ {
2590
+ scope: [`string`, `string.template`],
2591
+ settings: { foreground: `#d98c5a` }
2592
+ },
2593
+ {
2594
+ scope: [
2595
+ `constant.numeric`,
2596
+ `constant.language`,
2597
+ `constant.character`
2598
+ ],
2599
+ settings: { foreground: `#e69875` }
2600
+ },
2601
+ {
2602
+ scope: [
2603
+ `entity.name.function`,
2604
+ `support.function`,
2605
+ `meta.function-call entity.name.function`
2606
+ ],
2607
+ settings: { foreground: `#ca6e63` }
2608
+ },
2609
+ {
2610
+ scope: [
2611
+ `entity.name.type`,
2612
+ `entity.name.class`,
2613
+ `support.type`,
2614
+ `support.class`,
2615
+ `entity.other.inherited-class`,
2616
+ `support.variable.property`
2617
+ ],
2618
+ settings: { foreground: warmSand }
2619
+ },
2620
+ {
2621
+ scope: `variable.parameter`,
2622
+ settings: {
2623
+ foreground: warmSand,
2624
+ fontStyle: `italic`
2296
2625
  }
2626
+ },
2627
+ {
2628
+ scope: `entity.other.attribute-name`,
2629
+ settings: { foreground: amberBrown }
2630
+ },
2631
+ {
2632
+ scope: [`keyword.operator`, `punctuation.accessor`],
2633
+ settings: { foreground: mutedSage }
2634
+ },
2635
+ {
2636
+ scope: [`meta.tag`, `entity.name.tag`],
2637
+ settings: { foreground: `#c4907a` }
2297
2638
  }
2298
- else for (const converter of jsonProfileConverters) {
2299
- const parsed = converter.detect(json);
2300
- if (parsed !== void 0) {
2301
- markdown = converter.toMdInternal(parsed, options);
2639
+ ]
2640
+ };
2641
+
2642
+ //#endregion
2643
+ //#region src/cli/highlight.ts
2644
+ const highlightMarkdown = async (markdown, options) => {
2645
+ const ansis = makeAnsis(options);
2646
+ if (!ansis.isSupported()) return markdown;
2647
+ const { tokens, fg } = (await getHighlighter()).codeToTokens(markdown, {
2648
+ lang: `markdown`,
2649
+ theme: `kindling`,
2650
+ includeExplanation: `scopeName`
2651
+ });
2652
+ return renderTokens(tokens, fg, computeLineToIntensity(tokens), ansis);
2653
+ };
2654
+ const getHighlighter = () => highlighterPromise ??= createHighlighterCore();
2655
+ let highlighterPromise = null;
2656
+ const createHighlighterCore = async () => {
2657
+ const markdown = import(`@shikijs/langs/markdown`);
2658
+ const c = import(`@shikijs/langs/c`);
2659
+ const go = import(`@shikijs/langs/go`);
2660
+ const java = import(`@shikijs/langs/java`);
2661
+ const js = import(`@shikijs/langs/js`);
2662
+ const python = import(`@shikijs/langs/python`);
2663
+ const rust = import(`@shikijs/langs/rust`);
2664
+ const sh = import(`@shikijs/langs/sh`);
2665
+ const toml = import(`@shikijs/langs/toml`);
2666
+ const shikiCore = import(`@shikijs/core`);
2667
+ const onigurumaEngine = import(`@shikijs/engine-oniguruma`);
2668
+ const onigurumaEngineWasm = import(`@shikijs/engine-oniguruma/wasm-inlined`);
2669
+ return (await shikiCore).createHighlighterCore({
2670
+ langs: [
2671
+ markdown,
2672
+ c,
2673
+ go,
2674
+ java,
2675
+ js,
2676
+ python,
2677
+ rust,
2678
+ sh,
2679
+ toml
2680
+ ],
2681
+ themes: [kindlingTheme],
2682
+ engine: (await onigurumaEngine).createOnigurumaEngine(onigurumaEngineWasm)
2683
+ });
2684
+ };
2685
+ const computeLineToIntensity = (lines) => {
2686
+ const lineToIntensity = /* @__PURE__ */ new Map();
2687
+ const sections = [];
2688
+ let currentTable = null;
2689
+ for (const [lineIndex, lineTokens] of lines.entries()) {
2690
+ const line = parseLine(lineTokens);
2691
+ switch (line.kind) {
2692
+ case `heading`: {
2693
+ while (sections.length > 0 && sections.at(-1).level >= line.level) sections.pop();
2694
+ currentTable = null;
2695
+ const intensity = lookupAncestorIntensity(sections, line.inlineCode, line.afterInlineCode);
2696
+ sections.push({
2697
+ level: line.level,
2698
+ intensity,
2699
+ nameLocationToIntensity: /* @__PURE__ */ new Map()
2700
+ });
2701
+ if (intensity !== null) lineToIntensity.set(lineIndex, intensity);
2302
2702
  break;
2303
2703
  }
2704
+ case `table-row`: {
2705
+ if (currentTable === null) {
2706
+ currentTable = parseTableHeader(line.text);
2707
+ break;
2708
+ }
2709
+ if (currentTable.percentColumnIndex === -1) break;
2710
+ const intensity = tableRowIntensity(line.text, currentTable, sections.at(-1));
2711
+ if (intensity !== null) lineToIntensity.set(lineIndex, intensity);
2712
+ break;
2713
+ }
2714
+ case `other`:
2715
+ currentTable = null;
2716
+ break;
2304
2717
  }
2305
- if (markdown === void 0) {
2306
- process.stderr.write(`error: could not detect profile format from content\nUse --type to specify the format, or run with --help to see supported types.\n`);
2307
- process.exit(2);
2718
+ }
2719
+ return lineToIntensity;
2720
+ };
2721
+ const parseLine = (tokens) => {
2722
+ if (tokens.length === 0) return { kind: `other` };
2723
+ const headingLevel = determineHeadingLevel(tokens);
2724
+ if (headingLevel !== null) {
2725
+ const { inlineCode, afterInlineCode } = extractHeadingParts(tokens);
2726
+ return {
2727
+ kind: `heading`,
2728
+ level: headingLevel,
2729
+ inlineCode,
2730
+ afterInlineCode
2731
+ };
2732
+ }
2733
+ if (tokens.some((token) => tokenHasScope(token, `markup.table.markdown`))) return {
2734
+ kind: `table-row`,
2735
+ text: joinTokens(tokens)
2736
+ };
2737
+ return { kind: `other` };
2738
+ };
2739
+ const determineHeadingLevel = (tokens) => {
2740
+ for (const token of tokens) for (const { scopeName } of token.explanation?.[0]?.scopes ?? []) if (scopeName.startsWith(`heading.`) && scopeName.endsWith(`.markdown`)) {
2741
+ const level = Number.parseInt(scopeName.slice(`heading.`.length, -`.markdown`.length), 10);
2742
+ if (level >= 1 && level <= 6) return level;
2743
+ }
2744
+ return null;
2745
+ };
2746
+ const extractHeadingParts = (line) => {
2747
+ const inlineCodeRange = findInlineCodeRange(line);
2748
+ if (inlineCodeRange === null) return {
2749
+ inlineCode: null,
2750
+ afterInlineCode: ``
2751
+ };
2752
+ const [start, endExclusive] = inlineCodeRange;
2753
+ return {
2754
+ inlineCode: joinTokens(line.slice(start, endExclusive)),
2755
+ afterInlineCode: joinTokens(line.slice(endExclusive))
2756
+ };
2757
+ };
2758
+ const findInlineCodeRange = (line) => {
2759
+ const start = line.findIndex((token) => tokenHasScope(token, `markup.inline.raw.string.markdown`));
2760
+ if (start === -1) return null;
2761
+ let endExclusive = start + 1;
2762
+ while (endExclusive < line.length && tokenHasScope(line[endExclusive], `markup.inline.raw.string.markdown`)) endExclusive++;
2763
+ return [start, endExclusive];
2764
+ };
2765
+ const tokenHasScope = (token, scope) => !!token.explanation?.[0]?.scopes.some(({ scopeName }) => scopeName === scope);
2766
+ const joinTokens = (tokens) => tokens.map((token) => token.content).join(``);
2767
+ const lookupAncestorIntensity = (sections, inlineCode, afterInlineCode) => {
2768
+ if (inlineCode === null) return null;
2769
+ const trimmed = afterInlineCode.trim();
2770
+ if (!trimmed.startsWith(`(`) || !trimmed.endsWith(`)`)) return null;
2771
+ const key = `${inlineCode} (${trimmed.slice(1, -1)})`;
2772
+ for (let i = sections.length - 1; i >= 0; i--) {
2773
+ const intensity = sections[i].nameLocationToIntensity.get(key);
2774
+ if (intensity !== void 0) return intensity;
2775
+ }
2776
+ return null;
2777
+ };
2778
+ const parseTableHeader = (line) => {
2779
+ const cells = parseTableCells(line);
2780
+ return {
2781
+ percentColumnIndex: cells.indexOf(`%`),
2782
+ locationColumnIndex: cells.indexOf(`Location`),
2783
+ nameColumnIndex: -1
2784
+ };
2785
+ };
2786
+ const tableRowIntensity = (row, table, headingSection) => {
2787
+ const cells = parseTableCells(row);
2788
+ const percentageCell = cells[table.percentColumnIndex];
2789
+ if (percentageCell === void 0) return null;
2790
+ const percentage = parsePercent(percentageCell);
2791
+ if (percentage === null) return null;
2792
+ if (table.locationColumnIndex !== -1 && headingSection !== void 0) {
2793
+ if (table.nameColumnIndex === -1) table.nameColumnIndex = cells.findIndex((cell) => cell.startsWith(`\``) && cell.endsWith(`\``));
2794
+ if (table.nameColumnIndex !== -1) {
2795
+ const nameCell = cells[table.nameColumnIndex];
2796
+ const locationCell = cells[table.locationColumnIndex];
2797
+ const intensity = (headingSection.intensity ?? 1) * percentage;
2798
+ headingSection.nameLocationToIntensity.set(`${nameCell} (${locationCell})`, intensity);
2799
+ return intensity;
2308
2800
  }
2309
2801
  }
2310
- let output;
2311
- if (outputPath === `-`) output = process.stdout;
2312
- else {
2313
- output = createWriteStream(outputPath);
2314
- await new Promise((resolve, reject) => {
2315
- output.once(`open`, () => resolve()).once(`error`, reject);
2316
- });
2802
+ return (headingSection?.intensity ?? 1) * percentage;
2803
+ };
2804
+ const parseTableCells = (line) => {
2805
+ let inner = line.trim();
2806
+ if (inner.startsWith(`|`)) inner = inner.slice(1);
2807
+ if (inner.endsWith(`|`)) inner = inner.slice(0, -1);
2808
+ return inner.split(`|`).map((cell) => cell.trim());
2809
+ };
2810
+ const parsePercent = (cell) => {
2811
+ const trimmed = cell.trim();
2812
+ if (!trimmed.endsWith(`%`)) return null;
2813
+ const value = Number.parseFloat(trimmed.slice(0, -1));
2814
+ return Number.isNaN(value) ? null : value / 100;
2815
+ };
2816
+ const renderTokens = (tokens, themeFg, lineToIntensity, ansis) => tokens.map((line, lineIndex) => {
2817
+ const intensity = lineToIntensity.get(lineIndex) ?? 0;
2818
+ return line.map((token) => renderToken(token, themeFg, intensity, ansis)).join(``);
2819
+ }).join(`\n`);
2820
+ const renderToken = (token, themeFg, intensity, ansis) => {
2821
+ const baseRgb = parseRgb(token.color ?? themeFg);
2822
+ const { red, green, blue } = intensity > 0 ? tintHeat(baseRgb, intensity ** .5 * .75) : baseRgb;
2823
+ let styled = ansis.rgb(red, green, blue)(token.content);
2824
+ if (token.fontStyle) {
2825
+ if (token.fontStyle & FONT_STYLE_BOLD) styled = ansis.bold(styled);
2826
+ if (token.fontStyle & FONT_STYLE_ITALIC) styled = ansis.italic(styled);
2827
+ if (token.fontStyle & FONT_STYLE_UNDERLINE) styled = ansis.underline(styled);
2828
+ if (token.fontStyle & FONT_STYLE_STRIKETHROUGH) styled = ansis.strikethrough(styled);
2317
2829
  }
2318
- await new Promise((resolve, reject) => {
2319
- output.write(markdown, (error) => {
2320
- if (error) reject(error);
2321
- else if (output === process.stdout) resolve();
2322
- else output.end(resolve);
2323
- });
2830
+ return styled;
2831
+ };
2832
+ const parseRgb = (hex) => {
2833
+ const value = hex.replace(/^#/u, ``);
2834
+ return {
2835
+ red: Number.parseInt(value.slice(0, 2), 16),
2836
+ green: Number.parseInt(value.slice(2, 4), 16),
2837
+ blue: Number.parseInt(value.slice(4, 6), 16)
2838
+ };
2839
+ };
2840
+ const tintHeat = ({ red, green, blue }, intensity) => ({
2841
+ red: Math.round(red + (255 - red) * intensity),
2842
+ green: Math.round(green * (1 - intensity * .7)),
2843
+ blue: Math.round(blue * (1 - intensity * .7))
2844
+ });
2845
+ const FONT_STYLE_ITALIC = 1;
2846
+ const FONT_STYLE_BOLD = 2;
2847
+ const FONT_STYLE_UNDERLINE = 4;
2848
+ const FONT_STYLE_STRIKETHROUGH = 8;
2849
+
2850
+ //#endregion
2851
+ //#region src/cli/help.ts
2852
+ const printHelpTopic = async (topic, { pager, color }) => {
2853
+ if (topic === void 0) {
2854
+ await writeOutput(cli.help, `-`, { pager });
2855
+ process.exit(0);
2856
+ }
2857
+ const language = languages.get(languageAliasToPrimary.get(topic) ?? topic);
2858
+ const format = formats.get(topic);
2859
+ if (!language && !format) {
2860
+ process.stderr.write(`error: unknown topic "${topic}"\nAvailable topics: ${topics.join(`, `)}\n`);
2861
+ process.exit(2);
2862
+ }
2863
+ const doc = await readFile(new URL(`../../docs/${format ? `formats` : `languages`}/${topic}.md`, import.meta.url), `utf8`);
2864
+ const seeAlso = format ? [...languages.entries()].flatMap(([id, language]) => {
2865
+ if (!language.formats.includes(topic)) return [];
2866
+ return [id, ...language.aliases?.map((alias) => alias.id) ?? []];
2867
+ }) : language ? language.formats : [];
2868
+ const seeAlsoSuffix = seeAlso.length > 0 ? `\nSee also: ${seeAlso.join(`, `)}\n` : ``;
2869
+ const outputPath = `-`;
2870
+ await writeOutput(await highlightMarkdown(`${doc}${seeAlsoSuffix}`, {
2871
+ outputPath,
2872
+ color
2873
+ }), outputPath, { pager });
2874
+ process.exit(0);
2875
+ };
2876
+
2877
+ //#endregion
2878
+ //#region src/cli/input.ts
2879
+ const readInput = async (filePath) => {
2880
+ return decompress(await readRawInput(filePath), filePath);
2881
+ };
2882
+ const readRawInput = async (filePath) => {
2883
+ if (!filePath) return Buffer.concat(await Array.fromAsync(process.stdin));
2884
+ try {
2885
+ return await readFile(filePath);
2886
+ } catch (error) {
2887
+ throw new CliError(error instanceof Error ? error.message : String(error), 1);
2888
+ }
2889
+ };
2890
+ const decompress = async (data, filePath) => {
2891
+ try {
2892
+ if (filePath?.endsWith(`.br`)) return await brotliDecompressAsync(data);
2893
+ if (data[0] === 31 && data[1] === 139) return await gunzipAsync(data);
2894
+ return data;
2895
+ } catch (error) {
2896
+ throw new CliError(`failed to decompress input: ${error instanceof Error ? error.message : String(error)}`, 1);
2897
+ }
2898
+ };
2899
+ const gunzipAsync = promisify(gunzip);
2900
+ const brotliDecompressAsync = promisify(brotliDecompress);
2901
+
2902
+ //#endregion
2903
+ //#region src/cli/options.ts
2904
+ const buildOptions = async ({ topN, cwd, thirdParty, sourceMaps }) => ({
2905
+ topN,
2906
+ cwd,
2907
+ isThirdPartyEntry: buildIsThirdPartyEntry(thirdParty),
2908
+ sourceMaps: await loadSourceMaps(sourceMaps)
2909
+ });
2910
+ const buildIsThirdPartyEntry = (patterns) => {
2911
+ if (patterns.length === 0) return;
2912
+ const matchers = patterns.map((pattern) => picomatch(pattern, { dot: true }));
2913
+ return (entry) => defaultIsThirdPartyEntry(entry) || !!entry.location && matchers.some((match) => match(entry.location.url.pathname));
2914
+ };
2915
+ const loadSourceMaps = async (patterns) => {
2916
+ const paths = (await Promise.all(patterns.map((pattern) => Array.fromAsync(glob(pattern))))).flat();
2917
+ return Promise.all(paths.map(async (path) => {
2918
+ const content = await readFile(path, `utf8`);
2919
+ const inlineSourceMap = convertSourceMap.fromSource(content)?.toObject();
2920
+ if (!inlineSourceMap) return resolveSourceMapSources(JSON.parse(content), path);
2921
+ inlineSourceMap.file ??= pathToFileURL(resolve(path)).href;
2922
+ return resolveSourceMapSources(inlineSourceMap, path);
2923
+ }));
2924
+ };
2925
+ /**
2926
+ * Pre-resolves relative source paths against the map file's directory so that `source-map-js` returns
2927
+ * absolute URLs.
2928
+ */
2929
+ const resolveSourceMapSources = (sourceMap, path) => {
2930
+ if (sourceMap.sourceRoot) return sourceMap;
2931
+ return {
2932
+ ...sourceMap,
2933
+ sources: sourceMap.sources.map((source) => makeFileReference(source).type === `absolute` ? source : new URL(source, pathToFileURL(resolve(dirname(path)))).href)
2934
+ };
2935
+ };
2936
+
2937
+ //#endregion
2938
+ //#region src/cli/index.ts
2939
+ try {
2940
+ const { input: [filePath], flags: { help, output: outputPath, format: profileFormat, topN, cwd, thirdParty, sourceMaps, pager, color } } = cli;
2941
+ if (help) await printHelpTopic(filePath, {
2942
+ pager,
2943
+ color
2944
+ });
2945
+ const forcedFormat = profileFormat === void 0 ? void 0 : requireFormat(profileFormat);
2946
+ if (!filePath && process.stdin.isTTY) await printHelpTopic(void 0, {
2947
+ pager,
2948
+ color
2324
2949
  });
2950
+ await writeOutput(await highlightMarkdown(convertToMarkdown(await readInput(filePath), forcedFormat, await buildOptions({
2951
+ topN,
2952
+ cwd,
2953
+ thirdParty,
2954
+ sourceMaps
2955
+ })), {
2956
+ outputPath,
2957
+ color
2958
+ }), outputPath, { pager });
2325
2959
  } catch (error) {
2326
- if (error instanceof Error) {
2327
- process.stderr.write(`error: ${error.message}\n`);
2328
- if (error.stack) process.stderr.write(`${error.stack}\n`);
2329
- } else process.stderr.write(`error: ${String(error)}\n`);
2330
- process.exit(1);
2960
+ reportError(error);
2331
2961
  }
2332
2962
 
2333
2963
  //#endregion