@crvouga/mockingbird-service-customerio 0.1.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.
@@ -0,0 +1,1376 @@
1
+ import { Server } from 'node:http';
2
+ import { Hono } from 'hono';
3
+
4
+ /**
5
+ * The single source of time for a service.
6
+ *
7
+ * Every timestamp a mock writes reads from here, so a suite moves time instead of
8
+ * sleeping: appointment windows, result delays and expiries become reachable in
9
+ * milliseconds. A frozen clock also makes timestamps reproducible from a seed.
10
+ */
11
+ type ClockState$1 = {
12
+ /** Current epoch milliseconds. */
13
+ now: number;
14
+ /** True while time does not advance on its own. */
15
+ frozen: boolean;
16
+ /** Milliseconds this clock adds to its underlying source. */
17
+ offsetMs: number;
18
+ };
19
+ type Clock$1 = {
20
+ now(): number;
21
+ /** Pin the clock to an exact instant, keeping it frozen if it already was. */
22
+ set(epochMs: number): void;
23
+ /** Move the clock forward, or back with a negative delta. */
24
+ advance(deltaMs: number): void;
25
+ /** Stop time at the current instant. */
26
+ freeze(): void;
27
+ /** Resume from the current instant. */
28
+ unfreeze(): void;
29
+ /** Drop back to the underlying source, live. */
30
+ reset(): void;
31
+ state(): ClockState$1;
32
+ };
33
+
34
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
35
+ type SqliteValue$2 = null | number | bigint | string | Uint8Array | boolean;
36
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
37
+ type SqliteRunResult$2 = {
38
+ changes: number;
39
+ lastInsertRowid: number | bigint;
40
+ };
41
+ /**
42
+ * Prepared statement bound to a {@link SqliteClient}.
43
+ *
44
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
45
+ */
46
+ interface SqliteStatement$2 {
47
+ run(...params: SqliteValue$2[]): SqliteRunResult$2;
48
+ all<T = Record<string, unknown>>(...params: SqliteValue$2[]): T[];
49
+ get<T = Record<string, unknown>>(...params: SqliteValue$2[]): T | undefined;
50
+ }
51
+ /**
52
+ * Sync SQLite client port owned by Mockingbird.
53
+ *
54
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
55
+ * `bun:sqlite` instances all work when they expose this surface.
56
+ */
57
+ interface SqliteClient$2 {
58
+ exec(sql: string): void;
59
+ prepare(sql: string): SqliteStatement$2;
60
+ transaction<T>(fn: () => T): T;
61
+ }
62
+
63
+ /**
64
+ * Seeded pseudo-random numbers, so anything a mock invents — ids, jitter, which
65
+ * request a percentage fault hits — is reproducible from a seed.
66
+ *
67
+ * mulberry32: small, fast, and stable across runtimes, which matters more here
68
+ * than statistical quality.
69
+ */
70
+ type Rng$1 = {
71
+ /** Next value in `[0, 1)`. */
72
+ next(): number;
73
+ /** Next integer in `[min, max]`. */
74
+ int(min: number, max: number): number;
75
+ /** Restart the stream from its seed. */
76
+ reset(): void;
77
+ /** Serializable engine state used by deterministic checkpoints. */
78
+ state(): number;
79
+ /** Restore a state previously returned by {@link state}. */
80
+ setState(state: number): void;
81
+ seed: number;
82
+ };
83
+
84
+ /**
85
+ * A deliberate failure injected in front of an operation.
86
+ *
87
+ * This is how a suite reaches the vendor's failure modes without the vendor: the
88
+ * quota error that only appears when a shared sandbox is full, the 429 that only
89
+ * appears under load, the 5xx that proves a retry path works.
90
+ */
91
+ type FaultRule$1 = {
92
+ /** Stable id, so a suite can retire exactly the rule it added. */
93
+ id: string;
94
+ /** Fault only this operation. Omit to match every operation. */
95
+ operationId?: string;
96
+ /** Fault only this HTTP method, case-insensitive. Omit to match every method. */
97
+ method?: string;
98
+ /** Fault only paths starting with this prefix. Omit to match every path. */
99
+ pathPrefix?: string;
100
+ /**
101
+ * Fault only this namespace. Omit (or `"*"`) to fault every namespace — which is what
102
+ * an in-process caller usually wants, and what a parallel worker usually does not:
103
+ * rules added through `POST /__admin/faults` default to the calling namespace.
104
+ */
105
+ namespace?: string;
106
+ /**
107
+ * Status of the injected response. Omit for a rule that only delays (`delayMs` /
108
+ * `latencyMs`), only drops the connection (`drop`), or only switches on an `effect`:
109
+ * the request then still reaches the service.
110
+ */
111
+ status?: number;
112
+ /** Response body, serialized as JSON. A string is sent as-is. */
113
+ body?: unknown;
114
+ headers?: Record<string, string>;
115
+ /** Retire the rule after this many faults. Omit to keep it until removed. */
116
+ count?: number;
117
+ /** Fault this fraction of matching requests, `0`–`1`. Default `1`. */
118
+ rate?: number;
119
+ /** Hold the response back this long, to exercise timeouts. */
120
+ delayMs?: number;
121
+ /** Alias of `delayMs`. */
122
+ latencyMs?: number;
123
+ /**
124
+ * Drop the connection instead of answering: an in-process `fetch` rejects with a
125
+ * `TypeError`, and a served mock destroys the socket. Models "unknown outcome" failures.
126
+ */
127
+ drop?: boolean;
128
+ /**
129
+ * A named service behaviour to switch on for the matching request instead of (or
130
+ * before) a canned response, e.g. `created_but_500` or `numeric_tracking_id`. Services
131
+ * read it with `faultEffects(request)`.
132
+ */
133
+ effect?: string;
134
+ /** Parameters for `effect`. */
135
+ params?: Record<string, unknown>;
136
+ /** From the preset this rule was expanded from, if any. */
137
+ preset?: string;
138
+ };
139
+ /** A fault that fired for one request. */
140
+ type FaultHit$1 = {
141
+ id: string;
142
+ /** The injected response; absent when the rule only delays, drops, or sets an effect. */
143
+ response?: Response;
144
+ drop?: boolean;
145
+ effect?: {
146
+ name: string;
147
+ params: Record<string, unknown>;
148
+ };
149
+ };
150
+ /** What a request looks like to the fault matcher. */
151
+ type FaultCandidate$1 = {
152
+ operationId: string | undefined;
153
+ method: string;
154
+ path: string;
155
+ namespace: string;
156
+ };
157
+ type FaultRegistry$1 = {
158
+ add(rule: FaultRule$1): FaultRule$1;
159
+ list(): (FaultRule$1 & {
160
+ remaining: number | null;
161
+ hits: number;
162
+ })[];
163
+ remove(id: string): boolean;
164
+ clear(): void;
165
+ /**
166
+ * Every fault this request should get, in rule order, stopping at the first that answers
167
+ * or drops (effect-only and delay-only rules let later rules match too). Consumes one of
168
+ * each matching rule's remaining uses.
169
+ */
170
+ take(candidate: FaultCandidate$1): Promise<FaultHit$1[]>;
171
+ };
172
+
173
+ /** One handled request, as the structured log sees it. */
174
+ type RequestLog$1 = {
175
+ service: string;
176
+ namespace: string;
177
+ operationId: string | undefined;
178
+ method: string;
179
+ path: string;
180
+ status: number;
181
+ durationMs: number;
182
+ /** True when the path matched no operation in the contract. */
183
+ unmatched: boolean;
184
+ /** Set when a fault rule produced the response. */
185
+ faultId?: string;
186
+ /** Resource ids the handler touched (`userId`, `orderId`, …), when the service reports them. */
187
+ ids?: Record<string, string>;
188
+ /** Set when the service created a resource the request referred to but that did not exist. */
189
+ adopted?: boolean;
190
+ };
191
+ type MetricsReport$1 = {
192
+ requests: number;
193
+ /** Counts keyed `<operationId> <status>`. */
194
+ byOperation: Record<string, number>;
195
+ /**
196
+ * Paths that matched no operation, most frequent first.
197
+ *
198
+ * This is the early-warning signal: a consumer calling something the mock does
199
+ * not implement shows up here as a count, before it fails a suite as a 404.
200
+ */
201
+ unmatched: {
202
+ method: string;
203
+ path: string;
204
+ count: number;
205
+ }[];
206
+ faults: number;
207
+ totalDurationMs: number;
208
+ };
209
+ type Metrics$1 = {
210
+ record(entry: RequestLog$1): void;
211
+ report(): MetricsReport$1;
212
+ reset(): void;
213
+ };
214
+
215
+ /** One journal entry: a request log stamped with when (on the mock clock) it was handled. */
216
+ type JournalEntry$1 = RequestLog$1 & {
217
+ at: string;
218
+ };
219
+ type JournalQuery$1 = {
220
+ /** Only this namespace. Omit for every namespace, oldest first across all of them. */
221
+ namespace?: string;
222
+ operationId?: string;
223
+ status?: number;
224
+ /** Only entries at or after this instant (epoch ms). */
225
+ since?: number;
226
+ /** At most this many, the most recent kept. */
227
+ limit?: number;
228
+ };
229
+ type Journal$1 = {
230
+ readonly size: number;
231
+ record(entry: JournalEntry$1): void;
232
+ list(query?: JournalQuery$1): JournalEntry$1[];
233
+ /** Forget one namespace's entries, or every namespace's. */
234
+ clear(namespace?: string): void;
235
+ };
236
+
237
+ /** Credential → namespace mapping behind `PUT /__admin/credentials`. */
238
+ type CredentialRegistry$1 = {
239
+ set(credential: string, namespace: string): void;
240
+ get(credential: string): string | undefined;
241
+ remove(credential: string): boolean;
242
+ clear(): void;
243
+ entries(): {
244
+ credential: string;
245
+ namespace: string;
246
+ }[];
247
+ };
248
+
249
+ /** A stable identifier for a point in a {@link Timeline}. */
250
+ type CheckpointId$1 = string;
251
+ /** An immutable node in a timeline's checkpoint DAG. */
252
+ type Checkpoint$1<T> = Readonly<{
253
+ id: CheckpointId$1;
254
+ branch: string;
255
+ parent: CheckpointId$1 | null;
256
+ /** Logical time supplied by the timeline's injected clock. */
257
+ at: number;
258
+ value: T;
259
+ }>;
260
+ type TimelineOptions$1 = {
261
+ /** Logical clock used to stamp checkpoints. Defaults to a deterministic counter. */
262
+ now?: () => number;
263
+ /** Maximum retained checkpoints. Branch heads are never collected. Default 1,000. */
264
+ maxCheckpoints?: number;
265
+ /** Customize deterministic checkpoint IDs. */
266
+ id?: (sequence: number) => CheckpointId$1;
267
+ };
268
+ type CommitOptions$1 = {
269
+ branch?: string;
270
+ /** Parent checkpoint. Defaults to the selected branch's current head. */
271
+ parent?: CheckpointId$1 | null;
272
+ };
273
+ type ForkOptions$1 = {
274
+ /** Checkpoint to fork from. Defaults to the main branch's head. */
275
+ from?: CheckpointId$1;
276
+ };
277
+ /**
278
+ * Small, storage-agnostic checkpoint DAG shared by service runtimes. Its values may be immutable
279
+ * records, namespace images, or copy-on-write SQL engine snapshots.
280
+ *
281
+ * Values are retained by reference. Engines can therefore use persistent/COW snapshots while
282
+ * simpler services can use immutable values. IDs and GC order are deterministic, and all IO
283
+ * (the logical clock) is injected.
284
+ */
285
+ declare class Timeline$1<T> {
286
+ readonly maxCheckpoints: number;
287
+ private readonly now;
288
+ private readonly makeId;
289
+ private readonly nodes;
290
+ private readonly heads;
291
+ /** Unreferenced nodes in the exact order they became collectible. */
292
+ private readonly evictable;
293
+ /** Branch heads plus explicit retainers. Absent means zero. */
294
+ private readonly references;
295
+ private readonly explicitPins;
296
+ private sequence;
297
+ constructor(options?: TimelineOptions$1);
298
+ /** Capture a new immutable value and move `branch` to it. */
299
+ commit(value: T, options?: CommitOptions$1): Checkpoint$1<T>;
300
+ /** Create a branch pointer without copying its checkpoint value. */
301
+ fork(branch: string, options?: ForkOptions$1): Checkpoint$1<T> | undefined;
302
+ /** Move a branch pointer to an existing checkpoint. */
303
+ checkout(branch: string, id: CheckpointId$1): Checkpoint$1<T>;
304
+ get(id: CheckpointId$1): Checkpoint$1<T>;
305
+ head(branch?: string): Checkpoint$1<T> | undefined;
306
+ hasBranch(branch: string): boolean;
307
+ branches(): Readonly<Record<string, CheckpointId$1>>;
308
+ checkpoints(): readonly Checkpoint$1<T>[];
309
+ /** Number of retained checkpoints without allocating an array. */
310
+ get size(): number;
311
+ /** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
312
+ retain(id: CheckpointId$1): Checkpoint$1<T>;
313
+ /** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
314
+ release(id: CheckpointId$1): boolean;
315
+ deleteBranch(branch: string): boolean;
316
+ /**
317
+ * Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
318
+ * commits never scan pinned nodes or the retained history. Parents are metadata rather than a
319
+ * storage dependency, so a retained node remains usable after pruning.
320
+ */
321
+ gc(max?: number): CheckpointId$1[];
322
+ private collect;
323
+ private moveHead;
324
+ private addReference;
325
+ private removeReference;
326
+ private assertBranch;
327
+ }
328
+
329
+ /**
330
+ * Anything that can answer a Fetch `Request` with a `Response`.
331
+ *
332
+ * Every Mockingbird service implements this, and every runtime adapter consumes it.
333
+ * It is the only contract shared across the whole graph.
334
+ */
335
+ interface FetchAPI$2 {
336
+ fetch(request: Request): Promise<Response>;
337
+ }
338
+
339
+ /**
340
+ * A point-in-time copy of everything a service namespace holds.
341
+ *
342
+ * All service state lives in the two core tables keyed by namespace, so a snapshot
343
+ * is generic: any service gets per-test rollback without knowing its own schema.
344
+ * Restoring is much cheaper than rebuilding a namespace from a corpus.
345
+ */
346
+ type NamespaceSnapshot$1 = {
347
+ namespace: string;
348
+ records: {
349
+ collection: string;
350
+ id: string;
351
+ seq: number;
352
+ value: string;
353
+ }[];
354
+ sequences: {
355
+ name: string;
356
+ kind: string;
357
+ value: number;
358
+ }[];
359
+ };
360
+
361
+ type WebhookEndpoint$1 = {
362
+ /** Stable id; generated when omitted. */
363
+ id?: string;
364
+ url: string;
365
+ secret?: string;
366
+ /** Event types to deliver; omit or include `"*"` for every type. */
367
+ events?: string[];
368
+ /** Deliver only messages whose tags include all of these (e.g. `{ account: "mso" }`). */
369
+ tags?: Record<string, string>;
370
+ /** The public URL the receiver verifies signatures against (Twilio), when it differs. */
371
+ signUrl?: string;
372
+ headers?: Record<string, string>;
373
+ };
374
+ type WebhookMessage$1 = {
375
+ id: string;
376
+ namespace: string;
377
+ type: string;
378
+ body: string;
379
+ contentType: string;
380
+ tags: Record<string, string>;
381
+ headers?: Record<string, string>;
382
+ /** Wall-clock ISO-8601 time of publication. */
383
+ publishedAt: string;
384
+ };
385
+ type WebhookAttempt$1 = {
386
+ attempt: number;
387
+ at: string;
388
+ status: number | null;
389
+ error: string | null;
390
+ durationMs: number;
391
+ /** Exact receiver response body, when one was returned. */
392
+ responseBody?: string | null;
393
+ };
394
+ type WebhookDelivery$1 = {
395
+ id: string;
396
+ messageId: string;
397
+ namespace: string;
398
+ type: string;
399
+ endpointId: string;
400
+ url: string;
401
+ state: "pending" | "delivered" | "failed" | "dropped";
402
+ attempts: WebhookAttempt$1[];
403
+ };
404
+ /** A delivery-level fault: what happens to the next `count` messages in a namespace. */
405
+ type WebhookFault$1 = {
406
+ mode: "duplicate" | "reorder" | "drop";
407
+ /** Messages affected; default 1. */
408
+ count?: number;
409
+ };
410
+ type PublishInput$1 = {
411
+ namespace: string;
412
+ type: string;
413
+ /** Exact body; objects are JSON-encoded. */
414
+ body: string | Record<string, unknown> | unknown[];
415
+ /** Default `application/json`, or form-encoded when `form` is given. */
416
+ contentType?: string;
417
+ /** Form parameters, when the vendor posts `application/x-www-form-urlencoded`. */
418
+ form?: Record<string, string>;
419
+ tags?: Record<string, string>;
420
+ /** Message-specific delivery headers, captured as part of durable message state. */
421
+ headers?: Record<string, string>;
422
+ /** Message id; generated when omitted. */
423
+ id?: string;
424
+ };
425
+ type WebhookHub$1 = {
426
+ publish(input: PublishInput$1): WebhookMessage$1;
427
+ /** Replace a namespace's own endpoints (`PUT /__admin/webhook-endpoints`). */
428
+ setEndpoints(namespace: string, endpoints: WebhookEndpoint$1[]): WebhookEndpoint$1[];
429
+ /** The endpoints a namespace delivers to: its own, plus the global ones. */
430
+ endpoints(namespace: string): WebhookEndpoint$1[];
431
+ messages(namespace?: string): WebhookMessage$1[];
432
+ deliveries(namespace?: string): WebhookDelivery$1[];
433
+ replay(deliveryId: string): Promise<WebhookDelivery$1 | undefined>;
434
+ /** Run every pending retry (and release held reordered messages) now. */
435
+ flush(): Promise<void>;
436
+ /** Resolve once nothing is in flight. */
437
+ idle(): Promise<void>;
438
+ fault(namespace: string, fault: WebhookFault$1): void;
439
+ clear(namespace?: string): void;
440
+ };
441
+
442
+ /** What the runtime needs from a service: a Fetch handler it can reset. */
443
+ type ServiceInstance$1 = FetchAPI$2 & {
444
+ reset(): Promise<void>;
445
+ };
446
+ type ServiceTimelineState$1 = Readonly<{
447
+ snapshot: NamespaceSnapshot$1;
448
+ clock: Readonly<ReturnType<Clock$1["state"]>>;
449
+ rngState: number;
450
+ }>;
451
+ type ServiceCheckpoint$1 = Checkpoint$1<ServiceTimelineState$1>;
452
+ type ServiceRuntime$1<T extends ServiceInstance$1> = FetchAPI$2 & {
453
+ readonly name: string;
454
+ readonly sqlite: SqliteClient$2;
455
+ readonly clock: Clock$1;
456
+ readonly faults: FaultRegistry$1;
457
+ readonly metrics: Metrics$1;
458
+ readonly journal: Journal$1;
459
+ readonly rng: Rng$1;
460
+ readonly credentials: CredentialRegistry$1;
461
+ /** The webhook hub, when the service has outbound webhooks. */
462
+ readonly webhooks: WebhookHub$1 | undefined;
463
+ /** Expand a named preset into fault rules (and webhook faults) for `namespace`. */
464
+ applyPreset(name: string, namespace?: string, overrides?: Partial<FaultRule$1>): FaultRule$1[];
465
+ /** The instance behind `namespace` (the default one when omitted), created on first use. */
466
+ instance(namespace?: string): T;
467
+ /** Public names of every namespace created so far. */
468
+ namespaces(): string[];
469
+ /** Reset one namespace, or every namespace with `"*"`. */
470
+ reset(namespace?: string): Promise<void>;
471
+ snapshot(namespace?: string): NamespaceSnapshot$1;
472
+ restore(snapshot: NamespaceSnapshot$1, namespace?: string): void;
473
+ /** Capture the current branch. Mutating HTTP calls do this automatically. */
474
+ checkpoint(namespace?: string, branch?: string): ServiceCheckpoint$1;
475
+ /** Create an isolated branch, optionally from a historical checkpoint. */
476
+ branch(name: string, options?: {
477
+ namespace?: string;
478
+ at?: string;
479
+ }): ServiceCheckpoint$1;
480
+ /** Restore a branch, clock, and PRNG to a checkpoint. */
481
+ checkout(checkpoint: string, options?: {
482
+ namespace?: string;
483
+ branch?: string;
484
+ }): void;
485
+ /** Inspect the retained history for a namespace. */
486
+ timeline(namespace?: string): Timeline$1<ServiceTimelineState$1>;
487
+ };
488
+
489
+ type CliOption = {
490
+ type: "string" | "boolean";
491
+ description: string;
492
+ /** Shown in help; the value placeholder, e.g. `<port>`. */
493
+ value?: string;
494
+ default?: string | boolean;
495
+ };
496
+ type CliValues = Record<string, string | boolean | undefined>;
497
+ type CommonServeOptions = {
498
+ adminKey: string | undefined;
499
+ seed: string | undefined;
500
+ onLog: ((entry: RequestLog$1) => void) | undefined;
501
+ };
502
+ /**
503
+ * What a service contributes to `serve`: how to build its runtime from CLI flags,
504
+ * and what to say at startup. Every service's `./server` entry exports one as
505
+ * `serveTarget`, which is also how `serve --config` finds services by name.
506
+ */
507
+ type ServeTarget = {
508
+ name: string;
509
+ defaultPort: number;
510
+ /** Serve flags beyond the common ones. */
511
+ options?: Record<string, CliOption>;
512
+ create(values: CliValues, common: CommonServeOptions): Promise<ServiceRuntime$1<ServiceInstance$1>> | ServiceRuntime$1<ServiceInstance$1>;
513
+ /** Startup lines after the listen address, e.g. the loaded corpus version. */
514
+ banner?(runtime: ServiceRuntime$1<ServiceInstance$1>): string[];
515
+ };
516
+
517
+ /** A running server, with the address it actually bound. */
518
+ type Listening = {
519
+ url: string;
520
+ port: number;
521
+ host: string;
522
+ server: Server;
523
+ close(): Promise<void>;
524
+ };
525
+
526
+ /**
527
+ * The single source of time for a service.
528
+ *
529
+ * Every timestamp a mock writes reads from here, so a suite moves time instead of
530
+ * sleeping: appointment windows, result delays and expiries become reachable in
531
+ * milliseconds. A frozen clock also makes timestamps reproducible from a seed.
532
+ */
533
+ type ClockState = {
534
+ /** Current epoch milliseconds. */
535
+ now: number;
536
+ /** True while time does not advance on its own. */
537
+ frozen: boolean;
538
+ /** Milliseconds this clock adds to its underlying source. */
539
+ offsetMs: number;
540
+ };
541
+ type Clock = {
542
+ now(): number;
543
+ /** Pin the clock to an exact instant, keeping it frozen if it already was. */
544
+ set(epochMs: number): void;
545
+ /** Move the clock forward, or back with a negative delta. */
546
+ advance(deltaMs: number): void;
547
+ /** Stop time at the current instant. */
548
+ freeze(): void;
549
+ /** Resume from the current instant. */
550
+ unfreeze(): void;
551
+ /** Drop back to the underlying source, live. */
552
+ reset(): void;
553
+ state(): ClockState;
554
+ };
555
+
556
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
557
+ type SqliteValue$1 = null | number | bigint | string | Uint8Array | boolean;
558
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
559
+ type SqliteRunResult$1 = {
560
+ changes: number;
561
+ lastInsertRowid: number | bigint;
562
+ };
563
+ /**
564
+ * Prepared statement bound to a {@link SqliteClient}.
565
+ *
566
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
567
+ */
568
+ interface SqliteStatement$1 {
569
+ run(...params: SqliteValue$1[]): SqliteRunResult$1;
570
+ all<T = Record<string, unknown>>(...params: SqliteValue$1[]): T[];
571
+ get<T = Record<string, unknown>>(...params: SqliteValue$1[]): T | undefined;
572
+ }
573
+ /**
574
+ * Sync SQLite client port owned by Mockingbird.
575
+ *
576
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
577
+ * `bun:sqlite` instances all work when they expose this surface.
578
+ */
579
+ interface SqliteClient$1 {
580
+ exec(sql: string): void;
581
+ prepare(sql: string): SqliteStatement$1;
582
+ transaction<T>(fn: () => T): T;
583
+ }
584
+
585
+ /** Every stored record carries a monotonically increasing sequence for stable ordering. */
586
+ type Stored<T> = {
587
+ seq: number;
588
+ value: T;
589
+ };
590
+ type ListRecordsOptions<T> = {
591
+ /** Keep only records passing the predicate. */
592
+ where?: (value: T, seq: number) => boolean;
593
+ /** Sort order; default newest first. */
594
+ order?: "newest" | "oldest";
595
+ };
596
+ /**
597
+ * A SQLite-backed table of JSON records addressed by id. Ordering is by insertion
598
+ * sequence, never by id lexicographic order, so list semantics stay stable.
599
+ */
600
+ declare class Collection<T> {
601
+ private readonly sqlite;
602
+ private readonly namespace;
603
+ private readonly name;
604
+ constructor(sqlite: SqliteClient$1, namespace: string, name: string);
605
+ private bumpCollectionSeq;
606
+ nextSequence(): number;
607
+ get(id: string): T | undefined;
608
+ has(id: string): boolean;
609
+ /** Insert a new record, assigning it the next sequence number. */
610
+ insert(id: string, value: T): Stored<T>;
611
+ /** Replace an existing record's value, keeping its position. */
612
+ update(id: string, value: T): Stored<T> | undefined;
613
+ delete(id: string): boolean;
614
+ /** How many records the collection holds, without reading them. */
615
+ count(): number;
616
+ list(options?: ListRecordsOptions<T>): Array<Stored<T> & {
617
+ id: string;
618
+ }>;
619
+ }
620
+
621
+ /**
622
+ * Seeded pseudo-random numbers, so anything a mock invents — ids, jitter, which
623
+ * request a percentage fault hits — is reproducible from a seed.
624
+ *
625
+ * mulberry32: small, fast, and stable across runtimes, which matters more here
626
+ * than statistical quality.
627
+ */
628
+ type Rng = {
629
+ /** Next value in `[0, 1)`. */
630
+ next(): number;
631
+ /** Next integer in `[min, max]`. */
632
+ int(min: number, max: number): number;
633
+ /** Restart the stream from its seed. */
634
+ reset(): void;
635
+ /** Serializable engine state used by deterministic checkpoints. */
636
+ state(): number;
637
+ /** Restore a state previously returned by {@link state}. */
638
+ setState(state: number): void;
639
+ seed: number;
640
+ };
641
+
642
+ /**
643
+ * A deliberate failure injected in front of an operation.
644
+ *
645
+ * This is how a suite reaches the vendor's failure modes without the vendor: the
646
+ * quota error that only appears when a shared sandbox is full, the 429 that only
647
+ * appears under load, the 5xx that proves a retry path works.
648
+ */
649
+ type FaultRule = {
650
+ /** Stable id, so a suite can retire exactly the rule it added. */
651
+ id: string;
652
+ /** Fault only this operation. Omit to match every operation. */
653
+ operationId?: string;
654
+ /** Fault only this HTTP method, case-insensitive. Omit to match every method. */
655
+ method?: string;
656
+ /** Fault only paths starting with this prefix. Omit to match every path. */
657
+ pathPrefix?: string;
658
+ /**
659
+ * Fault only this namespace. Omit (or `"*"`) to fault every namespace — which is what
660
+ * an in-process caller usually wants, and what a parallel worker usually does not:
661
+ * rules added through `POST /__admin/faults` default to the calling namespace.
662
+ */
663
+ namespace?: string;
664
+ /**
665
+ * Status of the injected response. Omit for a rule that only delays (`delayMs` /
666
+ * `latencyMs`), only drops the connection (`drop`), or only switches on an `effect`:
667
+ * the request then still reaches the service.
668
+ */
669
+ status?: number;
670
+ /** Response body, serialized as JSON. A string is sent as-is. */
671
+ body?: unknown;
672
+ headers?: Record<string, string>;
673
+ /** Retire the rule after this many faults. Omit to keep it until removed. */
674
+ count?: number;
675
+ /** Fault this fraction of matching requests, `0`–`1`. Default `1`. */
676
+ rate?: number;
677
+ /** Hold the response back this long, to exercise timeouts. */
678
+ delayMs?: number;
679
+ /** Alias of `delayMs`. */
680
+ latencyMs?: number;
681
+ /**
682
+ * Drop the connection instead of answering: an in-process `fetch` rejects with a
683
+ * `TypeError`, and a served mock destroys the socket. Models "unknown outcome" failures.
684
+ */
685
+ drop?: boolean;
686
+ /**
687
+ * A named service behaviour to switch on for the matching request instead of (or
688
+ * before) a canned response, e.g. `created_but_500` or `numeric_tracking_id`. Services
689
+ * read it with `faultEffects(request)`.
690
+ */
691
+ effect?: string;
692
+ /** Parameters for `effect`. */
693
+ params?: Record<string, unknown>;
694
+ /** From the preset this rule was expanded from, if any. */
695
+ preset?: string;
696
+ };
697
+ /** A fault that fired for one request. */
698
+ type FaultHit = {
699
+ id: string;
700
+ /** The injected response; absent when the rule only delays, drops, or sets an effect. */
701
+ response?: Response;
702
+ drop?: boolean;
703
+ effect?: {
704
+ name: string;
705
+ params: Record<string, unknown>;
706
+ };
707
+ };
708
+ /** What a request looks like to the fault matcher. */
709
+ type FaultCandidate = {
710
+ operationId: string | undefined;
711
+ method: string;
712
+ path: string;
713
+ namespace: string;
714
+ };
715
+ type FaultRegistry = {
716
+ add(rule: FaultRule): FaultRule;
717
+ list(): (FaultRule & {
718
+ remaining: number | null;
719
+ hits: number;
720
+ })[];
721
+ remove(id: string): boolean;
722
+ clear(): void;
723
+ /**
724
+ * Every fault this request should get, in rule order, stopping at the first that answers
725
+ * or drops (effect-only and delay-only rules let later rules match too). Consumes one of
726
+ * each matching rule's remaining uses.
727
+ */
728
+ take(candidate: FaultCandidate): Promise<FaultHit[]>;
729
+ };
730
+
731
+ /** One handled request, as the structured log sees it. */
732
+ type RequestLog = {
733
+ service: string;
734
+ namespace: string;
735
+ operationId: string | undefined;
736
+ method: string;
737
+ path: string;
738
+ status: number;
739
+ durationMs: number;
740
+ /** True when the path matched no operation in the contract. */
741
+ unmatched: boolean;
742
+ /** Set when a fault rule produced the response. */
743
+ faultId?: string;
744
+ /** Resource ids the handler touched (`userId`, `orderId`, …), when the service reports them. */
745
+ ids?: Record<string, string>;
746
+ /** Set when the service created a resource the request referred to but that did not exist. */
747
+ adopted?: boolean;
748
+ };
749
+ type MetricsReport = {
750
+ requests: number;
751
+ /** Counts keyed `<operationId> <status>`. */
752
+ byOperation: Record<string, number>;
753
+ /**
754
+ * Paths that matched no operation, most frequent first.
755
+ *
756
+ * This is the early-warning signal: a consumer calling something the mock does
757
+ * not implement shows up here as a count, before it fails a suite as a 404.
758
+ */
759
+ unmatched: {
760
+ method: string;
761
+ path: string;
762
+ count: number;
763
+ }[];
764
+ faults: number;
765
+ totalDurationMs: number;
766
+ };
767
+ type Metrics = {
768
+ record(entry: RequestLog): void;
769
+ report(): MetricsReport;
770
+ reset(): void;
771
+ };
772
+
773
+ /** One journal entry: a request log stamped with when (on the mock clock) it was handled. */
774
+ type JournalEntry = RequestLog & {
775
+ at: string;
776
+ };
777
+ type JournalQuery = {
778
+ /** Only this namespace. Omit for every namespace, oldest first across all of them. */
779
+ namespace?: string;
780
+ operationId?: string;
781
+ status?: number;
782
+ /** Only entries at or after this instant (epoch ms). */
783
+ since?: number;
784
+ /** At most this many, the most recent kept. */
785
+ limit?: number;
786
+ };
787
+ type Journal = {
788
+ readonly size: number;
789
+ record(entry: JournalEntry): void;
790
+ list(query?: JournalQuery): JournalEntry[];
791
+ /** Forget one namespace's entries, or every namespace's. */
792
+ clear(namespace?: string): void;
793
+ };
794
+
795
+ /** Credential → namespace mapping behind `PUT /__admin/credentials`. */
796
+ type CredentialRegistry = {
797
+ set(credential: string, namespace: string): void;
798
+ get(credential: string): string | undefined;
799
+ remove(credential: string): boolean;
800
+ clear(): void;
801
+ entries(): {
802
+ credential: string;
803
+ namespace: string;
804
+ }[];
805
+ };
806
+
807
+ /**
808
+ * Sequential id source persisted in SQLite. Ids are deterministic for a given
809
+ * sequence history (`cus_` + 14 opaque chars), so reproductions stay stable.
810
+ */
811
+ declare class IdSequence {
812
+ private readonly sqlite;
813
+ private readonly namespace;
814
+ private readonly salt;
815
+ constructor(sqlite: SqliteClient$1, namespace: string, salt?: string);
816
+ next(prefix: string, length?: number): string;
817
+ }
818
+
819
+ /** A stable identifier for a point in a {@link Timeline}. */
820
+ type CheckpointId = string;
821
+ /** An immutable node in a timeline's checkpoint DAG. */
822
+ type Checkpoint<T> = Readonly<{
823
+ id: CheckpointId;
824
+ branch: string;
825
+ parent: CheckpointId | null;
826
+ /** Logical time supplied by the timeline's injected clock. */
827
+ at: number;
828
+ value: T;
829
+ }>;
830
+ type TimelineOptions = {
831
+ /** Logical clock used to stamp checkpoints. Defaults to a deterministic counter. */
832
+ now?: () => number;
833
+ /** Maximum retained checkpoints. Branch heads are never collected. Default 1,000. */
834
+ maxCheckpoints?: number;
835
+ /** Customize deterministic checkpoint IDs. */
836
+ id?: (sequence: number) => CheckpointId;
837
+ };
838
+ type CommitOptions = {
839
+ branch?: string;
840
+ /** Parent checkpoint. Defaults to the selected branch's current head. */
841
+ parent?: CheckpointId | null;
842
+ };
843
+ type ForkOptions = {
844
+ /** Checkpoint to fork from. Defaults to the main branch's head. */
845
+ from?: CheckpointId;
846
+ };
847
+ /**
848
+ * Small, storage-agnostic checkpoint DAG shared by service runtimes. Its values may be immutable
849
+ * records, namespace images, or copy-on-write SQL engine snapshots.
850
+ *
851
+ * Values are retained by reference. Engines can therefore use persistent/COW snapshots while
852
+ * simpler services can use immutable values. IDs and GC order are deterministic, and all IO
853
+ * (the logical clock) is injected.
854
+ */
855
+ declare class Timeline<T> {
856
+ readonly maxCheckpoints: number;
857
+ private readonly now;
858
+ private readonly makeId;
859
+ private readonly nodes;
860
+ private readonly heads;
861
+ /** Unreferenced nodes in the exact order they became collectible. */
862
+ private readonly evictable;
863
+ /** Branch heads plus explicit retainers. Absent means zero. */
864
+ private readonly references;
865
+ private readonly explicitPins;
866
+ private sequence;
867
+ constructor(options?: TimelineOptions);
868
+ /** Capture a new immutable value and move `branch` to it. */
869
+ commit(value: T, options?: CommitOptions): Checkpoint<T>;
870
+ /** Create a branch pointer without copying its checkpoint value. */
871
+ fork(branch: string, options?: ForkOptions): Checkpoint<T> | undefined;
872
+ /** Move a branch pointer to an existing checkpoint. */
873
+ checkout(branch: string, id: CheckpointId): Checkpoint<T>;
874
+ get(id: CheckpointId): Checkpoint<T>;
875
+ head(branch?: string): Checkpoint<T> | undefined;
876
+ hasBranch(branch: string): boolean;
877
+ branches(): Readonly<Record<string, CheckpointId>>;
878
+ checkpoints(): readonly Checkpoint<T>[];
879
+ /** Number of retained checkpoints without allocating an array. */
880
+ get size(): number;
881
+ /** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
882
+ retain(id: CheckpointId): Checkpoint<T>;
883
+ /** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
884
+ release(id: CheckpointId): boolean;
885
+ deleteBranch(branch: string): boolean;
886
+ /**
887
+ * Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
888
+ * commits never scan pinned nodes or the retained history. Parents are metadata rather than a
889
+ * storage dependency, so a retained node remains usable after pruning.
890
+ */
891
+ gc(max?: number): CheckpointId[];
892
+ private collect;
893
+ private moveHead;
894
+ private addReference;
895
+ private removeReference;
896
+ private assertBranch;
897
+ }
898
+
899
+ /**
900
+ * Anything that can answer a Fetch `Request` with a `Response`.
901
+ *
902
+ * Every Mockingbird service implements this, and every runtime adapter consumes it.
903
+ * It is the only contract shared across the whole graph.
904
+ */
905
+ interface FetchAPI$1 {
906
+ fetch(request: Request): Promise<Response>;
907
+ }
908
+
909
+ /**
910
+ * A point-in-time copy of everything a service namespace holds.
911
+ *
912
+ * All service state lives in the two core tables keyed by namespace, so a snapshot
913
+ * is generic: any service gets per-test rollback without knowing its own schema.
914
+ * Restoring is much cheaper than rebuilding a namespace from a corpus.
915
+ */
916
+ type NamespaceSnapshot = {
917
+ namespace: string;
918
+ records: {
919
+ collection: string;
920
+ id: string;
921
+ seq: number;
922
+ value: string;
923
+ }[];
924
+ sequences: {
925
+ name: string;
926
+ kind: string;
927
+ value: number;
928
+ }[];
929
+ };
930
+
931
+ type WebhookEndpoint = {
932
+ /** Stable id; generated when omitted. */
933
+ id?: string;
934
+ url: string;
935
+ secret?: string;
936
+ /** Event types to deliver; omit or include `"*"` for every type. */
937
+ events?: string[];
938
+ /** Deliver only messages whose tags include all of these (e.g. `{ account: "mso" }`). */
939
+ tags?: Record<string, string>;
940
+ /** The public URL the receiver verifies signatures against (Twilio), when it differs. */
941
+ signUrl?: string;
942
+ headers?: Record<string, string>;
943
+ };
944
+ type WebhookMessage = {
945
+ id: string;
946
+ namespace: string;
947
+ type: string;
948
+ body: string;
949
+ contentType: string;
950
+ tags: Record<string, string>;
951
+ headers?: Record<string, string>;
952
+ /** Wall-clock ISO-8601 time of publication. */
953
+ publishedAt: string;
954
+ };
955
+ type WebhookAttempt = {
956
+ attempt: number;
957
+ at: string;
958
+ status: number | null;
959
+ error: string | null;
960
+ durationMs: number;
961
+ /** Exact receiver response body, when one was returned. */
962
+ responseBody?: string | null;
963
+ };
964
+ type WebhookDelivery = {
965
+ id: string;
966
+ messageId: string;
967
+ namespace: string;
968
+ type: string;
969
+ endpointId: string;
970
+ url: string;
971
+ state: "pending" | "delivered" | "failed" | "dropped";
972
+ attempts: WebhookAttempt[];
973
+ };
974
+ /** A delivery-level fault: what happens to the next `count` messages in a namespace. */
975
+ type WebhookFault = {
976
+ mode: "duplicate" | "reorder" | "drop";
977
+ /** Messages affected; default 1. */
978
+ count?: number;
979
+ };
980
+ type PublishInput = {
981
+ namespace: string;
982
+ type: string;
983
+ /** Exact body; objects are JSON-encoded. */
984
+ body: string | Record<string, unknown> | unknown[];
985
+ /** Default `application/json`, or form-encoded when `form` is given. */
986
+ contentType?: string;
987
+ /** Form parameters, when the vendor posts `application/x-www-form-urlencoded`. */
988
+ form?: Record<string, string>;
989
+ tags?: Record<string, string>;
990
+ /** Message-specific delivery headers, captured as part of durable message state. */
991
+ headers?: Record<string, string>;
992
+ /** Message id; generated when omitted. */
993
+ id?: string;
994
+ };
995
+ type WebhookHub = {
996
+ publish(input: PublishInput): WebhookMessage;
997
+ /** Replace a namespace's own endpoints (`PUT /__admin/webhook-endpoints`). */
998
+ setEndpoints(namespace: string, endpoints: WebhookEndpoint[]): WebhookEndpoint[];
999
+ /** The endpoints a namespace delivers to: its own, plus the global ones. */
1000
+ endpoints(namespace: string): WebhookEndpoint[];
1001
+ messages(namespace?: string): WebhookMessage[];
1002
+ deliveries(namespace?: string): WebhookDelivery[];
1003
+ replay(deliveryId: string): Promise<WebhookDelivery | undefined>;
1004
+ /** Run every pending retry (and release held reordered messages) now. */
1005
+ flush(): Promise<void>;
1006
+ /** Resolve once nothing is in flight. */
1007
+ idle(): Promise<void>;
1008
+ fault(namespace: string, fault: WebhookFault): void;
1009
+ clear(namespace?: string): void;
1010
+ };
1011
+
1012
+ /** What the runtime needs from a service: a Fetch handler it can reset. */
1013
+ type ServiceInstance = FetchAPI$1 & {
1014
+ reset(): Promise<void>;
1015
+ };
1016
+ type ServiceTimelineState = Readonly<{
1017
+ snapshot: NamespaceSnapshot;
1018
+ clock: Readonly<ReturnType<Clock["state"]>>;
1019
+ rngState: number;
1020
+ }>;
1021
+ type ServiceCheckpoint = Checkpoint<ServiceTimelineState>;
1022
+ type ServiceRuntime<T extends ServiceInstance> = FetchAPI$1 & {
1023
+ readonly name: string;
1024
+ readonly sqlite: SqliteClient$1;
1025
+ readonly clock: Clock;
1026
+ readonly faults: FaultRegistry;
1027
+ readonly metrics: Metrics;
1028
+ readonly journal: Journal;
1029
+ readonly rng: Rng;
1030
+ readonly credentials: CredentialRegistry;
1031
+ /** The webhook hub, when the service has outbound webhooks. */
1032
+ readonly webhooks: WebhookHub | undefined;
1033
+ /** Expand a named preset into fault rules (and webhook faults) for `namespace`. */
1034
+ applyPreset(name: string, namespace?: string, overrides?: Partial<FaultRule>): FaultRule[];
1035
+ /** The instance behind `namespace` (the default one when omitted), created on first use. */
1036
+ instance(namespace?: string): T;
1037
+ /** Public names of every namespace created so far. */
1038
+ namespaces(): string[];
1039
+ /** Reset one namespace, or every namespace with `"*"`. */
1040
+ reset(namespace?: string): Promise<void>;
1041
+ snapshot(namespace?: string): NamespaceSnapshot;
1042
+ restore(snapshot: NamespaceSnapshot, namespace?: string): void;
1043
+ /** Capture the current branch. Mutating HTTP calls do this automatically. */
1044
+ checkpoint(namespace?: string, branch?: string): ServiceCheckpoint;
1045
+ /** Create an isolated branch, optionally from a historical checkpoint. */
1046
+ branch(name: string, options?: {
1047
+ namespace?: string;
1048
+ at?: string;
1049
+ }): ServiceCheckpoint;
1050
+ /** Restore a branch, clock, and PRNG to a checkpoint. */
1051
+ checkout(checkpoint: string, options?: {
1052
+ namespace?: string;
1053
+ branch?: string;
1054
+ }): void;
1055
+ /** Inspect the retained history for a namespace. */
1056
+ timeline(namespace?: string): Timeline<ServiceTimelineState>;
1057
+ };
1058
+
1059
+ /**
1060
+ * What a comms vendor "sent" (an SMS, an email, a Slack post), kept per namespace so a
1061
+ * suite can assert on it and read codes and links out of it. Stored in SQLite beside the
1062
+ * service's other records, so reset, snapshot and restore cover it.
1063
+ */
1064
+ type OutboxItem = {
1065
+ id: string;
1066
+ /** Recipient(s): a phone number, email address, channel or webhook path. */
1067
+ to: string | string[];
1068
+ /** ISO-8601 on the mock clock. */
1069
+ createdAt: string;
1070
+ };
1071
+ type OutboxQuery = {
1072
+ /** Case-insensitive match on any recipient. */
1073
+ to?: string;
1074
+ /** Only items at or after this instant (epoch ms). */
1075
+ since?: number;
1076
+ /** Extra filter over the item. */
1077
+ where?: (item: Record<string, unknown>) => boolean;
1078
+ limit?: number;
1079
+ };
1080
+ declare class OutboxStore<T extends OutboxItem = OutboxItem> {
1081
+ private readonly items;
1082
+ constructor(sqlite: SqliteClient$1, namespace: string, name?: string);
1083
+ record(item: T): T;
1084
+ get(id: string): T | undefined;
1085
+ update(id: string, item: T): void;
1086
+ /** Oldest first, so a suite reads messages in the order they were sent. */
1087
+ list(query?: OutboxQuery): T[];
1088
+ }
1089
+
1090
+ /** Options every provider constructor accepts. */
1091
+ type APIOptions = {
1092
+ /** Sync SQLite client. Defaults to `@crvouga/mockingbird-service-sqlite`. */
1093
+ sqlite?: SqliteClient$1;
1094
+ /** Clock used for `created`-style fields. Default `Date.now`. */
1095
+ now?: () => number;
1096
+ /**
1097
+ * Storage namespace for this instance's records. Instances sharing one SQLite
1098
+ * client stay isolated when their namespaces differ. Defaults to the service name.
1099
+ */
1100
+ namespace?: string;
1101
+ };
1102
+
1103
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
1104
+ type SqliteValue = null | number | bigint | string | Uint8Array | boolean;
1105
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
1106
+ type SqliteRunResult = {
1107
+ changes: number;
1108
+ lastInsertRowid: number | bigint;
1109
+ };
1110
+ /**
1111
+ * Prepared statement bound to a {@link SqliteClient}.
1112
+ *
1113
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
1114
+ */
1115
+ interface SqliteStatement {
1116
+ run(...params: SqliteValue[]): SqliteRunResult;
1117
+ all<T = Record<string, unknown>>(...params: SqliteValue[]): T[];
1118
+ get<T = Record<string, unknown>>(...params: SqliteValue[]): T | undefined;
1119
+ }
1120
+ /**
1121
+ * Sync SQLite client port owned by Mockingbird.
1122
+ *
1123
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
1124
+ * `bun:sqlite` instances all work when they expose this surface.
1125
+ */
1126
+ interface SqliteClient {
1127
+ exec(sql: string): void;
1128
+ prepare(sql: string): SqliteStatement;
1129
+ transaction<T>(fn: () => T): T;
1130
+ }
1131
+
1132
+ /**
1133
+ * Anything that can answer a Fetch `Request` with a `Response`.
1134
+ *
1135
+ * Every Mockingbird service implements this, and every runtime adapter consumes it.
1136
+ * It is the only contract shared across the whole graph.
1137
+ */
1138
+ interface FetchAPI {
1139
+ fetch(request: Request): Promise<Response>;
1140
+ }
1141
+
1142
+ /** One transactional message (template) in the workspace, as `GET /v1/transactional` lists it. */
1143
+ type TransactionalMessage = {
1144
+ id: number;
1145
+ name: string;
1146
+ trigger_name: string;
1147
+ description: string;
1148
+ send_to_unsubscribed: boolean;
1149
+ link_tracking: boolean;
1150
+ open_tracking: boolean;
1151
+ hide_message_body: boolean;
1152
+ queue_drafts: boolean;
1153
+ created_at: number;
1154
+ updated_at: number;
1155
+ };
1156
+ type Channel = "email" | "sms" | "inbox";
1157
+ /**
1158
+ * One transactional send, which is also the outbox entry a suite asserts on. `messageData` is
1159
+ * dropped when the request set `disable_message_retention` (Customer.io keeps no body then).
1160
+ */
1161
+ type Delivery = OutboxItem & {
1162
+ channel: Channel;
1163
+ transactionalMessageId: string;
1164
+ /** The catalog message the id or trigger name resolved to, when it did. */
1165
+ messageId: number | null;
1166
+ identifiers: {
1167
+ id?: string;
1168
+ email?: string;
1169
+ cio_id?: string;
1170
+ };
1171
+ from: string | null;
1172
+ subject: string | null;
1173
+ messageData: Record<string, unknown> | null;
1174
+ /** URLs found in `message_data` (tracked links are rewritten to `/click/<linkId>`). */
1175
+ links: string[];
1176
+ tracked: boolean;
1177
+ sendToUnsubscribed: boolean;
1178
+ disableMessageRetention: boolean;
1179
+ headers: Record<string, string>;
1180
+ attachments: string[];
1181
+ /** `suppressed` when the profile is unsubscribed and `send_to_unsubscribed` is false. */
1182
+ state: "sent" | "suppressed";
1183
+ queuedAt: number;
1184
+ clicks: number;
1185
+ };
1186
+ /** One CDP call (identify or track), with the fields a suite asserts on. */
1187
+ type CdpEvent = {
1188
+ messageId: string;
1189
+ type: "identify" | "track";
1190
+ userId: string | null;
1191
+ anonymousId: string | null;
1192
+ event: string | null;
1193
+ traits: Record<string, unknown>;
1194
+ properties: Record<string, unknown>;
1195
+ timestamp: string | null;
1196
+ receivedAt: string;
1197
+ /** The same `messageId` arrived earlier: accepted, not applied again. */
1198
+ duplicate: boolean;
1199
+ };
1200
+ /** A person as identify calls and reporting events have shaped them. */
1201
+ type Profile = {
1202
+ id: string;
1203
+ email: string | null;
1204
+ traits: Record<string, unknown>;
1205
+ unsubscribed: boolean;
1206
+ /** Channels switched off through subscription preferences. */
1207
+ channelsOff: ("email" | "sms")[];
1208
+ updatedAt: string;
1209
+ };
1210
+ type TrackedLink = {
1211
+ linkId: string;
1212
+ deliveryId: string;
1213
+ url: string;
1214
+ };
1215
+ /** Per-namespace knobs, set through `PUT /__admin/settings`; cleared on reset. */
1216
+ type Settings = {
1217
+ /**
1218
+ * Refuse sends whose `transactional_message_id` is neither a catalog id nor a trigger name
1219
+ * (Customer.io's behaviour). Off by default: the processor derives trigger names from every
1220
+ * notification type, which a test workspace cannot list in advance.
1221
+ */
1222
+ strictMessages: boolean;
1223
+ /** Base of rewritten tracked links, e.g. `https://links.example.com`. */
1224
+ trackingBase: string;
1225
+ /** Write keys / App API keys accepted as-is; empty means any non-empty key works. */
1226
+ keys: string[];
1227
+ };
1228
+ declare class CustomerIoState {
1229
+ private readonly seed;
1230
+ readonly deliveries: OutboxStore<Delivery>;
1231
+ readonly cdp: Collection<CdpEvent>;
1232
+ readonly profiles: Collection<Profile>;
1233
+ readonly messages: Collection<TransactionalMessage>;
1234
+ readonly links: Collection<TrackedLink>;
1235
+ readonly settings: Collection<Settings>;
1236
+ readonly ids: IdSequence;
1237
+ constructor(sqlite: SqliteClient, namespace: string, seed: {
1238
+ messages: readonly TransactionalMessage[];
1239
+ settings: Partial<Settings>;
1240
+ });
1241
+ ensureSeeded(): void;
1242
+ current(): Settings;
1243
+ update(patch: Partial<Settings>): Settings;
1244
+ catalog(): TransactionalMessage[];
1245
+ /** A catalog message by numeric id or (case-insensitive) trigger name. */
1246
+ message(idOrTrigger: string): TransactionalMessage | undefined;
1247
+ profile(id: string): Profile | undefined;
1248
+ /** The profile an App API `identifiers` object names (by id, else by email). */
1249
+ profileFor(identifiers: {
1250
+ id?: string;
1251
+ email?: string;
1252
+ }): Profile | undefined;
1253
+ upsertProfile(id: string, patch: Partial<Omit<Profile, "id">>, at: string): Profile;
1254
+ deliveryId(): string;
1255
+ linkId(): string;
1256
+ eventId(): string;
1257
+ }
1258
+
1259
+ /** The body Customer.io's reporting webhook posts (the fields our receiver's zod schema reads). */
1260
+ type ReportingEvent = {
1261
+ event_id: string;
1262
+ object_type: string;
1263
+ metric: string;
1264
+ timestamp: number;
1265
+ data: {
1266
+ identifiers: {
1267
+ id: string | null;
1268
+ email: string | null;
1269
+ cio_id: string | null;
1270
+ };
1271
+ customer_id: string | null;
1272
+ email_address?: string | null;
1273
+ delivery_id?: string;
1274
+ transactional_message_id?: number;
1275
+ href?: string;
1276
+ link_id?: string;
1277
+ content?: string;
1278
+ };
1279
+ };
1280
+ /** What a suite (or a click) asks the mock to report. */
1281
+ type ReportInput = {
1282
+ metric: string;
1283
+ objectType?: string;
1284
+ userId?: string;
1285
+ email?: string;
1286
+ deliveryId?: string;
1287
+ /** `cio_subscription_preferences_changed`: `{topics?, channels?}`, sent as a JSON string. */
1288
+ preferences?: {
1289
+ topics?: Record<string, boolean>;
1290
+ channels?: Record<string, boolean>;
1291
+ };
1292
+ href?: string;
1293
+ linkId?: string;
1294
+ };
1295
+ type CustomerIoAPIOptions = APIOptions & {
1296
+ /** The workspace's transactional messages. Default {@link DEFAULT_TRANSACTIONAL_MESSAGES}. */
1297
+ messages?: readonly TransactionalMessage[];
1298
+ settings?: Partial<Settings>;
1299
+ /** Called for every reporting event; the runtime signs and delivers it. */
1300
+ onReport?: (event: ReportingEvent) => void;
1301
+ /** Wall clock used for receiver freshness checks. Defaults to `Date.now`. */
1302
+ wallClock?: () => number;
1303
+ };
1304
+ /**
1305
+ * Stateful mock of Customer.io's CDP and App API. CDP calls shape profiles; transactional
1306
+ * sends land in the outbox (suppressed for unsubscribed profiles unless
1307
+ * `send_to_unsubscribed`); tracked links are rewritten to `/click/<linkId>`; reporting events
1308
+ * (admin-triggered, or a click) go to the reporting webhook.
1309
+ */
1310
+ declare class CustomerIoAPI implements FetchAPI {
1311
+ readonly app: Hono;
1312
+ readonly sqlite: SqliteClient;
1313
+ readonly state: CustomerIoState;
1314
+ private readonly service;
1315
+ private readonly now;
1316
+ private readonly wallClock;
1317
+ private readonly onReport;
1318
+ constructor(options?: CustomerIoAPIOptions);
1319
+ fetch(request: Request): Promise<Response>;
1320
+ reset(): Promise<void>;
1321
+ private iso;
1322
+ private cdp;
1323
+ /** Apply one CDP event; a repeated `messageId` is recorded as a duplicate and not re-applied. */
1324
+ private ingest;
1325
+ private send;
1326
+ private click;
1327
+ /**
1328
+ * Emit a reporting event and apply what it means to the profile (unsubscribed / subscribed /
1329
+ * spammed / subscription preferences). Returns the event, or a reason it could not be built.
1330
+ */
1331
+ report(input: ReportInput): ReportingEvent | string;
1332
+ profiles(): Profile[];
1333
+ }
1334
+
1335
+ type WebhookHubOptionsSubset = {
1336
+ retryDelaysMs?: readonly number[];
1337
+ fetch?: (request: Request) => Promise<Response>;
1338
+ };
1339
+ type CustomerIoRuntimeOptions = {
1340
+ sqlite?: SqliteClient;
1341
+ clock?: Clock;
1342
+ /** Real-time clock for webhook freshness/signing; injectable for deterministic tests. */
1343
+ wallClock?: () => number;
1344
+ seed?: number | string;
1345
+ adminKey?: string;
1346
+ onLog?: (entry: RequestLog) => void;
1347
+ messages?: readonly TransactionalMessage[];
1348
+ settings?: Partial<Settings>;
1349
+ /**
1350
+ * Where reporting events go (`POST /v1/customer-io/reporting-webhook`), signed with
1351
+ * `secret` (the app's `CUSTOMERIO_REPORTING_WEBHOOK_SIGNING_KEY`, 32+ characters).
1352
+ */
1353
+ webhooks?: Omit<WebhookEndpoint, "id"> & WebhookHubOptionsSubset;
1354
+ };
1355
+ type CustomerIoRuntime = ServiceRuntime<CustomerIoAPI> & {
1356
+ readonly webhooks: WebhookHub;
1357
+ };
1358
+
1359
+ /** Port `mockingbird-customerio serve` listens on when none is given. */
1360
+ declare const DEFAULT_PORT = 8810;
1361
+ type CustomerIoServerOptions = CustomerIoRuntimeOptions & {
1362
+ /** Default `0`: the OS picks a free port. */
1363
+ port?: number;
1364
+ /** Default `127.0.0.1`. */
1365
+ host?: string;
1366
+ };
1367
+ type CustomerIoServer = Listening & {
1368
+ runtime: CustomerIoRuntime;
1369
+ };
1370
+ /** Serve the Customer.io mock (CDP, App API and click tracking) over `node:http`. */
1371
+ declare const createServer: (options?: CustomerIoServerOptions) => Promise<CustomerIoServer>;
1372
+ /** How `serve` (and `serve --config`) builds the Customer.io mock from flags. */
1373
+ declare const serveTarget: ServeTarget;
1374
+
1375
+ export { DEFAULT_PORT, createServer, serveTarget };
1376
+ export type { CustomerIoServer, CustomerIoServerOptions };