@crvouga/mockingbird-service-step-functions 3.1.0 → 3.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,33 +1,15 @@
1
1
  import { Server } from 'node:http';
2
2
 
3
- /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
4
- type SqliteValue$2 = null | number | bigint | string | Uint8Array | boolean;
5
- /** Mutation counters returned by {@link SqliteStatement.run}. */
6
- type SqliteRunResult$2 = {
7
- changes: number;
8
- lastInsertRowid: number | bigint;
3
+ type MountedAPI$1 = FetchAPI$1 & {
4
+ readonly prefix: string;
5
+ GET: FetchHandler$1;
6
+ POST: FetchHandler$1;
7
+ PUT: FetchHandler$1;
8
+ PATCH: FetchHandler$1;
9
+ DELETE: FetchHandler$1;
10
+ HEAD: FetchHandler$1;
11
+ OPTIONS: FetchHandler$1;
9
12
  };
10
- /**
11
- * Prepared statement bound to a {@link SqliteClient}.
12
- *
13
- * Pass bind values as rest arguments on each call (no sticky `bind()`).
14
- */
15
- interface SqliteStatement$2 {
16
- run(...params: SqliteValue$2[]): SqliteRunResult$2;
17
- all<T = Record<string, unknown>>(...params: SqliteValue$2[]): T[];
18
- get<T = Record<string, unknown>>(...params: SqliteValue$2[]): T | undefined;
19
- }
20
- /**
21
- * Sync SQLite client port owned by Mockingbird.
22
- *
23
- * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
24
- * `bun:sqlite` instances all work when they expose this surface.
25
- */
26
- interface SqliteClient$2 {
27
- exec(sql: string): void;
28
- prepare(sql: string): SqliteStatement$2;
29
- transaction<T>(fn: () => T): T;
30
- }
31
13
 
32
14
  /** A stable identifier for a point in a {@link Timeline}. */
33
15
  type CheckpointId$1 = string;
@@ -118,6 +100,37 @@ declare class Timeline$1<T> {
118
100
  interface FetchAPI$1 {
119
101
  fetch(request: Request): Promise<Response>;
120
102
  }
103
+ /** A bare function form of {@link FetchAPI}, compatible with `Bun.serve`, workerd, and Deno. */
104
+ type FetchHandler$1 = (request: Request) => Promise<Response>;
105
+
106
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
107
+ type SqliteValue$2 = null | number | bigint | string | Uint8Array | boolean;
108
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
109
+ type SqliteRunResult$2 = {
110
+ changes: number;
111
+ lastInsertRowid: number | bigint;
112
+ };
113
+ /**
114
+ * Prepared statement bound to a {@link SqliteClient}.
115
+ *
116
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
117
+ */
118
+ interface SqliteStatement$2 {
119
+ run(...params: SqliteValue$2[]): SqliteRunResult$2;
120
+ all<T = Record<string, unknown>>(...params: SqliteValue$2[]): T[];
121
+ get<T = Record<string, unknown>>(...params: SqliteValue$2[]): T | undefined;
122
+ }
123
+ /**
124
+ * Sync SQLite client port owned by Mockingbird.
125
+ *
126
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
127
+ * `bun:sqlite` instances all work when they expose this surface.
128
+ */
129
+ interface SqliteClient$2 {
130
+ exec(sql: string): void;
131
+ prepare(sql: string): SqliteStatement$2;
132
+ transaction<T>(fn: () => T): T;
133
+ }
121
134
 
122
135
  /**
123
136
  * The single source of time for a service.
@@ -131,7 +144,7 @@ type ClockState$1 = {
131
144
  now: number;
132
145
  /** True while time does not advance on its own. */
133
146
  frozen: boolean;
134
- /** Milliseconds this clock adds to its underlying source. */
147
+ /** Milliseconds a running clock adds to its underlying source. `0` while frozen. */
135
148
  offsetMs: number;
136
149
  };
137
150
  type Clock$1 = {
@@ -167,7 +180,10 @@ type Rng$1 = {
167
180
  state(): number;
168
181
  /** Restore a state previously returned by {@link state}. */
169
182
  setState(state: number): void;
170
- seed: number;
183
+ /** Restart the stream from a new seed. `reset` then returns to this seed. */
184
+ reseed(seed: number | string): void;
185
+ /** The seed the stream currently starts from. */
186
+ readonly seed: number;
171
187
  };
172
188
 
173
189
  /**
@@ -176,44 +192,83 @@ type Rng$1 = {
176
192
  * This is how a suite reaches the vendor's failure modes without the vendor: the
177
193
  * quota error that only appears when a shared sandbox is full, the 429 that only
178
194
  * appears under load, the 5xx that proves a retry path works.
195
+ *
196
+ * A rule has three parts. What it **matches** (`operationId`, `method`, `path`, …), **when**
197
+ * it fires among the matching requests (`after`, `every`, `count`, `rate`, `from`, `until`),
198
+ * and what it **does** (`status`, `delay`, `timeout`, `drop`, `truncate`, `effect`).
179
199
  */
180
200
  type FaultRule$1 = {
181
- /** Stable id, so a suite can retire exactly the rule it added. */
201
+ /** Stable id, so a suite can retire exactly the rule it added. Unique within a namespace. */
182
202
  id: string;
183
203
  /** Fault only this operation. Omit to match every operation. */
184
204
  operationId?: string;
185
205
  /** Fault only this HTTP method, case-insensitive. Omit to match every method. */
186
206
  method?: string;
207
+ /** Fault only this exact path. */
208
+ path?: string;
187
209
  /** Fault only paths starting with this prefix. Omit to match every path. */
188
210
  pathPrefix?: string;
211
+ /** Fault only paths matching this regular expression (JavaScript syntax, unanchored). */
212
+ pathPattern?: string;
213
+ /** Fault only requests carrying these headers. `"*"` matches any value. */
214
+ requestHeaders?: Record<string, string>;
215
+ /** Fault only requests carrying these query parameters. `"*"` matches any value. */
216
+ query?: Record<string, string>;
189
217
  /**
190
218
  * Fault only this namespace. Omit (or `"*"`) to fault every namespace — which is what
191
219
  * an in-process caller usually wants, and what a parallel worker usually does not:
192
220
  * rules added through `POST /__admin/faults` default to the calling namespace.
193
221
  */
194
222
  namespace?: string;
223
+ /** Let this many matching requests through first. */
224
+ after?: number;
225
+ /** Then fault only every nth matching request: `3` faults the 3rd, 6th, 9th. */
226
+ every?: number;
227
+ /** Retire the rule after this many faults. Omit to keep it until removed. */
228
+ count?: number;
229
+ /** Fault this fraction of the remaining requests, `0`–`1`, drawn from the seed. Default `1`. */
230
+ rate?: number;
195
231
  /**
196
- * Status of the injected response. Omit for a rule that only delays (`delayMs` /
197
- * `latencyMs`), only drops the connection (`drop`), or only switches on an `effect`:
198
- * the request then still reaches the service.
232
+ * Fault only from this instant on the namespace clock. A duration (`"5m"`) counts from the
233
+ * clock when the rule was added. Listed as epoch ms.
234
+ */
235
+ from?: Instant$1 | Duration$1;
236
+ /** Stop faulting at this instant on the namespace clock. A duration counts from when added. */
237
+ until?: Instant$1 | Duration$1;
238
+ /**
239
+ * Status of the injected response. Omit for a rule that only delays, times out, drops,
240
+ * truncates, or switches on an `effect`: the request then still reaches the service.
199
241
  */
200
242
  status?: number;
201
243
  /** Response body, serialized as JSON. A string is sent as-is. */
202
244
  body?: unknown;
245
+ /** Response headers. */
203
246
  headers?: Record<string, string>;
204
- /** Retire the rule after this many faults. Omit to keep it until removed. */
205
- count?: number;
206
- /** Fault this fraction of matching requests, `0`–`1`. Default `1`. */
207
- rate?: number;
208
- /** Hold the response back this long, to exercise timeouts. */
247
+ /** Hold the response back this long. Listed as `delayMs`. */
248
+ delay?: Duration$1;
249
+ /** `delay`, in milliseconds. */
209
250
  delayMs?: number;
210
251
  /** Alias of `delayMs`. */
211
252
  latencyMs?: number;
253
+ /** Extra seeded delay in `[0, jitter]`. Listed as `jitterMs`. */
254
+ jitter?: Duration$1;
255
+ jitterMs?: number;
256
+ /**
257
+ * Never answer: hold the request this long, then drop the connection. Listed as
258
+ * `timeoutMs`. With virtual time the wait is spent on the mock clock.
259
+ */
260
+ timeout?: Duration$1;
261
+ timeoutMs?: number;
212
262
  /**
213
263
  * Drop the connection instead of answering: an in-process `fetch` rejects with a
214
264
  * `TypeError`, and a served mock destroys the socket. Models "unknown outcome" failures.
215
265
  */
216
266
  drop?: boolean;
267
+ /**
268
+ * Cut the response body off after this many bytes: the status and headers arrive, then
269
+ * the connection dies mid-body.
270
+ */
271
+ truncate?: number;
217
272
  /**
218
273
  * A named service behaviour to switch on for the matching request instead of (or
219
274
  * before) a canned response, e.g. `created_but_500` or `numeric_tracking_id`. Services
@@ -222,8 +277,8 @@ type FaultRule$1 = {
222
277
  effect?: string;
223
278
  /** Parameters for `effect`. */
224
279
  params?: Record<string, unknown>;
225
- /** From the preset this rule was expanded from, if any. */
226
- preset?: string;
280
+ /** The preset this rule was expanded from, if any. */
281
+ fromPreset?: string;
227
282
  };
228
283
  /** A fault that fired for one request. */
229
284
  type FaultHit$1 = {
@@ -231,6 +286,10 @@ type FaultHit$1 = {
231
286
  /** The injected response; absent when the rule only delays, drops, or sets an effect. */
232
287
  response?: Response;
233
288
  drop?: boolean;
289
+ /** Set with `drop` when the rule held the request for its `timeout` first. */
290
+ timeout?: boolean;
291
+ /** Bytes of response body to let through before the connection dies. */
292
+ truncate?: number;
234
293
  effect?: {
235
294
  name: string;
236
295
  params: Record<string, unknown>;
@@ -242,38 +301,200 @@ type FaultCandidate$1 = {
242
301
  method: string;
243
302
  path: string;
244
303
  namespace: string;
304
+ /** Request headers and query, for rules that match on them. */
305
+ headers?: Headers;
306
+ query?: URLSearchParams;
307
+ /** The namespace clock, for `from` / `until`. Rules with a window are skipped without it. */
308
+ now?: number;
309
+ /** How to spend a delay for this request. Default: the registry's own sleep. */
310
+ wait?: (ms: number) => Promise<void>;
311
+ };
312
+ /** A stored rule and how often it was consulted. */
313
+ type FaultListing$1 = FaultRule$1 & {
314
+ /** Faults left before the rule retires. `null` when it has no `count`. */
315
+ remaining: number | null;
316
+ /** Times the rule faulted a request. */
317
+ hits: number;
318
+ /** Requests that matched the rule, faulted or not. */
319
+ seen: number;
320
+ };
321
+ /** A namespace's own rules, with their counters, in the order they are tried. */
322
+ type FaultSnapshot$1 = {
323
+ /**
324
+ * `position` is how many `"*"` rules are tried before the rule, which is what its place
325
+ * in the order means to a request and holds in any process.
326
+ */
327
+ rules: (FaultListing$1 & {
328
+ position?: number;
329
+ })[];
330
+ /** How many `fault_<n>` ids the namespace has handed out. */
331
+ nextId?: number;
245
332
  };
246
333
  type FaultRegistry$1 = {
247
- isolateNamespaces(): void;
248
- snapshot(namespace: string): {
249
- rules: (FaultRule$1 & {
250
- remaining: number | null;
251
- hits: number;
252
- position: number;
253
- })[];
254
- rngState: number;
255
- };
334
+ snapshot(namespace: string): FaultSnapshot$1;
335
+ /** Add a rule, or replace the rule with the same id in the same namespace. */
256
336
  add(rule: FaultRule$1): FaultRule$1;
257
- list(): (FaultRule$1 & {
258
- remaining: number | null;
259
- hits: number;
260
- })[];
261
- remove(id: string): boolean;
262
- clear(): void;
263
- restore(namespace: string, state: {
264
- rules: (FaultRule$1 & {
265
- remaining: number | null;
266
- hits: number;
267
- position: number;
268
- })[];
269
- rngState: number;
270
- }): void;
337
+ /** The next unused `fault_<n>` id in `namespace`. */
338
+ nextId(namespace: string): string;
339
+ /** Every rule, or the rules a namespace's requests can hit: its own and the global ones. */
340
+ list(namespace?: string): FaultListing$1[];
341
+ get(id: string, namespace?: string): FaultListing$1 | undefined;
342
+ /** Remove a rule by id: from `namespace` (its own, then a global one), or wherever it is. */
343
+ remove(id: string, namespace?: string): boolean;
344
+ /** Remove every rule, or one namespace's own rules. */
345
+ clear(namespace?: string): void;
346
+ /** Replace a namespace's own rules with a snapshot's, wherever the snapshot was taken. */
347
+ restore(namespace: string, state: FaultSnapshot$1): void;
271
348
  /**
272
349
  * Every fault this request should get, in rule order, stopping at the first that answers
273
350
  * or drops (effect-only and delay-only rules let later rules match too). Consumes one of
274
351
  * each matching rule's remaining uses.
275
352
  */
276
353
  take(candidate: FaultCandidate$1): Promise<FaultHit$1[]>;
354
+ /**
355
+ * Fire these rules at one request without storing them: no matching, no schedule, in order,
356
+ * stopping at the first that answers or drops. Jitter draws from the namespace's stream.
357
+ */
358
+ fire(rules: readonly FaultRule$1[], candidate: FaultCandidate$1): Promise<FaultHit$1[]>;
359
+ };
360
+
361
+ /**
362
+ * The admin controls every mock shares, as one document.
363
+ *
364
+ * The same shape is accepted in three places, and means the same thing in each:
365
+ *
366
+ * - at boot: `createRuntime({ adminControls })`, `serve --admin-controls`,
367
+ * `MOCKINGBIRD_ADMIN_CONTROLS`
368
+ * - over HTTP: `PUT /__admin/controls`
369
+ * - per request: the `x-mockingbird-*` headers in {@link CONTROL_HEADERS}
370
+ *
371
+ * Every control is deterministic: given the same seed, clock and requests, a mock answers
372
+ * the same bytes. Nothing here reads the wall clock or `Math.random`.
373
+ */
374
+ /** Milliseconds, or a string like `"250ms"`, `"2s"`, `"15m"`, `"1h"`, `"3d"`. */
375
+ type Duration$1 = number | string;
376
+ /** Epoch milliseconds, or an ISO-8601 string. */
377
+ type Instant$1 = number | string;
378
+ type ClockControls$1 = {
379
+ /** Move the clock to this instant. */
380
+ now?: Instant$1;
381
+ /** Stop time. A frozen clock moves only when told to, so timestamps replay exactly. */
382
+ frozen?: boolean;
383
+ /**
384
+ * Step the clock forward by this much before every vendor request. With a frozen clock
385
+ * each request still gets its own, reproducible timestamp.
386
+ */
387
+ autoAdvance?: Duration$1;
388
+ };
389
+ /** How long a response takes: a fixed delay plus seeded jitter in `[0, jitter]`. */
390
+ type LatencyRuleInput$1 = {
391
+ delay?: Duration$1;
392
+ jitter?: Duration$1;
393
+ };
394
+ type LatencyControls$1 = LatencyRuleInput$1 & {
395
+ /** Per-operation overrides, keyed by operationId. A bare duration is its `delay`. */
396
+ operations?: Record<string, Duration$1 | LatencyRuleInput$1>;
397
+ };
398
+ /** A fault to add: a rule (the id is assigned when omitted), or a named preset with overrides. */
399
+ type FaultInput$1 = (Omit<FaultRule$1, "id"> & {
400
+ id?: string;
401
+ }) | ({
402
+ preset: string;
403
+ } & Partial<FaultRule$1>);
404
+ /** Identifies a {@link SnapshotDocument}. */
405
+ declare const SNAPSHOT_FORMAT$1 = "mockingbird.snapshot/v1";
406
+ /**
407
+ * A namespace, as portable JSON: what `GET /__admin/snapshots/:id` returns and what
408
+ * `PUT /__admin/snapshots/:id` and the boot `snapshot` control accept. Only `format` and
409
+ * `records` are required, so a hand-written seed file is a valid snapshot.
410
+ */
411
+ type SnapshotDocument$1 = {
412
+ format: typeof SNAPSHOT_FORMAT$1;
413
+ /** The service that wrote it. A snapshot is rejected by any other service. */
414
+ service?: string;
415
+ /**
416
+ * Stored rows. `seq` orders a collection; omitted, rows keep their listed order. `raw` is
417
+ * the stored text of a row that is not a plain record, and replaces `value` when present.
418
+ */
419
+ records: {
420
+ collection: string;
421
+ id: string;
422
+ seq?: number;
423
+ value?: unknown;
424
+ raw?: string;
425
+ }[];
426
+ /** Id counters, so the next generated id continues where the snapshot left off. */
427
+ sequences?: {
428
+ name: string;
429
+ kind: string;
430
+ value: number;
431
+ }[];
432
+ clock?: {
433
+ now: number;
434
+ frozen: boolean;
435
+ autoAdvanceMs?: number;
436
+ };
437
+ seed?: number | string;
438
+ /** Positions of the seeded random streams. */
439
+ rng?: {
440
+ state: number;
441
+ faults?: number;
442
+ latency?: number;
443
+ };
444
+ faults?: unknown;
445
+ latency?: unknown;
446
+ virtualTime?: boolean;
447
+ };
448
+ /** Controls for one namespace. */
449
+ type NamespaceControls$1 = {
450
+ /** Seeds every random choice: fault rates, jitter, and whatever the service invents. */
451
+ seed?: number | string;
452
+ clock?: ClockControls$1;
453
+ /**
454
+ * Spend injected waits (latency, fault delays, timeouts) on the mock clock instead of the
455
+ * wall clock: the request returns at once, the clock has moved, and the journal records
456
+ * the wait exactly. Default `false`: waits are real, so a client's own timeout can fire.
457
+ */
458
+ virtualTime?: boolean;
459
+ /** Baseline response time for every vendor request. A bare duration is its `delay`. */
460
+ latency?: Duration$1 | LatencyControls$1;
461
+ faults?: readonly FaultInput$1[];
462
+ /** Start from this state instead of the service's own seed data. */
463
+ snapshot?: SnapshotDocument$1;
464
+ };
465
+ /** {@link NamespaceControls} for every namespace, with per-namespace overrides. */
466
+ type MockControls$1 = NamespaceControls$1 & {
467
+ /** Vendor credential → namespace, for SDKs that cannot send a namespace header. */
468
+ credentials?: Record<string, string>;
469
+ /** Overrides for named namespaces. A key given here replaces the shared value. */
470
+ namespaces?: Record<string, NamespaceControls$1>;
471
+ };
472
+ /** A latency rule in milliseconds. */
473
+ type LatencyRule$1 = {
474
+ delayMs: number;
475
+ jitterMs: number;
476
+ };
477
+ /** Baseline latency for a namespace, normalized. */
478
+ type LatencyState$1 = LatencyRule$1 & {
479
+ operations: Record<string, LatencyRule$1>;
480
+ };
481
+ /** What {@link controlHeaders} turns into request headers. */
482
+ type ControlHeaderInput$1 = {
483
+ namespace?: string;
484
+ adminKey?: string;
485
+ branch?: string;
486
+ at?: string;
487
+ reset?: boolean;
488
+ restore?: string;
489
+ seed?: number | string;
490
+ time?: Instant$1 | Date;
491
+ advance?: Duration$1;
492
+ virtualTime?: boolean;
493
+ delay?: Duration$1;
494
+ timeout?: Duration$1;
495
+ /** A status, `"drop"`, a preset name, or a fault rule. */
496
+ fault?: number | string | Record<string, unknown>;
497
+ snapshot?: string;
277
498
  };
278
499
 
279
500
  /**
@@ -313,6 +534,8 @@ type RequestLog$1 = {
313
534
  unmatched: boolean;
314
535
  /** Set when a fault rule produced the response. */
315
536
  faultId?: string;
537
+ /** Milliseconds of injected wait: latency, fault delays and timeouts. Absent when none. */
538
+ delayMs?: number;
316
539
  /** Resource ids the handler touched (`userId`, `orderId`, …), when the service reports them. */
317
540
  ids?: Record<string, string>;
318
541
  /** Set when the service created a resource the request referred to but that did not exist. */
@@ -358,6 +581,12 @@ type JournalQuery$1 = {
358
581
  /** Only this namespace. Omit for every namespace, oldest first across all of them. */
359
582
  namespace?: string;
360
583
  operationId?: string;
584
+ /** Only this HTTP method, case-insensitive. */
585
+ method?: string;
586
+ /** Only this exact path. */
587
+ path?: string;
588
+ /** Only requests this fault rule answered or shaped. */
589
+ faultId?: string;
361
590
  status?: number;
362
591
  /** Only entries at or after this instant (epoch ms). */
363
592
  since?: number;
@@ -372,6 +601,50 @@ type Journal$1 = {
372
601
  clear(namespace?: string): void;
373
602
  };
374
603
 
604
+ /**
605
+ * Baseline response time, per namespace: how long every vendor request takes before any
606
+ * fault is considered. Jitter draws from a stream the caller owns, one per namespace and
607
+ * separate from the fault stream, so adding latency never shifts which requests a `rate`
608
+ * fault hits.
609
+ */
610
+ type LatencyRegistry$1 = {
611
+ get(namespace: string): LatencyState$1;
612
+ set(namespace: string, state: LatencyState$1): LatencyState$1;
613
+ /** Remove one namespace's latency, or every namespace's. */
614
+ clear(namespace?: string): void;
615
+ /** Milliseconds this request waits. Draws jitter, so call it once per request. */
616
+ take(namespace: string, operationId: string | undefined): number;
617
+ };
618
+
619
+ /** Clock state as the admin API reports it. */
620
+ type ControlClock$1 = ClockState$1 & {
621
+ /** `now`, as ISO-8601. */
622
+ iso: string;
623
+ /** Milliseconds the clock steps before every vendor request. */
624
+ autoAdvanceMs: number;
625
+ };
626
+ /** One namespace's controls: the body of `GET /__admin/controls`. */
627
+ type ControlState$1 = {
628
+ namespace: string;
629
+ seed: number | string;
630
+ clock: ControlClock$1;
631
+ virtualTime: boolean;
632
+ latency: LatencyState$1;
633
+ faults: FaultListing$1[];
634
+ };
635
+
636
+ /** What `GET /__admin/snapshots` lists for each snapshot. */
637
+ type SnapshotInfo$1 = {
638
+ id: string;
639
+ namespace: string;
640
+ /** Stored rows in the snapshot. */
641
+ records: number;
642
+ /** The namespace clock when it was taken, epoch ms. */
643
+ at: number;
644
+ /** Whether `GET /snapshots/:id` can return it as a {@link SnapshotDocument}. */
645
+ portable: boolean;
646
+ };
647
+
375
648
  /** Credential → namespace mapping behind `PUT /__admin/credentials`. */
376
649
  type CredentialRegistry$1 = {
377
650
  set(credential: string, namespace: string): void;
@@ -526,7 +799,10 @@ type ServiceInstance$1 = FetchAPI$1 & {
526
799
  };
527
800
  type ServiceTimelineState$1 = Readonly<{
528
801
  snapshot: NamespaceSnapshot$1;
529
- clock: Readonly<ReturnType<Clock$1["state"]>>;
802
+ /** `pinned`: the namespace's clock was frozen itself, not just following a frozen base. */
803
+ clock: Readonly<ClockState$1 & {
804
+ pinned?: boolean;
805
+ }>;
530
806
  rngState: number;
531
807
  }>;
532
808
  type ServiceCheckpoint$1 = Checkpoint$1<ServiceTimelineState$1>;
@@ -534,17 +810,23 @@ type ServiceRuntime$1<T extends ServiceInstance$1> = FetchAPI$1 & {
534
810
  /** Stop package-owned lifecycle timers when a supervisor closes the runtime. */
535
811
  stop?(): void;
536
812
  readonly name: string;
813
+ /** Same-origin Fetch handler and App Router method exports, sharing this runtime. */
814
+ mount(prefix: string): MountedAPI$1;
537
815
  readonly sqlite: SqliteClient$2;
538
816
  readonly clock: Clock$1;
539
817
  readonly faults: FaultRegistry$1;
818
+ /** Baseline response time per namespace. */
819
+ readonly latency: LatencyRegistry$1;
540
820
  readonly metrics: Metrics$1;
541
821
  readonly journal: Journal$1;
542
822
  readonly rng: Rng$1;
543
823
  readonly credentials: CredentialRegistry$1;
544
824
  /** The webhook hub, when the service has outbound webhooks. */
545
825
  readonly webhooks: WebhookHub$1 | undefined;
546
- /** Enable independent namespace clocks and PRNGs before serving a fleet. */
547
- isolateNamespaces(): void;
826
+ /**
827
+ * A namespace's clock. Each follows the base clock, {@link ServiceRuntime.clock}, with an
828
+ * offset and a freeze of its own, so moving one never moves another.
829
+ */
548
830
  namespaceClock(namespace?: string): Clock$1;
549
831
  namespaceOf(request: Request): string;
550
832
  /** Opaque in-process checkpoint including records, controls and webhook history. */
@@ -556,8 +838,38 @@ type ServiceRuntime$1<T extends ServiceInstance$1> = FetchAPI$1 & {
556
838
  instance(namespace?: string): T;
557
839
  /** Public names of every namespace created so far. */
558
840
  namespaces(): string[];
559
- /** Reset one namespace, or every namespace with `"*"`. */
841
+ /** Return one namespace to its boot state, or every namespace with `"*"`. */
560
842
  reset(namespace?: string): Promise<void>;
843
+ /** Reset a namespace and forget it, releasing everything it held. */
844
+ dropNamespace(namespace: string): Promise<void>;
845
+ /** A namespace's controls: seed, clock, virtual time, latency, faults and snapshots. */
846
+ controls(namespace?: string): ControlState$1 & {
847
+ snapshots: SnapshotInfo$1[];
848
+ };
849
+ /** Apply a control document to a namespace. A given key replaces that control. */
850
+ configure(controls: NamespaceControls$1, namespace?: string): ControlState$1 & {
851
+ snapshots: SnapshotInfo$1[];
852
+ };
853
+ /** Named snapshots of a namespace: records, clock, random streams, faults and latency. */
854
+ readonly snapshots: {
855
+ /** Capture the namespace now. Reusing a name replaces that snapshot. */
856
+ create(options?: {
857
+ name?: string;
858
+ namespace?: string;
859
+ }): SnapshotInfo$1;
860
+ list(namespace?: string): SnapshotInfo$1[];
861
+ /** The snapshot as portable JSON, to commit beside a suite or boot another mock from. */
862
+ export(id: string, namespace?: string): SnapshotDocument$1;
863
+ /** Store a document as a snapshot without restoring it. */
864
+ import(document: SnapshotDocument$1, options?: {
865
+ name?: string;
866
+ namespace?: string;
867
+ }): SnapshotInfo$1;
868
+ restore(id: string, namespace?: string): void;
869
+ delete(id: string, namespace?: string): boolean;
870
+ };
871
+ /** Request headers that carry controls, checked: spread them into a `fetch` or an SDK's defaults. */
872
+ headers(input: ControlHeaderInput$1): Record<string, string>;
561
873
  snapshot(namespace?: string): NamespaceSnapshot$1;
562
874
  restore(snapshot: NamespaceSnapshot$1, namespace?: string): void;
563
875
  /** Capture the current branch. Mutating HTTP calls do this automatically. */
@@ -600,6 +912,11 @@ type CommonServeOptions = {
600
912
  adminKey: string | undefined;
601
913
  seed: string | undefined;
602
914
  onLog: ((entry: RequestLog$1) => void) | undefined;
915
+ /** Admin controls to boot with: clock, latency, faults, a starting snapshot. */
916
+ adminControls?: MockControls$1;
917
+ /** Synthetic provider fixture objects supplied by a fleet entry. */
918
+ fixtures?: Record<string, unknown>;
919
+ baseUrl?: string;
603
920
  };
604
921
  /**
605
922
  * What a service contributes to `serve`: how to build its runtime from CLI flags,
@@ -618,88 +935,16 @@ type ServeTarget = {
618
935
  listening?(server: Listening): void;
619
936
  };
620
937
 
621
- /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
622
- type SqliteValue$1 = null | number | bigint | string | Uint8Array | boolean;
623
- /** Mutation counters returned by {@link SqliteStatement.run}. */
624
- type SqliteRunResult$1 = {
625
- changes: number;
626
- lastInsertRowid: number | bigint;
938
+ type MountedAPI = FetchAPI & {
939
+ readonly prefix: string;
940
+ GET: FetchHandler;
941
+ POST: FetchHandler;
942
+ PUT: FetchHandler;
943
+ PATCH: FetchHandler;
944
+ DELETE: FetchHandler;
945
+ HEAD: FetchHandler;
946
+ OPTIONS: FetchHandler;
627
947
  };
628
- /**
629
- * Prepared statement bound to a {@link SqliteClient}.
630
- *
631
- * Pass bind values as rest arguments on each call (no sticky `bind()`).
632
- */
633
- interface SqliteStatement$1 {
634
- run(...params: SqliteValue$1[]): SqliteRunResult$1;
635
- all<T = Record<string, unknown>>(...params: SqliteValue$1[]): T[];
636
- get<T = Record<string, unknown>>(...params: SqliteValue$1[]): T | undefined;
637
- }
638
- /**
639
- * Sync SQLite client port owned by Mockingbird.
640
- *
641
- * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
642
- * `bun:sqlite` instances all work when they expose this surface.
643
- */
644
- interface SqliteClient$1 {
645
- exec(sql: string): void;
646
- prepare(sql: string): SqliteStatement$1;
647
- transaction<T>(fn: () => T): T;
648
- }
649
-
650
- /** Every stored record carries a monotonically increasing sequence for stable ordering. */
651
- type Stored<T> = {
652
- seq: number;
653
- value: T;
654
- };
655
- type ListRecordsOptions<T> = {
656
- /** Keep only records passing the predicate. */
657
- where?: (value: T, seq: number) => boolean;
658
- /** Sort order; default newest first. */
659
- order?: "newest" | "oldest";
660
- };
661
- /**
662
- * A SQLite-backed table of JSON records addressed by id. Ordering is by insertion
663
- * sequence, never by id lexicographic order, so list semantics stay stable.
664
- */
665
- declare class Collection<T> {
666
- private readonly sqlite;
667
- /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
668
- readonly namespace: string;
669
- /** Table name inside the namespace. Stable across resets of the rows themselves. */
670
- readonly collectionName: string;
671
- constructor(sqlite: SqliteClient$1,
672
- /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
673
- namespace: string,
674
- /** Table name inside the namespace. Stable across resets of the rows themselves. */
675
- collectionName: string);
676
- private bumpCollectionSeq;
677
- nextSequence(): number;
678
- get(id: string): T | undefined;
679
- has(id: string): boolean;
680
- /** Insert a new record, assigning it the next sequence number. */
681
- insert(id: string, value: T): Stored<T>;
682
- /** Replace an existing record's value, keeping its position. */
683
- update(id: string, value: T): Stored<T> | undefined;
684
- delete(id: string): boolean;
685
- /** How many records the collection holds, without reading them. */
686
- count(): number;
687
- list(options?: ListRecordsOptions<T>): Array<Stored<T> & {
688
- id: string;
689
- }>;
690
- }
691
-
692
- /**
693
- * Sequential id source persisted in SQLite. Ids are deterministic for a given
694
- * sequence history (`cus_` + 14 opaque chars), so reproductions stay stable.
695
- */
696
- declare class IdSequence {
697
- private readonly sqlite;
698
- private readonly namespace;
699
- private readonly salt;
700
- constructor(sqlite: SqliteClient$1, namespace: string, salt?: string);
701
- next(prefix: string, length?: number): string;
702
- }
703
948
 
704
949
  /** A stable identifier for a point in a {@link Timeline}. */
705
950
  type CheckpointId = string;
@@ -790,6 +1035,91 @@ declare class Timeline<T> {
790
1035
  interface FetchAPI {
791
1036
  fetch(request: Request): Promise<Response>;
792
1037
  }
1038
+ /** A bare function form of {@link FetchAPI}, compatible with `Bun.serve`, workerd, and Deno. */
1039
+ type FetchHandler = (request: Request) => Promise<Response>;
1040
+
1041
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
1042
+ type SqliteValue$1 = null | number | bigint | string | Uint8Array | boolean;
1043
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
1044
+ type SqliteRunResult$1 = {
1045
+ changes: number;
1046
+ lastInsertRowid: number | bigint;
1047
+ };
1048
+ /**
1049
+ * Prepared statement bound to a {@link SqliteClient}.
1050
+ *
1051
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
1052
+ */
1053
+ interface SqliteStatement$1 {
1054
+ run(...params: SqliteValue$1[]): SqliteRunResult$1;
1055
+ all<T = Record<string, unknown>>(...params: SqliteValue$1[]): T[];
1056
+ get<T = Record<string, unknown>>(...params: SqliteValue$1[]): T | undefined;
1057
+ }
1058
+ /**
1059
+ * Sync SQLite client port owned by Mockingbird.
1060
+ *
1061
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
1062
+ * `bun:sqlite` instances all work when they expose this surface.
1063
+ */
1064
+ interface SqliteClient$1 {
1065
+ exec(sql: string): void;
1066
+ prepare(sql: string): SqliteStatement$1;
1067
+ transaction<T>(fn: () => T): T;
1068
+ }
1069
+
1070
+ /** Every stored record carries a monotonically increasing sequence for stable ordering. */
1071
+ type Stored<T> = {
1072
+ seq: number;
1073
+ value: T;
1074
+ };
1075
+ type ListRecordsOptions<T> = {
1076
+ /** Keep only records passing the predicate. */
1077
+ where?: (value: T, seq: number) => boolean;
1078
+ /** Sort order; default newest first. */
1079
+ order?: "newest" | "oldest";
1080
+ };
1081
+ /**
1082
+ * A SQLite-backed table of JSON records addressed by id. Ordering is by insertion
1083
+ * sequence, never by id lexicographic order, so list semantics stay stable.
1084
+ */
1085
+ declare class Collection<T> {
1086
+ private readonly sqlite;
1087
+ /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
1088
+ readonly namespace: string;
1089
+ /** Table name inside the namespace. Stable across resets of the rows themselves. */
1090
+ readonly collectionName: string;
1091
+ constructor(sqlite: SqliteClient$1,
1092
+ /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
1093
+ namespace: string,
1094
+ /** Table name inside the namespace. Stable across resets of the rows themselves. */
1095
+ collectionName: string);
1096
+ private bumpCollectionSeq;
1097
+ nextSequence(): number;
1098
+ get(id: string): T | undefined;
1099
+ has(id: string): boolean;
1100
+ /** Insert a new record, assigning it the next sequence number. */
1101
+ insert(id: string, value: T): Stored<T>;
1102
+ /** Replace an existing record's value, keeping its position. */
1103
+ update(id: string, value: T): Stored<T> | undefined;
1104
+ delete(id: string): boolean;
1105
+ /** How many records the collection holds, without reading them. */
1106
+ count(): number;
1107
+ list(options?: ListRecordsOptions<T>): Array<Stored<T> & {
1108
+ id: string;
1109
+ }>;
1110
+ }
1111
+
1112
+ /**
1113
+ * Sequential id source persisted in SQLite. Ids are deterministic for a given
1114
+ * sequence history (`cus_` + 14 opaque chars), so reproductions stay stable.
1115
+ */
1116
+ declare class IdSequence {
1117
+ private readonly sqlite;
1118
+ private readonly namespace;
1119
+ private readonly salt;
1120
+ constructor(sqlite: SqliteClient$1, namespace: string, salt?: string);
1121
+ next(prefix: string, length?: number): string;
1122
+ }
793
1123
 
794
1124
  /** Options every provider constructor accepts. */
795
1125
  type APIOptions = {
@@ -816,7 +1146,7 @@ type ClockState = {
816
1146
  now: number;
817
1147
  /** True while time does not advance on its own. */
818
1148
  frozen: boolean;
819
- /** Milliseconds this clock adds to its underlying source. */
1149
+ /** Milliseconds a running clock adds to its underlying source. `0` while frozen. */
820
1150
  offsetMs: number;
821
1151
  };
822
1152
  type Clock = {
@@ -852,7 +1182,10 @@ type Rng = {
852
1182
  state(): number;
853
1183
  /** Restore a state previously returned by {@link state}. */
854
1184
  setState(state: number): void;
855
- seed: number;
1185
+ /** Restart the stream from a new seed. `reset` then returns to this seed. */
1186
+ reseed(seed: number | string): void;
1187
+ /** The seed the stream currently starts from. */
1188
+ readonly seed: number;
856
1189
  };
857
1190
 
858
1191
  /**
@@ -861,44 +1194,83 @@ type Rng = {
861
1194
  * This is how a suite reaches the vendor's failure modes without the vendor: the
862
1195
  * quota error that only appears when a shared sandbox is full, the 429 that only
863
1196
  * appears under load, the 5xx that proves a retry path works.
1197
+ *
1198
+ * A rule has three parts. What it **matches** (`operationId`, `method`, `path`, …), **when**
1199
+ * it fires among the matching requests (`after`, `every`, `count`, `rate`, `from`, `until`),
1200
+ * and what it **does** (`status`, `delay`, `timeout`, `drop`, `truncate`, `effect`).
864
1201
  */
865
1202
  type FaultRule = {
866
- /** Stable id, so a suite can retire exactly the rule it added. */
1203
+ /** Stable id, so a suite can retire exactly the rule it added. Unique within a namespace. */
867
1204
  id: string;
868
1205
  /** Fault only this operation. Omit to match every operation. */
869
1206
  operationId?: string;
870
1207
  /** Fault only this HTTP method, case-insensitive. Omit to match every method. */
871
1208
  method?: string;
1209
+ /** Fault only this exact path. */
1210
+ path?: string;
872
1211
  /** Fault only paths starting with this prefix. Omit to match every path. */
873
1212
  pathPrefix?: string;
1213
+ /** Fault only paths matching this regular expression (JavaScript syntax, unanchored). */
1214
+ pathPattern?: string;
1215
+ /** Fault only requests carrying these headers. `"*"` matches any value. */
1216
+ requestHeaders?: Record<string, string>;
1217
+ /** Fault only requests carrying these query parameters. `"*"` matches any value. */
1218
+ query?: Record<string, string>;
874
1219
  /**
875
1220
  * Fault only this namespace. Omit (or `"*"`) to fault every namespace — which is what
876
1221
  * an in-process caller usually wants, and what a parallel worker usually does not:
877
1222
  * rules added through `POST /__admin/faults` default to the calling namespace.
878
1223
  */
879
1224
  namespace?: string;
1225
+ /** Let this many matching requests through first. */
1226
+ after?: number;
1227
+ /** Then fault only every nth matching request: `3` faults the 3rd, 6th, 9th. */
1228
+ every?: number;
1229
+ /** Retire the rule after this many faults. Omit to keep it until removed. */
1230
+ count?: number;
1231
+ /** Fault this fraction of the remaining requests, `0`–`1`, drawn from the seed. Default `1`. */
1232
+ rate?: number;
880
1233
  /**
881
- * Status of the injected response. Omit for a rule that only delays (`delayMs` /
882
- * `latencyMs`), only drops the connection (`drop`), or only switches on an `effect`:
883
- * the request then still reaches the service.
1234
+ * Fault only from this instant on the namespace clock. A duration (`"5m"`) counts from the
1235
+ * clock when the rule was added. Listed as epoch ms.
1236
+ */
1237
+ from?: Instant | Duration;
1238
+ /** Stop faulting at this instant on the namespace clock. A duration counts from when added. */
1239
+ until?: Instant | Duration;
1240
+ /**
1241
+ * Status of the injected response. Omit for a rule that only delays, times out, drops,
1242
+ * truncates, or switches on an `effect`: the request then still reaches the service.
884
1243
  */
885
1244
  status?: number;
886
1245
  /** Response body, serialized as JSON. A string is sent as-is. */
887
1246
  body?: unknown;
1247
+ /** Response headers. */
888
1248
  headers?: Record<string, string>;
889
- /** Retire the rule after this many faults. Omit to keep it until removed. */
890
- count?: number;
891
- /** Fault this fraction of matching requests, `0`–`1`. Default `1`. */
892
- rate?: number;
893
- /** Hold the response back this long, to exercise timeouts. */
1249
+ /** Hold the response back this long. Listed as `delayMs`. */
1250
+ delay?: Duration;
1251
+ /** `delay`, in milliseconds. */
894
1252
  delayMs?: number;
895
1253
  /** Alias of `delayMs`. */
896
1254
  latencyMs?: number;
1255
+ /** Extra seeded delay in `[0, jitter]`. Listed as `jitterMs`. */
1256
+ jitter?: Duration;
1257
+ jitterMs?: number;
1258
+ /**
1259
+ * Never answer: hold the request this long, then drop the connection. Listed as
1260
+ * `timeoutMs`. With virtual time the wait is spent on the mock clock.
1261
+ */
1262
+ timeout?: Duration;
1263
+ timeoutMs?: number;
897
1264
  /**
898
1265
  * Drop the connection instead of answering: an in-process `fetch` rejects with a
899
1266
  * `TypeError`, and a served mock destroys the socket. Models "unknown outcome" failures.
900
1267
  */
901
1268
  drop?: boolean;
1269
+ /**
1270
+ * Cut the response body off after this many bytes: the status and headers arrive, then
1271
+ * the connection dies mid-body.
1272
+ */
1273
+ truncate?: number;
902
1274
  /**
903
1275
  * A named service behaviour to switch on for the matching request instead of (or
904
1276
  * before) a canned response, e.g. `created_but_500` or `numeric_tracking_id`. Services
@@ -907,8 +1279,8 @@ type FaultRule = {
907
1279
  effect?: string;
908
1280
  /** Parameters for `effect`. */
909
1281
  params?: Record<string, unknown>;
910
- /** From the preset this rule was expanded from, if any. */
911
- preset?: string;
1282
+ /** The preset this rule was expanded from, if any. */
1283
+ fromPreset?: string;
912
1284
  };
913
1285
  /** A fault that fired for one request. */
914
1286
  type FaultHit = {
@@ -916,6 +1288,10 @@ type FaultHit = {
916
1288
  /** The injected response; absent when the rule only delays, drops, or sets an effect. */
917
1289
  response?: Response;
918
1290
  drop?: boolean;
1291
+ /** Set with `drop` when the rule held the request for its `timeout` first. */
1292
+ timeout?: boolean;
1293
+ /** Bytes of response body to let through before the connection dies. */
1294
+ truncate?: number;
919
1295
  effect?: {
920
1296
  name: string;
921
1297
  params: Record<string, unknown>;
@@ -927,38 +1303,200 @@ type FaultCandidate = {
927
1303
  method: string;
928
1304
  path: string;
929
1305
  namespace: string;
1306
+ /** Request headers and query, for rules that match on them. */
1307
+ headers?: Headers;
1308
+ query?: URLSearchParams;
1309
+ /** The namespace clock, for `from` / `until`. Rules with a window are skipped without it. */
1310
+ now?: number;
1311
+ /** How to spend a delay for this request. Default: the registry's own sleep. */
1312
+ wait?: (ms: number) => Promise<void>;
1313
+ };
1314
+ /** A stored rule and how often it was consulted. */
1315
+ type FaultListing = FaultRule & {
1316
+ /** Faults left before the rule retires. `null` when it has no `count`. */
1317
+ remaining: number | null;
1318
+ /** Times the rule faulted a request. */
1319
+ hits: number;
1320
+ /** Requests that matched the rule, faulted or not. */
1321
+ seen: number;
1322
+ };
1323
+ /** A namespace's own rules, with their counters, in the order they are tried. */
1324
+ type FaultSnapshot = {
1325
+ /**
1326
+ * `position` is how many `"*"` rules are tried before the rule, which is what its place
1327
+ * in the order means to a request and holds in any process.
1328
+ */
1329
+ rules: (FaultListing & {
1330
+ position?: number;
1331
+ })[];
1332
+ /** How many `fault_<n>` ids the namespace has handed out. */
1333
+ nextId?: number;
930
1334
  };
931
1335
  type FaultRegistry = {
932
- isolateNamespaces(): void;
933
- snapshot(namespace: string): {
934
- rules: (FaultRule & {
935
- remaining: number | null;
936
- hits: number;
937
- position: number;
938
- })[];
939
- rngState: number;
940
- };
1336
+ snapshot(namespace: string): FaultSnapshot;
1337
+ /** Add a rule, or replace the rule with the same id in the same namespace. */
941
1338
  add(rule: FaultRule): FaultRule;
942
- list(): (FaultRule & {
943
- remaining: number | null;
944
- hits: number;
945
- })[];
946
- remove(id: string): boolean;
947
- clear(): void;
948
- restore(namespace: string, state: {
949
- rules: (FaultRule & {
950
- remaining: number | null;
951
- hits: number;
952
- position: number;
953
- })[];
954
- rngState: number;
955
- }): void;
1339
+ /** The next unused `fault_<n>` id in `namespace`. */
1340
+ nextId(namespace: string): string;
1341
+ /** Every rule, or the rules a namespace's requests can hit: its own and the global ones. */
1342
+ list(namespace?: string): FaultListing[];
1343
+ get(id: string, namespace?: string): FaultListing | undefined;
1344
+ /** Remove a rule by id: from `namespace` (its own, then a global one), or wherever it is. */
1345
+ remove(id: string, namespace?: string): boolean;
1346
+ /** Remove every rule, or one namespace's own rules. */
1347
+ clear(namespace?: string): void;
1348
+ /** Replace a namespace's own rules with a snapshot's, wherever the snapshot was taken. */
1349
+ restore(namespace: string, state: FaultSnapshot): void;
956
1350
  /**
957
1351
  * Every fault this request should get, in rule order, stopping at the first that answers
958
1352
  * or drops (effect-only and delay-only rules let later rules match too). Consumes one of
959
1353
  * each matching rule's remaining uses.
960
1354
  */
961
1355
  take(candidate: FaultCandidate): Promise<FaultHit[]>;
1356
+ /**
1357
+ * Fire these rules at one request without storing them: no matching, no schedule, in order,
1358
+ * stopping at the first that answers or drops. Jitter draws from the namespace's stream.
1359
+ */
1360
+ fire(rules: readonly FaultRule[], candidate: FaultCandidate): Promise<FaultHit[]>;
1361
+ };
1362
+
1363
+ /**
1364
+ * The admin controls every mock shares, as one document.
1365
+ *
1366
+ * The same shape is accepted in three places, and means the same thing in each:
1367
+ *
1368
+ * - at boot: `createRuntime({ adminControls })`, `serve --admin-controls`,
1369
+ * `MOCKINGBIRD_ADMIN_CONTROLS`
1370
+ * - over HTTP: `PUT /__admin/controls`
1371
+ * - per request: the `x-mockingbird-*` headers in {@link CONTROL_HEADERS}
1372
+ *
1373
+ * Every control is deterministic: given the same seed, clock and requests, a mock answers
1374
+ * the same bytes. Nothing here reads the wall clock or `Math.random`.
1375
+ */
1376
+ /** Milliseconds, or a string like `"250ms"`, `"2s"`, `"15m"`, `"1h"`, `"3d"`. */
1377
+ type Duration = number | string;
1378
+ /** Epoch milliseconds, or an ISO-8601 string. */
1379
+ type Instant = number | string;
1380
+ type ClockControls = {
1381
+ /** Move the clock to this instant. */
1382
+ now?: Instant;
1383
+ /** Stop time. A frozen clock moves only when told to, so timestamps replay exactly. */
1384
+ frozen?: boolean;
1385
+ /**
1386
+ * Step the clock forward by this much before every vendor request. With a frozen clock
1387
+ * each request still gets its own, reproducible timestamp.
1388
+ */
1389
+ autoAdvance?: Duration;
1390
+ };
1391
+ /** How long a response takes: a fixed delay plus seeded jitter in `[0, jitter]`. */
1392
+ type LatencyRuleInput = {
1393
+ delay?: Duration;
1394
+ jitter?: Duration;
1395
+ };
1396
+ type LatencyControls = LatencyRuleInput & {
1397
+ /** Per-operation overrides, keyed by operationId. A bare duration is its `delay`. */
1398
+ operations?: Record<string, Duration | LatencyRuleInput>;
1399
+ };
1400
+ /** A fault to add: a rule (the id is assigned when omitted), or a named preset with overrides. */
1401
+ type FaultInput = (Omit<FaultRule, "id"> & {
1402
+ id?: string;
1403
+ }) | ({
1404
+ preset: string;
1405
+ } & Partial<FaultRule>);
1406
+ /** Identifies a {@link SnapshotDocument}. */
1407
+ declare const SNAPSHOT_FORMAT = "mockingbird.snapshot/v1";
1408
+ /**
1409
+ * A namespace, as portable JSON: what `GET /__admin/snapshots/:id` returns and what
1410
+ * `PUT /__admin/snapshots/:id` and the boot `snapshot` control accept. Only `format` and
1411
+ * `records` are required, so a hand-written seed file is a valid snapshot.
1412
+ */
1413
+ type SnapshotDocument = {
1414
+ format: typeof SNAPSHOT_FORMAT;
1415
+ /** The service that wrote it. A snapshot is rejected by any other service. */
1416
+ service?: string;
1417
+ /**
1418
+ * Stored rows. `seq` orders a collection; omitted, rows keep their listed order. `raw` is
1419
+ * the stored text of a row that is not a plain record, and replaces `value` when present.
1420
+ */
1421
+ records: {
1422
+ collection: string;
1423
+ id: string;
1424
+ seq?: number;
1425
+ value?: unknown;
1426
+ raw?: string;
1427
+ }[];
1428
+ /** Id counters, so the next generated id continues where the snapshot left off. */
1429
+ sequences?: {
1430
+ name: string;
1431
+ kind: string;
1432
+ value: number;
1433
+ }[];
1434
+ clock?: {
1435
+ now: number;
1436
+ frozen: boolean;
1437
+ autoAdvanceMs?: number;
1438
+ };
1439
+ seed?: number | string;
1440
+ /** Positions of the seeded random streams. */
1441
+ rng?: {
1442
+ state: number;
1443
+ faults?: number;
1444
+ latency?: number;
1445
+ };
1446
+ faults?: unknown;
1447
+ latency?: unknown;
1448
+ virtualTime?: boolean;
1449
+ };
1450
+ /** Controls for one namespace. */
1451
+ type NamespaceControls = {
1452
+ /** Seeds every random choice: fault rates, jitter, and whatever the service invents. */
1453
+ seed?: number | string;
1454
+ clock?: ClockControls;
1455
+ /**
1456
+ * Spend injected waits (latency, fault delays, timeouts) on the mock clock instead of the
1457
+ * wall clock: the request returns at once, the clock has moved, and the journal records
1458
+ * the wait exactly. Default `false`: waits are real, so a client's own timeout can fire.
1459
+ */
1460
+ virtualTime?: boolean;
1461
+ /** Baseline response time for every vendor request. A bare duration is its `delay`. */
1462
+ latency?: Duration | LatencyControls;
1463
+ faults?: readonly FaultInput[];
1464
+ /** Start from this state instead of the service's own seed data. */
1465
+ snapshot?: SnapshotDocument;
1466
+ };
1467
+ /** {@link NamespaceControls} for every namespace, with per-namespace overrides. */
1468
+ type MockControls = NamespaceControls & {
1469
+ /** Vendor credential → namespace, for SDKs that cannot send a namespace header. */
1470
+ credentials?: Record<string, string>;
1471
+ /** Overrides for named namespaces. A key given here replaces the shared value. */
1472
+ namespaces?: Record<string, NamespaceControls>;
1473
+ };
1474
+ /** A latency rule in milliseconds. */
1475
+ type LatencyRule = {
1476
+ delayMs: number;
1477
+ jitterMs: number;
1478
+ };
1479
+ /** Baseline latency for a namespace, normalized. */
1480
+ type LatencyState = LatencyRule & {
1481
+ operations: Record<string, LatencyRule>;
1482
+ };
1483
+ /** What {@link controlHeaders} turns into request headers. */
1484
+ type ControlHeaderInput = {
1485
+ namespace?: string;
1486
+ adminKey?: string;
1487
+ branch?: string;
1488
+ at?: string;
1489
+ reset?: boolean;
1490
+ restore?: string;
1491
+ seed?: number | string;
1492
+ time?: Instant | Date;
1493
+ advance?: Duration;
1494
+ virtualTime?: boolean;
1495
+ delay?: Duration;
1496
+ timeout?: Duration;
1497
+ /** A status, `"drop"`, a preset name, or a fault rule. */
1498
+ fault?: number | string | Record<string, unknown>;
1499
+ snapshot?: string;
962
1500
  };
963
1501
 
964
1502
  /**
@@ -998,6 +1536,8 @@ type RequestLog = {
998
1536
  unmatched: boolean;
999
1537
  /** Set when a fault rule produced the response. */
1000
1538
  faultId?: string;
1539
+ /** Milliseconds of injected wait: latency, fault delays and timeouts. Absent when none. */
1540
+ delayMs?: number;
1001
1541
  /** Resource ids the handler touched (`userId`, `orderId`, …), when the service reports them. */
1002
1542
  ids?: Record<string, string>;
1003
1543
  /** Set when the service created a resource the request referred to but that did not exist. */
@@ -1043,6 +1583,12 @@ type JournalQuery = {
1043
1583
  /** Only this namespace. Omit for every namespace, oldest first across all of them. */
1044
1584
  namespace?: string;
1045
1585
  operationId?: string;
1586
+ /** Only this HTTP method, case-insensitive. */
1587
+ method?: string;
1588
+ /** Only this exact path. */
1589
+ path?: string;
1590
+ /** Only requests this fault rule answered or shaped. */
1591
+ faultId?: string;
1046
1592
  status?: number;
1047
1593
  /** Only entries at or after this instant (epoch ms). */
1048
1594
  since?: number;
@@ -1057,6 +1603,50 @@ type Journal = {
1057
1603
  clear(namespace?: string): void;
1058
1604
  };
1059
1605
 
1606
+ /**
1607
+ * Baseline response time, per namespace: how long every vendor request takes before any
1608
+ * fault is considered. Jitter draws from a stream the caller owns, one per namespace and
1609
+ * separate from the fault stream, so adding latency never shifts which requests a `rate`
1610
+ * fault hits.
1611
+ */
1612
+ type LatencyRegistry = {
1613
+ get(namespace: string): LatencyState;
1614
+ set(namespace: string, state: LatencyState): LatencyState;
1615
+ /** Remove one namespace's latency, or every namespace's. */
1616
+ clear(namespace?: string): void;
1617
+ /** Milliseconds this request waits. Draws jitter, so call it once per request. */
1618
+ take(namespace: string, operationId: string | undefined): number;
1619
+ };
1620
+
1621
+ /** Clock state as the admin API reports it. */
1622
+ type ControlClock = ClockState & {
1623
+ /** `now`, as ISO-8601. */
1624
+ iso: string;
1625
+ /** Milliseconds the clock steps before every vendor request. */
1626
+ autoAdvanceMs: number;
1627
+ };
1628
+ /** One namespace's controls: the body of `GET /__admin/controls`. */
1629
+ type ControlState = {
1630
+ namespace: string;
1631
+ seed: number | string;
1632
+ clock: ControlClock;
1633
+ virtualTime: boolean;
1634
+ latency: LatencyState;
1635
+ faults: FaultListing[];
1636
+ };
1637
+
1638
+ /** What `GET /__admin/snapshots` lists for each snapshot. */
1639
+ type SnapshotInfo = {
1640
+ id: string;
1641
+ namespace: string;
1642
+ /** Stored rows in the snapshot. */
1643
+ records: number;
1644
+ /** The namespace clock when it was taken, epoch ms. */
1645
+ at: number;
1646
+ /** Whether `GET /snapshots/:id` can return it as a {@link SnapshotDocument}. */
1647
+ portable: boolean;
1648
+ };
1649
+
1060
1650
  /** Credential → namespace mapping behind `PUT /__admin/credentials`. */
1061
1651
  type CredentialRegistry = {
1062
1652
  set(credential: string, namespace: string): void;
@@ -1211,7 +1801,10 @@ type ServiceInstance = FetchAPI & {
1211
1801
  };
1212
1802
  type ServiceTimelineState = Readonly<{
1213
1803
  snapshot: NamespaceSnapshot;
1214
- clock: Readonly<ReturnType<Clock["state"]>>;
1804
+ /** `pinned`: the namespace's clock was frozen itself, not just following a frozen base. */
1805
+ clock: Readonly<ClockState & {
1806
+ pinned?: boolean;
1807
+ }>;
1215
1808
  rngState: number;
1216
1809
  }>;
1217
1810
  type ServiceCheckpoint = Checkpoint<ServiceTimelineState>;
@@ -1219,17 +1812,23 @@ type ServiceRuntime<T extends ServiceInstance> = FetchAPI & {
1219
1812
  /** Stop package-owned lifecycle timers when a supervisor closes the runtime. */
1220
1813
  stop?(): void;
1221
1814
  readonly name: string;
1815
+ /** Same-origin Fetch handler and App Router method exports, sharing this runtime. */
1816
+ mount(prefix: string): MountedAPI;
1222
1817
  readonly sqlite: SqliteClient$1;
1223
1818
  readonly clock: Clock;
1224
1819
  readonly faults: FaultRegistry;
1820
+ /** Baseline response time per namespace. */
1821
+ readonly latency: LatencyRegistry;
1225
1822
  readonly metrics: Metrics;
1226
1823
  readonly journal: Journal;
1227
1824
  readonly rng: Rng;
1228
1825
  readonly credentials: CredentialRegistry;
1229
1826
  /** The webhook hub, when the service has outbound webhooks. */
1230
1827
  readonly webhooks: WebhookHub | undefined;
1231
- /** Enable independent namespace clocks and PRNGs before serving a fleet. */
1232
- isolateNamespaces(): void;
1828
+ /**
1829
+ * A namespace's clock. Each follows the base clock, {@link ServiceRuntime.clock}, with an
1830
+ * offset and a freeze of its own, so moving one never moves another.
1831
+ */
1233
1832
  namespaceClock(namespace?: string): Clock;
1234
1833
  namespaceOf(request: Request): string;
1235
1834
  /** Opaque in-process checkpoint including records, controls and webhook history. */
@@ -1241,8 +1840,38 @@ type ServiceRuntime<T extends ServiceInstance> = FetchAPI & {
1241
1840
  instance(namespace?: string): T;
1242
1841
  /** Public names of every namespace created so far. */
1243
1842
  namespaces(): string[];
1244
- /** Reset one namespace, or every namespace with `"*"`. */
1843
+ /** Return one namespace to its boot state, or every namespace with `"*"`. */
1245
1844
  reset(namespace?: string): Promise<void>;
1845
+ /** Reset a namespace and forget it, releasing everything it held. */
1846
+ dropNamespace(namespace: string): Promise<void>;
1847
+ /** A namespace's controls: seed, clock, virtual time, latency, faults and snapshots. */
1848
+ controls(namespace?: string): ControlState & {
1849
+ snapshots: SnapshotInfo[];
1850
+ };
1851
+ /** Apply a control document to a namespace. A given key replaces that control. */
1852
+ configure(controls: NamespaceControls, namespace?: string): ControlState & {
1853
+ snapshots: SnapshotInfo[];
1854
+ };
1855
+ /** Named snapshots of a namespace: records, clock, random streams, faults and latency. */
1856
+ readonly snapshots: {
1857
+ /** Capture the namespace now. Reusing a name replaces that snapshot. */
1858
+ create(options?: {
1859
+ name?: string;
1860
+ namespace?: string;
1861
+ }): SnapshotInfo;
1862
+ list(namespace?: string): SnapshotInfo[];
1863
+ /** The snapshot as portable JSON, to commit beside a suite or boot another mock from. */
1864
+ export(id: string, namespace?: string): SnapshotDocument;
1865
+ /** Store a document as a snapshot without restoring it. */
1866
+ import(document: SnapshotDocument, options?: {
1867
+ name?: string;
1868
+ namespace?: string;
1869
+ }): SnapshotInfo;
1870
+ restore(id: string, namespace?: string): void;
1871
+ delete(id: string, namespace?: string): boolean;
1872
+ };
1873
+ /** Request headers that carry controls, checked: spread them into a `fetch` or an SDK's defaults. */
1874
+ headers(input: ControlHeaderInput): Record<string, string>;
1246
1875
  snapshot(namespace?: string): NamespaceSnapshot;
1247
1876
  restore(snapshot: NamespaceSnapshot, namespace?: string): void;
1248
1877
  /** Capture the current branch. Mutating HTTP calls do this automatically. */
@@ -1380,6 +2009,8 @@ type StepFunctionsRuntimeOptions = {
1380
2009
  seed?: number | string;
1381
2010
  adminPrefix?: string;
1382
2011
  adminKey?: string;
2012
+ /** Admin controls to boot with: clock, latency, faults, seed, a starting snapshot. */
2013
+ adminControls?: MockControls;
1383
2014
  onLog?: (entry: RequestLog) => void;
1384
2015
  region?: string;
1385
2016
  accountId?: string;