ostia 0.2.11 → 0.3.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.
Files changed (96) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -353
  3. package/docs/agent-protocol.md +210 -0
  4. package/docs/cli.md +1196 -0
  5. package/docs/config.md +233 -0
  6. package/docs/document-schema.md +224 -0
  7. package/docs/library.md +421 -0
  8. package/docs/preload-recipes.md +169 -0
  9. package/docs/statistics.md +218 -0
  10. package/index.d.ts +942 -642
  11. package/package.json +16 -14
  12. package/src/ab/ab-runner.ts +474 -0
  13. package/src/ab/index.ts +1086 -0
  14. package/src/baseline/index.ts +75 -0
  15. package/src/bench/index.ts +462 -0
  16. package/src/bench/projects.ts +39 -0
  17. package/src/bench/range.ts +27 -0
  18. package/src/bench/registry.ts +424 -0
  19. package/src/bench/run-tasks.ts +176 -0
  20. package/src/bench/run.ts +51 -0
  21. package/src/bench/runner.ts +147 -0
  22. package/src/bench/support.ts +161 -0
  23. package/src/bench/sweep.ts +39 -0
  24. package/src/cache/fingerprint.ts +59 -0
  25. package/src/cache/store.ts +28 -0
  26. package/src/capture/bunflags.ts +91 -0
  27. package/src/capture/cpu-parse.ts +119 -0
  28. package/src/capture/cpu.ts +44 -0
  29. package/src/capture/frames.ts +54 -0
  30. package/src/capture/heap-parse.ts +86 -0
  31. package/src/capture/heap.ts +32 -0
  32. package/src/capture/inspector.ts +46 -0
  33. package/src/capture/jsc-parse.ts +167 -0
  34. package/src/capture/jsc.ts +35 -0
  35. package/src/capture/sampling.ts +5 -0
  36. package/src/ci/index.ts +416 -0
  37. package/src/cli/flags.ts +264 -0
  38. package/{chunk-scvezzm9.js → src/cli/help.ts} +31 -15
  39. package/src/cli/main.ts +18 -0
  40. package/src/cli/output.ts +185 -0
  41. package/src/cli/run.ts +1110 -0
  42. package/src/compare/index.ts +617 -0
  43. package/src/config/index.ts +275 -0
  44. package/src/config/validate.ts +267 -0
  45. package/src/errors.ts +8 -0
  46. package/src/format.ts +36 -0
  47. package/src/glob.ts +48 -0
  48. package/src/index.ts +62 -0
  49. package/src/ir/cpu.ts +10 -0
  50. package/src/ir/document.ts +471 -0
  51. package/src/ir/fp.ts +31 -0
  52. package/src/ir/git.ts +36 -0
  53. package/src/ir/types.ts +615 -0
  54. package/src/measure/alloc.ts +57 -0
  55. package/src/measure/cpu.ts +99 -0
  56. package/src/measure/environment.ts +41 -0
  57. package/src/measure/inprocess.ts +191 -0
  58. package/src/measure/instructions.ts +133 -0
  59. package/src/measure/loop.ts +57 -0
  60. package/src/measure/noise.ts +55 -0
  61. package/src/measure/paired.ts +312 -0
  62. package/src/measure/peak.ts +202 -0
  63. package/src/measure/timing.ts +263 -0
  64. package/src/profile.ts +109 -0
  65. package/src/renderers/collapsed.ts +35 -0
  66. package/src/renderers/cpu-tree.ts +183 -0
  67. package/src/renderers/cpuprofile.ts +43 -0
  68. package/src/renderers/format.ts +142 -0
  69. package/src/renderers/index.ts +27 -0
  70. package/src/renderers/json.ts +10 -0
  71. package/src/renderers/jsonl.ts +15 -0
  72. package/src/renderers/markdown.ts +525 -0
  73. package/src/renderers/mermaid.ts +78 -0
  74. package/src/renderers/minimal.ts +602 -0
  75. package/src/renderers/paired.ts +229 -0
  76. package/src/renderers/relative.ts +64 -0
  77. package/src/renderers/select.ts +286 -0
  78. package/src/renderers/speedscope.ts +69 -0
  79. package/src/renderers/terminal.ts +466 -0
  80. package/src/renderers/types.ts +27 -0
  81. package/src/spawn/index.ts +396 -0
  82. package/src/stats/bootstrap.ts +153 -0
  83. package/src/stats/index.ts +140 -0
  84. package/src/stats/mannwhitney.ts +81 -0
  85. package/src/time.ts +325 -0
  86. package/src/version.ts +3 -0
  87. package/ab-runner.ts +0 -8
  88. package/chunk-5m601yfv.js +0 -15
  89. package/chunk-82vs1rw1.js +0 -2
  90. package/chunk-dvqggjkn.js +0 -14
  91. package/chunk-fc36fd0b.js +0 -3
  92. package/chunk-pdv5zb3w.js +0 -27
  93. package/chunk-r6hwb84z.js +0 -25
  94. package/cli.js +0 -3
  95. package/index.js +0 -2
  96. package/runner.ts +0 -7
