@specific.dev/spectest 0.38.0 → 0.41.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 (103) hide show
  1. package/dist/components/k3s.js +1 -24
  2. package/dist/components/supabase.d.ts +87 -27
  3. package/dist/components/supabase.js +352 -69
  4. package/dist/daemon.d.ts +38 -0
  5. package/dist/daemon.js +405 -946
  6. package/dist/harness/build-context.d.ts +82 -0
  7. package/dist/harness/build-context.js +113 -0
  8. package/dist/harness/buildkit-progress.d.ts +37 -0
  9. package/dist/harness/buildkit-progress.js +66 -0
  10. package/dist/harness/container-run.d.ts +89 -0
  11. package/dist/harness/container-run.js +118 -0
  12. package/dist/harness/file-mounts.d.ts +91 -0
  13. package/dist/harness/file-mounts.js +119 -0
  14. package/dist/harness/hostmatch.d.ts +65 -0
  15. package/dist/harness/hostmatch.js +108 -0
  16. package/dist/harness/http-proxy.d.ts +62 -0
  17. package/dist/harness/http-proxy.js +104 -0
  18. package/dist/harness/ingress-table.d.ts +148 -0
  19. package/dist/harness/ingress-table.js +129 -0
  20. package/dist/harness/log-delta.d.ts +54 -0
  21. package/dist/harness/log-delta.js +83 -0
  22. package/dist/harness/main.d.ts +47 -0
  23. package/dist/harness/main.js +164 -0
  24. package/dist/harness/methods.d.ts +54 -0
  25. package/dist/harness/methods.js +65 -0
  26. package/dist/harness/names-registry.d.ts +63 -0
  27. package/dist/harness/names-registry.js +90 -0
  28. package/dist/harness/protocol.d.ts +88 -0
  29. package/dist/harness/protocol.js +96 -0
  30. package/dist/harness/ready-poll.d.ts +47 -0
  31. package/dist/harness/ready-poll.js +67 -0
  32. package/dist/harness/service-graph.d.ts +29 -0
  33. package/dist/harness/service-graph.js +92 -0
  34. package/dist/harness/volume-paths.d.ts +70 -0
  35. package/dist/harness/volume-paths.js +81 -0
  36. package/dist/index.d.ts +3 -3
  37. package/dist/ingress.d.ts +1 -1
  38. package/dist/inspect.d.ts +23 -0
  39. package/dist/inspect.js +65 -0
  40. package/dist/resolver.js +5 -8
  41. package/dist/vendor/rrweb-plugin-console-record.umd.js +521 -0
  42. package/dist/vendor/rrweb-record.min.js +5061 -0
  43. package/package.json +7 -1
  44. package/src/aws-sigv4.ts +218 -0
  45. package/src/browser.ts +2040 -0
  46. package/src/components/aws.ts +554 -0
  47. package/src/components/email.ts +398 -0
  48. package/src/components/expo.ts +167 -0
  49. package/src/components/index.ts +81 -0
  50. package/src/components/k3s.ts +2061 -0
  51. package/src/components/postgres.ts +132 -0
  52. package/src/components/replayFake.ts +1015 -0
  53. package/src/components/s3.ts +132 -0
  54. package/src/components/supabase.ts +1699 -0
  55. package/src/daemon.ts +5489 -0
  56. package/src/harness/build-context.test.ts +0 -0
  57. package/src/harness/build-context.ts +146 -0
  58. package/src/harness/buildkit-progress.test.ts +98 -0
  59. package/src/harness/buildkit-progress.ts +74 -0
  60. package/src/harness/container-run.test.ts +209 -0
  61. package/src/harness/container-run.ts +158 -0
  62. package/src/harness/file-mounts.test.ts +185 -0
  63. package/src/harness/file-mounts.ts +145 -0
  64. package/src/harness/hostmatch.test.ts +148 -0
  65. package/src/harness/hostmatch.ts +109 -0
  66. package/src/harness/http-proxy.test.ts +156 -0
  67. package/src/harness/http-proxy.ts +119 -0
  68. package/src/harness/ingress-rebind.test.ts +125 -0
  69. package/src/harness/ingress-table.test.ts +172 -0
  70. package/src/harness/ingress-table.ts +186 -0
  71. package/src/harness/log-delta.test.ts +125 -0
  72. package/src/harness/log-delta.ts +100 -0
  73. package/src/harness/main.test.ts +211 -0
  74. package/src/harness/main.ts +196 -0
  75. package/src/harness/methods.test.ts +63 -0
  76. package/src/harness/methods.ts +92 -0
  77. package/src/harness/names-registry.test.ts +137 -0
  78. package/src/harness/names-registry.ts +108 -0
  79. package/src/harness/protocol.test.ts +148 -0
  80. package/src/harness/protocol.ts +163 -0
  81. package/src/harness/ready-poll.test.ts +172 -0
  82. package/src/harness/ready-poll.ts +93 -0
  83. package/src/harness/service-graph.test.ts +97 -0
  84. package/src/harness/service-graph.ts +97 -0
  85. package/src/harness/volume-paths.test.ts +102 -0
  86. package/src/harness/volume-paths.ts +112 -0
  87. package/src/ids.ts +89 -0
  88. package/src/index.ts +2725 -0
  89. package/src/ingress.ts +305 -0
  90. package/src/inspect.ts +739 -0
  91. package/src/locator.ts +716 -0
  92. package/src/mobile.ts +133 -0
  93. package/src/record-secrets.ts +41 -0
  94. package/src/recorder.ts +846 -0
  95. package/src/redis.ts +202 -0
  96. package/src/replay-bundle.ts +108 -0
  97. package/src/resolver.ts +348 -0
  98. package/src/s3.ts +333 -0
  99. package/src/sql.ts +243 -0
  100. package/src/terminal.ts +740 -0
  101. package/src/url-match.ts +67 -0
  102. package/src/vendor/rrweb-plugin-console-record.umd.js +521 -0
  103. package/src/vendor/rrweb-record.min.js +5061 -0
