@crvouga/mockingbird-service-workos 1.0.0 → 1.2.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/index.d.ts CHANGED
@@ -40,76 +40,16 @@ interface FetchAPI$1 {
40
40
  fetch(request: Request): Promise<Response>;
41
41
  }
42
42
 
43
- /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
44
- type SqliteValue = null | number | bigint | string | Uint8Array | boolean;
45
- /** Mutation counters returned by {@link SqliteStatement.run}. */
46
- type SqliteRunResult = {
47
- changes: number;
48
- lastInsertRowid: number | bigint;
43
+ type MountedAPI = FetchAPI & {
44
+ readonly prefix: string;
45
+ GET: FetchHandler;
46
+ POST: FetchHandler;
47
+ PUT: FetchHandler;
48
+ PATCH: FetchHandler;
49
+ DELETE: FetchHandler;
50
+ HEAD: FetchHandler;
51
+ OPTIONS: FetchHandler;
49
52
  };
50
- /**
51
- * Prepared statement bound to a {@link SqliteClient}.
52
- *
53
- * Pass bind values as rest arguments on each call (no sticky `bind()`).
54
- */
55
- interface SqliteStatement {
56
- run(...params: SqliteValue[]): SqliteRunResult;
57
- all<T = Record<string, unknown>>(...params: SqliteValue[]): T[];
58
- get<T = Record<string, unknown>>(...params: SqliteValue[]): T | undefined;
59
- }
60
- /**
61
- * Sync SQLite client port owned by Mockingbird.
62
- *
63
- * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
64
- * `bun:sqlite` instances all work when they expose this surface.
65
- */
66
- interface SqliteClient {
67
- exec(sql: string): void;
68
- prepare(sql: string): SqliteStatement;
69
- transaction<T>(fn: () => T): T;
70
- }
71
-
72
- /** Every stored record carries a monotonically increasing sequence for stable ordering. */
73
- type Stored<T> = {
74
- seq: number;
75
- value: T;
76
- };
77
- type ListRecordsOptions<T> = {
78
- /** Keep only records passing the predicate. */
79
- where?: (value: T, seq: number) => boolean;
80
- /** Sort order; default newest first. */
81
- order?: "newest" | "oldest";
82
- };
83
- /**
84
- * A SQLite-backed table of JSON records addressed by id. Ordering is by insertion
85
- * sequence, never by id lexicographic order, so list semantics stay stable.
86
- */
87
- declare class Collection<T> {
88
- private readonly sqlite;
89
- /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
90
- readonly namespace: string;
91
- /** Table name inside the namespace. Stable across resets of the rows themselves. */
92
- readonly collectionName: string;
93
- constructor(sqlite: SqliteClient,
94
- /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
95
- namespace: string,
96
- /** Table name inside the namespace. Stable across resets of the rows themselves. */
97
- collectionName: string);
98
- private bumpCollectionSeq;
99
- nextSequence(): number;
100
- get(id: string): T | undefined;
101
- has(id: string): boolean;
102
- /** Insert a new record, assigning it the next sequence number. */
103
- insert(id: string, value: T): Stored<T>;
104
- /** Replace an existing record's value, keeping its position. */
105
- update(id: string, value: T): Stored<T> | undefined;
106
- delete(id: string): boolean;
107
- /** How many records the collection holds, without reading them. */
108
- count(): number;
109
- list(options?: ListRecordsOptions<T>): Array<Stored<T> & {
110
- id: string;
111
- }>;
112
- }
113
53
 
114
54
  /** A stable identifier for a point in a {@link Timeline}. */
115
55
  type CheckpointId = string;
@@ -200,6 +140,79 @@ declare class Timeline<T> {
200
140
  interface FetchAPI {
201
141
  fetch(request: Request): Promise<Response>;
202
142
  }
143
+ /** A bare function form of {@link FetchAPI}, compatible with `Bun.serve`, workerd, and Deno. */
144
+ type FetchHandler = (request: Request) => Promise<Response>;
145
+
146
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
147
+ type SqliteValue = null | number | bigint | string | Uint8Array | boolean;
148
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
149
+ type SqliteRunResult = {
150
+ changes: number;
151
+ lastInsertRowid: number | bigint;
152
+ };
153
+ /**
154
+ * Prepared statement bound to a {@link SqliteClient}.
155
+ *
156
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
157
+ */
158
+ interface SqliteStatement {
159
+ run(...params: SqliteValue[]): SqliteRunResult;
160
+ all<T = Record<string, unknown>>(...params: SqliteValue[]): T[];
161
+ get<T = Record<string, unknown>>(...params: SqliteValue[]): T | undefined;
162
+ }
163
+ /**
164
+ * Sync SQLite client port owned by Mockingbird.
165
+ *
166
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
167
+ * `bun:sqlite` instances all work when they expose this surface.
168
+ */
169
+ interface SqliteClient {
170
+ exec(sql: string): void;
171
+ prepare(sql: string): SqliteStatement;
172
+ transaction<T>(fn: () => T): T;
173
+ }
174
+
175
+ /** Every stored record carries a monotonically increasing sequence for stable ordering. */
176
+ type Stored<T> = {
177
+ seq: number;
178
+ value: T;
179
+ };
180
+ type ListRecordsOptions<T> = {
181
+ /** Keep only records passing the predicate. */
182
+ where?: (value: T, seq: number) => boolean;
183
+ /** Sort order; default newest first. */
184
+ order?: "newest" | "oldest";
185
+ };
186
+ /**
187
+ * A SQLite-backed table of JSON records addressed by id. Ordering is by insertion
188
+ * sequence, never by id lexicographic order, so list semantics stay stable.
189
+ */
190
+ declare class Collection<T> {
191
+ private readonly sqlite;
192
+ /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
193
+ readonly namespace: string;
194
+ /** Table name inside the namespace. Stable across resets of the rows themselves. */
195
+ readonly collectionName: string;
196
+ constructor(sqlite: SqliteClient,
197
+ /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
198
+ namespace: string,
199
+ /** Table name inside the namespace. Stable across resets of the rows themselves. */
200
+ collectionName: string);
201
+ private bumpCollectionSeq;
202
+ nextSequence(): number;
203
+ get(id: string): T | undefined;
204
+ has(id: string): boolean;
205
+ /** Insert a new record, assigning it the next sequence number. */
206
+ insert(id: string, value: T): Stored<T>;
207
+ /** Replace an existing record's value, keeping its position. */
208
+ update(id: string, value: T): Stored<T> | undefined;
209
+ delete(id: string): boolean;
210
+ /** How many records the collection holds, without reading them. */
211
+ count(): number;
212
+ list(options?: ListRecordsOptions<T>): Array<Stored<T> & {
213
+ id: string;
214
+ }>;
215
+ }
203
216
 
204
217
  /** Options every provider constructor accepts. */
205
218
  type APIOptions = {
@@ -226,7 +239,7 @@ type ClockState = {
226
239
  now: number;
227
240
  /** True while time does not advance on its own. */
228
241
  frozen: boolean;
229
- /** Milliseconds this clock adds to its underlying source. */
242
+ /** Milliseconds a running clock adds to its underlying source. `0` while frozen. */
230
243
  offsetMs: number;
231
244
  };
232
245
  type Clock = {
@@ -262,7 +275,10 @@ type Rng = {
262
275
  state(): number;
263
276
  /** Restore a state previously returned by {@link state}. */
264
277
  setState(state: number): void;
265
- seed: number;
278
+ /** Restart the stream from a new seed. `reset` then returns to this seed. */
279
+ reseed(seed: number | string): void;
280
+ /** The seed the stream currently starts from. */
281
+ readonly seed: number;
266
282
  };
267
283
 
268
284
  /**
@@ -271,44 +287,83 @@ type Rng = {
271
287
  * This is how a suite reaches the vendor's failure modes without the vendor: the
272
288
  * quota error that only appears when a shared sandbox is full, the 429 that only
273
289
  * appears under load, the 5xx that proves a retry path works.
290
+ *
291
+ * A rule has three parts. What it **matches** (`operationId`, `method`, `path`, …), **when**
292
+ * it fires among the matching requests (`after`, `every`, `count`, `rate`, `from`, `until`),
293
+ * and what it **does** (`status`, `delay`, `timeout`, `drop`, `truncate`, `effect`).
274
294
  */
275
295
  type FaultRule = {
276
- /** Stable id, so a suite can retire exactly the rule it added. */
296
+ /** Stable id, so a suite can retire exactly the rule it added. Unique within a namespace. */
277
297
  id: string;
278
298
  /** Fault only this operation. Omit to match every operation. */
279
299
  operationId?: string;
280
300
  /** Fault only this HTTP method, case-insensitive. Omit to match every method. */
281
301
  method?: string;
302
+ /** Fault only this exact path. */
303
+ path?: string;
282
304
  /** Fault only paths starting with this prefix. Omit to match every path. */
283
305
  pathPrefix?: string;
306
+ /** Fault only paths matching this regular expression (JavaScript syntax, unanchored). */
307
+ pathPattern?: string;
308
+ /** Fault only requests carrying these headers. `"*"` matches any value. */
309
+ requestHeaders?: Record<string, string>;
310
+ /** Fault only requests carrying these query parameters. `"*"` matches any value. */
311
+ query?: Record<string, string>;
284
312
  /**
285
313
  * Fault only this namespace. Omit (or `"*"`) to fault every namespace — which is what
286
314
  * an in-process caller usually wants, and what a parallel worker usually does not:
287
315
  * rules added through `POST /__admin/faults` default to the calling namespace.
288
316
  */
289
317
  namespace?: string;
318
+ /** Let this many matching requests through first. */
319
+ after?: number;
320
+ /** Then fault only every nth matching request: `3` faults the 3rd, 6th, 9th. */
321
+ every?: number;
322
+ /** Retire the rule after this many faults. Omit to keep it until removed. */
323
+ count?: number;
324
+ /** Fault this fraction of the remaining requests, `0`–`1`, drawn from the seed. Default `1`. */
325
+ rate?: number;
290
326
  /**
291
- * Status of the injected response. Omit for a rule that only delays (`delayMs` /
292
- * `latencyMs`), only drops the connection (`drop`), or only switches on an `effect`:
293
- * the request then still reaches the service.
327
+ * Fault only from this instant on the namespace clock. A duration (`"5m"`) counts from the
328
+ * clock when the rule was added. Listed as epoch ms.
329
+ */
330
+ from?: Instant | Duration;
331
+ /** Stop faulting at this instant on the namespace clock. A duration counts from when added. */
332
+ until?: Instant | Duration;
333
+ /**
334
+ * Status of the injected response. Omit for a rule that only delays, times out, drops,
335
+ * truncates, or switches on an `effect`: the request then still reaches the service.
294
336
  */
295
337
  status?: number;
296
338
  /** Response body, serialized as JSON. A string is sent as-is. */
297
339
  body?: unknown;
340
+ /** Response headers. */
298
341
  headers?: Record<string, string>;
299
- /** Retire the rule after this many faults. Omit to keep it until removed. */
300
- count?: number;
301
- /** Fault this fraction of matching requests, `0`–`1`. Default `1`. */
302
- rate?: number;
303
- /** Hold the response back this long, to exercise timeouts. */
342
+ /** Hold the response back this long. Listed as `delayMs`. */
343
+ delay?: Duration;
344
+ /** `delay`, in milliseconds. */
304
345
  delayMs?: number;
305
346
  /** Alias of `delayMs`. */
306
347
  latencyMs?: number;
348
+ /** Extra seeded delay in `[0, jitter]`. Listed as `jitterMs`. */
349
+ jitter?: Duration;
350
+ jitterMs?: number;
351
+ /**
352
+ * Never answer: hold the request this long, then drop the connection. Listed as
353
+ * `timeoutMs`. With virtual time the wait is spent on the mock clock.
354
+ */
355
+ timeout?: Duration;
356
+ timeoutMs?: number;
307
357
  /**
308
358
  * Drop the connection instead of answering: an in-process `fetch` rejects with a
309
359
  * `TypeError`, and a served mock destroys the socket. Models "unknown outcome" failures.
310
360
  */
311
361
  drop?: boolean;
362
+ /**
363
+ * Cut the response body off after this many bytes: the status and headers arrive, then
364
+ * the connection dies mid-body.
365
+ */
366
+ truncate?: number;
312
367
  /**
313
368
  * A named service behaviour to switch on for the matching request instead of (or
314
369
  * before) a canned response, e.g. `created_but_500` or `numeric_tracking_id`. Services
@@ -317,8 +372,8 @@ type FaultRule = {
317
372
  effect?: string;
318
373
  /** Parameters for `effect`. */
319
374
  params?: Record<string, unknown>;
320
- /** From the preset this rule was expanded from, if any. */
321
- preset?: string;
375
+ /** The preset this rule was expanded from, if any. */
376
+ fromPreset?: string;
322
377
  };
323
378
  /** A fault that fired for one request. */
324
379
  type FaultHit = {
@@ -326,6 +381,10 @@ type FaultHit = {
326
381
  /** The injected response; absent when the rule only delays, drops, or sets an effect. */
327
382
  response?: Response;
328
383
  drop?: boolean;
384
+ /** Set with `drop` when the rule held the request for its `timeout` first. */
385
+ timeout?: boolean;
386
+ /** Bytes of response body to let through before the connection dies. */
387
+ truncate?: number;
329
388
  effect?: {
330
389
  name: string;
331
390
  params: Record<string, unknown>;
@@ -350,38 +409,200 @@ type FaultCandidate = {
350
409
  method: string;
351
410
  path: string;
352
411
  namespace: string;
412
+ /** Request headers and query, for rules that match on them. */
413
+ headers?: Headers;
414
+ query?: URLSearchParams;
415
+ /** The namespace clock, for `from` / `until`. Rules with a window are skipped without it. */
416
+ now?: number;
417
+ /** How to spend a delay for this request. Default: the registry's own sleep. */
418
+ wait?: (ms: number) => Promise<void>;
419
+ };
420
+ /** A stored rule and how often it was consulted. */
421
+ type FaultListing = FaultRule & {
422
+ /** Faults left before the rule retires. `null` when it has no `count`. */
423
+ remaining: number | null;
424
+ /** Times the rule faulted a request. */
425
+ hits: number;
426
+ /** Requests that matched the rule, faulted or not. */
427
+ seen: number;
428
+ };
429
+ /** A namespace's own rules, with their counters, in the order they are tried. */
430
+ type FaultSnapshot = {
431
+ /**
432
+ * `position` is how many `"*"` rules are tried before the rule, which is what its place
433
+ * in the order means to a request and holds in any process.
434
+ */
435
+ rules: (FaultListing & {
436
+ position?: number;
437
+ })[];
438
+ /** How many `fault_<n>` ids the namespace has handed out. */
439
+ nextId?: number;
353
440
  };
354
441
  type FaultRegistry = {
355
- isolateNamespaces(): void;
356
- snapshot(namespace: string): {
357
- rules: (FaultRule & {
358
- remaining: number | null;
359
- hits: number;
360
- position: number;
361
- })[];
362
- rngState: number;
363
- };
442
+ snapshot(namespace: string): FaultSnapshot;
443
+ /** Add a rule, or replace the rule with the same id in the same namespace. */
364
444
  add(rule: FaultRule): FaultRule;
365
- list(): (FaultRule & {
366
- remaining: number | null;
367
- hits: number;
368
- })[];
369
- remove(id: string): boolean;
370
- clear(): void;
371
- restore(namespace: string, state: {
372
- rules: (FaultRule & {
373
- remaining: number | null;
374
- hits: number;
375
- position: number;
376
- })[];
377
- rngState: number;
378
- }): void;
445
+ /** The next unused `fault_<n>` id in `namespace`. */
446
+ nextId(namespace: string): string;
447
+ /** Every rule, or the rules a namespace's requests can hit: its own and the global ones. */
448
+ list(namespace?: string): FaultListing[];
449
+ get(id: string, namespace?: string): FaultListing | undefined;
450
+ /** Remove a rule by id: from `namespace` (its own, then a global one), or wherever it is. */
451
+ remove(id: string, namespace?: string): boolean;
452
+ /** Remove every rule, or one namespace's own rules. */
453
+ clear(namespace?: string): void;
454
+ /** Replace a namespace's own rules with a snapshot's, wherever the snapshot was taken. */
455
+ restore(namespace: string, state: FaultSnapshot): void;
379
456
  /**
380
457
  * Every fault this request should get, in rule order, stopping at the first that answers
381
458
  * or drops (effect-only and delay-only rules let later rules match too). Consumes one of
382
459
  * each matching rule's remaining uses.
383
460
  */
384
461
  take(candidate: FaultCandidate): Promise<FaultHit[]>;
462
+ /**
463
+ * Fire these rules at one request without storing them: no matching, no schedule, in order,
464
+ * stopping at the first that answers or drops. Jitter draws from the namespace's stream.
465
+ */
466
+ fire(rules: readonly FaultRule[], candidate: FaultCandidate): Promise<FaultHit[]>;
467
+ };
468
+
469
+ /**
470
+ * The admin controls every mock shares, as one document.
471
+ *
472
+ * The same shape is accepted in three places, and means the same thing in each:
473
+ *
474
+ * - at boot: `createRuntime({ adminControls })`, `serve --admin-controls`,
475
+ * `MOCKINGBIRD_ADMIN_CONTROLS`
476
+ * - over HTTP: `PUT /__admin/controls`
477
+ * - per request: the `x-mockingbird-*` headers in {@link CONTROL_HEADERS}
478
+ *
479
+ * Every control is deterministic: given the same seed, clock and requests, a mock answers
480
+ * the same bytes. Nothing here reads the wall clock or `Math.random`.
481
+ */
482
+ /** Milliseconds, or a string like `"250ms"`, `"2s"`, `"15m"`, `"1h"`, `"3d"`. */
483
+ type Duration = number | string;
484
+ /** Epoch milliseconds, or an ISO-8601 string. */
485
+ type Instant = number | string;
486
+ type ClockControls = {
487
+ /** Move the clock to this instant. */
488
+ now?: Instant;
489
+ /** Stop time. A frozen clock moves only when told to, so timestamps replay exactly. */
490
+ frozen?: boolean;
491
+ /**
492
+ * Step the clock forward by this much before every vendor request. With a frozen clock
493
+ * each request still gets its own, reproducible timestamp.
494
+ */
495
+ autoAdvance?: Duration;
496
+ };
497
+ /** How long a response takes: a fixed delay plus seeded jitter in `[0, jitter]`. */
498
+ type LatencyRuleInput = {
499
+ delay?: Duration;
500
+ jitter?: Duration;
501
+ };
502
+ type LatencyControls = LatencyRuleInput & {
503
+ /** Per-operation overrides, keyed by operationId. A bare duration is its `delay`. */
504
+ operations?: Record<string, Duration | LatencyRuleInput>;
505
+ };
506
+ /** A fault to add: a rule (the id is assigned when omitted), or a named preset with overrides. */
507
+ type FaultInput = (Omit<FaultRule, "id"> & {
508
+ id?: string;
509
+ }) | ({
510
+ preset: string;
511
+ } & Partial<FaultRule>);
512
+ /** Identifies a {@link SnapshotDocument}. */
513
+ declare const SNAPSHOT_FORMAT = "mockingbird.snapshot/v1";
514
+ /**
515
+ * A namespace, as portable JSON: what `GET /__admin/snapshots/:id` returns and what
516
+ * `PUT /__admin/snapshots/:id` and the boot `snapshot` control accept. Only `format` and
517
+ * `records` are required, so a hand-written seed file is a valid snapshot.
518
+ */
519
+ type SnapshotDocument = {
520
+ format: typeof SNAPSHOT_FORMAT;
521
+ /** The service that wrote it. A snapshot is rejected by any other service. */
522
+ service?: string;
523
+ /**
524
+ * Stored rows. `seq` orders a collection; omitted, rows keep their listed order. `raw` is
525
+ * the stored text of a row that is not a plain record, and replaces `value` when present.
526
+ */
527
+ records: {
528
+ collection: string;
529
+ id: string;
530
+ seq?: number;
531
+ value?: unknown;
532
+ raw?: string;
533
+ }[];
534
+ /** Id counters, so the next generated id continues where the snapshot left off. */
535
+ sequences?: {
536
+ name: string;
537
+ kind: string;
538
+ value: number;
539
+ }[];
540
+ clock?: {
541
+ now: number;
542
+ frozen: boolean;
543
+ autoAdvanceMs?: number;
544
+ };
545
+ seed?: number | string;
546
+ /** Positions of the seeded random streams. */
547
+ rng?: {
548
+ state: number;
549
+ faults?: number;
550
+ latency?: number;
551
+ };
552
+ faults?: unknown;
553
+ latency?: unknown;
554
+ virtualTime?: boolean;
555
+ };
556
+ /** Controls for one namespace. */
557
+ type NamespaceControls = {
558
+ /** Seeds every random choice: fault rates, jitter, and whatever the service invents. */
559
+ seed?: number | string;
560
+ clock?: ClockControls;
561
+ /**
562
+ * Spend injected waits (latency, fault delays, timeouts) on the mock clock instead of the
563
+ * wall clock: the request returns at once, the clock has moved, and the journal records
564
+ * the wait exactly. Default `false`: waits are real, so a client's own timeout can fire.
565
+ */
566
+ virtualTime?: boolean;
567
+ /** Baseline response time for every vendor request. A bare duration is its `delay`. */
568
+ latency?: Duration | LatencyControls;
569
+ faults?: readonly FaultInput[];
570
+ /** Start from this state instead of the service's own seed data. */
571
+ snapshot?: SnapshotDocument;
572
+ };
573
+ /** {@link NamespaceControls} for every namespace, with per-namespace overrides. */
574
+ type MockControls = NamespaceControls & {
575
+ /** Vendor credential → namespace, for SDKs that cannot send a namespace header. */
576
+ credentials?: Record<string, string>;
577
+ /** Overrides for named namespaces. A key given here replaces the shared value. */
578
+ namespaces?: Record<string, NamespaceControls>;
579
+ };
580
+ /** A latency rule in milliseconds. */
581
+ type LatencyRule = {
582
+ delayMs: number;
583
+ jitterMs: number;
584
+ };
585
+ /** Baseline latency for a namespace, normalized. */
586
+ type LatencyState = LatencyRule & {
587
+ operations: Record<string, LatencyRule>;
588
+ };
589
+ /** What {@link controlHeaders} turns into request headers. */
590
+ type ControlHeaderInput = {
591
+ namespace?: string;
592
+ adminKey?: string;
593
+ branch?: string;
594
+ at?: string;
595
+ reset?: boolean;
596
+ restore?: string;
597
+ seed?: number | string;
598
+ time?: Instant | Date;
599
+ advance?: Duration;
600
+ virtualTime?: boolean;
601
+ delay?: Duration;
602
+ timeout?: Duration;
603
+ /** A status, `"drop"`, a preset name, or a fault rule. */
604
+ fault?: number | string | Record<string, unknown>;
605
+ snapshot?: string;
385
606
  };
386
607
 
387
608
  /**
@@ -421,6 +642,8 @@ type RequestLog = {
421
642
  unmatched: boolean;
422
643
  /** Set when a fault rule produced the response. */
423
644
  faultId?: string;
645
+ /** Milliseconds of injected wait: latency, fault delays and timeouts. Absent when none. */
646
+ delayMs?: number;
424
647
  /** Resource ids the handler touched (`userId`, `orderId`, …), when the service reports them. */
425
648
  ids?: Record<string, string>;
426
649
  /** Set when the service created a resource the request referred to but that did not exist. */
@@ -466,6 +689,12 @@ type JournalQuery = {
466
689
  /** Only this namespace. Omit for every namespace, oldest first across all of them. */
467
690
  namespace?: string;
468
691
  operationId?: string;
692
+ /** Only this HTTP method, case-insensitive. */
693
+ method?: string;
694
+ /** Only this exact path. */
695
+ path?: string;
696
+ /** Only requests this fault rule answered or shaped. */
697
+ faultId?: string;
469
698
  status?: number;
470
699
  /** Only entries at or after this instant (epoch ms). */
471
700
  since?: number;
@@ -480,6 +709,50 @@ type Journal = {
480
709
  clear(namespace?: string): void;
481
710
  };
482
711
 
712
+ /**
713
+ * Baseline response time, per namespace: how long every vendor request takes before any
714
+ * fault is considered. Jitter draws from a stream the caller owns, one per namespace and
715
+ * separate from the fault stream, so adding latency never shifts which requests a `rate`
716
+ * fault hits.
717
+ */
718
+ type LatencyRegistry = {
719
+ get(namespace: string): LatencyState;
720
+ set(namespace: string, state: LatencyState): LatencyState;
721
+ /** Remove one namespace's latency, or every namespace's. */
722
+ clear(namespace?: string): void;
723
+ /** Milliseconds this request waits. Draws jitter, so call it once per request. */
724
+ take(namespace: string, operationId: string | undefined): number;
725
+ };
726
+
727
+ /** Clock state as the admin API reports it. */
728
+ type ControlClock = ClockState & {
729
+ /** `now`, as ISO-8601. */
730
+ iso: string;
731
+ /** Milliseconds the clock steps before every vendor request. */
732
+ autoAdvanceMs: number;
733
+ };
734
+ /** One namespace's controls: the body of `GET /__admin/controls`. */
735
+ type ControlState = {
736
+ namespace: string;
737
+ seed: number | string;
738
+ clock: ControlClock;
739
+ virtualTime: boolean;
740
+ latency: LatencyState;
741
+ faults: FaultListing[];
742
+ };
743
+
744
+ /** What `GET /__admin/snapshots` lists for each snapshot. */
745
+ type SnapshotInfo = {
746
+ id: string;
747
+ namespace: string;
748
+ /** Stored rows in the snapshot. */
749
+ records: number;
750
+ /** The namespace clock when it was taken, epoch ms. */
751
+ at: number;
752
+ /** Whether `GET /snapshots/:id` can return it as a {@link SnapshotDocument}. */
753
+ portable: boolean;
754
+ };
755
+
483
756
  /** Credential → namespace mapping behind `PUT /__admin/credentials`. */
484
757
  type CredentialRegistry = {
485
758
  set(credential: string, namespace: string): void;
@@ -634,7 +907,10 @@ type ServiceInstance = FetchAPI & {
634
907
  };
635
908
  type ServiceTimelineState = Readonly<{
636
909
  snapshot: NamespaceSnapshot;
637
- clock: Readonly<ReturnType<Clock["state"]>>;
910
+ /** `pinned`: the namespace's clock was frozen itself, not just following a frozen base. */
911
+ clock: Readonly<ClockState & {
912
+ pinned?: boolean;
913
+ }>;
638
914
  rngState: number;
639
915
  }>;
640
916
  type ServiceCheckpoint = Checkpoint<ServiceTimelineState>;
@@ -642,17 +918,23 @@ type ServiceRuntime<T extends ServiceInstance> = FetchAPI & {
642
918
  /** Stop package-owned lifecycle timers when a supervisor closes the runtime. */
643
919
  stop?(): void;
644
920
  readonly name: string;
921
+ /** Same-origin Fetch handler and App Router method exports, sharing this runtime. */
922
+ mount(prefix: string): MountedAPI;
645
923
  readonly sqlite: SqliteClient;
646
924
  readonly clock: Clock;
647
925
  readonly faults: FaultRegistry;
926
+ /** Baseline response time per namespace. */
927
+ readonly latency: LatencyRegistry;
648
928
  readonly metrics: Metrics;
649
929
  readonly journal: Journal;
650
930
  readonly rng: Rng;
651
931
  readonly credentials: CredentialRegistry;
652
932
  /** The webhook hub, when the service has outbound webhooks. */
653
933
  readonly webhooks: WebhookHub | undefined;
654
- /** Enable independent namespace clocks and PRNGs before serving a fleet. */
655
- isolateNamespaces(): void;
934
+ /**
935
+ * A namespace's clock. Each follows the base clock, {@link ServiceRuntime.clock}, with an
936
+ * offset and a freeze of its own, so moving one never moves another.
937
+ */
656
938
  namespaceClock(namespace?: string): Clock;
657
939
  namespaceOf(request: Request): string;
658
940
  /** Opaque in-process checkpoint including records, controls and webhook history. */
@@ -664,8 +946,38 @@ type ServiceRuntime<T extends ServiceInstance> = FetchAPI & {
664
946
  instance(namespace?: string): T;
665
947
  /** Public names of every namespace created so far. */
666
948
  namespaces(): string[];
667
- /** Reset one namespace, or every namespace with `"*"`. */
949
+ /** Return one namespace to its boot state, or every namespace with `"*"`. */
668
950
  reset(namespace?: string): Promise<void>;
951
+ /** Reset a namespace and forget it, releasing everything it held. */
952
+ dropNamespace(namespace: string): Promise<void>;
953
+ /** A namespace's controls: seed, clock, virtual time, latency, faults and snapshots. */
954
+ controls(namespace?: string): ControlState & {
955
+ snapshots: SnapshotInfo[];
956
+ };
957
+ /** Apply a control document to a namespace. A given key replaces that control. */
958
+ configure(controls: NamespaceControls, namespace?: string): ControlState & {
959
+ snapshots: SnapshotInfo[];
960
+ };
961
+ /** Named snapshots of a namespace: records, clock, random streams, faults and latency. */
962
+ readonly snapshots: {
963
+ /** Capture the namespace now. Reusing a name replaces that snapshot. */
964
+ create(options?: {
965
+ name?: string;
966
+ namespace?: string;
967
+ }): SnapshotInfo;
968
+ list(namespace?: string): SnapshotInfo[];
969
+ /** The snapshot as portable JSON, to commit beside a suite or boot another mock from. */
970
+ export(id: string, namespace?: string): SnapshotDocument;
971
+ /** Store a document as a snapshot without restoring it. */
972
+ import(document: SnapshotDocument, options?: {
973
+ name?: string;
974
+ namespace?: string;
975
+ }): SnapshotInfo;
976
+ restore(id: string, namespace?: string): void;
977
+ delete(id: string, namespace?: string): boolean;
978
+ };
979
+ /** Request headers that carry controls, checked: spread them into a `fetch` or an SDK's defaults. */
980
+ headers(input: ControlHeaderInput): Record<string, string>;
669
981
  snapshot(namespace?: string): NamespaceSnapshot;
670
982
  restore(snapshot: NamespaceSnapshot, namespace?: string): void;
671
983
  /** Capture the current branch. Mutating HTTP calls do this automatically. */
@@ -863,6 +1175,8 @@ type WorkOSRuntimeOptions = Omit<WorkOSAPIOptions, "namespace" | "now"> & {
863
1175
  seed?: string | number;
864
1176
  adminPrefix?: string;
865
1177
  adminKey?: string;
1178
+ /** Admin controls to boot with: clock, latency, faults, seed, a starting snapshot. */
1179
+ adminControls?: MockControls;
866
1180
  onLog?: (entry: RequestLog) => void;
867
1181
  };
868
1182
  type WorkOSRuntime = ServiceRuntime<WorkOSAPI>;
package/dist/index.js CHANGED
@@ -8,7 +8,7 @@ import {
8
8
  document,
9
9
  operationIds,
10
10
  supportedOperationIds
11
- } from "./chunk-BXGLSAOT.js";
11
+ } from "./chunk-LE5B6IJG.js";
12
12
  export {
13
13
  DEFAULT_CLIENTS,
14
14
  DEFAULT_USERS,