@crvouga/mockingbird-service-docker 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.d.ts CHANGED
@@ -1,34 +1,16 @@
1
1
  import { Server } from 'node:http';
2
2
  import { Hono } from 'hono';
3
3
 
4
- /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
5
- type SqliteValue$2 = null | number | bigint | string | Uint8Array | boolean;
6
- /** Mutation counters returned by {@link SqliteStatement.run}. */
7
- type SqliteRunResult$2 = {
8
- changes: number;
9
- lastInsertRowid: number | bigint;
4
+ type MountedAPI$1 = FetchAPI$2 & {
5
+ readonly prefix: string;
6
+ GET: FetchHandler$1;
7
+ POST: FetchHandler$1;
8
+ PUT: FetchHandler$1;
9
+ PATCH: FetchHandler$1;
10
+ DELETE: FetchHandler$1;
11
+ HEAD: FetchHandler$1;
12
+ OPTIONS: FetchHandler$1;
10
13
  };
11
- /**
12
- * Prepared statement bound to a {@link SqliteClient}.
13
- *
14
- * Pass bind values as rest arguments on each call (no sticky `bind()`).
15
- */
16
- interface SqliteStatement$2 {
17
- run(...params: SqliteValue$2[]): SqliteRunResult$2;
18
- all<T = Record<string, unknown>>(...params: SqliteValue$2[]): T[];
19
- get<T = Record<string, unknown>>(...params: SqliteValue$2[]): T | undefined;
20
- }
21
- /**
22
- * Sync SQLite client port owned by Mockingbird.
23
- *
24
- * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
25
- * `bun:sqlite` instances all work when they expose this surface.
26
- */
27
- interface SqliteClient$2 {
28
- exec(sql: string): void;
29
- prepare(sql: string): SqliteStatement$2;
30
- transaction<T>(fn: () => T): T;
31
- }
32
14
 
33
15
  /** A stable identifier for a point in a {@link Timeline}. */
34
16
  type CheckpointId$1 = string;
@@ -119,6 +101,37 @@ declare class Timeline$1<T> {
119
101
  interface FetchAPI$2 {
120
102
  fetch(request: Request): Promise<Response>;
121
103
  }
104
+ /** A bare function form of {@link FetchAPI}, compatible with `Bun.serve`, workerd, and Deno. */
105
+ type FetchHandler$1 = (request: Request) => Promise<Response>;
106
+
107
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
108
+ type SqliteValue$2 = null | number | bigint | string | Uint8Array | boolean;
109
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
110
+ type SqliteRunResult$2 = {
111
+ changes: number;
112
+ lastInsertRowid: number | bigint;
113
+ };
114
+ /**
115
+ * Prepared statement bound to a {@link SqliteClient}.
116
+ *
117
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
118
+ */
119
+ interface SqliteStatement$2 {
120
+ run(...params: SqliteValue$2[]): SqliteRunResult$2;
121
+ all<T = Record<string, unknown>>(...params: SqliteValue$2[]): T[];
122
+ get<T = Record<string, unknown>>(...params: SqliteValue$2[]): T | undefined;
123
+ }
124
+ /**
125
+ * Sync SQLite client port owned by Mockingbird.
126
+ *
127
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
128
+ * `bun:sqlite` instances all work when they expose this surface.
129
+ */
130
+ interface SqliteClient$2 {
131
+ exec(sql: string): void;
132
+ prepare(sql: string): SqliteStatement$2;
133
+ transaction<T>(fn: () => T): T;
134
+ }
122
135
 
123
136
  /**
124
137
  * The single source of time for a service.
@@ -132,7 +145,7 @@ type ClockState$1 = {
132
145
  now: number;
133
146
  /** True while time does not advance on its own. */
134
147
  frozen: boolean;
135
- /** Milliseconds this clock adds to its underlying source. */
148
+ /** Milliseconds a running clock adds to its underlying source. `0` while frozen. */
136
149
  offsetMs: number;
137
150
  };
138
151
  type Clock$1 = {
@@ -168,7 +181,10 @@ type Rng$1 = {
168
181
  state(): number;
169
182
  /** Restore a state previously returned by {@link state}. */
170
183
  setState(state: number): void;
171
- seed: number;
184
+ /** Restart the stream from a new seed. `reset` then returns to this seed. */
185
+ reseed(seed: number | string): void;
186
+ /** The seed the stream currently starts from. */
187
+ readonly seed: number;
172
188
  };
173
189
 
174
190
  /**
@@ -177,44 +193,83 @@ type Rng$1 = {
177
193
  * This is how a suite reaches the vendor's failure modes without the vendor: the
178
194
  * quota error that only appears when a shared sandbox is full, the 429 that only
179
195
  * appears under load, the 5xx that proves a retry path works.
196
+ *
197
+ * A rule has three parts. What it **matches** (`operationId`, `method`, `path`, …), **when**
198
+ * it fires among the matching requests (`after`, `every`, `count`, `rate`, `from`, `until`),
199
+ * and what it **does** (`status`, `delay`, `timeout`, `drop`, `truncate`, `effect`).
180
200
  */
181
201
  type FaultRule$1 = {
182
- /** Stable id, so a suite can retire exactly the rule it added. */
202
+ /** Stable id, so a suite can retire exactly the rule it added. Unique within a namespace. */
183
203
  id: string;
184
204
  /** Fault only this operation. Omit to match every operation. */
185
205
  operationId?: string;
186
206
  /** Fault only this HTTP method, case-insensitive. Omit to match every method. */
187
207
  method?: string;
208
+ /** Fault only this exact path. */
209
+ path?: string;
188
210
  /** Fault only paths starting with this prefix. Omit to match every path. */
189
211
  pathPrefix?: string;
212
+ /** Fault only paths matching this regular expression (JavaScript syntax, unanchored). */
213
+ pathPattern?: string;
214
+ /** Fault only requests carrying these headers. `"*"` matches any value. */
215
+ requestHeaders?: Record<string, string>;
216
+ /** Fault only requests carrying these query parameters. `"*"` matches any value. */
217
+ query?: Record<string, string>;
190
218
  /**
191
219
  * Fault only this namespace. Omit (or `"*"`) to fault every namespace — which is what
192
220
  * an in-process caller usually wants, and what a parallel worker usually does not:
193
221
  * rules added through `POST /__admin/faults` default to the calling namespace.
194
222
  */
195
223
  namespace?: string;
224
+ /** Let this many matching requests through first. */
225
+ after?: number;
226
+ /** Then fault only every nth matching request: `3` faults the 3rd, 6th, 9th. */
227
+ every?: number;
228
+ /** Retire the rule after this many faults. Omit to keep it until removed. */
229
+ count?: number;
230
+ /** Fault this fraction of the remaining requests, `0`–`1`, drawn from the seed. Default `1`. */
231
+ rate?: number;
232
+ /**
233
+ * Fault only from this instant on the namespace clock. A duration (`"5m"`) counts from the
234
+ * clock when the rule was added. Listed as epoch ms.
235
+ */
236
+ from?: Instant$1 | Duration$1;
237
+ /** Stop faulting at this instant on the namespace clock. A duration counts from when added. */
238
+ until?: Instant$1 | Duration$1;
196
239
  /**
197
- * Status of the injected response. Omit for a rule that only delays (`delayMs` /
198
- * `latencyMs`), only drops the connection (`drop`), or only switches on an `effect`:
199
- * the request then still reaches the service.
240
+ * Status of the injected response. Omit for a rule that only delays, times out, drops,
241
+ * truncates, or switches on an `effect`: the request then still reaches the service.
200
242
  */
201
243
  status?: number;
202
244
  /** Response body, serialized as JSON. A string is sent as-is. */
203
245
  body?: unknown;
246
+ /** Response headers. */
204
247
  headers?: Record<string, string>;
205
- /** Retire the rule after this many faults. Omit to keep it until removed. */
206
- count?: number;
207
- /** Fault this fraction of matching requests, `0`–`1`. Default `1`. */
208
- rate?: number;
209
- /** Hold the response back this long, to exercise timeouts. */
248
+ /** Hold the response back this long. Listed as `delayMs`. */
249
+ delay?: Duration$1;
250
+ /** `delay`, in milliseconds. */
210
251
  delayMs?: number;
211
252
  /** Alias of `delayMs`. */
212
253
  latencyMs?: number;
254
+ /** Extra seeded delay in `[0, jitter]`. Listed as `jitterMs`. */
255
+ jitter?: Duration$1;
256
+ jitterMs?: number;
257
+ /**
258
+ * Never answer: hold the request this long, then drop the connection. Listed as
259
+ * `timeoutMs`. With virtual time the wait is spent on the mock clock.
260
+ */
261
+ timeout?: Duration$1;
262
+ timeoutMs?: number;
213
263
  /**
214
264
  * Drop the connection instead of answering: an in-process `fetch` rejects with a
215
265
  * `TypeError`, and a served mock destroys the socket. Models "unknown outcome" failures.
216
266
  */
217
267
  drop?: boolean;
268
+ /**
269
+ * Cut the response body off after this many bytes: the status and headers arrive, then
270
+ * the connection dies mid-body.
271
+ */
272
+ truncate?: number;
218
273
  /**
219
274
  * A named service behaviour to switch on for the matching request instead of (or
220
275
  * before) a canned response, e.g. `created_but_500` or `numeric_tracking_id`. Services
@@ -223,8 +278,8 @@ type FaultRule$1 = {
223
278
  effect?: string;
224
279
  /** Parameters for `effect`. */
225
280
  params?: Record<string, unknown>;
226
- /** From the preset this rule was expanded from, if any. */
227
- preset?: string;
281
+ /** The preset this rule was expanded from, if any. */
282
+ fromPreset?: string;
228
283
  };
229
284
  /** A fault that fired for one request. */
230
285
  type FaultHit$1 = {
@@ -232,6 +287,10 @@ type FaultHit$1 = {
232
287
  /** The injected response; absent when the rule only delays, drops, or sets an effect. */
233
288
  response?: Response;
234
289
  drop?: boolean;
290
+ /** Set with `drop` when the rule held the request for its `timeout` first. */
291
+ timeout?: boolean;
292
+ /** Bytes of response body to let through before the connection dies. */
293
+ truncate?: number;
235
294
  effect?: {
236
295
  name: string;
237
296
  params: Record<string, unknown>;
@@ -243,38 +302,200 @@ type FaultCandidate$1 = {
243
302
  method: string;
244
303
  path: string;
245
304
  namespace: string;
305
+ /** Request headers and query, for rules that match on them. */
306
+ headers?: Headers;
307
+ query?: URLSearchParams;
308
+ /** The namespace clock, for `from` / `until`. Rules with a window are skipped without it. */
309
+ now?: number;
310
+ /** How to spend a delay for this request. Default: the registry's own sleep. */
311
+ wait?: (ms: number) => Promise<void>;
312
+ };
313
+ /** A stored rule and how often it was consulted. */
314
+ type FaultListing$1 = FaultRule$1 & {
315
+ /** Faults left before the rule retires. `null` when it has no `count`. */
316
+ remaining: number | null;
317
+ /** Times the rule faulted a request. */
318
+ hits: number;
319
+ /** Requests that matched the rule, faulted or not. */
320
+ seen: number;
321
+ };
322
+ /** A namespace's own rules, with their counters, in the order they are tried. */
323
+ type FaultSnapshot$1 = {
324
+ /**
325
+ * `position` is how many `"*"` rules are tried before the rule, which is what its place
326
+ * in the order means to a request and holds in any process.
327
+ */
328
+ rules: (FaultListing$1 & {
329
+ position?: number;
330
+ })[];
331
+ /** How many `fault_<n>` ids the namespace has handed out. */
332
+ nextId?: number;
246
333
  };
247
334
  type FaultRegistry$1 = {
248
- isolateNamespaces(): void;
249
- snapshot(namespace: string): {
250
- rules: (FaultRule$1 & {
251
- remaining: number | null;
252
- hits: number;
253
- position: number;
254
- })[];
255
- rngState: number;
256
- };
335
+ snapshot(namespace: string): FaultSnapshot$1;
336
+ /** Add a rule, or replace the rule with the same id in the same namespace. */
257
337
  add(rule: FaultRule$1): FaultRule$1;
258
- list(): (FaultRule$1 & {
259
- remaining: number | null;
260
- hits: number;
261
- })[];
262
- remove(id: string): boolean;
263
- clear(): void;
264
- restore(namespace: string, state: {
265
- rules: (FaultRule$1 & {
266
- remaining: number | null;
267
- hits: number;
268
- position: number;
269
- })[];
270
- rngState: number;
271
- }): void;
338
+ /** The next unused `fault_<n>` id in `namespace`. */
339
+ nextId(namespace: string): string;
340
+ /** Every rule, or the rules a namespace's requests can hit: its own and the global ones. */
341
+ list(namespace?: string): FaultListing$1[];
342
+ get(id: string, namespace?: string): FaultListing$1 | undefined;
343
+ /** Remove a rule by id: from `namespace` (its own, then a global one), or wherever it is. */
344
+ remove(id: string, namespace?: string): boolean;
345
+ /** Remove every rule, or one namespace's own rules. */
346
+ clear(namespace?: string): void;
347
+ /** Replace a namespace's own rules with a snapshot's, wherever the snapshot was taken. */
348
+ restore(namespace: string, state: FaultSnapshot$1): void;
272
349
  /**
273
350
  * Every fault this request should get, in rule order, stopping at the first that answers
274
351
  * or drops (effect-only and delay-only rules let later rules match too). Consumes one of
275
352
  * each matching rule's remaining uses.
276
353
  */
277
354
  take(candidate: FaultCandidate$1): Promise<FaultHit$1[]>;
355
+ /**
356
+ * Fire these rules at one request without storing them: no matching, no schedule, in order,
357
+ * stopping at the first that answers or drops. Jitter draws from the namespace's stream.
358
+ */
359
+ fire(rules: readonly FaultRule$1[], candidate: FaultCandidate$1): Promise<FaultHit$1[]>;
360
+ };
361
+
362
+ /**
363
+ * The admin controls every mock shares, as one document.
364
+ *
365
+ * The same shape is accepted in three places, and means the same thing in each:
366
+ *
367
+ * - at boot: `createRuntime({ adminControls })`, `serve --admin-controls`,
368
+ * `MOCKINGBIRD_ADMIN_CONTROLS`
369
+ * - over HTTP: `PUT /__admin/controls`
370
+ * - per request: the `x-mockingbird-*` headers in {@link CONTROL_HEADERS}
371
+ *
372
+ * Every control is deterministic: given the same seed, clock and requests, a mock answers
373
+ * the same bytes. Nothing here reads the wall clock or `Math.random`.
374
+ */
375
+ /** Milliseconds, or a string like `"250ms"`, `"2s"`, `"15m"`, `"1h"`, `"3d"`. */
376
+ type Duration$1 = number | string;
377
+ /** Epoch milliseconds, or an ISO-8601 string. */
378
+ type Instant$1 = number | string;
379
+ type ClockControls$1 = {
380
+ /** Move the clock to this instant. */
381
+ now?: Instant$1;
382
+ /** Stop time. A frozen clock moves only when told to, so timestamps replay exactly. */
383
+ frozen?: boolean;
384
+ /**
385
+ * Step the clock forward by this much before every vendor request. With a frozen clock
386
+ * each request still gets its own, reproducible timestamp.
387
+ */
388
+ autoAdvance?: Duration$1;
389
+ };
390
+ /** How long a response takes: a fixed delay plus seeded jitter in `[0, jitter]`. */
391
+ type LatencyRuleInput$1 = {
392
+ delay?: Duration$1;
393
+ jitter?: Duration$1;
394
+ };
395
+ type LatencyControls$1 = LatencyRuleInput$1 & {
396
+ /** Per-operation overrides, keyed by operationId. A bare duration is its `delay`. */
397
+ operations?: Record<string, Duration$1 | LatencyRuleInput$1>;
398
+ };
399
+ /** A fault to add: a rule (the id is assigned when omitted), or a named preset with overrides. */
400
+ type FaultInput$1 = (Omit<FaultRule$1, "id"> & {
401
+ id?: string;
402
+ }) | ({
403
+ preset: string;
404
+ } & Partial<FaultRule$1>);
405
+ /** Identifies a {@link SnapshotDocument}. */
406
+ declare const SNAPSHOT_FORMAT$1 = "mockingbird.snapshot/v1";
407
+ /**
408
+ * A namespace, as portable JSON: what `GET /__admin/snapshots/:id` returns and what
409
+ * `PUT /__admin/snapshots/:id` and the boot `snapshot` control accept. Only `format` and
410
+ * `records` are required, so a hand-written seed file is a valid snapshot.
411
+ */
412
+ type SnapshotDocument$1 = {
413
+ format: typeof SNAPSHOT_FORMAT$1;
414
+ /** The service that wrote it. A snapshot is rejected by any other service. */
415
+ service?: string;
416
+ /**
417
+ * Stored rows. `seq` orders a collection; omitted, rows keep their listed order. `raw` is
418
+ * the stored text of a row that is not a plain record, and replaces `value` when present.
419
+ */
420
+ records: {
421
+ collection: string;
422
+ id: string;
423
+ seq?: number;
424
+ value?: unknown;
425
+ raw?: string;
426
+ }[];
427
+ /** Id counters, so the next generated id continues where the snapshot left off. */
428
+ sequences?: {
429
+ name: string;
430
+ kind: string;
431
+ value: number;
432
+ }[];
433
+ clock?: {
434
+ now: number;
435
+ frozen: boolean;
436
+ autoAdvanceMs?: number;
437
+ };
438
+ seed?: number | string;
439
+ /** Positions of the seeded random streams. */
440
+ rng?: {
441
+ state: number;
442
+ faults?: number;
443
+ latency?: number;
444
+ };
445
+ faults?: unknown;
446
+ latency?: unknown;
447
+ virtualTime?: boolean;
448
+ };
449
+ /** Controls for one namespace. */
450
+ type NamespaceControls$1 = {
451
+ /** Seeds every random choice: fault rates, jitter, and whatever the service invents. */
452
+ seed?: number | string;
453
+ clock?: ClockControls$1;
454
+ /**
455
+ * Spend injected waits (latency, fault delays, timeouts) on the mock clock instead of the
456
+ * wall clock: the request returns at once, the clock has moved, and the journal records
457
+ * the wait exactly. Default `false`: waits are real, so a client's own timeout can fire.
458
+ */
459
+ virtualTime?: boolean;
460
+ /** Baseline response time for every vendor request. A bare duration is its `delay`. */
461
+ latency?: Duration$1 | LatencyControls$1;
462
+ faults?: readonly FaultInput$1[];
463
+ /** Start from this state instead of the service's own seed data. */
464
+ snapshot?: SnapshotDocument$1;
465
+ };
466
+ /** {@link NamespaceControls} for every namespace, with per-namespace overrides. */
467
+ type MockControls$1 = NamespaceControls$1 & {
468
+ /** Vendor credential → namespace, for SDKs that cannot send a namespace header. */
469
+ credentials?: Record<string, string>;
470
+ /** Overrides for named namespaces. A key given here replaces the shared value. */
471
+ namespaces?: Record<string, NamespaceControls$1>;
472
+ };
473
+ /** A latency rule in milliseconds. */
474
+ type LatencyRule$1 = {
475
+ delayMs: number;
476
+ jitterMs: number;
477
+ };
478
+ /** Baseline latency for a namespace, normalized. */
479
+ type LatencyState$1 = LatencyRule$1 & {
480
+ operations: Record<string, LatencyRule$1>;
481
+ };
482
+ /** What {@link controlHeaders} turns into request headers. */
483
+ type ControlHeaderInput$1 = {
484
+ namespace?: string;
485
+ adminKey?: string;
486
+ branch?: string;
487
+ at?: string;
488
+ reset?: boolean;
489
+ restore?: string;
490
+ seed?: number | string;
491
+ time?: Instant$1 | Date;
492
+ advance?: Duration$1;
493
+ virtualTime?: boolean;
494
+ delay?: Duration$1;
495
+ timeout?: Duration$1;
496
+ /** A status, `"drop"`, a preset name, or a fault rule. */
497
+ fault?: number | string | Record<string, unknown>;
498
+ snapshot?: string;
278
499
  };
279
500
 
280
501
  /**
@@ -314,6 +535,8 @@ type RequestLog$1 = {
314
535
  unmatched: boolean;
315
536
  /** Set when a fault rule produced the response. */
316
537
  faultId?: string;
538
+ /** Milliseconds of injected wait: latency, fault delays and timeouts. Absent when none. */
539
+ delayMs?: number;
317
540
  /** Resource ids the handler touched (`userId`, `orderId`, …), when the service reports them. */
318
541
  ids?: Record<string, string>;
319
542
  /** Set when the service created a resource the request referred to but that did not exist. */
@@ -359,6 +582,12 @@ type JournalQuery$1 = {
359
582
  /** Only this namespace. Omit for every namespace, oldest first across all of them. */
360
583
  namespace?: string;
361
584
  operationId?: string;
585
+ /** Only this HTTP method, case-insensitive. */
586
+ method?: string;
587
+ /** Only this exact path. */
588
+ path?: string;
589
+ /** Only requests this fault rule answered or shaped. */
590
+ faultId?: string;
362
591
  status?: number;
363
592
  /** Only entries at or after this instant (epoch ms). */
364
593
  since?: number;
@@ -373,6 +602,50 @@ type Journal$1 = {
373
602
  clear(namespace?: string): void;
374
603
  };
375
604
 
605
+ /**
606
+ * Baseline response time, per namespace: how long every vendor request takes before any
607
+ * fault is considered. Jitter draws from a stream the caller owns, one per namespace and
608
+ * separate from the fault stream, so adding latency never shifts which requests a `rate`
609
+ * fault hits.
610
+ */
611
+ type LatencyRegistry$1 = {
612
+ get(namespace: string): LatencyState$1;
613
+ set(namespace: string, state: LatencyState$1): LatencyState$1;
614
+ /** Remove one namespace's latency, or every namespace's. */
615
+ clear(namespace?: string): void;
616
+ /** Milliseconds this request waits. Draws jitter, so call it once per request. */
617
+ take(namespace: string, operationId: string | undefined): number;
618
+ };
619
+
620
+ /** Clock state as the admin API reports it. */
621
+ type ControlClock$1 = ClockState$1 & {
622
+ /** `now`, as ISO-8601. */
623
+ iso: string;
624
+ /** Milliseconds the clock steps before every vendor request. */
625
+ autoAdvanceMs: number;
626
+ };
627
+ /** One namespace's controls: the body of `GET /__admin/controls`. */
628
+ type ControlState$1 = {
629
+ namespace: string;
630
+ seed: number | string;
631
+ clock: ControlClock$1;
632
+ virtualTime: boolean;
633
+ latency: LatencyState$1;
634
+ faults: FaultListing$1[];
635
+ };
636
+
637
+ /** What `GET /__admin/snapshots` lists for each snapshot. */
638
+ type SnapshotInfo$1 = {
639
+ id: string;
640
+ namespace: string;
641
+ /** Stored rows in the snapshot. */
642
+ records: number;
643
+ /** The namespace clock when it was taken, epoch ms. */
644
+ at: number;
645
+ /** Whether `GET /snapshots/:id` can return it as a {@link SnapshotDocument}. */
646
+ portable: boolean;
647
+ };
648
+
376
649
  /** Credential → namespace mapping behind `PUT /__admin/credentials`. */
377
650
  type CredentialRegistry$1 = {
378
651
  set(credential: string, namespace: string): void;
@@ -527,7 +800,10 @@ type ServiceInstance$1 = FetchAPI$2 & {
527
800
  };
528
801
  type ServiceTimelineState$1 = Readonly<{
529
802
  snapshot: NamespaceSnapshot$1;
530
- clock: Readonly<ReturnType<Clock$1["state"]>>;
803
+ /** `pinned`: the namespace's clock was frozen itself, not just following a frozen base. */
804
+ clock: Readonly<ClockState$1 & {
805
+ pinned?: boolean;
806
+ }>;
531
807
  rngState: number;
532
808
  }>;
533
809
  type ServiceCheckpoint$1 = Checkpoint$1<ServiceTimelineState$1>;
@@ -535,17 +811,23 @@ type ServiceRuntime$1<T extends ServiceInstance$1> = FetchAPI$2 & {
535
811
  /** Stop package-owned lifecycle timers when a supervisor closes the runtime. */
536
812
  stop?(): void;
537
813
  readonly name: string;
814
+ /** Same-origin Fetch handler and App Router method exports, sharing this runtime. */
815
+ mount(prefix: string): MountedAPI$1;
538
816
  readonly sqlite: SqliteClient$2;
539
817
  readonly clock: Clock$1;
540
818
  readonly faults: FaultRegistry$1;
819
+ /** Baseline response time per namespace. */
820
+ readonly latency: LatencyRegistry$1;
541
821
  readonly metrics: Metrics$1;
542
822
  readonly journal: Journal$1;
543
823
  readonly rng: Rng$1;
544
824
  readonly credentials: CredentialRegistry$1;
545
825
  /** The webhook hub, when the service has outbound webhooks. */
546
826
  readonly webhooks: WebhookHub$1 | undefined;
547
- /** Enable independent namespace clocks and PRNGs before serving a fleet. */
548
- isolateNamespaces(): void;
827
+ /**
828
+ * A namespace's clock. Each follows the base clock, {@link ServiceRuntime.clock}, with an
829
+ * offset and a freeze of its own, so moving one never moves another.
830
+ */
549
831
  namespaceClock(namespace?: string): Clock$1;
550
832
  namespaceOf(request: Request): string;
551
833
  /** Opaque in-process checkpoint including records, controls and webhook history. */
@@ -557,8 +839,38 @@ type ServiceRuntime$1<T extends ServiceInstance$1> = FetchAPI$2 & {
557
839
  instance(namespace?: string): T;
558
840
  /** Public names of every namespace created so far. */
559
841
  namespaces(): string[];
560
- /** Reset one namespace, or every namespace with `"*"`. */
842
+ /** Return one namespace to its boot state, or every namespace with `"*"`. */
561
843
  reset(namespace?: string): Promise<void>;
844
+ /** Reset a namespace and forget it, releasing everything it held. */
845
+ dropNamespace(namespace: string): Promise<void>;
846
+ /** A namespace's controls: seed, clock, virtual time, latency, faults and snapshots. */
847
+ controls(namespace?: string): ControlState$1 & {
848
+ snapshots: SnapshotInfo$1[];
849
+ };
850
+ /** Apply a control document to a namespace. A given key replaces that control. */
851
+ configure(controls: NamespaceControls$1, namespace?: string): ControlState$1 & {
852
+ snapshots: SnapshotInfo$1[];
853
+ };
854
+ /** Named snapshots of a namespace: records, clock, random streams, faults and latency. */
855
+ readonly snapshots: {
856
+ /** Capture the namespace now. Reusing a name replaces that snapshot. */
857
+ create(options?: {
858
+ name?: string;
859
+ namespace?: string;
860
+ }): SnapshotInfo$1;
861
+ list(namespace?: string): SnapshotInfo$1[];
862
+ /** The snapshot as portable JSON, to commit beside a suite or boot another mock from. */
863
+ export(id: string, namespace?: string): SnapshotDocument$1;
864
+ /** Store a document as a snapshot without restoring it. */
865
+ import(document: SnapshotDocument$1, options?: {
866
+ name?: string;
867
+ namespace?: string;
868
+ }): SnapshotInfo$1;
869
+ restore(id: string, namespace?: string): void;
870
+ delete(id: string, namespace?: string): boolean;
871
+ };
872
+ /** Request headers that carry controls, checked: spread them into a `fetch` or an SDK's defaults. */
873
+ headers(input: ControlHeaderInput$1): Record<string, string>;
562
874
  snapshot(namespace?: string): NamespaceSnapshot$1;
563
875
  restore(snapshot: NamespaceSnapshot$1, namespace?: string): void;
564
876
  /** Capture the current branch. Mutating HTTP calls do this automatically. */
@@ -601,6 +913,11 @@ type CommonServeOptions = {
601
913
  adminKey: string | undefined;
602
914
  seed: string | undefined;
603
915
  onLog: ((entry: RequestLog$1) => void) | undefined;
916
+ /** Admin controls to boot with: clock, latency, faults, a starting snapshot. */
917
+ adminControls?: MockControls$1;
918
+ /** Synthetic provider fixture objects supplied by a fleet entry. */
919
+ fixtures?: Record<string, unknown>;
920
+ baseUrl?: string;
604
921
  };
605
922
  /**
606
923
  * What a service contributes to `serve`: how to build its runtime from CLI flags,
@@ -629,76 +946,16 @@ interface FetchAPI$1 {
629
946
  fetch(request: Request): Promise<Response>;
630
947
  }
631
948
 
632
- /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
633
- type SqliteValue$1 = null | number | bigint | string | Uint8Array | boolean;
634
- /** Mutation counters returned by {@link SqliteStatement.run}. */
635
- type SqliteRunResult$1 = {
636
- changes: number;
637
- lastInsertRowid: number | bigint;
949
+ type MountedAPI = FetchAPI & {
950
+ readonly prefix: string;
951
+ GET: FetchHandler;
952
+ POST: FetchHandler;
953
+ PUT: FetchHandler;
954
+ PATCH: FetchHandler;
955
+ DELETE: FetchHandler;
956
+ HEAD: FetchHandler;
957
+ OPTIONS: FetchHandler;
638
958
  };
639
- /**
640
- * Prepared statement bound to a {@link SqliteClient}.
641
- *
642
- * Pass bind values as rest arguments on each call (no sticky `bind()`).
643
- */
644
- interface SqliteStatement$1 {
645
- run(...params: SqliteValue$1[]): SqliteRunResult$1;
646
- all<T = Record<string, unknown>>(...params: SqliteValue$1[]): T[];
647
- get<T = Record<string, unknown>>(...params: SqliteValue$1[]): T | undefined;
648
- }
649
- /**
650
- * Sync SQLite client port owned by Mockingbird.
651
- *
652
- * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
653
- * `bun:sqlite` instances all work when they expose this surface.
654
- */
655
- interface SqliteClient$1 {
656
- exec(sql: string): void;
657
- prepare(sql: string): SqliteStatement$1;
658
- transaction<T>(fn: () => T): T;
659
- }
660
-
661
- /** Every stored record carries a monotonically increasing sequence for stable ordering. */
662
- type Stored<T> = {
663
- seq: number;
664
- value: T;
665
- };
666
- type ListRecordsOptions<T> = {
667
- /** Keep only records passing the predicate. */
668
- where?: (value: T, seq: number) => boolean;
669
- /** Sort order; default newest first. */
670
- order?: "newest" | "oldest";
671
- };
672
- /**
673
- * A SQLite-backed table of JSON records addressed by id. Ordering is by insertion
674
- * sequence, never by id lexicographic order, so list semantics stay stable.
675
- */
676
- declare class Collection<T> {
677
- private readonly sqlite;
678
- /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
679
- readonly namespace: string;
680
- /** Table name inside the namespace. Stable across resets of the rows themselves. */
681
- readonly collectionName: string;
682
- constructor(sqlite: SqliteClient$1,
683
- /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
684
- namespace: string,
685
- /** Table name inside the namespace. Stable across resets of the rows themselves. */
686
- collectionName: string);
687
- private bumpCollectionSeq;
688
- nextSequence(): number;
689
- get(id: string): T | undefined;
690
- has(id: string): boolean;
691
- /** Insert a new record, assigning it the next sequence number. */
692
- insert(id: string, value: T): Stored<T>;
693
- /** Replace an existing record's value, keeping its position. */
694
- update(id: string, value: T): Stored<T> | undefined;
695
- delete(id: string): boolean;
696
- /** How many records the collection holds, without reading them. */
697
- count(): number;
698
- list(options?: ListRecordsOptions<T>): Array<Stored<T> & {
699
- id: string;
700
- }>;
701
- }
702
959
 
703
960
  /** A stable identifier for a point in a {@link Timeline}. */
704
961
  type CheckpointId = string;
@@ -789,6 +1046,79 @@ declare class Timeline<T> {
789
1046
  interface FetchAPI {
790
1047
  fetch(request: Request): Promise<Response>;
791
1048
  }
1049
+ /** A bare function form of {@link FetchAPI}, compatible with `Bun.serve`, workerd, and Deno. */
1050
+ type FetchHandler = (request: Request) => Promise<Response>;
1051
+
1052
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
1053
+ type SqliteValue$1 = null | number | bigint | string | Uint8Array | boolean;
1054
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
1055
+ type SqliteRunResult$1 = {
1056
+ changes: number;
1057
+ lastInsertRowid: number | bigint;
1058
+ };
1059
+ /**
1060
+ * Prepared statement bound to a {@link SqliteClient}.
1061
+ *
1062
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
1063
+ */
1064
+ interface SqliteStatement$1 {
1065
+ run(...params: SqliteValue$1[]): SqliteRunResult$1;
1066
+ all<T = Record<string, unknown>>(...params: SqliteValue$1[]): T[];
1067
+ get<T = Record<string, unknown>>(...params: SqliteValue$1[]): T | undefined;
1068
+ }
1069
+ /**
1070
+ * Sync SQLite client port owned by Mockingbird.
1071
+ *
1072
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
1073
+ * `bun:sqlite` instances all work when they expose this surface.
1074
+ */
1075
+ interface SqliteClient$1 {
1076
+ exec(sql: string): void;
1077
+ prepare(sql: string): SqliteStatement$1;
1078
+ transaction<T>(fn: () => T): T;
1079
+ }
1080
+
1081
+ /** Every stored record carries a monotonically increasing sequence for stable ordering. */
1082
+ type Stored<T> = {
1083
+ seq: number;
1084
+ value: T;
1085
+ };
1086
+ type ListRecordsOptions<T> = {
1087
+ /** Keep only records passing the predicate. */
1088
+ where?: (value: T, seq: number) => boolean;
1089
+ /** Sort order; default newest first. */
1090
+ order?: "newest" | "oldest";
1091
+ };
1092
+ /**
1093
+ * A SQLite-backed table of JSON records addressed by id. Ordering is by insertion
1094
+ * sequence, never by id lexicographic order, so list semantics stay stable.
1095
+ */
1096
+ declare class Collection<T> {
1097
+ private readonly sqlite;
1098
+ /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
1099
+ readonly namespace: string;
1100
+ /** Table name inside the namespace. Stable across resets of the rows themselves. */
1101
+ readonly collectionName: string;
1102
+ constructor(sqlite: SqliteClient$1,
1103
+ /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
1104
+ namespace: string,
1105
+ /** Table name inside the namespace. Stable across resets of the rows themselves. */
1106
+ collectionName: string);
1107
+ private bumpCollectionSeq;
1108
+ nextSequence(): number;
1109
+ get(id: string): T | undefined;
1110
+ has(id: string): boolean;
1111
+ /** Insert a new record, assigning it the next sequence number. */
1112
+ insert(id: string, value: T): Stored<T>;
1113
+ /** Replace an existing record's value, keeping its position. */
1114
+ update(id: string, value: T): Stored<T> | undefined;
1115
+ delete(id: string): boolean;
1116
+ /** How many records the collection holds, without reading them. */
1117
+ count(): number;
1118
+ list(options?: ListRecordsOptions<T>): Array<Stored<T> & {
1119
+ id: string;
1120
+ }>;
1121
+ }
792
1122
 
793
1123
  /**
794
1124
  * The slice of OpenAPI 3.1 (and JSON Schema 2020-12) Mockingbird understands.
@@ -980,7 +1310,7 @@ type ClockState = {
980
1310
  now: number;
981
1311
  /** True while time does not advance on its own. */
982
1312
  frozen: boolean;
983
- /** Milliseconds this clock adds to its underlying source. */
1313
+ /** Milliseconds a running clock adds to its underlying source. `0` while frozen. */
984
1314
  offsetMs: number;
985
1315
  };
986
1316
  type Clock = {
@@ -1016,7 +1346,10 @@ type Rng = {
1016
1346
  state(): number;
1017
1347
  /** Restore a state previously returned by {@link state}. */
1018
1348
  setState(state: number): void;
1019
- seed: number;
1349
+ /** Restart the stream from a new seed. `reset` then returns to this seed. */
1350
+ reseed(seed: number | string): void;
1351
+ /** The seed the stream currently starts from. */
1352
+ readonly seed: number;
1020
1353
  };
1021
1354
 
1022
1355
  /**
@@ -1025,44 +1358,83 @@ type Rng = {
1025
1358
  * This is how a suite reaches the vendor's failure modes without the vendor: the
1026
1359
  * quota error that only appears when a shared sandbox is full, the 429 that only
1027
1360
  * appears under load, the 5xx that proves a retry path works.
1361
+ *
1362
+ * A rule has three parts. What it **matches** (`operationId`, `method`, `path`, …), **when**
1363
+ * it fires among the matching requests (`after`, `every`, `count`, `rate`, `from`, `until`),
1364
+ * and what it **does** (`status`, `delay`, `timeout`, `drop`, `truncate`, `effect`).
1028
1365
  */
1029
1366
  type FaultRule = {
1030
- /** Stable id, so a suite can retire exactly the rule it added. */
1367
+ /** Stable id, so a suite can retire exactly the rule it added. Unique within a namespace. */
1031
1368
  id: string;
1032
1369
  /** Fault only this operation. Omit to match every operation. */
1033
1370
  operationId?: string;
1034
1371
  /** Fault only this HTTP method, case-insensitive. Omit to match every method. */
1035
1372
  method?: string;
1373
+ /** Fault only this exact path. */
1374
+ path?: string;
1036
1375
  /** Fault only paths starting with this prefix. Omit to match every path. */
1037
1376
  pathPrefix?: string;
1377
+ /** Fault only paths matching this regular expression (JavaScript syntax, unanchored). */
1378
+ pathPattern?: string;
1379
+ /** Fault only requests carrying these headers. `"*"` matches any value. */
1380
+ requestHeaders?: Record<string, string>;
1381
+ /** Fault only requests carrying these query parameters. `"*"` matches any value. */
1382
+ query?: Record<string, string>;
1038
1383
  /**
1039
1384
  * Fault only this namespace. Omit (or `"*"`) to fault every namespace — which is what
1040
1385
  * an in-process caller usually wants, and what a parallel worker usually does not:
1041
1386
  * rules added through `POST /__admin/faults` default to the calling namespace.
1042
1387
  */
1043
1388
  namespace?: string;
1389
+ /** Let this many matching requests through first. */
1390
+ after?: number;
1391
+ /** Then fault only every nth matching request: `3` faults the 3rd, 6th, 9th. */
1392
+ every?: number;
1393
+ /** Retire the rule after this many faults. Omit to keep it until removed. */
1394
+ count?: number;
1395
+ /** Fault this fraction of the remaining requests, `0`–`1`, drawn from the seed. Default `1`. */
1396
+ rate?: number;
1397
+ /**
1398
+ * Fault only from this instant on the namespace clock. A duration (`"5m"`) counts from the
1399
+ * clock when the rule was added. Listed as epoch ms.
1400
+ */
1401
+ from?: Instant | Duration;
1402
+ /** Stop faulting at this instant on the namespace clock. A duration counts from when added. */
1403
+ until?: Instant | Duration;
1044
1404
  /**
1045
- * Status of the injected response. Omit for a rule that only delays (`delayMs` /
1046
- * `latencyMs`), only drops the connection (`drop`), or only switches on an `effect`:
1047
- * the request then still reaches the service.
1405
+ * Status of the injected response. Omit for a rule that only delays, times out, drops,
1406
+ * truncates, or switches on an `effect`: the request then still reaches the service.
1048
1407
  */
1049
1408
  status?: number;
1050
1409
  /** Response body, serialized as JSON. A string is sent as-is. */
1051
1410
  body?: unknown;
1411
+ /** Response headers. */
1052
1412
  headers?: Record<string, string>;
1053
- /** Retire the rule after this many faults. Omit to keep it until removed. */
1054
- count?: number;
1055
- /** Fault this fraction of matching requests, `0`–`1`. Default `1`. */
1056
- rate?: number;
1057
- /** Hold the response back this long, to exercise timeouts. */
1413
+ /** Hold the response back this long. Listed as `delayMs`. */
1414
+ delay?: Duration;
1415
+ /** `delay`, in milliseconds. */
1058
1416
  delayMs?: number;
1059
1417
  /** Alias of `delayMs`. */
1060
1418
  latencyMs?: number;
1419
+ /** Extra seeded delay in `[0, jitter]`. Listed as `jitterMs`. */
1420
+ jitter?: Duration;
1421
+ jitterMs?: number;
1422
+ /**
1423
+ * Never answer: hold the request this long, then drop the connection. Listed as
1424
+ * `timeoutMs`. With virtual time the wait is spent on the mock clock.
1425
+ */
1426
+ timeout?: Duration;
1427
+ timeoutMs?: number;
1061
1428
  /**
1062
1429
  * Drop the connection instead of answering: an in-process `fetch` rejects with a
1063
1430
  * `TypeError`, and a served mock destroys the socket. Models "unknown outcome" failures.
1064
1431
  */
1065
1432
  drop?: boolean;
1433
+ /**
1434
+ * Cut the response body off after this many bytes: the status and headers arrive, then
1435
+ * the connection dies mid-body.
1436
+ */
1437
+ truncate?: number;
1066
1438
  /**
1067
1439
  * A named service behaviour to switch on for the matching request instead of (or
1068
1440
  * before) a canned response, e.g. `created_but_500` or `numeric_tracking_id`. Services
@@ -1071,8 +1443,8 @@ type FaultRule = {
1071
1443
  effect?: string;
1072
1444
  /** Parameters for `effect`. */
1073
1445
  params?: Record<string, unknown>;
1074
- /** From the preset this rule was expanded from, if any. */
1075
- preset?: string;
1446
+ /** The preset this rule was expanded from, if any. */
1447
+ fromPreset?: string;
1076
1448
  };
1077
1449
  /** A fault that fired for one request. */
1078
1450
  type FaultHit = {
@@ -1080,6 +1452,10 @@ type FaultHit = {
1080
1452
  /** The injected response; absent when the rule only delays, drops, or sets an effect. */
1081
1453
  response?: Response;
1082
1454
  drop?: boolean;
1455
+ /** Set with `drop` when the rule held the request for its `timeout` first. */
1456
+ timeout?: boolean;
1457
+ /** Bytes of response body to let through before the connection dies. */
1458
+ truncate?: number;
1083
1459
  effect?: {
1084
1460
  name: string;
1085
1461
  params: Record<string, unknown>;
@@ -1104,38 +1480,200 @@ type FaultCandidate = {
1104
1480
  method: string;
1105
1481
  path: string;
1106
1482
  namespace: string;
1483
+ /** Request headers and query, for rules that match on them. */
1484
+ headers?: Headers;
1485
+ query?: URLSearchParams;
1486
+ /** The namespace clock, for `from` / `until`. Rules with a window are skipped without it. */
1487
+ now?: number;
1488
+ /** How to spend a delay for this request. Default: the registry's own sleep. */
1489
+ wait?: (ms: number) => Promise<void>;
1490
+ };
1491
+ /** A stored rule and how often it was consulted. */
1492
+ type FaultListing = FaultRule & {
1493
+ /** Faults left before the rule retires. `null` when it has no `count`. */
1494
+ remaining: number | null;
1495
+ /** Times the rule faulted a request. */
1496
+ hits: number;
1497
+ /** Requests that matched the rule, faulted or not. */
1498
+ seen: number;
1499
+ };
1500
+ /** A namespace's own rules, with their counters, in the order they are tried. */
1501
+ type FaultSnapshot = {
1502
+ /**
1503
+ * `position` is how many `"*"` rules are tried before the rule, which is what its place
1504
+ * in the order means to a request and holds in any process.
1505
+ */
1506
+ rules: (FaultListing & {
1507
+ position?: number;
1508
+ })[];
1509
+ /** How many `fault_<n>` ids the namespace has handed out. */
1510
+ nextId?: number;
1107
1511
  };
1108
1512
  type FaultRegistry = {
1109
- isolateNamespaces(): void;
1110
- snapshot(namespace: string): {
1111
- rules: (FaultRule & {
1112
- remaining: number | null;
1113
- hits: number;
1114
- position: number;
1115
- })[];
1116
- rngState: number;
1117
- };
1513
+ snapshot(namespace: string): FaultSnapshot;
1514
+ /** Add a rule, or replace the rule with the same id in the same namespace. */
1118
1515
  add(rule: FaultRule): FaultRule;
1119
- list(): (FaultRule & {
1120
- remaining: number | null;
1121
- hits: number;
1122
- })[];
1123
- remove(id: string): boolean;
1124
- clear(): void;
1125
- restore(namespace: string, state: {
1126
- rules: (FaultRule & {
1127
- remaining: number | null;
1128
- hits: number;
1129
- position: number;
1130
- })[];
1131
- rngState: number;
1132
- }): void;
1516
+ /** The next unused `fault_<n>` id in `namespace`. */
1517
+ nextId(namespace: string): string;
1518
+ /** Every rule, or the rules a namespace's requests can hit: its own and the global ones. */
1519
+ list(namespace?: string): FaultListing[];
1520
+ get(id: string, namespace?: string): FaultListing | undefined;
1521
+ /** Remove a rule by id: from `namespace` (its own, then a global one), or wherever it is. */
1522
+ remove(id: string, namespace?: string): boolean;
1523
+ /** Remove every rule, or one namespace's own rules. */
1524
+ clear(namespace?: string): void;
1525
+ /** Replace a namespace's own rules with a snapshot's, wherever the snapshot was taken. */
1526
+ restore(namespace: string, state: FaultSnapshot): void;
1133
1527
  /**
1134
1528
  * Every fault this request should get, in rule order, stopping at the first that answers
1135
1529
  * or drops (effect-only and delay-only rules let later rules match too). Consumes one of
1136
1530
  * each matching rule's remaining uses.
1137
1531
  */
1138
1532
  take(candidate: FaultCandidate): Promise<FaultHit[]>;
1533
+ /**
1534
+ * Fire these rules at one request without storing them: no matching, no schedule, in order,
1535
+ * stopping at the first that answers or drops. Jitter draws from the namespace's stream.
1536
+ */
1537
+ fire(rules: readonly FaultRule[], candidate: FaultCandidate): Promise<FaultHit[]>;
1538
+ };
1539
+
1540
+ /**
1541
+ * The admin controls every mock shares, as one document.
1542
+ *
1543
+ * The same shape is accepted in three places, and means the same thing in each:
1544
+ *
1545
+ * - at boot: `createRuntime({ adminControls })`, `serve --admin-controls`,
1546
+ * `MOCKINGBIRD_ADMIN_CONTROLS`
1547
+ * - over HTTP: `PUT /__admin/controls`
1548
+ * - per request: the `x-mockingbird-*` headers in {@link CONTROL_HEADERS}
1549
+ *
1550
+ * Every control is deterministic: given the same seed, clock and requests, a mock answers
1551
+ * the same bytes. Nothing here reads the wall clock or `Math.random`.
1552
+ */
1553
+ /** Milliseconds, or a string like `"250ms"`, `"2s"`, `"15m"`, `"1h"`, `"3d"`. */
1554
+ type Duration = number | string;
1555
+ /** Epoch milliseconds, or an ISO-8601 string. */
1556
+ type Instant = number | string;
1557
+ type ClockControls = {
1558
+ /** Move the clock to this instant. */
1559
+ now?: Instant;
1560
+ /** Stop time. A frozen clock moves only when told to, so timestamps replay exactly. */
1561
+ frozen?: boolean;
1562
+ /**
1563
+ * Step the clock forward by this much before every vendor request. With a frozen clock
1564
+ * each request still gets its own, reproducible timestamp.
1565
+ */
1566
+ autoAdvance?: Duration;
1567
+ };
1568
+ /** How long a response takes: a fixed delay plus seeded jitter in `[0, jitter]`. */
1569
+ type LatencyRuleInput = {
1570
+ delay?: Duration;
1571
+ jitter?: Duration;
1572
+ };
1573
+ type LatencyControls = LatencyRuleInput & {
1574
+ /** Per-operation overrides, keyed by operationId. A bare duration is its `delay`. */
1575
+ operations?: Record<string, Duration | LatencyRuleInput>;
1576
+ };
1577
+ /** A fault to add: a rule (the id is assigned when omitted), or a named preset with overrides. */
1578
+ type FaultInput = (Omit<FaultRule, "id"> & {
1579
+ id?: string;
1580
+ }) | ({
1581
+ preset: string;
1582
+ } & Partial<FaultRule>);
1583
+ /** Identifies a {@link SnapshotDocument}. */
1584
+ declare const SNAPSHOT_FORMAT = "mockingbird.snapshot/v1";
1585
+ /**
1586
+ * A namespace, as portable JSON: what `GET /__admin/snapshots/:id` returns and what
1587
+ * `PUT /__admin/snapshots/:id` and the boot `snapshot` control accept. Only `format` and
1588
+ * `records` are required, so a hand-written seed file is a valid snapshot.
1589
+ */
1590
+ type SnapshotDocument = {
1591
+ format: typeof SNAPSHOT_FORMAT;
1592
+ /** The service that wrote it. A snapshot is rejected by any other service. */
1593
+ service?: string;
1594
+ /**
1595
+ * Stored rows. `seq` orders a collection; omitted, rows keep their listed order. `raw` is
1596
+ * the stored text of a row that is not a plain record, and replaces `value` when present.
1597
+ */
1598
+ records: {
1599
+ collection: string;
1600
+ id: string;
1601
+ seq?: number;
1602
+ value?: unknown;
1603
+ raw?: string;
1604
+ }[];
1605
+ /** Id counters, so the next generated id continues where the snapshot left off. */
1606
+ sequences?: {
1607
+ name: string;
1608
+ kind: string;
1609
+ value: number;
1610
+ }[];
1611
+ clock?: {
1612
+ now: number;
1613
+ frozen: boolean;
1614
+ autoAdvanceMs?: number;
1615
+ };
1616
+ seed?: number | string;
1617
+ /** Positions of the seeded random streams. */
1618
+ rng?: {
1619
+ state: number;
1620
+ faults?: number;
1621
+ latency?: number;
1622
+ };
1623
+ faults?: unknown;
1624
+ latency?: unknown;
1625
+ virtualTime?: boolean;
1626
+ };
1627
+ /** Controls for one namespace. */
1628
+ type NamespaceControls = {
1629
+ /** Seeds every random choice: fault rates, jitter, and whatever the service invents. */
1630
+ seed?: number | string;
1631
+ clock?: ClockControls;
1632
+ /**
1633
+ * Spend injected waits (latency, fault delays, timeouts) on the mock clock instead of the
1634
+ * wall clock: the request returns at once, the clock has moved, and the journal records
1635
+ * the wait exactly. Default `false`: waits are real, so a client's own timeout can fire.
1636
+ */
1637
+ virtualTime?: boolean;
1638
+ /** Baseline response time for every vendor request. A bare duration is its `delay`. */
1639
+ latency?: Duration | LatencyControls;
1640
+ faults?: readonly FaultInput[];
1641
+ /** Start from this state instead of the service's own seed data. */
1642
+ snapshot?: SnapshotDocument;
1643
+ };
1644
+ /** {@link NamespaceControls} for every namespace, with per-namespace overrides. */
1645
+ type MockControls = NamespaceControls & {
1646
+ /** Vendor credential → namespace, for SDKs that cannot send a namespace header. */
1647
+ credentials?: Record<string, string>;
1648
+ /** Overrides for named namespaces. A key given here replaces the shared value. */
1649
+ namespaces?: Record<string, NamespaceControls>;
1650
+ };
1651
+ /** A latency rule in milliseconds. */
1652
+ type LatencyRule = {
1653
+ delayMs: number;
1654
+ jitterMs: number;
1655
+ };
1656
+ /** Baseline latency for a namespace, normalized. */
1657
+ type LatencyState = LatencyRule & {
1658
+ operations: Record<string, LatencyRule>;
1659
+ };
1660
+ /** What {@link controlHeaders} turns into request headers. */
1661
+ type ControlHeaderInput = {
1662
+ namespace?: string;
1663
+ adminKey?: string;
1664
+ branch?: string;
1665
+ at?: string;
1666
+ reset?: boolean;
1667
+ restore?: string;
1668
+ seed?: number | string;
1669
+ time?: Instant | Date;
1670
+ advance?: Duration;
1671
+ virtualTime?: boolean;
1672
+ delay?: Duration;
1673
+ timeout?: Duration;
1674
+ /** A status, `"drop"`, a preset name, or a fault rule. */
1675
+ fault?: number | string | Record<string, unknown>;
1676
+ snapshot?: string;
1139
1677
  };
1140
1678
 
1141
1679
  /**
@@ -1175,6 +1713,8 @@ type RequestLog = {
1175
1713
  unmatched: boolean;
1176
1714
  /** Set when a fault rule produced the response. */
1177
1715
  faultId?: string;
1716
+ /** Milliseconds of injected wait: latency, fault delays and timeouts. Absent when none. */
1717
+ delayMs?: number;
1178
1718
  /** Resource ids the handler touched (`userId`, `orderId`, …), when the service reports them. */
1179
1719
  ids?: Record<string, string>;
1180
1720
  /** Set when the service created a resource the request referred to but that did not exist. */
@@ -1220,6 +1760,12 @@ type JournalQuery = {
1220
1760
  /** Only this namespace. Omit for every namespace, oldest first across all of them. */
1221
1761
  namespace?: string;
1222
1762
  operationId?: string;
1763
+ /** Only this HTTP method, case-insensitive. */
1764
+ method?: string;
1765
+ /** Only this exact path. */
1766
+ path?: string;
1767
+ /** Only requests this fault rule answered or shaped. */
1768
+ faultId?: string;
1223
1769
  status?: number;
1224
1770
  /** Only entries at or after this instant (epoch ms). */
1225
1771
  since?: number;
@@ -1234,6 +1780,38 @@ type Journal = {
1234
1780
  clear(namespace?: string): void;
1235
1781
  };
1236
1782
 
1783
+ /**
1784
+ * Baseline response time, per namespace: how long every vendor request takes before any
1785
+ * fault is considered. Jitter draws from a stream the caller owns, one per namespace and
1786
+ * separate from the fault stream, so adding latency never shifts which requests a `rate`
1787
+ * fault hits.
1788
+ */
1789
+ type LatencyRegistry = {
1790
+ get(namespace: string): LatencyState;
1791
+ set(namespace: string, state: LatencyState): LatencyState;
1792
+ /** Remove one namespace's latency, or every namespace's. */
1793
+ clear(namespace?: string): void;
1794
+ /** Milliseconds this request waits. Draws jitter, so call it once per request. */
1795
+ take(namespace: string, operationId: string | undefined): number;
1796
+ };
1797
+
1798
+ /** Clock state as the admin API reports it. */
1799
+ type ControlClock = ClockState & {
1800
+ /** `now`, as ISO-8601. */
1801
+ iso: string;
1802
+ /** Milliseconds the clock steps before every vendor request. */
1803
+ autoAdvanceMs: number;
1804
+ };
1805
+ /** One namespace's controls: the body of `GET /__admin/controls`. */
1806
+ type ControlState = {
1807
+ namespace: string;
1808
+ seed: number | string;
1809
+ clock: ControlClock;
1810
+ virtualTime: boolean;
1811
+ latency: LatencyState;
1812
+ faults: FaultListing[];
1813
+ };
1814
+
1237
1815
  type AdminRequest = {
1238
1816
  request: Request;
1239
1817
  url: URL;
@@ -1250,6 +1828,17 @@ type AdminRoute = (request: AdminRequest) => Response | Promise<Response>;
1250
1828
  * `:param` segments — e.g. `"POST /orders/:id/transition"`.
1251
1829
  */
1252
1830
  type AdminRoutes = Record<string, AdminRoute>;
1831
+ /** What `GET /__admin/snapshots` lists for each snapshot. */
1832
+ type SnapshotInfo = {
1833
+ id: string;
1834
+ namespace: string;
1835
+ /** Stored rows in the snapshot. */
1836
+ records: number;
1837
+ /** The namespace clock when it was taken, epoch ms. */
1838
+ at: number;
1839
+ /** Whether `GET /snapshots/:id` can return it as a {@link SnapshotDocument}. */
1840
+ portable: boolean;
1841
+ };
1253
1842
 
1254
1843
  /** Credential → namespace mapping behind `PUT /__admin/credentials`. */
1255
1844
  type CredentialRegistry = {
@@ -1494,14 +2083,26 @@ type RuntimeOptions<T extends ServiceInstance> = {
1494
2083
  sqlite?: SqliteClient$1;
1495
2084
  /** Defaults to a live clock over `Date.now`. */
1496
2085
  clock?: Clock;
1497
- /** Seeds every random choice the runtime makes (fault rates). Default `0`. */
2086
+ /** Seeds every random choice the runtime makes (fault rates, jitter). Default `0`. */
1498
2087
  seed?: number | string;
2088
+ /**
2089
+ * Admin controls to boot with: clock, latency, faults, a starting snapshot, credential
2090
+ * mappings and per-namespace overrides. `reset` returns a namespace to exactly this.
2091
+ */
2092
+ adminControls?: MockControls;
1499
2093
  /** Extra `GET /__admin/health` fields, such as the loaded corpus version. */
1500
2094
  describe?: () => Record<string, unknown>;
1501
2095
  /** Service-specific admin routes, given the runtime so they can reach any namespace. */
1502
2096
  admin?: (runtime: ServiceRuntime<T>) => AdminRoutes;
1503
2097
  /** Reserved tree for every internal HTTP endpoint, UI and namespace carrier. Default /__admin. */
1504
2098
  adminPrefix?: string;
2099
+ /**
2100
+ * A namespace's clock was moved — by `/__admin/clock`, a header, a restore, a reset, or a
2101
+ * wait spent in virtual time. Run whatever the service schedules by that clock, so what
2102
+ * came due is seen at once and not on the next request. Moving the base clock in process
2103
+ * (`runtime.clock`) is the caller's own doing and is not reported here.
2104
+ */
2105
+ onClockChange?: (namespace: string) => void;
1505
2106
  /** Invalidate transient handles before replacing an existing instance's stored state. */
1506
2107
  beforeRestore?: (instance: T) => void;
1507
2108
  /** Require this value in `x-mockingbird-admin-key` on admin data routes. */
@@ -1519,7 +2120,10 @@ type RuntimeOptions<T extends ServiceInstance> = {
1519
2120
  * `sigV4AccessKeyId`.
1520
2121
  */
1521
2122
  credential?: (request: Request) => string | undefined;
1522
- /** Named faults, switched on with `POST /__admin/faults {"preset": "<name>"}`. */
2123
+ /**
2124
+ * Named faults, switched on with `POST /__admin/faults {"preset": "<name>"}`. They join the
2125
+ * standard presets every mock has; one with a standard name replaces it.
2126
+ */
1523
2127
  presets?: Record<string, FaultPreset>;
1524
2128
  /** Outbound webhooks; adds the `/__admin/webhooks*` routes and clears on reset. */
1525
2129
  webhooks?: WebhookHub;
@@ -1542,11 +2146,15 @@ type RuntimeOptions<T extends ServiceInstance> = {
1542
2146
  type RuntimeIO = {
1543
2147
  wallNow(): number;
1544
2148
  monotonicNow(): number;
1545
- sleep(ms: number): Promise<void>;
2149
+ /** Wait on the wall clock. Rejects with the signal's reason when it aborts first. */
2150
+ sleep(ms: number, signal?: AbortSignal): Promise<void>;
1546
2151
  };
1547
2152
  type ServiceTimelineState = Readonly<{
1548
2153
  snapshot: NamespaceSnapshot;
1549
- clock: Readonly<ReturnType<Clock["state"]>>;
2154
+ /** `pinned`: the namespace's clock was frozen itself, not just following a frozen base. */
2155
+ clock: Readonly<ClockState & {
2156
+ pinned?: boolean;
2157
+ }>;
1550
2158
  rngState: number;
1551
2159
  }>;
1552
2160
  type ServiceCheckpoint = Checkpoint<ServiceTimelineState>;
@@ -1554,17 +2162,23 @@ type ServiceRuntime<T extends ServiceInstance> = FetchAPI & {
1554
2162
  /** Stop package-owned lifecycle timers when a supervisor closes the runtime. */
1555
2163
  stop?(): void;
1556
2164
  readonly name: string;
2165
+ /** Same-origin Fetch handler and App Router method exports, sharing this runtime. */
2166
+ mount(prefix: string): MountedAPI;
1557
2167
  readonly sqlite: SqliteClient$1;
1558
2168
  readonly clock: Clock;
1559
2169
  readonly faults: FaultRegistry;
2170
+ /** Baseline response time per namespace. */
2171
+ readonly latency: LatencyRegistry;
1560
2172
  readonly metrics: Metrics;
1561
2173
  readonly journal: Journal;
1562
2174
  readonly rng: Rng;
1563
2175
  readonly credentials: CredentialRegistry;
1564
2176
  /** The webhook hub, when the service has outbound webhooks. */
1565
2177
  readonly webhooks: WebhookHub | undefined;
1566
- /** Enable independent namespace clocks and PRNGs before serving a fleet. */
1567
- isolateNamespaces(): void;
2178
+ /**
2179
+ * A namespace's clock. Each follows the base clock, {@link ServiceRuntime.clock}, with an
2180
+ * offset and a freeze of its own, so moving one never moves another.
2181
+ */
1568
2182
  namespaceClock(namespace?: string): Clock;
1569
2183
  namespaceOf(request: Request): string;
1570
2184
  /** Opaque in-process checkpoint including records, controls and webhook history. */
@@ -1576,8 +2190,38 @@ type ServiceRuntime<T extends ServiceInstance> = FetchAPI & {
1576
2190
  instance(namespace?: string): T;
1577
2191
  /** Public names of every namespace created so far. */
1578
2192
  namespaces(): string[];
1579
- /** Reset one namespace, or every namespace with `"*"`. */
2193
+ /** Return one namespace to its boot state, or every namespace with `"*"`. */
1580
2194
  reset(namespace?: string): Promise<void>;
2195
+ /** Reset a namespace and forget it, releasing everything it held. */
2196
+ dropNamespace(namespace: string): Promise<void>;
2197
+ /** A namespace's controls: seed, clock, virtual time, latency, faults and snapshots. */
2198
+ controls(namespace?: string): ControlState & {
2199
+ snapshots: SnapshotInfo[];
2200
+ };
2201
+ /** Apply a control document to a namespace. A given key replaces that control. */
2202
+ configure(controls: NamespaceControls, namespace?: string): ControlState & {
2203
+ snapshots: SnapshotInfo[];
2204
+ };
2205
+ /** Named snapshots of a namespace: records, clock, random streams, faults and latency. */
2206
+ readonly snapshots: {
2207
+ /** Capture the namespace now. Reusing a name replaces that snapshot. */
2208
+ create(options?: {
2209
+ name?: string;
2210
+ namespace?: string;
2211
+ }): SnapshotInfo;
2212
+ list(namespace?: string): SnapshotInfo[];
2213
+ /** The snapshot as portable JSON, to commit beside a suite or boot another mock from. */
2214
+ export(id: string, namespace?: string): SnapshotDocument;
2215
+ /** Store a document as a snapshot without restoring it. */
2216
+ import(document: SnapshotDocument, options?: {
2217
+ name?: string;
2218
+ namespace?: string;
2219
+ }): SnapshotInfo;
2220
+ restore(id: string, namespace?: string): void;
2221
+ delete(id: string, namespace?: string): boolean;
2222
+ };
2223
+ /** Request headers that carry controls, checked: spread them into a `fetch` or an SDK's defaults. */
2224
+ headers(input: ControlHeaderInput): Record<string, string>;
1581
2225
  snapshot(namespace?: string): NamespaceSnapshot;
1582
2226
  restore(snapshot: NamespaceSnapshot, namespace?: string): void;
1583
2227
  /** Capture the current branch. Mutating HTTP calls do this automatically. */
@@ -1719,7 +2363,7 @@ declare class DockerLifecycle {
1719
2363
  cancelWaits(): void;
1720
2364
  }
1721
2365
 
1722
- type DockerRuntimeOptions = Pick<RuntimeOptions<DockerAPI>, "sqlite" | "clock" | "seed" | "adminKey" | "onLog" | "journalSize" | "maxCheckpoints"> & Pick<DockerAPIOptions, "onAttach">;
2366
+ type DockerRuntimeOptions = Pick<RuntimeOptions<DockerAPI>, "sqlite" | "clock" | "seed" | "adminKey" | "adminControls" | "onLog" | "journalSize" | "maxCheckpoints"> & Pick<DockerAPIOptions, "onAttach">;
1723
2367
  type DockerRuntime = ServiceRuntime<DockerAPI> & {
1724
2368
  close(): void;
1725
2369
  };