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,275 @@
1
+ import { DEFAULT_THRESHOLDS, type Thresholds } from "../compare/index.ts";
2
+ import { errorMessage } from "../errors.ts";
3
+ import type { PrepareHook, TimeSource } from "../spawn/index.ts";
4
+ import { ConfigError, validateConfig } from "./validate.ts";
5
+
6
+ export { ConfigError };
7
+
8
+ /**
9
+ * Exactly one of `command` (a subprocess to time) / `suites` (in-process
10
+ * `group()`/`task()` suite file globs, run via `bench()`, each task gated
11
+ * individually) must be given. */
12
+ export interface WorkloadConfig {
13
+ label?: string;
14
+ command?: string[];
15
+ suites?: string[];
16
+ /**
17
+ * `command` only. Globs of the files the timing depends on: `ostia ci`
18
+ * reuses a cached run while their contents are unchanged. Omitted, the
19
+ * workload always reruns; `[]` caches until the command or config changes.
20
+ * */
21
+ inputs?: string[];
22
+ /**
23
+ * `command` only. Runs before every trial (warmup included), unmeasured:
24
+ * a command string / argv array, or in `ostia.config.ts` a function. A
25
+ * function makes the workload uncacheable for `ostia ci`. */
26
+ prepare?: PrepareHook;
27
+ /**
28
+ * `command` only. Take timing from a number in the command's own output
29
+ * instead of its wall clock; see `TimeSource`. */
30
+ timeSource?: TimeSource;
31
+ /**
32
+ * `command`: kills a trial (or prepare hook) after this many ms.
33
+ * `suites`: kills a suite file's (or isolated task's) process after this
34
+ * many ms, overriding `bench.timeoutMs`. Overrides `ostia ci`'s 10-minute
35
+ * default. */
36
+ timeoutMs?: number;
37
+ /**
38
+ * `command` only. Exit codes to treat as success; see
39
+ * `TimeOptions.ignoreExitCodes`. */
40
+ ignoreExitCodes?: number[];
41
+ }
42
+
43
+ /**
44
+ * Launch settings for the suite files matching `suites`; see
45
+ * `BenchOptions.projects`. */
46
+ export interface BenchProject {
47
+ /**
48
+ * Globs against the current directory. A suite file takes the first
49
+ * project one of these matches; `ostia bench` with no files also runs
50
+ * every file they expand to. */
51
+ suites: string[];
52
+ /**
53
+ * Replaces the top-level `preload` for these files; `[]` runs them with
54
+ * none. Unset: the top-level list applies. */
55
+ preload?: string[];
56
+ /** Replaces the top-level `bunFlags` for these files, as `preload` does. */
57
+ bunFlags?: string[];
58
+ }
59
+
60
+ export interface BenchConfig {
61
+ /**
62
+ * Suite file globs, resolved against the config's directory (e.g.
63
+ * "bench/**\/*.bench.ts"). Suite files given on the command line replace
64
+ * this list. */
65
+ suites?: string[];
66
+ /**
67
+ * Per-suite `preload`/`bunFlags`, so one tier (e.g. DOM-dependent suites)
68
+ * can pay for a setup the others don't need. The first project whose
69
+ * `suites` match a file wins; a file no project matches gets the top-level
70
+ * `preload`/`bunFlags`. `--preload` / `--bun-flags` replace the matching
71
+ * field for every file. */
72
+ projects?: BenchProject[];
73
+ preload?: string[];
74
+ /**
75
+ * Extra flags for the `bun` process that runs each suite file; see
76
+ * `BenchOptions.bunFlags`. `--bun-flags` replaces this list. */
77
+ bunFlags?: string[];
78
+ jobs?: number | "auto";
79
+ budgetMs?: number;
80
+ samples?: number;
81
+ minSamples?: number;
82
+ gc?: boolean;
83
+ cpu?: boolean;
84
+ cpuIntervalUs?: number;
85
+ alloc?: boolean;
86
+ peakMem?: boolean;
87
+ filter?: string;
88
+ isolate?: boolean;
89
+ outDir?: string;
90
+ /**
91
+ * Kills a suite file's (or isolated task's) subprocess after this many
92
+ * ms; overrides `ostia ci`'s 10-minute default. */
93
+ timeoutMs?: number;
94
+ }
95
+
96
+ /**
97
+ * Settings for `ostia ab` only; it reads the rest (suites, filter,
98
+ * preload, ...) from `bench`. */
99
+ export interface AbConfig {
100
+ /**
101
+ * Shell command(s) run once in a freshly extracted base tree, e.g. to
102
+ * build gitignored files the suites import; see `AbOptions.baseSetup`.
103
+ * `--base-setup` replaces this list. */
104
+ setup?: string | string[];
105
+ /**
106
+ * Base trees to keep cached; see `AbOptions.keepTrees`. `--keep-trees`
107
+ * overrides. Default: 5. */
108
+ keepTrees?: number;
109
+ /**
110
+ * Judge rounds by `"time"` or `"instructions"`; see `AbOptions.metric`.
111
+ * `--metric` overrides. Default: `"time"`. */
112
+ metric?: "time" | "instructions";
113
+ /**
114
+ * Compare retained heap per call; see `AbOptions.alloc`. `--alloc` /
115
+ * `--no-alloc` override. `bench.alloc` doesn't apply to `ab`. */
116
+ alloc?: boolean;
117
+ /**
118
+ * Compare peak RSS of the first call; see `AbOptions.peakMem`.
119
+ * `--peak-mem` / `--no-peak-mem` override. `bench.peakMem` doesn't apply
120
+ * to `ab`. */
121
+ peakMem?: boolean;
122
+ /**
123
+ * Memory verdict threshold, percent; see `AbOptions.memThresholdPct`.
124
+ * `--mem-threshold` overrides. Default: 10. */
125
+ memThresholdPct?: number;
126
+ }
127
+
128
+ export interface OstiaConfig {
129
+ /** `command` workloads: exact trial count; see `time()`. */
130
+ samples?: number;
131
+ /** `command` workloads: sampling budget in ms; see `time()`. */
132
+ budgetMs?: number;
133
+ /** `command` workloads: floor on trials; see `time()`. */
134
+ minSamples?: number;
135
+ warmup: number;
136
+ outDir: string;
137
+ baselineDir: string;
138
+ baseline: string;
139
+ thresholds: Thresholds;
140
+ workloads: WorkloadConfig[];
141
+ bench?: BenchConfig;
142
+ ab?: AbConfig;
143
+ /**
144
+ * `ostia ci`'s policy for a workload with no matching baseline row (by
145
+ * workload id): `"fail"` exits 2 naming the baseline file, `"warn"` lists
146
+ * it in the report. Unset: `"fail"` when every workload is missing (a
147
+ * stale or wrong baseline), `"warn"` otherwise. */
148
+ onMissingBaseline?: "warn" | "fail";
149
+ /**
150
+ * Measure the machine's noise floor once per `ostia ci` run (default
151
+ * true) and stamp it on the candidate document, so `compare` widens its
152
+ * thresholds accordingly. `--no-noise-check` overrides this per run. */
153
+ noiseCheck?: boolean;
154
+ }
155
+
156
+ // Partial is shallow, so `thresholds` needs its own Partial to merge
157
+ // field-by-field.
158
+ export type OstiaConfigInput = Omit<Partial<OstiaConfig>, "thresholds"> & {
159
+ thresholds?: Partial<Thresholds>;
160
+ };
161
+
162
+ // node_modules/.cache is gitignored everywhere already.
163
+ export const DEFAULT_OUT_DIR = "node_modules/.cache/ostia";
164
+
165
+ // Baselines must survive node_modules churn, so they live outside outDir.
166
+ const DEFAULT_BASELINE_DIR = ".ostia/baselines";
167
+
168
+ export const DEFAULT_CONFIG: OstiaConfig = {
169
+ warmup: 3,
170
+ outDir: DEFAULT_OUT_DIR,
171
+ baselineDir: DEFAULT_BASELINE_DIR,
172
+ baseline: "main",
173
+ thresholds: DEFAULT_THRESHOLDS,
174
+ workloads: [],
175
+ };
176
+
177
+ // Renamed fields fail loudly instead of being silently ignored.
178
+ const RENAMED_FIELDS: Record<string, string> = { runs: "samples" };
179
+
180
+ /** In discovery order: `.ts` wins over JSON. */
181
+ export const CONFIG_FILES = ["ostia.config.ts", "ostia.config.json"];
182
+
183
+ const warnConfig = (message: string) => console.warn(`ostia: ${message}`);
184
+
185
+ /**
186
+ * An explicit `undefined` (`warmup: undefined`) means "unset", not
187
+ * "overwrite the default".
188
+ */
189
+ function withoutUndefined<T extends object>(obj: T): T {
190
+ return Object.fromEntries(
191
+ Object.entries(obj).filter(([, v]) => v !== undefined),
192
+ ) as T;
193
+ }
194
+
195
+ function resolveConfig(raw: unknown, path: string): OstiaConfig {
196
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
197
+ throw new ConfigError(`${path}: expected an object.`);
198
+ }
199
+ for (const [old, current] of Object.entries(RENAMED_FIELDS)) {
200
+ if (old in raw) {
201
+ throw new ConfigError(`${path}: "${old}" was renamed to "${current}".`);
202
+ }
203
+ }
204
+ validateConfig(raw as Record<string, unknown>, path, warnConfig);
205
+ const input = withoutUndefined(raw as OstiaConfigInput);
206
+ return {
207
+ ...DEFAULT_CONFIG,
208
+ ...input,
209
+ thresholds: {
210
+ ...DEFAULT_THRESHOLDS,
211
+ ...(input.thresholds && withoutUndefined(input.thresholds)),
212
+ },
213
+ };
214
+ }
215
+
216
+ async function readConfigFile(path: string): Promise<unknown> {
217
+ const absPath = path.startsWith("/") ? path : `${process.cwd()}/${path}`;
218
+ const file = Bun.file(absPath);
219
+ if (!(await file.exists())) return undefined;
220
+ try {
221
+ if (!path.endsWith(".ts")) return await file.json();
222
+ const exported = (await import(absPath)).default;
223
+ if (exported === undefined) {
224
+ throw new Error(
225
+ `no default export; use "export default defineConfig({ ... })"`,
226
+ );
227
+ }
228
+ return exported;
229
+ } catch (err) {
230
+ throw new ConfigError(`${path}: ${errorMessage(err)}`);
231
+ }
232
+ }
233
+
234
+ async function existingConfigFiles(): Promise<string[]> {
235
+ const found: string[] = [];
236
+ for (const file of CONFIG_FILES) {
237
+ if (await Bun.file(file).exists()) found.push(file);
238
+ }
239
+ return found;
240
+ }
241
+
242
+ /**
243
+ * Loads `path` (`.ts` or JSON by extension), or with no `path` the file
244
+ * `configFilePath()` finds. `undefined` when there is no such file. Throws
245
+ * `ConfigError` for a file that exists but is unusable, naming the bad
246
+ * key. */
247
+ export async function loadConfig(
248
+ path?: string,
249
+ ): Promise<OstiaConfig | undefined> {
250
+ let file = path;
251
+ if (file === undefined) {
252
+ const found = await existingConfigFiles();
253
+ if (found.length > 1) {
254
+ warnConfig(
255
+ `${found.join(" and ")} both exist; using ${found[0]} and ignoring the rest.`,
256
+ );
257
+ }
258
+ file = found[0];
259
+ }
260
+ if (file === undefined) return undefined;
261
+ const raw = await readConfigFile(file);
262
+ return raw === undefined ? undefined : resolveConfig(raw, file);
263
+ }
264
+
265
+ export function baselinePath(config: OstiaConfig, name?: string): string {
266
+ return `${config.baselineDir}/${name ?? config.baseline}.json`;
267
+ }
268
+
269
+ /**
270
+ * The config file discovery would load from the current directory, `.ts`
271
+ * before JSON.
272
+ */
273
+ export async function configFilePath(): Promise<string | undefined> {
274
+ return (await existingConfigFiles())[0];
275
+ }
@@ -0,0 +1,267 @@
1
+ /**
2
+ * A config file that exists but can't be used; the CLI reports it as
3
+ * `config-invalid`.
4
+ */
5
+ export class ConfigError extends Error {}
6
+
7
+ type Rule = (v: unknown) => boolean;
8
+
9
+ const isObject = (v: unknown): v is Record<string, unknown> =>
10
+ typeof v === "object" && v !== null && !Array.isArray(v);
11
+
12
+ const isInt =
13
+ (min: number): Rule =>
14
+ (v) =>
15
+ typeof v === "number" && Number.isInteger(v) && v >= min;
16
+ const isNum =
17
+ (min: number): Rule =>
18
+ (v) =>
19
+ typeof v === "number" && Number.isFinite(v) && v >= min;
20
+ const isString: Rule = (v) => typeof v === "string";
21
+ const isBool: Rule = (v) => typeof v === "boolean";
22
+ const isStringArray: Rule = (v) => Array.isArray(v) && v.every(isString);
23
+ const oneOf =
24
+ (...values: unknown[]): Rule =>
25
+ (v) =>
26
+ values.includes(v);
27
+
28
+ interface Field {
29
+ ok: Rule;
30
+ expects: string;
31
+ }
32
+
33
+ const field = (ok: Rule, expects: string): Field => ({ ok, expects });
34
+ const posInt = field(isInt(1), "a positive integer");
35
+ const nonNegInt = field(isInt(0), "a non-negative integer");
36
+ const text = field(isString, "a string");
37
+ const flag = field(isBool, "a boolean");
38
+ const strings = field(isStringArray, "an array of strings");
39
+
40
+ const THRESHOLD_FIELDS: Record<string, Field> = {
41
+ timingPct: field(isNum(0), "a non-negative number"),
42
+ frameSelfPct: field(isNum(0), "a non-negative number"),
43
+ heapTypePct: field(isNum(0), "a non-negative number"),
44
+ minFrameSelfUs: field(isNum(0), "a non-negative number"),
45
+ alpha: field((v) => isNum(0)(v) && (v as number) <= 1, "a number in [0, 1]"),
46
+ bootstrapIterations: posInt,
47
+ };
48
+
49
+ const PROJECT_FIELDS: Record<string, Field> = {
50
+ suites: field(
51
+ (v) => isStringArray(v) && (v as string[]).length > 0,
52
+ "a non-empty array of glob strings",
53
+ ),
54
+ preload: strings,
55
+ bunFlags: strings,
56
+ };
57
+
58
+ const BENCH_FIELDS: Record<string, Field> = {
59
+ suites: strings,
60
+ projects: field(Array.isArray, "an array of project objects"),
61
+ preload: strings,
62
+ bunFlags: strings,
63
+ jobs: field(
64
+ (v) => isInt(1)(v) || v === "auto",
65
+ `a positive integer or "auto"`,
66
+ ),
67
+ budgetMs: field(isNum(0), "a non-negative number"),
68
+ samples: posInt,
69
+ minSamples: posInt,
70
+ gc: flag,
71
+ cpu: flag,
72
+ cpuIntervalUs: posInt,
73
+ alloc: flag,
74
+ peakMem: flag,
75
+ filter: text,
76
+ isolate: flag,
77
+ outDir: text,
78
+ timeoutMs: posInt,
79
+ };
80
+
81
+ const AB_FIELDS: Record<string, Field> = {
82
+ setup: field(
83
+ (v) => isString(v) || isStringArray(v),
84
+ "a command string or an array of them",
85
+ ),
86
+ keepTrees: posInt,
87
+ metric: field(oneOf("time", "instructions"), `"time" or "instructions"`),
88
+ alloc: flag,
89
+ peakMem: flag,
90
+ memThresholdPct: field(isNum(0), "a non-negative number"),
91
+ };
92
+
93
+ const COMMAND_ONLY = ["inputs", "prepare", "timeSource", "ignoreExitCodes"];
94
+
95
+ const WORKLOAD_FIELDS: Record<string, Field> = {
96
+ label: text,
97
+ command: field(
98
+ (v) => isStringArray(v) && (v as string[]).length > 0,
99
+ "a non-empty array of strings (argv, no shell)",
100
+ ),
101
+ suites: field(
102
+ (v) => isStringArray(v) && (v as string[]).length > 0,
103
+ "a non-empty array of glob strings",
104
+ ),
105
+ inputs: strings,
106
+ prepare: field(
107
+ (v) => isString(v) || isStringArray(v) || typeof v === "function",
108
+ "a command string, an argv array, or (ostia.config.ts) a function",
109
+ ),
110
+ timeSource: field(
111
+ (v) =>
112
+ isObject(v) &&
113
+ (isString(v.pattern) || v.pattern instanceof RegExp) &&
114
+ (v.group === undefined || isInt(0)(v.group)) &&
115
+ (v.unit === undefined || oneOf("ns", "us", "ms", "s")(v.unit)),
116
+ `an object { pattern, group?, unit? } with a regex source string (or RegExp) pattern, an integer group, and unit "ns" | "us" | "ms" | "s"`,
117
+ ),
118
+ timeoutMs: posInt,
119
+ ignoreExitCodes: field(
120
+ (v) =>
121
+ Array.isArray(v) && v.every((c) => isInt(0)(c) && (c as number) <= 255),
122
+ "an array of exit codes 0-255",
123
+ ),
124
+ };
125
+
126
+ const TOP_FIELDS: Record<string, Field> = {
127
+ samples: posInt,
128
+ budgetMs: field(isNum(0), "a non-negative number"),
129
+ minSamples: posInt,
130
+ warmup: nonNegInt,
131
+ outDir: field((v) => isString(v) && v !== "", "a non-empty string"),
132
+ baselineDir: field((v) => isString(v) && v !== "", "a non-empty string"),
133
+ baseline: field((v) => isString(v) && v !== "", "a non-empty string"),
134
+ onMissingBaseline: field(oneOf("warn", "fail"), `"warn" or "fail"`),
135
+ noiseCheck: flag,
136
+ };
137
+
138
+ const describe = (v: unknown): string =>
139
+ typeof v === "function"
140
+ ? "a function"
141
+ : v instanceof RegExp
142
+ ? String(v)
143
+ : (JSON.stringify(v) ?? String(v));
144
+
145
+ /**
146
+ * Checks each present (non-`undefined`) key of `obj` against `fields`;
147
+ * unknown keys are reported to `warn` rather than failing, as they always
148
+ * were ignored. A `$`-prefixed key (`"$schema"`) is never reported. */
149
+ function checkFields(
150
+ obj: Record<string, unknown>,
151
+ fields: Record<string, Field>,
152
+ where: string,
153
+ file: string,
154
+ warn: (message: string) => void,
155
+ ): void {
156
+ const prefix = where === "" ? "" : `${where}.`;
157
+ for (const [key, value] of Object.entries(obj)) {
158
+ if (value === undefined) continue;
159
+ const spec = Object.hasOwn(fields, key) ? fields[key] : undefined;
160
+ if (!spec) {
161
+ if (!key.startsWith("$")) {
162
+ warn(`${file}: unknown key "${prefix}${key}" is ignored.`);
163
+ }
164
+ } else if (!spec.ok(value)) {
165
+ throw new ConfigError(
166
+ `${file}: "${prefix}${key}" must be ${spec.expects}, got ${describe(value)}.`,
167
+ );
168
+ }
169
+ }
170
+ }
171
+
172
+ function checkObject(
173
+ value: unknown,
174
+ where: string,
175
+ file: string,
176
+ ): Record<string, unknown> {
177
+ if (!isObject(value)) {
178
+ throw new ConfigError(
179
+ `${file}: "${where}" must be an object, got ${describe(value)}.`,
180
+ );
181
+ }
182
+ return value;
183
+ }
184
+
185
+ function checkWorkload(
186
+ wc: unknown,
187
+ i: number,
188
+ file: string,
189
+ warn: (message: string) => void,
190
+ ): void {
191
+ const where = `workloads[${i}]`;
192
+ const obj = checkObject(wc, where, file);
193
+ const has = (key: string) => obj[key] !== undefined;
194
+ if (has("command") === has("suites")) {
195
+ throw new ConfigError(
196
+ `${file}: "${where}" needs exactly one of "command" or "suites".`,
197
+ );
198
+ }
199
+ checkFields(obj, WORKLOAD_FIELDS, where, file, warn);
200
+ if (has("suites")) {
201
+ for (const key of COMMAND_ONLY) {
202
+ if (has(key)) {
203
+ warn(
204
+ `${file}: "${where}.${key}" applies to command workloads only; ignored on a suites workload.`,
205
+ );
206
+ }
207
+ }
208
+ }
209
+ const source = (obj.timeSource as { pattern?: unknown } | undefined)?.pattern;
210
+ if (typeof source === "string") {
211
+ try {
212
+ new RegExp(source);
213
+ } catch (err) {
214
+ throw new ConfigError(
215
+ `${file}: "${where}.timeSource.pattern" is not a valid regex: ${(err as Error).message}`,
216
+ );
217
+ }
218
+ }
219
+ }
220
+
221
+ /**
222
+ * Throws `ConfigError` naming the offending key for a wrong type or value;
223
+ * `warn` gets keys that are unknown (or inapplicable) and so ignored.
224
+ * `raw` is the already-object-checked config with `undefined` values still
225
+ * present. */
226
+ export function validateConfig(
227
+ raw: Record<string, unknown>,
228
+ file: string,
229
+ warn: (message: string) => void,
230
+ ): void {
231
+ const { thresholds, workloads, bench, ab, ...rest } = raw;
232
+ checkFields(rest, TOP_FIELDS, "", file, warn);
233
+ if (thresholds !== undefined) {
234
+ checkFields(
235
+ checkObject(thresholds, "thresholds", file),
236
+ THRESHOLD_FIELDS,
237
+ "thresholds",
238
+ file,
239
+ warn,
240
+ );
241
+ }
242
+ if (bench !== undefined) {
243
+ const benchObj = checkObject(bench, "bench", file);
244
+ checkFields(benchObj, BENCH_FIELDS, "bench", file, warn);
245
+ (benchObj.projects as unknown[] | undefined)?.forEach((project, i) => {
246
+ const where = `bench.projects[${i}]`;
247
+ const obj = checkObject(project, where, file);
248
+ if (obj.suites === undefined) {
249
+ throw new ConfigError(`${file}: "${where}" needs "suites".`);
250
+ }
251
+ checkFields(obj, PROJECT_FIELDS, where, file, warn);
252
+ });
253
+ }
254
+ if (ab !== undefined) {
255
+ checkFields(checkObject(ab, "ab", file), AB_FIELDS, "ab", file, warn);
256
+ }
257
+ if (workloads !== undefined) {
258
+ if (!Array.isArray(workloads)) {
259
+ throw new ConfigError(
260
+ `${file}: "workloads" must be an array, got ${describe(workloads)}.`,
261
+ );
262
+ }
263
+ workloads.forEach((wc, i) => {
264
+ checkWorkload(wc, i, file, warn);
265
+ });
266
+ }
267
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,8 @@
1
+ export function errorMessage(err: unknown): string {
2
+ return err instanceof Error ? err.message : String(err);
3
+ }
4
+
5
+ /** The caller's input can't be run as given (missing suite, bad ref, absent
6
+ * baseline): the CLI reports it as a usage error (exit 2) rather than an
7
+ * internal failure. */
8
+ export class OstiaUsageError extends Error {}
package/src/format.ts ADDED
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Duration formatting shared by the stats warnings and every renderer; a
3
+ * leaf module so neither imports the other. */
4
+ export type DurationUnit = "ns" | "µs" | "ms" | "s";
5
+
6
+ const UNIT_DIVISORS: Record<DurationUnit, number> = {
7
+ ns: 1,
8
+ µs: 1e3,
9
+ ms: 1e6,
10
+ s: 1e9,
11
+ };
12
+
13
+ export function pickDurationUnit(ns: number): DurationUnit {
14
+ const abs = Math.abs(ns);
15
+ if (abs >= 1e9) return "s";
16
+ if (abs >= 1e6) return "ms";
17
+ if (abs >= 1e3) return "µs";
18
+ return "ns";
19
+ }
20
+
21
+ // 2 decimals under 10, else 1: never fewer than one.
22
+ function sigFigDecimals(value: number): number {
23
+ const intDigits = Math.floor(Math.log10(Math.max(Math.abs(value), 1))) + 1;
24
+ return Math.max(1, 3 - intDigits);
25
+ }
26
+
27
+ /**
28
+ * Adaptive-unit duration, e.g. `3.02 ns`, `12.4 µs`, `275.8 ms`. Pass
29
+ * `unit` to keep a row's columns in one unit. */
30
+ export function formatDuration(
31
+ ns: number,
32
+ unit: DurationUnit = pickDurationUnit(ns),
33
+ ): string {
34
+ const value = ns / UNIT_DIVISORS[unit];
35
+ return `${value.toFixed(sigFigDecimals(value))} ${unit}`;
36
+ }
package/src/glob.ts ADDED
@@ -0,0 +1,48 @@
1
+ import { resolve } from "node:path";
2
+
3
+ const SKIPPED_DIRS = ["node_modules", ".git"];
4
+ // Where `ostia ab` extracts base trees: copies of the project.
5
+ const AB_TREES = ".ostia/ab";
6
+ // `@(` and `+(` open extglobs (Bun 1.4.4+); a bare `(` stays literal, as
7
+ // in `app/(marketing)`.
8
+ const GLOB_CHARS = /[*?[\]{}!]|[@+]\(/;
9
+
10
+ /**
11
+ * Segments after the pattern's literal prefix, i.e. the part the wildcards
12
+ * chose.
13
+ */
14
+ function wildcardSegments(pattern: string, path: string): [string[], string[]] {
15
+ const patternSegs = pattern.split("/");
16
+ const literal = patternSegs.findIndex((s) => GLOB_CHARS.test(s));
17
+ const from = literal < 0 ? patternSegs.length : literal;
18
+ return [patternSegs.slice(from), path.split("/").slice(from)];
19
+ }
20
+
21
+ /**
22
+ * Paths under `cwd` matching any of `patterns`, relative to `cwd`, deduped
23
+ * and sorted. Dotfiles match (`.github/**`), but wildcards never descend
24
+ * into `node_modules`, `.git` or `.ostia/ab` unless the pattern names that
25
+ * directory itself. */
26
+ export async function scanGlobs(
27
+ patterns: string[],
28
+ cwd: string,
29
+ ): Promise<string[]> {
30
+ const paths = new Set<string>();
31
+ for (const pattern of patterns) {
32
+ // Bun.Glob matches nothing for an absolute path with no wildcard.
33
+ if (!GLOB_CHARS.test(pattern)) {
34
+ if (await Bun.file(resolve(cwd, pattern)).exists()) paths.add(pattern);
35
+ continue;
36
+ }
37
+ for await (const path of new Bun.Glob(pattern).scan({ cwd, dot: true })) {
38
+ const [named, matched] = wildcardSegments(pattern, path);
39
+ const skipped = matched.some(
40
+ (seg) => SKIPPED_DIRS.includes(seg) && !named.includes(seg),
41
+ );
42
+ const inTrees =
43
+ `/${path}/`.includes(`/${AB_TREES}/`) && !pattern.includes(AB_TREES);
44
+ if (!skipped && !inTrees) paths.add(path);
45
+ }
46
+ }
47
+ return [...paths].sort();
48
+ }
package/src/index.ts ADDED
@@ -0,0 +1,62 @@
1
+ import type { OstiaConfigInput } from "./config/index.ts";
2
+
3
+ export type { AbOptions, AbProgress } from "./ab/index.ts";
4
+ export { AbBaseError, AbSetupError, AbSuiteError, ab } from "./ab/index.ts";
5
+ export type { BenchOptions } from "./bench/index.ts";
6
+ export { bench } from "./bench/index.ts";
7
+ export { range } from "./bench/range.ts";
8
+ export type { GroupOptions, TaskOptions } from "./bench/registry.ts";
9
+ export { group, task } from "./bench/registry.ts";
10
+ export type { RunOptions } from "./bench/run.ts";
11
+ export { run } from "./bench/run.ts";
12
+ export { sweep } from "./bench/sweep.ts";
13
+ export type { CompareResult, Thresholds } from "./compare/index.ts";
14
+ export { compareDocuments, DEFAULT_THRESHOLDS } from "./compare/index.ts";
15
+ export type {
16
+ AbConfig,
17
+ BenchProject,
18
+ OstiaConfig,
19
+ OstiaConfigInput,
20
+ WorkloadConfig,
21
+ } from "./config/index.ts";
22
+ export {
23
+ createDocument,
24
+ loadDocument,
25
+ OstiaDocumentError,
26
+ saveDocument,
27
+ } from "./ir/document.ts";
28
+ export type {
29
+ Comparison,
30
+ ProfileDocument,
31
+ Warning,
32
+ WarningCode,
33
+ Workload,
34
+ } from "./ir/types.ts";
35
+ export { keep } from "./measure/inprocess.ts";
36
+ export type { ProfileOptions, ProfileResult } from "./profile.ts";
37
+ export { profile } from "./profile.ts";
38
+ export { renderers } from "./renderers/index.ts";
39
+ export type { MermaidOptions } from "./renderers/mermaid.ts";
40
+ // `MinimalEvent` is one parsed line of `--format minimal` output; narrow
41
+ // on `event`.
42
+ export type {
43
+ MinimalEvent,
44
+ MinimalProtocolContext,
45
+ MinimalRenderOptions,
46
+ } from "./renderers/minimal.ts";
47
+ export { MINIMAL_PROTOCOL_VERSION } from "./renderers/minimal.ts";
48
+ export type { VizOptions } from "./renderers/types.ts";
49
+ export type {
50
+ PrepareFn,
51
+ PrepareHook,
52
+ PrepareRun,
53
+ TimeSource,
54
+ TimeUnit,
55
+ } from "./spawn/index.ts";
56
+ export type { CommandSpec, TimeOptions } from "./time.ts";
57
+ export { time } from "./time.ts";
58
+
59
+ /** Identity function that types an `ostia.config.ts` default export. */
60
+ export function defineConfig(config: OstiaConfigInput): OstiaConfigInput {
61
+ return config;
62
+ }