@crvouga/mockingbird-service-junction 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +448 -133
  3. package/dist/chunk-4C6VYRJN.js +18 -0
  4. package/dist/chunk-4C6VYRJN.js.map +7 -0
  5. package/dist/chunk-KKNULV7X.js +406 -0
  6. package/dist/chunk-KKNULV7X.js.map +7 -0
  7. package/dist/chunk-MA3HSUVD.js +7771 -0
  8. package/dist/chunk-MA3HSUVD.js.map +7 -0
  9. package/dist/chunk-MD4KYEIM.js +145758 -0
  10. package/dist/chunk-MD4KYEIM.js.map +7 -0
  11. package/dist/cli.js +214 -0
  12. package/dist/cli.js.map +7 -0
  13. package/dist/corpus.d.ts +97 -0
  14. package/dist/corpus.js +8 -0
  15. package/dist/corpus.js.map +7 -0
  16. package/dist/index.d.ts +1131 -21
  17. package/dist/index.js +82 -120
  18. package/dist/index.js.map +7 -1
  19. package/dist/server.d.ts +978 -0
  20. package/dist/server.js +16 -0
  21. package/dist/server.js.map +7 -0
  22. package/package.json +32 -12
  23. package/dist/catalog.d.ts +0 -63
  24. package/dist/catalog.d.ts.map +0 -1
  25. package/dist/catalog.js +0 -736
  26. package/dist/catalog.js.map +0 -1
  27. package/dist/coverage-corpus.d.ts +0 -76
  28. package/dist/coverage-corpus.d.ts.map +0 -1
  29. package/dist/coverage-corpus.js +0 -166
  30. package/dist/coverage-corpus.js.map +0 -1
  31. package/dist/generated/openapi.d.ts +0 -7
  32. package/dist/generated/openapi.d.ts.map +0 -1
  33. package/dist/generated/openapi.js +0 -5
  34. package/dist/generated/openapi.js.map +0 -1
  35. package/dist/index.d.ts.map +0 -1
  36. package/dist/lab-accounts.d.ts +0 -38
  37. package/dist/lab-accounts.d.ts.map +0 -1
  38. package/dist/lab-accounts.js +0 -213
  39. package/dist/lab-accounts.js.map +0 -1
  40. package/dist/orders.d.ts +0 -18
  41. package/dist/orders.d.ts.map +0 -1
  42. package/dist/orders.js +0 -1247
  43. package/dist/orders.js.map +0 -1
  44. package/dist/prefetch.d.ts +0 -43
  45. package/dist/prefetch.d.ts.map +0 -1
  46. package/dist/prefetch.js +0 -131
  47. package/dist/prefetch.js.map +0 -1
  48. package/dist/reshape.d.ts +0 -22
  49. package/dist/reshape.d.ts.map +0 -1
  50. package/dist/reshape.js +0 -190
  51. package/dist/reshape.js.map +0 -1
  52. package/dist/results.d.ts +0 -19
  53. package/dist/results.d.ts.map +0 -1
  54. package/dist/results.js +0 -221
  55. package/dist/results.js.map +0 -1
  56. package/dist/scheduling.d.ts +0 -113
  57. package/dist/scheduling.d.ts.map +0 -1
  58. package/dist/scheduling.js +0 -1508
  59. package/dist/scheduling.js.map +0 -1
  60. package/dist/sealed-corpus.d.ts +0 -28
  61. package/dist/sealed-corpus.d.ts.map +0 -1
  62. package/dist/sealed-corpus.js +0 -17
  63. package/dist/sealed-corpus.js.map +0 -1
  64. package/dist/seed-from.d.ts +0 -27
  65. package/dist/seed-from.d.ts.map +0 -1
  66. package/dist/seed-from.js +0 -523
  67. package/dist/seed-from.js.map +0 -1
  68. package/dist/seeds.d.ts +0 -9
  69. package/dist/seeds.d.ts.map +0 -1
  70. package/dist/seeds.js +0 -9
  71. package/dist/seeds.js.map +0 -1
  72. package/dist/state.d.ts +0 -270
  73. package/dist/state.d.ts.map +0 -1
  74. package/dist/state.js +0 -448
  75. package/dist/state.js.map +0 -1
  76. package/dist/users.d.ts +0 -13
  77. package/dist/users.d.ts.map +0 -1
  78. package/dist/users.js +0 -669
  79. package/dist/users.js.map +0 -1