package/src/index.ts ADDED
@@ -0,0 +1,2725 @@
1
+ // Spectest SDK. The user's single `spectest/index.ts` calls
2
+ // `defineEnvironment({ name, services })` once, defines test cases via
3
+ // the returned `env.test(...)`, and default-exports `env.project([...])`.
4
+ // The daemon loads this file on boot and the control plane talks to it
5
+ // over HTTP.
6
+
7
+ import { strict as nodeAssert } from "node:assert";
8
+
9
+ import { recordAssertion, safeSerialize } from "./recorder.js";
10
+ import { adoptNullishTag, readRaw, readTag } from "./inspect.js";
11
+
12
+ // Provenance-wrapper types: what tracked ops (ctx.fetch, db queries,
13
+ // browser.evaluate) resolve to, and the `.unwrap()` escape hatch.
14
+ export type {
15
+ Carrier,
16
+ Wrapped,
17
+ WrappedObject,
18
+ WrappedArray,
19
+ WrappedResponse,
20
+ Provenanced,
21
+ SpectestFetch,
22
+ Unwrap,
23
+ } from "./inspect.js";
24
+ import type { OpTag, Provenanced, SpectestFetch, Wrapped } from "./inspect.js";
25
+
26
+ // `field` — a provenance-preserving, null-safe selector: a `null`/`undefined`
27
+ // leaf read off a wrapped op result is raw and untagged, so an `expect(...)` on
28
+ // it renders detached from its source op; `field` tags from the container so the
29
+ // assertion still nests. (A decoded value loses provenance the same way — that
30
+ // case is the `.transform(label, fn)` method every wrapped value carries, which
31
+ // runs the still-tagged value through `fn` and re-wraps the result.)
32
+ // To recover a raw value, call `.unwrap()` on it — spectest op results are
33
+ // always wrapped (in every context), so the method is always there; there is no
34
+ // `unwrap(x)` free function. See the `.unwrap()` discipline section of `spectest docs`.
35
+ export { field } from "./inspect.js";
36
+
37
+ // Instrumented client primitives — drop-in replacements for Bun's native
38
+ // clients that record each operation on the test event log and return their
39
+ // results inspect-wrapped, so `expect(...)` on a result links back to the op
40
+ // in the timeline (same provenance mechanism as the wrapped `fetch`). Reach
41
+ // for these over the raw `Bun.*` clients in service `helpers` and tests so
42
+ // assertions stay tracked. See `sql.ts` / `redis.ts` / `s3.ts`.
43
+ export { SQL, type SqlClient, type SqlOptions } from "./sql.js";
44
+ export { RedisClient, type RedisClientLike, type RedisOptions } from "./redis.js";
45
+ export { S3Client, type S3ClientLike, type S3File, type S3ClientOptions } from "./s3.js";
46
+
47
+ export type { Browser, BrowserOptions, Keyboard, Mouse, Touchscreen } from "./browser.js";
48
+
49
+ import type { Browser, BrowserOptions } from "./browser.js";
50
+
51
+ // Playwright-native locators — the select-then-act surface shared by
52
+ // `ctx.browser()` and `ctx.mobile()`. `Locator` mirrors playwright-core's
53
+ // Locator (getBy*/filter/first/nth/click/fill/textContent/…, STRICT mode).
54
+ export type {
55
+ Locator,
56
+ GetByRoleOptions,
57
+ GetByTextOptions,
58
+ FilterOptions,
59
+ ClickOptions,
60
+ BoundingBox,
61
+ } from "./locator.js";
62
+ import type { Locator } from "./locator.js";
63
+ import {
64
+ isLocator,
65
+ getLocatorProbe,
66
+ isBrowserSession,
67
+ getBrowserProbe,
68
+ DEFAULT_ACTION_TIMEOUT_MS,
69
+ } from "./locator.js";
70
+
71
+ export type { UrlPattern } from "./url-match.js";
72
+ import type { UrlPattern } from "./url-match.js";
73
+ import { describeUrlPattern, matchesUrl } from "./url-match.js";
74
+
75
+ // Mobile (Expo / React Native Web) surface: a phone-emulated session driven
76
+ // with the same locators + touch gestures, replayed inside a phone bezel.
77
+ // Opened with `ctx.mobile(ctx.svc.app)` where the app is registered via the
78
+ // `expo()` component.
79
+ export type { Mobile, MobileApp } from "./mobile.js";
80
+ import type { Mobile, MobileApp } from "./mobile.js";
81
+
82
+ export type { Terminal, TerminalOpts, TerminalResult } from "./terminal.js";
83
+
84
+ import type { Terminal, TerminalOpts, TerminalResult } from "./terminal.js";
85
+
86
+ // Low-level ingress primitives + the framework lowering that the friendly
87
+ // `tls` / `hostnames` fields and `defineFake(...)` are built on. See
88
+ // `ingress.ts`.
89
+ export {
90
+ certificate,
91
+ dnsName,
92
+ proxy,
93
+ provides,
94
+ lowerIngress,
95
+ isWildcard,
96
+ SELF_SERVICE_TOKEN,
97
+ } from "./ingress.js";
98
+ export type {
99
+ CertificateDecl,
100
+ DnsDecl,
101
+ ProxyDecl,
102
+ IngressDecl,
103
+ DnsTarget,
104
+ LoweredIngress,
105
+ } from "./ingress.js";
106
+ import type { DnsTarget } from "./ingress.js";
107
+ import { isWildcard as isWildcardHost } from "./ingress.js";
108
+
109
+ // ──────────────────────────────────────────────────────────────────────────
110
+ // Environment configuration
111
+ // ──────────────────────────────────────────────────────────────────────────
112
+
113
+ export interface EnvironmentConfig<S extends ServicesMap = ServicesMap> {
114
+ /** Human-friendly name for the environment, e.g. "my-app". */
115
+ name: string;
116
+ /**
117
+ * Services that make up the environment, keyed by service name. The key
118
+ * is the container name, the DNS hostname on `spectest-net`, and the
119
+ * string used in `dependsOn` references.
120
+ */
121
+ services: S;
122
+ /** Sandbox timeout in seconds (default 1h). */
123
+ timeoutSecs?: number;
124
+ }
125
+
126
+ /**
127
+ * The shape that ends up in the JSON config the control plane and Rust
128
+ * mirror care about. `ServiceDefinition` is the same thing with an extra
129
+ * non-serialisable `client` factory tacked on; `JSON.stringify` drops
130
+ * functions, so the wire format is `ServiceConfig`.
131
+ */
132
+ export interface ServiceConfig {
133
+ /** Image definition: registry pull or inline build. */
134
+ image: ServiceImage;
135
+ /**
136
+ * Shell command to run (sh -c). Defaults to the image's CMD. NB: this
137
+ * **replaces the image's entrypoint** with `/bin/sh -c` — an
138
+ * init-wrapped image (postgres's `docker-entrypoint.sh`) skips its
139
+ * initialization. Use {@link args} to keep the entrypoint.
140
+ */
141
+ command?: string;
142
+ /**
143
+ * Arguments appended after the image name (`docker run <image>
144
+ * <args…>`) — a CMD override that **keeps the image's entrypoint**.
145
+ * E.g. `args: ["postgres", "-c", "wal_level=logical"]` still runs
146
+ * postgres's `docker-entrypoint.sh` initialization. Mutually
147
+ * exclusive with {@link command}.
148
+ */
149
+ args?: readonly string[];
150
+ env?: Record<string, string>;
151
+ /**
152
+ * Ports the container listens on. Advisory only — surfaced in
153
+ * `spectest list` output. Peer services reach each other by `<service>:<port>`
154
+ * without any port declaration.
155
+ */
156
+ ports?: readonly number[];
157
+ /**
158
+ * Extra DNS names this service answers to inside the environment.
159
+ * Each entry must be a fully-qualified, multi-label hostname (e.g.
160
+ * `api.stripe.com`). Both peer containers (via Docker's embedded DNS)
161
+ * and code on the VM host (via spectest-resolver) resolve these names
162
+ * to the service's IP on `spectest-net`. Useful for mocking external
163
+ * APIs — point an SDK at `http://api.stripe.com` and a service of
164
+ * yours answers directly (no proxy). For HTTPS, use {@link tls}
165
+ * instead — those names terminate TLS in the daemon and reverse-proxy
166
+ * to the service's HTTP port.
167
+ *
168
+ * A `*.suffix` wildcard (e.g. `"*.example.com"`) points a whole domain
169
+ * at this service. Wildcards are answered by spectest-resolver only —
170
+ * they never land in a container's `/etc/hosts` — which peer containers
171
+ * still reach, since Docker forwards unknown names to that resolver.
172
+ *
173
+ * The `.internal` TLD is reserved: every service automatically
174
+ * answers to `<name>.internal` in addition to its bare `<name>`, and
175
+ * user-supplied hostnames may not end in `.internal`.
176
+ */
177
+ hostnames?: readonly string[];
178
+ /**
179
+ * Expose this service over HTTPS via a TLS-terminating reverse proxy
180
+ * hosted in the harness. Each entry maps a fully-qualified
181
+ * hostname to the HTTP port the service listens on inside its
182
+ * container; the daemon binds the hostname on `:443` (SNI-multiplexed,
183
+ * with a leaf cert signed by the in-VM root CA) and on `:80`, and
184
+ * proxies the request to `http://<service>:<port>`. WebSocket
185
+ * upgrades are forwarded.
186
+ *
187
+ * The in-VM root CA is already trusted by Chromium (`ctx.browser()`)
188
+ * and by service-container runtimes (Node, Python, Go, etc.) via
189
+ * the env-var bundle, so `https://<hostname>/` Just Works from
190
+ * tests and from peer services. Hostname rules match {@link hostnames}:
191
+ * multi-label, lowercase, no `.internal` suffix, no collision with
192
+ * services, other service TLS hostnames, or fakes.
193
+ *
194
+ * A `*.suffix` wildcard claims a whole domain with one entry — e.g.
195
+ * `{ hostname: "*.us-east-1.amazonaws.com", port: 4566 }` puts every
196
+ * AWS regional endpoint on one emulator container, so an unmodified SDK
197
+ * reaches it at its production URL. The leaf cert gets a wildcard SAN,
198
+ * which (as in every TLS client) covers exactly **one** label: declare
199
+ * a separate entry for anything deeper. An exact `tls` hostname always
200
+ * beats a wildcard, so a single endpoint can be split off to another
201
+ * service.
202
+ */
203
+ tls?: readonly ServiceTls[];
204
+ /** Bind-mounted volumes for state that survives snapshot/fork. */
205
+ volumes?: readonly VolumeMount[];
206
+ /**
207
+ * Files seeded into the container's filesystem **before it starts**.
208
+ * Each entry's `content` is written to a VM-host staging path and
209
+ * bind-mounted (read-only) at `path` inside the container. Unlike a
210
+ * `setup` hook — which runs after the container is up — `files` is the
211
+ * way to inject configuration a process reads at boot, e.g. k3s's
212
+ * `/etc/rancher/k3s/registries.yaml`, which must exist before
213
+ * `k3s server` starts.
214
+ */
215
+ files?: readonly FileMount[];
216
+ /**
217
+ * Leaf certificates minted from the in-VM root CA and written into the
218
+ * container **before it starts**, so the service can terminate TLS
219
+ * *itself* with a certificate the whole environment already trusts.
220
+ *
221
+ * This is the counterpart to {@link ServiceConfig.tls}. `tls` puts the
222
+ * daemon in front as a terminating reverse proxy and forwards plain
223
+ * HTTP to the service — right for an ordinary web app, wrong for
224
+ * anything that has to see the TLS handshake: a gateway that routes by
225
+ * SNI, a server that verifies client certificates, or a protocol with
226
+ * its own TLS layer. Those need key material, and the only alternative
227
+ * was a self-signed cert plus `rejectUnauthorized: false` — which
228
+ * tests a code path production never runs.
229
+ *
230
+ * ```ts
231
+ * services: {
232
+ * gateway: {
233
+ * image: { type: "registry", reference: "…" },
234
+ * hostnames: ["sql.gateway.test"],
235
+ * certificates: [{
236
+ * hostnames: ["sql.gateway.test", "*.sql.gateway.test"],
237
+ * certPath: "/tls/tls.crt",
238
+ * keyPath: "/tls/tls.key",
239
+ * mode: "0600",
240
+ * }],
241
+ * },
242
+ * }
243
+ * // a test then connects with full verification on:
244
+ * // new Client({ connectionString, ssl: { rejectUnauthorized: true } })
245
+ * ```
246
+ *
247
+ * For a certificate a *test* needs as a value — to load into a
248
+ * Kubernetes Secret, say — use `ctx.certificate(hostnames)` instead,
249
+ * which returns the PEMs rather than mounting them.
250
+ */
251
+ certificates?: readonly CertificateMount[];
252
+ /** Other services (keys in the services map) that must be ready first. */
253
+ dependsOn?: readonly string[];
254
+ readyCheck?: ReadyCheck;
255
+ /** Container workdir override. */
256
+ workdir?: string;
257
+ /**
258
+ * Run the container with `--privileged`. Required by workloads that
259
+ * embed their own container runtime (e.g. k3s) and need full access
260
+ * to the host kernel surface. Off by default.
261
+ */
262
+ privileged?: boolean;
263
+ /**
264
+ * Tmpfs mounts (one `--tmpfs <path>` per entry). Required by some
265
+ * workloads — k3s wants `/run` and `/var/run` writable and
266
+ * non-persistent. Snapshots/forks preserve tmpfs contents along with
267
+ * the rest of process memory.
268
+ */
269
+ tmpfs?: readonly string[];
270
+ /**
271
+ * Cgroup namespace mode — `"host"` or `"private"`. Omit for docker's
272
+ * default. k3s needs `"host"` so its embedded containerd can manage
273
+ * cgroups for the pods it schedules.
274
+ */
275
+ cgroupns?: string;
276
+ }
277
+
278
+ /**
279
+ * Everything test-side code can reach inside the VM, in every
280
+ * context it runs in: a test body, `spectest env eval`, a project-level
281
+ * `setup`, and a component's service-level `setup` / `helpers` hooks.
282
+ *
283
+ * This is deliberately ONE type. The setup surfaces used to be two
284
+ * disjoint sets — a component hook could read project files but not mint
285
+ * a certificate; a project `setup` could mint a certificate but not read
286
+ * a project file — so bring-up logic got split across files by which
287
+ * context happened to carry which method. A component is now written
288
+ * against exactly the primitives an end user has in a test.
289
+ *
290
+ * The one member that differs by context is {@link exec}: in a test it
291
+ * returns a {@link Wrapped} result (its output carries provenance into
292
+ * the timeline), everywhere else a plain one. See {@link TestContext}.
293
+ *
294
+ * `svc` is scoped in a service-level hook: a service's `setup`/`helpers`
295
+ * can reach its own handle and those of its (transitive) `dependsOn`
296
+ * services — the ones the DAG guarantees are already up — and reading
297
+ * any other key throws with the dependency it's missing. Everywhere else
298
+ * (tests, eval, project `setup`) the whole map is live.
299
+ */
300
+ export interface SpectestContext<
301
+ S extends ServicesMap = ServicesMap,
302
+ F extends FakesMap = FakesMap,
303
+ > {
304
+ /**
305
+ * Absolute path of the extracted project root inside the VM — the
306
+ * directory the user's repo lands in, with `spectest/` directly under
307
+ * it. Use this (never a hard-coded path, and never `import.meta.url` —
308
+ * that only reaches files under `spectest/`) to locate project files:
309
+ * a manifest set, `supabase/migrations/**`, a fixture.
310
+ */
311
+ projectRoot: string;
312
+ /** Read a project file as UTF-8. Relative paths resolve against
313
+ * {@link projectRoot}; absolute paths are read as-is. */
314
+ readProjectFile(path: string): Promise<string>;
315
+ /**
316
+ * Run a command inside a service container. Pass an **array** for exact
317
+ * argv with no shell (`["psql", "-f", "-"]`), or a **string** to run via
318
+ * `sh -lc`. `opts.stdin` is piped to the process — the natural way to
319
+ * feed a SQL file to `psql -f -` or a manifest to `kubectl apply -f -`.
320
+ *
321
+ * Never throws on non-zero exit — inspect `exitCode` yourself.
322
+ *
323
+ * In a test this is the instrumented variant (recorded on the timeline,
324
+ * result {@link Wrapped}); in `setup`/`helpers` there is no timeline, so
325
+ * the result is a plain {@link ExecResult}.
326
+ */
327
+ exec(
328
+ service: string,
329
+ command: string | string[],
330
+ opts?: ExecOpts,
331
+ ): Promise<ExecResult>;
332
+ /**
333
+ * Instrumented `fetch`. In a test each call is recorded on the timeline
334
+ * and resolves to a {@link WrappedResponse}: reads carry provenance so
335
+ * `expect(res.status)` / `expect(await res.json())` nest under the HTTP
336
+ * call. Because the status-line accessors are {@link Carrier}s, a raw
337
+ * `res.status === 200` is a *type error* — use `res.status.unwrap()` /
338
+ * `res.unwrap().status`, or assert via `expect`. Outside a test the
339
+ * result is wrapped the same way, just with no timeline to link to.
340
+ *
341
+ * (The plain global `fetch` is wrapped the same way at runtime but keeps
342
+ * the standard `Response` type, so prefer `ctx.fetch` for honestly-typed
343
+ * results.)
344
+ */
345
+ fetch: SpectestFetch;
346
+ /**
347
+ * Per-service helper namespaces, keyed by service name. Only services
348
+ * whose definition ships a `helpers` factory appear here; the value at
349
+ * `ctx.svc.<name>` is exactly the record that factory returned. For a
350
+ * `postgres(...)` service that ships `{ client }`, tests do
351
+ * `await ctx.svc.db.client\`SELECT 1\``.
352
+ *
353
+ * In a service-level `setup`/`helpers` hook only the service itself and
354
+ * its transitive `dependsOn` are reachable (see {@link SpectestContext}).
355
+ */
356
+ readonly svc: ServiceHandlesFor<S>;
357
+ /**
358
+ * Per-fake helper namespaces, keyed by fake name. Each is the record
359
+ * of functions the fake's `helpers` factory returned (or `{ state }`
360
+ * when it ships none — tests never touch a fake's private state
361
+ * directly). Those functions read/mutate the fake's state internally;
362
+ * the state itself is in-process and lives across the fork along with
363
+ * the rest of daemon memory, so calls in a child test see the fork's
364
+ * own copy as mutated by its ancestors. In a test every helper call is
365
+ * recorded as a step and its return value tracked, so assertions on it
366
+ * nest under the call in the timeline.
367
+ *
368
+ * Strongly typed against the project's fakes map when fakes are
369
+ * declared in `defineEnvironment({ ..., fakes })`: `ctx.fakes.stripe`
370
+ * is exactly the helpers record `defineFake`'s `helpers` factory
371
+ * returned — no cast. (Falls back to a loose record only when the
372
+ * environment declares no fakes.)
373
+ */
374
+ readonly fakes: FakeHandlesFor<F>;
375
+ /**
376
+ * Poll a predicate until it returns a truthy value, then return that
377
+ * value. In a test it records one `wait` event for the whole loop (with
378
+ * attempt count, total duration, and the description) instead of one
379
+ * event per probe — useful for "wait until pod Running"-style checks
380
+ * where the intermediate states are noise. In `setup` there's no
381
+ * timeline; it's just the loop you'd otherwise hand-roll.
382
+ *
383
+ * - `null`, `undefined`, or `false` from `fn` mean "not yet" — wait
384
+ * `intervalMs` and try again.
385
+ * - Anything else is the success value and is returned, tagged with
386
+ * the wait event's seq. Downstream `expect(...)` on it links to
387
+ * the wait (one logical step), not to N suppressed HTTP calls.
388
+ * - Throws from `fn` propagate out immediately; the wait event is
389
+ * still recorded (with `error` set) so the timeline reflects the
390
+ * abort.
391
+ * - Defaults: `timeoutMs = 30_000`, `intervalMs = 1_000`.
392
+ *
393
+ * Side-effect calls inside `fn` (fetch, ctx.svc.* helpers, etc.)
394
+ * don't show up on the event log — the recorder is paused for the
395
+ * duration. Use `ctx.poll` for read-only observation, not for
396
+ * stateful work you want recorded.
397
+ */
398
+ poll<T>(
399
+ description: string,
400
+ fn: () => T | null | undefined | false | Promise<T | null | undefined | false>,
401
+ opts?: { timeoutMs?: number; intervalMs?: number },
402
+ ): Promise<Wrapped<T>>;
403
+ /**
404
+ * Register a DNS name so the rest of this context (and anything
405
+ * downstream of it) can reach it. `{ ingress: true }` points the name at
406
+ * the daemon (a fake / TLS proxy); `{ service }` points it at a
407
+ * container's live IP; a `*.suffix` wildcard (e.g. `"*.example.com"`)
408
+ * routes a whole domain — the natural fit for k3s Ingress hosts.
409
+ *
410
+ * Answered by spectest-resolver, so it works for VM-host/test code,
411
+ * `ctx.browser()`, and peer containers (Docker forwards unknown names to
412
+ * the host resolver). It does NOT land in any container's `/etc/hosts`.
413
+ * The registration mutates in-daemon state, so from a test it's isolated
414
+ * to that test's fork (like fake state); from `setup` it's captured by
415
+ * the warm-template snapshot and every test inherits it.
416
+ *
417
+ * ```ts
418
+ * await ctx.svc.k8s.apply(ingressFor("foo.example.com"));
419
+ * await ctx.dnsName("foo.example.com", { service: "k8s" });
420
+ * const res = await ctx.fetch("http://foo.example.com");
421
+ * ```
422
+ */
423
+ dnsName(hostname: string, target: DnsTarget): Promise<void>;
424
+ /**
425
+ * Mint a leaf certificate from the in-VM root CA and return the PEMs.
426
+ *
427
+ * The value-returning counterpart to the `certificates` service field
428
+ * (see {@link ServiceConfig.certificates}): that one hands a
429
+ * certificate to a container before it boots, this one hands it to
430
+ * *you* — for loading into a Kubernetes `kubernetes.io/tls` Secret,
431
+ * posting to a control-plane API that provisions TLS endpoints, or
432
+ * driving a client-certificate handshake.
433
+ *
434
+ * The returned `ca` is the same root the whole environment already
435
+ * trusts (`ctx.fetch`, `ctx.browser()`, every service container), so a
436
+ * server configured with these PEMs verifies cleanly — no
437
+ * `rejectUnauthorized: false`, no `sslmode=require` downgrade.
438
+ * Wildcards (`*.example.com`) are allowed in `hostnames`.
439
+ *
440
+ * ```ts
441
+ * const { cert, key } = await ctx.certificate(["*.apps.test"]);
442
+ * await ctx.svc.k8s.apply(`
443
+ * apiVersion: v1
444
+ * kind: Secret
445
+ * metadata: { name: apps-tls, namespace: default }
446
+ * type: kubernetes.io/tls
447
+ * stringData:
448
+ * tls.crt: |
449
+ * ${cert.replace(/^/gm, " ")}
450
+ * tls.key: |
451
+ * ${key.replace(/^/gm, " ")}
452
+ * `);
453
+ * ```
454
+ */
455
+ certificate(hostnames: readonly string[]): Promise<CertificateMaterial>;
456
+ /**
457
+ * Start a real container on `spectest-net` at runtime — a peer machine
458
+ * with its own IP, reachable like any boot service. Returns once the
459
+ * container is up and its `readyCheck` (if any) has passed.
460
+ *
461
+ * Started from a test, the new container is part of that test's
462
+ * post-state snapshot, so a `dependsOn` child inherits it (same PID,
463
+ * same data) while siblings, which fork from the parent's earlier
464
+ * snapshot, never see it — the same isolation fake `state` and
465
+ * {@link dnsName} get. Started from `setup`, it's captured into the
466
+ * warm template and every test inherits it. Reach it by `name`
467
+ * (single-label, via the resolver) or by any `hostnames` you pass; map a
468
+ * multi-label name onto it with `ctx.dnsName(host, { service: name })`.
469
+ *
470
+ * The image is pulled on first use (fast through the host cache). See
471
+ * {@link RuntimeServiceSpec}.
472
+ *
473
+ * ```ts
474
+ * const { name } = await ctx.startService({
475
+ * name: `db-${crypto.randomUUID().slice(0, 8)}`,
476
+ * image: { type: "registry", reference: "postgres:16-alpine" },
477
+ * env: { POSTGRES_PASSWORD: "secret" },
478
+ * readyCheck: { type: "exec", command: "pg_isready -h 127.0.0.1 -p 5432" },
479
+ * });
480
+ * const sql = new Bun.SQL(`postgres://postgres:secret@${name}:5432/postgres`);
481
+ * ```
482
+ */
483
+ startService(spec: RuntimeServiceSpec): Promise<RuntimeServiceHandle>;
484
+ /** Stop and remove a runtime service started via {@link startService}
485
+ * (no-op if it's already gone). */
486
+ stopService(name: string): Promise<void>;
487
+ }
488
+
489
+ /**
490
+ * @deprecated Use {@link SpectestContext} — component hooks and test
491
+ * bodies now receive the same capabilities. Kept as an alias so existing
492
+ * component code keeps compiling.
493
+ */
494
+ export type ComponentContext = SpectestContext;
495
+
496
+ /**
497
+ * Options for {@link SpectestContext.exec} — one type for every context,
498
+ * deliberately aliased rather than redeclared: the surfaces drifted once
499
+ * (the component one grew `stdin`/`timeoutMs`, the test one silently
500
+ * ignored them), and an alias makes that impossible to repeat.
501
+ *
502
+ * The one behavioural difference is the `timeoutMs` default: a
503
+ * service-level `setup`/`helpers` exec runs during boot, where nothing
504
+ * else bounds it, so it defaults to 120 s. Elsewhere there is no default —
505
+ * in a test the enclosing test's own timeout is the ceiling, and a
506
+ * project `setup` runs unbounded (it routinely waits on rollouts).
507
+ */
508
+ export type ComponentExecOpts = ExecOpts;
509
+
510
+ /** What a service's `setup` hook receives: the full
511
+ * {@link SpectestContext} plus the service's own name and helpers. */
512
+ export interface ServiceSetupContext<
513
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
514
+ H extends Record<string, any> = Record<string, never>,
515
+ > extends SpectestContext {
516
+ /** The service's key in the services map (container + DNS name). */
517
+ name: string;
518
+ /** The record the service's `helpers` factory returned (cached — setup
519
+ * and tests share one instance), or `{}` when it ships none. */
520
+ helpers: H;
521
+ }
522
+
523
+ /** What a service's `helpers` factory receives: the full
524
+ * {@link SpectestContext} plus the service's own name. Note `ctx.svc`
525
+ * here reaches the service's `dependsOn` only — never itself, since this
526
+ * hook is what builds that handle. */
527
+ export interface ServiceHelpersContext extends SpectestContext {
528
+ /** The service's key in the services map (container + DNS name). */
529
+ name: string;
530
+ }
531
+
532
+ /**
533
+ * Same shape as `ServiceConfig` plus an optional `helpers` factory that
534
+ * opens a namespace under `ctx.svc.<name>` inside tests. The factory
535
+ * returns a record — each key becomes `ctx.svc.<name>.<key>`. Components
536
+ * like `postgres(...)` use this to expose a pre-wired SQL pool at
537
+ * `ctx.svc.db.client`; nothing stops a component from exposing several
538
+ * helpers under one service (e.g. `client`, `admin`, `truncate()`).
539
+ */
540
+ export interface ServiceDefinition<
541
+ // `any` (not `unknown`) so closed-shape interfaces — like
542
+ // `PostgresHelpers` — are assignable. The constraint is only here to
543
+ // signal intent ("helpers is a record of named conveniences");
544
+ // `ServiceHandlesFor<S>` infers the helpers' real type at use sites.
545
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
546
+ H extends Record<string, any> = Record<string, never>,
547
+ > extends ServiceConfig {
548
+ /**
549
+ * Build the helpers exposed at `ctx.svc.<name>.<key>`. Called by the
550
+ * daemon the first time a test touches this service; the result is
551
+ * cached for the lifetime of the daemon (it survives snapshot/fork
552
+ * along with the rest of daemon memory). `args.name` is the key the
553
+ * user chose in the services map and matches the in-VM DNS name; the
554
+ * rest of the {@link ServiceHelpersContext} (exec, projectRoot) lets a
555
+ * component reach into its containers without daemon internals.
556
+ */
557
+ helpers?: (args: ServiceHelpersContext) => H | Promise<H>;
558
+ /**
559
+ * One-shot setup after the container's `readyCheck` passes, before
560
+ * dependents start and before any test runs. Awaited in-line with
561
+ * bootstrap, so anything it produces (an ingress controller deployed
562
+ * into k3s, a schema applied to a database) is part of the warm-template
563
+ * snapshot and never re-runs on warm starts.
564
+ *
565
+ * `helpers` is the same record the `helpers` factory returns — building
566
+ * it is cached, so `setup` and tests share one instance. If the service
567
+ * doesn't declare `helpers`, the field is the empty object. The rest of
568
+ * the {@link ServiceSetupContext} carries `exec` (docker exec with
569
+ * stdin) and `projectRoot`/`readProjectFile` for project-file access.
570
+ */
571
+ setup?: (args: ServiceSetupContext<H>) => void | Promise<void>;
572
+ }
573
+
574
+ /** A services map — what users pass to `environment.services`. Entries
575
+ * can be plain `ServiceConfig` literals or `ServiceDefinition`s that
576
+ * carry a `helpers` factory (e.g. what `postgres(...)` returns).
577
+ *
578
+ * The entry type is `ServiceDefinition`, not `ServiceConfig`: at runtime
579
+ * the map really does hold `helpers`/`setup` (the daemon reads them off
580
+ * each entry), and both are optional, so every plain `ServiceConfig`
581
+ * still satisfies it. Narrowing this to `ServiceConfig` — the wire type,
582
+ * which by definition carries no functions — made the natural way to
583
+ * hoist a services map out of `index.ts` (`… satisfies ServicesMap`) fail
584
+ * the typecheck on any service declaring a hook, while the same literal
585
+ * written inline passed. */
586
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
587
+ export type ServicesMap = Record<string, ServiceDefinition<any>>;
588
+
589
+ /** Awaited return type of a service's `helpers` factory, or `never` if
590
+ * the service doesn't ship one. */
591
+ type HelpersOf<D> = D extends {
592
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
593
+ helpers: (...args: any) => infer R;
594
+ }
595
+ ? Awaited<R>
596
+ : never;
597
+
598
+ /**
599
+ * Per-service handles derived from a concrete services map. Only
600
+ * services that ship a `helpers` factory appear here; `ctx.svc.<name>`
601
+ * is exactly the record the factory returned (e.g. `{ client: SqlClient }`
602
+ * for `postgres(...)`). Services without helpers don't show up at all,
603
+ * so plain `services: { api: { image: ... } }` adds no noise.
604
+ */
605
+ export type ServiceHandlesFor<S extends ServicesMap> = {
606
+ [K in keyof S as HelpersOf<S[K]> extends never ? never : K]: HelpersOf<S[K]>;
607
+ };
608
+
609
+ /** Loose, runtime-friendly shape of `ctx.svc` for code that doesn't
610
+ * know the concrete services map (the daemon, generic helpers). The
611
+ * typed `ctx.svc` in test bodies is `ServiceHandlesFor<S>`. */
612
+ export type ServiceHandles = Record<string, Record<string, unknown>>;
613
+
614
+ // ──────────────────────────────────────────────────────────────────────────
615
+ // Service groups — one services-map entry that expands to several services.
616
+ //
617
+ // A single container is a `ServiceConfig`/`ServiceDefinition`; a component
618
+ // that is inherently a *constellation* of containers (Supabase ≈ 7 of them)
619
+ // is a `ServiceGroup`. The user mounts the whole group under ONE key:
620
+ //
621
+ // services: { supabase: sb.group, app: { ... } }
622
+ //
623
+ // and `defineEnvironment` expands it: the group's `primary` part takes the
624
+ // group's own key (`supabase`), every other part lands at `<key>-<part>`
625
+ // (`supabase-db`, `supabase-auth`, …). Inside the group, `dependsOn`
626
+ // entries naming a relative part are rewritten to the final keys, so a
627
+ // group author never manually prefixes anything. Groups are pure sugar —
628
+ // they expand to plain services before validation, so the wire config the
629
+ // control plane sees is unchanged.
630
+ // ──────────────────────────────────────────────────────────────────────────
631
+
632
+ /** Symbol marking a value in the services map as a group to expand.
633
+ * Enumerable-symbol convention (like the ingress `provides` decls): it
634
+ * survives object spread but `JSON.stringify` drops it — not that a group
635
+ * ever reaches the wire; expansion happens before the config exists. */
636
+ const SERVICE_GROUP: unique symbol = Symbol.for("spectest.service.group");
637
+
638
+ /**
639
+ * Naming context handed to a group's `services` factory. Lets the factory
640
+ * embed *final* DNS names in env vars and config files without knowing the
641
+ * key the user will mount the group under.
642
+ */
643
+ export interface GroupNaming {
644
+ /** The services-map key the user chose for the group. */
645
+ name: string;
646
+ /** Final services-map key of a member part: `key(primary)` is `name`
647
+ * itself; any other part maps to `` `${name}-${part}` ``. */
648
+ key(part: string): string;
649
+ }
650
+
651
+ export interface ServiceGroupInput<
652
+ P extends ServicesMap,
653
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
654
+ H extends Record<string, any> = Record<string, never>,
655
+ Primary extends keyof P & string = keyof P & string,
656
+ > {
657
+ /**
658
+ * Build the group's member services, keyed by RELATIVE part name
659
+ * (`db`, `auth`, …). Called at expansion time with the final naming
660
+ * context, so strings that must carry final DNS names (connection
661
+ * URLs, embedded config) use `g.key("db")`. `dependsOn` entries that
662
+ * name a relative part are rewritten to final keys automatically
663
+ * (entries that don't match a part pass through untouched, so a group
664
+ * service may still depend on an outside service).
665
+ */
666
+ services: (g: GroupNaming) => P;
667
+ /**
668
+ * The part that represents the group: it takes the group's own map key
669
+ * (so `dependsOn: ["<groupKey>"]` from outside waits for it), and it
670
+ * carries the group's consolidated `helpers`/`setup`. The primary is
671
+ * made the group's dependency **sink** — every other member is added to
672
+ * its `dependsOn` — so "the primary is ready" means "the whole group is
673
+ * up, setup included". Consequently no member may depend on the
674
+ * primary (that would be a cycle); pick a gateway/front-door part.
675
+ */
676
+ primary: Primary;
677
+ /**
678
+ * The group's consolidated handle: helpers exposed at
679
+ * `ctx.svc.<groupKey>` — one typed surface for the whole group (e.g.
680
+ * `{ sql, url, anonKey }` for Supabase). Attached to the primary
681
+ * service; the primary part itself must not also declare `helpers`.
682
+ */
683
+ helpers?: (args: ServiceHelpersContext) => H | Promise<H>;
684
+ /**
685
+ * Group-level setup: runs once every member service is ready (run →
686
+ * probe → per-part setup), before anything that `dependsOn` the group
687
+ * starts and before any test runs. The home for "the whole stack is
688
+ * up, now do X". Runs after the primary part's own `setup`, if any.
689
+ */
690
+ setup?: (args: ServiceSetupContext<H>) => void | Promise<void>;
691
+ /**
692
+ * Pin the services-map key the group must be mounted under. For
693
+ * components whose *derived* surface (connection URLs, env for the app
694
+ * under test) is computed from a name option before expansion — a
695
+ * mismatched key would silently split the two. Expansion errors with a
696
+ * pointer to the component's `name` option instead.
697
+ */
698
+ expectKey?: string;
699
+ }
700
+
701
+ /**
702
+ * A multi-service component — the value `serviceGroup(...)` returns, and
703
+ * what a constellation component (e.g. `supabase()`) hands you to put in
704
+ * the services map. Opaque; `defineEnvironment` expands it.
705
+ */
706
+ export interface ServiceGroup<
707
+ P extends ServicesMap = ServicesMap,
708
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
709
+ H extends Record<string, any> = Record<string, never>,
710
+ Primary extends keyof P & string = keyof P & string,
711
+ > extends ServiceGroupInput<P, H, Primary> {
712
+ readonly [SERVICE_GROUP]: true;
713
+ }
714
+
715
+ /**
716
+ * Define a multi-service group. See {@link ServiceGroupInput} for the
717
+ * fields; the result goes straight into a services map:
718
+ *
719
+ * ```ts
720
+ * const stack = serviceGroup({
721
+ * primary: "gateway",
722
+ * services: (g) => ({
723
+ * db: { image: ..., ... },
724
+ * gateway: { image: ..., env: { DB_URL: `postgres://${g.key("db")}:5432/db` },
725
+ * dependsOn: ["db"] },
726
+ * }),
727
+ * helpers: () => ({ url: "http://..." }),
728
+ * });
729
+ *
730
+ * defineEnvironment({ name: "app", services: { stack } });
731
+ * // expands to services `stack` (the gateway) + `stack-db`;
732
+ * // ctx.svc.stack is the helpers record.
733
+ * ```
734
+ */
735
+ export function serviceGroup<
736
+ P extends ServicesMap,
737
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
738
+ H extends Record<string, any> = Record<string, never>,
739
+ Primary extends keyof P & string = keyof P & string,
740
+ >(input: ServiceGroupInput<P, H, Primary>): ServiceGroup<P, H, Primary> {
741
+ if (typeof input.services !== "function") {
742
+ throw new Error("serviceGroup: `services` must be a factory function");
743
+ }
744
+ if (!input.primary || typeof input.primary !== "string") {
745
+ throw new Error("serviceGroup: `primary` (a relative part name) is required");
746
+ }
747
+ const group = { ...input } as ServiceGroup<P, H, Primary>;
748
+ Object.defineProperty(group, SERVICE_GROUP, {
749
+ value: true,
750
+ enumerable: true,
751
+ configurable: true,
752
+ writable: false,
753
+ });
754
+ return group;
755
+ }
756
+
757
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
758
+ function isServiceGroup(v: unknown): v is ServiceGroup<any, any, any> {
759
+ return (
760
+ typeof v === "object" &&
761
+ v !== null &&
762
+ (v as Record<symbol, unknown>)[SERVICE_GROUP] === true
763
+ );
764
+ }
765
+
766
+ /** What users pass as `services` to `defineEnvironment`: plain services
767
+ * and/or groups to expand. */
768
+ export type InputServicesMap = Record<
769
+ string,
770
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
771
+ ServiceConfig | ServiceGroup<any, any, any>
772
+ >;
773
+
774
+ type UnionToIntersection<U> = (
775
+ U extends unknown ? (x: U) => void : never
776
+ ) extends (x: infer I) => void
777
+ ? I
778
+ : never;
779
+
780
+ /** Flatten an intersection of records into one mapped type (which also
781
+ * gives it the implicit index signature `ServicesMap` needs). */
782
+ type Reify<T> = { [K in keyof T]: T[K] };
783
+
784
+ /** The primary part with the group's consolidated `helpers` grafted on,
785
+ * so `ServiceHandlesFor` surfaces the group handle at the group key. */
786
+ type PrimaryWithHandle<C, H> = [H] extends [Record<string, never>]
787
+ ? C
788
+ : Omit<C, "helpers"> & { helpers: (args: ServiceHelpersContext) => H };
789
+
790
+ type ExpandGroupEntry<K extends string, G> = G extends ServiceGroup<
791
+ infer P,
792
+ infer H,
793
+ infer Primary
794
+ >
795
+ ? {
796
+ [Q in Exclude<keyof P & string, Primary> as `${K}-${Q}`]: P[Q];
797
+ } & { [Q in K]: PrimaryWithHandle<P[Primary & keyof P], H> }
798
+ : never;
799
+
800
+ /**
801
+ * The services map after group expansion — what `ctx.svc` and the wire
802
+ * config are typed against. Groups expand to `<key>` (primary, carrying
803
+ * the group handle) + `<key>-<part>` entries; plain services pass through.
804
+ */
805
+ export type ExpandServices<SI extends InputServicesMap> = Reify<
806
+ UnionToIntersection<
807
+ {
808
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
809
+ [K in keyof SI & string]: SI[K] extends ServiceGroup<any, any, any>
810
+ ? ExpandGroupEntry<K, SI[K]>
811
+ : { [Q in K]: SI[K] };
812
+ }[keyof SI & string]
813
+ >
814
+ > extends infer S extends ServicesMap
815
+ ? S
816
+ : ServicesMap;
817
+
818
+ /**
819
+ * Runtime counterpart of {@link ExpandServices}: expand every group entry
820
+ * into plain services. Throws on key collisions, a missing primary,
821
+ * nested groups, a violated `expectKey`, and members depending on the
822
+ * primary (the primary is the group's sink — see
823
+ * {@link ServiceGroupInput.primary}).
824
+ */
825
+ function expandServiceGroups(input: InputServicesMap): ServicesMap {
826
+ const out: ServicesMap = {};
827
+ const ownerOf = new Map<string, string>();
828
+ const claim = (key: string, owner: string): void => {
829
+ const prior = ownerOf.get(key);
830
+ if (prior !== undefined) {
831
+ throw new Error(
832
+ `service key ${JSON.stringify(key)} is produced by both ${prior} and ${owner}`,
833
+ );
834
+ }
835
+ ownerOf.set(key, owner);
836
+ };
837
+
838
+ for (const [key, entry] of Object.entries(input)) {
839
+ if (!isServiceGroup(entry)) {
840
+ claim(key, "the services map");
841
+ out[key] = entry;
842
+ continue;
843
+ }
844
+ const owner = `group ${JSON.stringify(key)}`;
845
+ if (entry.expectKey !== undefined && entry.expectKey !== key) {
846
+ throw new Error(
847
+ `service group at key ${JSON.stringify(key)} expects to be mounted at ` +
848
+ `${JSON.stringify(entry.expectKey)} — its derived names (URLs, app env) were built ` +
849
+ `from that name. Mount it at ${JSON.stringify(entry.expectKey)}, or pass ` +
850
+ `\`name: ${JSON.stringify(key)}\` to the component so both agree.`,
851
+ );
852
+ }
853
+ const naming: GroupNaming = {
854
+ name: key,
855
+ key: (part: string) => (part === entry.primary ? key : `${key}-${part}`),
856
+ };
857
+ const parts: ServicesMap = entry.services(naming);
858
+ const partKeys = new Set(Object.keys(parts));
859
+ if (!partKeys.has(entry.primary)) {
860
+ throw new Error(
861
+ `${owner}: primary part ${JSON.stringify(entry.primary)} is not in the parts the ` +
862
+ `services factory returned (${[...partKeys].join(", ")})`,
863
+ );
864
+ }
865
+ // No member may depend on the primary (directly or transitively within
866
+ // the group): the primary is about to become the group's sink.
867
+ const reachesPrimary = (part: string, seen = new Set<string>()): boolean => {
868
+ if (seen.has(part)) return false;
869
+ seen.add(part);
870
+ for (const dep of parts[part]?.dependsOn ?? []) {
871
+ if (!partKeys.has(dep)) continue;
872
+ if (dep === entry.primary || reachesPrimary(dep, seen)) return true;
873
+ }
874
+ return false;
875
+ };
876
+ for (const part of partKeys) {
877
+ if (isServiceGroup(parts[part])) {
878
+ throw new Error(`${owner}: part ${JSON.stringify(part)} is itself a group — groups don't nest`);
879
+ }
880
+ if (part !== entry.primary && reachesPrimary(part)) {
881
+ throw new Error(
882
+ `${owner}: part ${JSON.stringify(part)} depends on the primary ` +
883
+ `${JSON.stringify(entry.primary)} — the primary must be the group's sink ` +
884
+ `(everything else becomes its dependency so "primary ready" means "group up")`,
885
+ );
886
+ }
887
+ }
888
+ for (const [part, svc] of Object.entries(parts)) {
889
+ const finalKey = naming.key(part);
890
+ claim(finalKey, owner);
891
+ // Rewrite relative dependsOn to final keys; a spread keeps function
892
+ // fields (helpers/setup) and the enumerable-symbol ingress decls.
893
+ const final: ServiceConfig = { ...svc };
894
+ if (svc.dependsOn?.length) {
895
+ final.dependsOn = svc.dependsOn.map((d) =>
896
+ partKeys.has(d) ? naming.key(d) : d,
897
+ );
898
+ }
899
+ if (part === entry.primary) {
900
+ // Sink: the primary waits for every other member, so an outside
901
+ // `dependsOn: ["<groupKey>"]` (and the group `setup` below) means
902
+ // the whole group. Members already in dependsOn stay put.
903
+ const deps = new Set(final.dependsOn ?? []);
904
+ for (const other of partKeys) {
905
+ if (other !== entry.primary) deps.add(naming.key(other));
906
+ }
907
+ final.dependsOn = [...deps];
908
+ const def = final as ServiceDefinition<Record<string, unknown>>;
909
+ if (entry.helpers) {
910
+ if (def.helpers) {
911
+ throw new Error(
912
+ `${owner}: both the group and its primary part declare \`helpers\` — ` +
913
+ `declare them once, on the group`,
914
+ );
915
+ }
916
+ def.helpers = entry.helpers as (
917
+ args: ServiceHelpersContext,
918
+ ) => Record<string, unknown> | Promise<Record<string, unknown>>;
919
+ }
920
+ if (entry.setup) {
921
+ const partSetup = def.setup;
922
+ const groupSetup = entry.setup as (
923
+ args: ServiceSetupContext<Record<string, unknown>>,
924
+ ) => void | Promise<void>;
925
+ def.setup = async (args) => {
926
+ if (partSetup) await partSetup(args);
927
+ await groupSetup(args);
928
+ };
929
+ }
930
+ }
931
+ out[finalKey] = final;
932
+ }
933
+ }
934
+ return out;
935
+ }
936
+
937
+ /**
938
+ * One TLS-terminated hostname for a service. The daemon binds the
939
+ * hostname on `:443` (with a leaf cert signed by the in-VM root CA)
940
+ * and `:80`, and reverse-proxies each request to `http://<service>:<port>`
941
+ * inside the docker network. WebSocket upgrades are bridged.
942
+ */
943
+ export interface ServiceTls {
944
+ /** Fully-qualified hostname clients use (e.g. `app.test`). Must be
945
+ * multi-label, lowercase, not under the reserved `.internal` TLD,
946
+ * and unique across all services and fakes in this environment. */
947
+ hostname: string;
948
+ /** HTTP port the service listens on inside its container. The
949
+ * daemon forwards proxied requests here over `spectest-net`. */
950
+ port: number;
951
+ }
952
+
953
+ export type ServiceImage =
954
+ | { type: "registry"; reference: string }
955
+ | {
956
+ type: "dockerfile";
957
+ /**
958
+ * Dockerfile contents, written verbatim into the build context. The
959
+ * build context is the project root (where `spectest/` lives), so any
960
+ * `COPY` / `ADD` references resolve relative to that directory.
961
+ */
962
+ content: string;
963
+ /** Extra glob patterns to exclude from the build context. */
964
+ exclude?: readonly string[];
965
+ };
966
+
967
+ export interface VolumeMount {
968
+ /**
969
+ * Named shared volume. Two services mounting the same `name` share one
970
+ * backing directory — the fit for sidecar pairs that exchange files
971
+ * (e.g. an image proxy reading what a storage API wrote). The directory
972
+ * lives in the per-env state tree, so it snapshots/forks with the rest
973
+ * of the environment and is torn down for fresh-state like any other
974
+ * volume. Names are environment-global: prefix with your service/group
975
+ * name in a reusable component so two instances never collide.
976
+ * Mutually exclusive with `source`.
977
+ */
978
+ name?: string;
979
+ /**
980
+ * Host path. Relative paths resolve under
981
+ * `.spectest/volumes/<service>/`. Defaults to a path derived from `target`.
982
+ *
983
+ * An absolute path that already exists and is not a directory is
984
+ * bind-mounted as-is — the way to hand a service the VM's docker socket
985
+ * (`source: "/var/run/docker.sock"`), which LocalStack's Lambda executor
986
+ * and dind-style builders need. Such a mount is VM-host infrastructure,
987
+ * so unlike a volume directory it is never created or wiped by spectest.
988
+ */
989
+ source?: string;
990
+ /** Container path. */
991
+ target: string;
992
+ readOnly?: boolean;
993
+ /**
994
+ * Cache volume: the backing dir lives outside the per-env state tree and
995
+ * survives a delta-restore teardown (which recreates every container,
996
+ * volume, and the daemon for fresh-state semantics). Reserve this for
997
+ * content-addressed data whose presence is purely an accelerator — an
998
+ * image/layer store, a package cache — never for app state: anything in
999
+ * a cache volume is visible to the "fresh" environment.
1000
+ */
1001
+ cache?: boolean;
1002
+ }
1003
+
1004
+ export interface FileMount {
1005
+ /** Absolute path inside the container where the file is mounted. */
1006
+ path: string;
1007
+ /**
1008
+ * File contents. The literal token `{{SPECTEST_SERVICE}}` is expanded
1009
+ * to the owning service's name (its services-map key) before the file
1010
+ * is written — handy for self-referential config like a registry host
1011
+ * of `<key>.internal`, where a component can't know the key in advance.
1012
+ */
1013
+ content: string;
1014
+ /**
1015
+ * Optional octal mode string (e.g. `"0644"`) applied to the staged
1016
+ * file before it's bind-mounted. Defaults to the writer's umask.
1017
+ */
1018
+ mode?: string;
1019
+ /**
1020
+ * Owner of the staged file — a user name from the image's
1021
+ * `/etc/passwd` (resolved against the image, so `"postgres"` works),
1022
+ * or a numeric uid. A bind mount carries the staged file's ownership
1023
+ * straight through, so a file written by the daemon lands as `root`:
1024
+ * pair a restrictive `mode` with `user` or the container's own
1025
+ * process can't read it.
1026
+ */
1027
+ user?: string;
1028
+ /** Group of the staged file — a group name from the image's
1029
+ * `/etc/group`, or a numeric gid. */
1030
+ group?: string;
1031
+ }
1032
+
1033
+ /** PEM material returned by `ctx.certificate(hostnames)`. */
1034
+ export interface CertificateMaterial {
1035
+ /** PEM certificate, signed by the in-VM root CA. */
1036
+ cert: string;
1037
+ /** PEM private key for {@link cert}. */
1038
+ key: string;
1039
+ /** PEM root CA certificate — the one the environment already trusts. */
1040
+ ca: string;
1041
+ }
1042
+
1043
+ /** One leaf certificate materialized into a service container — see
1044
+ * {@link ServiceConfig.certificates}. */
1045
+ export interface CertificateMount {
1046
+ /** SANs the leaf covers. Wildcards (`*.example.com`) are allowed. */
1047
+ hostnames: readonly string[];
1048
+ /** Absolute path inside the container for the PEM certificate. */
1049
+ certPath: string;
1050
+ /** Absolute path inside the container for the PEM private key. */
1051
+ keyPath: string;
1052
+ /**
1053
+ * Optional absolute path for the root CA certificate. Every container
1054
+ * already trusts the CA (`SSL_CERT_FILE` and friends are pre-set), so
1055
+ * this is only for software that wants an explicit CA file — client
1056
+ * certificate verification, a `sslrootcert=` connection parameter.
1057
+ */
1058
+ caPath?: string;
1059
+ /**
1060
+ * Optional octal mode (e.g. `"0600"`) applied to the staged key.
1061
+ * Servers that refuse a group/world-readable key (postgres, ssh) need
1062
+ * this. The default is the writer's umask — or, once `user`/`group`
1063
+ * says who reads the key, the strictest mode that owner can still
1064
+ * read (`0600`, or `0640` when only `group` is given).
1065
+ */
1066
+ mode?: string;
1067
+ /**
1068
+ * Owner of the staged key and certificate — a user name from the
1069
+ * image's `/etc/passwd` (resolved against the image, so
1070
+ * `"postgres"` works), or a numeric uid.
1071
+ *
1072
+ * A bind mount carries the staged file's ownership through, and the
1073
+ * daemon writes as `root`, so a strict `mode` alone gives a
1074
+ * non-root server a key it cannot open — postgres reports
1075
+ * `could not access private key file`. `user` is what makes the
1076
+ * pair work, with no entrypoint wrapper and no custom image.
1077
+ */
1078
+ user?: string;
1079
+ /** Group of the staged key and certificate — a group name from the
1080
+ * image's `/etc/group`, or a numeric gid. Enough on its own for a
1081
+ * server that accepts a root-owned key readable by its group
1082
+ * (postgres does, at `0640`). */
1083
+ group?: string;
1084
+ }
1085
+
1086
+ export type ReadyCheck =
1087
+ | { type: "tcp"; port: number; timeoutSecs?: number }
1088
+ | {
1089
+ type: "http";
1090
+ port: number;
1091
+ path?: string;
1092
+ /**
1093
+ * Extra request headers sent with each probe — for health endpoints
1094
+ * behind auth (`{ Authorization: "Bearer …" }`). Keeps the probe
1095
+ * image-agnostic where an `exec` + curl would depend on curl being
1096
+ * in the image.
1097
+ */
1098
+ headers?: Record<string, string>;
1099
+ /**
1100
+ * Exact status code that counts as ready. Default: any 2xx. Use for
1101
+ * endpoints whose healthy answer isn't 2xx (e.g. a root path that
1102
+ * 301s or 401s once the server is actually up).
1103
+ */
1104
+ expectStatus?: number;
1105
+ timeoutSecs?: number;
1106
+ }
1107
+ /**
1108
+ * Run a shell command inside the container; exit 0 = ready. Used when
1109
+ * the readiness signal isn't reachable via plain TCP/HTTP from outside
1110
+ * (k3s API server uses mTLS, so the natural probe is `kubectl get
1111
+ * --raw=/readyz` from inside).
1112
+ */
1113
+ | { type: "exec"; command: string; timeoutSecs?: number };
1114
+
1115
+ // ──────────────────────────────────────────────────────────────────────────
1116
+ // Runtime services — containers started *during* a test/eval/setup or from
1117
+ // inside a fake handler, rather than declared up-front in `services`.
1118
+ // ──────────────────────────────────────────────────────────────────────────
1119
+
1120
+ /**
1121
+ * Spec for a service started at runtime via {@link TestContext.startService}
1122
+ * (or the `ctx` handed to a fake). It's a normal {@link ServiceConfig} plus a
1123
+ * required `name`, minus only `dependsOn` (there is no boot DAG at runtime;
1124
+ * the caller orders `startService` calls itself with `await`).
1125
+ *
1126
+ * The container joins `spectest-net` with its own IP and is resolvable by
1127
+ * `name` (single-label, via the resolver / docker embedded DNS) and by any
1128
+ * `hostnames` (extra `--network-alias`es). Like everything else in the VM it
1129
+ * is captured by the per-test post-state snapshot, so a `dependsOn` child
1130
+ * inherits the live container while siblings never see it.
1131
+ *
1132
+ * `tls: [{ hostname, port }]` works exactly as it does for a boot service:
1133
+ * the daemon mints a leaf cert from the in-VM root CA and stands up a
1134
+ * TLS-terminating reverse proxy at `https://<hostname>/` (and plain
1135
+ * `http://<hostname>/`) → the container's `port`, binding it onto the live
1136
+ * `:443`/`:80` ingress listeners the moment the container is ready. The
1137
+ * hostname resolves to the daemon gateway for tests, `ctx.browser()`, and
1138
+ * peer containers. Because the route lives in daemon memory (and the
1139
+ * resolver registry file), it forks with the per-test snapshot like fake
1140
+ * state, and is torn down when the service is stopped. This lets a runtime
1141
+ * provider mint a CA-trusted HTTPS endpoint on demand — e.g. a per-DB proxy
1142
+ * the Neon serverless driver reaches at its *default* `https://<host>/sql`.
1143
+ */
1144
+ export interface RuntimeServiceSpec extends Omit<ServiceConfig, "dependsOn"> {
1145
+ /**
1146
+ * Container name and primary DNS name on `spectest-net`. Must be unique
1147
+ * within the current fork — generate a fresh one per provisioned instance
1148
+ * (e.g. `db-${crypto.randomUUID().slice(0, 8)}`).
1149
+ */
1150
+ name: string;
1151
+ }
1152
+
1153
+ /** What {@link TestContext.startService} resolves to once the container is up
1154
+ * and its `readyCheck` (if any) has passed. */
1155
+ export interface RuntimeServiceHandle {
1156
+ /** The container/DNS name — the spec's `name`. */
1157
+ name: string;
1158
+ /** The container's IP on `spectest-net`. Reachable directly from peer
1159
+ * containers and from VM-host/test code. */
1160
+ ip: string;
1161
+ }
1162
+
1163
+ /**
1164
+ * The slice of the environment a fake can mutate at runtime — the same
1165
+ * primitives {@link TestContext} exposes to tests. Passed as the third
1166
+ * argument to a fake's `handler` and as `ctx` to its `helpers` factory, so
1167
+ * a fake (e.g. a database-provider control plane) can provision real
1168
+ * backing services on demand and wire up DNS for them, exactly as a test
1169
+ * would.
1170
+ */
1171
+ export interface FakeContext {
1172
+ /** Start a real container on `spectest-net` at runtime. See
1173
+ * {@link RuntimeServiceSpec}. */
1174
+ startService(spec: RuntimeServiceSpec): Promise<RuntimeServiceHandle>;
1175
+ /** Stop and remove a runtime service started earlier (no-op if gone). */
1176
+ stopService(name: string): Promise<void>;
1177
+ /** Map a DNS name onto a service IP (or the daemon ingress). See
1178
+ * {@link TestContext.dnsName}. */
1179
+ dnsName(hostname: string, target: DnsTarget): Promise<void>;
1180
+ /** Mint a CA-signed leaf certificate. See
1181
+ * {@link TestContext.certificate} — the primitive a fake standing in
1182
+ * for a TLS-provisioning provider hands back to the app under test. */
1183
+ certificate(hostnames: readonly string[]): Promise<CertificateMaterial>;
1184
+ }
1185
+
1186
+ function validateEnvironmentConfig<S extends ServicesMap>(
1187
+ config: EnvironmentConfig<S>,
1188
+ ): void {
1189
+ const entries = Object.entries(config.services);
1190
+ const serviceNames = new Set(entries.map(([n]) => n));
1191
+ const claimedBy = new Map<string, string>();
1192
+ const claimBy = (h: string, name: string, kind: "hostname" | "tls"): void => {
1193
+ const prior = claimedBy.get(h);
1194
+ if (prior !== undefined && prior !== name) {
1195
+ throw new Error(
1196
+ `hostname ${JSON.stringify(h)} is claimed by both "${prior}" and "${name}"`,
1197
+ );
1198
+ }
1199
+ if (serviceNames.has(h)) {
1200
+ throw new Error(
1201
+ `${kind} ${JSON.stringify(h)} collides with service name "${h}"`,
1202
+ );
1203
+ }
1204
+ claimedBy.set(h, name);
1205
+ };
1206
+ for (const [name, svc] of entries) {
1207
+ if (name.length === 0) {
1208
+ throw new Error(
1209
+ "service name (services map key) must be a non-empty string",
1210
+ );
1211
+ }
1212
+ for (const dep of svc.dependsOn ?? []) {
1213
+ if (!serviceNames.has(dep)) {
1214
+ throw new Error(
1215
+ `service "${name}" dependsOn "${dep}" which is not a service in this environment`,
1216
+ );
1217
+ }
1218
+ }
1219
+ for (const vol of svc.volumes ?? []) {
1220
+ if (vol.name !== undefined && vol.source !== undefined) {
1221
+ throw new Error(
1222
+ `service "${name}" volume for ${JSON.stringify(vol.target)} sets both \`name\` and \`source\` — a named shared volume derives its backing dir from the name`,
1223
+ );
1224
+ }
1225
+ if (vol.name !== undefined && !/^[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(vol.name)) {
1226
+ throw new Error(
1227
+ `service "${name}" volume name ${JSON.stringify(vol.name)} must be alphanumeric plus [._-]`,
1228
+ );
1229
+ }
1230
+ }
1231
+ for (const raw of svc.hostnames ?? []) {
1232
+ const h = raw.toLowerCase();
1233
+ if (!HOSTNAME_RE.test(hostPatternBody(h))) {
1234
+ throw new Error(
1235
+ `service "${name}" declares invalid hostname ${JSON.stringify(raw)} — must be a multi-label DNS name or a wildcard (e.g. "api.stripe.com", "*.stripe.com")`,
1236
+ );
1237
+ }
1238
+ if (h === "internal" || h.endsWith(".internal")) {
1239
+ throw new Error(
1240
+ `service "${name}" declares hostname ${JSON.stringify(raw)} — the ".internal" TLD is reserved; every service already answers to "<name>.internal" automatically`,
1241
+ );
1242
+ }
1243
+ claimBy(h, name, "hostname");
1244
+ }
1245
+ for (const entry of svc.tls ?? []) {
1246
+ if (!entry || typeof entry.hostname !== "string" || typeof entry.port !== "number") {
1247
+ throw new Error(
1248
+ `service "${name}" tls entry must be { hostname: string, port: number }; got ${JSON.stringify(entry)}`,
1249
+ );
1250
+ }
1251
+ const h = entry.hostname.toLowerCase();
1252
+ if (!HOSTNAME_RE.test(hostPatternBody(h))) {
1253
+ throw new Error(
1254
+ `service "${name}" tls hostname ${JSON.stringify(entry.hostname)} is not a multi-label DNS name or wildcard (e.g. "app.test", "*.us-east-1.amazonaws.com")`,
1255
+ );
1256
+ }
1257
+ if (h === "internal" || h.endsWith(".internal")) {
1258
+ throw new Error(
1259
+ `service "${name}" tls hostname ${JSON.stringify(entry.hostname)} ends in reserved ".internal" TLD`,
1260
+ );
1261
+ }
1262
+ if (!Number.isInteger(entry.port) || entry.port <= 0 || entry.port > 65535) {
1263
+ throw new Error(
1264
+ `service "${name}" tls hostname ${JSON.stringify(entry.hostname)} has invalid port ${entry.port}`,
1265
+ );
1266
+ }
1267
+ claimBy(h, name, "tls");
1268
+ }
1269
+ }
1270
+ }
1271
+
1272
+ // Multi-label hostname: at least one dot, each label 1–63 chars of
1273
+ // [a-z0-9-], no leading/trailing hyphen.
1274
+ const HOSTNAME_RE =
1275
+ /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)+$/;
1276
+
1277
+ /** The part of a declared name that must be a valid hostname: a `*.suffix`
1278
+ * wildcard is checked by its suffix, so `*.example.com` passes but `*.com`
1279
+ * (single-label, too broad) and `*` do not. Keeps the `.internal` checks
1280
+ * honest too — `*.foo.internal` reduces to `foo.internal`. */
1281
+ function hostPatternBody(lowercased: string): string {
1282
+ return isWildcardHost(lowercased) ? lowercased.slice(2) : lowercased;
1283
+ }
1284
+
1285
+ // ──────────────────────────────────────────────────────────────────────────
1286
+ // Test framework
1287
+ // ──────────────────────────────────────────────────────────────────────────
1288
+
1289
+ /**
1290
+ * A single test step. Created via `test(...)` or `createTest(services)`.
1291
+ * Tests are referenced (not named by string) when one test depends on
1292
+ * another — keeps refactors and type-checking honest.
1293
+ *
1294
+ * `T` is the return type of the test body; it surfaces as `ctx.parent`
1295
+ * in children that `dependsOn` this case. `S` is the project's services
1296
+ * map (threaded through `defineEnvironment(...).test`) so `ctx.svc.<key>`
1297
+ * is strongly typed.
1298
+ */
1299
+ export interface TestCase<
1300
+ T = unknown,
1301
+ S extends ServicesMap = ServicesMap,
1302
+ F extends FakesMap = FakesMap,
1303
+ > {
1304
+ /** Stable id (slug of name). Used in run results and CLI flags. */
1305
+ readonly id: string;
1306
+ readonly name: string;
1307
+ /** Parent test, if any. Single-parent for now. */
1308
+ readonly dependsOn?: TestCase<unknown, S, F>;
1309
+ /** Override the default per-test timeout (default 60s). */
1310
+ readonly timeoutMs?: number;
1311
+ /** @internal — the body that the in-sandbox daemon invokes. */
1312
+ readonly run: TestFn<T, unknown, S, F>;
1313
+ }
1314
+
1315
+ export interface TestOpts<
1316
+ P = undefined,
1317
+ S extends ServicesMap = ServicesMap,
1318
+ F extends FakesMap = FakesMap,
1319
+ > {
1320
+ dependsOn?: TestCase<P, S, F>;
1321
+ timeoutMs?: number;
1322
+ }
1323
+
1324
+ export type TestFn<
1325
+ T = void,
1326
+ P = undefined,
1327
+ S extends ServicesMap = ServicesMap,
1328
+ F extends FakesMap = FakesMap,
1329
+ > = (ctx: TestContext<P, S, F>) => T | Promise<T>;
1330
+
1331
+ /**
1332
+ * Context object passed to every test function.
1333
+ *
1334
+ * `P` is the return type of the parent test (the one named in
1335
+ * `dependsOn`); for root tests it's `undefined`. `S` is the project's
1336
+ * services map (threaded through `defineEnvironment(...).test`) so
1337
+ * `ctx.svc` only includes services with a `client` factory, each typed
1338
+ * as the factory's output (e.g. a Bun SQL pool for `postgres(...)`).
1339
+ */
1340
+ export interface TestContext<
1341
+ P = undefined,
1342
+ S extends ServicesMap = ServicesMap,
1343
+ F extends FakesMap = FakesMap,
1344
+ > extends Omit<SpectestContext<S, F>, "exec"> {
1345
+ /** Run a command inside a service container — a string via `sh -lc`,
1346
+ * or an array as exact argv. The result is {@link Wrapped}, so
1347
+ * `res.stdout` is a `Carrier<string>` — assert via `expect(res.stdout)`
1348
+ * or recover the raw string with `res.stdout.unwrap()`. (This is the
1349
+ * one place {@link SpectestContext.exec} differs: in `setup`/`helpers`
1350
+ * there's no timeline to link to, so the result is plain.)
1351
+ *
1352
+ * The full run is also captured as an asciicast and replayed in the
1353
+ * web UI — one recording per call, with output timestamped as it
1354
+ * streamed, so slow or animated CLI output can be watched rather
1355
+ * than read as a final blob. Unlike `terminal` there is no PTY: the
1356
+ * program sees plain pipes (`isatty` false), so stdout/stderr stay
1357
+ * byte-identical to what `exec` always returned and TTY-gated
1358
+ * spinners/colour won't be emitted — reach for `terminal` when the
1359
+ * CLI needs to believe it's on a TTY.
1360
+ *
1361
+ * Pass `{ cwd }` to run the command from a working directory instead of
1362
+ * prefixing it with `cd <dir> && ` — the cwd is kept off the command
1363
+ * string, so the timeline sidebar shows just the command and the
1364
+ * directory surfaces in the detail view. */
1365
+ exec(
1366
+ service: string,
1367
+ command: string | string[],
1368
+ opts?: ExecOpts,
1369
+ ): Promise<Wrapped<ExecResult>>;
1370
+ /**
1371
+ * Run a command inside a service container under a PTY and record the
1372
+ * full terminal session as an asciicast for replay in the web UI.
1373
+ * Unlike `exec`, the program sees a TTY (`isatty(1)` true, colour
1374
+ * codes preserved, line-buffered), so the byte stream may differ from
1375
+ * what `exec` returns. Reach for `terminal` when you're driving a CLI
1376
+ * and want a recording; reach for `exec` for plain piped output.
1377
+ *
1378
+ * One-shot convenience: this is a thin wrapper over `openTerminal` —
1379
+ * spawn `command`, wait for exit, close, return the captured output
1380
+ * and exit code. Reach for `openTerminal` when you want to keep the
1381
+ * session alive across multiple sends or `waitFor` predicates (e.g.
1382
+ * driving an interactive REPL or waiting on a loading spinner).
1383
+ */
1384
+ terminal(
1385
+ service: string,
1386
+ command: string,
1387
+ opts?: TerminalOpts,
1388
+ ): Promise<Wrapped<TerminalResult>>;
1389
+ /**
1390
+ * Open a long-lived interactive terminal in a service container.
1391
+ * Returns a `Terminal` you can `send` keystrokes to, poll the
1392
+ * rendered screen with `waitFor`, and `close` when done. Every byte
1393
+ * the PTY emits is captured as an asciicast and replayed in the web
1394
+ * UI the same way a one-shot `terminal(...)` is.
1395
+ *
1396
+ * Terminals are NOT auto-closed when the test ends. A docker exec
1397
+ * subprocess is cheap to keep alive and the VM snapshot captures it
1398
+ * cleanly along with the rest of the container, so leaking the handle
1399
+ * past test end is fine. Call `.close()`
1400
+ * explicitly if you want a `close` step in the timeline; otherwise
1401
+ * `await term.exited` (after the program self-terminates) is the
1402
+ * natural way to assert on the exit code.
1403
+ */
1404
+ openTerminal(service: string, opts?: TerminalOpts): Promise<Terminal>;
1405
+ /**
1406
+ * Open the headless browser. Backed by Chromium-over-CDP inside the VM.
1407
+ *
1408
+ * There is ONE persistent browser per environment: every `ctx.browser()`
1409
+ * call returns it, and it stays alive across tests — the browser is part
1410
+ * of the state a test's snapshot captures, so a `dependsOn` child resumes
1411
+ * the exact live page its parent left (cookies, localStorage, signed-in
1412
+ * SPA state). Sign in once in a parent test; every descendant is already
1413
+ * signed in. Sibling tests fork from the same parent snapshot, so they
1414
+ * can't see each other's browsing. A test with no browser-using ancestor
1415
+ * gets a fresh browser on first call (first call's options win).
1416
+ *
1417
+ * `.close()` destroys the shared instance — the next `ctx.browser()`
1418
+ * starts fresh. Don't call it for routine cleanup; recording is detached
1419
+ * automatically at test end.
1420
+ */
1421
+ browser(opts?: BrowserOptions): Promise<Browser>;
1422
+ /**
1423
+ * Open a phone-emulated session for a mobile app and return a {@link Mobile}
1424
+ * handle already pointed at it — no `navigate`. Pass the app handle a
1425
+ * mobile-app component exposes on `ctx.svc`, e.g. a service declared with
1426
+ * `expo()`:
1427
+ *
1428
+ * ```ts
1429
+ * services: { app: expo() }
1430
+ * // in a test:
1431
+ * const m = await ctx.mobile(ctx.svc.app);
1432
+ * await m.getByTestId("email").fill("a@b.com");
1433
+ * await m.getByRole("button", { name: "Sign in" }).tap();
1434
+ * await expect(m.getByText(/Welcome/)).toBeVisible();
1435
+ * ```
1436
+ *
1437
+ * The session emulates the latest iPhone (viewport + DPR + mobile UA +
1438
+ * touch) and the dashboard replays it inside a phone bezel.
1439
+ *
1440
+ * Sessions are persistent, one per app: like `ctx.browser()`, the live
1441
+ * session is captured in the test's snapshot, so a `dependsOn` child
1442
+ * picks up the app exactly where the parent left it (already signed in,
1443
+ * mid-flow) instead of reloading it. `.close()` discards the session;
1444
+ * the next `ctx.mobile(app)` opens the app fresh.
1445
+ */
1446
+ mobile(app: MobileApp): Promise<Mobile>;
1447
+ /** The test's display name. */
1448
+ readonly testName: string;
1449
+ /**
1450
+ * Value returned by the parent test. Carried across the fork in the
1451
+ * daemon's own memory (a VM snapshot is memory + filesystem), so
1452
+ * any JS value works — including Maps, Sets, class instances, and live
1453
+ * connections that survive the fork. `undefined` for root tests or when
1454
+ * the parent returned nothing.
1455
+ */
1456
+ readonly parent: P;
1457
+ }
1458
+
1459
+ export interface ExecResult {
1460
+ stdout: string;
1461
+ stderr: string;
1462
+ exitCode: number;
1463
+ }
1464
+
1465
+ /** Options for {@link TestContext.exec}.
1466
+ *
1467
+ * Unknown properties are rejected at runtime (`ctx.exec` throws), not
1468
+ * silently ignored — the type-level excess-property check is advisory
1469
+ * here, since `spectest test`'s typecheck never gates a run. */
1470
+ export interface ExecOpts {
1471
+ /**
1472
+ * Working directory inside the container to run the command from.
1473
+ * Equivalent to prefixing the command with `cd <cwd> && `, but the
1474
+ * directory is kept off the command string: the recorded step's
1475
+ * sidebar summary shows just the command, while the working directory
1476
+ * is surfaced in the detail view (the prompt line of the captured
1477
+ * terminal and the step's panel header). Implemented as `docker exec
1478
+ * -w <cwd>`, so a relative path resolves against the image's WORKDIR.
1479
+ */
1480
+ cwd?: string;
1481
+ /**
1482
+ * Piped to the command's stdin, then closed — the natural way to feed
1483
+ * a manifest to `kubectl apply -f -` or a SQL file to `psql -f -`
1484
+ * without staging a temp file in the container:
1485
+ *
1486
+ * ```ts
1487
+ * await ctx.exec("k8s", "kubectl apply -f -", { stdin: manifestYaml });
1488
+ * ```
1489
+ *
1490
+ * The payload is written after the process starts and the stream is
1491
+ * closed immediately after, so a command that never reads stdin still
1492
+ * exits normally (the write is allowed to fail with EPIPE).
1493
+ */
1494
+ stdin?: string;
1495
+ /**
1496
+ * Kill the command (SIGKILL) after this long and return `exitCode`
1497
+ * 124 with a `timeout after <n>ms` note on stderr, rather than
1498
+ * hanging until the enclosing test's own timeout fires.
1499
+ *
1500
+ * **There is no default** — an `exec` runs as long as it likes. In a
1501
+ * test the enclosing `env.test(..., { timeoutMs })` (60 s by default)
1502
+ * is the real ceiling; in `setup`/`eval`, where no test timeout
1503
+ * applies, an unbounded command hangs the boot, so set this when the
1504
+ * command can plausibly wedge.
1505
+ */
1506
+ timeoutMs?: number;
1507
+ }
1508
+
1509
+ export interface TestSuite<
1510
+ S extends ServicesMap = ServicesMap,
1511
+ F extends FakesMap = FakesMap,
1512
+ > {
1513
+ tests: TestCase<unknown, S, F>[];
1514
+ }
1515
+
1516
+ // ──────────────────────────────────────────────────────────────────────────
1517
+ // Fakes — in-daemon HTTP servers that masquerade as external APIs.
1518
+ // ──────────────────────────────────────────────────────────────────────────
1519
+
1520
+ /**
1521
+ * A fake server hosted in the harness. Use this to stand in for
1522
+ * external HTTP APIs (auth providers, payment gateways, …) that you can't
1523
+ * call directly from the hermetic test VM.
1524
+ *
1525
+ * Each fake declares one or more `hostnames` it answers to. The daemon
1526
+ * binds an HTTP listener per unique `port` on 0.0.0.0 (the bridge gateway
1527
+ * is reachable from every service container), and `spectest-resolver`
1528
+ * answers DNS for those hostnames with the bridge gateway IP. Containers
1529
+ * doing `fetch("http://api.stripe.com/v1/charges")` route into the daemon,
1530
+ * which dispatches to the matching fake by Host header.
1531
+ *
1532
+ * Internal state lives in plain JS memory — it forks with the rest of the
1533
+ * snapshot, so per-test forks start from a known baseline and each fork
1534
+ * has its own copy. State is private to the fake; expose it for assertions
1535
+ * via `helpers` functions that tests call as `ctx.fakes.<name>.<fn>(...)`.
1536
+ *
1537
+ * HTTPS works out of the box. Every fake is auto-bound on :443 with a
1538
+ * leaf cert signed by the in-VM root CA (SANs = `hostnames`), and
1539
+ * every service container trusts that CA via bind-mount + system-trust
1540
+ * layer — point your app at `https://api.stripe.com` and it Just Works.
1541
+ * HTTP also stays bound on `port` (default 80) for back-compat.
1542
+ */
1543
+ export interface FakeDefinition<
1544
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1545
+ S = any,
1546
+ H extends Record<string, unknown> = Record<string, never>,
1547
+ > {
1548
+ /** Stable name. Used as the key in `ctx.fakes` and in logs/UI. */
1549
+ name: string;
1550
+ /**
1551
+ * Fully-qualified hostnames the fake answers to (e.g.
1552
+ * `"api.stripe.com"`). Same rules as service `hostnames`: multi-label,
1553
+ * lowercase, no `.internal` suffix, no collisions with services or
1554
+ * other fakes.
1555
+ */
1556
+ hostnames: readonly string[];
1557
+ /** TCP port the fake listens on. Default `80`. */
1558
+ port?: number;
1559
+ /**
1560
+ * Build the fake's initial state. Called once when the project loads.
1561
+ * The returned value lives in daemon memory for the rest of the
1562
+ * environment's life — it survives `bootstrap`, the warm-template
1563
+ * snapshot, and every per-test fork (each fork sees its own copy).
1564
+ */
1565
+ state?: () => S | Promise<S>;
1566
+ /**
1567
+ * HTTP handler. Receives a standard `Request` (Bun-native), the fake's
1568
+ * mutable `state`, and a {@link FakeContext} `ctx` for mutating the
1569
+ * environment at runtime (e.g. `ctx.startService(...)` to provision a
1570
+ * real backing instance, `ctx.dnsName(...)` to name it). Return any
1571
+ * `Response`. Thrown errors surface as 500s. The request URL is the
1572
+ * absolute URL the client used — useful for routing on the path.
1573
+ */
1574
+ handler: (req: Request, state: S, ctx: FakeContext) => Response | Promise<Response>;
1575
+ /**
1576
+ * Build the helpers exposed at `ctx.fakes.<name>` — a record of
1577
+ * **functions** that read or mutate the fake's `state` (received here)
1578
+ * via closure. Called the first time a test touches the fake; result
1579
+ * is cached for the daemon's life. Omit it and tests see `{}`: state
1580
+ * stays private, reachable only through the functions you expose
1581
+ * (e.g. `{ lastCharge(), declineSource(src) }`). Don't expose raw
1582
+ * `state` or use getters — return copies/derived values from functions
1583
+ * instead.
1584
+ *
1585
+ * Every call is tracked in the test timeline: it records a `fake` step
1586
+ * and the return value is tagged so a later `expect(...)` on it nests
1587
+ * under that step in the UI (same provenance as `fetch`/db results).
1588
+ *
1589
+ * Receives the fake's `state` plus a {@link FakeContext} `ctx`, so a
1590
+ * helper can provision/teardown runtime services just like the handler.
1591
+ */
1592
+ helpers?: (args: { name: string; state: S; ctx: FakeContext }) => H | Promise<H>;
1593
+ /**
1594
+ * Internal. Platform secret references this fake needs at *record* time
1595
+ * (set by {@link replayFake}). The daemon reports the union of these to
1596
+ * the control plane, which resolves each via its `SecretResolver` and
1597
+ * pushes the values on the eval path only — they never enter project
1598
+ * files, the config hash, or a cassette. Not part of the authoring
1599
+ * surface; `JSON.stringify` ignores it (fakes never serialize to config).
1600
+ */
1601
+ secretRefs?: readonly string[];
1602
+ }
1603
+
1604
+ /**
1605
+ * Define a fake. `defineFake({ ... })` is a thin wrapper that pins the
1606
+ * generic `S` and `H` so `helpers`/`handler` see the inferred state type
1607
+ * without the caller having to spell it out twice.
1608
+ */
1609
+ export function defineFake<
1610
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1611
+ S = any,
1612
+ H extends Record<string, unknown> = Record<string, never>,
1613
+ >(opts: FakeDefinition<S, H>): FakeDefinition<S, H> {
1614
+ if (!opts.name || opts.name.length === 0) {
1615
+ throw new Error("defineFake: `name` is required");
1616
+ }
1617
+ if (!Array.isArray(opts.hostnames) || opts.hostnames.length === 0) {
1618
+ throw new Error(`defineFake(${opts.name}): at least one hostname is required`);
1619
+ }
1620
+ for (const h of opts.hostnames) {
1621
+ const lower = h.toLowerCase();
1622
+ if (!HOSTNAME_RE.test(lower)) {
1623
+ throw new Error(
1624
+ `defineFake(${opts.name}): invalid hostname ${JSON.stringify(h)} — must be a multi-label DNS name (e.g. "api.stripe.com")`,
1625
+ );
1626
+ }
1627
+ if (lower === "internal" || lower.endsWith(".internal")) {
1628
+ throw new Error(
1629
+ `defineFake(${opts.name}): hostname ${JSON.stringify(h)} ends in reserved ".internal" TLD`,
1630
+ );
1631
+ }
1632
+ }
1633
+ if (typeof opts.handler !== "function") {
1634
+ throw new Error(`defineFake(${opts.name}): \`handler\` is required`);
1635
+ }
1636
+ return opts;
1637
+ }
1638
+
1639
+ /** Map of fake-name -> FakeDefinition, keyed by stable name. `any` for
1640
+ * both generic args (not the bare `FakeDefinition` default of
1641
+ * `<any, Record<string, never>>`) so a concrete fake that ships real
1642
+ * `helpers` — whose `helpers`/`handler` function types would otherwise be
1643
+ * invariant-incompatible with the narrower default — is still assignable.
1644
+ * The precise per-fake helper types are recovered by `FakeHandlesFor<F>`
1645
+ * at use sites. */
1646
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1647
+ export type FakesMap = Record<string, FakeDefinition<any, any>>;
1648
+
1649
+ /** Rewrite a helpers record so each function's result is inspect-wrapped
1650
+ * ({@link Wrapped}) — mirroring the runtime, where `trackFakeHelpers` wraps
1651
+ * every helper return value for assertion provenance. Without this the raw
1652
+ * return type (e.g. `Charge[]`) reaches `expect`, which the `Provenanced`
1653
+ * gate rejects. Handles sync and async helpers; non-function members (and
1654
+ * `void` side-effect helpers) pass through untouched. Mirrors `Tagged<T>` in
1655
+ * `components/k3s.ts`, extended to cover synchronous returns. */
1656
+ type WrappedHelpers<H> = {
1657
+ [K in keyof H]: H[K] extends (...args: infer A) => Promise<infer R>
1658
+ ? (...args: A) => Promise<Wrapped<R>>
1659
+ : H[K] extends (...args: infer A) => infer R
1660
+ ? (...args: A) => [R] extends [void] ? void : Wrapped<R>
1661
+ : H[K];
1662
+ };
1663
+
1664
+ /** Awaited return type of a fake's `helpers` factory (with each result
1665
+ * inspect-wrapped, see {@link WrappedHelpers}), or `{ state: S }` (the
1666
+ * default) when the user didn't ship one. */
1667
+ type FakeHelpersOf<F> = F extends FakeDefinition<infer S, infer H>
1668
+ ? [H] extends [Record<string, never>]
1669
+ ? { state: S }
1670
+ : WrappedHelpers<H>
1671
+ : never;
1672
+
1673
+ /** Per-fake handles derived from a concrete fakes map; what tests see at
1674
+ * `ctx.fakes`. For a concrete map (fakes declared in `defineEnvironment`)
1675
+ * each key is the precise helpers record. When `F` is the loose default
1676
+ * `FakesMap` (no fakes declared, or generic daemon-side code), this
1677
+ * collapses to a permissive record so untyped access still compiles. */
1678
+ export type FakeHandlesFor<F extends FakesMap> = string extends keyof F
1679
+ ? Record<string, Record<string, unknown>>
1680
+ : { [K in keyof F]: FakeHelpersOf<F[K]> };
1681
+
1682
+ /**
1683
+ * A `test(...)` function bound to a concrete services map (and fakes map).
1684
+ * Returned by `defineEnvironment(...).test`; gives tests fully-typed access
1685
+ * to `ctx.svc.<key>` and `ctx.fakes.<key>` without per-call casts.
1686
+ */
1687
+ export interface TypedTest<
1688
+ S extends ServicesMap,
1689
+ F extends FakesMap = FakesMap,
1690
+ > {
1691
+ <T = void>(name: string, fn: TestFn<T, undefined, S, F>): TestCase<T, S, F>;
1692
+ <T = void, P = undefined>(
1693
+ name: string,
1694
+ opts: TestOpts<P, S, F>,
1695
+ fn: TestFn<T, P, S, F>,
1696
+ ): TestCase<T, S, F>;
1697
+ }
1698
+
1699
+ // ──────────────────────────────────────────────────────────────────────────
1700
+ // Project (the unified default export)
1701
+ // ──────────────────────────────────────────────────────────────────────────
1702
+
1703
+ /**
1704
+ * A complete project definition: an environment, an optional one-shot
1705
+ * setup hook, and an optional test suite. `spectest/index.ts`
1706
+ * default-exports one of these via `env.project([...tests])` or
1707
+ * `env.project({ setup, tests })`.
1708
+ */
1709
+ export interface Project<
1710
+ S extends ServicesMap = ServicesMap,
1711
+ F extends FakesMap = FakesMap,
1712
+ > {
1713
+ environment: EnvironmentConfig<S>;
1714
+ /**
1715
+ * Fake servers hosted in the harness (see {@link defineFake}).
1716
+ * Keyed by stable fake name; the key becomes the slot in
1717
+ * `ctx.fakes.<key>` from test code. Populated from the `fakes` declared
1718
+ * in `defineEnvironment(...)`.
1719
+ */
1720
+ fakes?: F;
1721
+ /**
1722
+ * Project-level setup. Runs once, after every service is Ready and
1723
+ * its per-service `setup` has completed, before the warm-template
1724
+ * snapshot. Use this for state that's part of "the environment as
1725
+ * the tests expect to find it" — seed data in a database, an initial
1726
+ * Deployment in k3s, etc. Like service-level setup, the result is
1727
+ * captured by every snapshot taken from that point, so warm restore
1728
+ * and per-test forks inherit it without re-running.
1729
+ *
1730
+ * The ctx here is a slimmer cousin of TestContext: no recorder, no
1731
+ * timeout, no browser/terminal — setup is not a test and doesn't
1732
+ * appear in the timeline.
1733
+ */
1734
+ setup?: ProjectSetupFn<S, F>;
1735
+ tests?: TestSuite<S, F>;
1736
+ }
1737
+
1738
+ /**
1739
+ * Context handed to the project-level `setup` hook: the full
1740
+ * {@link SpectestContext}, minus only what a timeline gives a test
1741
+ * (testName, parent, browser/mobile/terminal). Everything a test can do
1742
+ * to the environment — exec, fetch, `svc`/`fakes` helpers, `poll`,
1743
+ * `dnsName`, `certificate`, `startService`, and project-file access via
1744
+ * `projectRoot`/`readProjectFile` — is available here too, and whatever it
1745
+ * produces is captured into the warm-template snapshot, so every test
1746
+ * inherits it without re-running.
1747
+ */
1748
+ export interface ProjectSetupContext<
1749
+ S extends ServicesMap = ServicesMap,
1750
+ F extends FakesMap = FakesMap,
1751
+ > extends SpectestContext<S, F> {}
1752
+
1753
+ export type ProjectSetupFn<
1754
+ S extends ServicesMap = ServicesMap,
1755
+ F extends FakesMap = FakesMap,
1756
+ > = (ctx: ProjectSetupContext<S, F>) => void | Promise<void>;
1757
+
1758
+ /**
1759
+ * A defined environment. Returned by `defineEnvironment(...)` and used to
1760
+ * (a) build typed tests against this environment's services and (b)
1761
+ * bundle those tests into the project's default export.
1762
+ *
1763
+ * ```ts
1764
+ * const env = defineEnvironment({
1765
+ * name: "todos",
1766
+ * services: {
1767
+ * db: postgres({ database: "todos", user: "todos", password: "todos" }),
1768
+ * },
1769
+ * });
1770
+ *
1771
+ * const createTodo = env.test("create todo", async (ctx) => {
1772
+ * // ctx.svc.db.client is the Bun SQL pool (the helper postgres ships).
1773
+ * await ctx.svc.db.client`SELECT 1`;
1774
+ * return { id: 1 };
1775
+ * });
1776
+ *
1777
+ * const markDone = env.test(
1778
+ * "mark done",
1779
+ * { dependsOn: createTodo },
1780
+ * async (ctx) => {
1781
+ * // ctx.parent is { id: number }
1782
+ * await ctx.svc.db.client`UPDATE todos SET done = TRUE WHERE id = ${ctx.parent.id}`;
1783
+ * },
1784
+ * );
1785
+ *
1786
+ * export default env.project([createTodo, markDone]);
1787
+ * ```
1788
+ */
1789
+ export interface ProjectOpts<
1790
+ S extends ServicesMap = ServicesMap,
1791
+ F extends FakesMap = FakesMap,
1792
+ > {
1793
+ /** Optional project-level setup. See `Project.setup`. */
1794
+ setup?: ProjectSetupFn<S, F>;
1795
+ /** Test cases for this project's suite. */
1796
+ tests?: TestCase<unknown, S, F>[];
1797
+ }
1798
+
1799
+ /**
1800
+ * Input to {@link defineEnvironment}: the environment config plus an
1801
+ * optional `fakes` map. `fakes` is declared here (rather than on
1802
+ * `project(...)`) so the fakes' types are bound when `env.test(...)`
1803
+ * creates a test — that's what makes `ctx.fakes.<key>` strongly typed.
1804
+ * `fakes` is stripped from `config` before it's stored/serialised, so the
1805
+ * wire `EnvironmentConfig` the Rust control plane sees never carries it.
1806
+ *
1807
+ * Unlike the wire {@link EnvironmentConfig}, `services` entries here may
1808
+ * be {@link ServiceGroup}s — they're expanded to plain services (primary
1809
+ * at the group's key, other parts at `<key>-<part>`) before validation.
1810
+ */
1811
+ export interface EnvironmentInput<
1812
+ SI extends InputServicesMap,
1813
+ F extends FakesMap = FakesMap,
1814
+ > {
1815
+ /** Human-friendly name for the environment, e.g. "my-app". */
1816
+ name: string;
1817
+ /** Services and/or service groups, keyed by name. See
1818
+ * {@link EnvironmentConfig.services} and {@link ServiceGroup}. */
1819
+ services: SI;
1820
+ /** Sandbox timeout in seconds (default 1h). */
1821
+ timeoutSecs?: number;
1822
+ /** Fake servers — see {@link defineFake}. Keyed by stable name; the key
1823
+ * shows up as `ctx.fakes.<key>` in tests, typed as that fake's helpers
1824
+ * record. */
1825
+ fakes?: F;
1826
+ }
1827
+
1828
+ export interface DefinedEnvironment<
1829
+ S extends ServicesMap,
1830
+ F extends FakesMap = FakesMap,
1831
+ > {
1832
+ /** The validated environment config. Plain data, JSON-serialisable —
1833
+ * the in-VM daemon ships this to the control plane on `/load`. */
1834
+ readonly config: EnvironmentConfig<S>;
1835
+ /** Define a test against this environment. `ctx.svc.<key>` and
1836
+ * `ctx.fakes.<key>` are strongly typed against the services and fakes
1837
+ * maps. */
1838
+ readonly test: TypedTest<S, F>;
1839
+ /** Bundle this environment with a test suite into the project default
1840
+ * export. Pass tests as a plain array for the common case, or an
1841
+ * options bag to attach project-level `setup`. (Fakes are declared on
1842
+ * `defineEnvironment`, not here.) */
1843
+ project(tests?: TestCase<unknown, S, F>[]): Project<S, F>;
1844
+ project(opts: ProjectOpts<S, F>): Project<S, F>;
1845
+ }
1846
+
1847
+ /**
1848
+ * The `ctx` type for an environment, for typing shared test helpers without
1849
+ * `any`. Instantiate with the environment from `defineEnvironment`:
1850
+ *
1851
+ * ```ts
1852
+ * const env = defineEnvironment({ ... });
1853
+ * export type AppCtx = Ctx<typeof env>;
1854
+ *
1855
+ * // A helper reaching into ctx.svc / ctx.fakes stays fully typed:
1856
+ * async function runJob(ctx: AppCtx) {
1857
+ * await ctx.svc.db.client`SELECT 1`;
1858
+ * }
1859
+ * ```
1860
+ *
1861
+ * This is the same `ctx` an `env.test(...)` callback receives. The parent
1862
+ * return type is left as `unknown` (helpers rarely touch `ctx.parent` — read
1863
+ * it in the test body and pass the value in). Prefer this over `ctx: any`:
1864
+ * an `any`-typed ctx also defeats the `expect(...)` overloads, silently
1865
+ * resolving `expect(value)` to the `expect(locator)` overload so value
1866
+ * matchers like `.toBe(...)` disappear.
1867
+ */
1868
+ export type Ctx<E> =
1869
+ E extends DefinedEnvironment<infer S, infer F>
1870
+ ? TestContext<unknown, S, F>
1871
+ : never;
1872
+
1873
+ /**
1874
+ * The `ctx` type a `setup` hook receives for an environment — the
1875
+ * {@link Ctx} counterpart for bring-up code. Use it to type the deploy /
1876
+ * seed helpers a project's `setup` calls, instead of hand-rolling a
1877
+ * structural `{ exec, certificate }` interface:
1878
+ *
1879
+ * ```ts
1880
+ * const env = defineEnvironment({ ... });
1881
+ * export type AppSetupCtx = SetupCtx<typeof env>;
1882
+ *
1883
+ * async function deployPlatform(ctx: AppSetupCtx) {
1884
+ * const manifests = await ctx.readProjectFile("deploy/platform.yaml");
1885
+ * const { cert, key } = await ctx.certificate(["*.apps.test"]);
1886
+ * await ctx.svc.k8s.apply(manifests);
1887
+ * }
1888
+ * ```
1889
+ *
1890
+ * A service-level `setup`/`helpers` hook gets the same capabilities plus
1891
+ * its own `name`/`helpers` — see {@link ServiceSetupContext}. Since
1892
+ * {@link ProjectSetupContext} is a {@link SpectestContext}, a helper typed
1893
+ * with `SetupCtx` also accepts a service `setup` ctx, so one function can
1894
+ * serve both.
1895
+ */
1896
+ export type SetupCtx<E> =
1897
+ E extends DefinedEnvironment<infer S, infer F>
1898
+ ? ProjectSetupContext<S, F>
1899
+ : never;
1900
+
1901
+ /**
1902
+ * Define an environment and get back a builder you can hang tests off.
1903
+ * The builder's `.test(...)` returns test cases typed against the
1904
+ * environment's services (and any declared `fakes`), and `.project([...])`
1905
+ * produces the file's default export.
1906
+ */
1907
+ export function defineEnvironment<
1908
+ SI extends InputServicesMap,
1909
+ F extends FakesMap = FakesMap,
1910
+ >(input: EnvironmentInput<SI, F>): DefinedEnvironment<ExpandServices<SI>, F> {
1911
+ type S = ExpandServices<SI>;
1912
+ // Split fakes off the wire config and expand service groups; only
1913
+ // { name, services, timeoutSecs } — with plain, fully-expanded services —
1914
+ // is stored as `config` and shipped to the control plane.
1915
+ const { fakes, services: rawServices, ...rest } = input;
1916
+ const config: EnvironmentConfig<S> = {
1917
+ ...rest,
1918
+ services: expandServiceGroups(rawServices) as S,
1919
+ };
1920
+ validateEnvironmentConfig(config);
1921
+ if (fakes) validateFakes(config, fakes);
1922
+
1923
+ // Every test created via this env's `.test(...)` is registered here. A
1924
+ // split-layout project keeps its tests in `spectest/tests/**` — each file
1925
+ // imports this `env` (for types + `dependsOn` refs) and calls `env.test`,
1926
+ // which appends to `registry`. The daemon imports those files and then
1927
+ // reads the suite back off the default-exported Project's lazy `tests`
1928
+ // getter (installed in `project()` below). Keeping the env definition
1929
+ // itself free of test bodies is what lets the warm-template cache key
1930
+ // ignore test edits — see `project_content_hash` in the control plane.
1931
+ const registry: TestCase<unknown, S, F>[] = [];
1932
+ const test = ((
1933
+ name: string,
1934
+ optsOrFn: TestOpts<unknown, S, F> | TestFn<unknown, undefined, S, F>,
1935
+ maybeFn?: TestFn<unknown, unknown, S, F>,
1936
+ ): TestCase<unknown, S, F> => {
1937
+ const tc = (
1938
+ buildTestCase as unknown as (
1939
+ n: string,
1940
+ o: typeof optsOrFn,
1941
+ f?: typeof maybeFn,
1942
+ ) => TestCase<unknown, S, F>
1943
+ )(name, optsOrFn, maybeFn);
1944
+ registry.push(tc);
1945
+ return tc;
1946
+ }) as unknown as TypedTest<S, F>;
1947
+
1948
+ function project(
1949
+ arg?: TestCase<unknown, S, F>[] | ProjectOpts<S, F>,
1950
+ ): Project<S, F> {
1951
+ const opts: ProjectOpts<S, F> = Array.isArray(arg)
1952
+ ? { tests: arg }
1953
+ : (arg ?? {});
1954
+ const proj: Project<S, F> = { environment: config };
1955
+ if (opts.setup) proj.setup = opts.setup;
1956
+ if (fakes) proj.fakes = fakes;
1957
+ if (opts.tests && opts.tests.length > 0) {
1958
+ // Explicit suite (single-file / legacy layout): the tests are listed
1959
+ // right here, so freeze them now.
1960
+ proj.tests = validateSuite({ tests: opts.tests });
1961
+ } else {
1962
+ // Split layout: tests are defined in separate files and collected from
1963
+ // the registry as those files are imported. Expose them lazily so the
1964
+ // daemon sees whatever has registered by the time it reads `.tests`
1965
+ // (i.e. after it has imported `spectest/tests/**` on `/load-tests`).
1966
+ Object.defineProperty(proj, "tests", {
1967
+ enumerable: true,
1968
+ configurable: true,
1969
+ get(): TestSuite<S, F> | undefined {
1970
+ return registry.length > 0
1971
+ ? validateSuite({ tests: [...registry] })
1972
+ : undefined;
1973
+ },
1974
+ });
1975
+ }
1976
+ return proj;
1977
+ }
1978
+ return {
1979
+ config,
1980
+ test,
1981
+ project,
1982
+ };
1983
+ }
1984
+
1985
+ /**
1986
+ * Cross-check fakes against the environment's services: no duplicate
1987
+ * hostnames, no collisions with service names or service hostnames, and
1988
+ * each fake's name is unique (the user passed a map, so JS guarantees
1989
+ * the second condition — but we re-check defensively for the case where
1990
+ * an object literal is built programmatically).
1991
+ */
1992
+ function validateFakes(env: EnvironmentConfig, fakes: FakesMap): void {
1993
+ const claimedByService = new Map<string, string>();
1994
+ for (const [svcName, svc] of Object.entries(env.services)) {
1995
+ claimedByService.set(svcName.toLowerCase(), svcName);
1996
+ claimedByService.set(`${svcName.toLowerCase()}.internal`, svcName);
1997
+ for (const h of svc.hostnames ?? []) {
1998
+ claimedByService.set(h.toLowerCase(), svcName);
1999
+ }
2000
+ for (const entry of svc.tls ?? []) {
2001
+ claimedByService.set(entry.hostname.toLowerCase(), svcName);
2002
+ }
2003
+ }
2004
+ const claimedByFake = new Map<string, string>();
2005
+ for (const [key, fake] of Object.entries(fakes)) {
2006
+ if (!fake || typeof fake !== "object" || typeof fake.handler !== "function") {
2007
+ throw new Error(
2008
+ `fake ${JSON.stringify(key)} is not a FakeDefinition — pass the result of defineFake({...})`,
2009
+ );
2010
+ }
2011
+ for (const raw of fake.hostnames) {
2012
+ const h = raw.toLowerCase();
2013
+ const owningSvc = claimedByService.get(h);
2014
+ if (owningSvc !== undefined) {
2015
+ throw new Error(
2016
+ `fake ${JSON.stringify(key)} hostname ${JSON.stringify(raw)} collides with service ${JSON.stringify(owningSvc)}`,
2017
+ );
2018
+ }
2019
+ const owningFake = claimedByFake.get(h);
2020
+ if (owningFake !== undefined && owningFake !== key) {
2021
+ throw new Error(
2022
+ `hostname ${JSON.stringify(raw)} is claimed by both fake ${JSON.stringify(owningFake)} and fake ${JSON.stringify(key)}`,
2023
+ );
2024
+ }
2025
+ claimedByFake.set(h, key);
2026
+ }
2027
+ }
2028
+ }
2029
+
2030
+ // `buildTestCase` is the runtime implementation behind every typed
2031
+ // `env.test(...)`. The DefinedEnvironment exposes it cast to TypedTest<S>
2032
+ // so callers see the strongly-typed overloads while the body stays
2033
+ // generic — TestFn is contravariant in `ctx`, so a single implementation
2034
+ // satisfies every TypedTest<S>.
2035
+ function buildTestCase(
2036
+ name: string,
2037
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2038
+ optsOrFn: TestOpts<any> | TestFn<unknown, any>,
2039
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2040
+ maybeFn?: TestFn<unknown, any>,
2041
+ ): TestCase<unknown> {
2042
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2043
+ const [opts, fn]: [TestOpts<any>, TestFn<unknown, any>] =
2044
+ typeof optsOrFn === "function" ? [{}, optsOrFn] : [optsOrFn, maybeFn!];
2045
+ if (typeof fn !== "function") {
2046
+ throw new TypeError(
2047
+ `test(${JSON.stringify(name)}): missing test function`,
2048
+ );
2049
+ }
2050
+ return {
2051
+ id: slugify(name),
2052
+ name,
2053
+ dependsOn: opts.dependsOn,
2054
+ timeoutMs: opts.timeoutMs,
2055
+ run: fn,
2056
+ };
2057
+ }
2058
+
2059
+ function validateSuite<
2060
+ S extends ServicesMap,
2061
+ F extends FakesMap,
2062
+ >(suite: TestSuite<S, F>): TestSuite<S, F> {
2063
+ const seenIds = new Map<string, string>();
2064
+ for (const t of suite.tests) {
2065
+ const prior = seenIds.get(t.id);
2066
+ if (prior !== undefined) {
2067
+ throw new Error(
2068
+ `duplicate test id "${t.id}" (from ${JSON.stringify(
2069
+ prior,
2070
+ )} and ${JSON.stringify(t.name)}) — rename one`,
2071
+ );
2072
+ }
2073
+ seenIds.set(t.id, t.name);
2074
+ }
2075
+ // Validate that each dependsOn ref is in the suite. Catches typos /
2076
+ // imports forgotten in the tests array.
2077
+ for (const t of suite.tests) {
2078
+ if (t.dependsOn && !suite.tests.includes(t.dependsOn)) {
2079
+ throw new Error(
2080
+ `test "${t.name}" depends on "${t.dependsOn.name}" which is not in the suite`,
2081
+ );
2082
+ }
2083
+ }
2084
+ return suite;
2085
+ }
2086
+
2087
+ function slugify(name: string): string {
2088
+ const slug = name
2089
+ .toLowerCase()
2090
+ .replace(/[^a-z0-9]+/g, "-")
2091
+ .replace(/^-+|-+$/g, "");
2092
+ if (!slug) {
2093
+ throw new Error(`cannot derive id from test name ${JSON.stringify(name)}`);
2094
+ }
2095
+ return slug;
2096
+ }
2097
+
2098
+ // ──────────────────────────────────────────────────────────────────────────
2099
+ // Assertions
2100
+ // ──────────────────────────────────────────────────────────────────────────
2101
+
2102
+ export class ExpectationError extends Error {
2103
+ constructor(message: string) {
2104
+ super(message);
2105
+ this.name = "ExpectationError";
2106
+ }
2107
+ }
2108
+
2109
+ interface Matchers {
2110
+ toBe(expected: unknown): void;
2111
+ toEqual(expected: unknown): void;
2112
+ toBeTruthy(): void;
2113
+ toBeFalsy(): void;
2114
+ toBeGreaterThan(n: number): void;
2115
+ toBeLessThan(n: number): void;
2116
+ toBeGreaterThanOrEqual(n: number): void;
2117
+ toBeLessThanOrEqual(n: number): void;
2118
+ toContain(expected: unknown): void;
2119
+ toMatch(re: RegExp): void;
2120
+ toHaveLength(n: number): void;
2121
+ }
2122
+
2123
+ export interface Expectation extends Matchers {
2124
+ not: Matchers;
2125
+ }
2126
+
2127
+ /**
2128
+ * Auto-retrying web-first assertions for a {@link Locator} — Playwright's
2129
+ * `expect(locator)` matchers. Each polls the element until it passes or a
2130
+ * deadline elapses (default 5 s, `{ timeout }` overrides) and records an
2131
+ * assertion event just like a value `expect`. `await` them — they are async.
2132
+ */
2133
+ export interface LocatorMatchers {
2134
+ /** The element is present and visible. */
2135
+ toBeVisible(opts?: { timeout?: number }): Promise<void>;
2136
+ /** The element is absent or hidden. */
2137
+ toBeHidden(opts?: { timeout?: number }): Promise<void>;
2138
+ /** The element's (trimmed) text equals `expected` (or matches a RegExp). */
2139
+ toHaveText(expected: string | RegExp, opts?: { timeout?: number }): Promise<void>;
2140
+ /** The element's text contains `expected`. */
2141
+ toContainText(expected: string, opts?: { timeout?: number }): Promise<void>;
2142
+ /** The input's value equals `expected` (or matches a RegExp). */
2143
+ toHaveValue(expected: string | RegExp, opts?: { timeout?: number }): Promise<void>;
2144
+ /** The locator resolves to exactly `expected` elements. */
2145
+ toHaveCount(expected: number, opts?: { timeout?: number }): Promise<void>;
2146
+ toBeEnabled(opts?: { timeout?: number }): Promise<void>;
2147
+ toBeDisabled(opts?: { timeout?: number }): Promise<void>;
2148
+ toBeChecked(opts?: { timeout?: number }): Promise<void>;
2149
+ }
2150
+
2151
+ export interface LocatorAssertion extends LocatorMatchers {
2152
+ /** Negate every matcher (retries until the negated condition holds). */
2153
+ not: LocatorMatchers;
2154
+ }
2155
+
2156
+ /**
2157
+ * Auto-retrying assertions for a browser/mobile **session** — Playwright's
2158
+ * `expect(page)` matchers. Like the locator ones, they poll until the
2159
+ * condition holds or the deadline elapses (default 5 s) and record one
2160
+ * assertion under a settled browser step.
2161
+ */
2162
+ export interface BrowserMatchers {
2163
+ /**
2164
+ * The page's URL matches `expected` — a glob string (`*` within a path
2165
+ * segment, `**` across `/`), a RegExp, or a predicate over the parsed URL.
2166
+ * The settling twin of {@link Browser.waitForURL}: use `waitForURL` when
2167
+ * you want the matched URL back, this when you only mean to assert.
2168
+ */
2169
+ toHaveURL(expected: UrlPattern, opts?: { timeout?: number }): Promise<void>;
2170
+ }
2171
+
2172
+ export interface BrowserAssertion extends BrowserMatchers {
2173
+ /** Negate every matcher (retries until the negated condition holds). */
2174
+ not: BrowserMatchers;
2175
+ }
2176
+
2177
+ // `expect(locator)`/`expect(browser)` return the async web-first matchers;
2178
+ // `expect(value)` the synchronous value matchers. The two object overloads are
2179
+ // listed first so they win over `Provenanced` (neither has `unwrap`); a
2180
+ // Locator and a Browser are structurally disjoint, so their order is free.
2181
+ export function expect(actual: Locator, message?: string): LocatorAssertion;
2182
+ export function expect(actual: Browser, message?: string): BrowserAssertion;
2183
+ export function expect(actual: Provenanced, message?: string): Expectation;
2184
+ export function expect(
2185
+ actual: Provenanced | Locator | Browser,
2186
+ message?: string,
2187
+ ): Expectation | LocatorAssertion | BrowserAssertion {
2188
+ if (isLocator(actual)) return buildLocatorAssertion(actual, message);
2189
+ if (isBrowserSession(actual)) return buildBrowserAssertion(actual, message);
2190
+ return expectValue(actual as Provenanced, message);
2191
+ }
2192
+
2193
+ function expectValue(actual: Provenanced, message?: string): Expectation {
2194
+ // The first parameter is typed to the {@link Provenanced} family so a raw
2195
+ // value (`expect(res.status === 200)`, `expect(2 + 2)`) is a *compile error* —
2196
+ // every assertion that reaches the timeline this way carries a provenance link
2197
+ // back to the op that produced it. Assert on a genuinely raw value with
2198
+ // `expectRaw(value, message)` instead.
2199
+ //
2200
+ // `message` is an **optional** human label for the assertion. The UI already
2201
+ // renders the target, matcher, and expected value, so a message that just
2202
+ // restates them is noise — supply one *only* when the check's intent isn't
2203
+ // obvious from those alone (e.g.
2204
+ // `expect(res.status, "blocked once the rate limit trips").toBe(429)`). When
2205
+ // present it leads the assertion's summary, the same way `expectRaw`'s does.
2206
+ //
2207
+ // A `null`/`undefined` read off a wrapped op result reaches here untagged
2208
+ // (a symbol can't ride on nullish). `adoptNullishTag` recovers the tag from
2209
+ // the proxy's most-recent nullish-leaf note and mints a tagged holder, so
2210
+ // `expect(dep.status.readyReplicas).toBeFalsy()` nests under its op just like
2211
+ // a non-nullish read. Done once here (not in `buildMatchers`) so the `.not`
2212
+ // re-pass reuses the same tagged holder instead of re-consuming the note.
2213
+ return buildMatchers(adoptNullishTag(actual), false, message);
2214
+ }
2215
+
2216
+ // ── expect(locator): auto-retrying web-first matchers ─────────────────────
2217
+
2218
+ /** Poll interval for locator matchers. */
2219
+ const LOCATOR_POLL_MS = 50;
2220
+
2221
+ function buildLocatorAssertion(loc: Locator, message?: string): LocatorAssertion {
2222
+ return Object.assign(buildLocatorMatchers(loc, false, message), {
2223
+ not: buildLocatorMatchers(loc, true, message),
2224
+ });
2225
+ }
2226
+
2227
+ function buildLocatorMatchers(
2228
+ loc: Locator,
2229
+ negated: boolean,
2230
+ message?: string,
2231
+ ): LocatorMatchers {
2232
+ const probe = getLocatorProbe(loc);
2233
+
2234
+ // Poll `check` (a silent, non-recorded read) until the desired condition
2235
+ // holds or the deadline elapses, then emit ONE settled browser step (the
2236
+ // locator label + replay seek point) and record ONE assertion nested under
2237
+ // it via `sourceSeq` — so a web-first `expect(locator)` assertion carries
2238
+ // the same provenance a value assertion does (`expect(await loc.isVisible())`
2239
+ // renders identically). Without the anchor step these assertions floated as
2240
+ // disconnected top-level "value ✓" rows with no element and no replay seek.
2241
+ // `check` returns whether the base condition is satisfied plus the observed
2242
+ // value for the timeline.
2243
+ const run = async (
2244
+ matcher: string,
2245
+ timeout: number | undefined,
2246
+ check: () => Promise<{ satisfied: boolean; actual: unknown }>,
2247
+ describe: (actual: unknown) => string,
2248
+ expected?: unknown,
2249
+ ): Promise<void> => {
2250
+ const started = Date.now();
2251
+ const deadline = started + (timeout ?? DEFAULT_ACTION_TIMEOUT_MS);
2252
+ let actual: unknown;
2253
+ for (;;) {
2254
+ let satisfied: boolean;
2255
+ try {
2256
+ const r = await check();
2257
+ satisfied = r.satisfied;
2258
+ actual = r.actual;
2259
+ } catch (err) {
2260
+ if (Date.now() < deadline) {
2261
+ await new Promise((r) => setTimeout(r, LOCATOR_POLL_MS));
2262
+ continue;
2263
+ }
2264
+ satisfied = false;
2265
+ actual = `<error: ${(err as Error)?.message ?? String(err)}>`;
2266
+ }
2267
+ const passed = satisfied !== negated;
2268
+ if (passed) {
2269
+ const sourceSeq = await probe.settle(matcher, Date.now() - started);
2270
+ recordAssertion({
2271
+ matcher,
2272
+ negated,
2273
+ passed: true,
2274
+ actual: safeSerialize(actual),
2275
+ expected: expected === undefined ? undefined : safeSerialize(expected),
2276
+ message,
2277
+ sourceSeq,
2278
+ });
2279
+ return;
2280
+ }
2281
+ if (Date.now() >= deadline) {
2282
+ const msg = describe(actual);
2283
+ const sourceSeq = await probe.settle(matcher, Date.now() - started, msg);
2284
+ recordAssertion({
2285
+ matcher,
2286
+ negated,
2287
+ passed: false,
2288
+ actual: safeSerialize(actual),
2289
+ expected: expected === undefined ? undefined : safeSerialize(expected),
2290
+ error: msg,
2291
+ message,
2292
+ sourceSeq,
2293
+ });
2294
+ throw new ExpectationError(msg);
2295
+ }
2296
+ await new Promise((r) => setTimeout(r, LOCATOR_POLL_MS));
2297
+ }
2298
+ };
2299
+
2300
+ const not = negated ? " not" : "";
2301
+ const matchesText = (v: string, expected: string | RegExp): boolean =>
2302
+ expected instanceof RegExp ? expected.test(v) : v === expected;
2303
+
2304
+ return {
2305
+ toBeVisible: (opts) =>
2306
+ run(
2307
+ "toBeVisible",
2308
+ opts?.timeout,
2309
+ async () => {
2310
+ const v = await probe.isVisible();
2311
+ return { satisfied: v, actual: v };
2312
+ },
2313
+ () => `expected ${probe.label}${not} to be visible`,
2314
+ ),
2315
+ toBeHidden: (opts) =>
2316
+ run(
2317
+ "toBeHidden",
2318
+ opts?.timeout,
2319
+ async () => {
2320
+ const v = await probe.isVisible();
2321
+ return { satisfied: !v, actual: v };
2322
+ },
2323
+ () => `expected ${probe.label}${not} to be hidden`,
2324
+ ),
2325
+ toHaveText: (expected, opts) =>
2326
+ run(
2327
+ "toHaveText",
2328
+ opts?.timeout,
2329
+ async () => {
2330
+ const t = (await probe.textContent(opts?.timeout)) ?? "";
2331
+ return { satisfied: matchesText(t.trim(), expected), actual: t };
2332
+ },
2333
+ (a) => `expected ${probe.label}${not} to have text ${fmt(expected)}, got ${fmt(a)}`,
2334
+ expected instanceof RegExp ? String(expected) : expected,
2335
+ ),
2336
+ toContainText: (expected, opts) =>
2337
+ run(
2338
+ "toContainText",
2339
+ opts?.timeout,
2340
+ async () => {
2341
+ const t = (await probe.textContent(opts?.timeout)) ?? "";
2342
+ return { satisfied: t.includes(expected), actual: t };
2343
+ },
2344
+ (a) => `expected ${probe.label}${not} to contain text ${fmt(expected)}, got ${fmt(a)}`,
2345
+ expected,
2346
+ ),
2347
+ toHaveValue: (expected, opts) =>
2348
+ run(
2349
+ "toHaveValue",
2350
+ opts?.timeout,
2351
+ async () => {
2352
+ const v = await probe.inputValue(opts?.timeout);
2353
+ return { satisfied: matchesText(v, expected), actual: v };
2354
+ },
2355
+ (a) => `expected ${probe.label}${not} to have value ${fmt(expected)}, got ${fmt(a)}`,
2356
+ expected instanceof RegExp ? String(expected) : expected,
2357
+ ),
2358
+ toHaveCount: (expected, opts) =>
2359
+ run(
2360
+ "toHaveCount",
2361
+ opts?.timeout,
2362
+ async () => {
2363
+ const c = await probe.count();
2364
+ return { satisfied: c === expected, actual: c };
2365
+ },
2366
+ (a) => `expected ${probe.label}${not} to have count ${expected}, got ${fmt(a)}`,
2367
+ expected,
2368
+ ),
2369
+ toBeEnabled: (opts) =>
2370
+ run(
2371
+ "toBeEnabled",
2372
+ opts?.timeout,
2373
+ async () => {
2374
+ const v = await probe.isEnabled(opts?.timeout);
2375
+ return { satisfied: v, actual: v };
2376
+ },
2377
+ () => `expected ${probe.label}${not} to be enabled`,
2378
+ ),
2379
+ toBeDisabled: (opts) =>
2380
+ run(
2381
+ "toBeDisabled",
2382
+ opts?.timeout,
2383
+ async () => {
2384
+ const v = await probe.isEnabled(opts?.timeout);
2385
+ return { satisfied: !v, actual: v };
2386
+ },
2387
+ () => `expected ${probe.label}${not} to be disabled`,
2388
+ ),
2389
+ toBeChecked: (opts) =>
2390
+ run(
2391
+ "toBeChecked",
2392
+ opts?.timeout,
2393
+ async () => {
2394
+ const v = await probe.isChecked(opts?.timeout);
2395
+ return { satisfied: v, actual: v };
2396
+ },
2397
+ () => `expected ${probe.label}${not} to be checked`,
2398
+ ),
2399
+ };
2400
+ }
2401
+
2402
+ // ── expect(browser): auto-retrying session matchers ───────────────────────
2403
+
2404
+ function buildBrowserAssertion(session: unknown, message?: string): BrowserAssertion {
2405
+ return Object.assign(buildBrowserMatchers(session, false, message), {
2406
+ not: buildBrowserMatchers(session, true, message),
2407
+ });
2408
+ }
2409
+
2410
+ function buildBrowserMatchers(
2411
+ session: unknown,
2412
+ negated: boolean,
2413
+ message?: string,
2414
+ ): BrowserMatchers {
2415
+ const probe = getBrowserProbe(session);
2416
+ const not = negated ? " not" : "";
2417
+
2418
+ return {
2419
+ toHaveURL: async (expected, opts) => {
2420
+ const started = Date.now();
2421
+ const deadline = started + (opts?.timeout ?? DEFAULT_ACTION_TIMEOUT_MS);
2422
+ // `probe.url()` is a synchronous unrecorded read, so the poll costs
2423
+ // nothing and emits nothing — one settled step at the end, exactly like
2424
+ // the locator matchers.
2425
+ const label = describeUrlPattern(expected);
2426
+ for (;;) {
2427
+ const actual = probe.url();
2428
+ if (matchesUrl(actual, expected) !== negated) {
2429
+ const sourceSeq = await probe.settle("toHaveURL", Date.now() - started);
2430
+ recordAssertion({
2431
+ matcher: "toHaveURL",
2432
+ negated,
2433
+ passed: true,
2434
+ actual: safeSerialize(actual),
2435
+ expected: label,
2436
+ message,
2437
+ sourceSeq,
2438
+ });
2439
+ return;
2440
+ }
2441
+ if (Date.now() >= deadline) {
2442
+ const msg = `expected page URL${not} to match ${label}, got ${fmt(actual)}`;
2443
+ const sourceSeq = await probe.settle("toHaveURL", Date.now() - started, msg);
2444
+ recordAssertion({
2445
+ matcher: "toHaveURL",
2446
+ negated,
2447
+ passed: false,
2448
+ actual: safeSerialize(actual),
2449
+ expected: label,
2450
+ error: msg,
2451
+ message,
2452
+ sourceSeq,
2453
+ });
2454
+ throw new ExpectationError(msg);
2455
+ }
2456
+ await new Promise((r) => setTimeout(r, LOCATOR_POLL_MS));
2457
+ }
2458
+ },
2459
+ };
2460
+ }
2461
+
2462
+ /**
2463
+ * Assert on a value with **no provenance** — a computed number, a frame read
2464
+ * off a raw `WebSocket` you opened yourself, anything that never flowed from a
2465
+ * recorded op. `message` is required (it's the second argument) and reads as
2466
+ * the natural follow-on to "assert …" (e.g.
2467
+ * `expectRaw(id, "id matches the generated value")`); it renders as the
2468
+ * assertion's label in the CLI/dashboard ("ASSERT <message>") since a raw
2469
+ * assertion has no op to nest under. (`expect`'s own `message` is optional;
2470
+ * here it is mandatory, since the label is the only human-meaningful summary a
2471
+ * raw assertion has.)
2472
+ *
2473
+ * **This is an escape hatch, and reaching for it is almost always a mistake.**
2474
+ * A raw assertion is *deliberately* unlinked: it renders as a disconnected
2475
+ * top-level row with no op above it, so whoever reads the failure can't see the
2476
+ * request, query, or command the value came from. Using it to get past
2477
+ * `expect`'s compile-time provenance gate is an anti-pattern — the gate rejects
2478
+ * a value precisely because its provenance was destroyed on the way in, and
2479
+ * this doesn't restore it, it just accepts the loss.
2480
+ *
2481
+ * Nearly every real use is a *wrapped* value that got flattened by `.unwrap()`,
2482
+ * `String(x)`, `JSON.parse(x)`, `x.length`, or a home-grown coercion helper.
2483
+ * Keep it wrapped instead:
2484
+ *
2485
+ * ```ts
2486
+ * // ✗ flattened, then asserted raw — the link to the op is gone
2487
+ * expectRaw(JSON.parse(res.body.unwrap()).tier, "tier is pro").toBe("pro");
2488
+ * expectRaw(rows.length, "one row").toBe(1);
2489
+ *
2490
+ * // ✓ same checks, still nested under the http / db step
2491
+ * expect(res.body.transform<{ tier: string }>("json", (s) => JSON.parse(s)).tier).toBe("pro");
2492
+ * expect(rows).toHaveLength(1);
2493
+ * ```
2494
+ *
2495
+ * `.transform(label, fn)` carries the source op's tag through a decode,
2496
+ * `toHaveLength` reads a length without severing it, and a nullish leaf read
2497
+ * inline in `expect(...)` (or via `field`) recovers its own tag. If the value
2498
+ * came from a `fetch`/db/exec/browser/fake/kube op at any point, there is a
2499
+ * wrapped way to assert on it — see the `/tests` docs page.
2500
+ */
2501
+ export function expectRaw(actual: unknown, message: string): Expectation {
2502
+ // Force the raw form so no stray tag is read even if a wrapped value is
2503
+ // passed: an `expectRaw` assertion is *deliberately* unlinked, rendered at
2504
+ // top level under its own message rather than nested beneath an op.
2505
+ return buildMatchers(readRaw(actual), false, message);
2506
+ }
2507
+
2508
+ function buildMatchers(wrapped: unknown, negated: boolean, message?: string): Expectation {
2509
+ // If `wrapped` is an inspect-tagged value (from fetch / db / browser),
2510
+ // pull its origin metadata and run matchers against the raw underlying
2511
+ // value. Plain `expect(value)` is unaffected. Tag + raw are read once here
2512
+ // and threaded explicitly into `buildCore`, so `.not` and transforms re-pass
2513
+ // them directly instead of re-reading the wrapper (and re-consuming any
2514
+ // adopted nullish note).
2515
+ return buildCore(readRaw(wrapped), readTag(wrapped), negated, message);
2516
+ }
2517
+
2518
+ /**
2519
+ * The matcher/transform factory, working off an already-unwrapped `actual` and
2520
+ * an explicit `tag`. `pendingError`, when set, marks a transform that failed
2521
+ * upstream: every matcher then records a failed assertion carrying that error
2522
+ * (irrespective of negation) and throws, and further transforms propagate it.
2523
+ */
2524
+ function buildCore(
2525
+ actual: unknown,
2526
+ tag: OpTag | undefined,
2527
+ negated: boolean,
2528
+ message?: string,
2529
+ pendingError?: string,
2530
+ ): Expectation {
2531
+ // Wraps a matcher: it computes the raw condition, the failure message,
2532
+ // records the assertion event, then throws iff the result is a failure.
2533
+ // `expectedFor` lets matchers record their expected value where it
2534
+ // makes sense (toBe / toEqual / toContain / toMatch) while matchers
2535
+ // like toBeTruthy leave it unset.
2536
+ const run = (
2537
+ matcher: string,
2538
+ cond: boolean,
2539
+ msg: string,
2540
+ expectedFor?: unknown,
2541
+ opts?: { actual?: unknown },
2542
+ ): void => {
2543
+ // A failed upstream transform short-circuits every matcher to a failure —
2544
+ // there is no meaningful value to match, and negation can't rescue a value
2545
+ // that never decoded — so we record `pendingError` and throw regardless of
2546
+ // `cond`/`negated`.
2547
+ if (pendingError !== undefined) {
2548
+ recordAssertion({
2549
+ matcher,
2550
+ negated,
2551
+ passed: false,
2552
+ actual: safeSerialize(actual),
2553
+ expected: expectedFor === undefined ? undefined : safeSerialize(expectedFor),
2554
+ error: pendingError,
2555
+ message,
2556
+ sourceSeq: tag?.sourceSeq,
2557
+ path: tag ? [...tag.path] : undefined,
2558
+ });
2559
+ throw new ExpectationError(pendingError);
2560
+ }
2561
+ const passed = cond !== negated;
2562
+ recordAssertion({
2563
+ matcher,
2564
+ negated,
2565
+ passed,
2566
+ actual: safeSerialize(opts && "actual" in opts ? opts.actual : actual),
2567
+ expected: expectedFor === undefined ? undefined : safeSerialize(expectedFor),
2568
+ error: passed ? undefined : msg,
2569
+ message,
2570
+ sourceSeq: tag?.sourceSeq,
2571
+ path: tag ? [...tag.path] : undefined,
2572
+ });
2573
+ if (!passed) throw new ExpectationError(msg);
2574
+ };
2575
+ return {
2576
+ toBe(expected) {
2577
+ const exp = readRaw(expected);
2578
+ run(
2579
+ "toBe",
2580
+ Object.is(actual, exp),
2581
+ `expected ${fmt(actual)}${negated ? " not" : ""} to be ${fmt(exp)}`,
2582
+ exp,
2583
+ );
2584
+ },
2585
+ toEqual(expected) {
2586
+ const exp = readRaw(expected);
2587
+ let equal = true;
2588
+ try {
2589
+ nodeAssert.deepStrictEqual(actual, exp);
2590
+ } catch {
2591
+ equal = false;
2592
+ }
2593
+ run(
2594
+ "toEqual",
2595
+ equal,
2596
+ `expected ${fmt(actual)}${negated ? " not" : ""} to deep-equal ${fmt(exp)}`,
2597
+ exp,
2598
+ );
2599
+ },
2600
+ toBeTruthy() {
2601
+ run(
2602
+ "toBeTruthy",
2603
+ !!actual,
2604
+ `expected ${fmt(actual)}${negated ? " not" : ""} to be truthy`,
2605
+ );
2606
+ },
2607
+ toBeFalsy() {
2608
+ run(
2609
+ "toBeFalsy",
2610
+ !actual,
2611
+ `expected ${fmt(actual)}${negated ? " not" : ""} to be falsy`,
2612
+ );
2613
+ },
2614
+ toBeGreaterThan(n) {
2615
+ run(
2616
+ "toBeGreaterThan",
2617
+ typeof actual === "number" && actual > n,
2618
+ `expected ${fmt(actual)}${negated ? " not" : ""} to be > ${n}`,
2619
+ n,
2620
+ );
2621
+ },
2622
+ toBeLessThan(n) {
2623
+ run(
2624
+ "toBeLessThan",
2625
+ typeof actual === "number" && actual < n,
2626
+ `expected ${fmt(actual)}${negated ? " not" : ""} to be < ${n}`,
2627
+ n,
2628
+ );
2629
+ },
2630
+ toBeGreaterThanOrEqual(n) {
2631
+ run(
2632
+ "toBeGreaterThanOrEqual",
2633
+ typeof actual === "number" && actual >= n,
2634
+ `expected ${fmt(actual)}${negated ? " not" : ""} to be >= ${n}`,
2635
+ n,
2636
+ );
2637
+ },
2638
+ toBeLessThanOrEqual(n) {
2639
+ run(
2640
+ "toBeLessThanOrEqual",
2641
+ typeof actual === "number" && actual <= n,
2642
+ `expected ${fmt(actual)}${negated ? " not" : ""} to be <= ${n}`,
2643
+ n,
2644
+ );
2645
+ },
2646
+ toContain(expected) {
2647
+ const exp = readRaw(expected);
2648
+ let contained = false;
2649
+ if (typeof actual === "string" && typeof exp === "string") {
2650
+ contained = actual.includes(exp);
2651
+ } else if (Array.isArray(actual)) {
2652
+ contained = actual.some((v) => {
2653
+ try {
2654
+ nodeAssert.deepStrictEqual(v, exp);
2655
+ return true;
2656
+ } catch {
2657
+ return false;
2658
+ }
2659
+ });
2660
+ }
2661
+ run(
2662
+ "toContain",
2663
+ contained,
2664
+ `expected ${fmt(actual)}${negated ? " not" : ""} to contain ${fmt(exp)}`,
2665
+ exp,
2666
+ );
2667
+ },
2668
+ toMatch(re) {
2669
+ run(
2670
+ "toMatch",
2671
+ typeof actual === "string" && re.test(actual),
2672
+ `expected ${fmt(actual)}${negated ? " not" : ""} to match ${re}`,
2673
+ String(re),
2674
+ );
2675
+ },
2676
+ toHaveLength(n) {
2677
+ // Provenance-preserving count assertion. A wrapped array's `.length`
2678
+ // is deliberately raw (so `rows.length === 1` works), which means
2679
+ // `expect(rows.length)` can't link back to the originating op —
2680
+ // pass the container itself instead: `expect(rows).toHaveLength(1)`
2681
+ // keeps the tag, and we read the length off the raw value here.
2682
+ const len =
2683
+ typeof actual === "string" || Array.isArray(actual)
2684
+ ? actual.length
2685
+ : actual !== null &&
2686
+ typeof actual === "object" &&
2687
+ typeof (actual as { length?: unknown }).length === "number"
2688
+ ? ((actual as { length: number }).length as number)
2689
+ : undefined;
2690
+ // The provenance `path` stays the container's own path — `.length` is
2691
+ // the matcher's internal read, not a property access the author wrote,
2692
+ // so it doesn't belong in the path (recording it produced a redundant
2693
+ // "length toHaveLength N" in the UI, since the matcher name already says
2694
+ // "length"). `actual` is still the length number: that's what's worth
2695
+ // showing on failure, and the `toHaveLength` matcher disambiguates it.
2696
+ run(
2697
+ "toHaveLength",
2698
+ len === n,
2699
+ `expected ${fmt(actual)}${negated ? " not" : ""} to have length ${n}` +
2700
+ (len === undefined ? " (value has no length)" : ` (got ${len})`),
2701
+ n,
2702
+ { actual: len },
2703
+ );
2704
+ },
2705
+ get not(): Matchers {
2706
+ // Re-pass the already-unwrapped value, tag and message so the tag and raw
2707
+ // label are preserved for the negated branch's AssertionEvent.
2708
+ return buildCore(actual, tag, !negated, message, pendingError);
2709
+ },
2710
+ } as Expectation;
2711
+ }
2712
+
2713
+ function fmt(v: unknown): string {
2714
+ if (typeof v === "string") return JSON.stringify(v);
2715
+ if (typeof v === "bigint") return `${v}n`;
2716
+ if (v === undefined) return "undefined";
2717
+ try {
2718
+ return JSON.stringify(v);
2719
+ } catch {
2720
+ return String(v);
2721
+ }
2722
+ }
2723
+
2724
+ /** `node:assert/strict` re-exported for users who prefer Node's built-in API. */
2725
+ export const assert = nodeAssert;