@crvouga/mockingbird-service-paddle 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,1494 @@
1
+ import { Hono } from 'hono';
2
+
3
+ /**
4
+ * Anything that can answer a Fetch `Request` with a `Response`.
5
+ *
6
+ * Every Mockingbird service implements this, and every runtime adapter consumes it.
7
+ * It is the only contract shared across the whole graph.
8
+ */
9
+ interface FetchAPI$1 {
10
+ fetch(request: Request): Promise<Response>;
11
+ }
12
+
13
+ /**
14
+ * The single source of time for a service.
15
+ *
16
+ * Every timestamp a mock writes reads from here, so a suite moves time instead of
17
+ * sleeping: appointment windows, result delays and expiries become reachable in
18
+ * milliseconds. A frozen clock also makes timestamps reproducible from a seed.
19
+ */
20
+ type ClockState = {
21
+ /** Current epoch milliseconds. */
22
+ now: number;
23
+ /** True while time does not advance on its own. */
24
+ frozen: boolean;
25
+ /** Milliseconds this clock adds to its underlying source. */
26
+ offsetMs: number;
27
+ };
28
+ type Clock = {
29
+ now(): number;
30
+ /** Pin the clock to an exact instant, keeping it frozen if it already was. */
31
+ set(epochMs: number): void;
32
+ /** Move the clock forward, or back with a negative delta. */
33
+ advance(deltaMs: number): void;
34
+ /** Stop time at the current instant. */
35
+ freeze(): void;
36
+ /** Resume from the current instant. */
37
+ unfreeze(): void;
38
+ /** Drop back to the underlying source, live. */
39
+ reset(): void;
40
+ state(): ClockState;
41
+ };
42
+
43
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
44
+ type SqliteValue$1 = null | number | bigint | string | Uint8Array | boolean;
45
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
46
+ type SqliteRunResult$1 = {
47
+ changes: number;
48
+ lastInsertRowid: number | bigint;
49
+ };
50
+ /**
51
+ * Prepared statement bound to a {@link SqliteClient}.
52
+ *
53
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
54
+ */
55
+ interface SqliteStatement$1 {
56
+ run(...params: SqliteValue$1[]): SqliteRunResult$1;
57
+ all<T = Record<string, unknown>>(...params: SqliteValue$1[]): T[];
58
+ get<T = Record<string, unknown>>(...params: SqliteValue$1[]): T | undefined;
59
+ }
60
+ /**
61
+ * Sync SQLite client port owned by Mockingbird.
62
+ *
63
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
64
+ * `bun:sqlite` instances all work when they expose this surface.
65
+ */
66
+ interface SqliteClient$1 {
67
+ exec(sql: string): void;
68
+ prepare(sql: string): SqliteStatement$1;
69
+ transaction<T>(fn: () => T): T;
70
+ }
71
+
72
+ /** Every stored record carries a monotonically increasing sequence for stable ordering. */
73
+ type Stored<T> = {
74
+ seq: number;
75
+ value: T;
76
+ };
77
+ type ListRecordsOptions<T> = {
78
+ /** Keep only records passing the predicate. */
79
+ where?: (value: T, seq: number) => boolean;
80
+ /** Sort order; default newest first. */
81
+ order?: "newest" | "oldest";
82
+ };
83
+ /**
84
+ * A SQLite-backed table of JSON records addressed by id. Ordering is by insertion
85
+ * sequence, never by id lexicographic order, so list semantics stay stable.
86
+ */
87
+ declare class Collection<T> {
88
+ private readonly sqlite;
89
+ /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
90
+ readonly namespace: string;
91
+ /** Table name inside the namespace. Stable across resets of the rows themselves. */
92
+ readonly collectionName: string;
93
+ constructor(sqlite: SqliteClient$1,
94
+ /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
95
+ namespace: string,
96
+ /** Table name inside the namespace. Stable across resets of the rows themselves. */
97
+ collectionName: string);
98
+ private bumpCollectionSeq;
99
+ nextSequence(): number;
100
+ get(id: string): T | undefined;
101
+ has(id: string): boolean;
102
+ /** Insert a new record, assigning it the next sequence number. */
103
+ insert(id: string, value: T): Stored<T>;
104
+ /** Replace an existing record's value, keeping its position. */
105
+ update(id: string, value: T): Stored<T> | undefined;
106
+ delete(id: string): boolean;
107
+ /** How many records the collection holds, without reading them. */
108
+ count(): number;
109
+ list(options?: ListRecordsOptions<T>): Array<Stored<T> & {
110
+ id: string;
111
+ }>;
112
+ }
113
+
114
+ /**
115
+ * Seeded pseudo-random numbers, so anything a mock invents — ids, jitter, which
116
+ * request a percentage fault hits — is reproducible from a seed.
117
+ *
118
+ * mulberry32: small, fast, and stable across runtimes, which matters more here
119
+ * than statistical quality.
120
+ */
121
+ type Rng = {
122
+ /** Next value in `[0, 1)`. */
123
+ next(): number;
124
+ /** Next integer in `[min, max]`. */
125
+ int(min: number, max: number): number;
126
+ /** Restart the stream from its seed. */
127
+ reset(): void;
128
+ /** Serializable engine state used by deterministic checkpoints. */
129
+ state(): number;
130
+ /** Restore a state previously returned by {@link state}. */
131
+ setState(state: number): void;
132
+ seed: number;
133
+ };
134
+
135
+ /**
136
+ * A deliberate failure injected in front of an operation.
137
+ *
138
+ * This is how a suite reaches the vendor's failure modes without the vendor: the
139
+ * quota error that only appears when a shared sandbox is full, the 429 that only
140
+ * appears under load, the 5xx that proves a retry path works.
141
+ */
142
+ type FaultRule = {
143
+ /** Stable id, so a suite can retire exactly the rule it added. */
144
+ id: string;
145
+ /** Fault only this operation. Omit to match every operation. */
146
+ operationId?: string;
147
+ /** Fault only this HTTP method, case-insensitive. Omit to match every method. */
148
+ method?: string;
149
+ /** Fault only paths starting with this prefix. Omit to match every path. */
150
+ pathPrefix?: string;
151
+ /**
152
+ * Fault only this namespace. Omit (or `"*"`) to fault every namespace — which is what
153
+ * an in-process caller usually wants, and what a parallel worker usually does not:
154
+ * rules added through `POST /__admin/faults` default to the calling namespace.
155
+ */
156
+ namespace?: string;
157
+ /**
158
+ * Status of the injected response. Omit for a rule that only delays (`delayMs` /
159
+ * `latencyMs`), only drops the connection (`drop`), or only switches on an `effect`:
160
+ * the request then still reaches the service.
161
+ */
162
+ status?: number;
163
+ /** Response body, serialized as JSON. A string is sent as-is. */
164
+ body?: unknown;
165
+ headers?: Record<string, string>;
166
+ /** Retire the rule after this many faults. Omit to keep it until removed. */
167
+ count?: number;
168
+ /** Fault this fraction of matching requests, `0`–`1`. Default `1`. */
169
+ rate?: number;
170
+ /** Hold the response back this long, to exercise timeouts. */
171
+ delayMs?: number;
172
+ /** Alias of `delayMs`. */
173
+ latencyMs?: number;
174
+ /**
175
+ * Drop the connection instead of answering: an in-process `fetch` rejects with a
176
+ * `TypeError`, and a served mock destroys the socket. Models "unknown outcome" failures.
177
+ */
178
+ drop?: boolean;
179
+ /**
180
+ * A named service behaviour to switch on for the matching request instead of (or
181
+ * before) a canned response, e.g. `created_but_500` or `numeric_tracking_id`. Services
182
+ * read it with `faultEffects(request)`.
183
+ */
184
+ effect?: string;
185
+ /** Parameters for `effect`. */
186
+ params?: Record<string, unknown>;
187
+ /** From the preset this rule was expanded from, if any. */
188
+ preset?: string;
189
+ };
190
+ /** A fault that fired for one request. */
191
+ type FaultHit = {
192
+ id: string;
193
+ /** The injected response; absent when the rule only delays, drops, or sets an effect. */
194
+ response?: Response;
195
+ drop?: boolean;
196
+ effect?: {
197
+ name: string;
198
+ params: Record<string, unknown>;
199
+ };
200
+ };
201
+ /**
202
+ * A named, documented fault a suite switches on by name
203
+ * (`POST /__admin/faults {"preset": "rate_limited"}`): one or more rules, and optionally a
204
+ * webhook delivery fault.
205
+ */
206
+ type FaultPreset = {
207
+ description: string;
208
+ rules?: Omit<FaultRule, "id">[];
209
+ webhook?: {
210
+ mode: "duplicate" | "reorder" | "drop";
211
+ count?: number;
212
+ };
213
+ };
214
+ /** What a request looks like to the fault matcher. */
215
+ type FaultCandidate = {
216
+ operationId: string | undefined;
217
+ method: string;
218
+ path: string;
219
+ namespace: string;
220
+ };
221
+ type FaultRegistry = {
222
+ add(rule: FaultRule): FaultRule;
223
+ list(): (FaultRule & {
224
+ remaining: number | null;
225
+ hits: number;
226
+ })[];
227
+ remove(id: string): boolean;
228
+ clear(): void;
229
+ /**
230
+ * Every fault this request should get, in rule order, stopping at the first that answers
231
+ * or drops (effect-only and delay-only rules let later rules match too). Consumes one of
232
+ * each matching rule's remaining uses.
233
+ */
234
+ take(candidate: FaultCandidate): Promise<FaultHit[]>;
235
+ };
236
+
237
+ /** A stable identifier for a point in a {@link Timeline}. */
238
+ type CheckpointId = string;
239
+ /** An immutable node in a timeline's checkpoint DAG. */
240
+ type Checkpoint<T> = Readonly<{
241
+ id: CheckpointId;
242
+ branch: string;
243
+ parent: CheckpointId | null;
244
+ /** Logical time supplied by the timeline's injected clock. */
245
+ at: number;
246
+ value: T;
247
+ }>;
248
+ type TimelineOptions = {
249
+ /** Logical clock used to stamp checkpoints. Defaults to a deterministic counter. */
250
+ now?: () => number;
251
+ /** Maximum retained checkpoints. Branch heads are never collected. Default 1,000. */
252
+ maxCheckpoints?: number;
253
+ /** Customize deterministic checkpoint IDs. */
254
+ id?: (sequence: number) => CheckpointId;
255
+ };
256
+ type CommitOptions = {
257
+ branch?: string;
258
+ /** Parent checkpoint. Defaults to the selected branch's current head. */
259
+ parent?: CheckpointId | null;
260
+ };
261
+ type ForkOptions = {
262
+ /** Checkpoint to fork from. Defaults to the main branch's head. */
263
+ from?: CheckpointId;
264
+ };
265
+ /**
266
+ * Small, storage-agnostic checkpoint DAG shared by service runtimes. Its values may be immutable
267
+ * records, namespace images, or copy-on-write SQL engine snapshots.
268
+ *
269
+ * Values are retained by reference. Engines can therefore use persistent/COW snapshots while
270
+ * simpler services can use immutable values. IDs and GC order are deterministic, and all IO
271
+ * (the logical clock) is injected.
272
+ */
273
+ declare class Timeline<T> {
274
+ readonly maxCheckpoints: number;
275
+ private readonly now;
276
+ private readonly makeId;
277
+ private readonly nodes;
278
+ private readonly heads;
279
+ /** Unreferenced nodes in the exact order they became collectible. */
280
+ private readonly evictable;
281
+ /** Branch heads plus explicit retainers. Absent means zero. */
282
+ private readonly references;
283
+ private readonly explicitPins;
284
+ private sequence;
285
+ constructor(options?: TimelineOptions);
286
+ /** Capture a new immutable value and move `branch` to it. */
287
+ commit(value: T, options?: CommitOptions): Checkpoint<T>;
288
+ /** Create a branch pointer without copying its checkpoint value. */
289
+ fork(branch: string, options?: ForkOptions): Checkpoint<T> | undefined;
290
+ /** Move a branch pointer to an existing checkpoint. */
291
+ checkout(branch: string, id: CheckpointId): Checkpoint<T>;
292
+ get(id: CheckpointId): Checkpoint<T>;
293
+ head(branch?: string): Checkpoint<T> | undefined;
294
+ hasBranch(branch: string): boolean;
295
+ branches(): Readonly<Record<string, CheckpointId>>;
296
+ checkpoints(): readonly Checkpoint<T>[];
297
+ /** Number of retained checkpoints without allocating an array. */
298
+ get size(): number;
299
+ /** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
300
+ retain(id: CheckpointId): Checkpoint<T>;
301
+ /** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
302
+ release(id: CheckpointId): boolean;
303
+ deleteBranch(branch: string): boolean;
304
+ /**
305
+ * Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
306
+ * commits never scan pinned nodes or the retained history. Parents are metadata rather than a
307
+ * storage dependency, so a retained node remains usable after pruning.
308
+ */
309
+ gc(max?: number): CheckpointId[];
310
+ private collect;
311
+ private moveHead;
312
+ private addReference;
313
+ private removeReference;
314
+ private assertBranch;
315
+ }
316
+
317
+ /**
318
+ * Anything that can answer a Fetch `Request` with a `Response`.
319
+ *
320
+ * Every Mockingbird service implements this, and every runtime adapter consumes it.
321
+ * It is the only contract shared across the whole graph.
322
+ */
323
+ interface FetchAPI {
324
+ fetch(request: Request): Promise<Response>;
325
+ }
326
+
327
+ /** Options every provider constructor accepts. */
328
+ type APIOptions = {
329
+ /** Sync SQLite client. Defaults to `@crvouga/mockingbird-service-sqlite`. */
330
+ sqlite?: SqliteClient$1;
331
+ /** Clock used for `created`-style fields. Default `Date.now`. */
332
+ now?: () => number;
333
+ /**
334
+ * Storage namespace for this instance's records. Instances sharing one SQLite
335
+ * client stay isolated when their namespaces differ. Defaults to the service name.
336
+ */
337
+ namespace?: string;
338
+ };
339
+
340
+ /**
341
+ * One problem with a request body, at a dotted path (`patient.address.city`, `items.0.sku`).
342
+ * `kind` is `media_type` when the body is present but its media type is not one the operation
343
+ * accepts (a `415` on most vendors), `syntax` when it could not be decoded, `required` when
344
+ * the operation needs a body and none arrived, and `schema` for a contract violation.
345
+ */
346
+ type BodyIssue = {
347
+ path: string;
348
+ message: string;
349
+ kind?: "media_type" | "syntax" | "required" | "schema";
350
+ };
351
+
352
+ /**
353
+ * What the mock received from a request it rejected, so a 4xx can be attributed after the
354
+ * fact (an empty body, a missing `content-type`, a schema violation) without logging the body.
355
+ */
356
+ type RejectedRequest = {
357
+ /** The raw `content-type` header, or `null` when the request sent none. */
358
+ contentType: string | null;
359
+ /** Bytes of body received from `content-length` (`0` for none), or `null` when the client sent no length (a streamed / chunked body). */
360
+ bodyBytes: number | null;
361
+ /** The raw `transfer-encoding` header (`chunked`), or `null`. */
362
+ transferEncoding: string | null;
363
+ };
364
+ /** One handled request, as the structured log sees it. */
365
+ type RequestLog = {
366
+ service: string;
367
+ namespace: string;
368
+ operationId: string | undefined;
369
+ method: string;
370
+ path: string;
371
+ status: number;
372
+ durationMs: number;
373
+ /** True when the path matched no operation in the contract. */
374
+ unmatched: boolean;
375
+ /** Set when a fault rule produced the response. */
376
+ faultId?: string;
377
+ /** Resource ids the handler touched (`userId`, `orderId`, …), when the service reports them. */
378
+ ids?: Record<string, string>;
379
+ /** Set when the service created a resource the request referred to but that did not exist. */
380
+ adopted?: boolean;
381
+ /** Set on a rejection (status ≥ 400) the mock produced itself, never on a scripted fault. */
382
+ request?: RejectedRequest;
383
+ /** The validation issues behind a rejection, when the service found any. */
384
+ issues?: BodyIssue[];
385
+ };
386
+ type MetricsReport = {
387
+ requests: number;
388
+ /** Counts keyed `<operationId> <status>`. */
389
+ byOperation: Record<string, number>;
390
+ /**
391
+ * Paths that matched no operation, most frequent first.
392
+ *
393
+ * This is the early-warning signal: a consumer calling something the mock does
394
+ * not implement shows up here as a count, before it fails a suite as a 404.
395
+ */
396
+ unmatched: {
397
+ method: string;
398
+ path: string;
399
+ count: number;
400
+ }[];
401
+ faults: number;
402
+ totalDurationMs: number;
403
+ };
404
+ type Metrics = {
405
+ record(entry: RequestLog): void;
406
+ report(): MetricsReport;
407
+ reset(): void;
408
+ };
409
+
410
+ /** One journal entry: a request log stamped with when (on the mock clock) it was handled. */
411
+ type JournalEntry = RequestLog & {
412
+ at: string;
413
+ };
414
+ type JournalQuery = {
415
+ /** Only this namespace. Omit for every namespace, oldest first across all of them. */
416
+ namespace?: string;
417
+ operationId?: string;
418
+ status?: number;
419
+ /** Only entries at or after this instant (epoch ms). */
420
+ since?: number;
421
+ /** At most this many, the most recent kept. */
422
+ limit?: number;
423
+ };
424
+ type Journal = {
425
+ readonly size: number;
426
+ record(entry: JournalEntry): void;
427
+ list(query?: JournalQuery): JournalEntry[];
428
+ /** Forget one namespace's entries, or every namespace's. */
429
+ clear(namespace?: string): void;
430
+ };
431
+
432
+ /** Credential → namespace mapping behind `PUT /__admin/credentials`. */
433
+ type CredentialRegistry = {
434
+ set(credential: string, namespace: string): void;
435
+ get(credential: string): string | undefined;
436
+ remove(credential: string): boolean;
437
+ clear(): void;
438
+ entries(): {
439
+ credential: string;
440
+ namespace: string;
441
+ }[];
442
+ };
443
+
444
+ /**
445
+ * A point-in-time copy of everything a service namespace holds.
446
+ *
447
+ * All service state lives in the two core tables keyed by namespace, so a snapshot
448
+ * is generic: any service gets per-test rollback without knowing its own schema.
449
+ * Restoring is much cheaper than rebuilding a namespace from a corpus.
450
+ */
451
+ type NamespaceSnapshot = {
452
+ namespace: string;
453
+ records: {
454
+ collection: string;
455
+ id: string;
456
+ seq: number;
457
+ value: string;
458
+ }[];
459
+ sequences: {
460
+ name: string;
461
+ kind: string;
462
+ value: number;
463
+ }[];
464
+ };
465
+
466
+ declare const STATE_FIELD_KINDS: readonly ["string", "number", "boolean", "null", "object", "array", "unknown"];
467
+ type StateFieldKind = (typeof STATE_FIELD_KINDS)[number];
468
+ /** JSON-safe annotations a bespoke admin UI may read. The default UI shows them as text. */
469
+ type StateMeta = Readonly<Record<string, string | number | boolean | null>>;
470
+ type StateField = {
471
+ name: string;
472
+ kind: StateFieldKind;
473
+ optional: boolean;
474
+ description?: string;
475
+ /** One level of nested object fields. */
476
+ fields?: StateField[];
477
+ meta?: StateMeta;
478
+ };
479
+ type StateCollectionView = {
480
+ name: string;
481
+ label: string;
482
+ description?: string;
483
+ count: number;
484
+ /** `mixed` when a declaration and stored rows both contribute fields. */
485
+ source: "declared" | "inferred" | "mixed";
486
+ fields: StateField[];
487
+ meta?: StateMeta;
488
+ };
489
+ /** The shape of one namespace, for an admin UI that has never seen the service before. */
490
+ type StateView = {
491
+ namespace: string;
492
+ storageNamespace: string;
493
+ collections: StateCollectionView[];
494
+ };
495
+
496
+ /**
497
+ * Outbound webhooks, shared by every service that has them.
498
+ *
499
+ * A service publishes a message (the exact bytes the vendor would send); the hub fans it out
500
+ * to every matching endpoint, signs each delivery with the vendor's scheme, retries on the
501
+ * vendor's schedule, and keeps a record a suite can read, replay or flush through
502
+ * `/__admin/webhooks*`. Signature timestamps use the wall clock unless a service injects
503
+ * `now`: receivers check them against their own time, and an advanced mock clock would
504
+ * otherwise fail every delivery. A service whose caller injected the clock (Stripe) passes it,
505
+ * so a virtual-time receiver verifies at the mock's time.
506
+ */
507
+ /** What a signer sees for one delivery attempt. */
508
+ type SignInput = {
509
+ messageId: string;
510
+ /** Exact bytes about to be sent. */
511
+ body: string;
512
+ /** Unix seconds of this attempt: wall clock, or the hub's injected `now`. */
513
+ timestampSeconds: number;
514
+ /** Where the delivery is posted. */
515
+ url: string;
516
+ /** The endpoint's secret, if it has one. */
517
+ secret: string | undefined;
518
+ /** The endpoint's `signUrl` (the public URL the receiver verifies against), else `url`. */
519
+ signUrl: string;
520
+ /** Form parameters, when the body is form-encoded (Twilio signs these, not the body). */
521
+ form: Record<string, string> | undefined;
522
+ /** Stable event type and metadata captured with the message; avoids signer side-channel state. */
523
+ type: string;
524
+ tags: Readonly<Record<string, string>>;
525
+ };
526
+ /** Headers to add to one delivery. */
527
+ type WebhookSigner = (input: SignInput) => Record<string, string> | Promise<Record<string, string>>;
528
+ type WebhookEndpoint = {
529
+ /** Stable id; generated when omitted. */
530
+ id?: string;
531
+ url: string;
532
+ secret?: string;
533
+ /** Event types to deliver; omit or include `"*"` for every type. */
534
+ events?: string[];
535
+ /** Deliver only messages whose tags include all of these (e.g. `{ account: "mso" }`). */
536
+ tags?: Record<string, string>;
537
+ /** The public URL the receiver verifies signatures against (Twilio), when it differs. */
538
+ signUrl?: string;
539
+ headers?: Record<string, string>;
540
+ };
541
+ type WebhookMessage = {
542
+ id: string;
543
+ namespace: string;
544
+ type: string;
545
+ body: string;
546
+ contentType: string;
547
+ tags: Record<string, string>;
548
+ headers?: Record<string, string>;
549
+ /** Wall-clock ISO-8601 time of publication. */
550
+ publishedAt: string;
551
+ };
552
+ type WebhookAttempt = {
553
+ attempt: number;
554
+ at: string;
555
+ status: number | null;
556
+ error: string | null;
557
+ durationMs: number;
558
+ /** Exact receiver response body, when one was returned. */
559
+ responseBody?: string | null;
560
+ };
561
+ type WebhookDelivery = {
562
+ id: string;
563
+ messageId: string;
564
+ namespace: string;
565
+ type: string;
566
+ endpointId: string;
567
+ url: string;
568
+ state: "pending" | "delivered" | "failed" | "dropped";
569
+ attempts: WebhookAttempt[];
570
+ };
571
+ /** A delivery-level fault: what happens to the next `count` messages in a namespace. */
572
+ type WebhookFault = {
573
+ mode: "duplicate" | "reorder" | "drop";
574
+ /** Messages affected; default 1. */
575
+ count?: number;
576
+ };
577
+ type PublishInput = {
578
+ namespace: string;
579
+ type: string;
580
+ /** Exact body; objects are JSON-encoded. */
581
+ body: string | Record<string, unknown> | unknown[];
582
+ /** Default `application/json`, or form-encoded when `form` is given. */
583
+ contentType?: string;
584
+ /** Form parameters, when the vendor posts `application/x-www-form-urlencoded`. */
585
+ form?: Record<string, string>;
586
+ tags?: Record<string, string>;
587
+ /** Message-specific delivery headers, captured as part of durable message state. */
588
+ headers?: Record<string, string>;
589
+ /** Message id; generated when omitted. */
590
+ id?: string;
591
+ };
592
+ type WebhookHub = {
593
+ publish(input: PublishInput): WebhookMessage;
594
+ /** Replace a namespace's own endpoints (`PUT /__admin/webhook-endpoints`). */
595
+ setEndpoints(namespace: string, endpoints: WebhookEndpoint[]): WebhookEndpoint[];
596
+ /** The endpoints a namespace delivers to: its own, plus the global ones. */
597
+ endpoints(namespace: string): WebhookEndpoint[];
598
+ messages(namespace?: string): WebhookMessage[];
599
+ deliveries(namespace?: string): WebhookDelivery[];
600
+ replay(deliveryId: string): Promise<WebhookDelivery | undefined>;
601
+ /** Run every pending retry (and release held reordered messages) now, and every retry those attempts schedule, until nothing is pending. */
602
+ flush(): Promise<void>;
603
+ /** Resolve once nothing is in flight. */
604
+ idle(): Promise<void>;
605
+ fault(namespace: string, fault: WebhookFault): void;
606
+ clear(namespace?: string): void;
607
+ };
608
+
609
+ /** What the runtime needs from a service: a Fetch handler it can reset. */
610
+ type ServiceInstance = FetchAPI & {
611
+ reset(): Promise<void>;
612
+ };
613
+ type ServiceTimelineState = Readonly<{
614
+ snapshot: NamespaceSnapshot;
615
+ clock: Readonly<ReturnType<Clock["state"]>>;
616
+ rngState: number;
617
+ }>;
618
+ type ServiceCheckpoint = Checkpoint<ServiceTimelineState>;
619
+ type ServiceRuntime<T extends ServiceInstance> = FetchAPI & {
620
+ readonly name: string;
621
+ readonly sqlite: SqliteClient$1;
622
+ readonly clock: Clock;
623
+ readonly faults: FaultRegistry;
624
+ readonly metrics: Metrics;
625
+ readonly journal: Journal;
626
+ readonly rng: Rng;
627
+ readonly credentials: CredentialRegistry;
628
+ /** The webhook hub, when the service has outbound webhooks. */
629
+ readonly webhooks: WebhookHub | undefined;
630
+ /** Expand a named preset into fault rules (and webhook faults) for `namespace`. */
631
+ applyPreset(name: string, namespace?: string, overrides?: Partial<FaultRule>): FaultRule[];
632
+ /** The instance behind `namespace` (the default one when omitted), created on first use. */
633
+ instance(namespace?: string): T;
634
+ /** Public names of every namespace created so far. */
635
+ namespaces(): string[];
636
+ /** Reset one namespace, or every namespace with `"*"`. */
637
+ reset(namespace?: string): Promise<void>;
638
+ snapshot(namespace?: string): NamespaceSnapshot;
639
+ restore(snapshot: NamespaceSnapshot, namespace?: string): void;
640
+ /** Capture the current branch. Mutating HTTP calls do this automatically. */
641
+ checkpoint(namespace?: string, branch?: string): ServiceCheckpoint;
642
+ /** Create an isolated branch, optionally from a historical checkpoint. */
643
+ branch(name: string, options?: {
644
+ namespace?: string;
645
+ at?: string;
646
+ }): ServiceCheckpoint;
647
+ /** Restore a branch, clock, and PRNG to a checkpoint. */
648
+ checkout(checkpoint: string, options?: {
649
+ namespace?: string;
650
+ branch?: string;
651
+ }): void;
652
+ /** Inspect the retained history for a namespace. */
653
+ timeline(namespace?: string): Timeline<ServiceTimelineState>;
654
+ /** Collections in one namespace: declared shape plus what the rows actually hold. */
655
+ state(namespace?: string): StateView;
656
+ };
657
+
658
+ /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
659
+ type SqliteValue = null | number | bigint | string | Uint8Array | boolean;
660
+ /** Mutation counters returned by {@link SqliteStatement.run}. */
661
+ type SqliteRunResult = {
662
+ changes: number;
663
+ lastInsertRowid: number | bigint;
664
+ };
665
+ /**
666
+ * Prepared statement bound to a {@link SqliteClient}.
667
+ *
668
+ * Pass bind values as rest arguments on each call (no sticky `bind()`).
669
+ */
670
+ interface SqliteStatement {
671
+ run(...params: SqliteValue[]): SqliteRunResult;
672
+ all<T = Record<string, unknown>>(...params: SqliteValue[]): T[];
673
+ get<T = Record<string, unknown>>(...params: SqliteValue[]): T | undefined;
674
+ }
675
+ /**
676
+ * Sync SQLite client port owned by Mockingbird.
677
+ *
678
+ * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
679
+ * `bun:sqlite` instances all work when they expose this surface.
680
+ */
681
+ interface SqliteClient {
682
+ exec(sql: string): void;
683
+ prepare(sql: string): SqliteStatement;
684
+ transaction<T>(fn: () => T): T;
685
+ }
686
+
687
+ /**
688
+ * Stored records are the wire shape Paddle returns as `data` (snake_case), so a handler can
689
+ * serve them as-is and `include=` relations are layered on at response time.
690
+ */
691
+ type Status = "active" | "archived";
692
+ type CatalogType = "standard" | "custom";
693
+ type Interval = "day" | "week" | "month" | "year";
694
+ type CollectionMode = "automatic" | "manual";
695
+ type TransactionStatus = "draft" | "ready" | "billed" | "paid" | "completed" | "canceled" | "past_due";
696
+ type TransactionOrigin = "api" | "subscription_charge" | "subscription_payment_method_change" | "subscription_recurring" | "subscription_update" | "web";
697
+ type SubscriptionStatus = "active" | "canceled" | "past_due" | "paused" | "trialing";
698
+ type CustomData = Record<string, unknown> | null;
699
+ type TimePeriod = {
700
+ interval: Interval;
701
+ frequency: number;
702
+ };
703
+ type TrialPeriod = TimePeriod & {
704
+ requires_payment_method?: boolean;
705
+ };
706
+ type Money = {
707
+ amount: string;
708
+ currency_code: string;
709
+ };
710
+ type Period = {
711
+ starts_at: string;
712
+ ends_at: string;
713
+ };
714
+ type BillingDetails = {
715
+ enable_checkout: boolean;
716
+ purchase_order_number: string | null;
717
+ additional_information: string | null;
718
+ payment_terms: TimePeriod;
719
+ };
720
+ type CustomerRecord = {
721
+ id: string;
722
+ name: string | null;
723
+ email: string;
724
+ marketing_consent: boolean;
725
+ status: Status;
726
+ custom_data: CustomData;
727
+ locale: string;
728
+ created_at: string;
729
+ updated_at: string;
730
+ import_meta: null;
731
+ };
732
+ type AddressRecord = {
733
+ id: string;
734
+ customer_id: string;
735
+ description: string | null;
736
+ first_line: string | null;
737
+ second_line: string | null;
738
+ city: string | null;
739
+ postal_code: string | null;
740
+ region: string | null;
741
+ country_code: string;
742
+ custom_data: CustomData;
743
+ status: Status;
744
+ created_at: string;
745
+ updated_at: string;
746
+ import_meta: null;
747
+ };
748
+ type BusinessRecord = {
749
+ id: string;
750
+ customer_id: string;
751
+ name: string;
752
+ company_number: string | null;
753
+ tax_identifier: string | null;
754
+ status: Status;
755
+ contacts: {
756
+ name: string | null;
757
+ email: string;
758
+ }[] | null;
759
+ created_at: string;
760
+ updated_at: string;
761
+ custom_data: CustomData;
762
+ import_meta: null;
763
+ };
764
+ type ProductRecord = {
765
+ id: string;
766
+ name: string;
767
+ type: CatalogType;
768
+ description: string | null;
769
+ tax_category: string;
770
+ image_url: string | null;
771
+ custom_data: CustomData;
772
+ status: Status;
773
+ created_at: string;
774
+ updated_at: string;
775
+ import_meta: null;
776
+ };
777
+ type PriceRecord = {
778
+ id: string;
779
+ product_id: string;
780
+ description: string;
781
+ type: CatalogType;
782
+ name: string | null;
783
+ billing_cycle: TimePeriod | null;
784
+ trial_period: TrialPeriod | null;
785
+ tax_mode: string;
786
+ unit_price: Money;
787
+ unit_price_overrides: {
788
+ country_codes: string[];
789
+ unit_price: Money;
790
+ }[];
791
+ quantity: {
792
+ minimum: number;
793
+ maximum: number;
794
+ };
795
+ status: Status;
796
+ created_at: string;
797
+ updated_at: string;
798
+ custom_data: CustomData;
799
+ import_meta: null;
800
+ };
801
+ type Totals = {
802
+ subtotal: string;
803
+ discount: string;
804
+ tax: string;
805
+ total: string;
806
+ };
807
+ type TransactionTotals = Totals & {
808
+ credit: string;
809
+ credit_to_balance: string;
810
+ balance: string;
811
+ grand_total: string;
812
+ grand_total_tax: string;
813
+ fee: string | null;
814
+ earnings: string | null;
815
+ currency_code: string;
816
+ };
817
+ type LineItem = {
818
+ id: string;
819
+ price_id: string;
820
+ quantity: number;
821
+ proration: null;
822
+ tax_rate: string;
823
+ unit_totals: Totals;
824
+ totals: Totals;
825
+ product: ProductRecord;
826
+ };
827
+ type PreviewLineItem = Omit<LineItem, "id">;
828
+ type TransactionDetails = {
829
+ tax_rates_used: {
830
+ tax_rate: string;
831
+ totals: Totals;
832
+ }[];
833
+ totals: TransactionTotals;
834
+ adjusted_totals: {
835
+ subtotal: string;
836
+ tax: string;
837
+ total: string;
838
+ grand_total: string;
839
+ grand_total_tax: string;
840
+ fee: string | null;
841
+ earnings: string | null;
842
+ currency_code: string;
843
+ retained_fee: string;
844
+ };
845
+ payout_totals: null;
846
+ adjusted_payout_totals: null;
847
+ line_items: LineItem[];
848
+ };
849
+ type PreviewDetails = {
850
+ tax_rates_used: {
851
+ tax_rate: string;
852
+ totals: Totals;
853
+ }[];
854
+ totals: TransactionTotals;
855
+ line_items: PreviewLineItem[];
856
+ };
857
+ type PaymentAttempt = {
858
+ payment_attempt_id: string;
859
+ stored_payment_method_id: string;
860
+ payment_method_id: string | null;
861
+ amount: string;
862
+ status: "captured" | "error";
863
+ error_code: string | null;
864
+ method_details: {
865
+ type: "card";
866
+ card: {
867
+ type: string;
868
+ last4: string;
869
+ expiry_month: number;
870
+ expiry_year: number;
871
+ cardholder_name: string;
872
+ };
873
+ paypal: null;
874
+ south_korea_local_card: null;
875
+ underlying_details: null;
876
+ } | null;
877
+ created_at: string;
878
+ captured_at: string | null;
879
+ };
880
+ type TransactionItem = {
881
+ price_id: string;
882
+ /** The price as it was when the transaction was written, as Paddle embeds it. */
883
+ price: PriceRecord;
884
+ quantity: number;
885
+ proration: null;
886
+ };
887
+ type TransactionRecord = {
888
+ id: string;
889
+ status: TransactionStatus;
890
+ customer_id: string | null;
891
+ address_id: string | null;
892
+ business_id: string | null;
893
+ custom_data: CustomData;
894
+ currency_code: string;
895
+ origin: TransactionOrigin;
896
+ subscription_id: string | null;
897
+ invoice_id: string | null;
898
+ invoice_number: string | null;
899
+ collection_mode: CollectionMode;
900
+ discount_id: null;
901
+ billing_details: BillingDetails | null;
902
+ billing_period: Period | null;
903
+ items: TransactionItem[];
904
+ details: TransactionDetails;
905
+ payments: PaymentAttempt[];
906
+ checkout: {
907
+ url: string | null;
908
+ } | null;
909
+ created_at: string;
910
+ updated_at: string;
911
+ billed_at: string | null;
912
+ revised_at: null;
913
+ };
914
+ type SubscriptionItem = {
915
+ status: "active" | "inactive" | "trialing";
916
+ quantity: number;
917
+ recurring: boolean;
918
+ created_at: string;
919
+ updated_at: string;
920
+ previously_billed_at: string | null;
921
+ next_billed_at: string | null;
922
+ trial_dates: Period | null;
923
+ price: PriceRecord;
924
+ product: ProductRecord;
925
+ };
926
+ type ScheduledChange = {
927
+ action: "cancel" | "pause" | "resume";
928
+ effective_at: string;
929
+ resume_at: string | null;
930
+ };
931
+ type SubscriptionRecord = {
932
+ id: string;
933
+ status: SubscriptionStatus;
934
+ customer_id: string;
935
+ address_id: string;
936
+ business_id: string | null;
937
+ currency_code: string;
938
+ created_at: string;
939
+ updated_at: string;
940
+ started_at: string | null;
941
+ first_billed_at: string | null;
942
+ next_billed_at: string | null;
943
+ paused_at: string | null;
944
+ canceled_at: string | null;
945
+ discount: null;
946
+ collection_mode: CollectionMode;
947
+ billing_details: BillingDetails | null;
948
+ current_billing_period: Period | null;
949
+ billing_cycle: TimePeriod;
950
+ scheduled_change: ScheduledChange | null;
951
+ management_urls: {
952
+ update_payment_method: string | null;
953
+ cancel: string;
954
+ };
955
+ items: SubscriptionItem[];
956
+ custom_data: CustomData;
957
+ import_meta: null;
958
+ };
959
+ /** One-time charges queued with `effective_from: next_billing_period`, billed at the next renewal. */
960
+ type PendingCharge = {
961
+ price_id: string;
962
+ quantity: number;
963
+ };
964
+ type EventRecord = {
965
+ event_id: string;
966
+ event_type: string;
967
+ occurred_at: string;
968
+ notification_id: null;
969
+ data: Record<string, unknown>;
970
+ };
971
+
972
+ /** Paddle id prefixes, per entity. */
973
+ declare const ID_PREFIX: {
974
+ readonly customer: "ctm";
975
+ readonly address: "add";
976
+ readonly business: "biz";
977
+ readonly product: "pro";
978
+ readonly price: "pri";
979
+ readonly transaction: "txn";
980
+ readonly subscription: "sub";
981
+ readonly event: "evt";
982
+ readonly notification: "ntf";
983
+ readonly line_item: "txnitm";
984
+ readonly payment_attempt: "payatt";
985
+ readonly payment_method: "paymtd";
986
+ readonly invoice: "inv";
987
+ };
988
+ type IdKind = keyof typeof ID_PREFIX;
989
+ declare class PaddleState {
990
+ readonly customers: Collection<CustomerRecord>;
991
+ readonly addresses: Collection<AddressRecord>;
992
+ readonly businesses: Collection<BusinessRecord>;
993
+ readonly products: Collection<ProductRecord>;
994
+ readonly prices: Collection<PriceRecord>;
995
+ readonly transactions: Collection<TransactionRecord>;
996
+ readonly subscriptions: Collection<SubscriptionRecord>;
997
+ /** Queued one-time charges per subscription id. */
998
+ readonly pendingCharges: Collection<PendingCharge[]>;
999
+ readonly events: Collection<EventRecord>;
1000
+ private readonly ids;
1001
+ constructor(sqlite: SqliteClient, namespace: string);
1002
+ /**
1003
+ * A Paddle-shaped id: `<prefix>_01` followed by 24 lower-case alphanumerics (Paddle ids are a
1004
+ * prefix plus a 26-character ULID), deterministic for a given history.
1005
+ */
1006
+ nextId(kind: IdKind): string;
1007
+ /** An opaque token (auth tokens, signing material), deterministic for a given history. */
1008
+ nextToken(prefix: string, length: number): string;
1009
+ }
1010
+
1011
+ type FieldError = {
1012
+ field: string;
1013
+ message: string;
1014
+ };
1015
+ declare class PaddleError extends Error {
1016
+ readonly status: number;
1017
+ readonly code: string;
1018
+ readonly detail: string;
1019
+ readonly errors?: FieldError[] | undefined;
1020
+ constructor(status: number, code: string, detail: string, errors?: FieldError[] | undefined);
1021
+ toResponse(requestId: string): Response;
1022
+ }
1023
+
1024
+ /**
1025
+ * The slice of OpenAPI 3.1 (and JSON Schema 2020-12) Mockingbird understands.
1026
+ * Unknown keys (including `x-*` extensions) are preserved on every object.
1027
+ */
1028
+ type JsonPrimitive = string | number | boolean | null;
1029
+ type JsonValue = JsonPrimitive | JsonValue[] | {
1030
+ [key: string]: JsonValue;
1031
+ };
1032
+ type ReferenceObject = {
1033
+ $ref: string;
1034
+ description?: string;
1035
+ summary?: string;
1036
+ };
1037
+ type SchemaType = "string" | "number" | "integer" | "boolean" | "object" | "array" | "null";
1038
+ type SchemaObject = {
1039
+ $ref?: string;
1040
+ type?: SchemaType | SchemaType[];
1041
+ title?: string;
1042
+ description?: string;
1043
+ format?: string;
1044
+ enum?: JsonValue[];
1045
+ const?: JsonValue;
1046
+ default?: JsonValue;
1047
+ example?: JsonValue;
1048
+ examples?: JsonValue[];
1049
+ nullable?: boolean;
1050
+ deprecated?: boolean;
1051
+ readOnly?: boolean;
1052
+ writeOnly?: boolean;
1053
+ minimum?: number;
1054
+ maximum?: number;
1055
+ exclusiveMinimum?: number;
1056
+ exclusiveMaximum?: number;
1057
+ multipleOf?: number;
1058
+ minLength?: number;
1059
+ maxLength?: number;
1060
+ pattern?: string;
1061
+ minItems?: number;
1062
+ maxItems?: number;
1063
+ uniqueItems?: boolean;
1064
+ items?: SchemaObject;
1065
+ prefixItems?: SchemaObject[];
1066
+ minProperties?: number;
1067
+ maxProperties?: number;
1068
+ required?: string[];
1069
+ properties?: Record<string, SchemaObject>;
1070
+ additionalProperties?: boolean | SchemaObject;
1071
+ propertyNames?: SchemaObject;
1072
+ oneOf?: SchemaObject[];
1073
+ anyOf?: SchemaObject[];
1074
+ allOf?: SchemaObject[];
1075
+ not?: SchemaObject;
1076
+ discriminator?: {
1077
+ propertyName: string;
1078
+ mapping?: Record<string, string>;
1079
+ };
1080
+ [extension: `x-${string}`]: unknown;
1081
+ };
1082
+ type ParameterLocation = "path" | "query" | "header" | "cookie";
1083
+ type ParameterObject = {
1084
+ name: string;
1085
+ in: ParameterLocation;
1086
+ description?: string;
1087
+ required?: boolean;
1088
+ deprecated?: boolean;
1089
+ style?: string;
1090
+ explode?: boolean;
1091
+ schema?: SchemaObject;
1092
+ content?: Record<string, MediaTypeObject>;
1093
+ example?: JsonValue;
1094
+ [extension: `x-${string}`]: unknown;
1095
+ };
1096
+ type MediaTypeObject = {
1097
+ schema?: SchemaObject;
1098
+ example?: JsonValue;
1099
+ examples?: Record<string, unknown>;
1100
+ encoding?: Record<string, unknown>;
1101
+ [extension: `x-${string}`]: unknown;
1102
+ };
1103
+ type RequestBodyObject = {
1104
+ description?: string;
1105
+ required?: boolean;
1106
+ content: Record<string, MediaTypeObject>;
1107
+ [extension: `x-${string}`]: unknown;
1108
+ };
1109
+ type HeaderObject = {
1110
+ description?: string;
1111
+ required?: boolean;
1112
+ schema?: SchemaObject;
1113
+ [extension: `x-${string}`]: unknown;
1114
+ };
1115
+ type ResponseObject = {
1116
+ description: string;
1117
+ headers?: Record<string, HeaderObject | ReferenceObject>;
1118
+ content?: Record<string, MediaTypeObject>;
1119
+ [extension: `x-${string}`]: unknown;
1120
+ };
1121
+ type ResponsesObject = Record<string, ResponseObject | ReferenceObject>;
1122
+ type SecurityRequirementObject = Record<string, string[]>;
1123
+ type OperationObject = {
1124
+ operationId?: string;
1125
+ summary?: string;
1126
+ description?: string;
1127
+ tags?: string[];
1128
+ deprecated?: boolean;
1129
+ parameters?: Array<ParameterObject | ReferenceObject>;
1130
+ requestBody?: RequestBodyObject | ReferenceObject;
1131
+ responses: ResponsesObject;
1132
+ security?: SecurityRequirementObject[];
1133
+ [extension: `x-${string}`]: unknown;
1134
+ };
1135
+ declare const HTTP_METHODS: readonly ["get", "put", "post", "delete", "options", "head", "patch", "trace"];
1136
+ type HttpMethod = (typeof HTTP_METHODS)[number];
1137
+ type PathItemObject = {
1138
+ summary?: string;
1139
+ description?: string;
1140
+ parameters?: Array<ParameterObject | ReferenceObject>;
1141
+ [extension: `x-${string}`]: unknown;
1142
+ } & Partial<Record<HttpMethod, OperationObject>>;
1143
+ type SecuritySchemeObject = {
1144
+ type: "apiKey" | "http" | "oauth2" | "openIdConnect" | "mutualTLS";
1145
+ description?: string;
1146
+ name?: string;
1147
+ in?: ParameterLocation;
1148
+ scheme?: string;
1149
+ bearerFormat?: string;
1150
+ flows?: Record<string, unknown>;
1151
+ openIdConnectUrl?: string;
1152
+ [extension: `x-${string}`]: unknown;
1153
+ };
1154
+ type ComponentsObject = {
1155
+ schemas?: Record<string, SchemaObject>;
1156
+ responses?: Record<string, ResponseObject>;
1157
+ parameters?: Record<string, ParameterObject>;
1158
+ requestBodies?: Record<string, RequestBodyObject>;
1159
+ headers?: Record<string, HeaderObject>;
1160
+ securitySchemes?: Record<string, SecuritySchemeObject>;
1161
+ [extension: `x-${string}`]: unknown;
1162
+ };
1163
+ type ServerObject = {
1164
+ url: string;
1165
+ description?: string;
1166
+ variables?: Record<string, unknown>;
1167
+ [extension: `x-${string}`]: unknown;
1168
+ };
1169
+ type InfoObject = {
1170
+ title: string;
1171
+ version: string;
1172
+ description?: string;
1173
+ [extension: `x-${string}`]: unknown;
1174
+ };
1175
+ type OpenAPIDocument = {
1176
+ openapi: string;
1177
+ info: InfoObject;
1178
+ servers?: ServerObject[];
1179
+ paths: Record<string, PathItemObject>;
1180
+ components?: ComponentsObject;
1181
+ security?: SecurityRequirementObject[];
1182
+ tags?: Array<{
1183
+ name: string;
1184
+ description?: string;
1185
+ }>;
1186
+ [extension: `x-${string}`]: unknown;
1187
+ };
1188
+
1189
+ declare const document: OpenAPIDocument;
1190
+ type OperationId = "ListCustomers" | "CreateCustomer" | "GetCustomer" | "UpdateCustomer" | "GetCustomerCreditBalances" | "CreateCustomerAuthToken" | "ListAddresses" | "CreateAddress" | "GetAddress" | "UpdateAddress" | "ListBusinesses" | "CreateBusiness" | "GetBusiness" | "UpdateBusiness" | "ListProducts" | "CreateProduct" | "GetProduct" | "UpdateProduct" | "ListPrices" | "CreatePrice" | "GetPrice" | "UpdatePrice" | "ListTransactions" | "CreateTransaction" | "PreviewTransaction" | "GetTransaction" | "UpdateTransaction" | "GetTransactionInvoice" | "ReviseTransaction" | "ListSubscriptions" | "GetSubscription" | "UpdateSubscription" | "PreviewSubscriptionUpdate" | "ActivateSubscription" | "PauseSubscription" | "ResumeSubscription" | "CancelSubscription" | "CreateSubscriptionCharge" | "PreviewSubscriptionCharge" | "GetSubscriptionPaymentMethodChangeTransaction" | "ListEvents" | "ListNotificationSettings" | "CreateNotificationSetting" | "ListDiscounts" | "CreateDiscount" | "ListAdjustments" | "CreateAdjustment" | "CreateCustomerPortalSession";
1191
+ type SupportedOperationId = "ListCustomers" | "CreateCustomer" | "GetCustomer" | "UpdateCustomer" | "GetCustomerCreditBalances" | "CreateCustomerAuthToken" | "ListAddresses" | "CreateAddress" | "GetAddress" | "UpdateAddress" | "ListBusinesses" | "CreateBusiness" | "GetBusiness" | "UpdateBusiness" | "ListProducts" | "CreateProduct" | "GetProduct" | "UpdateProduct" | "ListPrices" | "CreatePrice" | "GetPrice" | "UpdatePrice" | "ListTransactions" | "CreateTransaction" | "PreviewTransaction" | "GetTransaction" | "UpdateTransaction" | "GetTransactionInvoice" | "ListSubscriptions" | "GetSubscription" | "UpdateSubscription" | "ActivateSubscription" | "PauseSubscription" | "ResumeSubscription" | "CancelSubscription" | "CreateSubscriptionCharge" | "ListEvents";
1192
+ declare const operationIds: readonly ["ListCustomers", "CreateCustomer", "GetCustomer", "UpdateCustomer", "GetCustomerCreditBalances", "CreateCustomerAuthToken", "ListAddresses", "CreateAddress", "GetAddress", "UpdateAddress", "ListBusinesses", "CreateBusiness", "GetBusiness", "UpdateBusiness", "ListProducts", "CreateProduct", "GetProduct", "UpdateProduct", "ListPrices", "CreatePrice", "GetPrice", "UpdatePrice", "ListTransactions", "CreateTransaction", "PreviewTransaction", "GetTransaction", "UpdateTransaction", "GetTransactionInvoice", "ReviseTransaction", "ListSubscriptions", "GetSubscription", "UpdateSubscription", "PreviewSubscriptionUpdate", "ActivateSubscription", "PauseSubscription", "ResumeSubscription", "CancelSubscription", "CreateSubscriptionCharge", "PreviewSubscriptionCharge", "GetSubscriptionPaymentMethodChangeTransaction", "ListEvents", "ListNotificationSettings", "CreateNotificationSetting", "ListDiscounts", "CreateDiscount", "ListAdjustments", "CreateAdjustment", "CreateCustomerPortalSession"];
1193
+ declare const supportedOperationIds: readonly ["ListCustomers", "CreateCustomer", "GetCustomer", "UpdateCustomer", "GetCustomerCreditBalances", "CreateCustomerAuthToken", "ListAddresses", "CreateAddress", "GetAddress", "UpdateAddress", "ListBusinesses", "CreateBusiness", "GetBusiness", "UpdateBusiness", "ListProducts", "CreateProduct", "GetProduct", "UpdateProduct", "ListPrices", "CreatePrice", "GetPrice", "UpdatePrice", "ListTransactions", "CreateTransaction", "PreviewTransaction", "GetTransaction", "UpdateTransaction", "GetTransactionInvoice", "ListSubscriptions", "GetSubscription", "UpdateSubscription", "ActivateSubscription", "PauseSubscription", "ResumeSubscription", "CancelSubscription", "CreateSubscriptionCharge", "ListEvents"];
1194
+
1195
+ /**
1196
+ * Every named Paddle misbehaviour a consumer branches on, switched on with
1197
+ * `POST /__admin/faults {"preset": "<name>"}` (add `count` to limit it). The SDK turns each
1198
+ * error body into an `ApiError` (with `retryAfter` from the header).
1199
+ */
1200
+ declare const PADDLE_PRESETS: Record<string, FaultPreset>;
1201
+ /**
1202
+ * Paddle's `Paddle-Signature: ts=<unix seconds>;h1=<hex HMAC-SHA256(secret, "<ts>:<body>")>`,
1203
+ * over the exact bytes sent. The secret is the notification destination's `pdl_ntfset_…` key.
1204
+ */
1205
+ declare const paddleSigner: () => WebhookSigner;
1206
+ type PaddleRuntimeOptions = {
1207
+ sqlite?: SqliteClient;
1208
+ clock?: Clock;
1209
+ seed?: number | string;
1210
+ adminKey?: string;
1211
+ onLog?: (entry: RequestLog) => void;
1212
+ /**
1213
+ * Where notifications go, signed with the endpoint's `pdl_ntfset_…` secret in
1214
+ * `Paddle-Signature`. `events` limits the event types (default all).
1215
+ */
1216
+ webhooks?: Omit<WebhookEndpoint, "id"> & {
1217
+ retryDelaysMs?: readonly number[];
1218
+ fetch?: (request: Request) => Promise<Response>;
1219
+ };
1220
+ /** The default payment link `checkout.url` is built from (`<link>?_ptxn=<id>`). */
1221
+ paymentLink?: string;
1222
+ /** Seed every namespace with the fixture account on first use (`seedFixtures`). */
1223
+ fixtures?: boolean;
1224
+ };
1225
+ type PaddleRuntime = ServiceRuntime<PaddleAPI> & {
1226
+ readonly webhooks: WebhookHub;
1227
+ };
1228
+ /**
1229
+ * The Paddle mock with Mockingbird's full service contract: `/health`, `/__admin/*`,
1230
+ * namespaces by header, by `/ns/<name>` path prefix, or by API key
1231
+ * (`PUT /__admin/credentials {"credentials": {"<PADDLE_API_KEY>": "<namespace>"}}`),
1232
+ * clock control, fault presets, `Paddle-Signature` webhooks, a request journal, and the
1233
+ * admin routes that stand in for the hosted checkout and the billing engine.
1234
+ */
1235
+ declare const createRuntime: (options?: PaddleRuntimeOptions) => PaddleRuntime;
1236
+
1237
+ declare const PADDLE_NAMESPACE = "paddle";
1238
+ /** How long a customer auth token (`POST /customers/{id}/auth-token`) is advertised to live. */
1239
+ declare const AUTH_TOKEN_TTL_MS: number;
1240
+ type Json = Record<string, unknown>;
1241
+ /** What `POST /__admin/checkout` accepts: a hosted-checkout completion, in one call. */
1242
+ type CheckoutInput = {
1243
+ /** An existing customer, or an email to find or create one by. */
1244
+ customer_id?: string;
1245
+ email?: string;
1246
+ name?: string;
1247
+ /** An existing address of the customer, or a country to create one for. Default `US`. */
1248
+ address_id?: string;
1249
+ country_code?: string;
1250
+ postal_code?: string;
1251
+ business_id?: string;
1252
+ items: {
1253
+ price_id: string;
1254
+ quantity?: number;
1255
+ }[];
1256
+ custom_data?: CustomData;
1257
+ currency_code?: string;
1258
+ };
1259
+ type CardInput = {
1260
+ type?: string;
1261
+ last4?: string;
1262
+ expiry_month?: number;
1263
+ expiry_year?: number;
1264
+ cardholder_name?: string;
1265
+ };
1266
+ type PaddleAPIOptions = APIOptions & {
1267
+ /** The public namespace name, for `/ns/<name>` in `meta.pagination.next` and management URLs. */
1268
+ publicNamespace?: string;
1269
+ /**
1270
+ * The default payment link: a `ready` automatic-collection transaction gets
1271
+ * `checkout.url = <paymentLink>?_ptxn=<id>`. Default none (`checkout.url` is `null`).
1272
+ */
1273
+ paymentLink?: string;
1274
+ /** Called with every event the account produces (the body a webhook would carry). */
1275
+ onEvent?: (event: EventRecord) => void;
1276
+ /**
1277
+ * Seed the fixture account (`seedFixtures`) on construction when the namespace is empty, and
1278
+ * again after every `reset()`. Fixture events are recorded (`GET /events`) but not passed to
1279
+ * `onEvent`: they are the account's pre-existing state, not new activity.
1280
+ */
1281
+ fixtures?: boolean;
1282
+ };
1283
+ /**
1284
+ * Stateful mock of the Paddle Billing API. Catalog and customer records behave as Paddle's do;
1285
+ * transactions carry computed totals (no tax, no discounts); subscriptions are created when a
1286
+ * transaction with recurring prices is paid, which the admin routes simulate (`payTransaction`,
1287
+ * `checkout`), and renewed or failed on demand (`renewSubscription`, `failPayment`).
1288
+ */
1289
+ declare class PaddleAPI implements FetchAPI$1 {
1290
+ readonly app: Hono;
1291
+ readonly sqlite: SqliteClient;
1292
+ readonly state: PaddleState;
1293
+ private readonly service;
1294
+ private readonly now;
1295
+ private readonly publicNamespace;
1296
+ private readonly paymentLink;
1297
+ private readonly onEvent;
1298
+ private readonly fixtures;
1299
+ private readonly requestIds;
1300
+ private requestCounter;
1301
+ /** While seeding fixtures: events are recorded but not published. */
1302
+ private seeding;
1303
+ constructor(options?: PaddleAPIOptions);
1304
+ fetch(request: Request): Promise<Response>;
1305
+ /** Empty the namespace; with `fixtures`, the fixture account is seeded again. */
1306
+ reset(): Promise<void>;
1307
+ /** Every event the account produced, oldest first. */
1308
+ events(): EventRecord[];
1309
+ private requestId;
1310
+ private iso;
1311
+ private prefix;
1312
+ private emit;
1313
+ /** The JSON body, validated against the contract; an absent body is `{}` when allowed. */
1314
+ private body;
1315
+ private includes;
1316
+ private statusFilter;
1317
+ private page;
1318
+ private ok;
1319
+ private mustCustomer;
1320
+ createCustomer(input: {
1321
+ email: string;
1322
+ name?: string | null;
1323
+ custom_data?: CustomData;
1324
+ locale?: string;
1325
+ }): CustomerRecord;
1326
+ private listCustomers;
1327
+ private createCustomerOp;
1328
+ private getCustomer;
1329
+ private updateCustomer;
1330
+ private creditBalances;
1331
+ private authToken;
1332
+ createAddress(customerId: string, input: Partial<Omit<AddressRecord, "id" | "customer_id" | "status" | "created_at" | "updated_at" | "import_meta">> & {
1333
+ country_code: string;
1334
+ }): AddressRecord;
1335
+ private mustAddress;
1336
+ private listAddresses;
1337
+ private createAddressOp;
1338
+ private getAddress;
1339
+ private updateAddress;
1340
+ createBusiness(customerId: string, input: {
1341
+ name: string;
1342
+ company_number?: string | null;
1343
+ tax_identifier?: string | null;
1344
+ contacts?: {
1345
+ name?: string | null;
1346
+ email: string;
1347
+ }[] | null;
1348
+ custom_data?: CustomData;
1349
+ }): BusinessRecord;
1350
+ private mustBusiness;
1351
+ private listBusinesses;
1352
+ private contacts;
1353
+ private createBusinessOp;
1354
+ private getBusiness;
1355
+ private updateBusiness;
1356
+ /** The product record for an input, not yet stored (`commitProduct` stores and announces it). */
1357
+ private buildProduct;
1358
+ private commitProduct;
1359
+ createProduct(input: Parameters<PaddleAPI["buildProduct"]>[0]): ProductRecord;
1360
+ private mustProduct;
1361
+ private renderProduct;
1362
+ private listProducts;
1363
+ private createProductOp;
1364
+ private getProduct;
1365
+ private updateProduct;
1366
+ private timePeriod;
1367
+ /**
1368
+ * The validated price record for an input, not yet stored (`commitPrice` stores and announces
1369
+ * it). `product` is a product that is itself not stored yet (a non-catalog item's product).
1370
+ */
1371
+ private buildPrice;
1372
+ private commitPrice;
1373
+ createPrice(input: Parameters<PaddleAPI["buildPrice"]>[0]): PriceRecord;
1374
+ private mustPrice;
1375
+ private renderPrice;
1376
+ private listPrices;
1377
+ private priceInput;
1378
+ private createPriceOp;
1379
+ private getPrice;
1380
+ private updatePrice;
1381
+ /**
1382
+ * The priced items of a request: catalog prices by `price_id`, or non-catalog `price`
1383
+ * objects, whose `type: custom` price (and product) are only stored once the whole request
1384
+ * has validated: the caller runs `catalog` after its last check (a preview never does).
1385
+ */
1386
+ private resolveItems;
1387
+ private resolveParties;
1388
+ private billingDetails;
1389
+ private period;
1390
+ private countryOf;
1391
+ private lineItems;
1392
+ private checkoutFor;
1393
+ /** Build (or rebuild) a transaction from request fields; shared by create and update. */
1394
+ private transactionFrom;
1395
+ /** Sequential and unique: one more than the invoices issued so far (`MOCK-01001` first). */
1396
+ private nextInvoiceNumber;
1397
+ private transactionEvents;
1398
+ /** `POST /transactions` as a method: what the hosted checkout and the admin routes call. */
1399
+ createTransaction(input: Json, origin?: TransactionOrigin): TransactionRecord;
1400
+ private mustTransaction;
1401
+ private renderTransaction;
1402
+ private dateFilter;
1403
+ private listTransactions;
1404
+ private createTransactionOp;
1405
+ private previewTransaction;
1406
+ private getTransaction;
1407
+ private updateTransaction;
1408
+ private transactionInvoice;
1409
+ private captured;
1410
+ private subscriptionItems;
1411
+ /**
1412
+ * Complete a `ready`, `billed` or `past_due` transaction as if the customer paid: a captured
1413
+ * card payment, `completed` status, an invoice, and, for recurring items, the subscription
1414
+ * (`trialing` when a price has a trial, else `active`) or the recovery of a past-due one.
1415
+ */
1416
+ payTransaction(id: string, card?: CardInput): {
1417
+ transaction: TransactionRecord;
1418
+ subscription: SubscriptionRecord | null;
1419
+ };
1420
+ private mustSubscription;
1421
+ private saveSubscription;
1422
+ private recurringPriced;
1423
+ private applyScheduledChange;
1424
+ /** A completed transaction for a subscription's billing period (renewal, charge, update). */
1425
+ private billSubscription;
1426
+ /**
1427
+ * Run the next billing date: a scheduled cancel or pause takes effect instead, a paused
1428
+ * subscription with a scheduled resume resumes (billed from its `effective_at`); otherwise a
1429
+ * `subscription_recurring` transaction is created (plus any queued one-time charges), the
1430
+ * billing period advances, and a trial ends into `active`.
1431
+ */
1432
+ renewSubscription(id: string): {
1433
+ subscription: SubscriptionRecord;
1434
+ transaction: TransactionRecord | null;
1435
+ };
1436
+ /** The next renewal's payment is declined: a `past_due` transaction and subscription. */
1437
+ failPayment(id: string): {
1438
+ subscription: SubscriptionRecord;
1439
+ transaction: TransactionRecord;
1440
+ };
1441
+ /** A hosted-checkout completion in one call: find or create the customer and address, then pay. */
1442
+ checkout(input: CheckoutInput): {
1443
+ transaction: TransactionRecord;
1444
+ subscription: SubscriptionRecord | null;
1445
+ };
1446
+ private nextTransactionPreview;
1447
+ private renderSubscription;
1448
+ private listSubscriptions;
1449
+ private subscriptionResponse;
1450
+ private getSubscription;
1451
+ private notCanceled;
1452
+ private updateSubscription;
1453
+ private activateSubscription;
1454
+ private pauseSubscription;
1455
+ private resumeSubscription;
1456
+ /**
1457
+ * A paused subscription becomes active for `period`; a period starting now (or one a
1458
+ * scheduled resume set) is billed at once, a continued one is not.
1459
+ */
1460
+ private resumeInto;
1461
+ private cancelSubscription;
1462
+ private chargeSubscription;
1463
+ private listEvents;
1464
+ /**
1465
+ * A small account to start from: a customer with an address and a business, a "Pro" product
1466
+ * with monthly, yearly and one-time prices, a "Starter" price with a 14-day trial, an active
1467
+ * monthly subscription, a trialing one, an unpaid `ready` transaction and a manual invoice.
1468
+ * Deterministic: two instances seeded at the same clock hold identical ids.
1469
+ */
1470
+ seedFixtures(): {
1471
+ customer: CustomerRecord;
1472
+ address: AddressRecord;
1473
+ business: BusinessRecord;
1474
+ product: ProductRecord;
1475
+ prices: {
1476
+ monthly: PriceRecord;
1477
+ yearly: PriceRecord;
1478
+ setup: PriceRecord;
1479
+ starter: PriceRecord;
1480
+ };
1481
+ subscriptions: {
1482
+ active: SubscriptionRecord;
1483
+ trialing: SubscriptionRecord;
1484
+ };
1485
+ transactions: {
1486
+ ready: TransactionRecord;
1487
+ invoice: TransactionRecord;
1488
+ };
1489
+ };
1490
+ private seedAccount;
1491
+ }
1492
+
1493
+ export { AUTH_TOKEN_TTL_MS, ID_PREFIX, PADDLE_NAMESPACE, PADDLE_PRESETS, PaddleAPI, PaddleError, PaddleState, createRuntime, document, operationIds, paddleSigner, supportedOperationIds };
1494
+ export type { AddressRecord, BillingDetails, BusinessRecord, CardInput, CheckoutInput, CollectionMode, CustomData, CustomerRecord, EventRecord, FetchAPI$1 as FetchAPI, LineItem, OperationId, PaddleAPIOptions, PaddleRuntime, PaddleRuntimeOptions, PaymentAttempt, Period, PreviewDetails, PriceRecord, ProductRecord, ScheduledChange, SqliteClient, SubscriptionItem, SubscriptionRecord, SubscriptionStatus, SupportedOperationId, TimePeriod, TransactionItem, TransactionOrigin, TransactionRecord, TransactionStatus, TrialPeriod };