@@ -0,0 +1,978 @@
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
+ seed: number;
78
+ };
79
+
80
+ /**
81
+ * A deliberate failure injected in front of an operation.
82
+ *
83
+ * This is how a suite reaches the vendor's failure modes without the vendor: the
84
+ * quota error that only appears when a shared sandbox is full, the 429 that only
85
+ * appears under load, the 5xx that proves a retry path works.
86
+ */
87
+ type FaultRule$1 = {
88
+ /** Stable id, so a suite can retire exactly the rule it added. */
89
+ id: string;
90
+ /** Fault only this operation. Omit to match every operation. */
91
+ operationId?: string;
92
+ /** Fault only this HTTP method, case-insensitive. Omit to match every method. */
93
+ method?: string;
94
+ /** Fault only paths starting with this prefix. Omit to match every path. */
95
+ pathPrefix?: string;
96
+ /**
97
+ * Fault only this namespace. Omit (or `"*"`) to fault every namespace — which is what
98
+ * an in-process caller usually wants, and what a parallel worker usually does not:
99
+ * rules added through `POST /__admin/faults` default to the calling namespace.
100
+ */
101
+ namespace?: string;
102
+ status: number;
103
+ /** Response body, serialized as JSON. A string is sent as-is. */
104
+ body?: unknown;
105
+ headers?: Record<string, string>;
106
+ /** Retire the rule after this many faults. Omit to keep it until removed. */
107
+ count?: number;
108
+ /** Fault this fraction of matching requests, `0`–`1`. Default `1`. */
109
+ rate?: number;
110
+ /** Hold the response back this long, to exercise timeouts. */
111
+ delayMs?: number;
112
+ };
113
+ /** What a request looks like to the fault matcher. */
114
+ type FaultCandidate$1 = {
115
+ operationId: string | undefined;
116
+ method: string;
117
+ path: string;
118
+ namespace: string;
119
+ };
120
+ type FaultRegistry$1 = {
121
+ add(rule: FaultRule$1): FaultRule$1;
122
+ list(): (FaultRule$1 & {
123
+ remaining: number | null;
124
+ hits: number;
125
+ })[];
126
+ remove(id: string): boolean;
127
+ clear(): void;
128
+ /**
129
+ * The fault this request should get, or `undefined` to let it through.
130
+ * Consumes one of the matching rule's remaining uses.
131
+ */
132
+ take(candidate: FaultCandidate$1): Promise<{
133
+ id: string;
134
+ response: Response;
135
+ } | undefined>;
136
+ };
137
+
138
+ /** One handled request, as the structured log sees it. */
139
+ type RequestLog$1 = {
140
+ service: string;
141
+ namespace: string;
142
+ operationId: string | undefined;
143
+ method: string;
144
+ path: string;
145
+ status: number;
146
+ durationMs: number;
147
+ /** True when the path matched no operation in the contract. */
148
+ unmatched: boolean;
149
+ /** Set when a fault rule produced the response. */
150
+ faultId?: string;
151
+ };
152
+ type MetricsReport$1 = {
153
+ requests: number;
154
+ /** Counts keyed `<operationId> <status>`. */
155
+ byOperation: Record<string, number>;
156
+ /**
157
+ * Paths that matched no operation, most frequent first.
158
+ *
159
+ * This is the early-warning signal: a consumer calling something the mock does
160
+ * not implement shows up here as a count, before it fails a suite as a 404.
161
+ */
162
+ unmatched: {
163
+ method: string;
164
+ path: string;
165
+ count: number;
166
+ }[];
167
+ faults: number;
168
+ totalDurationMs: number;
169
+ };
170
+ type Metrics$1 = {
171
+ record(entry: RequestLog$1): void;
172
+ report(): MetricsReport$1;
173
+ reset(): void;
174
+ };
175
+
176
+ /**
177
+ * A point-in-time copy of everything a service namespace holds.
178
+ *
179
+ * All service state lives in the two core tables keyed by namespace, so a snapshot
180
+ * is generic: any service gets per-test rollback without knowing its own schema.
181
+ * Restoring is much cheaper than rebuilding a namespace from a corpus.
182
+ */
183
+ type NamespaceSnapshot$1 = {
184
+ namespace: string;
185
+ records: {
186
+ collection: string;
187
+ id: string;
188
+ seq: number;
189
+ value: string;
190
+ }[];
191
+ sequences: {
192
+ name: string;
193
+ kind: string;
194
+ value: number;
195
+ }[];
196
+ };
197
+
198
+ /**
199
+ * Anything that can answer a Fetch `Request` with a `Response`.
200
+ *
201
+ * Every Mockingbird service implements this, and every runtime adapter consumes it.
202
+ * It is the only contract shared across the whole graph.
203
+ */
204
+ interface FetchAPI$2 {
205
+ fetch(request: Request): Promise<Response>;
206
+ }
207
+
208
+ /** What the runtime needs from a service: a Fetch handler it can reset. */
209
+ type ServiceInstance$1 = FetchAPI$2 & {
210
+ reset(): Promise<void>;
211
+ };
212
+ type ServiceRuntime$1<T extends ServiceInstance$1> = FetchAPI$2 & {
213
+ readonly name: string;
214
+ readonly sqlite: SqliteClient$2;
215
+ readonly clock: Clock$1;
216
+ readonly faults: FaultRegistry$1;
217
+ readonly metrics: Metrics$1;
218
+ readonly rng: Rng$1;
219
+ /** The instance behind `namespace` (the default one when omitted), created on first use. */
220
+ instance(namespace?: string): T;
221
+ /** Public names of every namespace created so far. */
222
+ namespaces(): string[];
223
+ /** Reset one namespace, or every namespace with `"*"`. */
224
+ reset(namespace?: string): Promise<void>;
225
+ snapshot(namespace?: string): NamespaceSnapshot$1;
226
+ restore(snapshot: NamespaceSnapshot$1, namespace?: string): void;
227
+ };
228
+
229
+ type CliOption = {
230
+ type: "string" | "boolean";
231
+ description: string;
232
+ /** Shown in help; the value placeholder, e.g. `<port>`. */
233
+ value?: string;
234
+ default?: string | boolean;
235
+ };
236
+ type CliValues = Record<string, string | boolean | undefined>;
237
+ type CommonServeOptions = {
238
+ adminKey: string | undefined;
239
+ seed: string | undefined;
240
+ onLog: ((entry: RequestLog$1) => void) | undefined;
241
+ };
242
+ /**
243
+ * What a service contributes to `serve`: how to build its runtime from CLI flags,
244
+ * and what to say at startup. Every service's `./server` entry exports one as
245
+ * `serveTarget`, which is also how `serve --config` finds services by name.
246
+ */
247
+ type ServeTarget = {
248
+ name: string;
249
+ defaultPort: number;
250
+ /** Serve flags beyond the common ones. */
251
+ options?: Record<string, CliOption>;
252
+ create(values: CliValues, common: CommonServeOptions): Promise<ServiceRuntime$1<ServiceInstance$1>> | ServiceRuntime$1<ServiceInstance$1>;
253
+ /** Startup lines after the listen address, e.g. the loaded corpus version. */
254
+ banner?(runtime: ServiceRuntime$1<ServiceInstance$1>): string[];
255
+ };
256
+
257
+ /** A running server, with the address it actually bound. */
258
+ type Listening = {
259
+ url: string;
260
+ port: number;
261
+ host: string;
262
+ server: Server;
263
+ close(): Promise<void>;
264
+ };
265
+
266
+ /**
267
+ * The single source of time for a service.
268
+ *
269
+ * Every timestamp a mock writes reads from here, so a suite moves time instead of
270
+ * sleeping: appointment windows, result delays and expiries become reachable in
271
+ * milliseconds. A frozen clock also makes timestamps reproducible from a seed.
272
+ */
273
+ type ClockState = {
274
+ /** Current epoch milliseconds. */
275
+ now: number;
276
+ /** True while time does not advance on its own. */
277
+ frozen: boolean;
278
+ /** Milliseconds this clock adds to its underlying source. */
279
+ offsetMs: number;
280
+ };
281
+ type Clock = {
282
+ now(): number;
283
+ /** Pin the clock to an exact instant, keeping it frozen if it already was. */
284
+ set(epochMs: number): void;
285
+ /** Move the clock forward, or back with a negative delta. */
286
+ advance(deltaMs: number): void;
287
+ /** Stop time at the current instant. */
288
+ freeze(): void;
289
+ /** Resume from the current instant. */
290
+ unfreeze(): void;
291
+ /** Drop back to the underlying source, live. */
292
+ reset(): void;
293
+ state(): ClockState;
294
+ };
295
+
296
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
297
+ type SqliteValue$1 = null | number | bigint | string | Uint8Array | boolean;
298
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
299
+ type SqliteRunResult$1 = {
300
+ changes: number;
301
+ lastInsertRowid: number | bigint;
302
+ };
303
+ /**
304
+ * Prepared statement bound to a {@link SqliteClient}.
305
+ *
306
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
307
+ */
308
+ interface SqliteStatement$1 {
309
+ run(...params: SqliteValue$1[]): SqliteRunResult$1;
310
+ all<T = Record<string, unknown>>(...params: SqliteValue$1[]): T[];
311
+ get<T = Record<string, unknown>>(...params: SqliteValue$1[]): T | undefined;
312
+ }
313
+ /**
314
+ * Sync SQLite client port owned by Mockingbird.
315
+ *
316
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
317
+ * `bun:sqlite` instances all work when they expose this surface.
318
+ */
319
+ interface SqliteClient$1 {
320
+ exec(sql: string): void;
321
+ prepare(sql: string): SqliteStatement$1;
322
+ transaction<T>(fn: () => T): T;
323
+ }
324
+
325
+ /**
326
+ * Seeded pseudo-random numbers, so anything a mock invents — ids, jitter, which
327
+ * request a percentage fault hits — is reproducible from a seed.
328
+ *
329
+ * mulberry32: small, fast, and stable across runtimes, which matters more here
330
+ * than statistical quality.
331
+ */
332
+ type Rng = {
333
+ /** Next value in `[0, 1)`. */
334
+ next(): number;
335
+ /** Next integer in `[min, max]`. */
336
+ int(min: number, max: number): number;
337
+ /** Restart the stream from its seed. */
338
+ reset(): void;
339
+ seed: number;
340
+ };
341
+
342
+ /**
343
+ * A deliberate failure injected in front of an operation.
344
+ *
345
+ * This is how a suite reaches the vendor's failure modes without the vendor: the
346
+ * quota error that only appears when a shared sandbox is full, the 429 that only
347
+ * appears under load, the 5xx that proves a retry path works.
348
+ */
349
+ type FaultRule = {
350
+ /** Stable id, so a suite can retire exactly the rule it added. */
351
+ id: string;
352
+ /** Fault only this operation. Omit to match every operation. */
353
+ operationId?: string;
354
+ /** Fault only this HTTP method, case-insensitive. Omit to match every method. */
355
+ method?: string;
356
+ /** Fault only paths starting with this prefix. Omit to match every path. */
357
+ pathPrefix?: string;
358
+ /**
359
+ * Fault only this namespace. Omit (or `"*"`) to fault every namespace — which is what
360
+ * an in-process caller usually wants, and what a parallel worker usually does not:
361
+ * rules added through `POST /__admin/faults` default to the calling namespace.
362
+ */
363
+ namespace?: string;
364
+ status: number;
365
+ /** Response body, serialized as JSON. A string is sent as-is. */
366
+ body?: unknown;
367
+ headers?: Record<string, string>;
368
+ /** Retire the rule after this many faults. Omit to keep it until removed. */
369
+ count?: number;
370
+ /** Fault this fraction of matching requests, `0`–`1`. Default `1`. */
371
+ rate?: number;
372
+ /** Hold the response back this long, to exercise timeouts. */
373
+ delayMs?: number;
374
+ };
375
+ /** What a request looks like to the fault matcher. */
376
+ type FaultCandidate = {
377
+ operationId: string | undefined;
378
+ method: string;
379
+ path: string;
380
+ namespace: string;
381
+ };
382
+ type FaultRegistry = {
383
+ add(rule: FaultRule): FaultRule;
384
+ list(): (FaultRule & {
385
+ remaining: number | null;
386
+ hits: number;
387
+ })[];
388
+ remove(id: string): boolean;
389
+ clear(): void;
390
+ /**
391
+ * The fault this request should get, or `undefined` to let it through.
392
+ * Consumes one of the matching rule's remaining uses.
393
+ */
394
+ take(candidate: FaultCandidate): Promise<{
395
+ id: string;
396
+ response: Response;
397
+ } | undefined>;
398
+ };
399
+
400
+ /** One handled request, as the structured log sees it. */
401
+ type RequestLog = {
402
+ service: string;
403
+ namespace: string;
404
+ operationId: string | undefined;
405
+ method: string;
406
+ path: string;
407
+ status: number;
408
+ durationMs: number;
409
+ /** True when the path matched no operation in the contract. */
410
+ unmatched: boolean;
411
+ /** Set when a fault rule produced the response. */
412
+ faultId?: string;
413
+ };
414
+ type MetricsReport = {
415
+ requests: number;
416
+ /** Counts keyed `<operationId> <status>`. */
417
+ byOperation: Record<string, number>;
418
+ /**
419
+ * Paths that matched no operation, most frequent first.
420
+ *
421
+ * This is the early-warning signal: a consumer calling something the mock does
422
+ * not implement shows up here as a count, before it fails a suite as a 404.
423
+ */
424
+ unmatched: {
425
+ method: string;
426
+ path: string;
427
+ count: number;
428
+ }[];
429
+ faults: number;
430
+ totalDurationMs: number;
431
+ };
432
+ type Metrics = {
433
+ record(entry: RequestLog): void;
434
+ report(): MetricsReport;
435
+ reset(): void;
436
+ };
437
+
438
+ /**
439
+ * A point-in-time copy of everything a service namespace holds.
440
+ *
441
+ * All service state lives in the two core tables keyed by namespace, so a snapshot
442
+ * is generic: any service gets per-test rollback without knowing its own schema.
443
+ * Restoring is much cheaper than rebuilding a namespace from a corpus.
444
+ */
445
+ type NamespaceSnapshot = {
446
+ namespace: string;
447
+ records: {
448
+ collection: string;
449
+ id: string;
450
+ seq: number;
451
+ value: string;
452
+ }[];
453
+ sequences: {
454
+ name: string;
455
+ kind: string;
456
+ value: number;
457
+ }[];
458
+ };
459
+
460
+ /**
461
+ * Anything that can answer a Fetch `Request` with a `Response`.
462
+ *
463
+ * Every Mockingbird service implements this, and every runtime adapter consumes it.
464
+ * It is the only contract shared across the whole graph.
465
+ */
466
+ interface FetchAPI$1 {
467
+ fetch(request: Request): Promise<Response>;
468
+ }
469
+
470
+ /** What the runtime needs from a service: a Fetch handler it can reset. */
471
+ type ServiceInstance = FetchAPI$1 & {
472
+ reset(): Promise<void>;
473
+ };
474
+ type ServiceRuntime<T extends ServiceInstance> = FetchAPI$1 & {
475
+ readonly name: string;
476
+ readonly sqlite: SqliteClient$1;
477
+ readonly clock: Clock;
478
+ readonly faults: FaultRegistry;
479
+ readonly metrics: Metrics;
480
+ readonly rng: Rng;
481
+ /** The instance behind `namespace` (the default one when omitted), created on first use. */
482
+ instance(namespace?: string): T;
483
+ /** Public names of every namespace created so far. */
484
+ namespaces(): string[];
485
+ /** Reset one namespace, or every namespace with `"*"`. */
486
+ reset(namespace?: string): Promise<void>;
487
+ snapshot(namespace?: string): NamespaceSnapshot;
488
+ restore(snapshot: NamespaceSnapshot, namespace?: string): void;
489
+ };
490
+
491
+ /** Options every provider constructor accepts. */
492
+ type APIOptions = {
493
+ /** Sync SQLite client. Defaults to `@crvouga/mockingbird-service-sqlite`. */
494
+ sqlite?: SqliteClient$1;
495
+ /** Clock used for `created`-style fields. Default `Date.now`. */
496
+ now?: () => number;
497
+ /**
498
+ * Storage namespace for this instance's records. Instances sharing one SQLite
499
+ * client stay isolated when their namespaces differ. Defaults to the service name.
500
+ */
501
+ namespace?: string;
502
+ };
503
+
504
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
505
+ type SqliteValue = null | number | bigint | string | Uint8Array | boolean;
506
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
507
+ type SqliteRunResult = {
508
+ changes: number;
509
+ lastInsertRowid: number | bigint;
510
+ };
511
+ /**
512
+ * Prepared statement bound to a {@link SqliteClient}.
513
+ *
514
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
515
+ */
516
+ interface SqliteStatement {
517
+ run(...params: SqliteValue[]): SqliteRunResult;
518
+ all<T = Record<string, unknown>>(...params: SqliteValue[]): T[];
519
+ get<T = Record<string, unknown>>(...params: SqliteValue[]): T | undefined;
520
+ }
521
+ /**
522
+ * Sync SQLite client port owned by Mockingbird.
523
+ *
524
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
525
+ * `bun:sqlite` instances all work when they expose this surface.
526
+ */
527
+ interface SqliteClient {
528
+ exec(sql: string): void;
529
+ prepare(sql: string): SqliteStatement;
530
+ transaction<T>(fn: () => T): T;
531
+ }
532
+
533
+ /** Lab-test catalog mirrored from the Junction sandbox (`GET /v3/lab_test`). */
534
+ type CatalogMarker = {
535
+ id: number;
536
+ name: string;
537
+ slug: string;
538
+ description: string | null;
539
+ lab_id: number | null;
540
+ provider_id: string | null;
541
+ type: string | null;
542
+ unit: string | null;
543
+ price: string | null;
544
+ aoe: unknown;
545
+ a_la_carte_enabled: boolean;
546
+ common_tat_days: number | null;
547
+ worst_case_tat_days: number | null;
548
+ is_orderable: boolean | null;
549
+ };
550
+ type ExpectedResultLoinc = {
551
+ id: number;
552
+ name: string;
553
+ slug: string;
554
+ code: string;
555
+ unit: string | null;
556
+ };
557
+ type ExpectedResult = {
558
+ id: number;
559
+ name: string;
560
+ slug: string;
561
+ lab_id: number | null;
562
+ provider_id: string | null;
563
+ required: boolean;
564
+ loinc: ExpectedResultLoinc | null;
565
+ };
566
+ type LabTestRecord = {
567
+ id: string;
568
+ slug: string;
569
+ name: string;
570
+ sample_type: string;
571
+ method: string;
572
+ price: number;
573
+ is_active: boolean;
574
+ status: string;
575
+ fasting: boolean;
576
+ lab: Record<string, unknown>;
577
+ markers: CatalogMarker[] | null;
578
+ is_delegated: boolean;
579
+ auto_generated: boolean;
580
+ has_collection_instructions: boolean | null;
581
+ common_tat_days: number | null;
582
+ worst_case_tat_days: number | null;
583
+ };
584
+
585
+ type GetCacheEntry = {
586
+ status: number;
587
+ headers: Record<string, string>;
588
+ body: unknown;
589
+ };
590
+ type JunctionWebhookEvent = {
591
+ event_type: "labtest.order.created" | "labtest.order.updated" | "labtest.appointment.updated";
592
+ data: Record<string, unknown>;
593
+ team_id: string;
594
+ user_id: string;
595
+ client_user_id: string;
596
+ };
597
+ type WebhookDeliveryAttempt = {
598
+ message_id: string;
599
+ event: JunctionWebhookEvent;
600
+ attempt: number;
601
+ scheduled_at: string;
602
+ timeout_ms: number;
603
+ acknowledged: boolean;
604
+ };
605
+ type OrderEventRecord = {
606
+ id: number;
607
+ created_at: string;
608
+ status: string;
609
+ status_detail: null;
610
+ };
611
+ type OrderTransactionEmbed = {
612
+ id: string;
613
+ status: "active" | "completed" | "cancelled";
614
+ orders: Array<{
615
+ id: string;
616
+ low_level_status: string;
617
+ low_level_status_created_at: string;
618
+ origin: string;
619
+ parent_id: null;
620
+ created_at: string;
621
+ updated_at: string;
622
+ }>;
623
+ };
624
+ type OrderRecord = {
625
+ id: string;
626
+ user_id: string;
627
+ team_id: string;
628
+ patient_details: Record<string, unknown>;
629
+ patient_address: Record<string, unknown>;
630
+ lab_test: LabTestRecord;
631
+ details: Record<string, unknown>;
632
+ sample_id: string | null;
633
+ notes: null;
634
+ clinical_notes: string | null;
635
+ passthrough: string | null;
636
+ /** Echoed from the request's opaque provider account id; absent when the order had none. */
637
+ lab_account_id?: string;
638
+ created_at: string;
639
+ updated_at: string;
640
+ events: OrderEventRecord[];
641
+ status: string;
642
+ last_event: OrderEventRecord;
643
+ physician: {
644
+ first_name: string;
645
+ last_name: string;
646
+ npi: string;
647
+ };
648
+ health_insurance_id: null;
649
+ requisition_form_url: string | null;
650
+ shipping_details: null;
651
+ has_abn: boolean;
652
+ billing_type: string;
653
+ priority: boolean;
654
+ activate_by: null;
655
+ icd_codes: string[] | null;
656
+ interpretation: string | null;
657
+ has_missing_results: boolean | null;
658
+ result_types: string[] | null;
659
+ expected_result_by_date: string | null;
660
+ worst_case_result_by_date: string | null;
661
+ origin: string;
662
+ order_transaction: OrderTransactionEmbed;
663
+ };
664
+ /**
665
+ * A lab account as the ordering rules read it. Structurally `LabAccountRecord` from
666
+ * lab-accounts.ts, restated here because that module imports this one.
667
+ */
668
+ type StoredLabAccount = {
669
+ id: string;
670
+ lab: string;
671
+ org_id: string | null;
672
+ status: "active" | "pending" | "suspended" | "ready_to_launch";
673
+ delegated_flow: "order_delegated" | "result_delegated" | "fully_delegated" | "not_delegated";
674
+ provider_account_id: string;
675
+ account_name: string | null;
676
+ default_clinical_notes: string | null;
677
+ business_units: string[] | null;
678
+ allowed_billing: Record<string, readonly string[]>;
679
+ team_id_allowlist: readonly string[];
680
+ };
681
+ /**
682
+ * A chosen result for one order, installed through the admin API. Replaces the
683
+ * generated biomarker lines, so a suite can assert on an exact payload — an abnormal
684
+ * panel, a critical value, a missing marker — instead of whatever the generator made.
685
+ */
686
+ type ResultFixture = {
687
+ /** The fixture's name, for logs and `GET /__admin/results`. */
688
+ name: string;
689
+ results?: unknown[];
690
+ missing_results?: unknown[] | null;
691
+ interpretation?: string;
692
+ /** Served from `GET /v3/order/{id}/result/pdf` instead of the generated PDF. */
693
+ pdf_base64?: string;
694
+ };
695
+ /**
696
+ * How serviceability reads answer a ZIP the loaded corpus has no record for.
697
+ *
698
+ * - `synthetic`: invent plausible coverage. Right for property tests that walk random ZIPs.
699
+ * - `corpus`: refuse with a documented Mockingbird error. Right for a mock standing in for
700
+ * the vendor, where invented coverage would silently disagree with production.
701
+ */
702
+ type GeoMode = "synthetic" | "corpus";
703
+ type WebhookPublisher = (event: JunctionWebhookEvent) => void;
704
+ type JunctionWebhookOptions = {
705
+ seed?: number;
706
+ jitterRatio?: number;
707
+ timeoutMs?: number;
708
+ };
709
+
710
+ /**
711
+ * Anything that can answer a Fetch `Request` with a `Response`.
712
+ *
713
+ * Every Mockingbird service implements this, and every runtime adapter consumes it.
714
+ * It is the only contract shared across the whole graph.
715
+ */
716
+ interface FetchAPI {
717
+ fetch(request: Request): Promise<Response>;
718
+ }
719
+
720
+ type LabAccountStatus = "active" | "pending" | "suspended" | "ready_to_launch";
721
+ type LabAccountDelegatedFlow = "order_delegated" | "result_delegated" | "fully_delegated" | "not_delegated";
722
+ /**
723
+ * A lab account as a consumer configures it. Mirrors `ClientFacingLabAccount`, with
724
+ * every field but `id` and `lab` optional, plus a `states` shorthand for the common
725
+ * case of an account that client-bills in a fixed set of states.
726
+ */
727
+ type LabAccountInput = {
728
+ id: string;
729
+ /** Lab slug, e.g. `"quest"`, `"labcorp"`, `"bioreference"`. */
730
+ lab: string;
731
+ status?: LabAccountStatus;
732
+ delegated_flow?: LabAccountDelegatedFlow;
733
+ account_name?: string | null;
734
+ provider_account_id?: string;
735
+ org_id?: string | null;
736
+ business_units?: string[] | null;
737
+ default_clinical_notes?: string | null;
738
+ /** Billing type → states it is allowed in. Takes precedence over `states`. */
739
+ allowed_billing?: Record<string, readonly string[]>;
740
+ /** Shorthand for `allowed_billing: { client_bill: states }`. Default: every state. */
741
+ states?: readonly string[];
742
+ /** Teams the account is linked to. Default: the mock team, so it is selectable. */
743
+ team_id_allowlist?: readonly string[];
744
+ };
745
+
746
+ /**
747
+ * Version of the sealed-corpus on-disk format. Bumped whenever the shape changes so a
748
+ * stale recording is rejected instead of half-applied.
749
+ */
750
+ declare const SEALED_CORPUS_VERSION = 1;
751
+ /**
752
+ * Exact sandbox recording of the provider-owned reads a drop-in consumer depends on:
753
+ * parameter-stable GET observations (area/PSC inventory), the lab catalog, team labs, and
754
+ * lab accounts. Availability is intentionally absent — its slot dates and single-use
755
+ * `booking_key`s can never match a live cache key, so it stays with the generator.
756
+ */
757
+ type SealedCorpus = {
758
+ version: typeof SEALED_CORPUS_VERSION;
759
+ recordedAt: string;
760
+ source: string;
761
+ /** SHA-256 of the recording's content, written by `corpus pull`. Identifies it in logs. */
762
+ fingerprint?: string;
763
+ observations: Record<string, GetCacheEntry>;
764
+ catalog: {
765
+ labTests: LabTestRecord[];
766
+ labs: Record<string, unknown>[];
767
+ expectedResults: Record<string, ExpectedResult[]>;
768
+ };
769
+ labAccounts: Record<string, unknown>[];
770
+ };
771
+
772
+ type SeedSource = {
773
+ fetch: (request: Request) => Promise<Response>;
774
+ baseUrl: string;
775
+ headers: Record<string, string>;
776
+ };
777
+ type SeedObservations = {
778
+ getCache?: ReadonlyMap<string, GetCacheEntry>;
779
+ };
780
+ type SeedReport = {
781
+ users: number;
782
+ orders: number;
783
+ appointments: number;
784
+ catalogTests: number;
785
+ labs: number;
786
+ cacheEntries: number;
787
+ };
788
+
789
+ /**
790
+ * Signed webhook delivery, the way Junction delivers through Svix.
791
+ *
792
+ * Signing lives here, next to the events, so a consumer never hand-rolls it. The
793
+ * signature is standard Svix — `v1,` + base64 HMAC-SHA256, keyed by the base64 part of
794
+ * `whsec_…`, over `"<svix-id>.<svix-timestamp>.<body>"` — so the official `svix`
795
+ * verifier, and a receiver written for real Junction webhooks, accept it unchanged.
796
+ */
797
+ type WebhookEndpoint = {
798
+ url: string;
799
+ /** Svix signing secret, `whsec_<base64>`. A bare base64 secret is accepted too. */
800
+ secret: string;
801
+ /**
802
+ * Delay before each attempt, in ms; the first entry delays the first attempt. Default:
803
+ * Svix's schedule (immediately, 5 s, 5 min, 30 min, 2 h, 5 h, 10 h, 10 h).
804
+ */
805
+ retryDelaysMs?: readonly number[];
806
+ /** Abort an attempt that takes longer than this. Default 15 s, like Svix. */
807
+ timeoutMs?: number;
808
+ /** Added to every delivery, e.g. a routing scope for a shared receiver. */
809
+ headers?: Record<string, string>;
810
+ fetch?: (request: Request) => Promise<Response>;
811
+ };
812
+ type WebhookAttempt = {
813
+ attempt: number;
814
+ /** Wall-clock time of the attempt, ISO-8601. */
815
+ at: string;
816
+ /** Receiver's status code, or `null` when the request never completed. */
817
+ status: number | null;
818
+ error: string | null;
819
+ durationMs: number;
820
+ };
821
+ type WebhookDelivery = {
822
+ messageId: string;
823
+ namespace: string;
824
+ event: JunctionWebhookEvent;
825
+ state: "pending" | "delivered" | "failed";
826
+ attempts: WebhookAttempt[];
827
+ };
828
+ type WebhookDispatcher = {
829
+ /** Queue an event for delivery. Returns immediately; delivery runs in the background. */
830
+ publish(event: JunctionWebhookEvent, namespace: string): WebhookDelivery;
831
+ deliveries(namespace?: string): WebhookDelivery[];
832
+ /** Deliver a message again now, as a new attempt, whatever its state. */
833
+ replay(messageId: string): Promise<WebhookDelivery | undefined>;
834
+ /** Run every pending retry now instead of waiting out its delay. */
835
+ flush(): Promise<void>;
836
+ /** Resolve once no delivery is in flight. */
837
+ idle(): Promise<void>;
838
+ /** Cancel pending retries and forget every delivery. */
839
+ clear(namespace?: string): void;
840
+ };
841
+
842
+ /**
843
+ * Stateful mock of the Junction (Vital) API user and lab-testing surfaces.
844
+ *
845
+ * Docs: https://docs.junction.com/
846
+ * Auth: `x-vital-api-key` — https://docs.junction.com/api-details/junction-api
847
+ */
848
+ type JunctionAPIOptions = APIOptions & {
849
+ onWebhook?: WebhookPublisher;
850
+ webhook?: JunctionWebhookOptions;
851
+ /** Install a recorded corpus at construction; it is re-applied on every `reset()`. */
852
+ corpus?: SealedCorpus;
853
+ /**
854
+ * How serviceability reads answer a ZIP the corpus does not cover. Default: `corpus`
855
+ * when a corpus is given (refuse, loudly), otherwise `synthetic` (invent coverage).
856
+ */
857
+ geo?: GeoMode;
858
+ /**
859
+ * The team's lab accounts, replacing the built-in fixtures (and any from the corpus).
860
+ * `create_order` routes, accepts and rejects `lab_account_id` against these.
861
+ */
862
+ labAccounts?: readonly LabAccountInput[];
863
+ };
864
+ /** What a loaded corpus covers, for `/health` and startup logs. */
865
+ type CorpusInfo = {
866
+ label: string;
867
+ recordedAt: string;
868
+ source: string;
869
+ observations: number;
870
+ labTests: number;
871
+ labAccounts: number;
872
+ zips: number;
873
+ };
874
+ declare class JunctionAPI implements FetchAPI {
875
+ readonly app: Hono;
876
+ readonly sqlite: SqliteClient;
877
+ private readonly service;
878
+ private readonly state;
879
+ private corpus;
880
+ private labAccountConfig;
881
+ constructor(options?: JunctionAPIOptions);
882
+ fetch(request: Request): Promise<Response>;
883
+ reset(): Promise<void>;
884
+ /**
885
+ * Install a sealed sandbox recording: seed the observation cache and replace the catalog,
886
+ * labs, and lab accounts with the recording's exact values. Re-applied on `reset()`.
887
+ */
888
+ installCorpus(corpus: SealedCorpus): void;
889
+ /**
890
+ * Which lab accounts the ordering rules see, in order of precedence: the configured
891
+ * ones, then a corpus's real accounts, then the built-in fixtures (which a corpus
892
+ * recorded from a team with no accounts leaves in place).
893
+ */
894
+ private seedLabAccounts;
895
+ /** Replace the team's lab accounts; `undefined` restores the default. Kept across resets. */
896
+ configureLabAccounts(accounts: readonly LabAccountInput[] | undefined): StoredLabAccount[];
897
+ labAccounts(): StoredLabAccount[];
898
+ corpusInfo(): CorpusInfo | undefined;
899
+ get geoMode(): GeoMode;
900
+ set geoMode(mode: GeoMode);
901
+ order(id: string): OrderRecord | undefined;
902
+ orders(): OrderRecord[];
903
+ /**
904
+ * Put an order straight into a status (a full `<status>.<method>.<event>` value) and
905
+ * publish the webhook a real transition would. `flags` takes the same keys as
906
+ * `simulate_order`'s body: `interpretation`, `result_types`, `has_missing_results`.
907
+ */
908
+ transitionOrder(id: string, status: string, options: {
909
+ now: () => number;
910
+ flags?: Record<string, unknown> | null;
911
+ }): OrderRecord | undefined;
912
+ /** Serve `fixture` as this order's results, replacing the generated ones. */
913
+ installResultFixture(orderId: string, fixture: ResultFixture): boolean;
914
+ resultFixture(orderId: string): ResultFixture | undefined;
915
+ seedFrom(source: SeedSource, observations?: SeedObservations): Promise<SeedReport>;
916
+ ensureLabTests(source: SeedSource, ids: readonly string[]): Promise<number>;
917
+ ensureOrders(source: SeedSource, ids: readonly string[]): Promise<number>;
918
+ markUserDeleted(userId: string): void;
919
+ webhookEvents(): JunctionWebhookEvent[];
920
+ webhookDeliveryAttempts(): WebhookDeliveryAttempt[];
921
+ }
922
+
923
+ type JunctionRuntimeOptions = {
924
+ /**
925
+ * Recorded vendor data every namespace starts from. The served mock loads the corpus
926
+ * shipped at `@crvouga/mockingbird-service-junction/corpus` unless told otherwise.
927
+ */
928
+ corpus?: SealedCorpus;
929
+ /** Default: `corpus` when a corpus is loaded, otherwise `synthetic`. */
930
+ geo?: GeoMode;
931
+ /** The team's lab accounts; see {@link JunctionAPIOptions.labAccounts}. */
932
+ labAccounts?: readonly LabAccountInput[];
933
+ /** Deliver signed webhooks here, with Svix's retry schedule. */
934
+ webhooks?: WebhookEndpoint;
935
+ /** Called in-process for every webhook event, delivered or not. */
936
+ onWebhook?: (event: Parameters<WebhookPublisher>[0], namespace: string) => void;
937
+ sqlite?: SqliteClient;
938
+ clock?: Clock;
939
+ /** Seeds fault rates and webhook retry jitter. */
940
+ seed?: number | string;
941
+ /** Require `x-mockingbird-admin-key` on `/__admin/*`. */
942
+ adminKey?: string;
943
+ onLog?: (entry: RequestLog) => void;
944
+ };
945
+ type JunctionRuntime = ServiceRuntime<JunctionAPI> & {
946
+ /** Signed delivery, when `webhooks` was configured. */
947
+ readonly webhooks: WebhookDispatcher | undefined;
948
+ };
949
+
950
+ /** Port `mockingbird-junction serve` listens on when none is given. */
951
+ declare const DEFAULT_PORT = 8787;
952
+ /** A corpus to serve: the shipped one, none (synthetic), a file path, or a loaded corpus. */
953
+ type CorpusSource = "default" | "none" | (string & {}) | SealedCorpus;
954
+ type JunctionServerOptions = Omit<JunctionRuntimeOptions, "corpus"> & {
955
+ /** Default `0`: the OS picks a free port (read it from `url` / `port`). */
956
+ port?: number;
957
+ /** Default `127.0.0.1`. */
958
+ host?: string;
959
+ /** Default `"default"`: the corpus shipped with this package. */
960
+ corpus?: CorpusSource;
961
+ };
962
+ type JunctionServer = Listening & {
963
+ runtime: JunctionRuntime;
964
+ };
965
+ /** Resolve a {@link CorpusSource} to a corpus, or `undefined` for synthetic data. */
966
+ declare const loadCorpus: (source: CorpusSource) => Promise<SealedCorpus | undefined>;
967
+ /**
968
+ * Serve the Junction mock over `node:http`. Resolves once it is listening.
969
+ *
970
+ * const server = await createServer()
971
+ * // point the Vital SDK at server.url; await server.close() when done
972
+ */
973
+ declare const createServer: (options?: JunctionServerOptions) => Promise<JunctionServer>;
974
+ /** How `serve` (and `serve --config`) builds the Junction mock from flags. */
975
+ declare const serveTarget: ServeTarget;
976
+
977
+ export { DEFAULT_PORT, createServer, loadCorpus, serveTarget };
978
+ export type { CorpusSource, JunctionServer, JunctionServerOptions };