@crvouga/mockingbird-service-formbricks 3.2.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
@@ -455,7 +455,7 @@ type ClockState = {
455
455
  now: number;
456
456
  /** True while time does not advance on its own. */
457
457
  frozen: boolean;
458
- /** Milliseconds this clock adds to its underlying source. */
458
+ /** Milliseconds a running clock adds to its underlying source. `0` while frozen. */
459
459
  offsetMs: number;
460
460
  };
461
461
  type Clock = {
@@ -491,7 +491,10 @@ type Rng = {
491
491
  state(): number;
492
492
  /** Restore a state previously returned by {@link state}. */
493
493
  setState(state: number): void;
494
- 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;
495
498
  };
496
499
 
497
500
  /**
@@ -500,44 +503,83 @@ type Rng = {
500
503
  * This is how a suite reaches the vendor's failure modes without the vendor: the
501
504
  * quota error that only appears when a shared sandbox is full, the 429 that only
502
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`).
503
510
  */
504
511
  type FaultRule = {
505
- /** 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. */
506
513
  id: string;
507
514
  /** Fault only this operation. Omit to match every operation. */
508
515
  operationId?: string;
509
516
  /** Fault only this HTTP method, case-insensitive. Omit to match every method. */
510
517
  method?: string;
518
+ /** Fault only this exact path. */
519
+ path?: string;
511
520
  /** Fault only paths starting with this prefix. Omit to match every path. */
512
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>;
513
528
  /**
514
529
  * Fault only this namespace. Omit (or `"*"`) to fault every namespace — which is what
515
530
  * an in-process caller usually wants, and what a parallel worker usually does not:
516
531
  * rules added through `POST /__admin/faults` default to the calling namespace.
517
532
  */
518
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;
519
549
  /**
520
- * Status of the injected response. Omit for a rule that only delays (`delayMs` /
521
- * `latencyMs`), only drops the connection (`drop`), or only switches on an `effect`:
522
- * 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.
523
552
  */
524
553
  status?: number;
525
554
  /** Response body, serialized as JSON. A string is sent as-is. */
526
555
  body?: unknown;
556
+ /** Response headers. */
527
557
  headers?: Record<string, string>;
528
- /** Retire the rule after this many faults. Omit to keep it until removed. */
529
- count?: number;
530
- /** Fault this fraction of matching requests, `0`–`1`. Default `1`. */
531
- rate?: number;
532
- /** 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. */
533
561
  delayMs?: number;
534
562
  /** Alias of `delayMs`. */
535
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;
536
573
  /**
537
574
  * Drop the connection instead of answering: an in-process `fetch` rejects with a
538
575
  * `TypeError`, and a served mock destroys the socket. Models "unknown outcome" failures.
539
576
  */
540
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;
541
583
  /**
542
584
  * A named service behaviour to switch on for the matching request instead of (or
543
585
  * before) a canned response, e.g. `created_but_500` or `numeric_tracking_id`. Services
@@ -546,8 +588,8 @@ type FaultRule = {
546
588
  effect?: string;
547
589
  /** Parameters for `effect`. */
548
590
  params?: Record<string, unknown>;
549
- /** From the preset this rule was expanded from, if any. */
550
- preset?: string;
591
+ /** The preset this rule was expanded from, if any. */
592
+ fromPreset?: string;
551
593
  };
552
594
  /** A fault that fired for one request. */
553
595
  type FaultHit = {
@@ -555,6 +597,10 @@ type FaultHit = {
555
597
  /** The injected response; absent when the rule only delays, drops, or sets an effect. */
556
598
  response?: Response;
557
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;
558
604
  effect?: {
559
605
  name: string;
560
606
  params: Record<string, unknown>;
@@ -579,38 +625,200 @@ type FaultCandidate = {
579
625
  method: string;
580
626
  path: string;
581
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;
582
656
  };
583
657
  type FaultRegistry = {
584
- isolateNamespaces(): void;
585
- snapshot(namespace: string): {
586
- rules: (FaultRule & {
587
- remaining: number | null;
588
- hits: number;
589
- position: number;
590
- })[];
591
- rngState: number;
592
- };
658
+ snapshot(namespace: string): FaultSnapshot;
659
+ /** Add a rule, or replace the rule with the same id in the same namespace. */
593
660
  add(rule: FaultRule): FaultRule;
594
- list(): (FaultRule & {
595
- remaining: number | null;
596
- hits: number;
597
- })[];
598
- remove(id: string): boolean;
599
- clear(): void;
600
- restore(namespace: string, state: {
601
- rules: (FaultRule & {
602
- remaining: number | null;
603
- hits: number;
604
- position: number;
605
- })[];
606
- rngState: number;
607
- }): 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;
608
672
  /**
609
673
  * Every fault this request should get, in rule order, stopping at the first that answers
610
674
  * or drops (effect-only and delay-only rules let later rules match too). Consumes one of
611
675
  * each matching rule's remaining uses.
612
676
  */
613
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;
614
822
  };
615
823
 
616
824
  /**
@@ -650,6 +858,8 @@ type RequestLog = {
650
858
  unmatched: boolean;
651
859
  /** Set when a fault rule produced the response. */
652
860
  faultId?: string;
861
+ /** Milliseconds of injected wait: latency, fault delays and timeouts. Absent when none. */
862
+ delayMs?: number;
653
863
  /** Resource ids the handler touched (`userId`, `orderId`, …), when the service reports them. */
654
864
  ids?: Record<string, string>;
655
865
  /** Set when the service created a resource the request referred to but that did not exist. */
@@ -695,6 +905,12 @@ type JournalQuery = {
695
905
  /** Only this namespace. Omit for every namespace, oldest first across all of them. */
696
906
  namespace?: string;
697
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;
698
914
  status?: number;
699
915
  /** Only entries at or after this instant (epoch ms). */
700
916
  since?: number;
@@ -709,6 +925,50 @@ type Journal = {
709
925
  clear(namespace?: string): void;
710
926
  };
711
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
+
712
972
  /** Credential → namespace mapping behind `PUT /__admin/credentials`. */
713
973
  type CredentialRegistry = {
714
974
  set(credential: string, namespace: string): void;
@@ -863,7 +1123,10 @@ type ServiceInstance = FetchAPI & {
863
1123
  };
864
1124
  type ServiceTimelineState = Readonly<{
865
1125
  snapshot: NamespaceSnapshot;
866
- 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
+ }>;
867
1130
  rngState: number;
868
1131
  }>;
869
1132
  type ServiceCheckpoint = Checkpoint<ServiceTimelineState>;
@@ -876,14 +1139,18 @@ type ServiceRuntime<T extends ServiceInstance> = FetchAPI & {
876
1139
  readonly sqlite: SqliteClient$1;
877
1140
  readonly clock: Clock;
878
1141
  readonly faults: FaultRegistry;
1142
+ /** Baseline response time per namespace. */
1143
+ readonly latency: LatencyRegistry;
879
1144
  readonly metrics: Metrics;
880
1145
  readonly journal: Journal;
881
1146
  readonly rng: Rng;
882
1147
  readonly credentials: CredentialRegistry;
883
1148
  /** The webhook hub, when the service has outbound webhooks. */
884
1149
  readonly webhooks: WebhookHub | undefined;
885
- /** Enable independent namespace clocks and PRNGs before serving a fleet. */
886
- 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
+ */
887
1154
  namespaceClock(namespace?: string): Clock;
888
1155
  namespaceOf(request: Request): string;
889
1156
  /** Opaque in-process checkpoint including records, controls and webhook history. */
@@ -895,8 +1162,38 @@ type ServiceRuntime<T extends ServiceInstance> = FetchAPI & {
895
1162
  instance(namespace?: string): T;
896
1163
  /** Public names of every namespace created so far. */
897
1164
  namespaces(): string[];
898
- /** Reset one namespace, or every namespace with `"*"`. */
1165
+ /** Return one namespace to its boot state, or every namespace with `"*"`. */
899
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>;
900
1197
  snapshot(namespace?: string): NamespaceSnapshot;
901
1198
  restore(snapshot: NamespaceSnapshot, namespace?: string): void;
902
1199
  /** Capture the current branch. Mutating HTTP calls do this automatically. */
@@ -1255,6 +1552,8 @@ type FormbricksRuntimeOptions = {
1255
1552
  seed?: number | string;
1256
1553
  adminPrefix?: string;
1257
1554
  adminKey?: string;
1555
+ /** Admin controls to boot with: clock, latency, faults, seed, a starting snapshot. */
1556
+ adminControls?: MockControls;
1258
1557
  onLog?: (entry: RequestLog) => void;
1259
1558
  surveys?: readonly Survey[];
1260
1559
  settings?: Partial<Settings>;
package/dist/index.js CHANGED
@@ -14,7 +14,7 @@ import {
14
14
  operationIds,
15
15
  supportedOperationIds,
16
16
  validateResponseData
17
- } from "./chunk-CRUFKJZU.js";
17
+ } from "./chunk-HE5W4CHW.js";
18
18
  export {
19
19
  CORPUS_SURVEYS,
20
20
  DEFAULT_SETTINGS,