@crvouga/mockingbird-service-formbricks 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/index.d.ts CHANGED
@@ -10,88 +10,16 @@ interface FetchAPI$1 {
10
10
  fetch(request: Request): Promise<Response>;
11
11
  }
12
12
 
13
- /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
14
- type SqliteValue$1 = null | number | bigint | string | Uint8Array | boolean;
15
- /** Mutation counters returned by {@link SqliteStatement.run}. */
16
- type SqliteRunResult$1 = {
17
- changes: number;
18
- lastInsertRowid: number | bigint;
13
+ type MountedAPI = FetchAPI & {
14
+ readonly prefix: string;
15
+ GET: FetchHandler;
16
+ POST: FetchHandler;
17
+ PUT: FetchHandler;
18
+ PATCH: FetchHandler;
19
+ DELETE: FetchHandler;
20
+ HEAD: FetchHandler;
21
+ OPTIONS: FetchHandler;
19
22
  };
20
- /**
21
- * Prepared statement bound to a {@link SqliteClient}.
22
- *
23
- * Pass bind values as rest arguments on each call (no sticky `bind()`).
24
- */
25
- interface SqliteStatement$1 {
26
- run(...params: SqliteValue$1[]): SqliteRunResult$1;
27
- all<T = Record<string, unknown>>(...params: SqliteValue$1[]): T[];
28
- get<T = Record<string, unknown>>(...params: SqliteValue$1[]): T | undefined;
29
- }
30
- /**
31
- * Sync SQLite client port owned by Mockingbird.
32
- *
33
- * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
34
- * `bun:sqlite` instances all work when they expose this surface.
35
- */
36
- interface SqliteClient$1 {
37
- exec(sql: string): void;
38
- prepare(sql: string): SqliteStatement$1;
39
- transaction<T>(fn: () => T): T;
40
- }
41
-
42
- /** Every stored record carries a monotonically increasing sequence for stable ordering. */
43
- type Stored<T> = {
44
- seq: number;
45
- value: T;
46
- };
47
- type ListRecordsOptions<T> = {
48
- /** Keep only records passing the predicate. */
49
- where?: (value: T, seq: number) => boolean;
50
- /** Sort order; default newest first. */
51
- order?: "newest" | "oldest";
52
- };
53
- /**
54
- * A SQLite-backed table of JSON records addressed by id. Ordering is by insertion
55
- * sequence, never by id lexicographic order, so list semantics stay stable.
56
- */
57
- declare class Collection<T> {
58
- private readonly sqlite;
59
- /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
60
- readonly namespace: string;
61
- /** Table name inside the namespace. Stable across resets of the rows themselves. */
62
- readonly collectionName: string;
63
- constructor(sqlite: SqliteClient$1,
64
- /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
65
- namespace: string,
66
- /** Table name inside the namespace. Stable across resets of the rows themselves. */
67
- collectionName: string);
68
- private bumpCollectionSeq;
69
- nextSequence(): number;
70
- get(id: string): T | undefined;
71
- has(id: string): boolean;
72
- /** Insert a new record, assigning it the next sequence number. */
73
- insert(id: string, value: T): Stored<T>;
74
- /** Replace an existing record's value, keeping its position. */
75
- update(id: string, value: T): Stored<T> | undefined;
76
- delete(id: string): boolean;
77
- /** How many records the collection holds, without reading them. */
78
- count(): number;
79
- list(options?: ListRecordsOptions<T>): Array<Stored<T> & {
80
- id: string;
81
- }>;
82
- }
83
-
84
- /**
85
- * Sequential id source persisted in SQLite. Ids are deterministic for a given
86
- * sequence history (`cus_` + 14 opaque chars), so reproductions stay stable.
87
- */
88
- declare class IdSequence {
89
- private readonly sqlite;
90
- private readonly namespace;
91
- private readonly salt;
92
- constructor(sqlite: SqliteClient$1, namespace: string, salt?: string);
93
- next(prefix: string, length?: number): string;
94
- }
95
23
 
96
24
  /** A stable identifier for a point in a {@link Timeline}. */
97
25
  type CheckpointId = string;
@@ -182,6 +110,91 @@ declare class Timeline<T> {
182
110
  interface FetchAPI {
183
111
  fetch(request: Request): Promise<Response>;
184
112
  }
113
+ /** A bare function form of {@link FetchAPI}, compatible with `Bun.serve`, workerd, and Deno. */
114
+ type FetchHandler = (request: Request) => Promise<Response>;
115
+
116
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
117
+ type SqliteValue$1 = null | number | bigint | string | Uint8Array | boolean;
118
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
119
+ type SqliteRunResult$1 = {
120
+ changes: number;
121
+ lastInsertRowid: number | bigint;
122
+ };
123
+ /**
124
+ * Prepared statement bound to a {@link SqliteClient}.
125
+ *
126
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
127
+ */
128
+ interface SqliteStatement$1 {
129
+ run(...params: SqliteValue$1[]): SqliteRunResult$1;
130
+ all<T = Record<string, unknown>>(...params: SqliteValue$1[]): T[];
131
+ get<T = Record<string, unknown>>(...params: SqliteValue$1[]): T | undefined;
132
+ }
133
+ /**
134
+ * Sync SQLite client port owned by Mockingbird.
135
+ *
136
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
137
+ * `bun:sqlite` instances all work when they expose this surface.
138
+ */
139
+ interface SqliteClient$1 {
140
+ exec(sql: string): void;
141
+ prepare(sql: string): SqliteStatement$1;
142
+ transaction<T>(fn: () => T): T;
143
+ }
144
+
145
+ /** Every stored record carries a monotonically increasing sequence for stable ordering. */
146
+ type Stored<T> = {
147
+ seq: number;
148
+ value: T;
149
+ };
150
+ type ListRecordsOptions<T> = {
151
+ /** Keep only records passing the predicate. */
152
+ where?: (value: T, seq: number) => boolean;
153
+ /** Sort order; default newest first. */
154
+ order?: "newest" | "oldest";
155
+ };
156
+ /**
157
+ * A SQLite-backed table of JSON records addressed by id. Ordering is by insertion
158
+ * sequence, never by id lexicographic order, so list semantics stay stable.
159
+ */
160
+ declare class Collection<T> {
161
+ private readonly sqlite;
162
+ /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
163
+ readonly namespace: string;
164
+ /** Table name inside the namespace. Stable across resets of the rows themselves. */
165
+ readonly collectionName: string;
166
+ constructor(sqlite: SqliteClient$1,
167
+ /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
168
+ namespace: string,
169
+ /** Table name inside the namespace. Stable across resets of the rows themselves. */
170
+ collectionName: string);
171
+ private bumpCollectionSeq;
172
+ nextSequence(): number;
173
+ get(id: string): T | undefined;
174
+ has(id: string): boolean;
175
+ /** Insert a new record, assigning it the next sequence number. */
176
+ insert(id: string, value: T): Stored<T>;
177
+ /** Replace an existing record's value, keeping its position. */
178
+ update(id: string, value: T): Stored<T> | undefined;
179
+ delete(id: string): boolean;
180
+ /** How many records the collection holds, without reading them. */
181
+ count(): number;
182
+ list(options?: ListRecordsOptions<T>): Array<Stored<T> & {
183
+ id: string;
184
+ }>;
185
+ }
186
+
187
+ /**
188
+ * Sequential id source persisted in SQLite. Ids are deterministic for a given
189
+ * sequence history (`cus_` + 14 opaque chars), so reproductions stay stable.
190
+ */
191
+ declare class IdSequence {
192
+ private readonly sqlite;
193
+ private readonly namespace;
194
+ private readonly salt;
195
+ constructor(sqlite: SqliteClient$1, namespace: string, salt?: string);
196
+ next(prefix: string, length?: number): string;
197
+ }
185
198
 
186
199
  type DecodedBody = {
187
200
  kind: "empty";
@@ -442,7 +455,7 @@ type ClockState = {
442
455
  now: number;
443
456
  /** True while time does not advance on its own. */
444
457
  frozen: boolean;
445
- /** Milliseconds this clock adds to its underlying source. */
458
+ /** Milliseconds a running clock adds to its underlying source. `0` while frozen. */
446
459
  offsetMs: number;
447
460
  };
448
461
  type Clock = {
@@ -478,7 +491,10 @@ type Rng = {
478
491
  state(): number;
479
492
  /** Restore a state previously returned by {@link state}. */
480
493
  setState(state: number): void;
481
- seed: number;
494
+ /** Restart the stream from a new seed. `reset` then returns to this seed. */
495
+ reseed(seed: number | string): void;
496
+ /** The seed the stream currently starts from. */
497
+ readonly seed: number;
482
498
  };
483
499
 
484
500
  /**
@@ -487,44 +503,83 @@ type Rng = {
487
503
  * This is how a suite reaches the vendor's failure modes without the vendor: the
488
504
  * quota error that only appears when a shared sandbox is full, the 429 that only
489
505
  * appears under load, the 5xx that proves a retry path works.
506
+ *
507
+ * A rule has three parts. What it **matches** (`operationId`, `method`, `path`, …), **when**
508
+ * it fires among the matching requests (`after`, `every`, `count`, `rate`, `from`, `until`),
509
+ * and what it **does** (`status`, `delay`, `timeout`, `drop`, `truncate`, `effect`).
490
510
  */
491
511
  type FaultRule = {
492
- /** Stable id, so a suite can retire exactly the rule it added. */
512
+ /** Stable id, so a suite can retire exactly the rule it added. Unique within a namespace. */
493
513
  id: string;
494
514
  /** Fault only this operation. Omit to match every operation. */
495
515
  operationId?: string;
496
516
  /** Fault only this HTTP method, case-insensitive. Omit to match every method. */
497
517
  method?: string;
518
+ /** Fault only this exact path. */
519
+ path?: string;
498
520
  /** Fault only paths starting with this prefix. Omit to match every path. */
499
521
  pathPrefix?: string;
522
+ /** Fault only paths matching this regular expression (JavaScript syntax, unanchored). */
523
+ pathPattern?: string;
524
+ /** Fault only requests carrying these headers. `"*"` matches any value. */
525
+ requestHeaders?: Record<string, string>;
526
+ /** Fault only requests carrying these query parameters. `"*"` matches any value. */
527
+ query?: Record<string, string>;
500
528
  /**
501
529
  * Fault only this namespace. Omit (or `"*"`) to fault every namespace — which is what
502
530
  * an in-process caller usually wants, and what a parallel worker usually does not:
503
531
  * rules added through `POST /__admin/faults` default to the calling namespace.
504
532
  */
505
533
  namespace?: string;
534
+ /** Let this many matching requests through first. */
535
+ after?: number;
536
+ /** Then fault only every nth matching request: `3` faults the 3rd, 6th, 9th. */
537
+ every?: number;
538
+ /** Retire the rule after this many faults. Omit to keep it until removed. */
539
+ count?: number;
540
+ /** Fault this fraction of the remaining requests, `0`–`1`, drawn from the seed. Default `1`. */
541
+ rate?: number;
542
+ /**
543
+ * Fault only from this instant on the namespace clock. A duration (`"5m"`) counts from the
544
+ * clock when the rule was added. Listed as epoch ms.
545
+ */
546
+ from?: Instant | Duration;
547
+ /** Stop faulting at this instant on the namespace clock. A duration counts from when added. */
548
+ until?: Instant | Duration;
506
549
  /**
507
- * Status of the injected response. Omit for a rule that only delays (`delayMs` /
508
- * `latencyMs`), only drops the connection (`drop`), or only switches on an `effect`:
509
- * the request then still reaches the service.
550
+ * Status of the injected response. Omit for a rule that only delays, times out, drops,
551
+ * truncates, or switches on an `effect`: the request then still reaches the service.
510
552
  */
511
553
  status?: number;
512
554
  /** Response body, serialized as JSON. A string is sent as-is. */
513
555
  body?: unknown;
556
+ /** Response headers. */
514
557
  headers?: Record<string, string>;
515
- /** Retire the rule after this many faults. Omit to keep it until removed. */
516
- count?: number;
517
- /** Fault this fraction of matching requests, `0`–`1`. Default `1`. */
518
- rate?: number;
519
- /** Hold the response back this long, to exercise timeouts. */
558
+ /** Hold the response back this long. Listed as `delayMs`. */
559
+ delay?: Duration;
560
+ /** `delay`, in milliseconds. */
520
561
  delayMs?: number;
521
562
  /** Alias of `delayMs`. */
522
563
  latencyMs?: number;
564
+ /** Extra seeded delay in `[0, jitter]`. Listed as `jitterMs`. */
565
+ jitter?: Duration;
566
+ jitterMs?: number;
567
+ /**
568
+ * Never answer: hold the request this long, then drop the connection. Listed as
569
+ * `timeoutMs`. With virtual time the wait is spent on the mock clock.
570
+ */
571
+ timeout?: Duration;
572
+ timeoutMs?: number;
523
573
  /**
524
574
  * Drop the connection instead of answering: an in-process `fetch` rejects with a
525
575
  * `TypeError`, and a served mock destroys the socket. Models "unknown outcome" failures.
526
576
  */
527
577
  drop?: boolean;
578
+ /**
579
+ * Cut the response body off after this many bytes: the status and headers arrive, then
580
+ * the connection dies mid-body.
581
+ */
582
+ truncate?: number;
528
583
  /**
529
584
  * A named service behaviour to switch on for the matching request instead of (or
530
585
  * before) a canned response, e.g. `created_but_500` or `numeric_tracking_id`. Services
@@ -533,8 +588,8 @@ type FaultRule = {
533
588
  effect?: string;
534
589
  /** Parameters for `effect`. */
535
590
  params?: Record<string, unknown>;
536
- /** From the preset this rule was expanded from, if any. */
537
- preset?: string;
591
+ /** The preset this rule was expanded from, if any. */
592
+ fromPreset?: string;
538
593
  };
539
594
  /** A fault that fired for one request. */
540
595
  type FaultHit = {
@@ -542,6 +597,10 @@ type FaultHit = {
542
597
  /** The injected response; absent when the rule only delays, drops, or sets an effect. */
543
598
  response?: Response;
544
599
  drop?: boolean;
600
+ /** Set with `drop` when the rule held the request for its `timeout` first. */
601
+ timeout?: boolean;
602
+ /** Bytes of response body to let through before the connection dies. */
603
+ truncate?: number;
545
604
  effect?: {
546
605
  name: string;
547
606
  params: Record<string, unknown>;
@@ -566,38 +625,200 @@ type FaultCandidate = {
566
625
  method: string;
567
626
  path: string;
568
627
  namespace: string;
628
+ /** Request headers and query, for rules that match on them. */
629
+ headers?: Headers;
630
+ query?: URLSearchParams;
631
+ /** The namespace clock, for `from` / `until`. Rules with a window are skipped without it. */
632
+ now?: number;
633
+ /** How to spend a delay for this request. Default: the registry's own sleep. */
634
+ wait?: (ms: number) => Promise<void>;
635
+ };
636
+ /** A stored rule and how often it was consulted. */
637
+ type FaultListing = FaultRule & {
638
+ /** Faults left before the rule retires. `null` when it has no `count`. */
639
+ remaining: number | null;
640
+ /** Times the rule faulted a request. */
641
+ hits: number;
642
+ /** Requests that matched the rule, faulted or not. */
643
+ seen: number;
644
+ };
645
+ /** A namespace's own rules, with their counters, in the order they are tried. */
646
+ type FaultSnapshot = {
647
+ /**
648
+ * `position` is how many `"*"` rules are tried before the rule, which is what its place
649
+ * in the order means to a request and holds in any process.
650
+ */
651
+ rules: (FaultListing & {
652
+ position?: number;
653
+ })[];
654
+ /** How many `fault_<n>` ids the namespace has handed out. */
655
+ nextId?: number;
569
656
  };
570
657
  type FaultRegistry = {
571
- isolateNamespaces(): void;
572
- snapshot(namespace: string): {
573
- rules: (FaultRule & {
574
- remaining: number | null;
575
- hits: number;
576
- position: number;
577
- })[];
578
- rngState: number;
579
- };
658
+ snapshot(namespace: string): FaultSnapshot;
659
+ /** Add a rule, or replace the rule with the same id in the same namespace. */
580
660
  add(rule: FaultRule): FaultRule;
581
- list(): (FaultRule & {
582
- remaining: number | null;
583
- hits: number;
584
- })[];
585
- remove(id: string): boolean;
586
- clear(): void;
587
- restore(namespace: string, state: {
588
- rules: (FaultRule & {
589
- remaining: number | null;
590
- hits: number;
591
- position: number;
592
- })[];
593
- rngState: number;
594
- }): void;
661
+ /** The next unused `fault_<n>` id in `namespace`. */
662
+ nextId(namespace: string): string;
663
+ /** Every rule, or the rules a namespace's requests can hit: its own and the global ones. */
664
+ list(namespace?: string): FaultListing[];
665
+ get(id: string, namespace?: string): FaultListing | undefined;
666
+ /** Remove a rule by id: from `namespace` (its own, then a global one), or wherever it is. */
667
+ remove(id: string, namespace?: string): boolean;
668
+ /** Remove every rule, or one namespace's own rules. */
669
+ clear(namespace?: string): void;
670
+ /** Replace a namespace's own rules with a snapshot's, wherever the snapshot was taken. */
671
+ restore(namespace: string, state: FaultSnapshot): void;
595
672
  /**
596
673
  * Every fault this request should get, in rule order, stopping at the first that answers
597
674
  * or drops (effect-only and delay-only rules let later rules match too). Consumes one of
598
675
  * each matching rule's remaining uses.
599
676
  */
600
677
  take(candidate: FaultCandidate): Promise<FaultHit[]>;
678
+ /**
679
+ * Fire these rules at one request without storing them: no matching, no schedule, in order,
680
+ * stopping at the first that answers or drops. Jitter draws from the namespace's stream.
681
+ */
682
+ fire(rules: readonly FaultRule[], candidate: FaultCandidate): Promise<FaultHit[]>;
683
+ };
684
+
685
+ /**
686
+ * The admin controls every mock shares, as one document.
687
+ *
688
+ * The same shape is accepted in three places, and means the same thing in each:
689
+ *
690
+ * - at boot: `createRuntime({ adminControls })`, `serve --admin-controls`,
691
+ * `MOCKINGBIRD_ADMIN_CONTROLS`
692
+ * - over HTTP: `PUT /__admin/controls`
693
+ * - per request: the `x-mockingbird-*` headers in {@link CONTROL_HEADERS}
694
+ *
695
+ * Every control is deterministic: given the same seed, clock and requests, a mock answers
696
+ * the same bytes. Nothing here reads the wall clock or `Math.random`.
697
+ */
698
+ /** Milliseconds, or a string like `"250ms"`, `"2s"`, `"15m"`, `"1h"`, `"3d"`. */
699
+ type Duration = number | string;
700
+ /** Epoch milliseconds, or an ISO-8601 string. */
701
+ type Instant = number | string;
702
+ type ClockControls = {
703
+ /** Move the clock to this instant. */
704
+ now?: Instant;
705
+ /** Stop time. A frozen clock moves only when told to, so timestamps replay exactly. */
706
+ frozen?: boolean;
707
+ /**
708
+ * Step the clock forward by this much before every vendor request. With a frozen clock
709
+ * each request still gets its own, reproducible timestamp.
710
+ */
711
+ autoAdvance?: Duration;
712
+ };
713
+ /** How long a response takes: a fixed delay plus seeded jitter in `[0, jitter]`. */
714
+ type LatencyRuleInput = {
715
+ delay?: Duration;
716
+ jitter?: Duration;
717
+ };
718
+ type LatencyControls = LatencyRuleInput & {
719
+ /** Per-operation overrides, keyed by operationId. A bare duration is its `delay`. */
720
+ operations?: Record<string, Duration | LatencyRuleInput>;
721
+ };
722
+ /** A fault to add: a rule (the id is assigned when omitted), or a named preset with overrides. */
723
+ type FaultInput = (Omit<FaultRule, "id"> & {
724
+ id?: string;
725
+ }) | ({
726
+ preset: string;
727
+ } & Partial<FaultRule>);
728
+ /** Identifies a {@link SnapshotDocument}. */
729
+ declare const SNAPSHOT_FORMAT = "mockingbird.snapshot/v1";
730
+ /**
731
+ * A namespace, as portable JSON: what `GET /__admin/snapshots/:id` returns and what
732
+ * `PUT /__admin/snapshots/:id` and the boot `snapshot` control accept. Only `format` and
733
+ * `records` are required, so a hand-written seed file is a valid snapshot.
734
+ */
735
+ type SnapshotDocument = {
736
+ format: typeof SNAPSHOT_FORMAT;
737
+ /** The service that wrote it. A snapshot is rejected by any other service. */
738
+ service?: string;
739
+ /**
740
+ * Stored rows. `seq` orders a collection; omitted, rows keep their listed order. `raw` is
741
+ * the stored text of a row that is not a plain record, and replaces `value` when present.
742
+ */
743
+ records: {
744
+ collection: string;
745
+ id: string;
746
+ seq?: number;
747
+ value?: unknown;
748
+ raw?: string;
749
+ }[];
750
+ /** Id counters, so the next generated id continues where the snapshot left off. */
751
+ sequences?: {
752
+ name: string;
753
+ kind: string;
754
+ value: number;
755
+ }[];
756
+ clock?: {
757
+ now: number;
758
+ frozen: boolean;
759
+ autoAdvanceMs?: number;
760
+ };
761
+ seed?: number | string;
762
+ /** Positions of the seeded random streams. */
763
+ rng?: {
764
+ state: number;
765
+ faults?: number;
766
+ latency?: number;
767
+ };
768
+ faults?: unknown;
769
+ latency?: unknown;
770
+ virtualTime?: boolean;
771
+ };
772
+ /** Controls for one namespace. */
773
+ type NamespaceControls = {
774
+ /** Seeds every random choice: fault rates, jitter, and whatever the service invents. */
775
+ seed?: number | string;
776
+ clock?: ClockControls;
777
+ /**
778
+ * Spend injected waits (latency, fault delays, timeouts) on the mock clock instead of the
779
+ * wall clock: the request returns at once, the clock has moved, and the journal records
780
+ * the wait exactly. Default `false`: waits are real, so a client's own timeout can fire.
781
+ */
782
+ virtualTime?: boolean;
783
+ /** Baseline response time for every vendor request. A bare duration is its `delay`. */
784
+ latency?: Duration | LatencyControls;
785
+ faults?: readonly FaultInput[];
786
+ /** Start from this state instead of the service's own seed data. */
787
+ snapshot?: SnapshotDocument;
788
+ };
789
+ /** {@link NamespaceControls} for every namespace, with per-namespace overrides. */
790
+ type MockControls = NamespaceControls & {
791
+ /** Vendor credential → namespace, for SDKs that cannot send a namespace header. */
792
+ credentials?: Record<string, string>;
793
+ /** Overrides for named namespaces. A key given here replaces the shared value. */
794
+ namespaces?: Record<string, NamespaceControls>;
795
+ };
796
+ /** A latency rule in milliseconds. */
797
+ type LatencyRule = {
798
+ delayMs: number;
799
+ jitterMs: number;
800
+ };
801
+ /** Baseline latency for a namespace, normalized. */
802
+ type LatencyState = LatencyRule & {
803
+ operations: Record<string, LatencyRule>;
804
+ };
805
+ /** What {@link controlHeaders} turns into request headers. */
806
+ type ControlHeaderInput = {
807
+ namespace?: string;
808
+ adminKey?: string;
809
+ branch?: string;
810
+ at?: string;
811
+ reset?: boolean;
812
+ restore?: string;
813
+ seed?: number | string;
814
+ time?: Instant | Date;
815
+ advance?: Duration;
816
+ virtualTime?: boolean;
817
+ delay?: Duration;
818
+ timeout?: Duration;
819
+ /** A status, `"drop"`, a preset name, or a fault rule. */
820
+ fault?: number | string | Record<string, unknown>;
821
+ snapshot?: string;
601
822
  };
602
823
 
603
824
  /**
@@ -637,6 +858,8 @@ type RequestLog = {
637
858
  unmatched: boolean;
638
859
  /** Set when a fault rule produced the response. */
639
860
  faultId?: string;
861
+ /** Milliseconds of injected wait: latency, fault delays and timeouts. Absent when none. */
862
+ delayMs?: number;
640
863
  /** Resource ids the handler touched (`userId`, `orderId`, …), when the service reports them. */
641
864
  ids?: Record<string, string>;
642
865
  /** Set when the service created a resource the request referred to but that did not exist. */
@@ -682,6 +905,12 @@ type JournalQuery = {
682
905
  /** Only this namespace. Omit for every namespace, oldest first across all of them. */
683
906
  namespace?: string;
684
907
  operationId?: string;
908
+ /** Only this HTTP method, case-insensitive. */
909
+ method?: string;
910
+ /** Only this exact path. */
911
+ path?: string;
912
+ /** Only requests this fault rule answered or shaped. */
913
+ faultId?: string;
685
914
  status?: number;
686
915
  /** Only entries at or after this instant (epoch ms). */
687
916
  since?: number;
@@ -696,6 +925,50 @@ type Journal = {
696
925
  clear(namespace?: string): void;
697
926
  };
698
927
 
928
+ /**
929
+ * Baseline response time, per namespace: how long every vendor request takes before any
930
+ * fault is considered. Jitter draws from a stream the caller owns, one per namespace and
931
+ * separate from the fault stream, so adding latency never shifts which requests a `rate`
932
+ * fault hits.
933
+ */
934
+ type LatencyRegistry = {
935
+ get(namespace: string): LatencyState;
936
+ set(namespace: string, state: LatencyState): LatencyState;
937
+ /** Remove one namespace's latency, or every namespace's. */
938
+ clear(namespace?: string): void;
939
+ /** Milliseconds this request waits. Draws jitter, so call it once per request. */
940
+ take(namespace: string, operationId: string | undefined): number;
941
+ };
942
+
943
+ /** Clock state as the admin API reports it. */
944
+ type ControlClock = ClockState & {
945
+ /** `now`, as ISO-8601. */
946
+ iso: string;
947
+ /** Milliseconds the clock steps before every vendor request. */
948
+ autoAdvanceMs: number;
949
+ };
950
+ /** One namespace's controls: the body of `GET /__admin/controls`. */
951
+ type ControlState = {
952
+ namespace: string;
953
+ seed: number | string;
954
+ clock: ControlClock;
955
+ virtualTime: boolean;
956
+ latency: LatencyState;
957
+ faults: FaultListing[];
958
+ };
959
+
960
+ /** What `GET /__admin/snapshots` lists for each snapshot. */
961
+ type SnapshotInfo = {
962
+ id: string;
963
+ namespace: string;
964
+ /** Stored rows in the snapshot. */
965
+ records: number;
966
+ /** The namespace clock when it was taken, epoch ms. */
967
+ at: number;
968
+ /** Whether `GET /snapshots/:id` can return it as a {@link SnapshotDocument}. */
969
+ portable: boolean;
970
+ };
971
+
699
972
  /** Credential → namespace mapping behind `PUT /__admin/credentials`. */
700
973
  type CredentialRegistry = {
701
974
  set(credential: string, namespace: string): void;
@@ -850,7 +1123,10 @@ type ServiceInstance = FetchAPI & {
850
1123
  };
851
1124
  type ServiceTimelineState = Readonly<{
852
1125
  snapshot: NamespaceSnapshot;
853
- clock: Readonly<ReturnType<Clock["state"]>>;
1126
+ /** `pinned`: the namespace's clock was frozen itself, not just following a frozen base. */
1127
+ clock: Readonly<ClockState & {
1128
+ pinned?: boolean;
1129
+ }>;
854
1130
  rngState: number;
855
1131
  }>;
856
1132
  type ServiceCheckpoint = Checkpoint<ServiceTimelineState>;
@@ -858,17 +1134,23 @@ type ServiceRuntime<T extends ServiceInstance> = FetchAPI & {
858
1134
  /** Stop package-owned lifecycle timers when a supervisor closes the runtime. */
859
1135
  stop?(): void;
860
1136
  readonly name: string;
1137
+ /** Same-origin Fetch handler and App Router method exports, sharing this runtime. */
1138
+ mount(prefix: string): MountedAPI;
861
1139
  readonly sqlite: SqliteClient$1;
862
1140
  readonly clock: Clock;
863
1141
  readonly faults: FaultRegistry;
1142
+ /** Baseline response time per namespace. */
1143
+ readonly latency: LatencyRegistry;
864
1144
  readonly metrics: Metrics;
865
1145
  readonly journal: Journal;
866
1146
  readonly rng: Rng;
867
1147
  readonly credentials: CredentialRegistry;
868
1148
  /** The webhook hub, when the service has outbound webhooks. */
869
1149
  readonly webhooks: WebhookHub | undefined;
870
- /** Enable independent namespace clocks and PRNGs before serving a fleet. */
871
- isolateNamespaces(): void;
1150
+ /**
1151
+ * A namespace's clock. Each follows the base clock, {@link ServiceRuntime.clock}, with an
1152
+ * offset and a freeze of its own, so moving one never moves another.
1153
+ */
872
1154
  namespaceClock(namespace?: string): Clock;
873
1155
  namespaceOf(request: Request): string;
874
1156
  /** Opaque in-process checkpoint including records, controls and webhook history. */
@@ -880,8 +1162,38 @@ type ServiceRuntime<T extends ServiceInstance> = FetchAPI & {
880
1162
  instance(namespace?: string): T;
881
1163
  /** Public names of every namespace created so far. */
882
1164
  namespaces(): string[];
883
- /** Reset one namespace, or every namespace with `"*"`. */
1165
+ /** Return one namespace to its boot state, or every namespace with `"*"`. */
884
1166
  reset(namespace?: string): Promise<void>;
1167
+ /** Reset a namespace and forget it, releasing everything it held. */
1168
+ dropNamespace(namespace: string): Promise<void>;
1169
+ /** A namespace's controls: seed, clock, virtual time, latency, faults and snapshots. */
1170
+ controls(namespace?: string): ControlState & {
1171
+ snapshots: SnapshotInfo[];
1172
+ };
1173
+ /** Apply a control document to a namespace. A given key replaces that control. */
1174
+ configure(controls: NamespaceControls, namespace?: string): ControlState & {
1175
+ snapshots: SnapshotInfo[];
1176
+ };
1177
+ /** Named snapshots of a namespace: records, clock, random streams, faults and latency. */
1178
+ readonly snapshots: {
1179
+ /** Capture the namespace now. Reusing a name replaces that snapshot. */
1180
+ create(options?: {
1181
+ name?: string;
1182
+ namespace?: string;
1183
+ }): SnapshotInfo;
1184
+ list(namespace?: string): SnapshotInfo[];
1185
+ /** The snapshot as portable JSON, to commit beside a suite or boot another mock from. */
1186
+ export(id: string, namespace?: string): SnapshotDocument;
1187
+ /** Store a document as a snapshot without restoring it. */
1188
+ import(document: SnapshotDocument, options?: {
1189
+ name?: string;
1190
+ namespace?: string;
1191
+ }): SnapshotInfo;
1192
+ restore(id: string, namespace?: string): void;
1193
+ delete(id: string, namespace?: string): boolean;
1194
+ };
1195
+ /** Request headers that carry controls, checked: spread them into a `fetch` or an SDK's defaults. */
1196
+ headers(input: ControlHeaderInput): Record<string, string>;
885
1197
  snapshot(namespace?: string): NamespaceSnapshot;
886
1198
  restore(snapshot: NamespaceSnapshot, namespace?: string): void;
887
1199
  /** Capture the current branch. Mutating HTTP calls do this automatically. */
@@ -1240,6 +1552,8 @@ type FormbricksRuntimeOptions = {
1240
1552
  seed?: number | string;
1241
1553
  adminPrefix?: string;
1242
1554
  adminKey?: string;
1555
+ /** Admin controls to boot with: clock, latency, faults, seed, a starting snapshot. */
1556
+ adminControls?: MockControls;
1243
1557
  onLog?: (entry: RequestLog) => void;
1244
1558
  surveys?: readonly Survey[];
1245
1559
  settings?: Partial<Settings>;