@specific.dev/spectest 0.26.0 → 0.27.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 (74) hide show
  1. package/dist/aws-sigv4.d.ts +42 -0
  2. package/dist/aws-sigv4.js +166 -0
  3. package/dist/browser.d.ts +314 -0
  4. package/dist/browser.js +1320 -0
  5. package/dist/components/email.d.ts +135 -0
  6. package/dist/components/email.js +271 -0
  7. package/dist/components/expo.d.ts +69 -0
  8. package/dist/components/expo.js +125 -0
  9. package/dist/components/index.d.ts +8 -0
  10. package/dist/components/index.js +18 -0
  11. package/dist/components/k3s.d.ts +143 -0
  12. package/dist/components/k3s.js +1067 -0
  13. package/dist/components/postgres.d.ts +93 -0
  14. package/dist/components/postgres.js +58 -0
  15. package/dist/components/replayFake.d.ts +169 -0
  16. package/dist/components/replayFake.js +738 -0
  17. package/dist/components/s3.d.ts +99 -0
  18. package/dist/components/s3.js +81 -0
  19. package/dist/components/supabase.d.ts +197 -0
  20. package/dist/components/supabase.js +1003 -0
  21. package/dist/daemon.d.ts +1 -0
  22. package/dist/daemon.js +4223 -0
  23. package/dist/ids.d.ts +2 -0
  24. package/{src/ids.ts → dist/ids.js} +46 -50
  25. package/dist/index.d.ts +1183 -0
  26. package/dist/index.js +769 -0
  27. package/dist/ingress.d.ts +114 -0
  28. package/dist/ingress.js +210 -0
  29. package/dist/inspect.d.ts +228 -0
  30. package/dist/inspect.js +429 -0
  31. package/dist/locator.d.ts +260 -0
  32. package/dist/locator.js +293 -0
  33. package/dist/mobile.d.ts +71 -0
  34. package/dist/mobile.js +65 -0
  35. package/dist/record-secrets.d.ts +9 -0
  36. package/{src/record-secrets.ts → dist/record-secrets.js} +13 -15
  37. package/dist/recorder.d.ts +516 -0
  38. package/dist/recorder.js +219 -0
  39. package/dist/redis.d.ts +54 -0
  40. package/dist/redis.js +126 -0
  41. package/dist/replay-bundle.d.ts +38 -0
  42. package/{src/replay-bundle.ts → dist/replay-bundle.js} +29 -47
  43. package/dist/resolver.d.ts +1 -0
  44. package/dist/resolver.js +309 -0
  45. package/dist/s3.d.ts +89 -0
  46. package/dist/s3.js +198 -0
  47. package/dist/sql.d.ts +74 -0
  48. package/dist/sql.js +151 -0
  49. package/dist/terminal.d.ts +161 -0
  50. package/dist/terminal.js +538 -0
  51. package/package.json +24 -9
  52. package/src/browser.ts +0 -1819
  53. package/src/components/email.ts +0 -398
  54. package/src/components/expo.ts +0 -167
  55. package/src/components/index.ts +0 -63
  56. package/src/components/k3s.ts +0 -1312
  57. package/src/components/postgres.ts +0 -105
  58. package/src/components/replayFake.ts +0 -848
  59. package/src/components/s3.ts +0 -132
  60. package/src/components/supabase.ts +0 -1299
  61. package/src/daemon.ts +0 -4969
  62. package/src/index.ts +0 -2350
  63. package/src/ingress.ts +0 -288
  64. package/src/inspect.ts +0 -673
  65. package/src/locator.ts +0 -594
  66. package/src/mobile.ts +0 -133
  67. package/src/recorder.ts +0 -817
  68. package/src/redis.ts +0 -202
  69. package/src/resolver.ts +0 -351
  70. package/src/s3.ts +0 -333
  71. package/src/sql.ts +0 -243
  72. package/src/terminal.ts +0 -740
  73. package/src/vendor/rrweb-plugin-console-record.umd.js +0 -521
  74. package/src/vendor/rrweb-record.min.js +0 -5061
