ostia 0.2.12 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -358
  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 +923 -679
  11. package/package.json +16 -14
  12. package/src/ab/ab-runner.ts +487 -0
  13. package/src/ab/index.ts +1160 -0
  14. package/src/baseline/index.ts +69 -0
  15. package/src/bench/index.ts +516 -0
  16. package/src/bench/projects.ts +43 -0
  17. package/src/bench/range.ts +27 -0
  18. package/src/bench/registry.ts +426 -0
  19. package/src/bench/run-tasks.ts +179 -0
  20. package/src/bench/run.ts +52 -0
  21. package/src/bench/runner.ts +162 -0
  22. package/src/bench/support.ts +161 -0
  23. package/src/bench/sweep.ts +41 -0
  24. package/src/cache/fingerprint.ts +62 -0
  25. package/src/cache/store.ts +40 -0
  26. package/src/capture/bunflags.ts +92 -0
  27. package/src/capture/cpu-parse.ts +131 -0
  28. package/src/capture/cpu.ts +47 -0
  29. package/src/capture/frames.ts +60 -0
  30. package/src/capture/heap-parse.ts +111 -0
  31. package/src/capture/heap.ts +36 -0
  32. package/src/capture/inspector.ts +47 -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 +440 -0
  37. package/src/cli/flags.ts +263 -0
  38. package/{chunk-9sx15b08.js → src/cli/help.ts} +23 -11
  39. package/src/cli/main.ts +18 -0
  40. package/src/cli/output.ts +179 -0
  41. package/src/cli/run.ts +1110 -0
  42. package/src/compare/index.ts +624 -0
  43. package/src/config/env.ts +13 -0
  44. package/src/config/index.ts +283 -0
  45. package/src/config/validate.ts +273 -0
  46. package/src/errors.ts +8 -0
  47. package/src/format.ts +35 -0
  48. package/src/glob.ts +45 -0
  49. package/src/index.ts +60 -0
  50. package/src/ir/cpu.ts +10 -0
  51. package/src/ir/defined.ts +12 -0
  52. package/src/ir/document.ts +491 -0
  53. package/src/ir/fp.ts +28 -0
  54. package/src/ir/git.ts +37 -0
  55. package/src/ir/types.ts +615 -0
  56. package/src/measure/alloc.ts +56 -0
  57. package/src/measure/cpu.ts +91 -0
  58. package/src/measure/environment.ts +38 -0
  59. package/src/measure/inprocess.ts +191 -0
  60. package/src/measure/instructions.ts +139 -0
  61. package/src/measure/loop.ts +64 -0
  62. package/src/measure/noise.ts +55 -0
  63. package/src/measure/paired.ts +304 -0
  64. package/src/measure/peak.ts +201 -0
  65. package/src/measure/timing.ts +263 -0
  66. package/src/profile.ts +110 -0
  67. package/src/renderers/collapsed.ts +42 -0
  68. package/src/renderers/cpu-tree.ts +191 -0
  69. package/src/renderers/cpuprofile.ts +43 -0
  70. package/src/renderers/format.ts +132 -0
  71. package/src/renderers/index.ts +37 -0
  72. package/src/renderers/json.ts +10 -0
  73. package/src/renderers/jsonl.ts +19 -0
  74. package/src/renderers/markdown.ts +543 -0
  75. package/src/renderers/mermaid.ts +90 -0
  76. package/src/renderers/minimal.ts +602 -0
  77. package/src/renderers/paired.ts +223 -0
  78. package/src/renderers/relative.ts +60 -0
  79. package/src/renderers/select.ts +264 -0
  80. package/src/renderers/speedscope.ts +73 -0
  81. package/src/renderers/terminal.ts +470 -0
  82. package/src/renderers/types.ts +27 -0
  83. package/src/spawn/index.ts +387 -0
  84. package/src/stats/bootstrap.ts +151 -0
  85. package/src/stats/index.ts +144 -0
  86. package/src/stats/mannwhitney.ts +82 -0
  87. package/src/time.ts +337 -0
  88. package/src/version.ts +3 -0
  89. package/ab-runner.ts +0 -8
  90. package/chunk-05jfst35.js +0 -28
  91. package/chunk-1g1x9zz2.js +0 -15
  92. package/chunk-23g2rwrn.js +0 -3
  93. package/chunk-468h5412.js +0 -25
  94. package/chunk-4esjfc2m.js +0 -2
  95. package/chunk-ct2xsezd.js +0 -14
  96. package/cli.js +0 -3
  97. package/index.js +0 -2
  98. package/runner.ts +0 -7
