@crvouga/mockingbird-service-s3 4.2.0 → 4.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ export { B as BucketRecord, M as MultipartPart, a as MultipartUpload, O as ObjectVersion, S as S3API, b as S3APIOptions, c as S3Notification, O as S3Object, d as S3Runtime, e as S3RuntimeOptions, f as S3SeedObject, g as S3_MAX_UPLOAD_BYTES, h as S3_NAMESPACE, i as S3_PRESETS, j as createRuntime } from './types-HwqI9Aq6.js';
2
+
1
3
  /**
2
4
  * The slice of OpenAPI 3.1 (and JSON Schema 2020-12) Mockingbird understands.
3
5
  * Unknown keys (including `x-*` extensions) are preserved on every object.
@@ -167,1373 +169,6 @@ declare const document: OpenAPIDocument;
167
169
  declare const operationIds: readonly ["ListObjectsV2", "CreateBucket", "BucketPost", "HeadBucket", "GetObject", "PutObject", "MultipartPost", "DeleteObject", "HeadObject"];
168
170
  declare const supportedOperationIds: readonly ["ListObjectsV2", "CreateBucket", "BucketPost", "HeadBucket", "GetObject", "PutObject", "MultipartPost", "DeleteObject", "HeadObject"];
169
171
 
170
- type MountedAPI = FetchAPI & {
171
- readonly prefix: string;
172
- GET: FetchHandler;
173
- POST: FetchHandler;
174
- PUT: FetchHandler;
175
- PATCH: FetchHandler;
176
- DELETE: FetchHandler;
177
- HEAD: FetchHandler;
178
- OPTIONS: FetchHandler;
179
- };
180
-
181
- /** A stable identifier for a point in a {@link Timeline}. */
182
- type CheckpointId = string;
183
- /** An immutable node in a timeline's checkpoint DAG. */
184
- type Checkpoint<T> = Readonly<{
185
- id: CheckpointId;
186
- branch: string;
187
- parent: CheckpointId | null;
188
- /** Logical time supplied by the timeline's injected clock. */
189
- at: number;
190
- value: T;
191
- }>;
192
- type TimelineOptions = {
193
- /** Logical clock used to stamp checkpoints. Defaults to a deterministic counter. */
194
- now?: () => number;
195
- /** Maximum retained checkpoints. Branch heads are never collected. Default 1,000. */
196
- maxCheckpoints?: number;
197
- /** Customize deterministic checkpoint IDs. */
198
- id?: (sequence: number) => CheckpointId;
199
- };
200
- type CommitOptions = {
201
- branch?: string;
202
- /** Parent checkpoint. Defaults to the selected branch's current head. */
203
- parent?: CheckpointId | null;
204
- };
205
- type ForkOptions = {
206
- /** Checkpoint to fork from. Defaults to the main branch's head. */
207
- from?: CheckpointId;
208
- };
209
- /**
210
- * Small, storage-agnostic checkpoint DAG shared by service runtimes. Its values may be immutable
211
- * records, namespace images, or copy-on-write SQL engine snapshots.
212
- *
213
- * Values are retained by reference. Engines can therefore use persistent/COW snapshots while
214
- * simpler services can use immutable values. IDs and GC order are deterministic, and all IO
215
- * (the logical clock) is injected.
216
- */
217
- declare class Timeline<T> {
218
- readonly maxCheckpoints: number;
219
- private readonly now;
220
- private readonly makeId;
221
- private readonly nodes;
222
- private readonly heads;
223
- /** Unreferenced nodes in the exact order they became collectible. */
224
- private readonly evictable;
225
- /** Branch heads plus explicit retainers. Absent means zero. */
226
- private readonly references;
227
- private readonly explicitPins;
228
- private sequence;
229
- constructor(options?: TimelineOptions);
230
- /** Capture a new immutable value and move `branch` to it. */
231
- commit(value: T, options?: CommitOptions): Checkpoint<T>;
232
- /** Create a branch pointer without copying its checkpoint value. */
233
- fork(branch: string, options?: ForkOptions): Checkpoint<T> | undefined;
234
- /** Move a branch pointer to an existing checkpoint. */
235
- checkout(branch: string, id: CheckpointId): Checkpoint<T>;
236
- get(id: CheckpointId): Checkpoint<T>;
237
- head(branch?: string): Checkpoint<T> | undefined;
238
- hasBranch(branch: string): boolean;
239
- branches(): Readonly<Record<string, CheckpointId>>;
240
- checkpoints(): readonly Checkpoint<T>[];
241
- /** Number of retained checkpoints without allocating an array. */
242
- get size(): number;
243
- /** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
244
- retain(id: CheckpointId): Checkpoint<T>;
245
- /** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
246
- release(id: CheckpointId): boolean;
247
- deleteBranch(branch: string): boolean;
248
- /**
249
- * Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
250
- * commits never scan pinned nodes or the retained history. Parents are metadata rather than a
251
- * storage dependency, so a retained node remains usable after pruning.
252
- */
253
- gc(max?: number): CheckpointId[];
254
- private collect;
255
- private moveHead;
256
- private addReference;
257
- private removeReference;
258
- private assertBranch;
259
- }
260
-
261
- /**
262
- * Anything that can answer a Fetch `Request` with a `Response`.
263
- *
264
- * Every Mockingbird service implements this, and every runtime adapter consumes it.
265
- * It is the only contract shared across the whole graph.
266
- */
267
- interface FetchAPI {
268
- fetch(request: Request): Promise<Response>;
269
- }
270
- /** A bare function form of {@link FetchAPI}, compatible with `Bun.serve`, workerd, and Deno. */
271
- type FetchHandler = (request: Request) => Promise<Response>;
272
-
273
- /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
274
- type SqliteValue$1 = null | number | bigint | string | Uint8Array | boolean;
275
- /** Mutation counters returned by {@link SqliteStatement.run}. */
276
- type SqliteRunResult$1 = {
277
- changes: number;
278
- lastInsertRowid: number | bigint;
279
- };
280
- /**
281
- * Prepared statement bound to a {@link SqliteClient}.
282
- *
283
- * Pass bind values as rest arguments on each call (no sticky `bind()`).
284
- */
285
- interface SqliteStatement$1 {
286
- run(...params: SqliteValue$1[]): SqliteRunResult$1;
287
- all<T = Record<string, unknown>>(...params: SqliteValue$1[]): T[];
288
- get<T = Record<string, unknown>>(...params: SqliteValue$1[]): T | undefined;
289
- }
290
- /**
291
- * Sync SQLite client port owned by Mockingbird.
292
- *
293
- * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
294
- * `bun:sqlite` instances all work when they expose this surface.
295
- */
296
- interface SqliteClient$1 {
297
- exec(sql: string): void;
298
- prepare(sql: string): SqliteStatement$1;
299
- transaction<T>(fn: () => T): T;
300
- }
301
-
302
- /** Every stored record carries a monotonically increasing sequence for stable ordering. */
303
- type Stored<T> = {
304
- seq: number;
305
- value: T;
306
- };
307
- type ListRecordsOptions<T> = {
308
- /** Keep only records passing the predicate. */
309
- where?: (value: T, seq: number) => boolean;
310
- /** Sort order; default newest first. */
311
- order?: "newest" | "oldest";
312
- };
313
- /**
314
- * A SQLite-backed table of JSON records addressed by id. Ordering is by insertion
315
- * sequence, never by id lexicographic order, so list semantics stay stable.
316
- */
317
- declare class Collection<T> {
318
- private readonly sqlite;
319
- /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
320
- readonly namespace: string;
321
- /** Table name inside the namespace. Stable across resets of the rows themselves. */
322
- readonly collectionName: string;
323
- private readonly statements;
324
- private prepare;
325
- constructor(sqlite: SqliteClient$1,
326
- /** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
327
- namespace: string,
328
- /** Table name inside the namespace. Stable across resets of the rows themselves. */
329
- collectionName: string);
330
- private bumpCollectionSeq;
331
- nextSequence(): number;
332
- get(id: string): T | undefined;
333
- has(id: string): boolean;
334
- /** Insert a new record, assigning it the next sequence number. */
335
- insert(id: string, value: T): Stored<T>;
336
- /** Replace an existing record's value, keeping its position. */
337
- update(id: string, value: T): Stored<T> | undefined;
338
- delete(id: string): boolean;
339
- /** How many records the collection holds, without reading them. */
340
- count(): number;
341
- list(options?: ListRecordsOptions<T>): Array<Stored<T> & {
342
- id: string;
343
- }>;
344
- }
345
-
346
- /**
347
- * What names an id base: a non-negative safe integer (or its decimal string) or `"boot"`,
348
- * which derives the base from the wall clock when the runtime is created.
349
- */
350
- type IdBase = number | string;
351
- /**
352
- * Sequential id source persisted in SQLite. Ids are deterministic for a given
353
- * sequence history (`cus_` + 14 opaque chars), so reproductions stay stable.
354
- * A runtime's `idBase` is mixed in, so a different base reissues none of another's ids.
355
- */
356
- declare class IdSequence {
357
- private readonly sqlite;
358
- private readonly namespace;
359
- private readonly salt;
360
- constructor(sqlite: SqliteClient$1, namespace: string, salt?: string);
361
- next(prefix: string, length?: number): string;
362
- }
363
-
364
- /** Options every provider constructor accepts. */
365
- type APIOptions = {
366
- /** Sync SQLite client. Defaults to `@crvouga/mockingbird-service-sqlite`. */
367
- sqlite?: SqliteClient$1;
368
- /** Clock used for `created`-style fields. Default `Date.now`. */
369
- now?: () => number;
370
- /**
371
- * Storage namespace for this instance's records. Instances sharing one SQLite
372
- * client stay isolated when their namespaces differ. Defaults to the service name.
373
- */
374
- namespace?: string;
375
- };
376
-
377
- /**
378
- * The single source of time for a service.
379
- *
380
- * Every timestamp a mock writes reads from here, so a suite moves time instead of
381
- * sleeping: appointment windows, result delays and expiries become reachable in
382
- * milliseconds. A frozen clock also makes timestamps reproducible from a seed.
383
- */
384
- type ClockState = {
385
- /** Current epoch milliseconds. */
386
- now: number;
387
- /** True while time does not advance on its own. */
388
- frozen: boolean;
389
- /** Milliseconds a running clock adds to its underlying source. `0` while frozen. */
390
- offsetMs: number;
391
- };
392
- type Clock = {
393
- now(): number;
394
- /** Pin the clock to an exact instant, keeping it frozen if it already was. */
395
- set(epochMs: number): void;
396
- /** Move the clock forward, or back with a negative delta. */
397
- advance(deltaMs: number): void;
398
- /** Stop time at the current instant. */
399
- freeze(): void;
400
- /** Resume from the current instant. */
401
- unfreeze(): void;
402
- /** Drop back to the underlying source, live. */
403
- reset(): void;
404
- state(): ClockState;
405
- };
406
-
407
- /**
408
- * Seeded pseudo-random numbers, so anything a mock invents — ids, jitter, which
409
- * request a percentage fault hits — is reproducible from a seed.
410
- *
411
- * mulberry32: small, fast, and stable across runtimes, which matters more here
412
- * than statistical quality.
413
- */
414
- type Rng = {
415
- /** Next value in `[0, 1)`. */
416
- next(): number;
417
- /** Next integer in `[min, max]`. */
418
- int(min: number, max: number): number;
419
- /** Restart the stream from its seed. */
420
- reset(): void;
421
- /** Serializable engine state used by deterministic checkpoints. */
422
- state(): number;
423
- /** Restore a state previously returned by {@link state}. */
424
- setState(state: number): void;
425
- /** Restart the stream from a new seed. `reset` then returns to this seed. */
426
- reseed(seed: number | string): void;
427
- /** The seed the stream currently starts from. */
428
- readonly seed: number;
429
- };
430
-
431
- /**
432
- * A deliberate failure injected in front of an operation.
433
- *
434
- * This is how a suite reaches the vendor's failure modes without the vendor: the
435
- * quota error that only appears when a shared sandbox is full, the 429 that only
436
- * appears under load, the 5xx that proves a retry path works.
437
- *
438
- * A rule has three parts. What it **matches** (`operationId`, `method`, `path`, …), **when**
439
- * it fires among the matching requests (`after`, `every`, `count`, `rate`, `from`, `until`),
440
- * and what it **does** (`status`, `delay`, `timeout`, `drop`, `truncate`, `effect`).
441
- */
442
- type FaultRule = {
443
- /** Stable id, so a suite can retire exactly the rule it added. Unique within a namespace. */
444
- id: string;
445
- /** Fault only this operation. Omit to match every operation. */
446
- operationId?: string;
447
- /** Fault only this HTTP method, case-insensitive. Omit to match every method. */
448
- method?: string;
449
- /** Fault only this exact path. */
450
- path?: string;
451
- /** Fault only paths starting with this prefix. Omit to match every path. */
452
- pathPrefix?: string;
453
- /** Fault only paths matching this regular expression (JavaScript syntax, unanchored). */
454
- pathPattern?: string;
455
- /** Fault only requests carrying these headers. `"*"` matches any value. */
456
- requestHeaders?: Record<string, string>;
457
- /** Fault only requests carrying these query parameters. `"*"` matches any value. */
458
- query?: Record<string, string>;
459
- /**
460
- * Fault only requests whose JSON body carries these fields. Each key is a dotted path into
461
- * the parsed body (`"patient_details.email"`; a number steps into an array, `"items.0.sku"`)
462
- * and each value is what the field must equal: a string, number, boolean or `null`, compared
463
- * strictly (`3` is not `"3"`). `"*"` matches any value that is present. A request whose body
464
- * is missing, is not JSON, or is not a JSON object never matches. Not `body`, which is the
465
- * response a rule injects.
466
- */
467
- requestBody?: Record<string, RequestBodyValue>;
468
- /**
469
- * Fault only this namespace. Omit (or `"*"`) to fault every namespace — which is what
470
- * an in-process caller usually wants, and what a parallel worker usually does not:
471
- * rules added through `POST /__admin/faults` default to the calling namespace.
472
- */
473
- namespace?: string;
474
- /** Let this many matching requests through first. */
475
- after?: number;
476
- /** Then fault only every nth matching request: `3` faults the 3rd, 6th, 9th. */
477
- every?: number;
478
- /** Retire the rule after this many faults. Omit to keep it until removed. */
479
- count?: number;
480
- /** Fault this fraction of the remaining requests, `0`–`1`, drawn from the seed. Default `1`. */
481
- rate?: number;
482
- /**
483
- * Fault only from this instant on the namespace clock. A duration (`"5m"`) counts from the
484
- * clock when the rule was added. Listed as epoch ms.
485
- */
486
- from?: Instant | Duration;
487
- /** Stop faulting at this instant on the namespace clock. A duration counts from when added. */
488
- until?: Instant | Duration;
489
- /**
490
- * Status of the injected response. Omit for a rule that only delays, times out, drops,
491
- * truncates, or switches on an `effect`: the request then still reaches the service.
492
- */
493
- status?: number;
494
- /** Response body, serialized as JSON. A string is sent as-is. */
495
- body?: unknown;
496
- /** Response headers. */
497
- headers?: Record<string, string>;
498
- /** Hold the response back this long. Listed as `delayMs`. */
499
- delay?: Duration;
500
- /** `delay`, in milliseconds. */
501
- delayMs?: number;
502
- /** Alias of `delayMs`. */
503
- latencyMs?: number;
504
- /** Extra seeded delay in `[0, jitter]`. Listed as `jitterMs`. */
505
- jitter?: Duration;
506
- jitterMs?: number;
507
- /**
508
- * Never answer: hold the request this long, then drop the connection. Listed as
509
- * `timeoutMs`. With virtual time the wait is spent on the mock clock.
510
- */
511
- timeout?: Duration;
512
- timeoutMs?: number;
513
- /**
514
- * Drop the connection instead of answering: an in-process `fetch` rejects with a
515
- * `TypeError`, and a served mock destroys the socket. Models "unknown outcome" failures.
516
- */
517
- drop?: boolean;
518
- /**
519
- * Cut the response body off after this many bytes: the status and headers arrive, then
520
- * the connection dies mid-body.
521
- */
522
- truncate?: number;
523
- /**
524
- * A named service behaviour to switch on for the matching request instead of (or
525
- * before) a canned response, e.g. `created_but_500` or `numeric_tracking_id`. Services
526
- * read it with `faultEffects(request)`.
527
- */
528
- effect?: string;
529
- /** Parameters for `effect`. */
530
- params?: Record<string, unknown>;
531
- /** The preset this rule was expanded from, if any. */
532
- fromPreset?: string;
533
- };
534
- /** What a field of the request body must equal in {@link FaultRule.requestBody}. */
535
- type RequestBodyValue = string | number | boolean | null;
536
- /** A fault that fired for one request. */
537
- type FaultHit = {
538
- id: string;
539
- /** The injected response; absent when the rule only delays, drops, or sets an effect. */
540
- response?: Response;
541
- drop?: boolean;
542
- /** Set with `drop` when the rule held the request for its `timeout` first. */
543
- timeout?: boolean;
544
- /** Bytes of response body to let through before the connection dies. */
545
- truncate?: number;
546
- effect?: {
547
- name: string;
548
- params: Record<string, unknown>;
549
- };
550
- };
551
- /**
552
- * A named, documented fault a suite switches on by name
553
- * (`POST /__admin/faults {"preset": "rate_limited"}`): one or more rules, and optionally a
554
- * webhook delivery fault.
555
- */
556
- type FaultPreset = {
557
- description: string;
558
- rules?: Omit<FaultRule, "id">[];
559
- webhook?: {
560
- mode: "duplicate" | "reorder" | "drop";
561
- count?: number;
562
- };
563
- };
564
- /** What a request looks like to the fault matcher. */
565
- type FaultCandidate = {
566
- operationId: string | undefined;
567
- method: string;
568
- path: string;
569
- namespace: string;
570
- /** Request headers and query, for rules that match on them. */
571
- headers?: Headers;
572
- query?: URLSearchParams;
573
- /**
574
- * The request body parsed as JSON, read only when a rule matches on `requestBody`. Resolve
575
- * `undefined` for a body that is missing or not JSON. It must leave the request readable.
576
- */
577
- readJson?: () => Promise<unknown>;
578
- /** The namespace clock, for `from` / `until`. Rules with a window are skipped without it. */
579
- now?: number;
580
- /** How to spend a delay for this request. Default: the registry's own sleep. */
581
- wait?: (ms: number) => Promise<void>;
582
- };
583
- /** A stored rule and how often it was consulted. */
584
- type FaultListing = FaultRule & {
585
- /** Faults left before the rule retires. `null` when it has no `count`. */
586
- remaining: number | null;
587
- /** Times the rule faulted a request. */
588
- hits: number;
589
- /** Requests that matched the rule, faulted or not. */
590
- seen: number;
591
- };
592
- /** A namespace's own rules, with their counters, in the order they are tried. */
593
- type FaultSnapshot = {
594
- /**
595
- * `position` is how many `"*"` rules are tried before the rule, which is what its place
596
- * in the order means to a request and holds in any process.
597
- */
598
- rules: (FaultListing & {
599
- position?: number;
600
- })[];
601
- /** How many `fault_<n>` ids the namespace has handed out. */
602
- nextId?: number;
603
- };
604
- type FaultRegistry = {
605
- snapshot(namespace: string): FaultSnapshot;
606
- /** Add a rule, or replace the rule with the same id in the same namespace. */
607
- add(rule: FaultRule): FaultRule;
608
- /** The next unused `fault_<n>` id in `namespace`. */
609
- nextId(namespace: string): string;
610
- /** Every rule, or the rules a namespace's requests can hit: its own and the global ones. */
611
- list(namespace?: string): FaultListing[];
612
- get(id: string, namespace?: string): FaultListing | undefined;
613
- /** Remove a rule by id: from `namespace` (its own, then a global one), or wherever it is. */
614
- remove(id: string, namespace?: string): boolean;
615
- /** Remove every rule, or one namespace's own rules. */
616
- clear(namespace?: string): void;
617
- /** Replace a namespace's own rules with a snapshot's, wherever the snapshot was taken. */
618
- restore(namespace: string, state: FaultSnapshot): void;
619
- /**
620
- * Every fault this request should get, in rule order, stopping at the first that answers
621
- * or drops (effect-only and delay-only rules let later rules match too). Consumes one of
622
- * each matching rule's remaining uses.
623
- */
624
- take(candidate: FaultCandidate): Promise<FaultHit[]>;
625
- /**
626
- * Fire these rules at one request without storing them: no matching, no schedule, in order,
627
- * stopping at the first that answers or drops. Jitter draws from the namespace's stream.
628
- */
629
- fire(rules: readonly FaultRule[], candidate: FaultCandidate): Promise<FaultHit[]>;
630
- };
631
-
632
- /**
633
- * The admin controls every mock shares, as one document.
634
- *
635
- * The same shape is accepted in three places, and means the same thing in each:
636
- *
637
- * - at boot: `createRuntime({ adminControls })`, `serve --admin-controls`,
638
- * `MOCKINGBIRD_ADMIN_CONTROLS`
639
- * - over HTTP: `PUT /__admin/controls`
640
- * - per request: the `x-mockingbird-*` headers in {@link CONTROL_HEADERS}
641
- *
642
- * Every control is deterministic: given the same seed, clock and requests, a mock answers
643
- * the same bytes. Nothing here reads the wall clock or `Math.random`.
644
- */
645
- /** Milliseconds, or a string like `"250ms"`, `"2s"`, `"15m"`, `"1h"`, `"3d"`. */
646
- type Duration = number | string;
647
- /** Epoch milliseconds, or an ISO-8601 string. */
648
- type Instant = number | string;
649
- type ClockControls = {
650
- /** Move the clock to this instant. */
651
- now?: Instant;
652
- /** Stop time. A frozen clock moves only when told to, so timestamps replay exactly. */
653
- frozen?: boolean;
654
- /**
655
- * Step the clock forward by this much before every vendor request. With a frozen clock
656
- * each request still gets its own, reproducible timestamp.
657
- */
658
- autoAdvance?: Duration;
659
- };
660
- /** How long a response takes: a fixed delay plus seeded jitter in `[0, jitter]`. */
661
- type LatencyRuleInput = {
662
- delay?: Duration;
663
- jitter?: Duration;
664
- };
665
- type LatencyControls = LatencyRuleInput & {
666
- /** Per-operation overrides, keyed by operationId. A bare duration is its `delay`. */
667
- operations?: Record<string, Duration | LatencyRuleInput>;
668
- };
669
- /** A fault to add: a rule (the id is assigned when omitted), or a named preset with overrides. */
670
- type FaultInput = (Omit<FaultRule, "id"> & {
671
- id?: string;
672
- }) | ({
673
- preset: string;
674
- } & Partial<FaultRule>);
675
- /** Identifies a {@link SnapshotDocument}. */
676
- declare const SNAPSHOT_FORMAT = "mockingbird.snapshot/v1";
677
- /**
678
- * A namespace, as portable JSON: what `GET /__admin/snapshots/:id` returns and what
679
- * `PUT /__admin/snapshots/:id` and the boot `snapshot` control accept. Only `format` and
680
- * `records` are required, so a hand-written seed file is a valid snapshot.
681
- */
682
- type SnapshotDocument = {
683
- format: typeof SNAPSHOT_FORMAT;
684
- /** The service that wrote it. A snapshot is rejected by any other service. */
685
- service?: string;
686
- /**
687
- * Stored rows. `seq` orders a collection; omitted, rows keep their listed order. `raw` is
688
- * the stored text of a row that is not a plain record, and replaces `value` when present.
689
- */
690
- records: {
691
- collection: string;
692
- id: string;
693
- seq?: number;
694
- value?: unknown;
695
- raw?: string;
696
- }[];
697
- /** Id counters, so the next generated id continues where the snapshot left off. */
698
- sequences?: {
699
- name: string;
700
- kind: string;
701
- value: number;
702
- }[];
703
- clock?: {
704
- now: number;
705
- frozen: boolean;
706
- autoAdvanceMs?: number;
707
- };
708
- seed?: number | string;
709
- /** Positions of the seeded random streams. */
710
- rng?: {
711
- state: number;
712
- faults?: number;
713
- latency?: number;
714
- };
715
- faults?: unknown;
716
- latency?: unknown;
717
- virtualTime?: boolean;
718
- /** Quiescent webhook endpoints, delivery history and fault state. Contains private configuration. */
719
- webhooks?: unknown;
720
- };
721
- /** Controls for one namespace. */
722
- type NamespaceControls = {
723
- /** Seeds every random choice: fault rates, jitter, and whatever the service invents. */
724
- seed?: number | string;
725
- clock?: ClockControls;
726
- /**
727
- * Spend injected waits (latency, fault delays, timeouts) on the mock clock instead of the
728
- * wall clock: the request returns at once, the clock has moved, and the journal records
729
- * the wait exactly. Default `false`: waits are real, so a client's own timeout can fire.
730
- */
731
- virtualTime?: boolean;
732
- /** Baseline response time for every vendor request. A bare duration is its `delay`. */
733
- latency?: Duration | LatencyControls;
734
- faults?: readonly FaultInput[];
735
- /** Start from this state instead of the service's own seed data. */
736
- snapshot?: SnapshotDocument;
737
- };
738
- /** {@link NamespaceControls} for every namespace, with per-namespace overrides. */
739
- type MockControls = NamespaceControls & {
740
- /** Vendor credential → namespace, for SDKs that cannot send a namespace header. */
741
- credentials?: Record<string, string>;
742
- /** Overrides for named namespaces. A key given here replaces the shared value. */
743
- namespaces?: Record<string, NamespaceControls>;
744
- };
745
- /** A latency rule in milliseconds. */
746
- type LatencyRule = {
747
- delayMs: number;
748
- jitterMs: number;
749
- };
750
- /** Baseline latency for a namespace, normalized. */
751
- type LatencyState = LatencyRule & {
752
- operations: Record<string, LatencyRule>;
753
- };
754
- /** What {@link controlHeaders} turns into request headers. */
755
- type ControlHeaderInput = {
756
- namespace?: string;
757
- adminKey?: string;
758
- branch?: string;
759
- at?: string;
760
- reset?: boolean;
761
- restore?: string;
762
- seed?: number | string;
763
- time?: Instant | Date;
764
- advance?: Duration;
765
- virtualTime?: boolean;
766
- delay?: Duration;
767
- timeout?: Duration;
768
- /** A status, `"drop"`, a preset name, or a fault rule. */
769
- fault?: number | string | Record<string, unknown>;
770
- snapshot?: string;
771
- };
772
-
773
- /**
774
- * One problem with a request body, at a dotted path (`patient.address.city`, `items.0.sku`).
775
- * `kind` is `media_type` when the body is present but its media type is not one the operation
776
- * accepts (a `415` on most vendors), `syntax` when it could not be decoded, `required` when
777
- * the operation needs a body and none arrived, and `schema` for a contract violation.
778
- */
779
- type BodyIssue = {
780
- path: string;
781
- message: string;
782
- kind?: "media_type" | "syntax" | "required" | "schema";
783
- };
784
-
785
- /**
786
- * What the mock received from a request it rejected, so a 4xx can be attributed after the
787
- * fact (an empty body, a missing `content-type`, a schema violation) without logging the body.
788
- */
789
- type RejectedRequest = {
790
- /** The raw `content-type` header, or `null` when the request sent none. */
791
- contentType: string | null;
792
- /** Bytes of body received from `content-length` (`0` for none), or `null` when the client sent no length (a streamed / chunked body). */
793
- bodyBytes: number | null;
794
- /** The raw `transfer-encoding` header (`chunked`), or `null`. */
795
- transferEncoding: string | null;
796
- };
797
- /** One handled request, as the structured log sees it. */
798
- type RequestLog = {
799
- service: string;
800
- namespace: string;
801
- operationId: string | undefined;
802
- method: string;
803
- path: string;
804
- status: number;
805
- durationMs: number;
806
- /** True when the path matched no operation in the contract. */
807
- unmatched: boolean;
808
- /** Set when a fault rule produced the response. */
809
- faultId?: string;
810
- /** Milliseconds of injected wait: latency, fault delays and timeouts. Absent when none. */
811
- delayMs?: number;
812
- /** Resource ids the handler touched (`userId`, `orderId`, …), when the service reports them. */
813
- ids?: Record<string, string>;
814
- /** Set when the service created a resource the request referred to but that did not exist. */
815
- adopted?: boolean;
816
- /** Explicit durable acceptance, independent of response delivery. */
817
- accepted?: boolean;
818
- /** Checkpoint captured at explicit acceptance. */
819
- checkpoint?: string;
820
- /** Set on a rejection (status ≥ 400) the mock produced itself, never on a scripted fault. */
821
- request?: RejectedRequest;
822
- /** The validation issues behind a rejection, when the service found any. */
823
- issues?: BodyIssue[];
824
- };
825
- type MetricsReport = {
826
- requests: number;
827
- /** Counts keyed `<operationId> <status>`. */
828
- byOperation: Record<string, number>;
829
- /**
830
- * Paths that matched no operation, most frequent first.
831
- *
832
- * This is the early-warning signal: a consumer calling something the mock does
833
- * not implement shows up here as a count, before it fails a suite as a 404.
834
- */
835
- unmatched: {
836
- method: string;
837
- path: string;
838
- count: number;
839
- }[];
840
- faults: number;
841
- totalDurationMs: number;
842
- };
843
- type Metrics = {
844
- record(entry: RequestLog): void;
845
- report(namespace?: string): MetricsReport;
846
- reset(namespace?: string): void;
847
- };
848
-
849
- /** One journal entry: a request log stamped with when (on the mock clock) it was handled. */
850
- type JournalEntry = RequestLog & {
851
- at: string;
852
- };
853
- type JournalQuery = {
854
- /** Only this namespace. Omit for every namespace, oldest first across all of them. */
855
- namespace?: string;
856
- operationId?: string;
857
- /** Only this HTTP method, case-insensitive. */
858
- method?: string;
859
- /** Only this exact path. */
860
- path?: string;
861
- /** Only requests this fault rule answered or shaped. */
862
- faultId?: string;
863
- status?: number;
864
- /** Only entries at or after this instant (epoch ms). */
865
- since?: number;
866
- /** At most this many, the most recent kept. */
867
- limit?: number;
868
- };
869
- type Journal = {
870
- readonly size: number;
871
- record(entry: JournalEntry): void;
872
- list(query?: JournalQuery): JournalEntry[];
873
- /** Forget one namespace's entries, or every namespace's. */
874
- clear(namespace?: string): void;
875
- };
876
-
877
- /**
878
- * Baseline response time, per namespace: how long every vendor request takes before any
879
- * fault is considered. Jitter draws from a stream the caller owns, one per namespace and
880
- * separate from the fault stream, so adding latency never shifts which requests a `rate`
881
- * fault hits.
882
- */
883
- type LatencyRegistry = {
884
- get(namespace: string): LatencyState;
885
- set(namespace: string, state: LatencyState): LatencyState;
886
- /** Remove one namespace's latency, or every namespace's. */
887
- clear(namespace?: string): void;
888
- /** Milliseconds this request waits. Draws jitter, so call it once per request. */
889
- take(namespace: string, operationId: string | undefined): number;
890
- };
891
-
892
- /** Clock state as the admin API reports it. */
893
- type ControlClock = ClockState & {
894
- /** `now`, as ISO-8601. */
895
- iso: string;
896
- /** Milliseconds the clock steps before every vendor request. */
897
- autoAdvanceMs: number;
898
- };
899
- /** One namespace's controls: the body of `GET /__admin/controls`. */
900
- type ControlState = {
901
- namespace: string;
902
- seed: number | string;
903
- clock: ControlClock;
904
- virtualTime: boolean;
905
- latency: LatencyState;
906
- faults: FaultListing[];
907
- };
908
-
909
- /** What `GET /__admin/snapshots` lists for each snapshot. */
910
- type SnapshotInfo = {
911
- id: string;
912
- namespace: string;
913
- /** Stored rows in the snapshot. */
914
- records: number;
915
- /** The namespace clock when it was taken, epoch ms. */
916
- at: number;
917
- /** Whether `GET /snapshots/:id` can return it as a {@link SnapshotDocument}. */
918
- portable: boolean;
919
- };
920
-
921
- /** Credential → namespace mapping behind `PUT /__admin/credentials`. */
922
- type CredentialRegistry = {
923
- set(credential: string, namespace: string): void;
924
- get(credential: string): string | undefined;
925
- remove(credential: string): boolean;
926
- clear(): void;
927
- entries(): {
928
- credential: string;
929
- namespace: string;
930
- }[];
931
- };
932
-
933
- type OwnedTransport = (request: Request, namespace: string, send: typeof fetch) => Promise<Response>;
934
-
935
- /**
936
- * A point-in-time copy of everything a service namespace holds.
937
- *
938
- * All service state lives in the two core tables keyed by namespace, so a snapshot
939
- * is generic: any service gets per-test rollback without knowing its own schema.
940
- * Restoring is much cheaper than rebuilding a namespace from a corpus.
941
- */
942
- type NamespaceSnapshot = {
943
- namespace: string;
944
- records: {
945
- collection: string;
946
- id: string;
947
- seq: number;
948
- value: string;
949
- }[];
950
- sequences: {
951
- name: string;
952
- kind: string;
953
- value: number;
954
- }[];
955
- };
956
-
957
- declare const STATE_FIELD_KINDS: readonly ["string", "number", "boolean", "null", "object", "array", "unknown"];
958
- type StateFieldKind = (typeof STATE_FIELD_KINDS)[number];
959
- /** JSON-safe annotations a bespoke admin UI may read. The default UI shows them as text. */
960
- type StateMeta = Readonly<Record<string, string | number | boolean | null>>;
961
- type StateField = {
962
- name: string;
963
- kind: StateFieldKind;
964
- optional: boolean;
965
- description?: string;
966
- /** One level of nested object fields. */
967
- fields?: StateField[];
968
- meta?: StateMeta;
969
- };
970
- type StateCollectionView = {
971
- name: string;
972
- label: string;
973
- description?: string;
974
- count: number;
975
- /** `mixed` when a declaration and stored rows both contribute fields. */
976
- source: "declared" | "inferred" | "mixed";
977
- fields: StateField[];
978
- meta?: StateMeta;
979
- };
980
- /** The shape of one namespace, for an admin UI that has never seen the service before. */
981
- type StateView = {
982
- namespace: string;
983
- storageNamespace: string;
984
- collections: StateCollectionView[];
985
- };
986
-
987
- type WebhookEndpoint = {
988
- /** Stable id; generated when omitted. */
989
- id?: string;
990
- url: string;
991
- secret?: string;
992
- /** Event types to deliver; omit or include `"*"` for every type. */
993
- events?: string[];
994
- /** Deliver only messages whose tags include all of these (e.g. `{ account: "mso" }`). */
995
- tags?: Record<string, string>;
996
- /** The public URL the receiver verifies signatures against (Twilio), when it differs. */
997
- signUrl?: string;
998
- headers?: Record<string, string>;
999
- };
1000
- type WebhookMessage = {
1001
- id: string;
1002
- namespace: string;
1003
- type: string;
1004
- body: string;
1005
- contentType: string;
1006
- tags: Record<string, string>;
1007
- headers?: Record<string, string>;
1008
- /** Wall-clock ISO-8601 time of publication. */
1009
- publishedAt: string;
1010
- };
1011
- type WebhookAttempt = {
1012
- attempt: number;
1013
- at: string;
1014
- status: number | null;
1015
- error: string | null;
1016
- durationMs: number;
1017
- /** Exact receiver response body, when one was returned. */
1018
- responseBody?: string | null;
1019
- };
1020
- type WebhookDelivery = {
1021
- id: string;
1022
- messageId: string;
1023
- namespace: string;
1024
- type: string;
1025
- endpointId: string;
1026
- url: string;
1027
- state: "pending" | "delivered" | "failed" | "dropped";
1028
- attempts: WebhookAttempt[];
1029
- };
1030
- /** A delivery-level fault: what happens to the next `count` messages in a namespace. */
1031
- type WebhookFault = {
1032
- mode: "duplicate" | "reorder" | "drop";
1033
- /** Messages affected; default 1. */
1034
- count?: number;
1035
- };
1036
- type PublishInput = {
1037
- namespace: string;
1038
- type: string;
1039
- /** Exact body; objects are JSON-encoded. */
1040
- body: string | Record<string, unknown> | unknown[];
1041
- /** Default `application/json`, or form-encoded when `form` is given. */
1042
- contentType?: string;
1043
- /** Form parameters, when the vendor posts `application/x-www-form-urlencoded`. */
1044
- form?: Record<string, string>;
1045
- tags?: Record<string, string>;
1046
- /** Message-specific delivery headers, captured as part of durable message state. */
1047
- headers?: Record<string, string>;
1048
- /** Message id; generated when omitted. */
1049
- id?: string;
1050
- };
1051
- type WebhookHub = {
1052
- observeDeliveries(listener: (event: {
1053
- namespace: string;
1054
- state: string;
1055
- deliveryId: string;
1056
- }) => void): () => void;
1057
- setTransportPolicy(policy: OwnedTransport): void;
1058
- pending(namespace: string): number;
1059
- snapshot(namespace: string): unknown;
1060
- exportSnapshot(handle: unknown): unknown;
1061
- importSnapshot(namespace: string, document: unknown): unknown;
1062
- restore(namespace: string, snapshot: unknown): void;
1063
- publish(input: PublishInput): WebhookMessage;
1064
- /** Replace a namespace's own endpoints (`PUT /__admin/webhook-endpoints`). */
1065
- setEndpoints(namespace: string, endpoints: WebhookEndpoint[]): WebhookEndpoint[];
1066
- /** The endpoints a namespace delivers to: its own, plus the global ones. */
1067
- endpoints(namespace: string): WebhookEndpoint[];
1068
- messages(namespace?: string): WebhookMessage[];
1069
- deliveries(namespace?: string): WebhookDelivery[];
1070
- replay(deliveryId: string): Promise<WebhookDelivery | undefined>;
1071
- /** Run every pending retry (and release held reordered messages) now, and every retry those attempts schedule, until nothing is pending. */
1072
- flush(): Promise<void>;
1073
- /** Resolve once nothing is in flight. */
1074
- idle(namespace?: string): Promise<void>;
1075
- fault(namespace: string, fault: WebhookFault): void;
1076
- clear(namespace?: string): void;
1077
- };
1078
-
1079
- /** What the runtime needs from a service: a Fetch handler it can reset. */
1080
- type ServiceInstance = FetchAPI & {
1081
- reset(): Promise<void>;
1082
- };
1083
- type ServiceTimelineState = Readonly<{
1084
- snapshot: NamespaceSnapshot;
1085
- /** `pinned`: the namespace's clock was frozen itself, not just following a frozen base. */
1086
- clock: Readonly<ClockState & {
1087
- pinned?: boolean;
1088
- }>;
1089
- rngState: number;
1090
- }>;
1091
- type ServiceCheckpoint = Checkpoint<ServiceTimelineState>;
1092
- type ServiceRuntime<T extends ServiceInstance> = FetchAPI & {
1093
- /** Stop package-owned lifecycle timers when a supervisor closes the runtime. */
1094
- stop?(): void;
1095
- readonly name: string;
1096
- /** Same-origin Fetch handler and App Router method exports, sharing this runtime. */
1097
- mount(prefix: string): MountedAPI;
1098
- readonly sqlite: SqliteClient$1;
1099
- readonly clock: Clock;
1100
- /**
1101
- * Change the id base ({@link RuntimeOptions.idBase}) for ids generated from now on, and
1102
- * return the number it resolved to. Set it before the first request so a boot's ids stay
1103
- * one run.
1104
- */
1105
- setIdBase(base: IdBase): number;
1106
- readonly faults: FaultRegistry;
1107
- /** Baseline response time per namespace. */
1108
- readonly latency: LatencyRegistry;
1109
- readonly metrics: Metrics;
1110
- readonly journal: Journal;
1111
- readonly rng: Rng;
1112
- readonly credentials: CredentialRegistry;
1113
- /** The webhook hub, when the service has outbound webhooks. */
1114
- readonly webhooks: WebhookHub | undefined;
1115
- /**
1116
- * A namespace's clock. Each follows the base clock, {@link ServiceRuntime.clock}, with an
1117
- * offset and a freeze of its own, so moving one never moves another.
1118
- */
1119
- namespaceClock(namespace?: string): Clock;
1120
- namespaceOf(request: Request): string;
1121
- /** Opaque in-process checkpoint including records, controls and webhook history. */
1122
- fleetSnapshot(namespace: string): object;
1123
- fleetRestore(snapshot: unknown, namespace: string): void;
1124
- fleetExport(snapshot: unknown): SnapshotDocument;
1125
- fleetImport(namespace: string, document: unknown): object;
1126
- /** Expand a named preset into fault rules (and webhook faults) for `namespace`. */
1127
- applyPreset(name: string, namespace?: string, overrides?: Partial<FaultRule>): FaultRule[];
1128
- /** The instance behind `namespace` (the default one when omitted), created on first use. */
1129
- instance(namespace?: string): T;
1130
- /** Public names of every namespace created so far. */
1131
- namespaces(): string[];
1132
- /** Return one namespace to its boot state, or every namespace with `"*"`. */
1133
- reset(namespace?: string): Promise<void>;
1134
- /** Reset a namespace and forget it, releasing everything it held. */
1135
- dropNamespace(namespace: string): Promise<void>;
1136
- /** A namespace's controls: seed, clock, virtual time, latency, faults and snapshots. */
1137
- controls(namespace?: string): ControlState & {
1138
- snapshots: SnapshotInfo[];
1139
- };
1140
- /** Apply a control document to a namespace. A given key replaces that control. */
1141
- configure(controls: NamespaceControls, namespace?: string): ControlState & {
1142
- snapshots: SnapshotInfo[];
1143
- };
1144
- /** Named snapshots of a namespace: records, clock, random streams, faults and latency. */
1145
- readonly snapshots: {
1146
- /** Capture the namespace now. Reusing a name replaces that snapshot. */
1147
- create(options?: {
1148
- name?: string;
1149
- namespace?: string;
1150
- }): SnapshotInfo;
1151
- list(namespace?: string): SnapshotInfo[];
1152
- /** The snapshot as portable JSON, to commit beside a suite or boot another mock from. */
1153
- export(id: string, namespace?: string): SnapshotDocument;
1154
- /** Store a document as a snapshot without restoring it. */
1155
- import(document: SnapshotDocument, options?: {
1156
- name?: string;
1157
- namespace?: string;
1158
- }): SnapshotInfo;
1159
- restore(id: string, namespace?: string): void;
1160
- delete(id: string, namespace?: string): boolean;
1161
- };
1162
- /** Request headers that carry controls, checked: spread them into a `fetch` or an SDK's defaults. */
1163
- headers(input: ControlHeaderInput): Record<string, string>;
1164
- snapshot(namespace?: string): NamespaceSnapshot;
1165
- restore(snapshot: NamespaceSnapshot, namespace?: string): void;
1166
- /** Capture the current branch. Mutating HTTP calls do this automatically. */
1167
- checkpoint(namespace?: string, branch?: string): ServiceCheckpoint;
1168
- /** Create an isolated branch, optionally from a historical checkpoint. */
1169
- branch(name: string, options?: {
1170
- namespace?: string;
1171
- at?: string;
1172
- }): ServiceCheckpoint;
1173
- /** Restore a branch, clock, and PRNG to a checkpoint. */
1174
- checkout(checkpoint: string, options?: {
1175
- namespace?: string;
1176
- branch?: string;
1177
- }): void;
1178
- /** Inspect the retained history for a namespace. */
1179
- timeline(namespace?: string): Timeline<ServiceTimelineState>;
1180
- /** Collections in one namespace: declared shape plus what the rows actually hold. */
1181
- state(namespace?: string): StateView;
1182
- };
1183
-
1184
- /** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
1185
- type SqliteValue = null | number | bigint | string | Uint8Array | boolean;
1186
- /** Mutation counters returned by {@link SqliteStatement.run}. */
1187
- type SqliteRunResult = {
1188
- changes: number;
1189
- lastInsertRowid: number | bigint;
1190
- };
1191
- /**
1192
- * Prepared statement bound to a {@link SqliteClient}.
1193
- *
1194
- * Pass bind values as rest arguments on each call (no sticky `bind()`).
1195
- */
1196
- interface SqliteStatement {
1197
- run(...params: SqliteValue[]): SqliteRunResult;
1198
- all<T = Record<string, unknown>>(...params: SqliteValue[]): T[];
1199
- get<T = Record<string, unknown>>(...params: SqliteValue[]): T | undefined;
1200
- }
1201
- /**
1202
- * Sync SQLite client port owned by Mockingbird.
1203
- *
1204
- * Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
1205
- * `bun:sqlite` instances all work when they expose this surface.
1206
- */
1207
- interface SqliteClient {
1208
- exec(sql: string): void;
1209
- prepare(sql: string): SqliteStatement;
1210
- transaction<T>(fn: () => T): T;
1211
- }
1212
-
1213
- type VersioningStatus = "Enabled" | "Suspended";
1214
- type BucketRecord = {
1215
- createdAt: number;
1216
- versioning?: VersioningStatus;
1217
- /** Created with `x-amz-bucket-object-lock-enabled: true`. */
1218
- objectLock?: boolean;
1219
- /** MinIO's versioning extension: prefixes (wildcard patterns) that stay unversioned. */
1220
- versioningExcludedPrefixes?: string[];
1221
- /** MinIO's versioning extension: keys ending in `/` stay unversioned. */
1222
- versioningExcludeFolders?: boolean;
1223
- /** The object-lock configuration's default retention, applied to new versions. */
1224
- defaultRetention?: {
1225
- mode: "GOVERNANCE" | "COMPLIANCE";
1226
- days?: number;
1227
- years?: number;
1228
- };
1229
- };
1230
- type ChecksumAlgorithmName = "CRC32" | "CRC32C" | "CRC64NVME" | "SHA1" | "SHA256";
1231
- type StoredChecksum = {
1232
- algorithm: ChecksumAlgorithmName;
1233
- /** base64 digest, with `-<parts>` for a composite multipart checksum. */
1234
- value: string;
1235
- type: "FULL_OBJECT" | "COMPOSITE";
1236
- };
1237
- type PartInfo = {
1238
- number: number;
1239
- size: number;
1240
- /** Unquoted. */
1241
- etag: string;
1242
- checksum?: string;
1243
- };
1244
- /** One version of an object (or a delete marker). The unversioned object is version `"null"`. */
1245
- type ObjectVersion = {
1246
- bucket: string;
1247
- key: string;
1248
- versionId: string;
1249
- deleteMarker?: boolean;
1250
- /** Blob id of the bytes; absent for delete markers. */
1251
- blob?: string;
1252
- size: number;
1253
- /** Unquoted ETag (`<md5 hex>` or `<md5 hex>-<parts>`); "" for delete markers. */
1254
- etag: string;
1255
- lastModified: number;
1256
- contentType?: string;
1257
- contentEncoding?: string;
1258
- contentDisposition?: string;
1259
- contentLanguage?: string;
1260
- cacheControl?: string;
1261
- /** The `Expires` header as sent. */
1262
- expires?: string;
1263
- websiteRedirect?: string;
1264
- /** User metadata, names lowercased without the `x-amz-meta-` prefix. */
1265
- metadata: Record<string, string>;
1266
- /** URL-encoded tag set (`a=1&b=2`), as S3 stores `x-amz-tagging`. */
1267
- tagging?: string;
1268
- storageClass?: string;
1269
- checksum?: StoredChecksum;
1270
- /** Present when the object was assembled by CompleteMultipartUpload. */
1271
- parts?: PartInfo[];
1272
- retention?: {
1273
- mode: "GOVERNANCE" | "COMPLIANCE";
1274
- until: string;
1275
- };
1276
- legalHold?: "ON" | "OFF";
1277
- /** Server-side encryption the object was written with. */
1278
- sse?: {
1279
- algorithm: "AES256" | "aws:kms";
1280
- kmsKeyId?: string;
1281
- bucketKey?: boolean;
1282
- };
1283
- /** Any other stored headers to replay verbatim (lowercased name → value). */
1284
- extra?: Record<string, string>;
1285
- };
1286
- /** The object fields a multipart upload carries until completion. */
1287
- type MultipartUpload = Omit<ObjectVersion, "versionId" | "blob" | "size" | "etag" | "lastModified" | "deleteMarker" | "parts" | "checksum"> & {
1288
- id: string;
1289
- initiated: number;
1290
- checksumAlgorithm?: ChecksumAlgorithmName;
1291
- checksumType?: "FULL_OBJECT" | "COMPOSITE";
1292
- };
1293
- type MultipartPart = {
1294
- uploadId: string;
1295
- partNumber: number;
1296
- blob: string;
1297
- size: number;
1298
- /** Unquoted. */
1299
- etag: string;
1300
- lastModified: number;
1301
- checksums?: Partial<Record<ChecksumAlgorithmName, string>>;
1302
- };
1303
- /** Object bytes, base64 in a row, written once and shared by every version that points at them. */
1304
- declare class BlobStore {
1305
- private readonly ids;
1306
- private readonly inner;
1307
- constructor(sqlite: SqliteClient, namespace: string, ids: IdSequence);
1308
- put(bytes: Uint8Array): string;
1309
- get(id: string | undefined): Uint8Array<ArrayBuffer>;
1310
- retain(id: string | undefined): void;
1311
- release(id: string | undefined): void;
1312
- }
1313
- declare class S3State {
1314
- readonly buckets: Collection<BucketRecord>;
1315
- /** Every version, keyed `[bucket, key, versionId]`. Sequence order is write order. */
1316
- readonly versions: Collection<ObjectVersion>;
1317
- /** The latest version of each key, keyed `[bucket, key]`. */
1318
- readonly heads: Collection<{
1319
- bucket: string;
1320
- key: string;
1321
- versionId: string;
1322
- }>;
1323
- /** Bucket sub-resources (policy, lifecycle, tagging, ...), keyed `[bucket, kind]`. */
1324
- readonly configurations: Collection<{
1325
- bucket: string;
1326
- kind: string;
1327
- body: string;
1328
- }>;
1329
- readonly uploads: Collection<MultipartUpload>;
1330
- readonly parts: Collection<MultipartPart>;
1331
- readonly blobs: BlobStore;
1332
- readonly ids: IdSequence;
1333
- constructor(sqlite: SqliteClient, namespace: string);
1334
- versionId(bucket: string, key: string, versionId: string): string;
1335
- headId(bucket: string, key: string): string;
1336
- configId(bucket: string, kind: string): string;
1337
- partId(uploadId: string, partNumber: number): string;
1338
- }
1339
-
1340
- /**
1341
- * The object store over S3State: buckets, versions and their latest-version pointers, with the
1342
- * versioning rules every write and delete shares (null versions, delete markers, head repair).
1343
- */
1344
-
1345
- type S3Notification = {
1346
- eventName: "ObjectCreated:Put" | "ObjectCreated:Post" | "ObjectCreated:Copy" | "ObjectCreated:CompleteMultipartUpload" | "ObjectRemoved:Delete" | "ObjectRemoved:DeleteMarkerCreated";
1347
- bucket: string;
1348
- key: string;
1349
- etag?: string;
1350
- size?: number;
1351
- versionId?: string;
1352
- occurredAt: string;
1353
- };
1354
- type CoreOptions = {
1355
- sqlite: SqliteClient;
1356
- namespace: string;
1357
- now: () => number;
1358
- random: () => number;
1359
- region: string;
1360
- /** access key → secret key. */
1361
- credentials: Readonly<Record<string, string>>;
1362
- /** `strict`: MinIO's auth exactly. `lenient`: unsigned requests act as the owner. */
1363
- authentication: "strict" | "lenient";
1364
- onNotification?: (event: S3Notification) => void;
1365
- };
1366
- /** Shared state and rules; handlers reach it as `ctx.core`. */
1367
- declare class S3Core {
1368
- readonly options: CoreOptions;
1369
- readonly state: S3State;
1370
- constructor(options: CoreOptions);
1371
- get region(): string;
1372
- now(): number;
1373
- /** A random-looking hex string from the seeded stream. */
1374
- randomHex(length: number): string;
1375
- /** A UUID v4 from the seeded stream (MinIO's version id format). */
1376
- uuid(): string;
1377
- notify(event: Omit<S3Notification, "occurredAt">): void;
1378
- bucket(name: string): BucketRecord | undefined;
1379
- requireBucket(name: string): BucketRecord;
1380
- saveBucket(name: string, record: BucketRecord): void;
1381
- config(bucket: string, kind: string): string | undefined;
1382
- setConfig(bucket: string, kind: string, body: string | undefined): void;
1383
- /** Remove a bucket and everything it holds. */
1384
- dropBucket(name: string): void;
1385
- /** The latest version of a key (possibly a delete marker). */
1386
- head(bucket: string, key: string): ObjectVersion | undefined;
1387
- version(bucket: string, key: string, versionId: string): ObjectVersion | undefined;
1388
- /** Every version of a key, newest first. */
1389
- versionsOf(bucket: string, key: string): ObjectVersion[];
1390
- bytes(version: ObjectVersion): Uint8Array<ArrayBuffer>;
1391
- private setHead;
1392
- /**
1393
- * MinIO's `PrefixEnabled`: versioning is Enabled and `key` matches none of the bucket's
1394
- * excluded prefixes (nor, with ExcludeFolders, ends in `/`).
1395
- */
1396
- versioned(bucket: string, key?: string): boolean;
1397
- /** Versioning is Suspended at the bucket level. */
1398
- suspended(bucket: string): boolean;
1399
- /** The id a new write of `key` gets: a fresh UUID when versioning applies, else `"null"`. */
1400
- nextVersionId(bucket: string, key?: string): string;
1401
- /**
1402
- * DeleteObject's versioning rules (MinIO's `erasureServerPools.DeleteObject`): with a version
1403
- * id, remove exactly that version; without one, a latest delete marker is returned as is, a
1404
- * versioned key gets a new delete marker, a suspended bucket a `null` delete marker (replacing
1405
- * the null version), and anything else loses its `null` version. A key with no versions at all
1406
- * is left alone (`undefined`). The result is the removed version or the marker written/found.
1407
- */
1408
- deleteObject(bucket: string, key: string, versionId: string, now: number): {
1409
- version: ObjectVersion;
1410
- marker: boolean;
1411
- } | undefined;
1412
- /**
1413
- * Store a new version as the latest. In an unversioned or suspended bucket it replaces the
1414
- * `null` version; in a versioned bucket it is added with a fresh id.
1415
- */
1416
- write(input: Omit<ObjectVersion, "versionId" | "blob" | "size"> & {
1417
- versionId?: string;
1418
- }, bytes: Uint8Array): ObjectVersion;
1419
- /** Store a version that shares an existing blob (copies keep one copy of the bytes). */
1420
- writeShared(input: Omit<ObjectVersion, "versionId"> & {
1421
- versionId?: string;
1422
- }): ObjectVersion;
1423
- /**
1424
- * MinIO's `checkPutObjectLockAllowed` default: in an object-lock bucket with a default
1425
- * retention rule, a new version written without its own retention or legal hold is retained
1426
- * until now + the rule's period.
1427
- */
1428
- private withDefaultRetention;
1429
- /** Change a stored version in place (tags, retention, legal hold) without reordering it. */
1430
- update(version: ObjectVersion): void;
1431
- /** Permanently delete one version and repoint the key's head. */
1432
- removeVersion(bucket: string, key: string, versionId: string): ObjectVersion | undefined;
1433
- /** The current object of every key in a bucket (delete markers excluded). */
1434
- currentObjects(bucket: string): ObjectVersion[];
1435
- /** Every version in a bucket, newest first. */
1436
- allVersions(bucket: string): ObjectVersion[];
1437
- isLatest(version: ObjectVersion): boolean;
1438
- /** No versions at all. Pending multipart uploads do not count: MinIO deletes them with the bucket. */
1439
- bucketIsEmpty(bucket: string): boolean;
1440
- }
1441
-
1442
- type S3SeedObject = {
1443
- bucket: string;
1444
- key: string;
1445
- body: Uint8Array | string;
1446
- metadata?: Record<string, string>;
1447
- contentType?: string;
1448
- cacheControl?: string;
1449
- contentDisposition?: string;
1450
- contentEncoding?: string;
1451
- /** URL-encoded tag set, or a record of tags. */
1452
- tags?: Record<string, string> | string;
1453
- storageClass?: string;
1454
- etag?: string;
1455
- lastModified?: number;
1456
- };
1457
- type S3APIOptions = APIOptions & {
1458
- buckets?: readonly string[];
1459
- objects?: readonly S3SeedObject[];
1460
- /** access key → secret key. Default `{ fixture: "fixture" }`. */
1461
- credentials?: Readonly<Record<string, string>>;
1462
- /**
1463
- * `lenient` (default): unsigned requests act as the bucket owner and header signatures are not
1464
- * checked; presigned URLs still are. `strict`: MinIO's authentication exactly — every request
1465
- * must be signed by a known key (or allowed anonymously by a bucket policy).
1466
- */
1467
- authentication?: "lenient" | "strict";
1468
- /** The server region (`x-amz-bucket-region`, signature scope). Default `us-east-1`. */
1469
- region?: string;
1470
- /**
1471
- * Base hosts for virtual-hosted-style addressing: `Host: <bucket>.<base>` names the bucket and
1472
- * the path is the key. Default `["localhost"]`; `[]` leaves every request path-style.
1473
- */
1474
- virtualHosts?: readonly string[];
1475
- onNotification?: (event: S3Notification) => void;
1476
- /** A seeded stream of `[0, 1)` for request and version ids. */
1477
- random?: () => number;
1478
- };
1479
- declare const S3_NAMESPACE = "s3";
1480
- /** S3 accepts at most 5 GiB in a single PUT and in each multipart part. */
1481
- declare const S3_MAX_UPLOAD_BYTES: number;
1482
- declare class S3API {
1483
- private readonly options;
1484
- readonly core: S3Core;
1485
- private readonly sqlite;
1486
- private readonly namespace;
1487
- private readonly ready;
1488
- constructor(options?: S3APIOptions);
1489
- get state(): S3State;
1490
- private seed;
1491
- reset(): Promise<void>;
1492
- /** Store an object directly (fixtures, the admin plane), creating its bucket if needed. */
1493
- putSeed(input: S3SeedObject): Promise<ObjectVersion>;
1494
- private requestId;
1495
- fetch(input: Request): Promise<Response>;
1496
- private renderError;
1497
- /** MinIO's `setCommonHeaders` plus the request ids, filled into the error body too. */
1498
- private finish;
1499
- private handle;
1500
- private authenticate;
1501
- }
1502
-
1503
- declare const S3_PRESETS: Record<string, FaultPreset>;
1504
- type S3RuntimeOptions = {
1505
- sqlite?: SqliteClient;
1506
- clock?: Clock;
1507
- seed?: number | string;
1508
- adminPrefix?: string;
1509
- adminKey?: string;
1510
- /** Admin controls to boot with: clock, latency, faults, seed, a starting snapshot. */
1511
- adminControls?: MockControls;
1512
- onLog?: (entry: RequestLog) => void;
1513
- buckets?: readonly string[];
1514
- objects?: readonly S3SeedObject[];
1515
- credentials?: Readonly<Record<string, string>>;
1516
- /** `lenient` (default) or `strict` (MinIO's SigV4 checks on every request). */
1517
- authentication?: "lenient" | "strict";
1518
- /** Server region. Default `us-east-1`. */
1519
- region?: string;
1520
- /**
1521
- * Base hosts for virtual-hosted-style addressing: `Host: <bucket>.<base>` names the bucket and
1522
- * the path is the key. Default `["localhost"]`; `[]` leaves every request path-style.
1523
- */
1524
- virtualHosts?: readonly string[];
1525
- webhooks?: {
1526
- endpoints?: WebhookEndpoint[];
1527
- retryDelaysMs?: readonly number[];
1528
- fetch?: (request: Request) => Promise<Response>;
1529
- };
1530
- };
1531
- type S3Runtime = ServiceRuntime<S3API> & {
1532
- readonly webhooks: WebhookHub;
1533
- };
1534
- declare const createRuntime: (options?: S3RuntimeOptions) => S3Runtime;
1535
-
1536
172
  declare const accessKeyCredential: (request: Request) => string | undefined;
1537
173
 
1538
- export { S3API, S3_MAX_UPLOAD_BYTES, S3_NAMESPACE, S3_PRESETS, accessKeyCredential, createRuntime, document, operationIds, supportedOperationIds };
1539
- export type { BucketRecord, MultipartPart, MultipartUpload, ObjectVersion, S3APIOptions, S3Notification, ObjectVersion as S3Object, S3Runtime, S3RuntimeOptions, S3SeedObject };
174
+ export { accessKeyCredential, document, operationIds, supportedOperationIds };