@@ -0,0 +1,1183 @@
1
+ import { strict as nodeAssert } from "node:assert";
2
+ export type { Carrier, Wrapped, WrappedObject, WrappedArray, WrappedResponse, Provenanced, SpectestFetch, Unwrap, } from "./inspect.js";
3
+ import type { Provenanced, SpectestFetch, Wrapped } from "./inspect.js";
4
+ export { field } from "./inspect.js";
5
+ export { SQL, type SqlClient, type SqlOptions } from "./sql.js";
6
+ export { RedisClient, type RedisClientLike, type RedisOptions } from "./redis.js";
7
+ export { S3Client, type S3ClientLike, type S3File, type S3ClientOptions } from "./s3.js";
8
+ export type { Browser, BrowserOptions, Keyboard, Mouse, Touchscreen } from "./browser.js";
9
+ import type { Browser, BrowserOptions } from "./browser.js";
10
+ export type { Locator, GetByRoleOptions, GetByTextOptions, FilterOptions, ClickOptions, BoundingBox, } from "./locator.js";
11
+ import type { Locator } from "./locator.js";
12
+ export type { Mobile, MobileApp } from "./mobile.js";
13
+ import type { Mobile, MobileApp } from "./mobile.js";
14
+ export type { Terminal, TerminalOpts, TerminalResult } from "./terminal.js";
15
+ import type { Terminal, TerminalOpts, TerminalResult } from "./terminal.js";
16
+ export { certificate, dnsName, proxy, provides, lowerIngress, isWildcard, SELF_SERVICE_TOKEN, } from "./ingress.js";
17
+ export type { CertificateDecl, DnsDecl, ProxyDecl, IngressDecl, DnsTarget, LoweredIngress, } from "./ingress.js";
18
+ import type { DnsTarget } from "./ingress.js";
19
+ export interface EnvironmentConfig<S extends ServicesMap = ServicesMap> {
20
+ /** Human-friendly name for the environment, e.g. "my-app". */
21
+ name: string;
22
+ /**
23
+ * Services that make up the environment, keyed by service name. The key
24
+ * is the container name, the DNS hostname on `spectest-net`, and the
25
+ * string used in `dependsOn` references.
26
+ */
27
+ services: S;
28
+ /** Sandbox timeout in seconds (default 1h). */
29
+ timeoutSecs?: number;
30
+ }
31
+ /**
32
+ * The shape that ends up in the JSON config the control plane and Rust
33
+ * mirror care about. `ServiceDefinition` is the same thing with an extra
34
+ * non-serialisable `client` factory tacked on; `JSON.stringify` drops
35
+ * functions, so the wire format is `ServiceConfig`.
36
+ */
37
+ export interface ServiceConfig {
38
+ /** Image definition: registry pull or inline build. */
39
+ image: ServiceImage;
40
+ /**
41
+ * Shell command to run (sh -c). Defaults to the image's CMD. NB: this
42
+ * **replaces the image's entrypoint** with `/bin/sh -c` — an
43
+ * init-wrapped image (postgres's `docker-entrypoint.sh`) skips its
44
+ * initialization. Use {@link args} to keep the entrypoint.
45
+ */
46
+ command?: string;
47
+ /**
48
+ * Arguments appended after the image name (`docker run <image>
49
+ * <args…>`) — a CMD override that **keeps the image's entrypoint**.
50
+ * E.g. `args: ["postgres", "-c", "wal_level=logical"]` still runs
51
+ * postgres's `docker-entrypoint.sh` initialization. Mutually
52
+ * exclusive with {@link command}.
53
+ */
54
+ args?: readonly string[];
55
+ env?: Record<string, string>;
56
+ /**
57
+ * Ports the container listens on. Advisory only — surfaced in
58
+ * `spectest list` output. Peer services reach each other by `<service>:<port>`
59
+ * without any port declaration.
60
+ */
61
+ ports?: readonly number[];
62
+ /**
63
+ * Extra DNS names this service answers to inside the environment.
64
+ * Each entry must be a fully-qualified, multi-label hostname (e.g.
65
+ * `api.stripe.com`). Both peer containers (via Docker's embedded DNS)
66
+ * and code on the VM host (via spectest-resolver) resolve these names
67
+ * to the service's IP on `spectest-net`. Useful for mocking external
68
+ * APIs — point an SDK at `http://api.stripe.com` and a service of
69
+ * yours answers directly (no proxy). For HTTPS, use {@link tls}
70
+ * instead — those names terminate TLS in the daemon and reverse-proxy
71
+ * to the service's HTTP port.
72
+ *
73
+ * The `.internal` TLD is reserved: every service automatically
74
+ * answers to `<name>.internal` in addition to its bare `<name>`, and
75
+ * user-supplied hostnames may not end in `.internal`.
76
+ */
77
+ hostnames?: readonly string[];
78
+ /**
79
+ * Expose this service over HTTPS via a TLS-terminating reverse proxy
80
+ * hosted in the spectest-daemon. Each entry maps a fully-qualified
81
+ * hostname to the HTTP port the service listens on inside its
82
+ * container; the daemon binds the hostname on `:443` (SNI-multiplexed,
83
+ * with a leaf cert signed by the in-VM root CA) and on `:80`, and
84
+ * proxies the request to `http://<service>:<port>`. WebSocket
85
+ * upgrades are forwarded.
86
+ *
87
+ * The in-VM root CA is already trusted by Chromium (`ctx.browser()`)
88
+ * and by service-container runtimes (Node, Python, Go, etc.) via
89
+ * the env-var bundle, so `https://<hostname>/` Just Works from
90
+ * tests and from peer services. Hostname rules match {@link hostnames}:
91
+ * multi-label, lowercase, no `.internal` suffix, no collision with
92
+ * services, other service TLS hostnames, or fakes.
93
+ */
94
+ tls?: readonly ServiceTls[];
95
+ /** Bind-mounted volumes for state that survives snapshot/fork. */
96
+ volumes?: readonly VolumeMount[];
97
+ /**
98
+ * Files seeded into the container's filesystem **before it starts**.
99
+ * Each entry's `content` is written to a VM-host staging path and
100
+ * bind-mounted (read-only) at `path` inside the container. Unlike a
101
+ * `setup` hook — which runs after the container is up — `files` is the
102
+ * way to inject configuration a process reads at boot, e.g. k3s's
103
+ * `/etc/rancher/k3s/registries.yaml`, which must exist before
104
+ * `k3s server` starts.
105
+ */
106
+ files?: readonly FileMount[];
107
+ /** Other services (keys in the services map) that must be ready first. */
108
+ dependsOn?: readonly string[];
109
+ readyCheck?: ReadyCheck;
110
+ /** Container workdir override. */
111
+ workdir?: string;
112
+ /**
113
+ * Run the container with `--privileged`. Required by workloads that
114
+ * embed their own container runtime (e.g. k3s) and need full access
115
+ * to the host kernel surface. Off by default.
116
+ */
117
+ privileged?: boolean;
118
+ /**
119
+ * Tmpfs mounts (one `--tmpfs <path>` per entry). Required by some
120
+ * workloads — k3s wants `/run` and `/var/run` writable and
121
+ * non-persistent. Snapshots/forks preserve tmpfs contents along with
122
+ * the rest of process memory.
123
+ */
124
+ tmpfs?: readonly string[];
125
+ /**
126
+ * Cgroup namespace mode — `"host"` or `"private"`. Omit for docker's
127
+ * default. k3s needs `"host"` so its embedded containerd can manage
128
+ * cgroups for the pods it schedules.
129
+ */
130
+ cgroupns?: string;
131
+ }
132
+ /**
133
+ * The slice of the in-VM world a component's `setup` / `helpers` hooks can
134
+ * reach — beyond what the service definition itself declares. Handed to
135
+ * both hooks (see {@link ServiceSetupContext} / {@link ServiceHelpersContext})
136
+ * so components stop hand-rolling `child_process` docker execs and stop
137
+ * hard-coding control-plane paths like `/workspace`.
138
+ */
139
+ export interface ComponentContext {
140
+ /**
141
+ * Absolute path of the extracted project root inside the VM — the
142
+ * directory the user's repo lands in, with `spectest/` directly under
143
+ * it. Use this (never a hard-coded path) to locate project files a
144
+ * component consumes, e.g. `supabase/migrations/**`.
145
+ */
146
+ projectRoot: string;
147
+ /** Read a project file as UTF-8. Relative paths resolve against
148
+ * {@link projectRoot}; absolute paths are read as-is. */
149
+ readProjectFile(path: string): Promise<string>;
150
+ /**
151
+ * Run a command inside a service container (a raw `docker exec` — not
152
+ * recorded on any test timeline, result is plain, not
153
+ * provenance-wrapped). Pass an **array** for exact argv with no shell
154
+ * (`["psql", "-f", "-"]`), or a **string** to run via `sh -lc`.
155
+ * `opts.stdin` is piped to the process — the natural way to feed a SQL
156
+ * file to `psql -f -` or a manifest to `kubectl apply -f -`.
157
+ *
158
+ * Never throws on non-zero exit — inspect `exitCode` yourself.
159
+ */
160
+ exec(service: string, command: string | string[], opts?: ComponentExecOpts): Promise<ExecResult>;
161
+ }
162
+ /** Options for {@link ComponentContext.exec}. */
163
+ export interface ComponentExecOpts {
164
+ /** Piped to the command's stdin, then closed. */
165
+ stdin?: string;
166
+ /** Working directory inside the container (`docker exec -w`). */
167
+ cwd?: string;
168
+ /** Kill the exec after this long. Default 120_000. */
169
+ timeoutMs?: number;
170
+ }
171
+ /** What a service's `setup` hook receives. */
172
+ export interface ServiceSetupContext<H extends Record<string, any> = Record<string, never>> extends ComponentContext {
173
+ /** The service's key in the services map (container + DNS name). */
174
+ name: string;
175
+ /** The record the service's `helpers` factory returned (cached — setup
176
+ * and tests share one instance), or `{}` when it ships none. */
177
+ helpers: H;
178
+ }
179
+ /** What a service's `helpers` factory receives. */
180
+ export interface ServiceHelpersContext extends ComponentContext {
181
+ /** The service's key in the services map (container + DNS name). */
182
+ name: string;
183
+ }
184
+ /**
185
+ * Same shape as `ServiceConfig` plus an optional `helpers` factory that
186
+ * opens a namespace under `ctx.svc.<name>` inside tests. The factory
187
+ * returns a record — each key becomes `ctx.svc.<name>.<key>`. Components
188
+ * like `postgres(...)` use this to expose a pre-wired SQL pool at
189
+ * `ctx.svc.db.client`; nothing stops a component from exposing several
190
+ * helpers under one service (e.g. `client`, `admin`, `truncate()`).
191
+ */
192
+ export interface ServiceDefinition<H extends Record<string, any> = Record<string, never>> extends ServiceConfig {
193
+ /**
194
+ * Build the helpers exposed at `ctx.svc.<name>.<key>`. Called by the
195
+ * daemon the first time a test touches this service; the result is
196
+ * cached for the lifetime of the daemon (it survives snapshot/fork
197
+ * along with the rest of daemon memory). `args.name` is the key the
198
+ * user chose in the services map and matches the in-VM DNS name; the
199
+ * rest of the {@link ServiceHelpersContext} (exec, projectRoot) lets a
200
+ * component reach into its containers without daemon internals.
201
+ */
202
+ helpers?: (args: ServiceHelpersContext) => H | Promise<H>;
203
+ /**
204
+ * One-shot setup after the container's `readyCheck` passes, before
205
+ * dependents start and before any test runs. Awaited in-line with
206
+ * bootstrap, so anything it produces (an ingress controller deployed
207
+ * into k3s, a schema applied to a database) is part of the warm-template
208
+ * snapshot and never re-runs on warm starts.
209
+ *
210
+ * `helpers` is the same record the `helpers` factory returns — building
211
+ * it is cached, so `setup` and tests share one instance. If the service
212
+ * doesn't declare `helpers`, the field is the empty object. The rest of
213
+ * the {@link ServiceSetupContext} carries `exec` (docker exec with
214
+ * stdin) and `projectRoot`/`readProjectFile` for project-file access.
215
+ */
216
+ setup?: (args: ServiceSetupContext<H>) => void | Promise<void>;
217
+ }
218
+ /** A services map — what users pass to `environment.services`. Entries
219
+ * can be plain `ServiceConfig` literals or `ServiceDefinition`s that
220
+ * carry a `helpers` factory (e.g. what `postgres(...)` returns). */
221
+ export type ServicesMap = Record<string, ServiceConfig>;
222
+ /** Awaited return type of a service's `helpers` factory, or `never` if
223
+ * the service doesn't ship one. */
224
+ type HelpersOf<D> = D extends {
225
+ helpers: (...args: any) => infer R;
226
+ } ? Awaited<R> : never;
227
+ /**
228
+ * Per-service handles derived from a concrete services map. Only
229
+ * services that ship a `helpers` factory appear here; `ctx.svc.<name>`
230
+ * is exactly the record the factory returned (e.g. `{ client: SqlClient }`
231
+ * for `postgres(...)`). Services without helpers don't show up at all,
232
+ * so plain `services: { api: { image: ... } }` adds no noise.
233
+ */
234
+ export type ServiceHandlesFor<S extends ServicesMap> = {
235
+ [K in keyof S as HelpersOf<S[K]> extends never ? never : K]: HelpersOf<S[K]>;
236
+ };
237
+ /** Loose, runtime-friendly shape of `ctx.svc` for code that doesn't
238
+ * know the concrete services map (the daemon, generic helpers). The
239
+ * typed `ctx.svc` in test bodies is `ServiceHandlesFor<S>`. */
240
+ export type ServiceHandles = Record<string, Record<string, unknown>>;
241
+ /** Symbol marking a value in the services map as a group to expand.
242
+ * Enumerable-symbol convention (like the ingress `provides` decls): it
243
+ * survives object spread but `JSON.stringify` drops it — not that a group
244
+ * ever reaches the wire; expansion happens before the config exists. */
245
+ declare const SERVICE_GROUP: unique symbol;
246
+ /**
247
+ * Naming context handed to a group's `services` factory. Lets the factory
248
+ * embed *final* DNS names in env vars and config files without knowing the
249
+ * key the user will mount the group under.
250
+ */
251
+ export interface GroupNaming {
252
+ /** The services-map key the user chose for the group. */
253
+ name: string;
254
+ /** Final services-map key of a member part: `key(primary)` is `name`
255
+ * itself; any other part maps to `` `${name}-${part}` ``. */
256
+ key(part: string): string;
257
+ }
258
+ export interface ServiceGroupInput<P extends ServicesMap, H extends Record<string, any> = Record<string, never>, Primary extends keyof P & string = keyof P & string> {
259
+ /**
260
+ * Build the group's member services, keyed by RELATIVE part name
261
+ * (`db`, `auth`, …). Called at expansion time with the final naming
262
+ * context, so strings that must carry final DNS names (connection
263
+ * URLs, embedded config) use `g.key("db")`. `dependsOn` entries that
264
+ * name a relative part are rewritten to final keys automatically
265
+ * (entries that don't match a part pass through untouched, so a group
266
+ * service may still depend on an outside service).
267
+ */
268
+ services: (g: GroupNaming) => P;
269
+ /**
270
+ * The part that represents the group: it takes the group's own map key
271
+ * (so `dependsOn: ["<groupKey>"]` from outside waits for it), and it
272
+ * carries the group's consolidated `helpers`/`setup`. The primary is
273
+ * made the group's dependency **sink** — every other member is added to
274
+ * its `dependsOn` — so "the primary is ready" means "the whole group is
275
+ * up, setup included". Consequently no member may depend on the
276
+ * primary (that would be a cycle); pick a gateway/front-door part.
277
+ */
278
+ primary: Primary;
279
+ /**
280
+ * The group's consolidated handle: helpers exposed at
281
+ * `ctx.svc.<groupKey>` — one typed surface for the whole group (e.g.
282
+ * `{ sql, url, anonKey }` for Supabase). Attached to the primary
283
+ * service; the primary part itself must not also declare `helpers`.
284
+ */
285
+ helpers?: (args: ServiceHelpersContext) => H | Promise<H>;
286
+ /**
287
+ * Group-level setup: runs once every member service is ready (run →
288
+ * probe → per-part setup), before anything that `dependsOn` the group
289
+ * starts and before any test runs. The home for "the whole stack is
290
+ * up, now do X". Runs after the primary part's own `setup`, if any.
291
+ */
292
+ setup?: (args: ServiceSetupContext<H>) => void | Promise<void>;
293
+ /**
294
+ * Pin the services-map key the group must be mounted under. For
295
+ * components whose *derived* surface (connection URLs, env for the app
296
+ * under test) is computed from a name option before expansion — a
297
+ * mismatched key would silently split the two. Expansion errors with a
298
+ * pointer to the component's `name` option instead.
299
+ */
300
+ expectKey?: string;
301
+ }
302
+ /**
303
+ * A multi-service component — the value `serviceGroup(...)` returns, and
304
+ * what a constellation component (e.g. `supabase()`) hands you to put in
305
+ * the services map. Opaque; `defineEnvironment` expands it.
306
+ */
307
+ export interface ServiceGroup<P extends ServicesMap = ServicesMap, H extends Record<string, any> = Record<string, never>, Primary extends keyof P & string = keyof P & string> extends ServiceGroupInput<P, H, Primary> {
308
+ readonly [SERVICE_GROUP]: true;
309
+ }
310
+ /**
311
+ * Define a multi-service group. See {@link ServiceGroupInput} for the
312
+ * fields; the result goes straight into a services map:
313
+ *
314
+ * ```ts
315
+ * const stack = serviceGroup({
316
+ * primary: "gateway",
317
+ * services: (g) => ({
318
+ * db: { image: ..., ... },
319
+ * gateway: { image: ..., env: { DB_URL: `postgres://${g.key("db")}:5432/db` },
320
+ * dependsOn: ["db"] },
321
+ * }),
322
+ * helpers: () => ({ url: "http://..." }),
323
+ * });
324
+ *
325
+ * defineEnvironment({ name: "app", services: { stack } });
326
+ * // expands to services `stack` (the gateway) + `stack-db`;
327
+ * // ctx.svc.stack is the helpers record.
328
+ * ```
329
+ */
330
+ export declare function serviceGroup<P extends ServicesMap, H extends Record<string, any> = Record<string, never>, Primary extends keyof P & string = keyof P & string>(input: ServiceGroupInput<P, H, Primary>): ServiceGroup<P, H, Primary>;
331
+ /** What users pass as `services` to `defineEnvironment`: plain services
332
+ * and/or groups to expand. */
333
+ export type InputServicesMap = Record<string, ServiceConfig | ServiceGroup<any, any, any>>;
334
+ type UnionToIntersection<U> = (U extends unknown ? (x: U) => void : never) extends (x: infer I) => void ? I : never;
335
+ /** Flatten an intersection of records into one mapped type (which also
336
+ * gives it the implicit index signature `ServicesMap` needs). */
337
+ type Reify<T> = {
338
+ [K in keyof T]: T[K];
339
+ };
340
+ /** The primary part with the group's consolidated `helpers` grafted on,
341
+ * so `ServiceHandlesFor` surfaces the group handle at the group key. */
342
+ type PrimaryWithHandle<C, H> = [H] extends [Record<string, never>] ? C : Omit<C, "helpers"> & {
343
+ helpers: (args: ServiceHelpersContext) => H;
344
+ };
345
+ type ExpandGroupEntry<K extends string, G> = G extends ServiceGroup<infer P, infer H, infer Primary> ? {
346
+ [Q in Exclude<keyof P & string, Primary> as `${K}-${Q}`]: P[Q];
347
+ } & {
348
+ [Q in K]: PrimaryWithHandle<P[Primary & keyof P], H>;
349
+ } : never;
350
+ /**
351
+ * The services map after group expansion — what `ctx.svc` and the wire
352
+ * config are typed against. Groups expand to `<key>` (primary, carrying
353
+ * the group handle) + `<key>-<part>` entries; plain services pass through.
354
+ */
355
+ export type ExpandServices<SI extends InputServicesMap> = Reify<UnionToIntersection<{
356
+ [K in keyof SI & string]: SI[K] extends ServiceGroup<any, any, any> ? ExpandGroupEntry<K, SI[K]> : {
357
+ [Q in K]: SI[K];
358
+ };
359
+ }[keyof SI & string]>> extends infer S extends ServicesMap ? S : ServicesMap;
360
+ /**
361
+ * One TLS-terminated hostname for a service. The daemon binds the
362
+ * hostname on `:443` (with a leaf cert signed by the in-VM root CA)
363
+ * and `:80`, and reverse-proxies each request to `http://<service>:<port>`
364
+ * inside the docker network. WebSocket upgrades are bridged.
365
+ */
366
+ export interface ServiceTls {
367
+ /** Fully-qualified hostname clients use (e.g. `app.test`). Must be
368
+ * multi-label, lowercase, not under the reserved `.internal` TLD,
369
+ * and unique across all services and fakes in this environment. */
370
+ hostname: string;
371
+ /** HTTP port the service listens on inside its container. The
372
+ * daemon forwards proxied requests here over `spectest-net`. */
373
+ port: number;
374
+ }
375
+ export type ServiceImage = {
376
+ type: "registry";
377
+ reference: string;
378
+ } | {
379
+ type: "dockerfile";
380
+ /**
381
+ * Dockerfile contents, written verbatim into the build context. The
382
+ * build context is the project root (where `spectest/` lives), so any
383
+ * `COPY` / `ADD` references resolve relative to that directory.
384
+ */
385
+ content: string;
386
+ /** Extra glob patterns to exclude from the build context. */
387
+ exclude?: readonly string[];
388
+ };
389
+ export interface VolumeMount {
390
+ /**
391
+ * Named shared volume. Two services mounting the same `name` share one
392
+ * backing directory — the fit for sidecar pairs that exchange files
393
+ * (e.g. an image proxy reading what a storage API wrote). The directory
394
+ * lives in the per-env state tree, so it snapshots/forks with the rest
395
+ * of the environment and is torn down for fresh-state like any other
396
+ * volume. Names are environment-global: prefix with your service/group
397
+ * name in a reusable component so two instances never collide.
398
+ * Mutually exclusive with `source`.
399
+ */
400
+ name?: string;
401
+ /**
402
+ * Host path. Relative paths resolve under
403
+ * `.spectest/volumes/<service>/`. Defaults to a path derived from `target`.
404
+ */
405
+ source?: string;
406
+ /** Container path. */
407
+ target: string;
408
+ readOnly?: boolean;
409
+ /**
410
+ * Cache volume: the backing dir lives outside the per-env state tree and
411
+ * survives a delta-restore teardown (which recreates every container,
412
+ * volume, and the daemon for fresh-state semantics). Reserve this for
413
+ * content-addressed data whose presence is purely an accelerator — an
414
+ * image/layer store, a package cache — never for app state: anything in
415
+ * a cache volume is visible to the "fresh" environment.
416
+ */
417
+ cache?: boolean;
418
+ }
419
+ export interface FileMount {
420
+ /** Absolute path inside the container where the file is mounted. */
421
+ path: string;
422
+ /**
423
+ * File contents. The literal token `{{SPECTEST_SERVICE}}` is expanded
424
+ * to the owning service's name (its services-map key) before the file
425
+ * is written — handy for self-referential config like a registry host
426
+ * of `<key>.internal`, where a component can't know the key in advance.
427
+ */
428
+ content: string;
429
+ /**
430
+ * Optional octal mode string (e.g. `"0644"`) applied to the staged
431
+ * file before it's bind-mounted. Defaults to the writer's umask.
432
+ */
433
+ mode?: string;
434
+ }
435
+ export type ReadyCheck = {
436
+ type: "tcp";
437
+ port: number;
438
+ timeoutSecs?: number;
439
+ } | {
440
+ type: "http";
441
+ port: number;
442
+ path?: string;
443
+ /**
444
+ * Extra request headers sent with each probe — for health endpoints
445
+ * behind auth (`{ Authorization: "Bearer …" }`). Keeps the probe
446
+ * image-agnostic where an `exec` + curl would depend on curl being
447
+ * in the image.
448
+ */
449
+ headers?: Record<string, string>;
450
+ /**
451
+ * Exact status code that counts as ready. Default: any 2xx. Use for
452
+ * endpoints whose healthy answer isn't 2xx (e.g. a root path that
453
+ * 301s or 401s once the server is actually up).
454
+ */
455
+ expectStatus?: number;
456
+ timeoutSecs?: number;
457
+ }
458
+ /**
459
+ * Run a shell command inside the container; exit 0 = ready. Used when
460
+ * the readiness signal isn't reachable via plain TCP/HTTP from outside
461
+ * (k3s API server uses mTLS, so the natural probe is `kubectl get
462
+ * --raw=/readyz` from inside).
463
+ */
464
+ | {
465
+ type: "exec";
466
+ command: string;
467
+ timeoutSecs?: number;
468
+ };
469
+ /**
470
+ * Spec for a service started at runtime via {@link TestContext.startService}
471
+ * (or the `ctx` handed to a fake). It's a normal {@link ServiceConfig} plus a
472
+ * required `name`, minus only `dependsOn` (there is no boot DAG at runtime;
473
+ * the caller orders `startService` calls itself with `await`).
474
+ *
475
+ * The container joins `spectest-net` with its own IP and is resolvable by
476
+ * `name` (single-label, via the resolver / docker embedded DNS) and by any
477
+ * `hostnames` (extra `--network-alias`es). Like everything else in the VM it
478
+ * is captured by the per-test post-state snapshot, so a `dependsOn` child
479
+ * inherits the live container while siblings never see it.
480
+ *
481
+ * `tls: [{ hostname, port }]` works exactly as it does for a boot service:
482
+ * the daemon mints a leaf cert from the in-VM root CA and stands up a
483
+ * TLS-terminating reverse proxy at `https://<hostname>/` (and plain
484
+ * `http://<hostname>/`) → the container's `port`, binding it onto the live
485
+ * `:443`/`:80` ingress listeners the moment the container is ready. The
486
+ * hostname resolves to the daemon gateway for tests, `ctx.browser()`, and
487
+ * peer containers. Because the route lives in daemon memory (and the
488
+ * resolver registry file), it forks with the per-test snapshot like fake
489
+ * state, and is torn down when the service is stopped. This lets a runtime
490
+ * provider mint a CA-trusted HTTPS endpoint on demand — e.g. a per-DB proxy
491
+ * the Neon serverless driver reaches at its *default* `https://<host>/sql`.
492
+ */
493
+ export interface RuntimeServiceSpec extends Omit<ServiceConfig, "dependsOn"> {
494
+ /**
495
+ * Container name and primary DNS name on `spectest-net`. Must be unique
496
+ * within the current fork — generate a fresh one per provisioned instance
497
+ * (e.g. `db-${crypto.randomUUID().slice(0, 8)}`).
498
+ */
499
+ name: string;
500
+ }
501
+ /** What {@link TestContext.startService} resolves to once the container is up
502
+ * and its `readyCheck` (if any) has passed. */
503
+ export interface RuntimeServiceHandle {
504
+ /** The container/DNS name — the spec's `name`. */
505
+ name: string;
506
+ /** The container's IP on `spectest-net`. Reachable directly from peer
507
+ * containers and from VM-host/test code. */
508
+ ip: string;
509
+ }
510
+ /**
511
+ * The slice of the environment a fake can mutate at runtime — the same
512
+ * primitives {@link TestContext} exposes to tests. Passed as the third
513
+ * argument to a fake's `handler` and as `ctx` to its `helpers` factory, so
514
+ * a fake (e.g. a database-provider control plane) can provision real
515
+ * backing services on demand and wire up DNS for them, exactly as a test
516
+ * would.
517
+ */
518
+ export interface FakeContext {
519
+ /** Start a real container on `spectest-net` at runtime. See
520
+ * {@link RuntimeServiceSpec}. */
521
+ startService(spec: RuntimeServiceSpec): Promise<RuntimeServiceHandle>;
522
+ /** Stop and remove a runtime service started earlier (no-op if gone). */
523
+ stopService(name: string): Promise<void>;
524
+ /** Map a DNS name onto a service IP (or the daemon ingress). See
525
+ * {@link TestContext.dnsName}. */
526
+ dnsName(hostname: string, target: DnsTarget): Promise<void>;
527
+ }
528
+ /**
529
+ * A single test step. Created via `test(...)` or `createTest(services)`.
530
+ * Tests are referenced (not named by string) when one test depends on
531
+ * another — keeps refactors and type-checking honest.
532
+ *
533
+ * `T` is the return type of the test body; it surfaces as `ctx.parent`
534
+ * in children that `dependsOn` this case. `S` is the project's services
535
+ * map (threaded through `defineEnvironment(...).test`) so `ctx.svc.<key>`
536
+ * is strongly typed.
537
+ */
538
+ export interface TestCase<T = unknown, S extends ServicesMap = ServicesMap, F extends FakesMap = FakesMap> {
539
+ /** Stable id (slug of name). Used in MCP responses and CLI flags. */
540
+ readonly id: string;
541
+ readonly name: string;
542
+ /** Parent test, if any. Single-parent for now. */
543
+ readonly dependsOn?: TestCase<unknown, S, F>;
544
+ /** Override the default per-test timeout (default 60s). */
545
+ readonly timeoutMs?: number;
546
+ /** @internal — the body that the in-sandbox daemon invokes. */
547
+ readonly run: TestFn<T, unknown, S, F>;
548
+ }
549
+ export interface TestOpts<P = undefined, S extends ServicesMap = ServicesMap, F extends FakesMap = FakesMap> {
550
+ dependsOn?: TestCase<P, S, F>;
551
+ timeoutMs?: number;
552
+ }
553
+ export type TestFn<T = void, P = undefined, S extends ServicesMap = ServicesMap, F extends FakesMap = FakesMap> = (ctx: TestContext<P, S, F>) => T | Promise<T>;
554
+ /**
555
+ * Context object passed to every test function.
556
+ *
557
+ * `P` is the return type of the parent test (the one named in
558
+ * `dependsOn`); for root tests it's `undefined`. `S` is the project's
559
+ * services map (threaded through `defineEnvironment(...).test`) so
560
+ * `ctx.svc` only includes services with a `client` factory, each typed
561
+ * as the factory's output (e.g. a Bun SQL pool for `postgres(...)`).
562
+ */
563
+ export interface TestContext<P = undefined, S extends ServicesMap = ServicesMap, F extends FakesMap = FakesMap> {
564
+ /**
565
+ * Instrumented `fetch`, exposed on `ctx`. Each call is recorded on the
566
+ * test timeline and resolves to a {@link WrappedResponse}: reads carry
567
+ * provenance so `expect(res.status)` / `expect(await res.json())` nest
568
+ * under the HTTP call. Because the status-line accessors are
569
+ * {@link Carrier}s, a raw `res.status === 200` is a *type error* — use
570
+ * `res.status.unwrap()` / `res.unwrap().status`, or assert via `expect`.
571
+ *
572
+ * (The plain global `fetch` is wrapped the same way at runtime but keeps
573
+ * the standard `Response` type, so prefer `ctx.fetch` for honestly-typed
574
+ * results.)
575
+ */
576
+ fetch: SpectestFetch;
577
+ /** Run `sh -lc <command>` inside a service container. The result is
578
+ * {@link Wrapped}, so `res.stdout` is a `Carrier<string>` — assert via
579
+ * `expect(res.stdout)` or recover the raw string with `res.stdout.unwrap()`.
580
+ * (In `setup`/`eval` the result is wrapped too, just without a timeline
581
+ * link, so `.unwrap()` works there the same way.)
582
+ *
583
+ * The full run is also captured as an asciicast and replayed in the
584
+ * web UI — one recording per call, with output timestamped as it
585
+ * streamed, so slow or animated CLI output can be watched rather
586
+ * than read as a final blob. Unlike `terminal` there is no PTY: the
587
+ * program sees plain pipes (`isatty` false), so stdout/stderr stay
588
+ * byte-identical to what `exec` always returned and TTY-gated
589
+ * spinners/colour won't be emitted — reach for `terminal` when the
590
+ * CLI needs to believe it's on a TTY.
591
+ *
592
+ * Pass `{ cwd }` to run the command from a working directory instead of
593
+ * prefixing it with `cd <dir> && ` — the cwd is kept off the command
594
+ * string, so the timeline sidebar shows just the command and the
595
+ * directory surfaces in the detail view. */
596
+ exec(service: string, command: string, opts?: ExecOpts): Promise<Wrapped<ExecResult>>;
597
+ /**
598
+ * Run a command inside a service container under a PTY and record the
599
+ * full terminal session as an asciicast for replay in the web UI.
600
+ * Unlike `exec`, the program sees a TTY (`isatty(1)` true, colour
601
+ * codes preserved, line-buffered), so the byte stream may differ from
602
+ * what `exec` returns. Reach for `terminal` when you're driving a CLI
603
+ * and want a recording; reach for `exec` for plain piped output.
604
+ *
605
+ * One-shot convenience: this is a thin wrapper over `openTerminal` —
606
+ * spawn `command`, wait for exit, close, return the captured output
607
+ * and exit code. Reach for `openTerminal` when you want to keep the
608
+ * session alive across multiple sends or `waitFor` predicates (e.g.
609
+ * driving an interactive REPL or waiting on a loading spinner).
610
+ */
611
+ terminal(service: string, command: string, opts?: TerminalOpts): Promise<Wrapped<TerminalResult>>;
612
+ /**
613
+ * Open a long-lived interactive terminal in a service container.
614
+ * Returns a `Terminal` you can `send` keystrokes to, poll the
615
+ * rendered screen with `waitFor`, and `close` when done. Every byte
616
+ * the PTY emits is captured as an asciicast and replayed in the web
617
+ * UI the same way a one-shot `terminal(...)` is.
618
+ *
619
+ * Terminals are NOT auto-closed when the test ends. A docker exec
620
+ * subprocess is cheap to keep alive and Freestyle captures it
621
+ * cleanly in the snapshot along with the rest of the container, so
622
+ * leaking the handle past test end is fine. Call `.close()`
623
+ * explicitly if you want a `close` step in the timeline; otherwise
624
+ * `await term.exited` (after the program self-terminates) is the
625
+ * natural way to assert on the exit code.
626
+ */
627
+ openTerminal(service: string, opts?: TerminalOpts): Promise<Terminal>;
628
+ /**
629
+ * Open the headless browser. Backed by Chromium-over-CDP inside the VM.
630
+ *
631
+ * There is ONE persistent browser per environment: every `ctx.browser()`
632
+ * call returns it, and it stays alive across tests — the browser is part
633
+ * of the state a test's snapshot captures, so a `dependsOn` child resumes
634
+ * the exact live page its parent left (cookies, localStorage, signed-in
635
+ * SPA state). Sign in once in a parent test; every descendant is already
636
+ * signed in. Sibling tests fork from the same parent snapshot, so they
637
+ * can't see each other's browsing. A test with no browser-using ancestor
638
+ * gets a fresh browser on first call (first call's options win).
639
+ *
640
+ * `.close()` destroys the shared instance — the next `ctx.browser()`
641
+ * starts fresh. Don't call it for routine cleanup; recording is detached
642
+ * automatically at test end.
643
+ */
644
+ browser(opts?: BrowserOptions): Promise<Browser>;
645
+ /**
646
+ * Open a phone-emulated session for a mobile app and return a {@link Mobile}
647
+ * handle already pointed at it — no `navigate`. Pass the app handle a
648
+ * mobile-app component exposes on `ctx.svc`, e.g. a service declared with
649
+ * `expo()`:
650
+ *
651
+ * ```ts
652
+ * services: { app: expo() }
653
+ * // in a test:
654
+ * const m = await ctx.mobile(ctx.svc.app);
655
+ * await m.getByTestId("email").fill("a@b.com");
656
+ * await m.getByRole("button", { name: "Sign in" }).tap();
657
+ * await expect(m.getByText(/Welcome/)).toBeVisible();
658
+ * ```
659
+ *
660
+ * The session emulates the latest iPhone (viewport + DPR + mobile UA +
661
+ * touch) and the dashboard replays it inside a phone bezel.
662
+ *
663
+ * Sessions are persistent, one per app: like `ctx.browser()`, the live
664
+ * session is captured in the test's snapshot, so a `dependsOn` child
665
+ * picks up the app exactly where the parent left it (already signed in,
666
+ * mid-flow) instead of reloading it. `.close()` discards the session;
667
+ * the next `ctx.mobile(app)` opens the app fresh.
668
+ */
669
+ mobile(app: MobileApp): Promise<Mobile>;
670
+ /** The test's display name. */
671
+ readonly testName: string;
672
+ /**
673
+ * Value returned by the parent test. Carried across the fork in the
674
+ * daemon's own memory (Freestyle's snapshot is memory + filesystem), so
675
+ * any JS value works — including Maps, Sets, class instances, and live
676
+ * connections that survive the fork. `undefined` for root tests or when
677
+ * the parent returned nothing.
678
+ */
679
+ readonly parent: P;
680
+ /**
681
+ * Per-service helper namespaces, keyed by service name. Only services
682
+ * whose definition ships a `helpers` factory appear here; the value at
683
+ * `ctx.svc.<name>` is exactly the record that factory returned. For a
684
+ * `postgres(...)` service that ships `{ client }`, tests do
685
+ * `await ctx.svc.db.client\`SELECT 1\``.
686
+ */
687
+ readonly svc: ServiceHandlesFor<S>;
688
+ /**
689
+ * Per-fake helper namespaces, keyed by fake name. Each is the record
690
+ * of functions the fake's `helpers` factory returned (or `{ state }`
691
+ * when it ships none — tests never touch a fake's private state
692
+ * directly). Those functions read/mutate the fake's state internally;
693
+ * the state itself is in-process and lives across the fork along with
694
+ * the rest of daemon memory, so calls in a child test see the fork's
695
+ * own copy as mutated by its ancestors. Every helper call is recorded
696
+ * as a step and its return value tracked, so assertions on it nest
697
+ * under the call in the timeline.
698
+ *
699
+ * Strongly typed against the project's fakes map when fakes are
700
+ * declared in `defineEnvironment({ ..., fakes })`: `ctx.fakes.stripe`
701
+ * is exactly the helpers record `defineFake`'s `helpers` factory
702
+ * returned — no cast. (Falls back to a loose record only when the
703
+ * environment declares no fakes.)
704
+ */
705
+ readonly fakes: FakeHandlesFor<F>;
706
+ /**
707
+ * Poll a predicate until it returns a truthy value, then return that
708
+ * value. Records one `wait` event for the whole loop (with attempt
709
+ * count, total duration, and the description) instead of one event
710
+ * per probe — useful for "wait until pod Running"-style checks where
711
+ * the intermediate states are noise.
712
+ *
713
+ * - `null`, `undefined`, or `false` from `fn` mean "not yet" — wait
714
+ * `intervalMs` and try again.
715
+ * - Anything else is the success value and is returned, tagged with
716
+ * the wait event's seq. Downstream `expect(...)` on it links to
717
+ * the wait (one logical step), not to N suppressed HTTP calls.
718
+ * - Throws from `fn` propagate out immediately; the wait event is
719
+ * still recorded (with `error` set) so the timeline reflects the
720
+ * abort.
721
+ * - Defaults: `timeoutMs = 30_000`, `intervalMs = 1_000`.
722
+ *
723
+ * Side-effect calls inside `fn` (fetch, ctx.svc.* helpers, etc.)
724
+ * don't show up on the event log — the recorder is paused for the
725
+ * duration. Use `ctx.poll` for read-only observation, not for
726
+ * stateful work you want recorded.
727
+ */
728
+ poll<T>(description: string, fn: () => T | null | undefined | false | Promise<T | null | undefined | false>, opts?: {
729
+ timeoutMs?: number;
730
+ intervalMs?: number;
731
+ }): Promise<Wrapped<T>>;
732
+ /**
733
+ * Register a DNS name at runtime so the rest of this test (and anything
734
+ * downstream of it) can reach it. `{ ingress: true }` points the name at
735
+ * the daemon (a fake / TLS proxy); `{ service }` points it at a
736
+ * container's live IP; a `*.suffix` wildcard (e.g. `"*.example.com"`)
737
+ * routes a whole domain — the natural fit for k3s Ingress hosts a test
738
+ * applies on the fly.
739
+ *
740
+ * Answered by spectest-resolver, so it works for VM-host/test code,
741
+ * `ctx.browser()`, and peer containers (Docker forwards unknown names to
742
+ * the host resolver). It does NOT land in any container's `/etc/hosts`.
743
+ * The registration mutates in-daemon state, so it's isolated to this
744
+ * test's fork — like fake state.
745
+ *
746
+ * ```ts
747
+ * await ctx.svc.k8s.apply(ingressFor("foo.example.com"));
748
+ * await ctx.dnsName("foo.example.com", { service: "k8s" });
749
+ * const res = await ctx.fetch("http://foo.example.com");
750
+ * ```
751
+ */
752
+ dnsName(hostname: string, target: DnsTarget): Promise<void>;
753
+ /**
754
+ * Start a real container on `spectest-net` at runtime — a peer machine
755
+ * with its own IP, reachable like any boot service. Returns once the
756
+ * container is up and its `readyCheck` (if any) has passed.
757
+ *
758
+ * The new container is part of this test's post-state snapshot, so a
759
+ * `dependsOn` child inherits it (same PID, same data) while siblings,
760
+ * which fork from the parent's earlier snapshot, never see it — the same
761
+ * isolation fake `state` and {@link dnsName} get. Reach it by `name`
762
+ * (single-label, via the resolver) or by any `hostnames` you pass; map a
763
+ * multi-label name onto it with `ctx.dnsName(host, { service: name })`.
764
+ *
765
+ * The image is pulled on first use (fast through the host cache). See
766
+ * {@link RuntimeServiceSpec}.
767
+ *
768
+ * ```ts
769
+ * const { name } = await ctx.startService({
770
+ * name: `db-${crypto.randomUUID().slice(0, 8)}`,
771
+ * image: { type: "registry", reference: "postgres:16-alpine" },
772
+ * env: { POSTGRES_PASSWORD: "secret" },
773
+ * readyCheck: { type: "exec", command: "pg_isready -h 127.0.0.1 -p 5432" },
774
+ * });
775
+ * const sql = new Bun.SQL(`postgres://postgres:secret@${name}:5432/postgres`);
776
+ * ```
777
+ */
778
+ startService(spec: RuntimeServiceSpec): Promise<RuntimeServiceHandle>;
779
+ /** Stop and remove a runtime service started via {@link startService}
780
+ * (no-op if it's already gone). */
781
+ stopService(name: string): Promise<void>;
782
+ }
783
+ export interface ExecResult {
784
+ stdout: string;
785
+ stderr: string;
786
+ exitCode: number;
787
+ }
788
+ /** Options for {@link TestContext.exec}. */
789
+ export interface ExecOpts {
790
+ /**
791
+ * Working directory inside the container to run the command from.
792
+ * Equivalent to prefixing the command with `cd <cwd> && `, but the
793
+ * directory is kept off the command string: the recorded step's
794
+ * sidebar summary shows just the command, while the working directory
795
+ * is surfaced in the detail view (the prompt line of the captured
796
+ * terminal and the step's panel header). Implemented as `docker exec
797
+ * -w <cwd>`, so a relative path resolves against the image's WORKDIR.
798
+ */
799
+ cwd?: string;
800
+ }
801
+ export interface TestSuite<S extends ServicesMap = ServicesMap, F extends FakesMap = FakesMap> {
802
+ tests: TestCase<unknown, S, F>[];
803
+ }
804
+ /**
805
+ * A fake server hosted in the spectest-daemon. Use this to stand in for
806
+ * external HTTP APIs (auth providers, payment gateways, …) that you can't
807
+ * call directly from the hermetic test VM.
808
+ *
809
+ * Each fake declares one or more `hostnames` it answers to. The daemon
810
+ * binds an HTTP listener per unique `port` on 0.0.0.0 (the bridge gateway
811
+ * is reachable from every service container), and `spectest-resolver`
812
+ * answers DNS for those hostnames with the bridge gateway IP. Containers
813
+ * doing `fetch("http://api.stripe.com/v1/charges")` route into the daemon,
814
+ * which dispatches to the matching fake by Host header.
815
+ *
816
+ * Internal state lives in plain JS memory — it forks with the rest of the
817
+ * snapshot, so per-test forks start from a known baseline and each fork
818
+ * has its own copy. State is private to the fake; expose it for assertions
819
+ * via `helpers` functions that tests call as `ctx.fakes.<name>.<fn>(...)`.
820
+ *
821
+ * HTTPS works out of the box. Every fake is auto-bound on :443 with a
822
+ * leaf cert signed by the in-VM root CA (SANs = `hostnames`), and
823
+ * every service container trusts that CA via bind-mount + system-trust
824
+ * layer — point your app at `https://api.stripe.com` and it Just Works.
825
+ * HTTP also stays bound on `port` (default 80) for back-compat.
826
+ */
827
+ export interface FakeDefinition<S = any, H extends Record<string, unknown> = Record<string, never>> {
828
+ /** Stable name. Used as the key in `ctx.fakes` and in logs/UI. */
829
+ name: string;
830
+ /**
831
+ * Fully-qualified hostnames the fake answers to (e.g.
832
+ * `"api.stripe.com"`). Same rules as service `hostnames`: multi-label,
833
+ * lowercase, no `.internal` suffix, no collisions with services or
834
+ * other fakes.
835
+ */
836
+ hostnames: readonly string[];
837
+ /** TCP port the fake listens on. Default `80`. */
838
+ port?: number;
839
+ /**
840
+ * Build the fake's initial state. Called once when the project loads.
841
+ * The returned value lives in daemon memory for the rest of the
842
+ * environment's life — it survives `bootstrap`, the warm-template
843
+ * snapshot, and every per-test fork (each fork sees its own copy).
844
+ */
845
+ state?: () => S | Promise<S>;
846
+ /**
847
+ * HTTP handler. Receives a standard `Request` (Bun-native), the fake's
848
+ * mutable `state`, and a {@link FakeContext} `ctx` for mutating the
849
+ * environment at runtime (e.g. `ctx.startService(...)` to provision a
850
+ * real backing instance, `ctx.dnsName(...)` to name it). Return any
851
+ * `Response`. Thrown errors surface as 500s. The request URL is the
852
+ * absolute URL the client used — useful for routing on the path.
853
+ */
854
+ handler: (req: Request, state: S, ctx: FakeContext) => Response | Promise<Response>;
855
+ /**
856
+ * Build the helpers exposed at `ctx.fakes.<name>` — a record of
857
+ * **functions** that read or mutate the fake's `state` (received here)
858
+ * via closure. Called the first time a test touches the fake; result
859
+ * is cached for the daemon's life. Omit it and tests see `{}`: state
860
+ * stays private, reachable only through the functions you expose
861
+ * (e.g. `{ lastCharge(), declineSource(src) }`). Don't expose raw
862
+ * `state` or use getters — return copies/derived values from functions
863
+ * instead.
864
+ *
865
+ * Every call is tracked in the test timeline: it records a `fake` step
866
+ * and the return value is tagged so a later `expect(...)` on it nests
867
+ * under that step in the UI (same provenance as `fetch`/db results).
868
+ *
869
+ * Receives the fake's `state` plus a {@link FakeContext} `ctx`, so a
870
+ * helper can provision/teardown runtime services just like the handler.
871
+ */
872
+ helpers?: (args: {
873
+ name: string;
874
+ state: S;
875
+ ctx: FakeContext;
876
+ }) => H | Promise<H>;
877
+ /**
878
+ * Internal. Platform secret references this fake needs at *record* time
879
+ * (set by {@link replayFake}). The daemon reports the union of these to
880
+ * the control plane, which resolves each via its `SecretResolver` and
881
+ * pushes the values on the eval path only — they never enter project
882
+ * files, the config hash, or a cassette. Not part of the authoring
883
+ * surface; `JSON.stringify` ignores it (fakes never serialize to config).
884
+ */
885
+ secretRefs?: readonly string[];
886
+ }
887
+ /**
888
+ * Define a fake. `defineFake({ ... })` is a thin wrapper that pins the
889
+ * generic `S` and `H` so `helpers`/`handler` see the inferred state type
890
+ * without the caller having to spell it out twice.
891
+ */
892
+ export declare function defineFake<S = any, H extends Record<string, unknown> = Record<string, never>>(opts: FakeDefinition<S, H>): FakeDefinition<S, H>;
893
+ /** Map of fake-name -> FakeDefinition, keyed by stable name. `any` for
894
+ * both generic args (not the bare `FakeDefinition` default of
895
+ * `<any, Record<string, never>>`) so a concrete fake that ships real
896
+ * `helpers` — whose `helpers`/`handler` function types would otherwise be
897
+ * invariant-incompatible with the narrower default — is still assignable.
898
+ * The precise per-fake helper types are recovered by `FakeHandlesFor<F>`
899
+ * at use sites. */
900
+ export type FakesMap = Record<string, FakeDefinition<any, any>>;
901
+ /** Rewrite a helpers record so each function's result is inspect-wrapped
902
+ * ({@link Wrapped}) — mirroring the runtime, where `trackFakeHelpers` wraps
903
+ * every helper return value for assertion provenance. Without this the raw
904
+ * return type (e.g. `Charge[]`) reaches `expect`, which the `Provenanced`
905
+ * gate rejects. Handles sync and async helpers; non-function members (and
906
+ * `void` side-effect helpers) pass through untouched. Mirrors `Tagged<T>` in
907
+ * `components/k3s.ts`, extended to cover synchronous returns. */
908
+ type WrappedHelpers<H> = {
909
+ [K in keyof H]: H[K] extends (...args: infer A) => Promise<infer R> ? (...args: A) => Promise<Wrapped<R>> : H[K] extends (...args: infer A) => infer R ? (...args: A) => [R] extends [void] ? void : Wrapped<R> : H[K];
910
+ };
911
+ /** Awaited return type of a fake's `helpers` factory (with each result
912
+ * inspect-wrapped, see {@link WrappedHelpers}), or `{ state: S }` (the
913
+ * default) when the user didn't ship one. */
914
+ type FakeHelpersOf<F> = F extends FakeDefinition<infer S, infer H> ? [H] extends [Record<string, never>] ? {
915
+ state: S;
916
+ } : WrappedHelpers<H> : never;
917
+ /** Per-fake handles derived from a concrete fakes map; what tests see at
918
+ * `ctx.fakes`. For a concrete map (fakes declared in `defineEnvironment`)
919
+ * each key is the precise helpers record. When `F` is the loose default
920
+ * `FakesMap` (no fakes declared, or generic daemon-side code), this
921
+ * collapses to a permissive record so untyped access still compiles. */
922
+ export type FakeHandlesFor<F extends FakesMap> = string extends keyof F ? Record<string, Record<string, unknown>> : {
923
+ [K in keyof F]: FakeHelpersOf<F[K]>;
924
+ };
925
+ /**
926
+ * A `test(...)` function bound to a concrete services map (and fakes map).
927
+ * Returned by `defineEnvironment(...).test`; gives tests fully-typed access
928
+ * to `ctx.svc.<key>` and `ctx.fakes.<key>` without per-call casts.
929
+ */
930
+ export interface TypedTest<S extends ServicesMap, F extends FakesMap = FakesMap> {
931
+ <T = void>(name: string, fn: TestFn<T, undefined, S, F>): TestCase<T, S, F>;
932
+ <T = void, P = undefined>(name: string, opts: TestOpts<P, S, F>, fn: TestFn<T, P, S, F>): TestCase<T, S, F>;
933
+ }
934
+ /**
935
+ * A complete project definition: an environment, an optional one-shot
936
+ * setup hook, and an optional test suite. `spectest/index.ts`
937
+ * default-exports one of these via `env.project([...tests])` or
938
+ * `env.project({ setup, tests })`.
939
+ */
940
+ export interface Project<S extends ServicesMap = ServicesMap, F extends FakesMap = FakesMap> {
941
+ environment: EnvironmentConfig<S>;
942
+ /**
943
+ * Fake servers hosted in the spectest-daemon (see {@link defineFake}).
944
+ * Keyed by stable fake name; the key becomes the slot in
945
+ * `ctx.fakes.<key>` from test code. Populated from the `fakes` declared
946
+ * in `defineEnvironment(...)`.
947
+ */
948
+ fakes?: F;
949
+ /**
950
+ * Project-level setup. Runs once, after every service is Ready and
951
+ * its per-service `setup` has completed, before the warm-template
952
+ * snapshot. Use this for state that's part of "the environment as
953
+ * the tests expect to find it" — seed data in a database, an initial
954
+ * Deployment in k3s, etc. Like service-level setup, the result is
955
+ * captured by every snapshot taken from that point, so warm restore
956
+ * and per-test forks inherit it without re-running.
957
+ *
958
+ * The ctx here is a slimmer cousin of TestContext: no recorder, no
959
+ * timeout, no browser/terminal — setup is not a test and doesn't
960
+ * appear in the timeline.
961
+ */
962
+ setup?: ProjectSetupFn<S, F>;
963
+ tests?: TestSuite<S, F>;
964
+ }
965
+ /**
966
+ * Slim context handed to the project-level `setup` hook. Same shape as
967
+ * `TestContext` but pared down — no testName, no parent, no recording
968
+ * surfaces (browser, terminal, poll). If you need polling inside setup,
969
+ * write a plain loop: setup runs outside the test timeline so there's
970
+ * nothing to record into.
971
+ */
972
+ export interface ProjectSetupContext<S extends ServicesMap = ServicesMap, F extends FakesMap = FakesMap> {
973
+ fetch: SpectestFetch;
974
+ exec(service: string, command: string, opts?: ExecOpts): Promise<Wrapped<ExecResult>>;
975
+ readonly svc: ServiceHandlesFor<S>;
976
+ /** Same surface tests see — fakes are already up by setup time. Typed
977
+ * against the declared fakes map (see {@link TestContext.fakes}). */
978
+ readonly fakes: FakeHandlesFor<F>;
979
+ /**
980
+ * Register a DNS name (see {@link TestContext.dnsName}). Useful here to
981
+ * wire a wildcard like `"*.example.com"` to a k3s cluster once, before
982
+ * any test runs — it's captured into the warm-template snapshot, so every
983
+ * test inherits the route without re-registering.
984
+ */
985
+ dnsName(hostname: string, target: DnsTarget): Promise<void>;
986
+ /**
987
+ * Start a runtime service (see {@link TestContext.startService}). Started
988
+ * here, it's captured into the warm-template snapshot and inherited by
989
+ * every test — use it for backing instances that should exist before any
990
+ * test runs but aren't worth a boot-time `services` entry.
991
+ */
992
+ startService(spec: RuntimeServiceSpec): Promise<RuntimeServiceHandle>;
993
+ /** Stop a runtime service (see {@link TestContext.stopService}). */
994
+ stopService(name: string): Promise<void>;
995
+ }
996
+ export type ProjectSetupFn<S extends ServicesMap = ServicesMap, F extends FakesMap = FakesMap> = (ctx: ProjectSetupContext<S, F>) => void | Promise<void>;
997
+ /**
998
+ * A defined environment. Returned by `defineEnvironment(...)` and used to
999
+ * (a) build typed tests against this environment's services and (b)
1000
+ * bundle those tests into the project's default export.
1001
+ *
1002
+ * ```ts
1003
+ * const env = defineEnvironment({
1004
+ * name: "todos",
1005
+ * services: {
1006
+ * db: postgres({ database: "todos", user: "todos", password: "todos" }),
1007
+ * },
1008
+ * });
1009
+ *
1010
+ * const createTodo = env.test("create todo", async (ctx) => {
1011
+ * // ctx.svc.db.client is the Bun SQL pool (the helper postgres ships).
1012
+ * await ctx.svc.db.client`SELECT 1`;
1013
+ * return { id: 1 };
1014
+ * });
1015
+ *
1016
+ * const markDone = env.test(
1017
+ * "mark done",
1018
+ * { dependsOn: createTodo },
1019
+ * async (ctx) => {
1020
+ * // ctx.parent is { id: number }
1021
+ * await ctx.svc.db.client`UPDATE todos SET done = TRUE WHERE id = ${ctx.parent.id}`;
1022
+ * },
1023
+ * );
1024
+ *
1025
+ * export default env.project([createTodo, markDone]);
1026
+ * ```
1027
+ */
1028
+ export interface ProjectOpts<S extends ServicesMap = ServicesMap, F extends FakesMap = FakesMap> {
1029
+ /** Optional project-level setup. See `Project.setup`. */
1030
+ setup?: ProjectSetupFn<S, F>;
1031
+ /** Test cases for this project's suite. */
1032
+ tests?: TestCase<unknown, S, F>[];
1033
+ }
1034
+ /**
1035
+ * Input to {@link defineEnvironment}: the environment config plus an
1036
+ * optional `fakes` map. `fakes` is declared here (rather than on
1037
+ * `project(...)`) so the fakes' types are bound when `env.test(...)`
1038
+ * creates a test — that's what makes `ctx.fakes.<key>` strongly typed.
1039
+ * `fakes` is stripped from `config` before it's stored/serialised, so the
1040
+ * wire `EnvironmentConfig` the Rust control plane sees never carries it.
1041
+ *
1042
+ * Unlike the wire {@link EnvironmentConfig}, `services` entries here may
1043
+ * be {@link ServiceGroup}s — they're expanded to plain services (primary
1044
+ * at the group's key, other parts at `<key>-<part>`) before validation.
1045
+ */
1046
+ export interface EnvironmentInput<SI extends InputServicesMap, F extends FakesMap = FakesMap> {
1047
+ /** Human-friendly name for the environment, e.g. "my-app". */
1048
+ name: string;
1049
+ /** Services and/or service groups, keyed by name. See
1050
+ * {@link EnvironmentConfig.services} and {@link ServiceGroup}. */
1051
+ services: SI;
1052
+ /** Sandbox timeout in seconds (default 1h). */
1053
+ timeoutSecs?: number;
1054
+ /** Fake servers — see {@link defineFake}. Keyed by stable name; the key
1055
+ * shows up as `ctx.fakes.<key>` in tests, typed as that fake's helpers
1056
+ * record. */
1057
+ fakes?: F;
1058
+ }
1059
+ export interface DefinedEnvironment<S extends ServicesMap, F extends FakesMap = FakesMap> {
1060
+ /** The validated environment config. Plain data, JSON-serialisable —
1061
+ * the in-VM daemon ships this to the control plane on `/load`. */
1062
+ readonly config: EnvironmentConfig<S>;
1063
+ /** Define a test against this environment. `ctx.svc.<key>` and
1064
+ * `ctx.fakes.<key>` are strongly typed against the services and fakes
1065
+ * maps. */
1066
+ readonly test: TypedTest<S, F>;
1067
+ /** Bundle this environment with a test suite into the project default
1068
+ * export. Pass tests as a plain array for the common case, or an
1069
+ * options bag to attach project-level `setup`. (Fakes are declared on
1070
+ * `defineEnvironment`, not here.) */
1071
+ project(tests?: TestCase<unknown, S, F>[]): Project<S, F>;
1072
+ project(opts: ProjectOpts<S, F>): Project<S, F>;
1073
+ }
1074
+ /**
1075
+ * The `ctx` type for an environment, for typing shared test helpers without
1076
+ * `any`. Instantiate with the environment from `defineEnvironment`:
1077
+ *
1078
+ * ```ts
1079
+ * const env = defineEnvironment({ ... });
1080
+ * export type AppCtx = Ctx<typeof env>;
1081
+ *
1082
+ * // A helper reaching into ctx.svc / ctx.fakes stays fully typed:
1083
+ * async function runJob(ctx: AppCtx) {
1084
+ * await ctx.svc.db.client`SELECT 1`;
1085
+ * }
1086
+ * ```
1087
+ *
1088
+ * This is the same `ctx` an `env.test(...)` callback receives. The parent
1089
+ * return type is left as `unknown` (helpers rarely touch `ctx.parent` — read
1090
+ * it in the test body and pass the value in). Prefer this over `ctx: any`:
1091
+ * an `any`-typed ctx also defeats the `expect(...)` overloads, silently
1092
+ * resolving `expect(value)` to the `expect(locator)` overload so value
1093
+ * matchers like `.toBe(...)` disappear.
1094
+ */
1095
+ export type Ctx<E> = E extends DefinedEnvironment<infer S, infer F> ? TestContext<unknown, S, F> : never;
1096
+ /**
1097
+ * Define an environment and get back a builder you can hang tests off.
1098
+ * The builder's `.test(...)` returns test cases typed against the
1099
+ * environment's services (and any declared `fakes`), and `.project([...])`
1100
+ * produces the file's default export.
1101
+ */
1102
+ export declare function defineEnvironment<SI extends InputServicesMap, F extends FakesMap = FakesMap>(input: EnvironmentInput<SI, F>): DefinedEnvironment<ExpandServices<SI>, F>;
1103
+ export declare class ExpectationError extends Error {
1104
+ constructor(message: string);
1105
+ }
1106
+ interface Matchers {
1107
+ toBe(expected: unknown): void;
1108
+ toEqual(expected: unknown): void;
1109
+ toBeTruthy(): void;
1110
+ toBeFalsy(): void;
1111
+ toBeGreaterThan(n: number): void;
1112
+ toBeLessThan(n: number): void;
1113
+ toBeGreaterThanOrEqual(n: number): void;
1114
+ toBeLessThanOrEqual(n: number): void;
1115
+ toContain(expected: unknown): void;
1116
+ toMatch(re: RegExp): void;
1117
+ toHaveLength(n: number): void;
1118
+ }
1119
+ export interface Expectation extends Matchers {
1120
+ not: Matchers;
1121
+ }
1122
+ /**
1123
+ * Auto-retrying web-first assertions for a {@link Locator} — Playwright's
1124
+ * `expect(locator)` matchers. Each polls the element until it passes or a
1125
+ * deadline elapses (default 5 s, `{ timeout }` overrides) and records an
1126
+ * assertion event just like a value `expect`. `await` them — they are async.
1127
+ */
1128
+ export interface LocatorMatchers {
1129
+ /** The element is present and visible. */
1130
+ toBeVisible(opts?: {
1131
+ timeout?: number;
1132
+ }): Promise<void>;
1133
+ /** The element is absent or hidden. */
1134
+ toBeHidden(opts?: {
1135
+ timeout?: number;
1136
+ }): Promise<void>;
1137
+ /** The element's (trimmed) text equals `expected` (or matches a RegExp). */
1138
+ toHaveText(expected: string | RegExp, opts?: {
1139
+ timeout?: number;
1140
+ }): Promise<void>;
1141
+ /** The element's text contains `expected`. */
1142
+ toContainText(expected: string, opts?: {
1143
+ timeout?: number;
1144
+ }): Promise<void>;
1145
+ /** The input's value equals `expected` (or matches a RegExp). */
1146
+ toHaveValue(expected: string | RegExp, opts?: {
1147
+ timeout?: number;
1148
+ }): Promise<void>;
1149
+ /** The locator resolves to exactly `expected` elements. */
1150
+ toHaveCount(expected: number, opts?: {
1151
+ timeout?: number;
1152
+ }): Promise<void>;
1153
+ toBeEnabled(opts?: {
1154
+ timeout?: number;
1155
+ }): Promise<void>;
1156
+ toBeDisabled(opts?: {
1157
+ timeout?: number;
1158
+ }): Promise<void>;
1159
+ toBeChecked(opts?: {
1160
+ timeout?: number;
1161
+ }): Promise<void>;
1162
+ }
1163
+ export interface LocatorAssertion extends LocatorMatchers {
1164
+ /** Negate every matcher (retries until the negated condition holds). */
1165
+ not: LocatorMatchers;
1166
+ }
1167
+ export declare function expect(actual: Locator, message?: string): LocatorAssertion;
1168
+ export declare function expect(actual: Provenanced, message?: string): Expectation;
1169
+ /**
1170
+ * Assert on a value with **no provenance** — a computed number, a raw
1171
+ * WebSocket frame, anything that didn't flow from a recorded op. `message` is
1172
+ * required (it's the second argument) and reads as the natural follow-on to
1173
+ * "assert …" (e.g. `expectRaw(id, "id matches the generated value")`); it
1174
+ * renders as the assertion's label in the CLI/dashboard ("ASSERT <message>")
1175
+ * since a raw assertion has no op to nest under. Prefer `expect(...)` whenever
1176
+ * the value carries provenance — only reach for this when the type gate would
1177
+ * (rightly) reject the value. (`expect`'s own `message` is optional; here it is
1178
+ * mandatory, since the label is the only human-meaningful summary a raw
1179
+ * assertion has.)
1180
+ */
1181
+ export declare function expectRaw(actual: unknown, message: string): Expectation;
1182
+ /** `node:assert/strict` re-exported for users who prefer Node's built-in API. */
1183
+ export declare const assert: typeof nodeAssert;