@@ -0,0 +1,421 @@
1
+ # Library API
2
+
3
+ The CLI is a thin wrapper over these functions;
4
+ both produce the same `ProfileDocument`
5
+ ([document-schema.md](document-schema.md)).
6
+
7
+ ```ts
8
+ import {
9
+ time, profile, bench, ab, group, task, sweep, range, run, keep,
10
+ compareDocuments, DEFAULT_THRESHOLDS, defineConfig,
11
+ createDocument, loadDocument, saveDocument, OstiaDocumentError,
12
+ renderers, MINIMAL_PROTOCOL_VERSION,
13
+ } from "ostia"
14
+ import type {
15
+ ProfileDocument, Workload, Comparison, Warning, WarningCode, CompareResult, Thresholds,
16
+ TaskOptions, GroupOptions, RunOptions, OstiaConfig, OstiaConfigInput, WorkloadConfig,
17
+ TimeOptions, CommandSpec, PrepareHook, PrepareFn, PrepareRun, TimeSource, TimeUnit,
18
+ BenchOptions, AbOptions, ProfileOptions, ProfileResult,
19
+ MinimalEvent, MinimalRenderOptions, MinimalProtocolContext, MermaidOptions, VizOptions,
20
+ } from "ostia"
21
+ ```
22
+
23
+ ## `time(opts)` → `Promise<ProfileDocument>`
24
+
25
+ Subprocess timing; the same behavior as `ostia time`
26
+ ([cli.md](cli.md#ostia-time)).
27
+
28
+ ```ts
29
+ const controller = new AbortController()
30
+ const doc = await time({
31
+ commands: ["bun a.ts", ["bun", "-e", "console.log('a b')"]],
32
+ prepare: "rm -rf dist", // before every trial; or ({ phase, index }) => ...
33
+ timeSource: { pattern: /in (\d+)ms/, unit: "ms" },
34
+ samples: 10, // or budgetMs / minSamples
35
+ warmup: 2,
36
+ interleave: true, // default with 2+ commands
37
+ cpu: true,
38
+ heap: false,
39
+ cpuIntervalUs: 1000, // default
40
+ cwd: "packages/app",
41
+ env: { NODE_ENV: "production" },
42
+ outDir: "node_modules/.cache/ostia",
43
+ noiseCheck: true,
44
+ timeoutMs: 30_000, // no default
45
+ ignoreExitCodes: [1],
46
+ signal: controller.signal,
47
+ })
48
+ ```
49
+
50
+ A command is a string (whitespace-split, no shell), an argv array,
51
+ or an object
52
+ `{ command, label?, prepare?, timeSource?, timeoutMs?, ignoreExitCodes? }`
53
+ whose fields override the top-level ones for that command.
54
+ That's how one command becomes several labeled workloads:
55
+
56
+ ```ts
57
+ const build = ["bun", "cli.ts", "build", "fixture"]
58
+ const inMs = { pattern: /in (\d+)ms/ }
59
+ const doc = await time({
60
+ commands: [
61
+ { command: build, label: "warm", timeSource: inMs },
62
+ { command: build, label: "incremental", timeSource: inMs, prepare: () => touchPost() },
63
+ { command: build, label: "cold", timeSource: inMs, prepare: "rm -rf fixture/dist" },
64
+ { command: build, label: "wall clock" },
65
+ ],
66
+ samples: 5,
67
+ })
68
+ ```
69
+
70
+ A `prepare` function receives `{ phase, index }` with `phase` one of
71
+ `"warmup"`, `"timing"`, `"cpu"`, `"heap"`.
72
+ A `RegExp` `timeSource` pattern must not have the `g`, `y` or `d` flag;
73
+ `time()` rejects with a `RangeError` before running anything.
74
+
75
+ A command stops at its first non-ignored non-zero exit.
76
+ `time()` still resolves; check `Trial.exitCode` or the `nonzero-exit`
77
+ warning.
78
+ Aborting `signal` kills in-flight children and resolves with the
79
+ measurements completed so far, the last one carrying an `aborted`
80
+ warning.
81
+
82
+ ## `profile(fn, opts?)` → `Promise<{ result, measurement, document }>`
83
+
84
+ CPU capture of a function in the current process.
85
+ The default `origin: "inspector"` produces CDP-shaped evidence;
86
+ `origin: "jsc"` uses `bun:jsc`'s sampling profiler
87
+ and adds JIT tier counts (LLInt / Baseline / DFG / FTL).
88
+
89
+ ```ts
90
+ const { result, measurement, document } = await profile(() => hashLoop(8_000_000), {
91
+ origin: "jsc",
92
+ cpuIntervalUs: 100, // default 1000, as in time()/bench() and `--cpu-interval`
93
+ name: "hash loop", // optional: the workload's label and id
94
+ })
95
+ measurement.jit?.tiers // { llint: 0, baseline: 9, dfg: 37, ftl: 2825 }
96
+ const { files } = await renderers.collapsed.render(document, {})
97
+ ```
98
+
99
+ `document` holds the one workload and measurement.
100
+ An already-aborted `signal` runs `fn` without the profiler
101
+ and returns an `aborted` warning in place of CPU evidence;
102
+ a signal can't interrupt `fn` once it's running.
103
+
104
+ By default the workload id hashes the function's name and source text,
105
+ not the values it closes over: `() => work(n)` profiled for two
106
+ different `n` yields the same id twice,
107
+ and editing the function changes its id.
108
+ Pass `name` to identify the workload yourself:
109
+ the id then hashes `name` alone and `name` is also the label,
110
+ so differently-parameterised closures stay distinct under
111
+ `createDocument`, comparisons and renderers,
112
+ and the id survives edits to the function.
113
+ `name` must be a non-empty string.
114
+
115
+ ## Suites: `group()`, `task()`, `bench()`
116
+
117
+ ```ts
118
+ // suite.ts
119
+ import { group, task } from "ostia"
120
+
121
+ group("parse", () => {
122
+ task("small input", () => parse(smallBuf))
123
+ task("large input", () => parse(largeBuf))
124
+ task("full pipeline", () => build(), { budgetMs: 2000, minSamples: 10 })
125
+ })
126
+ ```
127
+
128
+ ```ts
129
+ const doc = await bench({
130
+ suites: ["bench/parse.ts"],
131
+ budgetMs: 500, // per task; default 500
132
+ // samples: 50, // exact per-task count instead
133
+ minSamples: 20,
134
+ jobs: 1,
135
+ isolate: false,
136
+ gc: false,
137
+ cpu: false,
138
+ cpuIntervalUs: 100, // default
139
+ alloc: false,
140
+ peakMem: false,
141
+ filter: "parse/",
142
+ preload: ["bench/setup.ts"],
143
+ bunFlags: ["--conditions=browser"],
144
+ timeoutMs: 60_000,
145
+ outDir: "node_modules/.cache/ostia",
146
+ cwd: process.cwd(),
147
+ noiseCheck: true,
148
+ })
149
+ ```
150
+
151
+ `bench()` runs each suite file in a child process
152
+ (and each isolated task in its own),
153
+ exactly like `ostia bench` ([cli.md](cli.md#ostia-bench)).
154
+ It rejects if a suite fails, if a suite file doesn't exist,
155
+ or if `jobs` isn't an integer >= 1.
156
+ Each call keeps its scratch files in a directory of its own under
157
+ `outDir`, so concurrent calls can share one.
158
+ It also takes a `signal`: aborting kills in-flight suite processes
159
+ and resolves with the suites and tasks that had finished.
160
+
161
+ ### `TaskOptions`
162
+
163
+ | Option | Meaning |
164
+ |---|---|
165
+ | `budgetMs`, `samples`, `minSamples` | Override the suite-wide sampling settings for this task. |
166
+ | `isolate`, `gc`, `cpu`, `alloc`, `peakMem` | Override the suite-wide flag (and the group's) for this task. |
167
+ | `baseline` | This task is the group's Relative reference (default: the group's fastest). |
168
+ | `description` | Stored as `Workload.description` and shown in `minimal` output. |
169
+ | `aliases` | Former names of the task in the same group. `compare`, `ci` and `ab` match a base measured under any of them, so a rename still compares. |
170
+ | `params` | Structured parameters; part of the workload id. Merged over the current `sweep()` point. |
171
+ | `before`, `after` | Run once, unmeasured, before the task's warmup and after its last trial, in the task's own process (works with `isolate`). |
172
+
173
+ `GroupOptions` takes `description`, `isolate`, `gc`, `cpu`, `alloc`,
174
+ `peakMem`, `before` and `after`; the flags are defaults for the group's
175
+ tasks, and `before`/`after` run once around the group's first
176
+ and last measured task.
177
+
178
+ Groups nest.
179
+ A task's group is the names of its enclosing groups joined with `/`,
180
+ outermost first, so a task `t` in `group("a")` > `group("b")` has id
181
+ `a/b/t` and `Workload.group` `a/b`
182
+ (ids of tasks in a single group are unchanged).
183
+ An inner group inherits what it doesn't set from the group around it:
184
+ `description`, `isolate`, `gc`, `cpu`,
185
+ `alloc` and `peakMem` (the inner value wins), and `.skip`/`.only`.
186
+ Hooks don't merge, they nest: the outer group's `before` runs once
187
+ before the first measured task anywhere inside it,
188
+ nested groups included, then each inner group's own,
189
+ and `after` runs innermost first.
190
+
191
+ ```ts
192
+ group(
193
+ "editor",
194
+ () => {
195
+ let doc: Document
196
+ task("append", () => doc.append(node), {
197
+ before: () => { doc = mountDocument() },
198
+ after: () => doc.destroy(),
199
+ description: "worst case: full repaint at max document size",
200
+ })
201
+ },
202
+ { before: setupSharedFixture, after: teardownSharedFixture, isolate: true },
203
+ )
204
+ ```
205
+
206
+ Module-scope code in a suite file runs once, before any task is sampled.
207
+ There is no per-trial hook, since that would defeat batching;
208
+ use `gc` or `isolate` for per-trial concerns.
209
+ Because `before`/`after` run once per task,
210
+ a suite that creates several instances of something stateful
211
+ (a mounted component, a server) needs to scope its queries to the
212
+ instance, not to a global lookup that assumes only one exists.
213
+
214
+ Task functions and hooks may be async.
215
+ Awaiting costs a microtask per call,
216
+ so an async task measures a few nanoseconds slower than the same
217
+ synchronous body.
218
+
219
+ ### `.skip` and `.only`
220
+
221
+ `task.skip()`/`group.skip()` register without measuring.
222
+ The workload stays in the document with `skipped: true`,
223
+ prints as `- skipped`, and `compare` treats it as unchanged with a
224
+ `skipped` warning.
225
+ `task.only()`/`group.only()` restrict the suite file to the marked tasks
226
+ (`--filter` still applies) and print
227
+ `bench: N task(s) selected by .only` to stderr, once per suite file,
228
+ so a forgotten `.only` is visible.
229
+ A `.skip` or `.only` group applies to the groups nested in it.
230
+ Under `ab`, a `.only` in the candidate suite also leaves out the tasks
231
+ that exist only at the base ref, as `--filter` does.
232
+
233
+ ### `keep(value)`
234
+
235
+ A task's return value is already protected from dead-code elimination.
236
+ Use `keep()` for an intermediate value the task doesn't return:
237
+
238
+ ```ts
239
+ task("parse then validate", () => {
240
+ const ast = parse(input)
241
+ keep(ast)
242
+ return validate(ast)
243
+ })
244
+ ```
245
+
246
+ ## `sweep(dims, fn)` and `range(start, end, multiplier = 8)`
247
+
248
+ `sweep()` calls `fn` once per point of the Cartesian product of `dims`;
249
+ `task()` calls inside inherit the point as `params`,
250
+ so each point is its own workload and `compare` matches points across
251
+ runs.
252
+
253
+ ```ts
254
+ group("parse", () => {
255
+ sweep({ size: range(100, 10_000), impl: ["current", "fast"] }, ({ size, impl }) => {
256
+ const input = buildInput(size) // once per point, unmeasured
257
+ task(impl, () => impls[impl](input))
258
+ })
259
+ })
260
+ ```
261
+
262
+ `range()` produces geometric points ending exactly on `end`:
263
+ `range(100, 10_000)` is `[100, 800, 6400, 10000]`.
264
+ The markdown renderer pivots a group into a table
265
+ (rows = first dimension, columns = second) when all its tasks share the
266
+ same two param keys; otherwise params print as a `key=value` suffix.
267
+
268
+ ## `run(opts?)` → `Promise<ProfileDocument>`
269
+
270
+ Runs the tasks registered in the current file, in the current process,
271
+ prints a report, and returns the document.
272
+ For a suite run directly with `bun suite.ts`:
273
+
274
+ ```ts
275
+ import { group, run, task } from "ostia"
276
+
277
+ group("parse", () => { task("small", () => parse(smallBuf)) })
278
+
279
+ try {
280
+ await run({ filter: process.env.FILTER })
281
+ } finally {
282
+ await cleanupFixtures()
283
+ }
284
+ ```
285
+
286
+ Options: `filter`, `budgetMs`, `samples`, `minSamples`,
287
+ `warmup` (a fraction of the budget, default 0.1), `gc`, `cpu`,
288
+ `cpuIntervalUs`, `alloc`, `noiseCheck`, `quiet` (don't print),
289
+ `format` (default `"table"`).
290
+ There is no subprocess, so `isolate` and `peakMem` are ignored;
291
+ prefer `ostia bench` or `bench()` for numbers you will compare.
292
+
293
+ ## `ab(opts)` → `Promise<ProfileDocument>`
294
+
295
+ Paired A/B timing of suite files against a git ref;
296
+ the same behavior as `ostia ab` ([cli.md](cli.md#ostia-ab)).
297
+ The suite files are the ones `bench()` runs, unchanged.
298
+
299
+ ```ts
300
+ const doc = await ab({
301
+ suites: ["bench/parse.bench.ts"],
302
+ base: "origin/main", // default "HEAD"; the candidate is the working tree
303
+ baseSetup: ["bun scripts/generate.ts"], // run once in a freshly extracted base tree
304
+ keepTrees: 5, // cached base trees to keep; default
305
+ rounds: 15, // default
306
+ metric: "time", // default; "instructions" judges instructions retired per call
307
+ thresholdPct: 10, // default
308
+ geomeanThresholdPct: 1.5, // default
309
+ confirm: 2, // fresh-process repeats per flagged task; default
310
+ alloc: true, // also compare retained heap per call
311
+ peakMem: true, // also compare first-call RSS rise; both use 3 fresh processes per side
312
+ memThresholdPct: 10, // default
313
+ filter: "parse/",
314
+ preload: ["bench/setup.ts"],
315
+ bunFlags: ["--conditions=browser"],
316
+ timeoutMs: 120_000,
317
+ outDir: "node_modules/.cache/ostia",
318
+ cwd: process.cwd(),
319
+ noiseCheck: true,
320
+ onProgress: (p) => console.error(p), // { phase: "setup" | "measure" | "confirm" | "memory", ... }
321
+ })
322
+ doc.ab // { base, matched, regressed, improved, unchanged, unconfirmed, outputDiffers, notComparable, threw, memory?, geomeanPct, verdict, ... }
323
+ doc.measurements // one phase: "paired" measurement per paired task; `threw` instead of `timing` when it threw
324
+ if (doc.ab!.verdict === "fail") process.exitCode = 1
325
+ ```
326
+
327
+ It rejects with a `RangeError` for bad settings,
328
+ with an `AbBaseError` when `cwd` isn't in a git repository
329
+ or `base` isn't a commit, with an `AbSetupError`
330
+ (its message ends with the command's output) when a `baseSetup` command
331
+ fails, and with an `AbSuiteError` when one side's suite fails outside
332
+ any task, such as on import; its `side` is `"base"` or `"cand"`.
333
+ A task that returns its result gets an output comparison between the two
334
+ sides for free (`paired.sameOutput`).
335
+
336
+ ## `compareDocuments(base, cand, thresholds?)` → `CompareResult`
337
+
338
+ The comparison behind `ostia compare`
339
+ and `ostia ci` ([statistics.md](statistics.md)).
340
+ `thresholds` defaults to `DEFAULT_THRESHOLDS` and must be complete;
341
+ spread over the defaults to change one field.
342
+
343
+ ```ts
344
+ const result = compareDocuments(base, cand, { ...DEFAULT_THRESHOLDS, timingPct: 3 })
345
+ result.comparisons // Comparison[], one per workload id in both documents
346
+ result.unmatched // { baseOnly: Workload[], candOnly: Workload[] }
347
+ result.summary // { matched, regressed, improved, unchanged, geomeanPct, effectiveTimingPct, verdict }
348
+ ```
349
+
350
+ `ostia compare` stores these on the candidate document as `comparisons`,
351
+ `comparisonSummary` and `unmatched` (ids only).
352
+
353
+ ## Documents
354
+
355
+ ```ts
356
+ const doc = createDocument(workloads, measurements) // optional 3rd arg: environment
357
+ await saveDocument(doc, "doc.json") // atomic write
358
+ const loaded = await loadDocument("doc.json") // throws OstiaDocumentError
359
+ ```
360
+
361
+ `createDocument` stamps versions, platform, timestamp and git metadata.
362
+ It's useful for combining several `profile()` results:
363
+
364
+ ```ts
365
+ const a = await profile(() => taskA())
366
+ const b = await profile(() => taskB())
367
+ const doc = createDocument(
368
+ [a.document.workloads[0]!, b.document.workloads[0]!],
369
+ [a.measurement, b.measurement],
370
+ )
371
+ ```
372
+
373
+ `loadDocument` accepts `schemaVersion: 2` only.
374
+
375
+ ## `renderers`
376
+
377
+ Each renderer is `{ name, render(doc, options) }` returning `{ text? }`
378
+ and/or `{ files? }`.
379
+ Names: `table`, `markdown`, `json`, `jsonl`, `minimal`, `collapsed`,
380
+ `mermaid`, `speedscope`, `cpuprofile`.
381
+ Each renderer's options are typed per format:
382
+ `collapsed`, `speedscope` and `cpuprofile` take `VizOptions`
383
+ (`{ measurementId? }`), `mermaid` takes `MermaidOptions`
384
+ (`VizOptions` plus `topN?`), `minimal` takes `MinimalRenderOptions`
385
+ (`{ protocol? }`, a `MinimalProtocolContext`, to emit the `unmatched`
386
+ and `summary` events), and the rest take no options (pass `{}`).
387
+
388
+ The `table` and `markdown` renderers agree on grouping
389
+ (a task's `group`, else the part of its id before the last `/`),
390
+ on percent deltas
391
+ (`+3.2%`, `-1.5%`, and `0.0%` with no sign when a delta rounds to zero),
392
+ on byte counts (1024-based `B`/`KiB`/`MiB`),
393
+ and on naming a comparison or capture whose workload is missing from the
394
+ document by its raw id.
395
+
396
+ ```ts
397
+ const { text } = await renderers.markdown.render(doc, {})
398
+ const { files } = await renderers.speedscope.render(doc, { measurementId })
399
+ ```
400
+
401
+ ## `defineConfig(config)`
402
+
403
+ Returns its argument unchanged; it exists to type-check
404
+ `ostia.config.ts`.
405
+ See [config.md](config.md).
406
+
407
+ ## Coming from mitata or hyperfine
408
+
409
+ | mitata / hyperfine | ostia |
410
+ |---|---|
411
+ | `bench("name", fn)` | `task("name", fn)` |
412
+ | `run()` at the bottom of the file | `run()` at the bottom of the file |
413
+ | `baseline()` | `task(name, fn, { baseline: true })` |
414
+ | `.range(name, start, end, mult)` | `sweep({ name: range(start, end, mult) }, ...)` |
415
+ | generator setup (`function* () { ...; yield fn }`) | `task(name, fn, { before, after })` |
416
+ | `do_not_optimize(value)` | `keep(value)` |
417
+ | `hyperfine --runs N --warmup N` | `ostia time --samples N --warmup N` |
418
+ | `hyperfine --prepare CMD` | `ostia time --prepare CMD` |
419
+ | `hyperfine -i` / `--ignore-failure` | `ostia time --ignore-failure` |
420
+ | `hyperfine -L var a,b cmd-{var}` | one command per value, or `sweep()` for in-process code |
421
+ | `hyperfine --export-json` / `--export-markdown` | `--export-json PATH` / `--format markdown` |
@@ -0,0 +1,169 @@
1
+ # preload recipes
2
+
3
+ `--preload PATH` (see [cli.md](cli.md#--preload-and---bun-flags)) is a
4
+ hook, not a feature - ostia runs your script before each suite file
5
+ loads and otherwise has no opinion on what's in it.
6
+ In practice, almost every adopter benchmarking DOM
7
+ or framework-component code ends up writing one of two scripts:
8
+ something that installs DOM globals,
9
+ or something that registers a `Bun.plugin()` loader for a
10
+ non-`.ts`/`.js` file type.
11
+ These are worked, copy-paste-adapt examples of both,
12
+ plus a lighter-weight DOM variant.
13
+ None of the packages below (`jsdom`, `happy-dom`, `svelte`) are ostia
14
+ dependencies - install whichever one your suite needs.
15
+
16
+ ## jsdom
17
+
18
+ The naive version of this script does
19
+ `Object.assign(globalThis, { document, window })`
20
+ - see the tiny example in [cli.md](cli.md#--preload-and---bun-flags).
21
+ That's enough for suites that only ever touch `document`,
22
+ but it breaks the moment a suite does an `instanceof` check
23
+ (such as `node instanceof HTMLElement` or `event instanceof Event`):
24
+ `HTMLElement` and `Event` still resolve to `undefined` on
25
+ `globalThis`, or worse, to some other realm's version of the same
26
+ class if another preload script or dependency defined one.
27
+ DOM constructors all need to come from the *same* jsdom realm as
28
+ `document`/`window` for `instanceof` to hold,
29
+ which means copying jsdom's entire window surface,
30
+ not cherry-picking two properties.
31
+
32
+ ```ts
33
+ // bench/dom-preload.ts
34
+ import { JSDOM } from "jsdom"
35
+
36
+ const dom = new JSDOM("<!doctype html><html><body></body></html>", {
37
+ url: "http://localhost/",
38
+ })
39
+
40
+ // Left on Bun's own globals rather than jsdom's: `process`/`Bun` because suite code and
41
+ // ostia's own instrumentation expect the real runtime, and the timer/microtask functions
42
+ // because jsdom's versions aren't wired into Bun's event loop the way the trial harness
43
+ // needs them to be.
44
+ const KEEP_BUNS_OWN = new Set([
45
+ "process",
46
+ "Bun",
47
+ "global",
48
+ "globalThis",
49
+ "setTimeout",
50
+ "clearTimeout",
51
+ "setInterval",
52
+ "clearInterval",
53
+ "queueMicrotask",
54
+ ])
55
+
56
+ for (const key of Object.getOwnPropertyNames(dom.window)) {
57
+ if (KEEP_BUNS_OWN.has(key)) continue
58
+ ;(globalThis as Record<string, unknown>)[key] = (dom.window as unknown as Record<string, unknown>)[key]
59
+ }
60
+ ```
61
+
62
+ ```sh
63
+ ostia bench --preload ./bench/dom-preload.ts bench/*.dom.bench.ts
64
+ ```
65
+
66
+ ## happy-dom
67
+
68
+ Same global-copy pattern, different source object - `happy-dom`'s
69
+ `Window` class instead of `JSDOM`'s `.window`.
70
+ happy-dom trades some spec coverage
71
+ (fewer of the more obscure DOM APIs are implemented) for a noticeably
72
+ faster startup, which matters when `--preload` runs once per suite-file
73
+ subprocess.
74
+ Reach for this first if your suite's DOM surface is simple
75
+ (rendering components, reading text content) and only fall back to jsdom
76
+ if something you need isn't implemented.
77
+
78
+ ```ts
79
+ // bench/happy-dom-preload.ts
80
+ import { Window } from "happy-dom"
81
+
82
+ const window = new Window({ url: "http://localhost/" })
83
+
84
+ const KEEP_BUNS_OWN = new Set([
85
+ "process",
86
+ "Bun",
87
+ "global",
88
+ "globalThis",
89
+ "setTimeout",
90
+ "clearTimeout",
91
+ "setInterval",
92
+ "clearInterval",
93
+ "queueMicrotask",
94
+ ])
95
+
96
+ for (const key of Object.getOwnPropertyNames(window)) {
97
+ if (KEEP_BUNS_OWN.has(key)) continue
98
+ ;(globalThis as Record<string, unknown>)[key] = (window as unknown as Record<string, unknown>)[key]
99
+ }
100
+ ```
101
+
102
+ ## Component-framework compile plugin (Svelte)
103
+
104
+ Benchmarking `.svelte` (or `.vue`, `.astro` and other compiled formats)
105
+ components means Bun needs to know how to turn that file into JS before
106
+ it can import it - `Bun.plugin()`'s `onLoad` hook is the integration
107
+ point, registered from a preload script so it's in place before the
108
+ suite file's own `import "./MyComponent.svelte"` runs.
109
+
110
+ Two wrinkles that aren't obvious from the plugin API alone:
111
+
112
+ - Frameworks that support "module" files - plain `.js`/`.ts` files that
113
+ still use framework-specific syntax
114
+ (Svelte 5 runes outside a component, such as
115
+ `@testing-library/svelte-core`'s own `*.svelte.js` internals) -
116
+ compile through a *different* entry point than components do
117
+ (`compileModule` vs `compile`).
118
+ One `onLoad` filter matching only `\.svelte$` will miss these
119
+ and Bun will try to load them as plain JS,
120
+ which fails on the rune syntax.
121
+ - `<script lang="ts">` inside a `.svelte` file isn't touched by Bun's
122
+ own TS transform, because that pipeline only applies to files Bun
123
+ loads directly - content an `onLoad` hook fetches by hand
124
+ (`Bun.file(path).text()`) and hands to the framework compiler bypasses
125
+ it entirely.
126
+ `Bun.Transpiler` (a Bun-native API, unrelated to ostia) is the tool
127
+ for stripping that script block yourself before compiling.
128
+
129
+ ```ts
130
+ // bench/svelte-preload.ts
131
+ import { compile, compileModule } from "svelte/compiler"
132
+
133
+ const transpiler = new Bun.Transpiler({ loader: "ts" })
134
+
135
+ function stripScriptLangTs(source: string): string {
136
+ return source.replace(
137
+ /<script lang="ts">([\s\S]*?)<\/script>/,
138
+ (_match, code: string) => `<script>${transpiler.transformSync(code)}</script>`,
139
+ )
140
+ }
141
+
142
+ Bun.plugin({
143
+ name: "svelte-compile",
144
+ setup(build) {
145
+ // Components.
146
+ build.onLoad({ filter: /\.svelte$/ }, async ({ path }) => {
147
+ const source = stripScriptLangTs(await Bun.file(path).text())
148
+ const { js } = compile(source, { filename: path, generate: "client" })
149
+ return { contents: js.code, loader: "js" }
150
+ })
151
+
152
+ // Rune-using plain-JS "module" files - matched separately since the filter above
153
+ // would also match `.svelte.js` and hand it to the wrong compiler entry point.
154
+ build.onLoad({ filter: /\.svelte\.js$/ }, async ({ path }) => {
155
+ const source = await Bun.file(path).text()
156
+ const { js } = compileModule(source, { filename: path, generate: "client" })
157
+ return { contents: js.code, loader: "js" }
158
+ })
159
+ },
160
+ })
161
+ ```
162
+
163
+ ```sh
164
+ ostia bench --preload ./bench/svelte-preload.ts bench/*.component.bench.ts
165
+ ```
166
+
167
+ Adapting this to another framework means swapping in that framework's
168
+ own compile/transform call in place of `compile`/`compileModule` - the
169
+ `Bun.plugin()` + `onLoad` + filter-by-extension shape stays the same.