@@ -0,0 +1,416 @@
1
+ import { bench, resolveBenchOptions } from "../bench/index.ts";
2
+ import { captureRunEnvironment } from "../bench/support.ts";
3
+ import { computeCacheKey, computeInputsDigest } from "../cache/fingerprint.ts";
4
+ import { readCachedRun, writeCachedRun } from "../cache/store.ts";
5
+ import { createComparer, summarizeComparisons } from "../compare/index.ts";
6
+ import {
7
+ baselinePath,
8
+ type OstiaConfig,
9
+ type WorkloadConfig,
10
+ } from "../config/index.ts";
11
+ import { OstiaUsageError } from "../errors.ts";
12
+ import { scanGlobs } from "../glob.ts";
13
+ import {
14
+ configFingerprint,
15
+ createDocument,
16
+ loadDocument,
17
+ makeSubprocessWorkload,
18
+ makeTimingMeasurement,
19
+ } from "../ir/document.ts";
20
+ import type {
21
+ Comparison,
22
+ Environment,
23
+ Measurement,
24
+ ProfileDocument,
25
+ Warning,
26
+ Workload,
27
+ } from "../ir/types.ts";
28
+ import { stampDrift } from "../measure/environment.ts";
29
+ import { isHarnessFailure, runTimingPhase } from "../measure/timing.ts";
30
+ import { formatSignedPct, workloadLabel } from "../renderers/format.ts";
31
+ import { abortedWarning } from "../time.ts";
32
+ import { TOOL_VERSION } from "../version.ts";
33
+
34
+ export interface CiOptions {
35
+ config: OstiaConfig;
36
+ full: boolean;
37
+ baselineName?: string;
38
+ /**
39
+ * Abort kills in-flight trials and suite processes and stops scheduling
40
+ * workloads. `runCi` then resolves with `aborted: true`: the document
41
+ * holds what completed, nothing is compared, and no run is written to the
42
+ * cache. */
43
+ signal?: AbortSignal;
44
+ }
45
+
46
+ /**
47
+ * Hung workloads time out rather than block a CI job;
48
+ * `WorkloadConfig.timeoutMs` / `BenchConfig.timeoutMs` override this. */
49
+ const DEFAULT_CI_TIMEOUT_MS = 600_000;
50
+
51
+ type WorkloadStatus = "cached" | "executed";
52
+
53
+ interface MeasuredWorkload {
54
+ workload: Workload;
55
+ status: WorkloadStatus;
56
+ run: Measurement;
57
+ /**
58
+ * `command` workloads only (see `isHarnessFailure`): not a regression, so
59
+ * gated separately from a timing verdict. Always `false` for `suites`. */
60
+ harnessFailed: boolean;
61
+ }
62
+
63
+ interface CiWorkloadResult extends MeasuredWorkload {
64
+ comparison?: Comparison;
65
+ }
66
+
67
+ export interface CiSummary {
68
+ total: number;
69
+ cached: number;
70
+ executed: number;
71
+ passed: number;
72
+ regressed: number;
73
+ missingBaseline: number;
74
+ /**
75
+ * Count of `results` with `harnessFailed: true`; always gates the exit to
76
+ * 2.
77
+ */
78
+ failed: number;
79
+ results: CiWorkloadResult[];
80
+ /**
81
+ * Workloads on only one side: `candOnly` is what `missingBaseline` counts,
82
+ * as full `Workload`s so a renderer can name them. */
83
+ unmatched: { baseOnly: Workload[]; candOnly: Workload[] };
84
+ }
85
+
86
+ /**
87
+ * Base of the two baseline errors, so the CLI reports either as
88
+ * `baseline-missing`.
89
+ */
90
+ export class BaselineError extends OstiaUsageError {}
91
+
92
+ export class BaselineNotFoundError extends BaselineError {
93
+ constructor(public readonly path: string) {
94
+ super(
95
+ `No baseline document at ${path}. Create one with: ostia baseline save ${path
96
+ .split("/")
97
+ .pop()!
98
+ .replace(/\.json$/, "")}`,
99
+ );
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Thrown by `runCi` when the `onMissingBaseline` policy makes unmatched
105
+ * workloads a hard error. */
106
+ export class MissingBaselineError extends BaselineError {
107
+ constructor(
108
+ public readonly path: string,
109
+ public readonly missing: number,
110
+ public readonly total: number,
111
+ ) {
112
+ super(
113
+ `${missing} of ${total} configured workload(s) have no matching row in baseline ${path} (by workload id). Re-seed with: ostia baseline save`,
114
+ );
115
+ }
116
+ }
117
+
118
+ export interface MeasureConfigWorkloadsResult {
119
+ results: MeasuredWorkload[];
120
+ /**
121
+ * One reference measurement taken before any workload runs, unless
122
+ * `config.noiseCheck` is false. */
123
+ environment?: Environment;
124
+ /** The signal fired: `results` holds only what completed. */
125
+ aborted: boolean;
126
+ }
127
+
128
+ async function measureSuiteWorkloads(
129
+ config: OstiaConfig,
130
+ wc: WorkloadConfig,
131
+ noiseWarning: Warning | undefined,
132
+ signal: AbortSignal | undefined,
133
+ ): Promise<MeasuredWorkload[]> {
134
+ // Always executes: a suite file's task ids (so its cache keys) are unknown
135
+ // without importing it.
136
+ const suiteFiles = await scanGlobs(wc.suites!, process.cwd());
137
+ if (suiteFiles.length === 0) {
138
+ // Gating zero tasks would pass silently.
139
+ throw new OstiaUsageError(
140
+ `Workload suites ${JSON.stringify(wc.suites)} matched no files.`,
141
+ );
142
+ }
143
+ // Same CLI-over-config resolution as `ostia bench`; only the defaults
144
+ // differ.
145
+ const benchOpts = await resolveBenchOptions(
146
+ { suites: suiteFiles, preload: [], bunFlags: [], noiseCheck: false },
147
+ config.bench,
148
+ );
149
+ const doc = await bench({
150
+ ...benchOpts,
151
+ outDir: benchOpts.outDir ?? config.outDir,
152
+ // The workload's own limit, then `bench.timeoutMs`, as for a command.
153
+ timeoutMs: wc.timeoutMs ?? benchOpts.timeoutMs ?? DEFAULT_CI_TIMEOUT_MS,
154
+ signal,
155
+ });
156
+ const results: MeasuredWorkload[] = [];
157
+ for (const workload of doc.workloads) {
158
+ const run = doc.measurements.find(
159
+ (m) => m.workloadId === workload.id && m.phase === "timing",
160
+ );
161
+ // A task.skip()'d task has no timing measurement: nothing to gate.
162
+ if (!run) continue;
163
+ if (noiseWarning) run.warnings.push(noiseWarning);
164
+ results.push({ workload, status: "executed", run, harnessFailed: false });
165
+ }
166
+ return results;
167
+ }
168
+
169
+ async function measureCommandWorkload(
170
+ config: OstiaConfig,
171
+ wc: WorkloadConfig,
172
+ full: boolean,
173
+ noiseWarning: Warning | undefined,
174
+ signal: AbortSignal | undefined,
175
+ ): Promise<MeasuredWorkload> {
176
+ const workload = makeSubprocessWorkload(wc.command!, wc.label, {
177
+ prepare: wc.prepare,
178
+ timeSource: wc.timeSource,
179
+ });
180
+ const cfgFp = configFingerprint({
181
+ samples: config.samples ?? null,
182
+ budgetMs: config.budgetMs ?? null,
183
+ minSamples: config.minSamples ?? null,
184
+ warmup: config.warmup,
185
+ });
186
+ // Only declared `inputs` say what a cached run depends on (`inputs: []`
187
+ // means "nothing"). A function-form prepare can read anything, so it never
188
+ // comes from cache either.
189
+ const cacheable = wc.inputs !== undefined && typeof wc.prepare !== "function";
190
+ const cacheKey = computeCacheKey({
191
+ workloadId: workload.id,
192
+ phase: "timing",
193
+ configFingerprint: cfgFp,
194
+ bunVersion: Bun.version,
195
+ toolVersion: TOOL_VERSION,
196
+ instrumented: false,
197
+ inputsDigest: await computeInputsDigest(wc.inputs ?? []),
198
+ });
199
+
200
+ const cachedRun =
201
+ full || !cacheable
202
+ ? undefined
203
+ : await readCachedRun(config.outDir, cacheKey);
204
+ let run: Measurement;
205
+ if (cachedRun) {
206
+ run = cachedRun;
207
+ } else {
208
+ const phaseResult = await runTimingPhase({
209
+ argv: wc.command!,
210
+ samples: config.samples,
211
+ budgetMs: config.budgetMs,
212
+ minSamples: config.minSamples,
213
+ warmup: config.warmup,
214
+ prepare: wc.prepare,
215
+ timeSource: wc.timeSource,
216
+ timeoutMs: wc.timeoutMs ?? DEFAULT_CI_TIMEOUT_MS,
217
+ ignoreExitCodes: wc.ignoreExitCodes,
218
+ signal,
219
+ });
220
+ run = makeTimingMeasurement({
221
+ workload,
222
+ configFingerprint: cfgFp,
223
+ trials: phaseResult.trials,
224
+ timing: phaseResult.timing,
225
+ warnings: noiseWarning
226
+ ? [...phaseResult.warnings, noiseWarning]
227
+ : phaseResult.warnings,
228
+ });
229
+ // A cancelled run holds partial trials, which must never be served later.
230
+ if (cacheable && !signal?.aborted) {
231
+ await writeCachedRun(config.outDir, cacheKey, run);
232
+ }
233
+ }
234
+
235
+ return {
236
+ workload,
237
+ status: cachedRun ? "cached" : "executed",
238
+ run,
239
+ harnessFailed: isHarnessFailure(run, wc.ignoreExitCodes),
240
+ };
241
+ }
242
+
243
+ /**
244
+ * Runs every configured workload (or reads it from cache) with no baseline
245
+ * comparison. Shared by `runCi` and `ostia baseline save`, so a saved
246
+ * baseline comes from the same code path `ci` gates against. */
247
+ export async function measureConfigWorkloads(
248
+ config: OstiaConfig,
249
+ full: boolean,
250
+ signal?: AbortSignal,
251
+ ): Promise<MeasureConfigWorkloadsResult> {
252
+ // Stamped on every measurement taken now, never on a cached one.
253
+ const { environment, noiseWarning } = captureRunEnvironment(
254
+ config.noiseCheck,
255
+ );
256
+ const results: MeasuredWorkload[] = [];
257
+ for (const wc of config.workloads) {
258
+ if (signal?.aborted) break;
259
+ if (wc.suites) {
260
+ results.push(
261
+ ...(await measureSuiteWorkloads(config, wc, noiseWarning, signal)),
262
+ );
263
+ } else {
264
+ results.push(
265
+ await measureCommandWorkload(config, wc, full, noiseWarning, signal),
266
+ );
267
+ }
268
+ }
269
+ const aborted = signal?.aborted ?? false;
270
+ const last = results.at(-1)?.run;
271
+ if (aborted && last && !last.warnings.some((w) => w.code === "aborted")) {
272
+ last.warnings = [...last.warnings, abortedWarning()];
273
+ }
274
+ if (results.some((r) => r.status === "executed")) stampDrift(environment);
275
+ return { results, environment, aborted };
276
+ }
277
+
278
+ export async function runCi(opts: CiOptions): Promise<{
279
+ document: ProfileDocument;
280
+ summary: CiSummary;
281
+ /**
282
+ * The baseline `document` was compared against, so a caller can report its
283
+ * `git` without loading it again. */
284
+ baseline: ProfileDocument;
285
+ /** Cancelled by `signal`: `document` is partial and has no comparisons. */
286
+ aborted: boolean;
287
+ }> {
288
+ const { config } = opts;
289
+ const path = baselinePath(config, opts.baselineName);
290
+ if (!(await Bun.file(path).exists())) {
291
+ throw new BaselineNotFoundError(path);
292
+ }
293
+ const baseline = await loadDocument(path);
294
+
295
+ const {
296
+ results: measured,
297
+ environment,
298
+ aborted,
299
+ } = await measureConfigWorkloads(config, opts.full, opts.signal);
300
+ const results: CiWorkloadResult[] = measured.map((m) => ({ ...m }));
301
+ const executed = results.filter((r) => r.status === "executed").length;
302
+ const candidateDoc = createDocument(
303
+ results.map((r) => r.workload),
304
+ results.map((r) => r.run),
305
+ environment,
306
+ );
307
+
308
+ if (aborted) {
309
+ return {
310
+ document: candidateDoc,
311
+ summary: {
312
+ total: results.length,
313
+ cached: results.length - executed,
314
+ executed,
315
+ passed: 0,
316
+ regressed: 0,
317
+ missingBaseline: 0,
318
+ failed: 0,
319
+ results,
320
+ unmatched: { baseOnly: [], candOnly: [] },
321
+ },
322
+ baseline,
323
+ aborted,
324
+ };
325
+ }
326
+
327
+ const comparer = createComparer(baseline, candidateDoc, config.thresholds);
328
+ const matched: [string, Comparison][] = [];
329
+ for (const result of results) {
330
+ const comparison = comparer.compare(result.workload.id);
331
+ if (comparison) {
332
+ result.comparison = comparison;
333
+ matched.push([result.workload.id, comparison]);
334
+ }
335
+ }
336
+ const comparisons = matched.map(([, c]) => c);
337
+ const missingBaseline = results.length - comparisons.length;
338
+ const passed = comparisons.filter((c) => c.verdict === "pass").length;
339
+
340
+ // Unset: fail only when every workload is missing (a stale baseline file),
341
+ // warn when just some are (a workload added since the baseline was saved).
342
+ const policy =
343
+ config.onMissingBaseline ??
344
+ (missingBaseline === results.length ? "fail" : "warn");
345
+ if (missingBaseline > 0 && policy === "fail") {
346
+ throw new MissingBaselineError(path, missingBaseline, results.length);
347
+ }
348
+
349
+ const unmatched = comparer.unmatched();
350
+ candidateDoc.comparisons = comparisons;
351
+ candidateDoc.unmatched = {
352
+ baseOnly: unmatched.baseOnly.map((w) => w.id),
353
+ candOnly: unmatched.candOnly.map((w) => w.id),
354
+ };
355
+ candidateDoc.compared = comparer.compared(matched);
356
+ candidateDoc.comparisonSummary = summarizeComparisons(
357
+ comparisons,
358
+ comparer.effectiveTimingPct,
359
+ comparer.driftPct,
360
+ );
361
+
362
+ return {
363
+ document: candidateDoc,
364
+ summary: {
365
+ total: results.length,
366
+ cached: results.length - executed,
367
+ executed,
368
+ passed,
369
+ regressed: comparisons.length - passed,
370
+ missingBaseline,
371
+ failed: results.filter((r) => r.harnessFailed).length,
372
+ results,
373
+ unmatched,
374
+ },
375
+ baseline,
376
+ aborted: false,
377
+ };
378
+ }
379
+
380
+ export function renderCiReport(summary: CiSummary): string {
381
+ const lines = [
382
+ `${summary.total} workloads`,
383
+ `${summary.cached} cached`,
384
+ `${summary.executed} executed`,
385
+ ];
386
+ if (summary.missingBaseline > 0) {
387
+ lines.push(
388
+ `${summary.missingBaseline} skipped (no matching baseline workload)`,
389
+ );
390
+ }
391
+ if (summary.failed > 0) {
392
+ const failedLabels = summary.results
393
+ .filter((r) => r.harnessFailed)
394
+ .map((r) => workloadLabel(r.workload));
395
+ lines.push(
396
+ `${summary.failed} failed (harness error, a command exited non-zero or produced no samples: ${failedLabels.join(", ")})`,
397
+ );
398
+ }
399
+
400
+ const regressionDetails = summary.results
401
+ .filter((r) => r.comparison?.verdict === "fail")
402
+ .map((r) => {
403
+ const t = r.comparison!.timing;
404
+ const label = workloadLabel(r.workload);
405
+ return t
406
+ ? `${formatSignedPct(t.medianDeltaPct)} median on ${label}`
407
+ : label;
408
+ });
409
+
410
+ lines.push(
411
+ `${summary.passed} passed ${summary.regressed} regressed${regressionDetails.length > 0 ? ` (${regressionDetails.join(", ")})` : ""}`,
412
+ "",
413
+ `Profile CI: ${summary.regressed > 0 || summary.failed > 0 ? "✗" : "✓"}`,
414
+ );
415
+ return `${lines.join("\n")}\n`;
416
+ }
@@ -0,0 +1,264 @@
1
+ import { availableJobs } from "../bench/index.ts";
2
+ import type { FormatName } from "../renderers/index.ts";
3
+ import { splitCommand } from "../spawn/index.ts";
4
+
5
+ /**
6
+ * Thrown for a malformed flag; the dispatcher prints it with a `--help`
7
+ * pointer and exits 2.
8
+ */
9
+ export class CliUsageError extends Error {}
10
+
11
+ const DOCUMENT_FORMATS = [
12
+ "table",
13
+ "json",
14
+ "jsonl",
15
+ "markdown",
16
+ "minimal",
17
+ ] as const;
18
+
19
+ export const VIZ_FORMATS = [
20
+ "collapsed",
21
+ "mermaid",
22
+ "speedscope",
23
+ "cpuprofile",
24
+ ] as const;
25
+
26
+ export const REPORT_FORMATS = [...DOCUMENT_FORMATS, ...VIZ_FORMATS] as const;
27
+
28
+ /**
29
+ * Integer flag value >= `opts.min` (default 1); `opts.allowAuto` also
30
+ * accepts "auto" as the available job count.
31
+ */
32
+ export function parseIntFlag(
33
+ name: string,
34
+ raw: string | undefined,
35
+ opts: { min?: number; allowAuto?: boolean } = {},
36
+ ): number {
37
+ if (opts.allowAuto && raw === "auto") return availableJobs();
38
+ const min = opts.min ?? 1;
39
+ const n = raw?.trim() === "" ? Number.NaN : Number(raw);
40
+ if (!Number.isInteger(n) || n < min) {
41
+ throw new CliUsageError(
42
+ `Invalid ${name} "${raw}": expected an integer ≥ ${min}${
43
+ opts.allowAuto ? ` (or "auto")` : ""
44
+ }`,
45
+ );
46
+ }
47
+ return n;
48
+ }
49
+
50
+ function parseExitCodes(name: string, raw: string): number[] {
51
+ return raw.split(",").map((part) => {
52
+ const code = /^\d+$/.test(part) ? Number(part) : Number.NaN;
53
+ if (!(code <= 255)) {
54
+ throw new CliUsageError(
55
+ `Invalid ${name} "${raw}": expected exit codes 0-255, comma-separated`,
56
+ );
57
+ }
58
+ return code;
59
+ });
60
+ }
61
+
62
+ type FlagSpec =
63
+ | { kind: "string" }
64
+ | { kind: "int"; min?: number; allowAuto?: boolean }
65
+ | { kind: "number"; min: number }
66
+ | { kind: "bool"; value: boolean }
67
+ | { kind: "enum"; values: readonly string[] }
68
+ | { kind: "list" }
69
+ | { kind: "words" }
70
+ | { kind: "exitCodes" };
71
+
72
+ interface FlagDef {
73
+ dest: string;
74
+ spec: FlagSpec;
75
+ }
76
+
77
+ type FlagTable = Record<string, FlagDef>;
78
+
79
+ const def = (dest: string, spec: FlagSpec): FlagDef => ({ dest, spec });
80
+
81
+ /**
82
+ * Builders for `FlagTable` entries; `dest` is the property set on the
83
+ * parsed args.
84
+ */
85
+ export const flag = {
86
+ str: (dest: string) => def(dest, { kind: "string" }),
87
+ int: (dest: string, min = 1, allowAuto = false) =>
88
+ def(dest, { kind: "int", min, allowAuto }),
89
+ num: (dest: string, min: number) => def(dest, { kind: "number", min }),
90
+ on: (dest: string) => def(dest, { kind: "bool", value: true }),
91
+ off: (dest: string) => def(dest, { kind: "bool", value: false }),
92
+ oneOf: (dest: string, values: readonly string[]) =>
93
+ def(dest, { kind: "enum", values }),
94
+ /** Repeatable; each occurrence appends one value. */
95
+ list: (dest: string) => def(dest, { kind: "list" }),
96
+ /** Repeatable; each occurrence is whitespace-split and appended. */
97
+ words: (dest: string) => def(dest, { kind: "words" }),
98
+ /** `--flag[=CODE,...]`: bare means every non-zero exit code. */
99
+ exitCodes: (dest: string) => def(dest, { kind: "exitCodes" }),
100
+ };
101
+
102
+ export interface OutputArgs {
103
+ exportJson?: string;
104
+ format: FormatName;
105
+ quiet: boolean;
106
+ help: boolean;
107
+ }
108
+
109
+ export interface RunArgs extends OutputArgs {
110
+ noiseCheck: boolean;
111
+ }
112
+
113
+ export const OUTPUT_DEFAULTS = {
114
+ format: "table",
115
+ quiet: false,
116
+ help: false,
117
+ } as const;
118
+
119
+ export const RUN_DEFAULTS = { ...OUTPUT_DEFAULTS, noiseCheck: true } as const;
120
+
121
+ export const HELP_FLAGS: FlagTable = {
122
+ "--help": flag.on("help"),
123
+ "-h": flag.on("help"),
124
+ };
125
+
126
+ export const OUTPUT_FLAGS: FlagTable = {
127
+ ...HELP_FLAGS,
128
+ "--export-json": flag.str("exportJson"),
129
+ "--format": flag.oneOf("format", DOCUMENT_FORMATS),
130
+ "--quiet": flag.on("quiet"),
131
+ };
132
+
133
+ export const NOISE_CHECK_FLAGS: FlagTable = {
134
+ "--no-noise-check": flag.off("noiseCheck"),
135
+ };
136
+
137
+ /**
138
+ * `--config PATH`: for the commands that read a config file (bench, ab,
139
+ * compare, ci, baseline).
140
+ */
141
+ export const CONFIG_FLAGS: FlagTable = {
142
+ "--config": flag.str("config"),
143
+ };
144
+
145
+ export interface ConfigArgs {
146
+ config?: string;
147
+ }
148
+
149
+ /**
150
+ * Flags shared by every command that runs measurements (`ci` has no
151
+ * per-run flags).
152
+ */
153
+ export const RUN_FLAGS: FlagTable = {
154
+ ...OUTPUT_FLAGS,
155
+ ...NOISE_CHECK_FLAGS,
156
+ "--timeout": flag.int("timeoutMs"),
157
+ "--out-dir": flag.str("outDir"),
158
+ };
159
+
160
+ /** Flags shared by `bench` and `ab`. */
161
+ export const SUITE_FLAGS: FlagTable = {
162
+ ...RUN_FLAGS,
163
+ ...CONFIG_FLAGS,
164
+ "--filter": flag.str("filter"),
165
+ "--preload": flag.list("preload"),
166
+ "--bun-flags": flag.words("bunFlags"),
167
+ };
168
+
169
+ interface ParseSpec<T> {
170
+ command: string;
171
+ flags: FlagTable;
172
+ args: T;
173
+ /** Receives each bare word; omitted, a bare word is an unknown-flag error. */
174
+ positional?: (arg: string, args: T) => void;
175
+ /**
176
+ * Receives everything after a `--`, verbatim; omitted, `--` is an unknown
177
+ * flag.
178
+ */
179
+ rest?: (rest: string[], args: T) => void;
180
+ }
181
+
182
+ /**
183
+ * Parses `argv` into `args` per `flags`; `--flag=value` equals `--flag
184
+ * value`. Throws `CliUsageError`.
185
+ */
186
+ export function parseFlags<T extends object>(
187
+ argv: string[],
188
+ { command, flags, args, positional, rest }: ParseSpec<T>,
189
+ ): T {
190
+ const bag = args as Record<string, unknown>;
191
+ for (let i = 0; i < argv.length; i++) {
192
+ const arg = argv[i]!;
193
+ if (arg === "--" && rest) {
194
+ rest(argv.slice(i + 1), args);
195
+ break;
196
+ }
197
+ const eq = arg.startsWith("--") ? arg.indexOf("=") : -1;
198
+ const name = eq > 0 ? arg.slice(0, eq) : arg;
199
+ const flagDef = Object.hasOwn(flags, name) ? flags[name] : undefined;
200
+ if (!flagDef || (eq > 0 && flagDef.spec.kind === "bool")) {
201
+ if (arg.startsWith("-") || !positional) {
202
+ throw new CliUsageError(
203
+ `Unknown flag "${arg}" for "ostia ${command}".`,
204
+ );
205
+ }
206
+ positional(arg, args);
207
+ continue;
208
+ }
209
+ const value = (): string => {
210
+ if (eq > 0) return arg.slice(eq + 1);
211
+ if (i + 1 >= argv.length) {
212
+ throw new CliUsageError(`Missing value for ${name}.`);
213
+ }
214
+ return argv[++i]!;
215
+ };
216
+ const { dest, spec } = flagDef;
217
+ switch (spec.kind) {
218
+ case "string":
219
+ bag[dest] = value();
220
+ break;
221
+ case "int":
222
+ bag[dest] = parseIntFlag(name, value(), spec);
223
+ break;
224
+ case "number": {
225
+ const raw = value();
226
+ const n = Number(raw);
227
+ if (raw === "" || !Number.isFinite(n) || n < spec.min) {
228
+ throw new CliUsageError(
229
+ `Invalid ${name} "${raw}": expected a number ≥ ${spec.min}`,
230
+ );
231
+ }
232
+ bag[dest] = n;
233
+ break;
234
+ }
235
+ case "bool":
236
+ bag[dest] = spec.value;
237
+ break;
238
+ case "list":
239
+ (bag[dest] as string[]).push(value());
240
+ break;
241
+ case "words":
242
+ (bag[dest] as string[]).push(...splitCommand(value()));
243
+ break;
244
+ case "exitCodes":
245
+ (bag[dest] as number[]).push(
246
+ ...(eq > 0
247
+ ? parseExitCodes(name, arg.slice(eq + 1))
248
+ : Array.from({ length: 255 }, (_, n) => n + 1)),
249
+ );
250
+ break;
251
+ case "enum": {
252
+ const raw = value();
253
+ if (!spec.values.includes(raw)) {
254
+ throw new CliUsageError(
255
+ `Invalid ${name} "${raw}": expected one of: ${spec.values.join(", ")}`,
256
+ );
257
+ }
258
+ bag[dest] = raw;
259
+ break;
260
+ }
261
+ }
262
+ }
263
+ return args;
264
+ }