@crvouga/mockingbird-service-resend 3.2.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,15 +1,21 @@
1
1
  # Changelog — @crvouga/mockingbird-service-resend
2
2
 
3
- ## 3.2.0 (2026-10-09)
3
+ ## 3.3.0 (2026-10-12)
4
4
 
5
5
  ### Features
6
6
 
7
- - match Emulate provider coverage ([16b65ce](https://github.com/crvouga/mockingbird/commit/16b65ce791fa216f28ec1521df636f57771d9c5e))
7
+ - unify the emulator control plane ([2068547](https://github.com/crvouga/mockingbird/commit/2068547bedde4e2e2331c1657c1a78120e84428b))
8
8
 
9
9
  ### Dependencies
10
10
 
11
11
  - `@crvouga/mockingbird-service-sqlite`
12
12
 
13
+ ## 3.2.0 (2026-10-08)
14
+
15
+ ### Features
16
+
17
+ - match Emulate provider coverage ([16b65ce](https://github.com/crvouga/mockingbird/commit/16b65ce791fa216f28ec1521df636f57771d9c5e))
18
+
13
19
  ## 3.1.0 (2026-10-08)
14
20
 
15
21
  ### Features
package/DISCOVERY.md CHANGED
@@ -35,6 +35,7 @@ repository; live parity is an additional oracle check, not a substitute for the
35
35
 
36
36
  - `GET /__admin/health`
37
37
  - `GET /__admin`
38
+ - `GET /__admin/controls`
38
39
  - `GET /__admin/state`
39
40
  - `GET /__admin/requests`
40
41
  - `GET /__admin/metrics`
@@ -45,6 +46,28 @@ For HTTP services, use `x-mockingbird-namespace` (or the documented credential/p
45
46
  parallel tests do not share state. Admin state, journal, metrics and fault-preset endpoints are
46
47
  designed for assertions and diagnosis by consuming test suites.
47
48
 
49
+ ## Admin controls
50
+
51
+ Every HTTP emulator takes the same controls, and each means the same thing at boot
52
+ (`createRuntime({ adminControls })`, `serve --admin-controls`), over `/__admin`, and in a request header:
53
+
54
+ | Control | Admin API | Request header | Interface |
55
+ | --- | --- | --- | --- |
56
+ | Isolate state by key | `GET /__admin/namespaces` | `x-mockingbird-namespace: <key>` | [Namespaces](https://mockingbird.chrisvouga.dev/docs/admin-controls/namespaces) |
57
+ | Reset to boot | `POST /__admin/reset` | `x-mockingbird-reset: true` | [Reset](https://mockingbird.chrisvouga.dev/docs/admin-controls/reset) |
58
+ | Snapshot and restore | `POST /__admin/snapshots`, `POST /__admin/snapshots/<id>/restore` | `x-mockingbird-snapshot: <name>`, `x-mockingbird-restore: <name>` | [Snapshot and restore](https://mockingbird.chrisvouga.dev/docs/admin-controls/snapshot-and-restore) |
59
+ | Move the clock | `POST /__admin/clock` | `x-mockingbird-time: <instant>`, `x-mockingbird-advance: <duration>` | [Clock](https://mockingbird.chrisvouga.dev/docs/admin-controls/clock) |
60
+ | Read or branch from old state | `GET /__admin/timeline` | `x-mockingbird-at: <checkpoint>`, `x-mockingbird-branch: <name>` | [Checkpoints and branches](https://mockingbird.chrisvouga.dev/docs/admin-controls/checkpoints-and-branches) |
61
+ | Inject a fault | `POST /__admin/faults` | `x-mockingbird-fault: <fault>` | [Faults](https://mockingbird.chrisvouga.dev/docs/admin-controls/faults) |
62
+ | Latency and timeouts | `PUT /__admin/latency` | `x-mockingbird-delay: <duration>`, `x-mockingbird-timeout: <duration>` | [Latency and timeouts](https://mockingbird.chrisvouga.dev/docs/admin-controls/latency-and-timeouts) |
63
+ | Replay from a seed | `PUT /__admin/controls` | `x-mockingbird-seed: <seed>` | [Seed and determinism](https://mockingbird.chrisvouga.dev/docs/admin-controls/seed-and-determinism) |
64
+ | See what happened | `GET /__admin/requests`, `GET /__admin/state` | | [Journal, metrics and state](https://mockingbird.chrisvouga.dev/docs/admin-controls/journal-and-state) |
65
+
66
+ `GET /__admin` lists every route and header with a one-line summary, and `GET /__admin/controls`
67
+ is the namespace's current control document. The same seed and the same requests give the same
68
+ bytes. Setting controls as an emulator starts is [Boot](https://mockingbird.chrisvouga.dev/docs/admin-controls/boot); every route and header is in
69
+ the [Reference](https://mockingbird.chrisvouga.dev/docs/admin-controls/reference). The full guide: <https://mockingbird.chrisvouga.dev/docs/admin-controls>.
70
+
48
71
  ## Report a mismatch or missing capability
49
72
 
50
73
  Follow the [agent reporting contract](https://github.com/crvouga/mockingbird/blob/main/docs/REPORTING_ISSUES.md). Include package version,
package/README.md CHANGED
@@ -37,13 +37,15 @@ npx mockingbird-resend serve --port 8794 \
37
37
  RESEND_BASE_URL=http://127.0.0.1:8794 node app.js
38
38
  ```
39
39
 
40
- ```js
40
+ ```ts
41
41
  import { createServer } from "@crvouga/mockingbird-service-resend/server"
42
42
 
43
+ // Test setup: the emulator, and the base URL the Resend SDK reads at import.
43
44
  const emulator = await createServer()
44
45
  process.env.RESEND_BASE_URL = emulator.url
45
46
  const { Resend } = await import("resend")
46
47
 
48
+ // The app's own Resend call.
47
49
  await new Resend("re_test").emails.send({
48
50
  from: "Acme <no-reply@acme.example>",
49
51
  to: ["invitee@example.com"],
@@ -51,23 +53,31 @@ await new Resend("re_test").emails.send({
51
53
  html: '<a href="https://app.test/family/invitations/claim?token=abc">Join</a>',
52
54
  })
53
55
 
56
+ // The test reads the mail back from the outbox.
54
57
  const { messages } = await (await fetch(`${emulator.url}/__admin/outbox?to=invitee@example.com`)).json()
55
58
  const { links } = await (await fetch(`${emulator.url}/__admin/outbox/${messages[0].id}/links`)).json()
56
59
  // links[0] === "https://app.test/family/invitations/claim?token=abc"
60
+ await emulator.close()
57
61
  ```
58
62
 
59
- Whatever sends the mail (the SDK above, or raw HTTP), the outbox is the assertion surface:
63
+ The outbox is the assertion surface for every send. An `idempotencyKey` replay returns the first
64
+ send's id and leaves one message in it:
60
65
 
61
66
  ```ts
62
67
  import { createServer } from "@crvouga/mockingbird-service-resend/server"
63
68
 
64
69
  const emulator = await createServer()
65
- await fetch(`${emulator.url}/emails`, {
66
- method: "POST",
67
- headers: { "content-type": "application/json", authorization: "Bearer re_test" },
68
- body: JSON.stringify({ from: "no-reply@example.com", to: ["invitee@example.com"], subject: "Hi", text: "Hello" }),
69
- })
70
+ process.env.RESEND_BASE_URL = emulator.url
71
+ const { Resend } = await import("resend")
72
+
73
+ const resend = new Resend("re_test")
74
+ const email = { from: "no-reply@example.com", to: ["invitee@example.com"], subject: "Hi", text: "Hello" }
75
+ const first = await resend.emails.send(email, { idempotencyKey: "invite-1" })
76
+ const retry = await resend.emails.send(email, { idempotencyKey: "invite-1" })
77
+ // retry.data?.id === first.data?.id
78
+
70
79
  const sent = await (await fetch(`${emulator.url}/__admin/outbox?to=invitee@example.com`)).json()
80
+ // sent.messages.length === 1
71
81
  await emulator.close()
72
82
  ```
73
83
 
@@ -42,11 +42,38 @@ function createHmac(algorithm, key) {
42
42
  };
43
43
  return hash;
44
44
  }
45
+ var source;
46
+ function useRandom(next) {
47
+ source = next;
48
+ }
49
+ function withRandom(next, run) {
50
+ const previous = source;
51
+ source = next;
52
+ try {
53
+ return run();
54
+ } finally {
55
+ source = previous;
56
+ }
57
+ }
58
+ function random() {
59
+ return source ? source() : Math.random();
60
+ }
45
61
  function randomBytes(length) {
46
- return Buffer.from(crypto.getRandomValues(new Uint8Array(length)));
62
+ if (!source)
63
+ return Buffer.from(crypto.getRandomValues(new Uint8Array(length)));
64
+ const out = new Uint8Array(length);
65
+ for (let i = 0; i < length; i++)
66
+ out[i] = Math.floor(source() * 256);
67
+ return Buffer.from(out);
47
68
  }
48
69
  function randomUUID() {
49
- return crypto.randomUUID();
70
+ if (!source)
71
+ return crypto.randomUUID();
72
+ const b = randomBytes(16);
73
+ b[6] = b[6] & 15 | 64;
74
+ b[8] = b[8] & 63 | 128;
75
+ const hex = b.toString("hex");
76
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
50
77
  }
51
78
  function timingSafeEqual(a, b) {
52
79
  if (a.length !== b.length)
@@ -60,8 +87,11 @@ function timingSafeEqual(a, b) {
60
87
  export {
61
88
  createHash,
62
89
  createHmac,
90
+ useRandom,
91
+ withRandom,
92
+ random,
63
93
  randomBytes,
64
94
  randomUUID,
65
95
  timingSafeEqual
66
96
  };
67
- //# sourceMappingURL=chunk-M73LWCCP.js.map
97
+ //# sourceMappingURL=chunk-6Z2MR3PO.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../http/provider/src/vendor/core/crypto.ts"],
4
- "sourcesContent": ["import { hmac } from \"@noble/hashes/hmac.js\"\nimport { sha1 } from \"@noble/hashes/legacy.js\"\nimport { md5 } from \"@noble/hashes/legacy.js\"\nimport { sha256 } from \"@noble/hashes/sha2.js\"\nimport { Buffer } from \"buffer\"\n\nconst digest = (algorithm: string) => {\n if (algorithm === \"sha256\") return sha256\n if (algorithm === \"sha1\") return sha1\n if (algorithm === \"md5\") return md5\n throw new Error(`Unsupported digest ${algorithm}`)\n}\nconst bytes = (input: string | Uint8Array) => typeof input === \"string\" ? new TextEncoder().encode(input) : input\ninterface Hash {\n update(input: string | Uint8Array): Hash\n digest(): Buffer\n digest(encoding: string): string\n}\nexport function createHash(algorithm: string): Hash {\n const parts: Uint8Array[] = []\n const hash = {\n update(input: string | Uint8Array) { parts.push(bytes(input)); return hash },\n digest(encoding?: string): Buffer | string {\n const result = Buffer.from(digest(algorithm)(Buffer.concat(parts)))\n return encoding === \"base64url\" ? result.toString(\"base64\").replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\") : encoding ? result.toString(encoding as BufferEncoding) : result\n },\n }\n return hash as Hash\n}\nexport function createHmac(algorithm: string, key: string | Uint8Array): Hash {\n const parts: Uint8Array[] = []\n const hash = {\n update(input: string | Uint8Array) { parts.push(bytes(input)); return hash },\n digest(encoding?: string): Buffer | string {\n const result = Buffer.from(hmac(digest(algorithm), bytes(key), Buffer.concat(parts)))\n return encoding === \"base64url\" ? result.toString(\"base64\").replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\") : encoding ? result.toString(encoding as BufferEncoding) : result\n },\n }\n return hash as Hash\n}\nexport function randomBytes(length: number): Buffer {\n return Buffer.from(crypto.getRandomValues(new Uint8Array(length)))\n}\nexport function randomUUID(): string { return crypto.randomUUID() }\nexport function timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) throw new Error(\"Buffers must have equal lengths\")\n let difference = 0\n for (let i = 0; i < a.length; i++) difference |= a[i] ^ b[i]\n return difference === 0\n}\n"],
5
- "mappings": ";AAAA,SAAS,YAAY;AACrB,SAAS,YAAY;AACrB,SAAS,WAAW;AACpB,SAAS,cAAc;AACvB,SAAS,cAAc;AAEvB,IAAM,SAAS,CAAC,cAAqB;AACnC,MAAI,cAAc;AAAU,WAAO;AACnC,MAAI,cAAc;AAAQ,WAAO;AACjC,MAAI,cAAc;AAAO,WAAO;AAChC,QAAM,IAAI,MAAM,sBAAsB,SAAS,EAAE;AACnD;AACA,IAAM,QAAQ,CAAC,UAA+B,OAAO,UAAU,WAAW,IAAI,YAAW,EAAG,OAAO,KAAK,IAAI;AAMtG,SAAU,WAAW,WAAiB;AAC1C,QAAM,QAAsB,CAAA;AAC5B,QAAM,OAAO;IACX,OAAO,OAA0B;AAAI,YAAM,KAAK,MAAM,KAAK,CAAC;AAAG,aAAO;IAAK;IAC3E,OAAO,UAAiB;AACtB,YAAM,SAAS,OAAO,KAAK,OAAO,SAAS,EAAE,OAAO,OAAO,KAAK,CAAC,CAAC;AAClE,aAAO,aAAa,cAAc,OAAO,SAAS,QAAQ,EAAE,QAAQ,OAAO,GAAG,EAAE,QAAQ,OAAO,GAAG,EAAE,QAAQ,OAAO,EAAE,IAAI,WAAW,OAAO,SAAS,QAA0B,IAAI;IACpL;;AAEF,SAAO;AACT;AACM,SAAU,WAAW,WAAmB,KAAwB;AACpE,QAAM,QAAsB,CAAA;AAC5B,QAAM,OAAO;IACX,OAAO,OAA0B;AAAI,YAAM,KAAK,MAAM,KAAK,CAAC;AAAG,aAAO;IAAK;IAC3E,OAAO,UAAiB;AACtB,YAAM,SAAS,OAAO,KAAK,KAAK,OAAO,SAAS,GAAG,MAAM,GAAG,GAAG,OAAO,OAAO,KAAK,CAAC,CAAC;AACpF,aAAO,aAAa,cAAc,OAAO,SAAS,QAAQ,EAAE,QAAQ,OAAO,GAAG,EAAE,QAAQ,OAAO,GAAG,EAAE,QAAQ,OAAO,EAAE,IAAI,WAAW,OAAO,SAAS,QAA0B,IAAI;IACpL;;AAEF,SAAO;AACT;AACM,SAAU,YAAY,QAAc;AACxC,SAAO,OAAO,KAAK,OAAO,gBAAgB,IAAI,WAAW,MAAM,CAAC,CAAC;AACnE;AACM,SAAU,aAAU;AAAa,SAAO,OAAO,WAAU;AAAG;AAC5D,SAAU,gBAAgB,GAAe,GAAa;AAC1D,MAAI,EAAE,WAAW,EAAE;AAAQ,UAAM,IAAI,MAAM,iCAAiC;AAC5E,MAAI,aAAa;AACjB,WAAS,IAAI,GAAG,IAAI,EAAE,QAAQ;AAAK,kBAAc,EAAE,CAAC,IAAI,EAAE,CAAC;AAC3D,SAAO,eAAe;AACxB;",
4
+ "sourcesContent": ["import { hmac } from \"@noble/hashes/hmac.js\"\nimport { sha1 } from \"@noble/hashes/legacy.js\"\nimport { md5 } from \"@noble/hashes/legacy.js\"\nimport { sha256 } from \"@noble/hashes/sha2.js\"\nimport { Buffer } from \"buffer\"\n\nconst digest = (algorithm: string) => {\n if (algorithm === \"sha256\") return sha256\n if (algorithm === \"sha1\") return sha1\n if (algorithm === \"md5\") return md5\n throw new Error(`Unsupported digest ${algorithm}`)\n}\nconst bytes = (input: string | Uint8Array) => typeof input === \"string\" ? new TextEncoder().encode(input) : input\ninterface Hash {\n update(input: string | Uint8Array): Hash\n digest(): Buffer\n digest(encoding: string): string\n}\nexport function createHash(algorithm: string): Hash {\n const parts: Uint8Array[] = []\n const hash = {\n update(input: string | Uint8Array) { parts.push(bytes(input)); return hash },\n digest(encoding?: string): Buffer | string {\n const result = Buffer.from(digest(algorithm)(Buffer.concat(parts)))\n return encoding === \"base64url\" ? result.toString(\"base64\").replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\") : encoding ? result.toString(encoding as BufferEncoding) : result\n },\n }\n return hash as Hash\n}\nexport function createHmac(algorithm: string, key: string | Uint8Array): Hash {\n const parts: Uint8Array[] = []\n const hash = {\n update(input: string | Uint8Array) { parts.push(bytes(input)); return hash },\n digest(encoding?: string): Buffer | string {\n const result = Buffer.from(hmac(digest(algorithm), bytes(key), Buffer.concat(parts)))\n return encoding === \"base64url\" ? result.toString(\"base64\").replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\") : encoding ? result.toString(encoding as BufferEncoding) : result\n },\n }\n return hash as Hash\n}\n/**\n * Mockingbird: where ids and tokens come from. With a seeded stream in place, everything the\n * vendor code mints replays from the seed; without one it is the platform's own randomness.\n */\nlet source: (() => number) | undefined\n/** Mint from `next` (a seeded stream of `[0, 1)`) until told otherwise. */\nexport function useRandom(next: (() => number) | undefined): void { source = next }\n/** Mint from `next` for one synchronous section, then put the previous source back. */\nexport function withRandom<T>(next: (() => number) | undefined, run: () => T): T {\n const previous = source\n source = next\n try { return run() } finally { source = previous }\n}\n/** `Math.random`, from the seeded stream when one is in place. */\nexport function random(): number { return source ? source() : Math.random() }\nexport function randomBytes(length: number): Buffer {\n if (!source) return Buffer.from(crypto.getRandomValues(new Uint8Array(length)))\n const out = new Uint8Array(length)\n for (let i = 0; i < length; i++) out[i] = Math.floor(source() * 256)\n return Buffer.from(out)\n}\nexport function randomUUID(): string {\n if (!source) return crypto.randomUUID()\n const b = randomBytes(16)\n b[6] = (b[6] & 0x0f) | 0x40\n b[8] = (b[8] & 0x3f) | 0x80\n const hex = b.toString(\"hex\")\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`\n}\nexport function timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) throw new Error(\"Buffers must have equal lengths\")\n let difference = 0\n for (let i = 0; i < a.length; i++) difference |= a[i] ^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1,12 @@
1
1
  import {
2
2
  createClock,
3
3
  createRuntime,
4
+ normalizeBootControls,
4
5
  parseDuration,
5
- resolveAdminPrefix
6
- } from "./chunk-XQ4BQDIK.js";
6
+ parseFaultHeader,
7
+ resolveAdminPrefix,
8
+ restoreClock
9
+ } from "./chunk-YJDLINUI.js";
7
10
 
8
11
  // ../../adapters/node/dist/cli.js
9
12
  import { readFile as readFile2 } from "node:fs/promises";
@@ -50,6 +53,8 @@ var serve = async (api, options = {}) => {
50
53
  req.socket.destroy();
51
54
  return;
52
55
  }
56
+ if (aborted.signal.aborted)
57
+ return;
53
58
  res.writeHead(500, { "content-type": "application/json" });
54
59
  res.end(JSON.stringify({
55
60
  error: {
@@ -81,6 +86,7 @@ var serve = async (api, options = {}) => {
81
86
  }
82
87
  res.end();
83
88
  } catch {
89
+ await new Promise((resolve2) => setImmediate(resolve2));
84
90
  res.destroy();
85
91
  } finally {
86
92
  reader.releaseLock();
@@ -164,11 +170,11 @@ var httpChild = async (target, entry, options) => {
164
170
  adminKey: entry.adminKey,
165
171
  seed: entry.seed,
166
172
  onLog: options.onLog,
173
+ ...entry.adminControls !== void 0 ? { adminControls: entry.adminControls } : {},
167
174
  ...entry.fixtures !== void 0 ? { fixtures: entry.fixtures } : {},
168
175
  ...entry.baseUrl !== void 0 ? { baseUrl: entry.baseUrl } : {}
169
176
  });
170
177
  const adminPrefix = resolveAdminPrefix(entry.adminPrefix);
171
- runtime.isolateNamespaces();
172
178
  const locked = /* @__PURE__ */ new Set();
173
179
  const active = /* @__PURE__ */ new Map();
174
180
  const api = {
@@ -430,19 +436,12 @@ async function startFleet(config, options) {
430
436
  return json(400, { error: "freeze must be boolean" });
431
437
  const response2 = await transaction(namespace, selected, async (_name, child) => {
432
438
  const childClock = child.clock(namespace);
433
- childClock.freeze();
434
- childClock.set(target);
435
- if (!frozen)
436
- childClock.unfreeze();
439
+ restoreClock(childClock, { now: target, frozen });
437
440
  await child.settle?.(namespace);
438
441
  return childClock.state();
439
442
  });
440
- if (response2.ok) {
441
- current.freeze();
442
- current.set(target);
443
- if (!frozen)
444
- current.unfreeze();
445
- }
443
+ if (response2.ok)
444
+ restoreClock(current, { now: target, frozen });
446
445
  return response2;
447
446
  }
448
447
  if (!route)
@@ -461,13 +460,8 @@ async function startFleet(config, options) {
461
460
  return json(404, { error: "no snapshot in this namespace" });
462
461
  const restored = new Map([...point.values].map(([name]) => [name, children.get(name)]));
463
462
  const response2 = await transaction(namespace, restored, async (name, child) => child.restore(namespace, point.values.get(name)));
464
- if (response2.ok) {
465
- const current = clock(namespace);
466
- current.freeze();
467
- current.set(point.clock.now);
468
- if (!point.clock.frozen)
469
- current.unfreeze();
470
- }
463
+ if (response2.ok)
464
+ restoreClock(clock(namespace), point.clock);
471
465
  return response2;
472
466
  }
473
467
  const snapshotId = randomUUID();
@@ -493,6 +487,8 @@ async function startFleet(config, options) {
493
487
  for (const [name, entry] of Object.entries(config.services)) {
494
488
  if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name))
495
489
  throw new Error("invalid service name");
490
+ if (config.adminControls !== void 0 || entry.adminControls !== void 0)
491
+ normalizeBootControls({ ...config.adminControls, ...entry.adminControls }, `services.${name}.adminControls`);
496
492
  try {
497
493
  const target = await options.load(name);
498
494
  if (entry.protocol && entry.protocol !== ("protocol" in target ? target.protocol : "http"))
@@ -501,7 +497,9 @@ async function startFleet(config, options) {
501
497
  const child = "start" in target ? await target.start(entry) : await httpChild(target, {
502
498
  ...entry,
503
499
  adminPrefix: resolveAdminPrefix(entry.adminPrefix ?? adminPrefix),
504
- ...adminKey !== void 0 ? { adminKey } : {}
500
+ ...adminKey !== void 0 ? { adminKey } : {},
501
+ // Fleet-wide controls, with the service's own keys replacing them.
502
+ ...config.adminControls !== void 0 || entry.adminControls !== void 0 ? { adminControls: { ...config.adminControls, ...entry.adminControls } } : {}
505
503
  }, options);
506
504
  children.set(name, child);
507
505
  if (!await child.ready())
@@ -634,7 +632,51 @@ var COMMON_SERVE_OPTIONS = {
634
632
  value: "<key>",
635
633
  description: "Require x-mockingbird-admin-key on /__admin/* (env MOCKINGBIRD_ADMIN_KEY)"
636
634
  },
637
- seed: { type: "string", value: "<seed>", description: "Seed for every random choice" },
635
+ seed: {
636
+ type: "string",
637
+ value: "<seed>",
638
+ description: "Seed for every random choice (env MOCKINGBIRD_SEED)"
639
+ },
640
+ "admin-controls": {
641
+ type: "string",
642
+ value: "<json|file>",
643
+ description: "Admin controls to boot with, as JSON or a JSON file: clock, latency, faults, snapshot, namespaces (env MOCKINGBIRD_ADMIN_CONTROLS)"
644
+ },
645
+ clock: {
646
+ type: "string",
647
+ value: "<instant>",
648
+ description: "Start the clock at this instant (epoch ms or ISO-8601)"
649
+ },
650
+ freeze: { type: "boolean", description: "Freeze the clock: it moves only when told to" },
651
+ "auto-advance": {
652
+ type: "string",
653
+ value: "<duration>",
654
+ description: "Step the clock this much before every request (e.g. 1s)"
655
+ },
656
+ latency: {
657
+ type: "string",
658
+ value: "<duration>",
659
+ description: "Baseline response time for every request (e.g. 250ms)"
660
+ },
661
+ jitter: {
662
+ type: "string",
663
+ value: "<duration>",
664
+ description: "Seeded extra latency between 0 and this"
665
+ },
666
+ "virtual-time": {
667
+ type: "boolean",
668
+ description: "Spend latency, delays and timeouts on the mock clock instead of really waiting"
669
+ },
670
+ fault: {
671
+ type: "string",
672
+ value: "<fault>",
673
+ description: 'A fault to boot with, as in x-mockingbird-fault: 503, rate_limited, "status=503; delay=2s"'
674
+ },
675
+ snapshot: {
676
+ type: "string",
677
+ value: "<file>",
678
+ description: "Start from a snapshot document (GET /__admin/snapshots/:id)"
679
+ },
638
680
  log: {
639
681
  type: "string",
640
682
  value: "<pretty|json|off>",
@@ -681,6 +723,68 @@ var formatLog = (format) => {
681
723
  };
682
724
  };
683
725
  var asString = (value) => typeof value === "string" ? value : void 0;
726
+ var readJsonFile = async (path, label) => {
727
+ try {
728
+ return JSON.parse(await readFile2(path, "utf8"));
729
+ } catch (error) {
730
+ throw new Error(`${label}: cannot read ${path}: ${error instanceof Error ? error.message : error}`);
731
+ }
732
+ };
733
+ var isObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
734
+ var resolveServeControls = async (values, env = process.env, base) => {
735
+ const source = asString(values["admin-controls"]) ?? env.MOCKINGBIRD_ADMIN_CONTROLS;
736
+ let document = isObject2(base) ? { ...base } : {};
737
+ if (source !== void 0 && source.trim() !== "") {
738
+ let parsed;
739
+ if (source.trim().startsWith("{")) {
740
+ try {
741
+ parsed = JSON.parse(source);
742
+ } catch {
743
+ throw new Error("--admin-controls: not valid JSON");
744
+ }
745
+ } else
746
+ parsed = await readJsonFile(source, "--admin-controls");
747
+ if (!isObject2(parsed))
748
+ throw new Error("--admin-controls: expected a JSON object");
749
+ document = { ...document, ...parsed };
750
+ }
751
+ const clock = isObject2(document.clock) ? { ...document.clock } : {};
752
+ const now = asString(values.clock);
753
+ if (now !== void 0)
754
+ clock.now = now;
755
+ if (values.freeze === true)
756
+ clock.frozen = true;
757
+ const autoAdvance = asString(values["auto-advance"]);
758
+ if (autoAdvance !== void 0)
759
+ clock.autoAdvance = autoAdvance;
760
+ if (Object.keys(clock).length > 0)
761
+ document.clock = clock;
762
+ const delay = asString(values.latency);
763
+ const jitter = asString(values.jitter);
764
+ if (delay !== void 0 || jitter !== void 0) {
765
+ const latency = isObject2(document.latency) ? { ...document.latency } : document.latency !== void 0 ? { delay: document.latency } : {};
766
+ if (delay !== void 0)
767
+ latency.delay = delay;
768
+ if (jitter !== void 0)
769
+ latency.jitter = jitter;
770
+ document.latency = latency;
771
+ }
772
+ if (values["virtual-time"] === true)
773
+ document.virtualTime = true;
774
+ const fault = asString(values.fault);
775
+ if (fault !== void 0)
776
+ document.faults = [
777
+ ...Array.isArray(document.faults) ? document.faults : [],
778
+ parseFaultHeader(fault, "--fault")
779
+ ];
780
+ const snapshot = asString(values.snapshot);
781
+ if (snapshot !== void 0)
782
+ document.snapshot = await readJsonFile(snapshot, "--snapshot");
783
+ if (Object.keys(document).length === 0)
784
+ return void 0;
785
+ normalizeBootControls(document, "adminControls");
786
+ return document;
787
+ };
684
788
  var loadTarget = async (name, own) => {
685
789
  if (name === own.name)
686
790
  return own;
@@ -707,7 +811,8 @@ var start = async (target, values, config) => {
707
811
  adminPrefix,
708
812
  adminKey: config.adminKey,
709
813
  seed: config.seed,
710
- onLog: formatLog(config.log)
814
+ onLog: formatLog(config.log),
815
+ ...config.adminControls !== void 0 ? { adminControls: config.adminControls } : {}
711
816
  });
712
817
  const listening = await listen(runtime, { port: config.port, host: config.host });
713
818
  target.listening?.(listening);
@@ -747,6 +852,9 @@ var serveCommand = (target) => ({
747
852
  const adminKey2 = config.adminKey ?? asString(values["admin-key"]) ?? process.env.MOCKINGBIRD_ADMIN_KEY;
748
853
  if (adminKey2 !== void 0)
749
854
  config.adminKey = adminKey2;
855
+ const adminControls = await resolveServeControls(values, process.env, config.adminControls);
856
+ if (adminControls !== void 0)
857
+ config.adminControls = adminControls;
750
858
  const fleet = await startFleet(config, {
751
859
  load: (name) => loadTarget(name, target),
752
860
  onLog: formatLog(config.log ?? log),
@@ -772,10 +880,12 @@ var serveCommand = (target) => ({
772
880
  }
773
881
  const port = asString(values.port);
774
882
  const adminKey = asString(values["admin-key"]) ?? process.env.MOCKINGBIRD_ADMIN_KEY;
775
- const seed = asString(values.seed);
883
+ const seed = asString(values.seed) ?? process.env.MOCKINGBIRD_SEED;
776
884
  let listening;
777
885
  try {
886
+ const adminControls = await resolveServeControls(values);
778
887
  listening = await start(target, values, {
888
+ ...adminControls !== void 0 ? { adminControls } : {},
779
889
  adminPrefix: resolveAdminPrefix(asString(values["admin-prefix"]) ?? process.env.MOCKINGBIRD_ADMIN_PREFIX),
780
890
  port: port === void 0 ? target.defaultPort : Number.parseInt(port, 10),
781
891
  host: asString(values.host) ?? "127.0.0.1",
@@ -888,11 +998,13 @@ var serveTarget = {
888
998
  forwardToInbox: {
889
999
  url: inbox,
890
1000
  ...common.adminPrefix !== void 0 ? { adminPrefix: common.adminPrefix } : {},
891
- ...common.adminKey !== void 0 ? { adminKey: common.adminKey } : {}
1001
+ ...common.adminKey !== void 0 ? { adminKey: common.adminKey } : {},
1002
+ ...common.adminControls !== void 0 ? { adminControls: common.adminControls } : {}
892
1003
  }
893
1004
  } : {},
894
1005
  ...common.adminPrefix !== void 0 ? { adminPrefix: common.adminPrefix } : {},
895
1006
  ...common.adminKey !== void 0 ? { adminKey: common.adminKey } : {},
1007
+ ...common.adminControls !== void 0 ? { adminControls: common.adminControls } : {},
896
1008
  ...common.seed !== void 0 ? { seed: common.seed } : {},
897
1009
  ...common.onLog ? { onLog: common.onLog } : {}
898
1010
  });
@@ -912,4 +1024,4 @@ export {
912
1024
  createServer2 as createServer,
913
1025
  serveTarget
914
1026
  };
915
- //# sourceMappingURL=chunk-WMQIKI4U.js.map
1027
+ //# sourceMappingURL=chunk-YE2BKTX6.js.map