@crvouga/mockingbird-service-intercom 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.
- package/CHANGELOG.md +5 -0
- package/README.md +218 -0
- package/dist/chunk-5RRE6WVT.js +364 -0
- package/dist/chunk-5RRE6WVT.js.map +7 -0
- package/dist/chunk-OSBG2XJ7.js +3835 -0
- package/dist/chunk-OSBG2XJ7.js.map +7 -0
- package/dist/cli.js +19 -0
- package/dist/cli.js.map +7 -0
- package/dist/index.d.ts +1204 -0
- package/dist/index.js +39 -0
- package/dist/index.js.map +7 -0
- package/dist/server.d.ts +1510 -0
- package/dist/server.js +12 -0
- package/dist/server.js.map +7 -0
- package/package.json +87 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../core/src/clock.ts", "../../core/src/collection.ts", "../../core/src/control.ts", "../../core/src/credentials.ts", "../../core/src/rng.ts", "../../core/src/faults.ts", "../../../openapi/core/src/refs.ts", "../../../openapi/core/src/types.ts", "../../../openapi/core/src/document.ts", "../../../openapi/core/src/schema.ts", "../../../http/codec/src/form.ts", "../../../http/codec/src/content.ts", "../../core/src/http.ts", "../../core/src/idempotency.ts", "../../core/src/ids.ts", "../../core/src/journal.ts", "../../core/src/metrics.ts", "../../../core/src/timeline.ts", "../../../sqlite/src/default.ts", "../../../sqlite/src/migrate.ts", "../../../sqlite/src/schema.ts", "../../../openapi/metadata/src/types.ts", "../../../openapi/metadata/src/read.ts", "../../core/src/service.ts", "../../core/src/snapshot.ts", "../../core/src/version.ts", "../../core/src/signing.ts", "../../core/src/webhooks.ts", "../../core/src/runtime.ts", "../../core/src/validation.ts", "../src/generated/openapi.ts", "../src/query.ts", "../src/state.ts", "../src/runtime.ts", "../src/index.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * The single source of time for a service.\n *\n * Every timestamp a mock writes reads from here, so a suite moves time instead of\n * sleeping: appointment windows, result delays and expiries become reachable in\n * milliseconds. A frozen clock also makes timestamps reproducible from a seed.\n */\nexport type ClockState = {\n /** Current epoch milliseconds. */\n now: number\n /** True while time does not advance on its own. */\n frozen: boolean\n /** Milliseconds this clock adds to its underlying source. */\n offsetMs: number\n}\n\nexport type Clock = {\n now(): number\n /** Pin the clock to an exact instant, keeping it frozen if it already was. */\n set(epochMs: number): void\n /** Move the clock forward, or back with a negative delta. */\n advance(deltaMs: number): void\n /** Stop time at the current instant. */\n freeze(): void\n /** Resume from the current instant. */\n unfreeze(): void\n /** Drop back to the underlying source, live. */\n reset(): void\n state(): ClockState\n}\n\n/** A {@link Clock} over `source` (default `Date.now`), live and unfrozen. */\nexport const createClock = (source: () => number = Date.now): Clock => {\n let offsetMs = 0\n let frozenAt: number | undefined\n const now = () => frozenAt ?? source() + offsetMs\n return {\n now,\n set: (epochMs) => {\n if (frozenAt !== undefined) frozenAt = epochMs\n else offsetMs = epochMs - source()\n },\n advance: (deltaMs) => {\n if (frozenAt !== undefined) frozenAt += deltaMs\n else offsetMs += deltaMs\n },\n freeze: () => {\n frozenAt = now()\n },\n unfreeze: () => {\n if (frozenAt === undefined) return\n offsetMs = frozenAt - source()\n frozenAt = undefined\n },\n reset: () => {\n offsetMs = 0\n frozenAt = undefined\n },\n state: () => ({ now: now(), frozen: frozenAt !== undefined, offsetMs }),\n }\n}\n", "import type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\n\n/** Every stored record carries a monotonically increasing sequence for stable ordering. */\nexport type Stored<T> = { seq: number; value: T }\n\nexport type ListRecordsOptions<T> = {\n /** Keep only records passing the predicate. */\n where?: (value: T, seq: number) => boolean\n /** Sort order; default newest first. */\n order?: \"newest\" | \"oldest\"\n}\n\ntype RecordRow = { id: string; seq: number; value: string }\n\n/**\n * A SQLite-backed table of JSON records addressed by id. Ordering is by insertion\n * sequence, never by id lexicographic order, so list semantics stay stable.\n */\nexport class Collection<T> {\n constructor(\n private readonly sqlite: SqliteClient,\n private readonly namespace: string,\n private readonly name: string,\n ) {}\n\n private bumpCollectionSeq(): number {\n const row = this.sqlite\n .prepare(\n \"SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'collection'\",\n )\n .get<{ value: number }>(this.namespace, this.name)\n const next = (row?.value ?? 0) + 1\n this.sqlite\n .prepare(\n `INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, 'collection', ?)\n ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`,\n )\n .run(this.namespace, this.name, next)\n return next\n }\n\n nextSequence(): number {\n return this.sqlite.transaction(() => this.bumpCollectionSeq())\n }\n\n get(id: string): T | undefined {\n const row = this.sqlite\n .prepare(\n \"SELECT value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?\",\n )\n .get<{ value: string }>(this.namespace, this.name, id)\n if (!row) return undefined\n return (JSON.parse(row.value) as Stored<T>).value\n }\n\n has(id: string): boolean {\n const row = this.sqlite\n .prepare(\n \"SELECT 1 AS ok FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?\",\n )\n .get<{ ok: number }>(this.namespace, this.name, id)\n return row !== undefined\n }\n\n /** Insert a new record, assigning it the next sequence number. */\n insert(id: string, value: T): Stored<T> {\n return this.sqlite.transaction(() => {\n const seq = this.bumpCollectionSeq()\n const stored = { seq, value }\n this.sqlite\n .prepare(\n `INSERT INTO mockingbird_records (namespace, collection, id, seq, value)\n VALUES (?, ?, ?, ?, ?)\n ON CONFLICT(namespace, collection, id) DO UPDATE SET seq = excluded.seq, value = excluded.value`,\n )\n .run(this.namespace, this.name, id, seq, JSON.stringify(stored))\n return stored\n })\n }\n\n /** Replace an existing record's value, keeping its position. */\n update(id: string, value: T): Stored<T> | undefined {\n return this.sqlite.transaction(() => {\n const row = this.sqlite\n .prepare(\n \"SELECT seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?\",\n )\n .get<{ seq: number; value: string }>(this.namespace, this.name, id)\n if (!row) return undefined\n const stored = { seq: row.seq, value }\n this.sqlite\n .prepare(\n \"UPDATE mockingbird_records SET value = ? WHERE namespace = ? AND collection = ? AND id = ?\",\n )\n .run(JSON.stringify(stored), this.namespace, this.name, id)\n return stored\n })\n }\n\n delete(id: string): boolean {\n const result = this.sqlite\n .prepare(\"DELETE FROM mockingbird_records WHERE namespace = ? AND collection = ? AND id = ?\")\n .run(this.namespace, this.name, id)\n return result.changes > 0\n }\n\n /** How many records the collection holds, without reading them. */\n count(): number {\n const row = this.sqlite\n .prepare(\n \"SELECT COUNT(*) AS n FROM mockingbird_records WHERE namespace = ? AND collection = ?\",\n )\n .get<{ n: number }>(this.namespace, this.name)\n return Number(row?.n ?? 0)\n }\n\n list(options: ListRecordsOptions<T> = {}): Array<Stored<T> & { id: string }> {\n const rows = this.sqlite\n .prepare(\n \"SELECT id, seq, value FROM mockingbird_records WHERE namespace = ? AND collection = ?\",\n )\n .all<RecordRow>(this.namespace, this.name)\n const out: Array<Stored<T> & { id: string }> = []\n for (const row of rows) {\n const stored = JSON.parse(row.value) as Stored<T>\n if (options.where && !options.where(stored.value, stored.seq)) continue\n out.push({ id: row.id, seq: stored.seq, value: stored.value })\n }\n out.sort((a, b) => (options.order === \"oldest\" ? a.seq - b.seq : b.seq - a.seq))\n return out\n }\n}\n", "import type { Clock } from \"./clock.js\"\nimport type { FaultRegistry, FaultRule } from \"./faults.js\"\nimport type { Journal } from \"./journal.js\"\nimport type { Metrics } from \"./metrics.js\"\n\n/** Unauthenticated readiness probe, served ahead of every vendor auth gate. */\nexport const HEALTH_PATH = \"/health\"\n/** Prefix of every control-plane route; never part of a vendor contract. */\nexport const ADMIN_PREFIX = \"/__admin\"\n/** Carries the admin key, which is separate from any vendor credential. */\nexport const ADMIN_KEY_HEADER = \"x-mockingbird-admin-key\"\n/** Selects the isolated namespace a request reads and writes. */\nexport const NAMESPACE_HEADER = \"x-mockingbird-namespace\"\n\nexport type AdminRequest = {\n request: Request\n url: URL\n /** `:param` segments of the matched route. */\n params: Record<string, string>\n /** Namespace the request targets: `?namespace=`, then the header, then the default. */\n namespace: string\n /** Parsed JSON body, or `undefined` when there is none. */\n body: unknown\n}\n\nexport type AdminRoute = (request: AdminRequest) => Response | Promise<Response>\n\n/**\n * Service-specific admin routes, keyed `METHOD /path` relative to `/__admin`, with\n * `:param` segments \u2014 e.g. `\"POST /orders/:id/transition\"`.\n */\nexport type AdminRoutes = Record<string, AdminRoute>\n\nexport type ControlContext = {\n name: string\n startedAt: number\n wallNow: () => number\n clock: Clock\n faults: FaultRegistry\n metrics: Metrics\n journal: Journal\n defaultNamespace: string\n namespaces(): string[]\n reset(namespace: string | \"*\"): Promise<void>\n timeTravel: {\n checkpoint(\n namespace: string,\n branch: string,\n ): { id: string; branch: string; parent: string | null; at: number; records?: number }\n branch(\n name: string,\n options: { namespace: string; at?: string },\n ): { id: string; branch: string; parent: string | null; at: number }\n checkout(checkpoint: string, options: { namespace: string; branch: string }): void\n retain(namespace: string, checkpoint: string): void\n release(namespace: string, checkpoint: string): boolean\n inspect(namespace: string): {\n branches: Readonly<Record<string, string>>\n checkpoints: readonly { id: string; branch: string; parent: string | null; at: number }[]\n }\n }\n /** Extra fields for `GET /health`, such as the loaded corpus version. */\n describe(): Record<string, unknown>\n routes: AdminRoutes\n adminKey: string | undefined\n /** Expand a named fault preset; enables `POST /faults {\"preset\": \"<name>\"}`. */\n applyPreset?(name: string, namespace: string, overrides: Partial<FaultRule>): FaultRule[]\n}\n\nexport type ControlPlane = {\n /** The control-plane response for `request`, or `undefined` for a vendor request. */\n handle(request: Request): Promise<Response | undefined>\n /**\n * Namespace a vendor request targets, from {@link NAMESPACE_HEADER}. Only admin routes\n * also accept `?namespace=`, so a vendor query parameter of that name can never\n * silently reroute a request.\n */\n namespaceOf(request: Request): string\n}\n\nconst json = (status: number, body: unknown): Response =>\n new Response(JSON.stringify(body), {\n status,\n headers: { \"content-type\": \"application/json\" },\n })\n\n/** Admin errors use one documented shape, distinct from any vendor's error body. */\nconst adminError = (status: number, message: string): Response =>\n json(status, { error: { type: \"mockingbird_admin\", message } })\n\nconst UNITS: Record<string, number> = {\n ms: 1,\n s: 1000,\n m: 60_000,\n h: 3_600_000,\n d: 86_400_000,\n}\n\n/** Milliseconds from a number, or a duration like `\"90s\"`, `\"15m\"`, `\"2h\"`, `\"3d\"`. */\nexport const parseDuration = (value: unknown): number | undefined => {\n if (typeof value === \"number\" && Number.isFinite(value)) return value\n if (typeof value !== \"string\") return undefined\n const match = /^(-?\\d+(?:\\.\\d+)?)\\s*(ms|s|m|h|d)$/.exec(value.trim())\n if (!match) return undefined\n return Number(match[1]) * (UNITS[match[2] as string] as number)\n}\n\n/** Epoch milliseconds from a number or an ISO-8601 string. */\nconst parseInstant = (value: unknown): number | undefined => {\n if (typeof value === \"number\" && Number.isFinite(value)) return value\n if (typeof value !== \"string\") return undefined\n const parsed = Date.parse(value)\n return Number.isNaN(parsed) ? undefined : parsed\n}\n\nconst matchRoute = (pattern: string, path: string): Record<string, string> | undefined => {\n const want = pattern.split(\"/\").filter(Boolean)\n const have = path.split(\"/\").filter(Boolean)\n if (want.length !== have.length) return undefined\n const params: Record<string, string> = {}\n for (let i = 0; i < want.length; i++) {\n const segment = want[i] as string\n const actual = have[i] as string\n if (segment.startsWith(\":\")) params[segment.slice(1)] = decodeURIComponent(actual)\n else if (segment !== actual) return undefined\n }\n return params\n}\n\nconst readJson = async (request: Request): Promise<unknown> => {\n const text = await request.text()\n if (text.trim() === \"\") return undefined\n return JSON.parse(text) as unknown\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\nexport const createControlPlane = (context: ControlContext): ControlPlane => {\n // Legacy snapshot ids are opaque aliases to pinned Timeline checkpoints. Timeline remains the\n // only history owner; this map carries no state value and can be removed with the alias.\n const snapshots = new Map<string, { namespace: string; checkpoint: string }>()\n let snapshotCounter = 0\n\n const headerNamespace = (request: Request): string =>\n request.headers.get(NAMESPACE_HEADER) ?? context.defaultNamespace\n const adminNamespace = (request: Request, url: URL): string =>\n url.searchParams.get(\"namespace\") ?? headerNamespace(request)\n\n const builtin: AdminRoutes = {\n \"GET /\": () =>\n json(200, {\n service: context.name,\n routes: [...Object.keys(builtin), ...Object.keys(context.routes)].sort(),\n }),\n\n \"POST /reset\": async ({ url, namespace }) => {\n const target = url.searchParams.get(\"all\") === \"1\" ? \"*\" : namespace\n await context.reset(target)\n return json(200, { status: \"ok\", reset: target === \"*\" ? context.namespaces() : [target] })\n },\n\n \"GET /namespaces\": () =>\n json(200, { default: context.defaultNamespace, namespaces: context.namespaces() }),\n\n \"GET /clock\": () => json(200, context.clock.state()),\n \"POST /clock\": ({ body }) => {\n if (!isRecord(body)) return adminError(400, \"expected a JSON object\")\n if (body.reset === true) context.clock.reset()\n if (body.set !== undefined) {\n const instant = parseInstant(body.set)\n if (instant === undefined) return adminError(400, \"set: expected epoch ms or ISO-8601\")\n context.clock.set(instant)\n }\n if (body.advance !== undefined) {\n const delta = parseDuration(body.advance)\n if (delta === undefined) return adminError(400, 'advance: expected ms or \"15m\"-style')\n context.clock.advance(delta)\n }\n if (body.freeze === true) context.clock.freeze()\n if (body.freeze === false) context.clock.unfreeze()\n return json(200, context.clock.state())\n },\n\n \"GET /faults\": () => json(200, { faults: context.faults.list() }),\n \"POST /faults\": ({ body, namespace }) => {\n if (isRecord(body) && typeof body.preset === \"string\") {\n if (!context.applyPreset) return adminError(400, `${context.name} has no fault presets`)\n const { preset, ...overrides } = body\n try {\n return json(201, {\n preset,\n rules: context.applyPreset(preset, namespace, overrides as Partial<FaultRule>),\n })\n } catch (error) {\n return adminError(404, error instanceof Error ? error.message : String(error))\n }\n }\n if (\n !isRecord(body) ||\n (typeof body.status !== \"number\" &&\n typeof body.delayMs !== \"number\" &&\n typeof body.latencyMs !== \"number\" &&\n body.drop !== true &&\n typeof body.effect !== \"string\")\n ) {\n return adminError(\n 400,\n \"a fault needs a numeric status, a delayMs/latencyMs, drop: true, an effect, or a preset\",\n )\n }\n const rule = {\n // Scoped to the caller's namespace unless it asks for every one, so one worker's\n // injected failure never lands on another's request.\n namespace,\n ...body,\n id: typeof body.id === \"string\" ? body.id : `fault_${context.faults.list().length + 1}`,\n } as FaultRule\n return json(201, context.faults.add(rule))\n },\n \"DELETE /faults\": ({ url }) => {\n const id = url.searchParams.get(\"id\")\n if (id === null) {\n context.faults.clear()\n return json(200, { status: \"ok\" })\n }\n return context.faults.remove(id)\n ? json(200, { status: \"ok\" })\n : adminError(404, `no fault ${id}`)\n },\n\n \"POST /snapshots\": ({ namespace }) => {\n const point = context.timeTravel.checkpoint(namespace, \"main\")\n context.timeTravel.retain(namespace, point.id)\n snapshotCounter++\n const id = `snap_${snapshotCounter}`\n snapshots.set(id, { namespace, checkpoint: point.id })\n return json(201, { id, namespace, records: point.records ?? 0 })\n },\n \"POST /snapshots/:id/restore\": ({ params, namespace }) => {\n const alias = snapshots.get(params.id as string)\n if (!alias) return adminError(404, `no snapshot ${params.id}`)\n if (alias.namespace !== namespace) {\n return adminError(409, `snapshot ${params.id} belongs to namespace ${alias.namespace}`)\n }\n context.timeTravel.checkout(alias.checkpoint, { namespace, branch: \"main\" })\n return json(200, { status: \"ok\", id: params.id, namespace })\n },\n \"DELETE /snapshots/:id\": ({ params }) => {\n const id = params.id as string\n const alias = snapshots.get(id)\n if (!alias) return adminError(404, `no snapshot ${id}`)\n snapshots.delete(id)\n context.timeTravel.release(alias.namespace, alias.checkpoint)\n return json(200, { status: \"ok\" })\n },\n\n \"GET /timeline\": ({ namespace }) => json(200, context.timeTravel.inspect(namespace)),\n \"POST /checkpoints\": ({ body, namespace }) => {\n const branch = isRecord(body) && typeof body.branch === \"string\" ? body.branch : \"main\"\n try {\n return json(201, context.timeTravel.checkpoint(namespace, branch))\n } catch (error) {\n return adminError(409, error instanceof Error ? error.message : String(error))\n }\n },\n \"POST /branches/:name\": ({ params, body, namespace }) => {\n const at = isRecord(body) && typeof body.at === \"string\" ? body.at : undefined\n try {\n return json(\n 201,\n context.timeTravel.branch(params.name as string, {\n namespace,\n ...(at !== undefined ? { at } : {}),\n }),\n )\n } catch (error) {\n return adminError(409, error instanceof Error ? error.message : String(error))\n }\n },\n \"POST /branches/:name/checkout\": ({ params, body, namespace }) => {\n if (!isRecord(body) || typeof body.checkpoint !== \"string\") {\n return adminError(400, 'expected {\"checkpoint\":\"cp_...\"}')\n }\n try {\n context.timeTravel.checkout(body.checkpoint, {\n namespace,\n branch: params.name as string,\n })\n return json(200, { status: \"ok\", branch: params.name, checkpoint: body.checkpoint })\n } catch (error) {\n return adminError(409, error instanceof Error ? error.message : String(error))\n }\n },\n\n \"GET /requests\": ({ url, namespace }) => {\n const status = url.searchParams.get(\"status\")\n const since = url.searchParams.get(\"since\")\n const limit = url.searchParams.get(\"limit\")\n const sinceMs =\n since === null ? undefined : parseInstant(/^\\d+$/.test(since) ? Number(since) : since)\n if (since !== null && sinceMs === undefined) {\n return adminError(400, \"since: expected epoch ms or ISO-8601\")\n }\n if (status !== null && !/^\\d{3}$/.test(status))\n return adminError(400, \"status: expected an HTTP status\")\n if (limit !== null && !/^\\d+$/.test(limit)) return adminError(400, \"limit: expected a count\")\n const operationId = url.searchParams.get(\"operationId\")\n const everyNamespace = url.searchParams.get(\"all\") === \"1\"\n return json(200, {\n size: context.journal.size,\n requests: context.journal.list({\n ...(everyNamespace ? {} : { namespace }),\n ...(operationId !== null ? { operationId } : {}),\n ...(status !== null ? { status: Number(status) } : {}),\n ...(sinceMs !== undefined ? { since: sinceMs } : {}),\n ...(limit !== null ? { limit: Number(limit) } : {}),\n }),\n })\n },\n \"DELETE /requests\": ({ url, namespace }) => {\n context.journal.clear(url.searchParams.get(\"all\") === \"1\" ? undefined : namespace)\n return json(200, { status: \"ok\" })\n },\n\n \"GET /metrics\": () => json(200, context.metrics.report()),\n \"DELETE /metrics\": () => {\n context.metrics.reset()\n return json(200, { status: \"ok\" })\n },\n }\n\n const routes = [...Object.entries(context.routes), ...Object.entries(builtin)].map(\n ([key, handler]) => {\n const space = key.indexOf(\" \")\n return { method: key.slice(0, space), pattern: key.slice(space + 1), handler }\n },\n )\n\n return {\n namespaceOf: headerNamespace,\n async handle(request) {\n const url = new URL(request.url)\n if (url.pathname === HEALTH_PATH && request.method === \"GET\") {\n return json(200, {\n status: \"ok\",\n service: context.name,\n uptimeMs: context.wallNow() - context.startedAt,\n clock: context.clock.state(),\n namespaces: context.namespaces().length,\n ...context.describe(),\n })\n }\n if (url.pathname !== ADMIN_PREFIX && !url.pathname.startsWith(`${ADMIN_PREFIX}/`)) {\n return undefined\n }\n if (\n context.adminKey !== undefined &&\n request.headers.get(ADMIN_KEY_HEADER) !== context.adminKey\n ) {\n return adminError(401, `missing or wrong ${ADMIN_KEY_HEADER}`)\n }\n const path = url.pathname.slice(ADMIN_PREFIX.length) || \"/\"\n for (const route of routes) {\n if (route.method !== request.method) continue\n const params = matchRoute(route.pattern, path)\n if (!params) continue\n let body: unknown\n try {\n body = await readJson(request)\n } catch {\n return adminError(400, \"request body is not valid JSON\")\n }\n return route.handler({\n request,\n url,\n params,\n namespace: adminNamespace(request, url),\n body,\n })\n }\n return adminError(\n 404,\n `no admin route ${request.method} ${path}; GET ${ADMIN_PREFIX} lists them`,\n )\n },\n }\n}\n", "/**\n * Reading the vendor credential a request carries.\n *\n * Several vendor SDKs (Stripe, AWS, PostHog, Twilio) cannot add a namespace header, so a\n * runtime can also pick a request's namespace from its credential: a suite maps each\n * worker's API key, token or account SID to a namespace through `PUT /__admin/credentials`.\n * These helpers pull the credential out of the usual carriers.\n */\n\n/** The token after `Bearer `, or `undefined`. */\nexport const bearerToken = (request: Request): string | undefined => {\n const header = request.headers.get(\"authorization\")\n if (!header) return undefined\n const match = /^Bearer\\s+(.+)$/i.exec(header.trim())\n return match?.[1]?.trim() || undefined\n}\n\nexport type BasicCredentials = { username: string; password: string }\n\n/** `{ username, password }` from `Authorization: Basic \u2026`, or `undefined`. */\nexport const basicAuth = (request: Request): BasicCredentials | undefined => {\n const header = request.headers.get(\"authorization\")\n if (!header) return undefined\n const match = /^Basic\\s+(.+)$/i.exec(header.trim())\n if (!match?.[1]) return undefined\n let decoded: string\n try {\n decoded = atob(match[1].trim())\n } catch {\n return undefined\n }\n const colon = decoded.indexOf(\":\")\n if (colon < 0) return { username: decoded, password: \"\" }\n return { username: decoded.slice(0, colon), password: decoded.slice(colon + 1) }\n}\n\n/**\n * The access key id of an AWS SigV4-signed request (`Credential=AKID/date/region/service/\u2026`),\n * from the `Authorization` header or a presigned `X-Amz-Credential` query parameter.\n */\nexport const sigV4AccessKeyId = (request: Request): string | undefined => {\n const header = request.headers.get(\"authorization\")\n const fromHeader = header ? /Credential=([^/,\\s]+)\\//.exec(header)?.[1] : undefined\n if (fromHeader) return fromHeader\n const query = new URL(request.url).searchParams.get(\"X-Amz-Credential\")\n return query ? (query.split(\"/\")[0] ?? undefined) : undefined\n}\n\n/** The credential in any of the common carriers: Bearer, Basic username, SigV4, or `x-api-key`. */\nexport const anyCredential = (request: Request): string | undefined =>\n bearerToken(request) ??\n basicAuth(request)?.username ??\n sigV4AccessKeyId(request) ??\n request.headers.get(\"x-api-key\") ??\n undefined\n\n/** Credential \u2192 namespace mapping behind `PUT /__admin/credentials`. */\nexport type CredentialRegistry = {\n set(credential: string, namespace: string): void\n get(credential: string): string | undefined\n remove(credential: string): boolean\n clear(): void\n entries(): { credential: string; namespace: string }[]\n}\n\nexport const createCredentialRegistry = (): CredentialRegistry => {\n const map = new Map<string, string>()\n return {\n set: (credential, namespace) => {\n map.set(credential, namespace)\n },\n get: (credential) => map.get(credential),\n remove: (credential) => map.delete(credential),\n clear: () => map.clear(),\n entries: () =>\n [...map]\n .map(([credential, namespace]) => ({ credential, namespace }))\n .sort((a, b) => a.credential.localeCompare(b.credential)),\n }\n}\n\n/** A credential shown in admin output: enough to recognise it, never the whole secret. */\nexport const maskCredential = (credential: string): string =>\n credential.length <= 8\n ? `${credential.slice(0, 2)}\u2026`\n : `${credential.slice(0, 6)}\u2026${credential.slice(-2)}`\n", "/**\n * Seeded pseudo-random numbers, so anything a mock invents \u2014 ids, jitter, which\n * request a percentage fault hits \u2014 is reproducible from a seed.\n *\n * mulberry32: small, fast, and stable across runtimes, which matters more here\n * than statistical quality.\n */\nexport type Rng = {\n /** Next value in `[0, 1)`. */\n next(): number\n /** Next integer in `[min, max]`. */\n int(min: number, max: number): number\n /** Restart the stream from its seed. */\n reset(): void\n /** Serializable engine state used by deterministic checkpoints. */\n state(): number\n /** Restore a state previously returned by {@link state}. */\n setState(state: number): void\n seed: number\n}\n\n/** Hash an arbitrary string into a 32-bit seed, so callers can seed by name. */\nexport const seedFrom = (value: string): number => {\n let hash = 2166136261\n for (let i = 0; i < value.length; i++) {\n hash ^= value.charCodeAt(i)\n hash = Math.imul(hash, 16777619)\n }\n return hash >>> 0\n}\n\nexport const createRng = (seed: number | string = 0): Rng => {\n const numeric = typeof seed === \"string\" ? seedFrom(seed) : seed >>> 0\n let state = numeric\n const next = () => {\n state = (state + 0x6d2b79f5) >>> 0\n let t = state\n t = Math.imul(t ^ (t >>> 15), t | 1)\n t ^= t + Math.imul(t ^ (t >>> 7), t | 61)\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296\n }\n return {\n next,\n int: (min, max) => min + Math.floor(next() * (max - min + 1)),\n reset: () => {\n state = numeric\n },\n state: () => state,\n setState: (next) => {\n if (!Number.isSafeInteger(next) || next < 0 || next > 0xffffffff) {\n throw new RangeError(\"rng state must be an unsigned 32-bit integer\")\n }\n state = next >>> 0\n },\n seed: numeric,\n }\n}\n", "import { createRng, type Rng } from \"./rng.js\"\n\n/**\n * A deliberate failure injected in front of an operation.\n *\n * This is how a suite reaches the vendor's failure modes without the vendor: the\n * quota error that only appears when a shared sandbox is full, the 429 that only\n * appears under load, the 5xx that proves a retry path works.\n */\nexport type FaultRule = {\n /** Stable id, so a suite can retire exactly the rule it added. */\n id: string\n /** Fault only this operation. Omit to match every operation. */\n operationId?: string\n /** Fault only this HTTP method, case-insensitive. Omit to match every method. */\n method?: string\n /** Fault only paths starting with this prefix. Omit to match every path. */\n pathPrefix?: string\n /**\n * Fault only this namespace. Omit (or `\"*\"`) to fault every namespace \u2014 which is what\n * an in-process caller usually wants, and what a parallel worker usually does not:\n * rules added through `POST /__admin/faults` default to the calling namespace.\n */\n namespace?: string\n /**\n * Status of the injected response. Omit for a rule that only delays (`delayMs` /\n * `latencyMs`), only drops the connection (`drop`), or only switches on an `effect`:\n * the request then still reaches the service.\n */\n status?: number\n /** Response body, serialized as JSON. A string is sent as-is. */\n body?: unknown\n headers?: Record<string, string>\n /** Retire the rule after this many faults. Omit to keep it until removed. */\n count?: number\n /** Fault this fraction of matching requests, `0`\u2013`1`. Default `1`. */\n rate?: number\n /** Hold the response back this long, to exercise timeouts. */\n delayMs?: number\n /** Alias of `delayMs`. */\n latencyMs?: number\n /**\n * Drop the connection instead of answering: an in-process `fetch` rejects with a\n * `TypeError`, and a served mock destroys the socket. Models \"unknown outcome\" failures.\n */\n drop?: boolean\n /**\n * A named service behaviour to switch on for the matching request instead of (or\n * before) a canned response, e.g. `created_but_500` or `numeric_tracking_id`. Services\n * read it with `faultEffects(request)`.\n */\n effect?: string\n /** Parameters for `effect`. */\n params?: Record<string, unknown>\n /** From the preset this rule was expanded from, if any. */\n preset?: string\n}\n\n/** A fault that fired for one request. */\nexport type FaultHit = {\n id: string\n /** The injected response; absent when the rule only delays, drops, or sets an effect. */\n response?: Response\n drop?: boolean\n effect?: { name: string; params: Record<string, unknown> }\n}\n\n/**\n * A named, documented fault a suite switches on by name\n * (`POST /__admin/faults {\"preset\": \"rate_limited\"}`): one or more rules, and optionally a\n * webhook delivery fault.\n */\nexport type FaultPreset = {\n description: string\n rules?: Omit<FaultRule, \"id\">[]\n webhook?: { mode: \"duplicate\" | \"reorder\" | \"drop\"; count?: number }\n}\n\n/** What a request looks like to the fault matcher. */\nexport type FaultCandidate = {\n operationId: string | undefined\n method: string\n path: string\n namespace: string\n}\n\nexport type FaultRegistry = {\n add(rule: FaultRule): FaultRule\n list(): (FaultRule & { remaining: number | null; hits: number })[]\n remove(id: string): boolean\n clear(): void\n /**\n * Every fault this request should get, in rule order, stopping at the first that answers\n * or drops (effect-only and delay-only rules let later rules match too). Consumes one of\n * each matching rule's remaining uses.\n */\n take(candidate: FaultCandidate): Promise<FaultHit[]>\n}\n\ntype Entry = { rule: FaultRule; remaining: number | null; hits: number }\n\nconst matches = (rule: FaultRule, candidate: FaultCandidate): boolean => {\n if (\n rule.namespace !== undefined &&\n rule.namespace !== \"*\" &&\n rule.namespace !== candidate.namespace\n ) {\n return false\n }\n if (rule.operationId !== undefined && rule.operationId !== candidate.operationId) return false\n if (rule.method !== undefined && rule.method.toUpperCase() !== candidate.method.toUpperCase()) {\n return false\n }\n if (rule.pathPrefix !== undefined && !candidate.path.startsWith(rule.pathPrefix)) return false\n return true\n}\n\nconst faultResponse = (rule: FaultRule): Response => {\n const status = rule.status ?? 500\n const headers = { \"content-type\": \"application/json\", ...rule.headers }\n if (typeof rule.body === \"string\") return new Response(rule.body, { status, headers })\n if (rule.body === null) return new Response(null, { status, headers: rule.headers ?? {} })\n const body = rule.body === undefined ? { detail: \"Injected by Mockingbird\" } : rule.body\n return new Response(JSON.stringify(body), { status, headers })\n}\n\n/**\n * Rules are matched in the order they were added, so a narrow rule added first\n * wins over a later catch-all. `rate` draws from `rng`, which is seeded, so a\n * partial-failure run replays identically.\n */\nexport const createFaultRegistry = (\n rng: Rng = createRng(0),\n sleep: (ms: number) => Promise<void> = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),\n): FaultRegistry => {\n const entries: Entry[] = []\n return {\n add(rule) {\n const existing = entries.findIndex((e) => e.rule.id === rule.id)\n const entry: Entry = { rule, remaining: rule.count ?? null, hits: 0 }\n if (existing >= 0) entries[existing] = entry\n else entries.push(entry)\n return rule\n },\n list: () => entries.map((e) => ({ ...e.rule, remaining: e.remaining, hits: e.hits })),\n remove(id) {\n const index = entries.findIndex((e) => e.rule.id === id)\n if (index < 0) return false\n entries.splice(index, 1)\n return true\n },\n clear() {\n entries.length = 0\n },\n async take(candidate) {\n const hits: FaultHit[] = []\n for (const entry of entries) {\n if (entry.remaining === 0) continue\n if (!matches(entry.rule, candidate)) continue\n const rate = entry.rule.rate ?? 1\n // Draw even when the rule always fires, so a seeded stream stays aligned.\n if (rng.next() >= rate) continue\n entry.hits++\n if (entry.remaining !== null) entry.remaining--\n const delay = entry.rule.delayMs ?? entry.rule.latencyMs\n if (delay !== undefined && delay > 0) {\n await sleep(delay)\n }\n const hit: FaultHit = { id: entry.rule.id }\n if (entry.rule.effect !== undefined) {\n hit.effect = { name: entry.rule.effect, params: entry.rule.params ?? {} }\n }\n if (entry.rule.drop === true) hit.drop = true\n else if (entry.rule.status !== undefined) hit.response = faultResponse(entry.rule)\n hits.push(hit)\n if (hit.drop || hit.response) break\n }\n return hits\n },\n }\n}\n", "import type { OpenAPIDocument, ReferenceObject } from \"./types.js\"\n\nexport class OpenAPIReferenceError extends Error {\n constructor(readonly ref: string) {\n super(`unresolvable $ref: ${ref}`)\n this.name = \"OpenAPIReferenceError\"\n }\n}\n\nconst unescapePointer = (segment: string) => segment.replace(/~1/g, \"/\").replace(/~0/g, \"~\")\n\n/** True when `value` is a `{ $ref }` object. */\nexport const isReference = (value: unknown): value is ReferenceObject =>\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { $ref?: unknown }).$ref === \"string\"\n\n/** Resolve a local JSON pointer reference (`#/components/schemas/customer`) inside `document`. */\nexport const resolveRef = (document: OpenAPIDocument, ref: string): unknown => {\n if (!ref.startsWith(\"#/\")) throw new OpenAPIReferenceError(ref)\n let cursor: unknown = document\n for (const raw of ref.slice(2).split(\"/\")) {\n const segment = unescapePointer(raw)\n if (typeof cursor !== \"object\" || cursor === null || !(segment in cursor)) {\n throw new OpenAPIReferenceError(ref)\n }\n cursor = (cursor as Record<string, unknown>)[segment]\n }\n if (cursor === undefined) throw new OpenAPIReferenceError(ref)\n return cursor\n}\n\n/**\n * Follow `$ref` chains until a concrete object is reached. Guards against cycles.\n * Sibling keys next to `$ref` are ignored, as in OpenAPI 3.0/3.1 for non-schema objects.\n */\nexport const deref = <T>(document: OpenAPIDocument, value: T | ReferenceObject): T => {\n let current: unknown = value\n const seen = new Set<string>()\n while (isReference(current)) {\n if (seen.has(current.$ref)) throw new OpenAPIReferenceError(`${current.$ref} (cycle)`)\n seen.add(current.$ref)\n current = resolveRef(document, current.$ref)\n }\n return current as T\n}\n\n/** The component name at the end of a `#/components/<kind>/<name>` reference, if any. */\nexport const componentNameOf = (ref: string): string | undefined => {\n const match = /^#\\/components\\/[^/]+\\/(.+)$/.exec(ref)\n return match?.[1] === undefined ? undefined : unescapePointer(match[1])\n}\n", "/**\n * The slice of OpenAPI 3.1 (and JSON Schema 2020-12) Mockingbird understands.\n * Unknown keys (including `x-*` extensions) are preserved on every object.\n */\n\nexport type JsonPrimitive = string | number | boolean | null\nexport type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue }\n\nexport type ReferenceObject = { $ref: string; description?: string; summary?: string }\n\nexport type SchemaType = \"string\" | \"number\" | \"integer\" | \"boolean\" | \"object\" | \"array\" | \"null\"\n\nexport type SchemaObject = {\n $ref?: string\n type?: SchemaType | SchemaType[]\n title?: string\n description?: string\n format?: string\n enum?: JsonValue[]\n const?: JsonValue\n default?: JsonValue\n example?: JsonValue\n examples?: JsonValue[]\n nullable?: boolean\n deprecated?: boolean\n readOnly?: boolean\n writeOnly?: boolean\n minimum?: number\n maximum?: number\n exclusiveMinimum?: number\n exclusiveMaximum?: number\n multipleOf?: number\n minLength?: number\n maxLength?: number\n pattern?: string\n minItems?: number\n maxItems?: number\n uniqueItems?: boolean\n items?: SchemaObject\n prefixItems?: SchemaObject[]\n minProperties?: number\n maxProperties?: number\n required?: string[]\n properties?: Record<string, SchemaObject>\n additionalProperties?: boolean | SchemaObject\n propertyNames?: SchemaObject\n oneOf?: SchemaObject[]\n anyOf?: SchemaObject[]\n allOf?: SchemaObject[]\n not?: SchemaObject\n discriminator?: { propertyName: string; mapping?: Record<string, string> }\n [extension: `x-${string}`]: unknown\n}\n\nexport type ParameterLocation = \"path\" | \"query\" | \"header\" | \"cookie\"\n\nexport type ParameterObject = {\n name: string\n in: ParameterLocation\n description?: string\n required?: boolean\n deprecated?: boolean\n style?: string\n explode?: boolean\n schema?: SchemaObject\n content?: Record<string, MediaTypeObject>\n example?: JsonValue\n [extension: `x-${string}`]: unknown\n}\n\nexport type MediaTypeObject = {\n schema?: SchemaObject\n example?: JsonValue\n examples?: Record<string, unknown>\n encoding?: Record<string, unknown>\n [extension: `x-${string}`]: unknown\n}\n\nexport type RequestBodyObject = {\n description?: string\n required?: boolean\n content: Record<string, MediaTypeObject>\n [extension: `x-${string}`]: unknown\n}\n\nexport type HeaderObject = {\n description?: string\n required?: boolean\n schema?: SchemaObject\n [extension: `x-${string}`]: unknown\n}\n\nexport type ResponseObject = {\n description: string\n headers?: Record<string, HeaderObject | ReferenceObject>\n content?: Record<string, MediaTypeObject>\n [extension: `x-${string}`]: unknown\n}\n\nexport type ResponsesObject = Record<string, ResponseObject | ReferenceObject>\n\nexport type SecurityRequirementObject = Record<string, string[]>\n\nexport type OperationObject = {\n operationId?: string\n summary?: string\n description?: string\n tags?: string[]\n deprecated?: boolean\n parameters?: Array<ParameterObject | ReferenceObject>\n requestBody?: RequestBodyObject | ReferenceObject\n responses: ResponsesObject\n security?: SecurityRequirementObject[]\n [extension: `x-${string}`]: unknown\n}\n\nexport const HTTP_METHODS = [\n \"get\",\n \"put\",\n \"post\",\n \"delete\",\n \"options\",\n \"head\",\n \"patch\",\n \"trace\",\n] as const\nexport type HttpMethod = (typeof HTTP_METHODS)[number]\n\nexport type PathItemObject = {\n summary?: string\n description?: string\n parameters?: Array<ParameterObject | ReferenceObject>\n [extension: `x-${string}`]: unknown\n} & Partial<Record<HttpMethod, OperationObject>>\n\nexport type SecuritySchemeObject = {\n type: \"apiKey\" | \"http\" | \"oauth2\" | \"openIdConnect\" | \"mutualTLS\"\n description?: string\n name?: string\n in?: ParameterLocation\n scheme?: string\n bearerFormat?: string\n flows?: Record<string, unknown>\n openIdConnectUrl?: string\n [extension: `x-${string}`]: unknown\n}\n\nexport type ComponentsObject = {\n schemas?: Record<string, SchemaObject>\n responses?: Record<string, ResponseObject>\n parameters?: Record<string, ParameterObject>\n requestBodies?: Record<string, RequestBodyObject>\n headers?: Record<string, HeaderObject>\n securitySchemes?: Record<string, SecuritySchemeObject>\n [extension: `x-${string}`]: unknown\n}\n\nexport type ServerObject = {\n url: string\n description?: string\n variables?: Record<string, unknown>\n [extension: `x-${string}`]: unknown\n}\n\nexport type InfoObject = {\n title: string\n version: string\n description?: string\n [extension: `x-${string}`]: unknown\n}\n\nexport type OpenAPIDocument = {\n openapi: string\n info: InfoObject\n servers?: ServerObject[]\n paths: Record<string, PathItemObject>\n components?: ComponentsObject\n security?: SecurityRequirementObject[]\n tags?: Array<{ name: string; description?: string }>\n [extension: `x-${string}`]: unknown\n}\n\n/** One concrete HTTP operation discovered in a document. */\nexport type Operation = {\n operationId: string\n method: HttpMethod\n /** OpenAPI path template, e.g. `/v1/customers/{customer}`. */\n path: string\n operation: OperationObject\n /** Path-level parameters merged with operation-level ones (operation wins), `$ref`s resolved. */\n parameters: ParameterObject[]\n requestBody: RequestBodyObject | undefined\n responses: Record<string, ResponseObject>\n}\n", "import { deref, isReference, resolveRef } from \"./refs.js\"\nimport {\n HTTP_METHODS,\n type HttpMethod,\n type OpenAPIDocument,\n type Operation,\n type ParameterObject,\n type PathItemObject,\n type RequestBodyObject,\n type ResponseObject,\n} from \"./types.js\"\n\nexport class OpenAPIDocumentError extends Error {\n constructor(readonly issues: string[]) {\n super(`invalid OpenAPI document:\\n${issues.map((issue) => ` - ${issue}`).join(\"\\n\")}`)\n this.name = \"OpenAPIDocumentError\"\n }\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\n/**\n * Accept an already-parsed JSON/YAML value and return it typed as an {@link OpenAPIDocument}.\n * Performs the structural checks Mockingbird relies on (see {@link validateOpenAPIDocument}) and\n * throws {@link OpenAPIDocumentError} listing every problem.\n */\nexport const parseOpenAPIDocument = (value: unknown): OpenAPIDocument => {\n const issues: string[] = []\n if (!isRecord(value)) throw new OpenAPIDocumentError([\"document must be an object\"])\n if (typeof value.openapi !== \"string\" || !/^3\\.[01]\\./.test(value.openapi)) {\n issues.push(\n `openapi must be a 3.0.x or 3.1.x version string, got ${JSON.stringify(value.openapi)}`,\n )\n }\n if (\n !isRecord(value.info) ||\n typeof value.info.title !== \"string\" ||\n typeof value.info.version !== \"string\"\n ) {\n issues.push(\"info.title and info.version are required strings\")\n }\n if (!isRecord(value.paths)) issues.push(\"paths must be an object\")\n if (issues.length > 0) throw new OpenAPIDocumentError(issues)\n const document = value as unknown as OpenAPIDocument\n const problems = validateOpenAPIDocument(document)\n if (problems.length > 0) throw new OpenAPIDocumentError(problems)\n return document\n}\n\nconst walkRefs = (\n document: OpenAPIDocument,\n node: unknown,\n at: string,\n issues: string[],\n seen: Set<unknown>,\n) => {\n if (typeof node !== \"object\" || node === null || seen.has(node)) return\n seen.add(node)\n if (isReference(node)) {\n try {\n resolveRef(document, node.$ref)\n } catch {\n issues.push(`${at}: unresolvable $ref ${node.$ref}`)\n }\n }\n for (const [key, child] of Object.entries(node))\n walkRefs(document, child, `${at}/${key}`, issues, seen)\n}\n\nconst templateParams = (path: string) =>\n [...path.matchAll(/\\{([^}]+)\\}/g)].map((m) => m[1] as string)\n\n/**\n * Mockingbird's document rules:\n * - every operation has a unique `operationId`\n * - every `$ref` resolves\n * - every `{param}` in a path template has a matching required path parameter\n * - every path parameter appears in the template\n */\nexport const validateOpenAPIDocument = (document: OpenAPIDocument): string[] => {\n const issues: string[] = []\n walkRefs(document, document, \"#\", issues, new Set())\n if (issues.length > 0) return issues\n const seenIds = new Map<string, string>()\n for (const [path, item] of Object.entries(document.paths)) {\n if (!isRecord(item)) {\n issues.push(`paths.${path}: must be an object`)\n continue\n }\n const inTemplate = new Set(templateParams(path))\n for (const method of HTTP_METHODS) {\n const operation = item[method]\n if (operation === undefined) continue\n const label = `${method.toUpperCase()} ${path}`\n if (typeof operation.operationId !== \"string\" || operation.operationId.length === 0) {\n issues.push(`${label}: operationId is required`)\n continue\n }\n const previous = seenIds.get(operation.operationId)\n if (previous !== undefined)\n issues.push(`${label}: duplicate operationId ${operation.operationId} (also ${previous})`)\n seenIds.set(operation.operationId, label)\n if (!isRecord(operation.responses) || Object.keys(operation.responses).length === 0) {\n issues.push(`${label}: responses must declare at least one status`)\n }\n const parameters = mergeParameters(document, item, operation.parameters)\n const declared = new Set(parameters.filter((p) => p.in === \"path\").map((p) => p.name))\n for (const name of inTemplate) {\n if (!declared.has(name)) issues.push(`${label}: path parameter {${name}} is not declared`)\n }\n for (const parameter of parameters) {\n if (parameter.in === \"path\") {\n if (!inTemplate.has(parameter.name))\n issues.push(`${label}: path parameter ${parameter.name} is not in the template`)\n if (parameter.required !== true)\n issues.push(`${label}: path parameter ${parameter.name} must be required`)\n }\n }\n }\n }\n return issues\n}\n\nconst mergeParameters = (\n document: OpenAPIDocument,\n item: PathItemObject,\n own: PathItemObject[\"parameters\"],\n): ParameterObject[] => {\n const merged = new Map<string, ParameterObject>()\n for (const raw of item.parameters ?? []) {\n const parameter = deref<ParameterObject>(document, raw)\n merged.set(`${parameter.in}:${parameter.name}`, parameter)\n }\n for (const raw of own ?? []) {\n const parameter = deref<ParameterObject>(document, raw)\n merged.set(`${parameter.in}:${parameter.name}`, parameter)\n }\n return [...merged.values()]\n}\n\n/** Enumerate every operation in the document in path, then method order. */\nexport const listOperations = (document: OpenAPIDocument): Operation[] => {\n const operations: Operation[] = []\n for (const [path, item] of Object.entries(document.paths)) {\n for (const method of HTTP_METHODS) {\n const operation = item[method]\n if (operation?.operationId === undefined) continue\n const responses: Record<string, ResponseObject> = {}\n for (const [status, response] of Object.entries(operation.responses)) {\n responses[status] = deref<ResponseObject>(document, response)\n }\n operations.push({\n operationId: operation.operationId,\n method,\n path,\n operation,\n parameters: mergeParameters(document, item, operation.parameters),\n requestBody:\n operation.requestBody === undefined\n ? undefined\n : deref<RequestBodyObject>(document, operation.requestBody),\n responses,\n })\n }\n }\n return operations\n}\n\n/** Find one operation by id. */\nexport const findOperation = (\n document: OpenAPIDocument,\n operationId: string,\n): Operation | undefined =>\n listOperations(document).find((operation) => operation.operationId === operationId)\n\n/** Parameter names inside a path template, in order. */\nexport const pathTemplateParameters = templateParams\n\n/** Substitute `{name}` placeholders. Values are percent-encoded as path segments. */\nexport const expandPathTemplate = (template: string, values: Record<string, string>): string =>\n template.replace(/\\{([^}]+)\\}/g, (_, name: string) => {\n const value = values[name]\n if (value === undefined) throw new RangeError(`missing path parameter ${name}`)\n return encodeURIComponent(value)\n })\n\n/** The response object matching an HTTP status: exact match, then `2XX`-style range, then `default`. */\nexport const responseForStatus = (\n responses: Record<string, ResponseObject>,\n status: number,\n): ResponseObject | undefined =>\n responses[String(status)] ?? responses[`${Math.floor(status / 100)}XX`] ?? responses.default\n\nexport type { HttpMethod }\n", "import { resolveRef } from \"./refs.js\"\nimport type { JsonValue, OpenAPIDocument, SchemaObject, SchemaType } from \"./types.js\"\n\n/**\n * Resolve a schema's `$ref` (merging sibling keywords, as JSON Schema 2020-12 allows) and\n * normalise OpenAPI 3.0 `nullable` into a 3.1 type array.\n */\nexport const resolveSchema = (document: OpenAPIDocument, schema: SchemaObject): SchemaObject => {\n let current = schema\n const seen = new Set<string>()\n while (typeof current.$ref === \"string\") {\n const ref = current.$ref\n if (seen.has(ref)) break\n seen.add(ref)\n const { $ref: _ignored, ...siblings } = current\n const target = resolveRef(document, ref) as SchemaObject\n current = { ...target, ...siblings }\n }\n if (current.nullable === true) {\n const { nullable: _nullable, ...rest } = current\n const types = schemaTypes(rest)\n if (types.length > 0 && !types.includes(\"null\")) current = { ...rest, type: [...types, \"null\"] }\n else current = rest\n }\n return current\n}\n\n/** Declared JSON types of a schema (empty when unconstrained). */\nexport const schemaTypes = (schema: SchemaObject): SchemaType[] => {\n if (Array.isArray(schema.type)) return schema.type\n if (schema.type !== undefined) return [schema.type]\n const inferred: SchemaType[] = []\n if (schema.properties || schema.required || schema.additionalProperties !== undefined)\n inferred.push(\"object\")\n if (\n schema.items ||\n schema.prefixItems ||\n schema.minItems !== undefined ||\n schema.maxItems !== undefined\n )\n inferred.push(\"array\")\n if (\n schema.minLength !== undefined ||\n schema.maxLength !== undefined ||\n schema.pattern !== undefined\n )\n inferred.push(\"string\")\n if (\n schema.minimum !== undefined ||\n schema.maximum !== undefined ||\n schema.multipleOf !== undefined\n )\n inferred.push(\"number\")\n return inferred\n}\n\n/** The JSON type name of a runtime value. */\nexport const jsonTypeOf = (value: unknown): SchemaType | \"undefined\" => {\n if (value === null) return \"null\"\n if (Array.isArray(value)) return \"array\"\n switch (typeof value) {\n case \"string\":\n return \"string\"\n case \"boolean\":\n return \"boolean\"\n case \"number\":\n return Number.isInteger(value) ? \"integer\" : \"number\"\n case \"object\":\n return \"object\"\n default:\n return \"undefined\"\n }\n}\n\nexport type SchemaVisitor = (schema: SchemaObject, path: string[]) => void\n\n/**\n * Depth-first walk over a schema tree, resolving `$ref`s. Each resolved schema is visited once per\n * call: the annotation consumers (identities, refs, volatile/scope marks) only care that a node is\n * reachable, and visiting per path is exponential on densely cross-referenced documents.\n */\nexport const walkSchema = (\n document: OpenAPIDocument,\n schema: SchemaObject,\n visit: SchemaVisitor,\n path: string[] = [],\n) => {\n const seen = new Set<SchemaObject>()\n const go = (node: SchemaObject, at: string[]) => {\n const resolved = resolveSchema(document, node)\n if (seen.has(resolved)) return\n seen.add(resolved)\n visit(resolved, at)\n for (const [name, child] of Object.entries(resolved.properties ?? {}))\n go(child, [...at, \"properties\", name])\n if (typeof resolved.additionalProperties === \"object\")\n go(resolved.additionalProperties, [...at, \"additionalProperties\"])\n if (resolved.items) go(resolved.items, [...at, \"items\"])\n resolved.prefixItems?.forEach((child, i) => {\n go(child, [...at, \"prefixItems\", String(i)])\n })\n resolved.propertyNames && go(resolved.propertyNames, [...at, \"propertyNames\"])\n for (const keyword of [\"oneOf\", \"anyOf\", \"allOf\"] as const) {\n resolved[keyword]?.forEach((child, i) => {\n go(child, [...at, keyword, String(i)])\n })\n }\n resolved.not && go(resolved.not, [...at, \"not\"])\n }\n go(schema, path)\n}\nexport type ValidationError = { path: Array<string | number>; message: string }\n\nconst deepEqual = (a: unknown, b: unknown): boolean => {\n if (a === b) return true\n if (typeof a !== typeof b || a === null || b === null) return false\n if (Array.isArray(a)) {\n return Array.isArray(b) && a.length === b.length && a.every((item, i) => deepEqual(item, b[i]))\n }\n if (typeof a === \"object\" && typeof b === \"object\" && !Array.isArray(b)) {\n const ka = Object.keys(a as object)\n const kb = Object.keys(b as object)\n return (\n ka.length === kb.length &&\n ka.every((k) =>\n deepEqual((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k]),\n )\n )\n }\n return false\n}\n\nconst FORMAT_PATTERNS: Record<string, RegExp> = {\n uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,\n date: /^\\d{4}-\\d{2}-\\d{2}$/,\n \"date-time\": /^\\d{4}-\\d{2}-\\d{2}[Tt ]\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?([Zz]|[+-]\\d{2}:\\d{2})$/,\n email: /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/,\n uri: /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\\s]*$/,\n ipv4: /^(25[0-5]|2[0-4]\\d|1?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|1?\\d?\\d)){3}$/,\n}\n\nconst graphemeLength = (value: string) => [...value].length\n\n/**\n * Validate `value` against `schema`. Supports the JSON Schema subset Mockingbird generates from\n * (see `@crvouga/mockingbird-openapi-arbitrary`). Returns an empty array when valid.\n */\nexport const validateValue = (\n document: OpenAPIDocument,\n schema: SchemaObject,\n value: unknown,\n path: Array<string | number> = [],\n): ValidationError[] => {\n const errors: ValidationError[] = []\n const s = resolveSchema(document, schema)\n const fail = (message: string) => errors.push({ path, message })\n const actual = jsonTypeOf(value)\n if (actual === \"undefined\") {\n fail(\"value is undefined\")\n return errors\n }\n const types = schemaTypes(s)\n if (types.length > 0) {\n const ok = types.some((t) => t === actual || (t === \"number\" && actual === \"integer\"))\n if (!ok) {\n fail(`expected type ${types.join(\"|\")}, got ${actual}`)\n return errors\n }\n }\n // OpenAPI commonly pairs `type: [\"string\",\"null\"]` with an enum of the non-null values;\n // null is admitted by the type union and must not fail the enum check.\n if (\n s.enum &&\n !(value === null && types.includes(\"null\")) &&\n !s.enum.some((candidate) => deepEqual(candidate, value))\n ) {\n fail(\"value not in enum\")\n }\n if (s.const !== undefined && !deepEqual(s.const, value)) fail(\"value does not equal const\")\n if (typeof value === \"string\") {\n const length = graphemeLength(value)\n if (s.minLength !== undefined && length < s.minLength)\n fail(`length ${length} < minLength ${s.minLength}`)\n if (s.maxLength !== undefined && length > s.maxLength)\n fail(`length ${length} > maxLength ${s.maxLength}`)\n if (s.pattern !== undefined) {\n try {\n if (!new RegExp(s.pattern, \"u\").test(value)) fail(`does not match pattern ${s.pattern}`)\n } catch {\n // unsupported pattern syntax: skip, matching lenient validators\n }\n }\n if (s.format !== undefined) {\n const pattern = FORMAT_PATTERNS[s.format]\n if (pattern && !pattern.test(value)) fail(`does not match format ${s.format}`)\n }\n }\n if (typeof value === \"number\") {\n if (s.minimum !== undefined && value < s.minimum) fail(`${value} < minimum ${s.minimum}`)\n if (s.maximum !== undefined && value > s.maximum) fail(`${value} > maximum ${s.maximum}`)\n if (s.exclusiveMinimum !== undefined && value <= s.exclusiveMinimum)\n fail(`${value} <= exclusiveMinimum ${s.exclusiveMinimum}`)\n if (s.exclusiveMaximum !== undefined && value >= s.exclusiveMaximum)\n fail(`${value} >= exclusiveMaximum ${s.exclusiveMaximum}`)\n if (\n s.multipleOf !== undefined &&\n Math.abs(value / s.multipleOf - Math.round(value / s.multipleOf)) > 1e-9\n ) {\n fail(`${value} is not a multiple of ${s.multipleOf}`)\n }\n }\n if (Array.isArray(value)) {\n if (s.minItems !== undefined && value.length < s.minItems)\n fail(`${value.length} items < minItems ${s.minItems}`)\n if (s.maxItems !== undefined && value.length > s.maxItems)\n fail(`${value.length} items > maxItems ${s.maxItems}`)\n if (\n s.uniqueItems &&\n value.some((item, i) => value.slice(0, i).some((prev) => deepEqual(prev, item)))\n )\n fail(\"items are not unique\")\n value.forEach((item, i) => {\n const itemSchema = s.prefixItems?.[i] ?? s.items\n if (itemSchema) errors.push(...validateValue(document, itemSchema, item, [...path, i]))\n })\n }\n if (actual === \"object\") {\n const record = value as Record<string, unknown>\n const keys = Object.keys(record)\n for (const name of s.required ?? [])\n if (!(name in record)) fail(`missing required property ${name}`)\n if (s.minProperties !== undefined && keys.length < s.minProperties)\n fail(`${keys.length} properties < minProperties ${s.minProperties}`)\n if (s.maxProperties !== undefined && keys.length > s.maxProperties)\n fail(`${keys.length} properties > maxProperties ${s.maxProperties}`)\n for (const key of keys) {\n const property = s.properties?.[key]\n if (property) {\n errors.push(...validateValue(document, property, record[key], [...path, key]))\n continue\n }\n if (s.additionalProperties === false) fail(`unexpected property ${key}`)\n else if (typeof s.additionalProperties === \"object\") {\n errors.push(...validateValue(document, s.additionalProperties, record[key], [...path, key]))\n }\n if (s.propertyNames) {\n const nameErrors = validateValue(document, s.propertyNames, key, [...path, key])\n if (nameErrors.length > 0)\n fail(`property name ${key} is invalid: ${nameErrors[0]?.message}`)\n }\n }\n }\n if (s.allOf)\n for (const branch of s.allOf) errors.push(...validateValue(document, branch, value, path))\n if (s.anyOf && !s.anyOf.some((branch) => validateValue(document, branch, value).length === 0))\n fail(\"matches no anyOf branch\")\n if (s.oneOf) {\n const matches = s.oneOf.filter(\n (branch) => validateValue(document, branch, value).length === 0,\n ).length\n if (matches !== 1) fail(`matches ${matches} oneOf branches, expected exactly 1`)\n }\n if (s.not && validateValue(document, s.not, value).length === 0)\n fail(\"matches forbidden `not` schema\")\n return errors\n}\n\nexport const isValid = (document: OpenAPIDocument, schema: SchemaObject, value: unknown) =>\n validateValue(document, schema, value).length === 0\n\nexport type { JsonValue }\n", "/**\n * Rails/PHP/Stripe-style bracket notation for `application/x-www-form-urlencoded` bodies and\n * query strings:\n *\n * address[city]=Paris -> { address: { city: \"Paris\" } }\n * items[0][name]=a -> { items: [{ name: \"a\" }] }\n * tags[]=x&tags[]=y -> { tags: [\"x\", \"y\"] }\n * metadata[k]=v -> { metadata: { k: \"v\" } }\n *\n * Decoding yields only strings, arrays and plain objects \u2014 coercion is the caller's concern,\n * exactly like a real HTTP server.\n */\n\nexport type FormValue = string | FormValue[] | { [key: string]: FormValue }\n\nexport type FormObject = { [key: string]: FormValue }\n\nconst encodeComponent = (value: string) =>\n encodeURIComponent(value).replace(\n /[!'()*]/g,\n (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,\n )\n\nconst flatten = (prefix: string, value: unknown, out: Array<[string, string]>) => {\n if (value === undefined) return\n if (value === null) {\n out.push([prefix, \"\"])\n return\n }\n if (Array.isArray(value)) {\n if (value.length === 0) {\n out.push([prefix, \"\"])\n return\n }\n value.forEach((item, index) => {\n flatten(`${prefix}[${index}]`, item, out)\n })\n return\n }\n if (typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>)\n if (entries.length === 0) {\n out.push([prefix, \"\"])\n return\n }\n for (const [key, item] of entries) flatten(`${prefix}[${key}]`, item, out)\n return\n }\n out.push([prefix, String(value)])\n}\n\n/**\n * Encode a JSON-like value as bracket-notation pairs. Nested arrays use explicit indices\n * (`a[0]`), which every bracket parser (including Stripe's) accepts; empty arrays/objects\n * encode as an empty string, matching how Stripe unsets fields.\n */\nexport const encodeFormPairs = (value: Record<string, unknown>): Array<[string, string]> => {\n const out: Array<[string, string]> = []\n for (const [key, item] of Object.entries(value)) flatten(key, item, out)\n return out\n}\n\n/** Encode to a full `application/x-www-form-urlencoded` string. */\nexport const encodeForm = (value: Record<string, unknown>): string =>\n encodeFormPairs(value)\n .map(([k, v]) => `${encodeComponent(k)}=${encodeComponent(v)}`)\n .join(\"&\")\n\nconst parsePath = (rawKey: string): string[] => {\n const open = rawKey.indexOf(\"[\")\n if (open === -1) return [rawKey]\n const path = [rawKey.slice(0, open)]\n const rest = rawKey.slice(open)\n const pattern = /\\[([^\\]]*)\\]/g\n let match: RegExpExecArray | null = pattern.exec(rest)\n let consumed = 0\n while (match !== null) {\n if (match.index !== consumed) return [rawKey]\n path.push(match[1] ?? \"\")\n consumed = match.index + match[0].length\n match = pattern.exec(rest)\n }\n if (consumed !== rest.length) return [rawKey]\n return path\n}\n\nconst isIndex = (segment: string) => /^(0|[1-9][0-9]*)$/.test(segment)\n\n/**\n * Write an own property. `__proto__` is the one key with an inherited setter, so it needs\n * `defineProperty`; every other key shadows its inherited namesake by plain assignment.\n */\nconst put = (target: object, key: string | number, value: FormValue): void => {\n if (key === \"__proto__\") {\n Object.defineProperty(target, key, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n })\n return\n }\n ;(target as Record<string | number, FormValue>)[key] = value\n}\n\nconst assign = (target: FormObject, path: string[], value: string) => {\n let cursor: FormValue = target\n for (let i = 0; i < path.length; i++) {\n const segment = path[i] as string\n const last = i === path.length - 1\n if (Array.isArray(cursor)) {\n const index: number | undefined =\n segment === \"\" ? cursor.length : isIndex(segment) ? Number(segment) : undefined\n if (index === undefined) return\n if (last) {\n put(cursor, index, value)\n return\n }\n const next: FormValue | undefined = Object.hasOwn(cursor, index)\n ? (cursor as Record<number, FormValue>)[index]\n : undefined\n if (next === undefined || typeof next === \"string\") {\n const created: FormValue = path[i + 1] === \"\" || isIndex(path[i + 1] as string) ? [] : {}\n put(cursor, index, created)\n cursor = created\n } else {\n cursor = next\n }\n continue\n }\n if (typeof cursor === \"string\") return\n if (last) {\n put(cursor, segment, value)\n return\n }\n const nextSegment = path[i + 1] as string\n const existing: FormValue | undefined = Object.hasOwn(cursor, segment)\n ? (cursor as Record<string, FormValue>)[segment]\n : undefined\n if (existing === undefined || typeof existing === \"string\") {\n const created: FormValue = nextSegment === \"\" || isIndex(nextSegment) ? [] : {}\n put(cursor, segment, created)\n cursor = created\n } else {\n cursor = existing\n }\n }\n}\n\n/** Decode `key=value&...` pairs (already percent-decoded) into a nested object. */\nexport const decodeFormPairs = (pairs: Iterable<[string, string]>): FormObject => {\n const out: FormObject = {}\n for (const [rawKey, value] of pairs) assign(out, parsePath(rawKey), value)\n return densify(out) as FormObject\n}\n\n/** Sparse arrays (`a[2]=x` without `a[0]`) become dense in bracket parsers. */\nconst densify = (value: FormValue): FormValue => {\n if (typeof value === \"string\") return value\n if (Array.isArray(value)) return value.filter((item) => item !== undefined).map(densify)\n const out: FormObject = {}\n for (const [key, item] of Object.entries(value)) put(out, key, densify(item))\n return out\n}\n\n/** Decode an `application/x-www-form-urlencoded` body or a query string (with or without `?`). */\nexport const decodeForm = (text: string): FormObject => {\n const source = text.startsWith(\"?\") ? text.slice(1) : text\n return decodeFormPairs(new URLSearchParams(source).entries())\n}\n", "import { decodeForm, encodeForm } from \"./form.js\"\n\nexport const JSON_MEDIA_TYPE = \"application/json\"\nexport const FORM_MEDIA_TYPE = \"application/x-www-form-urlencoded\"\n\n/** The essence of a `Content-Type` header: lower-cased media type without parameters. */\nexport const mediaTypeOf = (contentType: string | null | undefined): string | undefined => {\n if (!contentType) return undefined\n const essence = contentType.split(\";\")[0]?.trim().toLowerCase()\n return essence ? essence : undefined\n}\n\nconst isJsonMediaType = (mediaType: string) =>\n mediaType === JSON_MEDIA_TYPE || mediaType.endsWith(\"+json\") || mediaType === \"text/json\"\n\nexport type DecodedBody =\n | { kind: \"empty\" }\n | { kind: \"json\"; value: unknown }\n | { kind: \"form\"; value: Record<string, unknown> }\n | { kind: \"text\"; value: string }\n | { kind: \"bytes\"; value: Uint8Array }\n | { kind: \"invalid\"; mediaType: string; text: string; error: string }\n\nconst utf8 = new TextDecoder(\"utf-8\", { fatal: false })\n\n/**\n * Decode raw bytes according to a `Content-Type`. Never throws: malformed payloads come back as\n * `{ kind: \"invalid\" }` so callers (mock servers, the differential runner) can respond like a real\n * server would instead of crashing.\n */\nexport const decodeBody = (\n contentType: string | null | undefined,\n bytes: Uint8Array,\n): DecodedBody => {\n if (bytes.byteLength === 0) return { kind: \"empty\" }\n const mediaType = mediaTypeOf(contentType)\n if (mediaType === undefined) return { kind: \"bytes\", value: bytes }\n if (isJsonMediaType(mediaType)) {\n const text = utf8.decode(bytes)\n try {\n return { kind: \"json\", value: JSON.parse(text) }\n } catch (error) {\n return {\n kind: \"invalid\",\n mediaType,\n text,\n error: error instanceof Error ? error.message : String(error),\n }\n }\n }\n if (mediaType === FORM_MEDIA_TYPE) {\n return { kind: \"form\", value: decodeForm(utf8.decode(bytes)) }\n }\n if (mediaType.startsWith(\"text/\")) return { kind: \"text\", value: utf8.decode(bytes) }\n return { kind: \"bytes\", value: bytes }\n}\n\n/** Read and decode a Request/Response body. */\nexport const readBody = async (message: Request | Response): Promise<DecodedBody> => {\n const bytes = new Uint8Array(await message.arrayBuffer())\n return decodeBody(message.headers.get(\"content-type\"), bytes)\n}\n\nexport type EncodedBody = {\n contentType: string\n body: string\n}\n\n/** Encode a JSON-like value for the given media type. Throws for unsupported media types. */\nexport const encodeBody = (mediaType: string, value: unknown): EncodedBody => {\n const essence = mediaTypeOf(mediaType) ?? mediaType\n if (isJsonMediaType(essence)) return { contentType: essence, body: JSON.stringify(value) }\n if (essence === FORM_MEDIA_TYPE) {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(`${FORM_MEDIA_TYPE} bodies must be objects`)\n }\n return { contentType: essence, body: encodeForm(value as Record<string, unknown>) }\n }\n if (essence.startsWith(\"text/\")) return { contentType: essence, body: String(value) }\n throw new TypeError(`unsupported request media type: ${mediaType}`)\n}\n", "import { JSON_MEDIA_TYPE } from \"@crvouga/mockingbird-http-codec\"\n\n/** JSON response with a normalised content type. */\nexport const jsonRes = (\n status: number,\n body: unknown,\n headers: Record<string, string> = {},\n): Response =>\n new Response(JSON.stringify(body), {\n status,\n headers: { \"content-type\": JSON_MEDIA_TYPE, ...headers },\n })\n\n/** Thrown by handlers to produce a provider-shaped error response via `onError`. */\nexport class HttpError extends Error {\n constructor(\n readonly status: number,\n readonly body: unknown,\n readonly headers: Record<string, string> = {},\n ) {\n super(`HTTP ${status}`)\n this.name = \"HttpError\"\n }\n\n toResponse(): Response {\n const contentType = this.headers[\"content-type\"]?.split(\";\", 1)[0]?.trim().toLowerCase()\n if (contentType === \"text/plain\") {\n return new Response(String(this.body), {\n status: this.status,\n headers: this.headers,\n })\n }\n return jsonRes(this.status, this.body, this.headers)\n }\n}\n\nexport type FieldResult<T> = { ok: true; value: T } | { ok: false; reason: string }\n\nconst ok = <T>(value: T): FieldResult<T> => ({ ok: true, value })\nconst fail = <T>(reason: string): FieldResult<T> => ({ ok: false, reason })\n\n/** Form bodies decode to strings; these coerce the way HTTP servers do, reporting why not. */\nexport const coerce = {\n string(value: unknown): FieldResult<string> {\n return typeof value === \"string\" ? ok(value) : fail(\"expected a string\")\n },\n integer(value: unknown): FieldResult<number> {\n if (typeof value === \"number\" && Number.isInteger(value)) return ok(value)\n if (typeof value === \"string\" && /^-?\\d+$/.test(value.trim())) {\n const parsed = Number(value)\n return Number.isSafeInteger(parsed) ? ok(parsed) : fail(\"integer out of range\")\n }\n return fail(\"expected an integer\")\n },\n boolean(value: unknown): FieldResult<boolean> {\n if (typeof value === \"boolean\") return ok(value)\n if (value === \"true\" || value === \"1\") return ok(true)\n if (value === \"false\" || value === \"0\") return ok(false)\n return fail(\"expected a boolean\")\n },\n enumeration<T extends string>(value: unknown, allowed: readonly T[]): FieldResult<T> {\n const match = allowed.find((candidate) => candidate === value)\n return match === undefined ? fail(`expected one of ${allowed.join(\", \")}`) : ok(match)\n },\n /** Flat string-to-string map, the shape of Stripe-style `metadata`. */\n stringMap(value: unknown): FieldResult<Record<string, string>> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value))\n return fail(\"expected an object\")\n const out: Record<string, string> = {}\n for (const [key, item] of Object.entries(value)) {\n if (typeof item !== \"string\") return fail(`expected a string at ${key}`)\n out[key] = item\n }\n return ok(out)\n },\n}\n\n/** Count Unicode code points, the way JSON Schema and most APIs measure string length. */\nexport const codePointLength = (value: string) => [...value].length\n", "import type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\nimport { Collection } from \"./collection.js\"\n\n/**\n * Vendor idempotency keys: the same key with the same parameters replays the stored\n * response byte for byte; the same key with different parameters gets the vendor's\n * mismatch error; a key whose first request is still running gets the vendor's conflict.\n *\n * Stored responses live in SQLite (so reset and snapshots cover them); in-flight keys live\n * in memory, since \"in flight\" only means something inside one process.\n */\ntype StoredResponse = {\n fingerprint: string\n status: number\n headers: [string, string][]\n body: string\n}\n\nexport type IdempotencyErrors = {\n /** Same key, different parameters. */\n mismatch: () => Response\n /** Same key while the first request is still being handled. */\n conflict: () => Response\n}\n\nconst inFlight = new Map<string, Promise<void>>()\n\nexport class IdempotencyStore {\n private readonly responses: Collection<StoredResponse>\n\n constructor(\n sqlite: SqliteClient,\n private readonly namespace: string,\n name = \"idempotency\",\n ) {\n this.responses = new Collection<StoredResponse>(sqlite, namespace, name)\n }\n\n /**\n * Run `handler` once per `key`. `fingerprint` identifies the request's parameters (e.g.\n * the method, path and canonical body). Only `replayable` responses are stored (default:\n * every status below 500, as Stripe does), so a transient failure can be retried.\n */\n async run(\n key: string,\n fingerprint: string,\n errors: IdempotencyErrors,\n handler: () => Promise<Response> | Response,\n replayable: (status: number) => boolean = (status) => status < 500,\n ): Promise<Response> {\n const slot = `${this.namespace}\\u0000${key}`\n const stored = this.responses.get(key)\n if (stored) {\n if (stored.fingerprint !== fingerprint) return errors.mismatch()\n return new Response(stored.body, {\n status: stored.status,\n headers: [...stored.headers, [\"idempotent-replayed\", \"true\"]],\n })\n }\n if (inFlight.has(slot)) return errors.conflict()\n let release = () => {}\n inFlight.set(\n slot,\n new Promise<void>((resolve) => {\n release = resolve\n }),\n )\n try {\n const response = await handler()\n if (!replayable(response.status)) return response\n const body = await response.clone().text()\n this.responses.insert(key, {\n fingerprint,\n status: response.status,\n headers: [...response.headers],\n body,\n })\n return response\n } finally {\n inFlight.delete(slot)\n release()\n }\n }\n}\n\n/** A stable fingerprint of a request's method, path and parsed body. */\nexport const requestFingerprint = (method: string, path: string, body: unknown): string =>\n `${method.toUpperCase()} ${path} ${stableStringify(body)}`\n\nexport const stableStringify = (value: unknown): string => {\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(\",\")}]`\n if (value && typeof value === \"object\") {\n return `{${Object.keys(value as Record<string, unknown>)\n .sort()\n .map((k) => `${JSON.stringify(k)}:${stableStringify((value as Record<string, unknown>)[k])}`)\n .join(\",\")}}`\n }\n return JSON.stringify(value) ?? \"undefined\"\n}\n", "import type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\n\nconst ALPHABET = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\"\n\n/** FNV-1a over a string, mixed once more so consecutive counters look unrelated. */\nconst mix = (input: string): number => {\n let hash = 0x811c9dc5\n for (let i = 0; i < input.length; i++) {\n hash ^= input.charCodeAt(i)\n hash = Math.imul(hash, 0x01000193) >>> 0\n }\n hash ^= hash >>> 16\n hash = Math.imul(hash, 0x85ebca6b) >>> 0\n hash ^= hash >>> 13\n return hash >>> 0\n}\n\n/** Deterministic, opaque-looking alphanumeric token of `length` characters derived from `input`. */\nexport const opaqueToken = (input: string, length: number): string => {\n let out = \"\"\n let round = 0\n while (out.length < length) {\n let hash = mix(`${input}:${round++}`)\n for (let i = 0; i < 5 && out.length < length; i++) {\n out += ALPHABET.charAt(hash % ALPHABET.length)\n hash = Math.floor(hash / ALPHABET.length)\n }\n }\n return out\n}\n\n/**\n * Sequential id source persisted in SQLite. Ids are deterministic for a given\n * sequence history (`cus_` + 14 opaque chars), so reproductions stay stable.\n */\nexport class IdSequence {\n constructor(\n private readonly sqlite: SqliteClient,\n private readonly namespace: string,\n private readonly salt = \"mockingbird\",\n ) {}\n\n next(prefix: string, length = 14): string {\n return this.sqlite.transaction(() => {\n const row = this.sqlite\n .prepare(\n \"SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'id'\",\n )\n .get<{ value: number }>(this.namespace, prefix)\n const value = (row?.value ?? 0) + 1\n this.sqlite\n .prepare(\n `INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, 'id', ?)\n ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`,\n )\n .run(this.namespace, prefix, value)\n return `${prefix}${opaqueToken(`${this.salt}:${prefix}:${value}`, length)}`\n })\n }\n}\n", "import type { RequestLog } from \"./metrics.js\"\n\n/** One journal entry: a request log stamped with when (on the mock clock) it was handled. */\nexport type JournalEntry = RequestLog & { at: string }\n\nexport type JournalQuery = {\n /** Only this namespace. Omit for every namespace, oldest first across all of them. */\n namespace?: string\n operationId?: string\n status?: number\n /** Only entries at or after this instant (epoch ms). */\n since?: number\n /** At most this many, the most recent kept. */\n limit?: number\n}\n\nexport type Journal = {\n readonly size: number\n record(entry: JournalEntry): void\n list(query?: JournalQuery): JournalEntry[]\n /** Forget one namespace's entries, or every namespace's. */\n clear(namespace?: string): void\n}\n\n/** Default number of entries each namespace keeps. */\nexport const DEFAULT_JOURNAL_SIZE = 1000\n\n/**\n * The last `size` requests per namespace, in a ring buffer: what the mock actually saw,\n * so a test can prove a request arrived (or never did) without reading logs.\n */\nexport const createJournal = (size: number = DEFAULT_JOURNAL_SIZE): Journal => {\n const capacity = Math.max(0, Math.floor(size))\n const rings = new Map<string, { entries: JournalEntry[]; next: number }>()\n let sequence = 0\n const order = new WeakMap<JournalEntry, number>()\n const inOrder = (ring: { entries: JournalEntry[]; next: number }): JournalEntry[] =>\n ring.entries.length < capacity\n ? ring.entries\n : [...ring.entries.slice(ring.next), ...ring.entries.slice(0, ring.next)]\n return {\n size: capacity,\n record(entry) {\n if (capacity === 0) return\n order.set(entry, sequence++)\n let ring = rings.get(entry.namespace)\n if (!ring) {\n ring = { entries: [], next: 0 }\n rings.set(entry.namespace, ring)\n }\n if (ring.entries.length < capacity) ring.entries.push(entry)\n else {\n ring.entries[ring.next] = entry\n ring.next = (ring.next + 1) % capacity\n }\n },\n list(query = {}) {\n const source =\n query.namespace !== undefined\n ? inOrder(rings.get(query.namespace) ?? { entries: [], next: 0 })\n : [...rings.values()]\n .flatMap(inOrder)\n .sort((a, b) => (order.get(a) ?? 0) - (order.get(b) ?? 0))\n const matched = source.filter(\n (entry) =>\n (query.operationId === undefined || entry.operationId === query.operationId) &&\n (query.status === undefined || entry.status === query.status) &&\n (query.since === undefined || Date.parse(entry.at) >= query.since),\n )\n return query.limit !== undefined ? matched.slice(-Math.max(0, query.limit)) : matched\n },\n clear(namespace) {\n if (namespace === undefined) rings.clear()\n else rings.delete(namespace)\n },\n }\n}\n\n/** What a service knows about a request that the runtime cannot see from outside. */\nexport type ResponseNotes = {\n /** Resource ids the handler touched, e.g. `{ userId, orderId }`. */\n ids?: Record<string, string>\n /** Set when the handler created a resource the request referred to but did not exist. */\n adopted?: boolean\n}\n\nconst notes = new WeakMap<Response, ResponseNotes>()\n\n/**\n * Attach notes to a response for the request journal and structured log. They travel\n * beside the response, never in it, so nothing the vendor would not send reaches a client.\n */\nexport const annotateResponse = (response: Response, extra: ResponseNotes): Response => {\n const existing = notes.get(response)\n notes.set(response, {\n ...existing,\n ...extra,\n ...(existing?.ids || extra.ids ? { ids: { ...existing?.ids, ...extra.ids } } : {}),\n })\n return response\n}\n\nexport const responseNotes = (response: Response): ResponseNotes | undefined => notes.get(response)\n", "/** One handled request, as the structured log sees it. */\nexport type RequestLog = {\n service: string\n namespace: string\n operationId: string | undefined\n method: string\n path: string\n status: number\n durationMs: number\n /** True when the path matched no operation in the contract. */\n unmatched: boolean\n /** Set when a fault rule produced the response. */\n faultId?: string\n /** Resource ids the handler touched (`userId`, `orderId`, \u2026), when the service reports them. */\n ids?: Record<string, string>\n /** Set when the service created a resource the request referred to but that did not exist. */\n adopted?: boolean\n}\n\nexport type MetricsReport = {\n requests: number\n /** Counts keyed `<operationId> <status>`. */\n byOperation: Record<string, number>\n /**\n * Paths that matched no operation, most frequent first.\n *\n * This is the early-warning signal: a consumer calling something the mock does\n * not implement shows up here as a count, before it fails a suite as a 404.\n */\n unmatched: { method: string; path: string; count: number }[]\n faults: number\n totalDurationMs: number\n}\n\nexport type Metrics = {\n record(entry: RequestLog): void\n report(): MetricsReport\n reset(): void\n}\n\nexport const createMetrics = (): Metrics => {\n let requests = 0\n let faults = 0\n let totalDurationMs = 0\n const byOperation = new Map<string, number>()\n const unmatched = new Map<string, number>()\n return {\n record(entry) {\n requests++\n totalDurationMs += entry.durationMs\n if (entry.faultId !== undefined) faults++\n const key = `${entry.operationId ?? \"(unmatched)\"} ${entry.status}`\n byOperation.set(key, (byOperation.get(key) ?? 0) + 1)\n if (entry.unmatched) {\n const route = `${entry.method} ${entry.path}`\n unmatched.set(route, (unmatched.get(route) ?? 0) + 1)\n }\n },\n report: () => ({\n requests,\n byOperation: Object.fromEntries([...byOperation].sort(([a], [b]) => a.localeCompare(b))),\n unmatched: [...unmatched]\n .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))\n .map(([route, count]) => {\n const space = route.indexOf(\" \")\n return { method: route.slice(0, space), path: route.slice(space + 1), count }\n }),\n faults,\n totalDurationMs,\n }),\n reset() {\n requests = 0\n faults = 0\n totalDurationMs = 0\n byOperation.clear()\n unmatched.clear()\n },\n }\n}\n", "/** A stable identifier for a point in a {@link Timeline}. */\nexport type CheckpointId = string\n\n/** An immutable node in a timeline's checkpoint DAG. */\nexport type Checkpoint<T> = Readonly<{\n id: CheckpointId\n branch: string\n parent: CheckpointId | null\n /** Logical time supplied by the timeline's injected clock. */\n at: number\n value: T\n}>\n\nexport type TimelineOptions = {\n /** Logical clock used to stamp checkpoints. Defaults to a deterministic counter. */\n now?: () => number\n /** Maximum retained checkpoints. Branch heads are never collected. Default 1,000. */\n maxCheckpoints?: number\n /** Customize deterministic checkpoint IDs. */\n id?: (sequence: number) => CheckpointId\n}\n\nexport type CommitOptions = {\n branch?: string\n /** Parent checkpoint. Defaults to the selected branch's current head. */\n parent?: CheckpointId | null\n}\n\nexport type ForkOptions = {\n /** Checkpoint to fork from. Defaults to the main branch's head. */\n from?: CheckpointId\n}\n\nconst BRANCH_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/\n\n/**\n * Small, storage-agnostic checkpoint DAG shared by service runtimes. Its values may be immutable\n * records, namespace images, or copy-on-write SQL engine snapshots.\n *\n * Values are retained by reference. Engines can therefore use persistent/COW snapshots while\n * simpler services can use immutable values. IDs and GC order are deterministic, and all IO\n * (the logical clock) is injected.\n */\nexport class Timeline<T> {\n readonly maxCheckpoints: number\n private readonly now: () => number\n private readonly makeId: (sequence: number) => CheckpointId\n private readonly nodes = new Map<CheckpointId, Checkpoint<T>>()\n private readonly heads = new Map<string, CheckpointId>()\n /** Unreferenced nodes in the exact order they became collectible. */\n private readonly evictable = new Set<CheckpointId>()\n /** Branch heads plus explicit retainers. Absent means zero. */\n private readonly references = new Map<CheckpointId, number>()\n private readonly explicitPins = new Map<CheckpointId, number>()\n private sequence = 0\n\n constructor(options: TimelineOptions = {}) {\n const max = options.maxCheckpoints ?? 1_000\n if (!Number.isSafeInteger(max) || max < 1)\n throw new RangeError(\"maxCheckpoints must be a positive integer\")\n this.maxCheckpoints = max\n this.now = options.now ?? (() => this.sequence)\n this.makeId = options.id ?? ((sequence) => `cp_${sequence.toString(36).padStart(8, \"0\")}`)\n }\n\n /** Capture a new immutable value and move `branch` to it. */\n commit(value: T, options: CommitOptions = {}): Checkpoint<T> {\n const branch = options.branch ?? \"main\"\n this.assertBranch(branch)\n const parent = options.parent === undefined ? (this.heads.get(branch) ?? null) : options.parent\n if (parent !== null && !this.nodes.has(parent)) throw new RangeError(`no checkpoint ${parent}`)\n const id = this.makeId(++this.sequence)\n if (this.nodes.has(id)) throw new RangeError(`duplicate checkpoint id ${id}`)\n const checkpoint = Object.freeze({ id, branch, parent, at: this.now(), value })\n this.nodes.set(id, checkpoint)\n this.moveHead(branch, id)\n this.collect(this.maxCheckpoints)\n return checkpoint\n }\n\n /** Create a branch pointer without copying its checkpoint value. */\n fork(branch: string, options: ForkOptions = {}): Checkpoint<T> | undefined {\n this.assertBranch(branch)\n if (this.heads.has(branch)) throw new RangeError(`branch already exists: ${branch}`)\n const from = options.from ?? this.heads.get(\"main\")\n if (from === undefined) return undefined\n const checkpoint = this.get(from)\n this.moveHead(branch, checkpoint.id)\n return checkpoint\n }\n\n /** Move a branch pointer to an existing checkpoint. */\n checkout(branch: string, id: CheckpointId): Checkpoint<T> {\n this.assertBranch(branch)\n const checkpoint = this.get(id)\n this.moveHead(branch, checkpoint.id)\n return checkpoint\n }\n\n get(id: CheckpointId): Checkpoint<T> {\n const checkpoint = this.nodes.get(id)\n if (!checkpoint) throw new RangeError(`no checkpoint ${id}`)\n return checkpoint\n }\n\n head(branch = \"main\"): Checkpoint<T> | undefined {\n const id = this.heads.get(branch)\n return id === undefined ? undefined : this.get(id)\n }\n\n hasBranch(branch: string): boolean {\n return this.heads.has(branch)\n }\n\n branches(): Readonly<Record<string, CheckpointId>> {\n return Object.freeze(\n Object.fromEntries([...this.heads].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))),\n )\n }\n\n checkpoints(): readonly Checkpoint<T>[] {\n return [...this.nodes.values()]\n }\n\n /** Number of retained checkpoints without allocating an array. */\n get size(): number {\n return this.nodes.size\n }\n\n /** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */\n retain(id: CheckpointId): Checkpoint<T> {\n const checkpoint = this.get(id)\n this.explicitPins.set(id, (this.explicitPins.get(id) ?? 0) + 1)\n this.addReference(id)\n return checkpoint\n }\n\n /** Release one explicit pin. Branch heads remain pinned until moved or deleted. */\n release(id: CheckpointId): boolean {\n if (!this.nodes.has(id)) return false\n const pins = this.explicitPins.get(id) ?? 0\n if (pins === 0) return false\n if (pins === 1) this.explicitPins.delete(id)\n else this.explicitPins.set(id, pins - 1)\n this.removeReference(id)\n this.collect(this.maxCheckpoints)\n return true\n }\n\n deleteBranch(branch: string): boolean {\n if (branch === \"main\") throw new RangeError(\"cannot delete main branch\")\n const previous = this.heads.get(branch)\n const deleted = this.heads.delete(branch)\n if (previous !== undefined) this.removeReference(previous)\n this.collect(this.maxCheckpoints)\n return deleted\n }\n\n /**\n * Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):\n * commits never scan pinned nodes or the retained history. Parents are metadata rather than a\n * storage dependency, so a retained node remains usable after pruning.\n */\n gc(max = this.maxCheckpoints): CheckpointId[] {\n if (!Number.isSafeInteger(max) || max < 1)\n throw new RangeError(\"max must be a positive integer\")\n const removed: CheckpointId[] = []\n this.collect(max, removed)\n return removed\n }\n\n private collect(max: number, removed?: CheckpointId[]): void {\n while (this.nodes.size > max && this.evictable.size > 0) {\n const id = this.evictable.values().next().value as CheckpointId\n this.evictable.delete(id)\n this.nodes.delete(id)\n removed?.push(id)\n }\n }\n\n private moveHead(branch: string, id: CheckpointId): void {\n const previous = this.heads.get(branch)\n if (previous === id) return\n if (previous !== undefined) this.removeReference(previous)\n this.heads.set(branch, id)\n this.addReference(id)\n }\n\n private addReference(id: CheckpointId): void {\n this.references.set(id, (this.references.get(id) ?? 0) + 1)\n this.evictable.delete(id)\n }\n\n private removeReference(id: CheckpointId): void {\n const next = (this.references.get(id) ?? 0) - 1\n if (next > 0) this.references.set(id, next)\n else {\n this.references.delete(id)\n if (this.nodes.has(id)) this.evictable.add(id)\n }\n }\n\n private assertBranch(branch: string): void {\n if (!BRANCH_PATTERN.test(branch)) throw new RangeError(`branch must match ${BRANCH_PATTERN}`)\n }\n}\n", "import { Database } from \"@crvouga/mockingbird-service-sqlite\"\nimport type { SqliteClient } from \"./client.js\"\n\n/** Construct the default in-memory SQLite client (`@crvouga/mockingbird-service-sqlite`). */\nexport const createDefaultSqlite = (): SqliteClient => new Database()\n\n/** Use the injected client, or fall back to {@link createDefaultSqlite}. */\nexport const resolveSqlite = (sqlite?: SqliteClient): SqliteClient =>\n sqlite ?? createDefaultSqlite()\n", "import type { SqliteClient } from \"./client.js\"\n\n/** One named, ordered schema change applied exactly once per client. */\nexport type Migration = {\n /** Stable id stored in `schema_migrations`. Must be unique across the list. */\n id: string\n sql: string\n}\n\nconst ensureMigrationsTable = (sqlite: SqliteClient) => {\n sqlite.exec(`\n CREATE TABLE IF NOT EXISTS schema_migrations (\n id TEXT PRIMARY KEY NOT NULL,\n applied_at INTEGER NOT NULL\n )\n `)\n}\n\n/**\n * Apply pending migrations in order inside a single transaction.\n *\n * Idempotent: already-applied ids are skipped. Re-running with the same list\n * is a no-op after the first successful boot.\n */\nexport const migrate = (sqlite: SqliteClient, migrations: readonly Migration[]): void => {\n ensureMigrationsTable(sqlite)\n const applied = new Set(\n sqlite\n .prepare(\"SELECT id FROM schema_migrations\")\n .all<{ id: string }>()\n .map((row) => row.id),\n )\n const pending = migrations.filter((migration) => !applied.has(migration.id))\n if (pending.length === 0) return\n\n const insert = sqlite.prepare(\"INSERT INTO schema_migrations (id, applied_at) VALUES (?, ?)\")\n const now = Math.floor(Date.now() / 1000)\n sqlite.transaction(() => {\n for (const migration of pending) {\n sqlite.exec(migration.sql)\n insert.run(migration.id, now)\n }\n })\n}\n\n/** Applied migration ids in application order (by `applied_at`, then `id`). */\nexport const listAppliedMigrations = (sqlite: SqliteClient): string[] => {\n ensureMigrationsTable(sqlite)\n return sqlite\n .prepare(\"SELECT id FROM schema_migrations ORDER BY applied_at ASC, id ASC\")\n .all<{ id: string }>()\n .map((row) => row.id)\n}\n", "import type { SqliteClient } from \"./client.js\"\nimport { type Migration, migrate } from \"./migrate.js\"\n\n/**\n * Core Mockingbird service schema: namespaced JSON records and counters.\n *\n * Applied on every service boot via {@link migrateCore}.\n */\nexport const CORE_MIGRATIONS: readonly Migration[] = [\n {\n id: \"20260322_core_records_sequences\",\n sql: `\n CREATE TABLE IF NOT EXISTS mockingbird_records (\n namespace TEXT NOT NULL,\n collection TEXT NOT NULL,\n id TEXT NOT NULL,\n seq INTEGER NOT NULL,\n value TEXT NOT NULL,\n PRIMARY KEY (namespace, collection, id)\n );\n CREATE INDEX IF NOT EXISTS mockingbird_records_seq\n ON mockingbird_records (namespace, collection, seq);\n CREATE TABLE IF NOT EXISTS mockingbird_sequences (\n namespace TEXT NOT NULL,\n name TEXT NOT NULL,\n kind TEXT NOT NULL,\n value INTEGER NOT NULL,\n PRIMARY KEY (namespace, name, kind)\n );\n `,\n },\n]\n\n/** Apply {@link CORE_MIGRATIONS} (idempotent). */\nexport const migrateCore = (sqlite: SqliteClient): void => {\n migrate(sqlite, CORE_MIGRATIONS)\n}\n\n/** Delete every record and sequence belonging to `namespace`. */\nexport const clearNamespace = (sqlite: SqliteClient, namespace: string): void => {\n sqlite.transaction(() => {\n sqlite.prepare(\"DELETE FROM mockingbird_records WHERE namespace = ?\").run(namespace)\n sqlite.prepare(\"DELETE FROM mockingbird_sequences WHERE namespace = ?\").run(namespace)\n })\n}\n", "/**\n * Mockingbird's OpenAPI extensions. They are deliberately generic: nothing here knows about any\n * particular provider. Provider specifics live in each provider's `openapi.yaml`.\n */\n\n/** `x-mockingbird` on an operation. */\nexport type OperationExtension = {\n /** `false` marks an operation the mock explicitly does not implement. Default `true`. */\n supported?: boolean\n /** Human explanation, required when `supported: false` or `parity.enabled: false`. */\n reason?: string\n parity?: {\n /** Whether the differential runner generates this operation. Defaults to `supported`. */\n enabled?: boolean\n /** `false` for operations that must never hit a real account (destructive, billing\u2026). Default `true`. */\n safe?: boolean\n reason?: string\n }\n}\n\nexport type OperationMetadata = {\n supported: boolean\n reason: string | undefined\n parity: { enabled: boolean; safe: boolean; reason: string | undefined }\n}\n\n/** `x-mockingbird-resource`: this string value is the identity of a resource. */\nexport type ResourceIdentityExtension = { type: string; identity: true }\n\n/** `x-mockingbird-resource-ref`: this value must reference an existing resource of `type`. */\nexport type ResourceRefExtension = {\n type: string\n /** A well-formed id that does not exist, used to exercise not-found behaviour. */\n missing?: string\n}\n\nexport const VOLATILE_KINDS = [\"id\", \"timestamp\", \"token\", \"url\", \"account\", \"opaque\"] as const\nexport type VolatileKind = (typeof VOLATILE_KINDS)[number]\n\n/** `x-mockingbird-volatile`: nondeterministic on the real side; compared by shape only. */\nexport type VolatileExtension = { kind: VolatileKind }\n\nexport const SCOPE_VALUES = [\"run-id\", \"walk-start-unix\", \"walk-start-iso\"] as const\nexport type ScopeValue = (typeof SCOPE_VALUES)[number]\n\n/** `x-mockingbird-scope`: always generate this run-scoped value instead of a random one. */\nexport type ScopeExtension = { value: ScopeValue }\n\n/** `x-mockingbird-unsupported`: the mock does not implement this parameter/property. */\nexport type UnsupportedExtension = true | { reason?: string }\n\nexport type SchemaMetadata = {\n resource: ResourceIdentityExtension | undefined\n resourceRef: ResourceRefExtension | undefined\n volatile: VolatileExtension | undefined\n scope: ScopeExtension | undefined\n unsupported: { reason: string | undefined } | undefined\n}\n\nexport const EXTENSION_KEYS = {\n operation: \"x-mockingbird\",\n resource: \"x-mockingbird-resource\",\n resourceRef: \"x-mockingbird-resource-ref\",\n volatile: \"x-mockingbird-volatile\",\n scope: \"x-mockingbird-scope\",\n unsupported: \"x-mockingbird-unsupported\",\n parityHeader: \"x-mockingbird-parity-header\",\n} as const\n", "import type {\n HeaderObject,\n OpenAPIDocument,\n OperationObject,\n ParameterObject,\n ResponseObject,\n SchemaObject,\n} from \"@crvouga/mockingbird-openapi\"\nimport { deref, resolveSchema } from \"@crvouga/mockingbird-openapi\"\nimport {\n EXTENSION_KEYS,\n type OperationExtension,\n type OperationMetadata,\n SCOPE_VALUES,\n type SchemaMetadata,\n VOLATILE_KINDS,\n} from \"./types.js\"\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\nconst extensionOf = (holder: object, key: string): unknown =>\n (holder as Record<string, unknown>)[key]\n\n/** Read `x-mockingbird` from an operation, applying defaults. */\nexport const operationMetadata = (operation: OperationObject): OperationMetadata => {\n const raw = extensionOf(operation, EXTENSION_KEYS.operation)\n const ext: OperationExtension = isRecord(raw) ? (raw as OperationExtension) : {}\n const supported = ext.supported ?? true\n const parity = ext.parity ?? {}\n return {\n supported,\n reason: typeof ext.reason === \"string\" ? ext.reason : undefined,\n parity: {\n enabled: supported && (parity.enabled ?? true),\n safe: parity.safe ?? true,\n reason: typeof parity.reason === \"string\" ? parity.reason : undefined,\n },\n }\n}\n\nconst readResource = (raw: unknown): SchemaMetadata[\"resource\"] => {\n if (!isRecord(raw) || typeof raw.type !== \"string\" || raw.identity !== true) return undefined\n return { type: raw.type, identity: true }\n}\n\nconst readResourceRef = (raw: unknown): SchemaMetadata[\"resourceRef\"] => {\n if (!isRecord(raw) || typeof raw.type !== \"string\") return undefined\n return { type: raw.type, ...(typeof raw.missing === \"string\" ? { missing: raw.missing } : {}) }\n}\n\nconst readVolatile = (raw: unknown): SchemaMetadata[\"volatile\"] => {\n if (!isRecord(raw) || typeof raw.kind !== \"string\") return undefined\n const kind = VOLATILE_KINDS.find((k) => k === raw.kind)\n return kind === undefined ? undefined : { kind }\n}\n\nconst readScope = (raw: unknown): SchemaMetadata[\"scope\"] => {\n if (!isRecord(raw) || typeof raw.value !== \"string\") return undefined\n const value = SCOPE_VALUES.find((v) => v === raw.value)\n return value === undefined ? undefined : { value }\n}\n\nconst readUnsupported = (raw: unknown): SchemaMetadata[\"unsupported\"] => {\n if (raw === true) return { reason: undefined }\n if (isRecord(raw)) return { reason: typeof raw.reason === \"string\" ? raw.reason : undefined }\n return undefined\n}\n\n/**\n * Read Mockingbird's schema-level extensions from a (resolved) schema or parameter.\n * Extensions on a `$ref` wrapper win over the target's, matching {@link resolveSchema}.\n */\nexport const schemaMetadata = (holder: SchemaObject | ParameterObject): SchemaMetadata => ({\n resource: readResource(extensionOf(holder, EXTENSION_KEYS.resource)),\n resourceRef: readResourceRef(extensionOf(holder, EXTENSION_KEYS.resourceRef)),\n volatile: readVolatile(extensionOf(holder, EXTENSION_KEYS.volatile)),\n scope: readScope(extensionOf(holder, EXTENSION_KEYS.scope)),\n unsupported: readUnsupported(extensionOf(holder, EXTENSION_KEYS.unsupported)),\n})\n\n/** Metadata of a parameter: extensions on the parameter itself win over its schema's. */\nexport const parameterMetadata = (\n document: OpenAPIDocument,\n parameter: ParameterObject,\n): SchemaMetadata => {\n const own = schemaMetadata(parameter)\n const fromSchema = parameter.schema\n ? schemaMetadata(resolveSchema(document, parameter.schema))\n : undefined\n return {\n resource: own.resource ?? fromSchema?.resource,\n resourceRef: own.resourceRef ?? fromSchema?.resourceRef,\n volatile: own.volatile ?? fromSchema?.volatile,\n scope: own.scope ?? fromSchema?.scope,\n unsupported: own.unsupported ?? fromSchema?.unsupported,\n }\n}\n\n/** Lower-cased names of response headers flagged with `x-mockingbird-parity-header: true`. */\nexport const parityHeaders = (document: OpenAPIDocument, response: ResponseObject): string[] => {\n const names: string[] = []\n for (const [name, raw] of Object.entries(response.headers ?? {})) {\n const header = deref<HeaderObject>(document, raw)\n if (extensionOf(header, EXTENSION_KEYS.parityHeader) === true) names.push(name.toLowerCase())\n }\n return names.sort()\n}\n", "import type { FetchAPI } from \"@crvouga/mockingbird-core\"\nimport {\n type DecodedBody,\n decodeFormPairs,\n type FormObject,\n readBody,\n} from \"@crvouga/mockingbird-http-codec\"\nimport { listOperations, type OpenAPIDocument, type Operation } from \"@crvouga/mockingbird-openapi\"\nimport { operationMetadata } from \"@crvouga/mockingbird-openapi-metadata\"\nimport {\n clearNamespace,\n migrateCore,\n resolveSqlite,\n type SqliteClient,\n} from \"@crvouga/mockingbird-sqlite\"\nimport { type Context, Hono } from \"hono\"\n\n/** Options every provider constructor accepts. */\nexport type APIOptions = {\n /** Sync SQLite client. Defaults to `@crvouga/mockingbird-service-sqlite`. */\n sqlite?: SqliteClient\n /** Clock used for `created`-style fields. Default `Date.now`. */\n now?: () => number\n /**\n * Storage namespace for this instance's records. Instances sharing one SQLite\n * client stay isolated when their namespaces differ. Defaults to the service name.\n */\n namespace?: string\n}\n\nexport type OperationContext = {\n request: Request\n url: URL\n /** Path parameters. */\n params: Record<string, string>\n /** Query string decoded with bracket notation (`created[gte]=1` -> `{ created: { gte: \"1\" } }`). */\n query: FormObject\n body: DecodedBody\n /** Shared SQLite client for this service (already migrated). */\n sqlite: SqliteClient\n /** Service namespace used for records / sequences. */\n namespace: string\n operation: Operation\n /** The vendor contract the service was built from. */\n document: OpenAPIDocument\n now: () => number\n}\n\nexport type OperationHandler = (context: OperationContext) => Promise<Response> | Response\n\nexport type OperationHandlers = Record<string, OperationHandler>\n\n/** Identity helper that keeps handler maps type-checked against a fixed set of operation ids. */\nexport const defineOperations = <Id extends string>(\n handlers: Record<Id, OperationHandler>,\n): Record<Id, OperationHandler> => handlers\n\nexport class OperationRegistryError extends Error {\n constructor(readonly problems: string[]) {\n super(`operation registry is inconsistent:\\n${problems.map((p) => ` - ${p}`).join(\"\\n\")}`)\n this.name = \"OperationRegistryError\"\n }\n}\n\n/**\n * Cross-check handlers against the document: every supported operation needs exactly one\n * handler, no handler may target an unknown or unsupported operation, no duplicate ids.\n */\nexport const verifyOperations = (\n document: OpenAPIDocument,\n handlers: OperationHandlers,\n): string[] => {\n const problems: string[] = []\n const operations = listOperations(document)\n const seen = new Set<string>()\n for (const operation of operations) {\n if (seen.has(operation.operationId))\n problems.push(`duplicate operationId ${operation.operationId}`)\n seen.add(operation.operationId)\n const supported = operationMetadata(operation.operation).supported\n const handler = handlers[operation.operationId]\n if (supported && !handler)\n problems.push(`supported operation ${operation.operationId} has no handler`)\n if (!supported && handler)\n problems.push(`operation ${operation.operationId} is marked unsupported but has a handler`)\n }\n for (const id of Object.keys(handlers)) {\n if (!seen.has(id)) problems.push(`handler ${id} has no OpenAPI operation`)\n }\n return problems\n}\n\nexport type ServiceOptions = {\n document: OpenAPIDocument\n handlers: OperationHandlers\n sqlite: SqliteClient\n /** Namespace isolating this service's records and sequences. */\n namespace: string\n now?: (() => number) | undefined\n /** Response for paths/methods outside the contract. */\n notFound: (request: Request) => Response | Promise<Response>\n /** Response for operations declared but marked `supported: false`. Default: `notFound`. */\n unsupported?: (request: Request, operation: Operation) => Response | Promise<Response>\n /** Convert handler exceptions into a provider-shaped response. */\n onError: (error: unknown, request: Request) => Response | Promise<Response>\n /** Runs before every operation; return a Response to short-circuit (e.g. authentication). */\n before?: (context: OperationContext) => Promise<Response | undefined> | Response | undefined\n}\n\nexport type Service = FetchAPI & {\n app: Hono\n sqlite: SqliteClient\n namespace: string\n /** Delete every record and sequence in the service namespace. */\n reset(): Promise<void>\n}\n\nconst honoPath = (template: string) => template.replace(/\\{([^}]+)\\}/g, \":$1\")\n\n/** Static segments before parameters so `/v1/customers/search` beats `/v1/customers/:id`. */\nconst routeOrder = (a: Operation, b: Operation) => {\n const sa = a.path.split(\"/\")\n const sb = b.path.split(\"/\")\n for (let i = 0; i < Math.max(sa.length, sb.length); i++) {\n const x = sa[i] ?? \"\"\n const y = sb[i] ?? \"\"\n const px = x.startsWith(\"{\")\n const py = y.startsWith(\"{\")\n if (px !== py) return px ? 1 : -1\n if (x !== y) return x < y ? -1 : 1\n }\n return 0\n}\n\nconst queryOf = (url: URL): FormObject => decodeFormPairs(url.searchParams.entries())\n\n/**\n * Resolve optional `sqlite`, run core migrations, and return the ready client.\n * Call this from every provider constructor before building state.\n */\nexport const bootSqlite = (sqlite?: SqliteClient): SqliteClient => {\n const client = resolveSqlite(sqlite)\n migrateCore(client)\n return client\n}\n\n/** Build a Fetch-native service whose routes are exactly the document's operations. */\nexport const createService = (options: ServiceOptions): Service => {\n const problems = verifyOperations(options.document, options.handlers)\n if (problems.length > 0) throw new OperationRegistryError(problems)\n migrateCore(options.sqlite)\n const now = options.now ?? (() => Date.now())\n const app = new Hono()\n app.notFound((c) => options.notFound(c.req.raw))\n app.onError((error, c) => options.onError(error, c.req.raw))\n\n const operations = [...listOperations(options.document)].sort(routeOrder)\n for (const operation of operations) {\n const metadata = operationMetadata(operation.operation)\n const handler = options.handlers[operation.operationId]\n const route = async (c: Context) => {\n const request = c.req.raw\n if (!metadata.supported || !handler) {\n return options.unsupported\n ? options.unsupported(request, operation)\n : options.notFound(request)\n }\n const url = new URL(request.url)\n const context: OperationContext = {\n request,\n url,\n params: c.req.param(),\n query: queryOf(url),\n body: await readBody(request),\n sqlite: options.sqlite,\n namespace: options.namespace,\n operation,\n document: options.document,\n now,\n }\n const short = await options.before?.(context)\n if (short) return short\n return handler(context)\n }\n app.on(operation.method.toUpperCase(), honoPath(operation.path), route)\n }\n\n return {\n app,\n sqlite: options.sqlite,\n namespace: options.namespace,\n fetch: async (request) => app.fetch(request),\n reset: async () => {\n clearNamespace(options.sqlite, options.namespace)\n },\n }\n}\n", "import { Timeline } from \"@crvouga/mockingbird-core\"\nimport type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\n\n/**\n * A point-in-time copy of everything a service namespace holds.\n *\n * All service state lives in the two core tables keyed by namespace, so a snapshot\n * is generic: any service gets per-test rollback without knowing its own schema.\n * Restoring is much cheaper than rebuilding a namespace from a corpus.\n */\nexport type NamespaceSnapshot = {\n namespace: string\n records: { collection: string; id: string; seq: number; value: string }[]\n sequences: { name: string; kind: string; value: number }[]\n}\n\n/**\n * @deprecated Low-level Timeline payload capture retained for API compatibility. Provider code\n * must use the runtime Timeline or `withNamespaceRollback`.\n */\nexport const snapshotNamespace = (sqlite: SqliteClient, namespace: string): NamespaceSnapshot => ({\n namespace,\n records: sqlite\n .prepare(\n \"SELECT collection, id, seq, value FROM mockingbird_records WHERE namespace = ? ORDER BY collection, seq\",\n )\n .all<{ collection: string; id: string; seq: number; value: string }>(namespace),\n sequences: sqlite\n .prepare(\n \"SELECT name, kind, value FROM mockingbird_sequences WHERE namespace = ? ORDER BY name, kind\",\n )\n .all<{ name: string; kind: string; value: number }>(namespace),\n})\n\n/**\n * Replace a namespace's contents with `snapshot`. The namespace is emptied first,\n * so restoring is an assignment, not a merge \u2014 records created since the snapshot\n * are gone afterwards.\n *\n * @deprecated Low-level Timeline payload restore retained for API compatibility. Provider code\n * must use the runtime Timeline or `withNamespaceRollback`.\n */\nexport const restoreNamespace = (\n sqlite: SqliteClient,\n namespace: string,\n snapshot: NamespaceSnapshot,\n): void => {\n sqlite.transaction(() => {\n sqlite.prepare(\"DELETE FROM mockingbird_records WHERE namespace = ?\").run(namespace)\n sqlite.prepare(\"DELETE FROM mockingbird_sequences WHERE namespace = ?\").run(namespace)\n const record = sqlite.prepare(\n \"INSERT INTO mockingbird_records (namespace, collection, id, seq, value) VALUES (?, ?, ?, ?, ?)\",\n )\n for (const row of snapshot.records) {\n record.run(namespace, row.collection, row.id, row.seq, row.value)\n }\n const sequence = sqlite.prepare(\n \"INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, ?, ?)\",\n )\n for (const row of snapshot.sequences) {\n sequence.run(namespace, row.name, row.kind, row.value)\n }\n })\n}\n\n/**\n * Execute asynchronous service work atomically using the canonical Timeline rollback primitive.\n * This is the prescribed escape hatch when the SQLite adapter cannot hold a transaction across\n * `await`; service code should not coordinate raw namespace snapshots itself.\n */\nexport const withNamespaceRollback = async <T>(\n sqlite: SqliteClient,\n namespace: string,\n run: () => Promise<T>,\n): Promise<T> => {\n const rollback = new Timeline<NamespaceSnapshot>({ maxCheckpoints: 1 })\n const before = rollback.commit(snapshotNamespace(sqlite, namespace))\n try {\n return await run()\n } catch (error) {\n restoreNamespace(sqlite, namespace, before.value)\n throw error\n }\n}\n", "/**\n * Set by `scripts/bundle-service.ts` when a service is bundled, and rewritten to the\n * released version when it is published. Undefined when running from source.\n */\ndeclare const __MOCKINGBIRD_PACKAGE_VERSION__: string | undefined\n\n/** Placeholder a bundle carries until `release:publish` writes the real version over it. */\nexport const UNRELEASED_VERSION = \"0.0.0-development\"\n\n/** The published version of the service package this code is bundled into. */\nexport const PACKAGE_VERSION: string =\n typeof __MOCKINGBIRD_PACKAGE_VERSION__ === \"string\"\n ? __MOCKINGBIRD_PACKAGE_VERSION__\n : UNRELEASED_VERSION\n", "/**\n * HMAC and encoding primitives for vendor webhook signatures, over WebCrypto so they run\n * wherever the mocks do (Node, Bun, workers).\n */\n\nexport type HmacAlgorithm = \"SHA-1\" | \"SHA-256\" | \"SHA-512\"\nexport type ByteEncoding = \"hex\" | \"base64\"\n\nconst encoder = new TextEncoder()\n\nexport const toBase64 = (bytes: ArrayBuffer | Uint8Array): string => {\n let binary = \"\"\n for (const byte of bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)) {\n binary += String.fromCharCode(byte)\n }\n return btoa(binary)\n}\n\nexport const fromBase64 = (value: string): Uint8Array =>\n Uint8Array.from(atob(value), (char) => char.charCodeAt(0))\n\nexport const toHex = (bytes: ArrayBuffer | Uint8Array): string =>\n [...(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes))]\n .map((byte) => byte.toString(16).padStart(2, \"0\"))\n .join(\"\")\n\nconst keyBytes = (key: string | Uint8Array): Uint8Array =>\n typeof key === \"string\" ? encoder.encode(key) : key\n\n/** HMAC of `message` under `key` (a UTF-8 string or raw bytes), encoded as hex or base64. */\nexport const hmac = async (\n algorithm: HmacAlgorithm,\n key: string | Uint8Array,\n message: string | Uint8Array,\n encoding: ByteEncoding = \"hex\",\n): Promise<string> => {\n const imported = await crypto.subtle.importKey(\n \"raw\",\n keyBytes(key) as BufferSource,\n { name: \"HMAC\", hash: algorithm },\n false,\n [\"sign\"],\n )\n const signed = await crypto.subtle.sign(\n \"HMAC\",\n imported,\n (typeof message === \"string\" ? encoder.encode(message) : message) as BufferSource,\n )\n return encoding === \"hex\" ? toHex(signed) : toBase64(signed)\n}\n\n/** SHA digest of `input`, hex-encoded. */\nexport const sha = async (\n algorithm: \"SHA-1\" | \"SHA-256\" | \"SHA-512\",\n input: string | Uint8Array,\n): Promise<string> =>\n toHex(\n await crypto.subtle.digest(\n algorithm,\n (typeof input === \"string\" ? encoder.encode(input) : input) as BufferSource,\n ),\n )\n\n/**\n * The raw key of a Svix-style secret: `whsec_<base64>` (Svix, Resend, Junction) or\n * `fwhsec_<base64>` (Flex). A bare base64 secret is accepted too.\n */\nexport const svixSecretBytes = (secret: string): Uint8Array => {\n const raw = secret.replace(/^f?whsec_/, \"\")\n try {\n return fromBase64(raw)\n } catch {\n throw new TypeError(\"webhook secret must be whsec_<base64> (as Svix issues it)\")\n }\n}\n\n/** `v1,<base64 HMAC-SHA256>` over `\"<id>.<timestamp>.<body>\"`, as Svix signs. */\nexport const signSvix = async (\n secret: string,\n messageId: string,\n timestampSeconds: number,\n body: string,\n): Promise<string> =>\n `v1,${await hmac(\"SHA-256\", svixSecretBytes(secret), `${messageId}.${timestampSeconds}.${body}`, \"base64\")}`\n\n/** `t=<unix>,v1=<hex HMAC-SHA256(secret, \"<t>.<body>\")>`, as Stripe (and Persona) sign. */\nexport const signTimestamped = async (\n secret: string,\n timestampSeconds: number,\n body: string,\n): Promise<string> =>\n `t=${timestampSeconds},v1=${await hmac(\"SHA-256\", secret, `${timestampSeconds}.${body}`, \"hex\")}`\n\n/**\n * Twilio's `X-Twilio-Signature`: base64 HMAC-SHA1 of the full URL followed by every form\n * parameter as `key + value`, keys sorted. Sign against the public URL the app is\n * configured with, not the address the request is actually posted to.\n */\nexport const signTwilio = async (\n authToken: string,\n url: string,\n params: Record<string, string>,\n): Promise<string> => {\n const payload =\n url +\n Object.keys(params)\n .sort()\n .map((key) => `${key}${params[key]}`)\n .join(\"\")\n return hmac(\"SHA-1\", authToken, payload, \"base64\")\n}\n\n/** Constant-time string comparison, so a verifier in a test double does not leak timing. */\nexport const timingSafeEqual = (a: string, b: string): boolean => {\n if (a.length !== b.length) return false\n let diff = 0\n for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i)\n return diff === 0\n}\n", "import type { AdminRoutes } from \"./control.js\"\nimport { signSvix, signTimestamped, signTwilio } from \"./signing.js\"\n\n/**\n * Outbound webhooks, shared by every service that has them.\n *\n * A service publishes a message (the exact bytes the vendor would send); the hub fans it out\n * to every matching endpoint, signs each delivery with the vendor's scheme, retries on the\n * vendor's schedule, and keeps a record a suite can read, replay or flush through\n * `/__admin/webhooks*`. Signature timestamps always use the wall clock, never the mock\n * clock: receivers check them against their own time, and an advanced mock clock would\n * otherwise fail every delivery.\n */\n\n/** What a signer sees for one delivery attempt. */\nexport type SignInput = {\n messageId: string\n /** Exact bytes about to be sent. */\n body: string\n /** Wall-clock unix seconds of this attempt. */\n timestampSeconds: number\n /** Where the delivery is posted. */\n url: string\n /** The endpoint's secret, if it has one. */\n secret: string | undefined\n /** The endpoint's `signUrl` (the public URL the receiver verifies against), else `url`. */\n signUrl: string\n /** Form parameters, when the body is form-encoded (Twilio signs these, not the body). */\n form: Record<string, string> | undefined\n /** Stable event type and metadata captured with the message; avoids signer side-channel state. */\n type: string\n tags: Readonly<Record<string, string>>\n}\n\n/** Headers to add to one delivery. */\nexport type WebhookSigner = (\n input: SignInput,\n) => Record<string, string> | Promise<Record<string, string>>\n\n/** Named signers for the vendor schemes the catalog needs. */\nexport const signers = {\n /** No signature. */\n none: (): WebhookSigner => () => ({}),\n /** Svix (`svix-id`, `svix-timestamp`, `svix-signature: v1,<b64>`): Junction, Flex, Resend. */\n svix:\n (options: { prefix?: \"svix\" | \"webhook\" } = {}): WebhookSigner =>\n async ({ messageId, body, timestampSeconds, secret }) => {\n if (!secret) return {}\n const prefix = options.prefix ?? \"svix\"\n return {\n [`${prefix}-id`]: messageId,\n [`${prefix}-timestamp`]: String(timestampSeconds),\n [`${prefix}-signature`]: await signSvix(secret, messageId, timestampSeconds, body),\n }\n },\n /** `<header>: t=<unix>,v1=<hex HMAC-SHA256(secret, \"t.body\")>`: Stripe, Persona, Fullscript. */\n timestamped:\n (header = \"Stripe-Signature\"): WebhookSigner =>\n async ({ body, timestampSeconds, secret }) =>\n secret ? { [header]: await signTimestamped(secret, timestampSeconds, body) } : {},\n /** `X-Twilio-Signature` over the public URL plus the sorted form parameters. */\n twilio:\n (): WebhookSigner =>\n async ({ signUrl, form, secret }) =>\n secret ? { \"X-Twilio-Signature\": await signTwilio(secret, signUrl, form ?? {}) } : {},\n /** The secret itself in a header (optionally templated): RxVortex, Pharmetika, AHA `Token <s>`. */\n header:\n (header: string, format: (secret: string) => string = (s) => s): WebhookSigner =>\n ({ secret }) =>\n secret ? { [header]: format(secret) } : {},\n /** Anything else: the service computes the headers itself. */\n custom: (sign: WebhookSigner): WebhookSigner => sign,\n}\n\nexport type WebhookEndpoint = {\n /** Stable id; generated when omitted. */\n id?: string\n url: string\n secret?: string\n /** Event types to deliver; omit or include `\"*\"` for every type. */\n events?: string[]\n /** Deliver only messages whose tags include all of these (e.g. `{ account: \"mso\" }`). */\n tags?: Record<string, string>\n /** The public URL the receiver verifies signatures against (Twilio), when it differs. */\n signUrl?: string\n headers?: Record<string, string>\n}\n\nexport type WebhookMessage = {\n id: string\n namespace: string\n type: string\n body: string\n contentType: string\n tags: Record<string, string>\n headers?: Record<string, string>\n /** Wall-clock ISO-8601 time of publication. */\n publishedAt: string\n}\n\nexport type WebhookAttempt = {\n attempt: number\n at: string\n status: number | null\n error: string | null\n durationMs: number\n /** Exact receiver response body, when one was returned. */\n responseBody?: string | null\n}\n\nexport type WebhookDelivery = {\n id: string\n messageId: string\n namespace: string\n type: string\n endpointId: string\n url: string\n state: \"pending\" | \"delivered\" | \"failed\" | \"dropped\"\n attempts: WebhookAttempt[]\n}\n\n/** A delivery-level fault: what happens to the next `count` messages in a namespace. */\nexport type WebhookFault = {\n mode: \"duplicate\" | \"reorder\" | \"drop\"\n /** Messages affected; default 1. */\n count?: number\n}\n\nexport type PublishInput = {\n namespace: string\n type: string\n /** Exact body; objects are JSON-encoded. */\n body: string | Record<string, unknown> | unknown[]\n /** Default `application/json`, or form-encoded when `form` is given. */\n contentType?: string\n /** Form parameters, when the vendor posts `application/x-www-form-urlencoded`. */\n form?: Record<string, string>\n tags?: Record<string, string>\n /** Message-specific delivery headers, captured as part of durable message state. */\n headers?: Record<string, string>\n /** Message id; generated when omitted. */\n id?: string\n}\n\nexport type WebhookHubOptions = {\n signer: WebhookSigner\n /**\n * Delay before each attempt, in ms; the first entry delays the first attempt. Default:\n * immediately, then 5 s, 5 min, 30 min, 2 h.\n */\n retryDelaysMs?: readonly number[]\n /** Abort an attempt after this long. Default 15 s. */\n timeoutMs?: number\n /** Which receiver statuses count as delivered. Default 2xx. */\n delivered?: (status: number) => boolean\n /** Endpoints every namespace delivers to (from `--webhook-url`). */\n endpoints?: WebhookEndpoint[]\n fetch?: (request: Request) => Promise<Response>\n /** Called in-process for every published message, delivered or not. */\n onMessage?: (message: WebhookMessage) => void\n /** Messages kept per namespace for `GET /__admin/webhooks/events`. Default 500. */\n keep?: number\n /** Injectable wall clock for signatures and attempt records. */\n now?: () => number\n /** Injectable deterministic identifier source. Receives `\"msg_\"` or `\"dlv_\"`. */\n id?: (prefix: string) => string\n /** Injectable scheduler used by timeouts and retries. */\n schedule?: (callback: () => void, delayMs: number) => unknown\n cancel?: (handle: unknown) => void\n}\n\nexport type WebhookHub = {\n publish(input: PublishInput): WebhookMessage\n /** Replace a namespace's own endpoints (`PUT /__admin/webhook-endpoints`). */\n setEndpoints(namespace: string, endpoints: WebhookEndpoint[]): WebhookEndpoint[]\n /** The endpoints a namespace delivers to: its own, plus the global ones. */\n endpoints(namespace: string): WebhookEndpoint[]\n messages(namespace?: string): WebhookMessage[]\n deliveries(namespace?: string): WebhookDelivery[]\n replay(deliveryId: string): Promise<WebhookDelivery | undefined>\n /** Run every pending retry (and release held reordered messages) now. */\n flush(): Promise<void>\n /** Resolve once nothing is in flight. */\n idle(): Promise<void>\n fault(namespace: string, fault: WebhookFault): void\n clear(namespace?: string): void\n}\n\nconst DEFAULT_DELAYS = [0, 5_000, 300_000, 1_800_000, 7_200_000] as const\n\nconst unref = (timer: unknown) => {\n ;(timer as { unref?: () => void }).unref?.()\n}\n\nconst randomId = (prefix: string) =>\n `${prefix}${crypto.randomUUID().replace(/-/g, \"\").slice(0, 24)}`\n\nconst matchesEndpoint = (endpoint: WebhookEndpoint, message: WebhookMessage): boolean => {\n const events = endpoint.events ?? [\"*\"]\n if (!events.includes(\"*\") && !events.includes(message.type)) return false\n for (const [key, value] of Object.entries(endpoint.tags ?? {})) {\n if (message.tags[key] !== value) return false\n }\n return true\n}\n\nexport const createWebhookHub = (options: WebhookHubOptions): WebhookHub => {\n const delays = options.retryDelaysMs ?? DEFAULT_DELAYS\n const timeoutMs = options.timeoutMs ?? 15_000\n const delivered = options.delivered ?? ((status: number) => status >= 200 && status < 300)\n const send = options.fetch ?? ((request: Request) => fetch(request))\n const keep = options.keep ?? 500\n const now = options.now ?? Date.now\n const id = options.id ?? randomId\n const scheduleTimer =\n options.schedule ?? ((callback: () => void, delayMs: number) => setTimeout(callback, delayMs))\n const cancel =\n options.cancel ?? ((handle: unknown) => clearTimeout(handle as ReturnType<typeof setTimeout>))\n const global = (options.endpoints ?? []).map((e, i) => ({ ...e, id: e.id ?? `we_global_${i}` }))\n const own = new Map<string, WebhookEndpoint[]>()\n const messages: WebhookMessage[] = []\n const deliveries = new Map<string, WebhookDelivery>()\n const pending = new Map<string, unknown | undefined>()\n const payloads = new Map<string, { message: WebhookMessage; endpoint: WebhookEndpoint }>()\n const faults = new Map<string, { mode: WebhookFault[\"mode\"]; remaining: number }[]>()\n const held = new Map<string, WebhookMessage[]>()\n const inFlight = new Set<Promise<void>>()\n\n const track = (work: Promise<void>) => {\n inFlight.add(work)\n void work.finally(() => inFlight.delete(work))\n }\n\n const attempt = async (delivery: WebhookDelivery): Promise<boolean> => {\n const entry = payloads.get(delivery.id)\n if (!entry) return false\n const { message, endpoint } = entry\n const timestampSeconds = Math.floor(now() / 1000)\n const started = now()\n const record: WebhookAttempt = {\n attempt: delivery.attempts.length + 1,\n at: new Date(started).toISOString(),\n status: null,\n error: null,\n durationMs: 0,\n responseBody: null,\n }\n const controller = new AbortController()\n const timer = scheduleTimer(() => controller.abort(), timeoutMs)\n try {\n const signed = await options.signer({\n messageId: message.id,\n body: message.body,\n timestampSeconds,\n url: endpoint.url,\n secret: endpoint.secret,\n signUrl: endpoint.signUrl ?? endpoint.url,\n form: message.contentType.startsWith(\"application/x-www-form-urlencoded\")\n ? Object.fromEntries(new URLSearchParams(message.body))\n : undefined,\n type: message.type,\n tags: message.tags,\n })\n const response = await send(\n new Request(endpoint.url, {\n method: \"POST\",\n headers: {\n \"content-type\": message.contentType,\n ...endpoint.headers,\n ...message.headers,\n ...signed,\n },\n body: message.body,\n signal: controller.signal,\n }),\n )\n record.status = response.status\n record.responseBody = await response.text()\n } catch (error) {\n record.error = controller.signal.aborted\n ? `timed out after ${timeoutMs}ms`\n : error instanceof Error\n ? error.message\n : String(error)\n } finally {\n cancel(timer)\n record.durationMs = now() - started\n delivery.attempts.push(record)\n }\n return record.status !== null && delivered(record.status)\n }\n\n const schedule = (delivery: WebhookDelivery) => {\n const index = delivery.attempts.length\n if (index >= delays.length) {\n delivery.state = \"failed\"\n pending.delete(delivery.id)\n return\n }\n const run = () => {\n pending.delete(delivery.id)\n track(\n attempt(delivery).then((ok) => {\n if (ok) delivery.state = \"delivered\"\n else schedule(delivery)\n }),\n )\n }\n const delay = delays[index] ?? 0\n if (delay <= 0) {\n pending.set(delivery.id, undefined)\n run()\n return\n }\n const timer = scheduleTimer(run, delay)\n unref(timer)\n pending.set(delivery.id, timer)\n }\n\n const endpointsFor = (namespace: string) => [...(own.get(namespace) ?? []), ...global]\n\n const fanOut = (message: WebhookMessage, state: WebhookDelivery[\"state\"] = \"pending\") => {\n for (const endpoint of endpointsFor(message.namespace)) {\n if (!matchesEndpoint(endpoint, message)) continue\n const delivery: WebhookDelivery = {\n id: id(\"dlv_\"),\n messageId: message.id,\n namespace: message.namespace,\n type: message.type,\n endpointId: endpoint.id ?? \"we_unknown\",\n url: endpoint.url,\n state,\n attempts: [],\n }\n deliveries.set(delivery.id, delivery)\n payloads.set(delivery.id, { message, endpoint })\n if (state === \"pending\") schedule(delivery)\n }\n }\n\n const takeFault = (namespace: string): WebhookFault[\"mode\"] | undefined => {\n const queue = faults.get(namespace)\n const head = queue?.[0]\n if (!queue || !head) return undefined\n head.remaining--\n if (head.remaining <= 0) queue.shift()\n return head.mode\n }\n\n const releaseHeld = (namespace: string) => {\n const waiting = held.get(namespace)\n if (!waiting) return\n held.delete(namespace)\n for (const message of waiting) fanOut(message)\n }\n\n const hub: WebhookHub = {\n publish(input) {\n const contentType =\n input.contentType ?? (input.form ? \"application/x-www-form-urlencoded\" : \"application/json\")\n const body =\n typeof input.body === \"string\"\n ? input.body\n : input.form\n ? new URLSearchParams(input.form).toString()\n : JSON.stringify(input.body)\n const message: WebhookMessage = {\n id: input.id ?? id(\"msg_\"),\n namespace: input.namespace,\n type: input.type,\n body,\n contentType,\n tags: input.tags ?? {},\n headers: input.headers ?? {},\n publishedAt: new Date(now()).toISOString(),\n }\n messages.push(message)\n const ofNamespace = messages.filter((m) => m.namespace === message.namespace)\n const oldest = ofNamespace[0]\n if (ofNamespace.length > keep && oldest) messages.splice(messages.indexOf(oldest), 1)\n options.onMessage?.(message)\n const fault = takeFault(message.namespace)\n if (fault === \"drop\") {\n fanOut(message, \"dropped\")\n return message\n }\n if (fault === \"reorder\") {\n // Held until the next message goes out, so the receiver sees them swapped.\n held.set(message.namespace, [...(held.get(message.namespace) ?? []), message])\n return message\n }\n fanOut(message)\n if (fault === \"duplicate\") fanOut(message)\n releaseHeld(message.namespace)\n return message\n },\n setEndpoints(namespace, endpoints) {\n const withIds = endpoints.map((e, i) => ({ ...e, id: e.id ?? `we_${namespace}_${i}` }))\n own.set(namespace, withIds)\n return withIds\n },\n endpoints: endpointsFor,\n messages: (namespace) =>\n namespace === undefined ? [...messages] : messages.filter((m) => m.namespace === namespace),\n deliveries: (namespace) =>\n [...deliveries.values()].filter((d) => namespace === undefined || d.namespace === namespace),\n async replay(id) {\n const delivery = deliveries.get(id)\n if (!delivery) return undefined\n const ok = await attempt(delivery)\n if (ok) delivery.state = \"delivered\"\n return delivery\n },\n async flush() {\n for (const namespace of [...held.keys()]) releaseHeld(namespace)\n const waiting = [...pending.entries()]\n for (const [id, timer] of waiting) {\n if (timer === undefined) continue\n cancel(timer)\n pending.delete(id)\n const delivery = deliveries.get(id)\n if (!delivery) continue\n track(\n attempt(delivery).then((ok) => {\n if (ok) delivery.state = \"delivered\"\n else schedule(delivery)\n }),\n )\n }\n await hub.idle()\n },\n async idle() {\n while (inFlight.size > 0) await Promise.allSettled([...inFlight])\n },\n fault(namespace, fault) {\n const queue = faults.get(namespace) ?? []\n queue.push({ mode: fault.mode, remaining: Math.max(1, fault.count ?? 1) })\n faults.set(namespace, queue)\n },\n clear(namespace) {\n for (const [id, delivery] of deliveries) {\n if (namespace !== undefined && delivery.namespace !== namespace) continue\n const timer = pending.get(id)\n if (timer !== undefined) cancel(timer)\n pending.delete(id)\n deliveries.delete(id)\n payloads.delete(id)\n }\n for (let i = messages.length - 1; i >= 0; i--) {\n if (namespace === undefined || messages[i]?.namespace === namespace) messages.splice(i, 1)\n }\n if (namespace === undefined) {\n held.clear()\n faults.clear()\n own.clear()\n } else {\n held.delete(namespace)\n faults.delete(namespace)\n own.delete(namespace)\n }\n },\n }\n return hub\n}\n\nconst json = (status: number, body: unknown): Response =>\n new Response(JSON.stringify(body), { status, headers: { \"content-type\": \"application/json\" } })\n\nconst adminError = (status: number, message: string): Response =>\n json(status, { error: { type: \"mockingbird_admin\", message } })\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\nconst parseEndpoint = (value: unknown): WebhookEndpoint | string => {\n if (!isRecord(value) || typeof value.url !== \"string\") return \"each endpoint needs a url\"\n try {\n new URL(value.url)\n } catch {\n return `not a URL: ${value.url}`\n }\n const endpoint: WebhookEndpoint = { url: value.url }\n if (typeof value.id === \"string\") endpoint.id = value.id\n if (typeof value.secret === \"string\") endpoint.secret = value.secret\n if (typeof value.signUrl === \"string\") endpoint.signUrl = value.signUrl\n const events = value.events ?? value.enabledEvents\n if (Array.isArray(events)) endpoint.events = events.map(String)\n if (isRecord(value.tags)) {\n endpoint.tags = Object.fromEntries(Object.entries(value.tags).map(([k, v]) => [k, String(v)]))\n }\n if (typeof value.account === \"string\")\n endpoint.tags = { ...endpoint.tags, account: value.account }\n if (isRecord(value.headers)) {\n endpoint.headers = Object.fromEntries(\n Object.entries(value.headers).map(([k, v]) => [k, String(v)]),\n )\n }\n return endpoint\n}\n\n/**\n * The standard webhook admin routes, for a runtime that owns `hub`:\n *\n * - `GET /webhooks` deliveries, `GET /webhooks/events` published messages (with bodies:\n * they are the mock's own output), `POST /webhooks/:id/replay`, `POST /webhooks/flush`\n * - `GET|PUT|DELETE /webhook-endpoints` per namespace\n * - `POST /webhooks/faults {mode: duplicate|reorder|drop, count?}`\n */\nexport const webhookAdminRoutes = (hub: WebhookHub): AdminRoutes => ({\n \"GET /webhooks\": ({ url, namespace }) =>\n json(200, {\n deliveries: hub\n .deliveries(url.searchParams.get(\"all\") === \"1\" ? undefined : namespace)\n .filter((d) => {\n const type = url.searchParams.get(\"type\")\n return type === null || d.type === type\n }),\n }),\n \"GET /webhooks/events\": ({ url, namespace }) => {\n const type = url.searchParams.get(\"type\")\n return json(200, {\n events: hub\n .messages(url.searchParams.get(\"all\") === \"1\" ? undefined : namespace)\n .filter((m) => type === null || m.type === type)\n .map((m) => ({ ...m, payload: parsePayload(m) })),\n })\n },\n \"POST /webhooks/:id/replay\": async ({ params }) => {\n const replayed = await hub.replay(params.id as string)\n return replayed ? json(200, replayed) : adminError(404, `no delivery ${params.id}`)\n },\n \"POST /webhooks/flush\": async () => {\n await hub.flush()\n return json(200, { status: \"ok\" })\n },\n \"POST /webhooks/faults\": ({ body, namespace }) => {\n if (!isRecord(body) || ![\"duplicate\", \"reorder\", \"drop\"].includes(String(body.mode))) {\n return adminError(400, \"mode must be duplicate, reorder or drop\")\n }\n const fault: WebhookFault = { mode: body.mode as WebhookFault[\"mode\"] }\n if (typeof body.count === \"number\") fault.count = body.count\n hub.fault(namespace, fault)\n return json(201, { namespace, ...fault })\n },\n \"GET /webhook-endpoints\": ({ namespace }) =>\n json(200, {\n endpoints: hub.endpoints(namespace).map(({ secret, ...rest }) => ({\n ...rest,\n secret: secret ? \"(set)\" : null,\n })),\n }),\n \"PUT /webhook-endpoints\": ({ body, namespace }) => {\n const list = Array.isArray(body) ? body : isRecord(body) ? body.endpoints : undefined\n if (!Array.isArray(list)) return adminError(400, \"expected [{url, secret?, events?}]\")\n const parsed: WebhookEndpoint[] = []\n for (const each of list) {\n const endpoint = parseEndpoint(each)\n if (typeof endpoint === \"string\") return adminError(400, endpoint)\n parsed.push(endpoint)\n }\n const set = hub.setEndpoints(namespace, parsed)\n return json(200, { endpoints: set.map((e) => ({ ...e, secret: e.secret ? \"(set)\" : null })) })\n },\n \"DELETE /webhook-endpoints\": ({ namespace }) => {\n hub.setEndpoints(namespace, [])\n return json(200, { status: \"ok\" })\n },\n})\n\nconst parsePayload = (message: WebhookMessage): unknown => {\n if (message.contentType.startsWith(\"application/json\")) {\n try {\n return JSON.parse(message.body)\n } catch {\n return message.body\n }\n }\n if (message.contentType.startsWith(\"application/x-www-form-urlencoded\")) {\n return Object.fromEntries(new URLSearchParams(message.body))\n }\n return message.body\n}\n", "import { type Checkpoint, type FetchAPI, Timeline } from \"@crvouga/mockingbird-core\"\nimport { listOperations, type OpenAPIDocument } from \"@crvouga/mockingbird-openapi\"\nimport { clearNamespace, type SqliteClient } from \"@crvouga/mockingbird-sqlite\"\nimport { type Clock, createClock } from \"./clock.js\"\nimport { type AdminRoutes, createControlPlane, NAMESPACE_HEADER } from \"./control.js\"\nimport { type CredentialRegistry, createCredentialRegistry, maskCredential } from \"./credentials.js\"\nimport {\n createFaultRegistry,\n type FaultHit,\n type FaultPreset,\n type FaultRegistry,\n type FaultRule,\n} from \"./faults.js\"\nimport { createJournal, DEFAULT_JOURNAL_SIZE, type Journal, responseNotes } from \"./journal.js\"\nimport { createMetrics, type Metrics, type RequestLog } from \"./metrics.js\"\nimport { createRng, type Rng, seedFrom } from \"./rng.js\"\nimport { bootSqlite } from \"./service.js\"\nimport { type NamespaceSnapshot, restoreNamespace, snapshotNamespace } from \"./snapshot.js\"\nimport { PACKAGE_VERSION } from \"./version.js\"\nimport { type WebhookHub, webhookAdminRoutes } from \"./webhooks.js\"\n\n/**\n * Stamped on every response the runtime returns \u2014 vendor, fault, admin and health alike \u2014\n * as `<service>@<version>; ns=<namespace>`, so a consumer can tell the mock from the vendor.\n */\nexport const MOCKINGBIRD_HEADER = \"x-mockingbird\"\n/** Selects a named copy-on-write history branch. `main` is the compatibility default. */\nexport const BRANCH_HEADER = \"x-mockingbird-branch\"\n/** Reads a historical checkpoint. With a branch header, initializes that branch from it. */\nexport const AT_HEADER = \"x-mockingbird-at\"\n/** Identifies the resulting checkpoint on successful mutations. */\nexport const CHECKPOINT_HEADER = \"x-mockingbird-checkpoint\"\n\n/** What the runtime needs from a service: a Fetch handler it can reset. */\nexport type ServiceInstance = FetchAPI & { reset(): Promise<void> }\n\n/** Everything an instance shares with the runtime that owns it. */\nexport type InstanceContext = {\n /** Storage namespace for this instance's records. */\n namespace: string\n /** The public namespace name a request selects it by. */\n publicNamespace: string\n sqlite: SqliteClient\n clock: Clock\n rng: Rng\n}\n\nexport type RuntimeOptions<T extends ServiceInstance> = {\n /** Service name, e.g. `\"junction\"`. Also the default namespace's storage key. */\n name: string\n /** Build the instance backing one namespace. Called once per namespace, on first use. */\n create: (context: InstanceContext) => T\n /** The vendor contract, used to name each request's operation in logs, metrics and faults. */\n document?: OpenAPIDocument\n /** Shared by every namespace. Defaults to a fresh `@crvouga/mockingbird-service-sqlite`. */\n sqlite?: SqliteClient\n /** Defaults to a live clock over `Date.now`. */\n clock?: Clock\n /** Seeds every random choice the runtime makes (fault rates). Default `0`. */\n seed?: number | string\n /** Extra `GET /health` fields, such as the loaded corpus version. */\n describe?: () => Record<string, unknown>\n /** Service-specific admin routes, given the runtime so they can reach any namespace. */\n admin?: (runtime: ServiceRuntime<T>) => AdminRoutes\n /** Require this value in `x-mockingbird-admin-key` on `/__admin/*`. Omit to leave admin open. */\n adminKey?: string\n /** Structured request log sink, called once per request. */\n onLog?: (entry: RequestLog) => void\n /** Requests each namespace's journal keeps (`GET /__admin/requests`). Default 1000; 0 turns it off. */\n journalSize?: number\n /** Reported in the `x-mockingbird` header. Default: the bundled package's version. */\n version?: string\n /**\n * The vendor credential a request carries (API key, token, account SID, AWS access key\n * id), for SDKs that cannot send `x-mockingbird-namespace`: a suite maps credentials to\n * namespaces with `PUT /__admin/credentials`. See `bearerToken`, `basicAuth`,\n * `sigV4AccessKeyId`.\n */\n credential?: (request: Request) => string | undefined\n /** Named faults, switched on with `POST /__admin/faults {\"preset\": \"<name>\"}`. */\n presets?: Record<string, FaultPreset>\n /** Outbound webhooks; adds the `/__admin/webhooks*` routes and clears on reset. */\n webhooks?: WebhookHub\n /** Retained time-travel checkpoints per namespace. Default 1,000. */\n maxCheckpoints?: number\n /** Injectable process IO used for observability and delays; logical service time uses `clock`. */\n io?: Partial<RuntimeIO>\n}\n\nexport type RuntimeIO = {\n wallNow(): number\n monotonicNow(): number\n sleep(ms: number): Promise<void>\n}\n\nexport type ServiceTimelineState = Readonly<{\n snapshot: NamespaceSnapshot\n clock: Readonly<ReturnType<Clock[\"state\"]>>\n rngState: number\n}>\n\nexport type ServiceCheckpoint = Checkpoint<ServiceTimelineState>\n\nexport type ServiceRuntime<T extends ServiceInstance> = FetchAPI & {\n readonly name: string\n readonly sqlite: SqliteClient\n readonly clock: Clock\n readonly faults: FaultRegistry\n readonly metrics: Metrics\n readonly journal: Journal\n readonly rng: Rng\n readonly credentials: CredentialRegistry\n /** The webhook hub, when the service has outbound webhooks. */\n readonly webhooks: WebhookHub | undefined\n /** Expand a named preset into fault rules (and webhook faults) for `namespace`. */\n applyPreset(name: string, namespace?: string, overrides?: Partial<FaultRule>): FaultRule[]\n /** The instance behind `namespace` (the default one when omitted), created on first use. */\n instance(namespace?: string): T\n /** Public names of every namespace created so far. */\n namespaces(): string[]\n /** Reset one namespace, or every namespace with `\"*\"`. */\n reset(namespace?: string): Promise<void>\n snapshot(namespace?: string): NamespaceSnapshot\n restore(snapshot: NamespaceSnapshot, namespace?: string): void\n /** Capture the current branch. Mutating HTTP calls do this automatically. */\n checkpoint(namespace?: string, branch?: string): ServiceCheckpoint\n /** Create an isolated branch, optionally from a historical checkpoint. */\n branch(name: string, options?: { namespace?: string; at?: string }): ServiceCheckpoint\n /** Restore a branch, clock, and PRNG to a checkpoint. */\n checkout(checkpoint: string, options?: { namespace?: string; branch?: string }): void\n /** Inspect the retained history for a namespace. */\n timeline(namespace?: string): Timeline<ServiceTimelineState>\n}\n\n/** The namespace used when a request names none. */\nexport const DEFAULT_NAMESPACE = \"default\"\n\nconst NAMESPACE_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/\n\n/** `/ns/<namespace>/\u2026`: the namespace carrier for SDKs that only take a base URL. */\nconst PATH_PREFIX = /^\\/ns\\/([^/]+)(\\/.*)?$/\nconst BRANCH_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/\nconst MUTATING_METHODS = new Set([\"POST\", \"PUT\", \"PATCH\", \"DELETE\"])\n\nconst effects = new WeakMap<Request, FaultHit[\"effect\"][]>()\n\n/**\n * Merge two sorted snapshot row arrays, retaining byte-identical old objects. Unlike the previous\n * Map/string-key implementation this is allocation-free apart from the result array and O(n).\n */\nconst reuseSorted = <T>(\n fresh: T[],\n previous: T[] | undefined,\n compare: (left: T, right: T) => number,\n equal: (left: T, right: T) => boolean,\n): T[] => {\n if (!previous || previous.length === 0) return fresh.map((row) => Object.freeze(row))\n const result = new Array<T>(fresh.length)\n let unchanged = fresh.length === previous.length\n let oldIndex = 0\n for (let index = 0; index < fresh.length; index++) {\n const row = fresh[index] as T\n while (oldIndex < previous.length && compare(previous[oldIndex] as T, row) < 0) {\n oldIndex++\n }\n const old = previous[oldIndex]\n result[index] =\n old !== undefined && compare(old, row) === 0 && equal(old, row) ? old : Object.freeze(row)\n if (result[index] !== previous[index]) unchanged = false\n }\n return unchanged ? previous : result\n}\n\n/**\n * The fault effects (`{\"effect\": \"created_but_500\"}` rules) that fired for this request, in\n * rule order. Handlers read this to switch on a named vendor misbehaviour.\n */\nexport const faultEffects = (\n request: Request,\n): { name: string; params: Record<string, unknown> }[] =>\n (effects.get(request) ?? []).filter((e): e is NonNullable<typeof e> => e !== undefined)\n\n/** Whether the named effect fired for this request; its params when it did. */\nexport const faultEffect = (request: Request, name: string): Record<string, unknown> | undefined =>\n faultEffects(request).find((e) => e.name === name)?.params\n\n/**\n * Thrown by an in-process `runtime.fetch` when a `drop` fault fires: the same thing a real\n * `fetch` does when the connection dies mid-request. A served mock destroys the socket.\n */\nexport class DroppedConnectionError extends TypeError {\n readonly code = \"MOCKINGBIRD_DROP\"\n constructor() {\n super(\"fetch failed: connection dropped by Mockingbird fault\")\n this.name = \"TypeError\"\n }\n}\n\ntype Matcher = { operationId: string; method: string; pattern: RegExp; params: number }\n\n/** Resolve a request to its operationId: static segments beat parameters, as in routing. */\nconst operationMatcher = (document: OpenAPIDocument) => {\n const matchers: Matcher[] = listOperations(document)\n .map((operation) => ({\n operationId: operation.operationId,\n method: operation.method.toUpperCase(),\n pattern: new RegExp(\n `^${operation.path\n .split(\"/\")\n .map((segment) =>\n segment.startsWith(\"{\") ? \"[^/]+\" : segment.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\"),\n )\n .join(\"/\")}/?$`,\n ),\n params: (operation.path.match(/\\{/g) ?? []).length,\n }))\n .sort((a, b) => a.params - b.params)\n return (request: Request, path: string): string | undefined =>\n matchers.find((m) => m.method === request.method && m.pattern.test(path))?.operationId\n}\n\n/**\n * Wrap a service in the shared Mockingbird contract: an unauthenticated `/health`,\n * the `/__admin/*` control plane, per-request namespaces, a controllable clock,\n * fault injection, and request metrics.\n *\n * Namespaces isolate parallel workers inside one process: each gets its own\n * instance over the same SQLite database, so rows are partitioned by namespace\n * and a worker's reset or restore never touches another worker's data.\n */\nexport const createRuntime = <T extends ServiceInstance>(\n options: RuntimeOptions<T>,\n): ServiceRuntime<T> => {\n const sqlite = bootSqlite(options.sqlite)\n const clock = options.clock ?? createClock()\n const rng = createRng(options.seed ?? 0)\n const wallNow = options.io?.wallNow ?? Date.now\n const monotonicNow = options.io?.monotonicNow ?? (() => performance.now())\n const sleep =\n options.io?.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)))\n const faults = createFaultRegistry(createRng(options.seed ?? 0), sleep)\n const metrics = createMetrics()\n const journal = createJournal(options.journalSize ?? DEFAULT_JOURNAL_SIZE)\n const version = options.version ?? PACKAGE_VERSION\n const instances = new Map<string, T>()\n const publicNamespaces = new Set<string>()\n const branchRngs = new Map<string, Rng>()\n const timelines = new Map<string, Timeline<ServiceTimelineState>>()\n const branchStorage = new Map<string, string>()\n const captured = new Map<string, NamespaceSnapshot>()\n const credentials = createCredentialRegistry()\n const operationIdFor = options.document ? operationMatcher(options.document) : () => undefined\n\n const storageNamespace = (name: string) =>\n name === DEFAULT_NAMESPACE ? options.name : `${options.name}:${name}`\n\n const instanceFor = (key: string, publicNamespace = key, isolatedRng?: Rng): T => {\n const existing = instances.get(key)\n if (existing) return existing\n if (!NAMESPACE_PATTERN.test(key) || !NAMESPACE_PATTERN.test(publicNamespace)) {\n throw new RangeError(\n `namespace must match ${NAMESPACE_PATTERN}: ${JSON.stringify(publicNamespace)}`,\n )\n }\n const created = options.create({\n namespace: storageNamespace(key),\n publicNamespace,\n sqlite,\n clock,\n rng: isolatedRng ?? rng,\n })\n instances.set(key, created)\n publicNamespaces.add(publicNamespace)\n if (isolatedRng) branchRngs.set(key, isolatedRng)\n return created\n }\n\n const instance = (name: string = DEFAULT_NAMESPACE): T => instanceFor(name)\n\n const capture = (storage: string): ServiceTimelineState => {\n const fresh = snapshotNamespace(sqlite, storageNamespace(storage))\n const previous = captured.get(storage)\n const snapshot: NamespaceSnapshot = {\n namespace: fresh.namespace,\n records: reuseSorted(\n fresh.records,\n previous?.records,\n (left, right) =>\n left.collection < right.collection\n ? -1\n : left.collection > right.collection\n ? 1\n : left.seq - right.seq,\n (left, right) => left.id === right.id && left.value === right.value,\n ),\n sequences: reuseSorted(\n fresh.sequences,\n previous?.sequences,\n (left, right) =>\n left.name < right.name\n ? -1\n : left.name > right.name\n ? 1\n : left.kind < right.kind\n ? -1\n : left.kind > right.kind\n ? 1\n : 0,\n (left, right) => left.value === right.value,\n ),\n }\n Object.freeze(snapshot.records)\n Object.freeze(snapshot.sequences)\n Object.freeze(snapshot)\n captured.set(storage, snapshot)\n return Object.freeze({\n snapshot,\n clock: Object.freeze(clock.state()),\n rngState: (branchRngs.get(storage) ?? rng).state(),\n })\n }\n\n const timeline = (name: string = DEFAULT_NAMESPACE): Timeline<ServiceTimelineState> => {\n let found = timelines.get(name)\n if (found) return found\n instance(name)\n found = new Timeline<ServiceTimelineState>({\n now: clock.now,\n ...(options.maxCheckpoints !== undefined ? { maxCheckpoints: options.maxCheckpoints } : {}),\n })\n found.commit(capture(name))\n timelines.set(name, found)\n return found\n }\n\n const physicalBranch = (namespace: string, branch: string): string => {\n if (branch === \"main\") return namespace\n const mapKey = `${namespace}\\0${branch}`\n const existing = branchStorage.get(mapKey)\n if (existing) return existing\n // The hash keeps the internal instance key inside the 64-character namespace contract.\n const key = `branch_${seedFrom(`${options.name}\\0${namespace}\\0${branch}`).toString(36)}`\n branchStorage.set(mapKey, key)\n return key\n }\n\n const ensureBranch = (namespace: string, branch: string, at?: string): string => {\n if (!BRANCH_PATTERN.test(branch)) throw new RangeError(`branch must match ${BRANCH_PATTERN}`)\n const history = timeline(namespace)\n if (branch === \"main\") {\n if (at !== undefined) {\n const point = history.checkout(\"main\", at)\n restoreNamespace(sqlite, storageNamespace(namespace), point.value.snapshot)\n captured.set(namespace, point.value.snapshot)\n rng.setState(point.value.rngState)\n clock.set(point.value.clock.now)\n if (point.value.clock.frozen) clock.freeze()\n else clock.unfreeze()\n }\n return namespace\n }\n const storage = physicalBranch(namespace, branch)\n if (!history.hasBranch(branch)) {\n // Capture unobserved background work before branching from the current main head.\n if (at === undefined) history.commit(capture(namespace))\n const point = history.fork(branch, at === undefined ? {} : { from: at })\n const branchRng = createRng(options.seed ?? 0)\n if (point) branchRng.setState(point.value.rngState)\n instanceFor(storage, namespace, branchRng)\n if (point) restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot)\n if (point) captured.set(storage, point.value.snapshot)\n } else if (at !== undefined && history.head(branch)?.id !== at) {\n const point = history.checkout(branch, at)\n if (!instances.has(storage)) {\n const branchRng = createRng(options.seed ?? 0)\n branchRng.setState(point.value.rngState)\n instanceFor(storage, namespace, branchRng)\n }\n branchRngs.get(storage)?.setState(point.value.rngState)\n restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot)\n captured.set(storage, point.value.snapshot)\n } else {\n if (!instances.has(storage)) {\n const point = history.head(branch)\n const branchRng = createRng(options.seed ?? 0)\n if (point) branchRng.setState(point.value.rngState)\n instanceFor(storage, namespace, branchRng)\n }\n }\n return storage\n }\n\n const checkpoint = (namespace = DEFAULT_NAMESPACE, branch = \"main\"): ServiceCheckpoint => {\n const storage = ensureBranch(namespace, branch)\n return timeline(namespace).commit(capture(storage), { branch })\n }\n\n const branch = (\n name: string,\n branchOptions: { namespace?: string; at?: string } = {},\n ): ServiceCheckpoint => {\n const namespace = branchOptions.namespace ?? DEFAULT_NAMESPACE\n ensureBranch(namespace, name, branchOptions.at)\n const head = timeline(namespace).head(name)\n if (!head) throw new RangeError(`branch ${name} has no checkpoint`)\n return head\n }\n\n const checkout = (\n checkpointId: string,\n checkoutOptions: { namespace?: string; branch?: string } = {},\n ): void => {\n const namespace = checkoutOptions.namespace ?? DEFAULT_NAMESPACE\n const branchName = checkoutOptions.branch ?? \"main\"\n const history = timeline(namespace)\n const point = history.checkout(branchName, checkpointId)\n const storage = ensureBranch(namespace, branchName)\n restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot)\n captured.set(storage, point.value.snapshot)\n clock.set(point.value.clock.now)\n if (point.value.clock.frozen) clock.freeze()\n else clock.unfreeze()\n ;(branchRngs.get(storage) ?? rng).setState(point.value.rngState)\n }\n\n const reset = async (name: string = DEFAULT_NAMESPACE): Promise<void> => {\n if (name === \"*\") {\n options.webhooks?.clear()\n for (const each of instances.values()) await each.reset()\n timelines.clear()\n branchStorage.clear()\n branchRngs.clear()\n captured.clear()\n return\n }\n options.webhooks?.clear(name)\n const target = instances.get(name)\n if (target) await target.reset()\n else clearNamespace(sqlite, storageNamespace(name))\n for (const [mapping, storage] of branchStorage) {\n if (!mapping.startsWith(`${name}\\0`)) continue\n const branchInstance = instances.get(storage)\n if (branchInstance) await branchInstance.reset()\n else clearNamespace(sqlite, storageNamespace(storage))\n branchStorage.delete(mapping)\n branchRngs.delete(storage)\n captured.delete(storage)\n }\n timelines.delete(name)\n captured.delete(name)\n }\n\n const snapshot = (name: string = DEFAULT_NAMESPACE): NamespaceSnapshot => {\n return checkpoint(name, \"main\").value.snapshot\n }\n\n const restore = (from: NamespaceSnapshot, name: string = DEFAULT_NAMESPACE): void => {\n instance(name)\n restoreNamespace(sqlite, storageNamespace(name), from)\n captured.set(name, from)\n // Import legacy snapshots into the canonical history instead of creating a second rollback\n // mechanism. The compatibility method stays synchronous and keeps its original return type.\n const history = timelines.get(name)\n if (history) history.commit(capture(name), { branch: \"main\" })\n else timeline(name)\n }\n\n const runtime: ServiceRuntime<T> = {\n name: options.name,\n sqlite,\n clock,\n faults,\n metrics,\n journal,\n rng,\n credentials,\n webhooks: options.webhooks,\n applyPreset: (name, namespace = DEFAULT_NAMESPACE, overrides = {}) => {\n const preset = options.presets?.[name]\n if (!preset) throw new RangeError(`no fault preset ${JSON.stringify(name)}`)\n const added = (preset.rules ?? []).map((rule, index) =>\n faults.add({\n namespace,\n ...rule,\n ...overrides,\n preset: name,\n id: `${overrides.id ?? name}${(preset.rules ?? []).length > 1 ? `_${index + 1}` : \"\"}`,\n } as FaultRule),\n )\n if (preset.webhook && options.webhooks) {\n options.webhooks.fault(namespace, {\n ...preset.webhook,\n ...(overrides.count !== undefined ? { count: overrides.count } : {}),\n })\n }\n return added\n },\n instance,\n namespaces: () => [...publicNamespaces].sort(),\n reset,\n snapshot,\n restore,\n checkpoint,\n branch,\n checkout,\n timeline,\n fetch: async (incoming) => {\n let request = incoming\n // `/ns/<name>/\u2026` selects a namespace (and is stripped) for SDKs that cannot add headers.\n const prefixed = PATH_PREFIX.exec(new URL(request.url).pathname)\n if (prefixed) {\n const url = new URL(request.url)\n url.pathname = prefixed[2] ?? \"/\"\n const headers = new Headers(request.headers)\n if (!headers.has(NAMESPACE_HEADER)) {\n headers.set(NAMESPACE_HEADER, decodeURIComponent(prefixed[1] as string))\n }\n const hasBody = request.method !== \"GET\" && request.method !== \"HEAD\"\n request = new Request(url, {\n method: request.method,\n headers,\n ...(hasBody ? { body: await request.arrayBuffer() } : {}),\n signal: request.signal,\n })\n }\n let namespace = control.namespaceOf(request)\n if (!request.headers.has(NAMESPACE_HEADER) && options.credential) {\n const credential = options.credential(request)\n const mapped = credential !== undefined ? credentials.get(credential) : undefined\n if (mapped !== undefined) namespace = mapped\n }\n const selectedBranch = request.headers.get(BRANCH_HEADER) ?? \"main\"\n const at = request.headers.get(AT_HEADER) ?? undefined\n const stamp = (response: Response): Response => {\n // An invalid namespace is not echoed back.\n const value = NAMESPACE_PATTERN.test(namespace)\n ? `${options.name}@${version}; ns=${namespace}`\n : `${options.name}@${version}`\n try {\n response.headers.set(MOCKINGBIRD_HEADER, value)\n return response\n } catch {\n // Immutable headers (a response passed through from `fetch`): copy it.\n const copy = new Response(response.body, response)\n copy.headers.set(MOCKINGBIRD_HEADER, value)\n return copy\n }\n }\n const handled = await control.handle(request)\n if (handled) return stamp(handled)\n const started = monotonicNow()\n const url = new URL(request.url)\n const operationId = operationIdFor(request, url.pathname)\n const log = (status: number, faultId?: string, response?: Response) => {\n const noted = response ? responseNotes(response) : undefined\n const entry: RequestLog = {\n service: options.name,\n namespace,\n operationId,\n method: request.method,\n path: url.pathname,\n status,\n durationMs: Math.round((monotonicNow() - started) * 100) / 100,\n unmatched: options.document !== undefined && operationId === undefined,\n ...(faultId !== undefined ? { faultId } : {}),\n ...(noted?.ids && Object.keys(noted.ids).length > 0 ? { ids: noted.ids } : {}),\n ...(noted?.adopted ? { adopted: true } : {}),\n }\n metrics.record(entry)\n journal.record({ ...entry, at: new Date(clock.now()).toISOString() })\n options.onLog?.(entry)\n }\n if (!NAMESPACE_PATTERN.test(namespace)) {\n log(400)\n return stamp(\n new Response(\n JSON.stringify({\n error: {\n type: \"mockingbird_admin\",\n message: `${NAMESPACE_HEADER} must match ${NAMESPACE_PATTERN}`,\n },\n }),\n { status: 400, headers: { \"content-type\": \"application/json\" } },\n ),\n )\n }\n if (!BRANCH_PATTERN.test(selectedBranch)) {\n log(400)\n return stamp(adminFail(400, `${BRANCH_HEADER} must match ${BRANCH_PATTERN}`))\n }\n let storage: string\n try {\n if (\n at !== undefined &&\n selectedBranch === \"main\" &&\n !MUTATING_METHODS.has(request.method)\n ) {\n const point = timeline(namespace).get(at)\n storage = physicalBranch(namespace, `at_${at}`)\n let viewRng = branchRngs.get(storage)\n if (!viewRng) {\n viewRng = createRng(options.seed ?? 0)\n instanceFor(storage, namespace, viewRng)\n }\n viewRng.setState(point.value.rngState)\n restoreNamespace(sqlite, storageNamespace(storage), point.value.snapshot)\n captured.set(storage, point.value.snapshot)\n } else {\n storage = ensureBranch(namespace, selectedBranch, at)\n }\n } catch (error) {\n log(409)\n return stamp(adminFail(409, error instanceof Error ? error.message : String(error)))\n }\n const hits = await faults.take({\n operationId,\n method: request.method,\n path: url.pathname,\n namespace,\n })\n const final = hits.find((hit) => hit.drop || hit.response)\n if (final?.drop) {\n log(0, final.id)\n throw new DroppedConnectionError()\n }\n if (final?.response) {\n log(final.response.status, final.id)\n return stamp(final.response)\n }\n const fired = hits.filter((hit) => hit.effect !== undefined)\n if (fired.length > 0)\n effects.set(\n request,\n fired.map((hit) => hit.effect),\n )\n let response = await instanceFor(storage, namespace).fetch(request)\n if (MUTATING_METHODS.has(request.method) && response.status >= 200 && response.status < 400) {\n const point = timeline(namespace).commit(capture(storage), { branch: selectedBranch })\n response = mutableResponse(response)\n response.headers.set(CHECKPOINT_HEADER, point.id)\n }\n if (selectedBranch !== \"main\") {\n response = mutableResponse(response)\n response.headers.set(BRANCH_HEADER, selectedBranch)\n }\n if (at !== undefined) {\n response = mutableResponse(response)\n response.headers.set(AT_HEADER, at)\n }\n log(response.status, fired[0]?.id, response)\n return stamp(response)\n },\n }\n\n const control = createControlPlane({\n name: options.name,\n startedAt: wallNow(),\n wallNow,\n clock,\n faults,\n metrics,\n journal,\n defaultNamespace: DEFAULT_NAMESPACE,\n namespaces: runtime.namespaces,\n reset,\n timeTravel: {\n checkpoint: (name, branchName) => {\n const point = checkpoint(name, branchName)\n return {\n id: point.id,\n branch: point.branch,\n parent: point.parent,\n at: point.at,\n records: point.value.snapshot.records.length,\n }\n },\n branch: (branchName, branchOptions) => {\n const point = branch(branchName, branchOptions)\n return { id: point.id, branch: point.branch, parent: point.parent, at: point.at }\n },\n checkout: (checkpointId, checkoutOptions) => checkout(checkpointId, checkoutOptions),\n retain: (name, checkpointId) => {\n timeline(name).retain(checkpointId)\n },\n release: (name, checkpointId) => timeline(name).release(checkpointId),\n inspect: (name) => {\n const history = timeline(name)\n return {\n branches: history.branches(),\n checkpoints: history.checkpoints().map(({ id, branch: branchName, parent, at }) => ({\n id,\n branch: branchName,\n parent,\n at,\n })),\n }\n },\n },\n describe: options.describe ?? (() => ({})),\n ...(options.presets\n ? {\n applyPreset: (name: string, namespace: string, overrides: Partial<FaultRule>) =>\n runtime.applyPreset(name, namespace, overrides),\n }\n : {}),\n routes: {\n ...credentialRoutes(credentials),\n ...(options.presets ? presetRoutes(options.presets, runtime) : {}),\n ...(options.webhooks ? webhookAdminRoutes(options.webhooks) : {}),\n ...(options.admin?.(runtime) ?? {}),\n },\n adminKey: options.adminKey,\n })\n\n return runtime\n}\n\nconst mutableResponse = (response: Response): Response => {\n try {\n response.headers.set(\"x-mockingbird-mutable-probe\", \"1\")\n response.headers.delete(\"x-mockingbird-mutable-probe\")\n return response\n } catch {\n return new Response(response.body, response)\n }\n}\n\nconst adminJson = (status: number, body: unknown): Response =>\n new Response(JSON.stringify(body), { status, headers: { \"content-type\": \"application/json\" } })\n\nconst adminFail = (status: number, message: string): Response =>\n adminJson(status, { error: { type: \"mockingbird_admin\", message } })\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\n/**\n * `PUT /__admin/credentials` accepts `{ credentials: { \"<credential>\": \"<namespace>\" } }`,\n * `[{ credential, namespace }]`, or `{ credentials: [\"<credential>\"] }` with `?namespace=`\n * (maps each to the calling namespace). `GET` lists them masked; `DELETE` removes one\n * (`?credential=`) or all.\n */\nconst credentialRoutes = (registry: CredentialRegistry): AdminRoutes => ({\n \"GET /credentials\": () =>\n adminJson(200, {\n credentials: registry.entries().map(({ credential, namespace }) => ({\n credential: maskCredential(credential),\n namespace,\n })),\n }),\n \"PUT /credentials\": ({ body, namespace }) => {\n const pairs: [string, string][] = []\n const list = Array.isArray(body) ? body : isObject(body) ? body.credentials : undefined\n if (Array.isArray(list)) {\n for (const each of list) {\n if (typeof each === \"string\") pairs.push([each, namespace])\n else if (isObject(each) && typeof each.credential === \"string\") {\n pairs.push([\n each.credential,\n typeof each.namespace === \"string\" ? each.namespace : namespace,\n ])\n } else return adminFail(400, \"each entry is a credential string or {credential, namespace}\")\n }\n } else if (isObject(list)) {\n for (const [credential, target] of Object.entries(list)) {\n if (typeof target !== \"string\")\n return adminFail(400, `namespace for ${credential} must be a string`)\n pairs.push([credential, target])\n }\n } else if (isObject(body) && typeof body.credential === \"string\") {\n pairs.push([body.credential, typeof body.namespace === \"string\" ? body.namespace : namespace])\n } else {\n return adminFail(400, 'expected {\"credentials\": {\"<credential>\": \"<namespace>\"}}')\n }\n for (const [credential, target] of pairs) {\n if (!NAMESPACE_PATTERN.test(target))\n return adminFail(400, `bad namespace ${JSON.stringify(target)}`)\n registry.set(credential, target)\n }\n return adminJson(200, { mapped: pairs.length })\n },\n \"DELETE /credentials\": ({ url }) => {\n const credential = url.searchParams.get(\"credential\")\n if (credential === null) registry.clear()\n else registry.remove(credential)\n return adminJson(200, { status: \"ok\" })\n },\n})\n\nconst presetRoutes = <T extends ServiceInstance>(\n presets: Record<string, FaultPreset>,\n runtime: ServiceRuntime<T>,\n): AdminRoutes => ({\n \"GET /faults/presets\": () =>\n adminJson(200, {\n presets: Object.entries(presets).map(([name, preset]) => ({ name, ...preset })),\n }),\n \"POST /faults/presets/:name\": ({ params, body, namespace }) => {\n const name = params.name as string\n if (!presets[name])\n return adminFail(404, `no fault preset ${name}; GET /__admin/faults/presets`)\n const overrides = isObject(body) ? (body as Partial<FaultRule>) : {}\n return adminJson(201, { preset: name, rules: runtime.applyPreset(name, namespace, overrides) })\n },\n})\n", "import {\n deref,\n resolveSchema,\n type SchemaObject,\n validateValue,\n} from \"@crvouga/mockingbird-openapi\"\nimport type { OperationContext } from \"./service.js\"\n\n/** One problem with a request body, at a dotted path (`patient.address.city`, `items.0.sku`). */\nexport type BodyIssue = { path: string; message: string }\n\n/**\n * Validate the decoded JSON body against the operation's `requestBody` schema in the vendor\n * contract. Returns `[]` when valid, or when the operation declares no JSON body. Services\n * turn the issues into the vendor's own validation error shape.\n */\nexport const bodyIssues = (\n context: OperationContext,\n contentType = \"application/json\",\n): BodyIssue[] => {\n const requestBody = context.operation.operation.requestBody\n if (!requestBody) return []\n const resolved = deref(context.document, requestBody) as {\n required?: boolean\n content?: Record<string, { schema?: SchemaObject }>\n }\n const schema = resolved.content?.[contentType]?.schema\n if (!schema) return []\n const value =\n context.body.kind === \"json\" || context.body.kind === \"form\" ? context.body.value : undefined\n if (context.body.kind === \"invalid\") {\n return [{ path: \"\", message: `request body is not valid ${context.body.mediaType}` }]\n }\n if (value === undefined) {\n return resolved.required ? [{ path: \"\", message: \"request body is required\" }] : []\n }\n return validateValue(context.document, resolveSchema(context.document, schema), value).map(\n (issue) => ({ path: issue.path.join(\".\"), message: issue.message }),\n )\n}\n\n/** Issues grouped Laravel-style: `{ \"patient.email\": [\"\u2026\"] }`. */\nexport const issuesByField = (issues: BodyIssue[]): Record<string, string[]> => {\n const out: Record<string, string[]> = {}\n for (const issue of issues) {\n const missing = /^missing required property (.+)$/.exec(issue.message)\n const field = missing\n ? [issue.path, missing[1]].filter(Boolean).join(\".\")\n : issue.path || \"body\"\n const message = missing\n ? `The ${field} field is required.`\n : `The ${field} field ${issue.message}.`\n out[field] = [...(out[field] ?? []), message]\n }\n return out\n}\n", "// Generated by @crvouga/mockingbird-openapi-codegen from openapi.yaml. Do not edit.\n\nimport type { OpenAPIDocument } from \"@crvouga/mockingbird-openapi\"\n\nexport const document: OpenAPIDocument = JSON.parse(`{\"openapi\":\"3.1.0\",\"info\":{\"title\":\"Intercom REST API 2.11 (Mockingbird subset)\",\"description\":\"Stateful mock subset of the Intercom REST API (version 2.11): contacts (search, create,\\\\nupdate, get), conversations (create, update, reply as user or admin with attachments,\\\\nclose/open/snooze/assign, get, search) and the admin identity endpoints. Covers the backend's\\\\nmember messaging adapter and the Intercom sync adapter.\\\\n\",\"version\":\"2.11\",\"x-mockingbird-upstream\":{\"note\":\"Trimmed from Intercom's published 2.11 API reference to the operations and fields our consumers use (intercom-messaging.adapter.ts, intercom-api.adapter.ts) and the webhook receivers (messaging.controller.ts, the EMR IntercomWebhookService).\"}},\"servers\":[{\"url\":\"https://api.intercom.io\"}],\"security\":[{\"bearerAuth\":[]}],\"paths\":{\"/contacts/search\":{\"post\":{\"operationId\":\"SearchContacts\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"type\":\"object\",\"required\":[\"query\"],\"properties\":{\"query\":{\"$ref\":\"#/components/schemas/ContactQuery\"},\"pagination\":{\"$ref\":\"#/components/schemas/Pagination\"}}}}}},\"responses\":{\"200\":{\"description\":\"Matching contacts\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ContactList\"}}}},\"400\":{\"$ref\":\"#/components/responses/BadRequest\"},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"}}}},\"/contacts\":{\"post\":{\"operationId\":\"CreateContact\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":false}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ContactCreate\"}}}},\"responses\":{\"200\":{\"description\":\"The created contact\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/Contact\"}}}},\"400\":{\"$ref\":\"#/components/responses/BadRequest\"},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"},\"409\":{\"$ref\":\"#/components/responses/Conflict\"}}}},\"/contacts/{contact_id}\":{\"parameters\":[{\"name\":\"contact_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"x-mockingbird-resource-ref\":{\"type\":\"contact\",\"missing\":0}}}],\"get\":{\"operationId\":\"GetContact\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"responses\":{\"200\":{\"description\":\"The contact\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/Contact\"}}}},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"},\"404\":{\"$ref\":\"#/components/responses/NotFound\"}}},\"put\":{\"operationId\":\"UpdateContact\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":false}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ContactUpdate\"}}}},\"responses\":{\"200\":{\"description\":\"The updated contact\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/Contact\"}}}},\"400\":{\"$ref\":\"#/components/responses/BadRequest\"},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"},\"404\":{\"$ref\":\"#/components/responses/NotFound\"},\"409\":{\"$ref\":\"#/components/responses/Conflict\"}}}},\"/conversations\":{\"post\":{\"operationId\":\"CreateConversation\",\"description\":\"A contact-initiated conversation. An optional \\`Idempotency-Key\\` header replays.\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":false}},\"parameters\":[{\"name\":\"Idempotency-Key\",\"in\":\"header\",\"schema\":{\"type\":\"string\",\"pattern\":\"^[A-Za-z0-9_-]{1,40}$\"}}],\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"type\":\"object\",\"required\":[\"from\",\"body\"],\"properties\":{\"from\":{\"type\":\"object\",\"required\":[\"type\",\"id\"],\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"user\",\"lead\",\"contact\"]},\"id\":{\"type\":\"string\",\"x-mockingbird-resource-ref\":{\"type\":\"contact\",\"missing\":0}}}},\"body\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":400},\"created_at\":{\"type\":\"integer\",\"minimum\":1600000000,\"maximum\":1900000000}}}}}},\"responses\":{\"200\":{\"description\":\"The first message of the new conversation\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/Message\"}}}},\"400\":{\"$ref\":\"#/components/responses/BadRequest\"},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"},\"404\":{\"$ref\":\"#/components/responses/NotFound\"},\"409\":{\"$ref\":\"#/components/responses/Conflict\"}}}},\"/conversations/search\":{\"post\":{\"operationId\":\"SearchConversations\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"parameters\":[{\"$ref\":\"#/components/parameters/DisplayAs\"}],\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"type\":\"object\",\"required\":[\"query\"],\"properties\":{\"query\":{\"$ref\":\"#/components/schemas/ConversationQuery\"},\"pagination\":{\"$ref\":\"#/components/schemas/Pagination\"},\"sort_field\":{\"type\":\"string\",\"enum\":[\"updated_at\",\"created_at\",\"id\",\"waiting_since\"]},\"sort_order\":{\"type\":\"string\",\"enum\":[\"ascending\",\"descending\"]}}}}}},\"responses\":{\"200\":{\"description\":\"A page of matching conversations (without conversation parts)\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ConversationList\"}}}},\"400\":{\"$ref\":\"#/components/responses/BadRequest\"},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"}}}},\"/conversations/{conversation_id}\":{\"parameters\":[{\"$ref\":\"#/components/parameters/ConversationId\"}],\"get\":{\"operationId\":\"GetConversation\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"parameters\":[{\"$ref\":\"#/components/parameters/DisplayAs\"}],\"responses\":{\"200\":{\"description\":\"The conversation with its parts\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/Conversation\"}}}},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"},\"404\":{\"$ref\":\"#/components/responses/NotFound\"}}},\"put\":{\"operationId\":\"UpdateConversation\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":false}},\"parameters\":[{\"$ref\":\"#/components/parameters/DisplayAs\"}],\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"type\":\"object\",\"properties\":{\"read\":{\"type\":\"boolean\"},\"title\":{\"type\":\"string\",\"maxLength\":120},\"custom_attributes\":{\"type\":\"object\",\"maxProperties\":4,\"additionalProperties\":{\"type\":[\"string\",\"number\",\"boolean\",\"null\"]}}}}}}},\"responses\":{\"200\":{\"description\":\"The updated conversation\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/Conversation\"}}}},\"400\":{\"$ref\":\"#/components/responses/BadRequest\"},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"},\"404\":{\"$ref\":\"#/components/responses/NotFound\"}}}},\"/conversations/{conversation_id}/reply\":{\"parameters\":[{\"$ref\":\"#/components/parameters/ConversationId\"}],\"post\":{\"operationId\":\"ReplyConversation\",\"description\":\"Reply as the contact (\\`type: user\\` + \\`intercom_user_id\\`) or as an admin (\\`type: admin\\` + \\`admin_id\\`), as JSON (attachments as base64 \\`attachment_files\\`) or multipart (\\`attachment_files[]\\` file parts). Admin comments fire \\`conversation.admin.replied\\`.\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":false}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ReplyBody\"}},\"multipart/form-data\":{\"schema\":{\"type\":\"object\",\"required\":[\"message_type\",\"type\"],\"properties\":{\"message_type\":{\"type\":\"string\"},\"type\":{\"type\":\"string\"},\"intercom_user_id\":{\"type\":\"string\"},\"admin_id\":{\"type\":\"string\"},\"body\":{\"type\":\"string\"},\"attachment_files[]\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"format\":\"binary\"}}}}}}},\"responses\":{\"200\":{\"description\":\"The conversation, with the new part\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/Conversation\"}}}},\"400\":{\"$ref\":\"#/components/responses/BadRequest\"},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"},\"404\":{\"$ref\":\"#/components/responses/NotFound\"}}}},\"/conversations/{conversation_id}/parts\":{\"parameters\":[{\"$ref\":\"#/components/parameters/ConversationId\"}],\"post\":{\"operationId\":\"ManageConversation\",\"description\":\"Close, open, snooze or assign; close and open fire \\`conversation.admin.closed\\` / \\`opened\\`.\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":false}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"type\":\"object\",\"required\":[\"message_type\",\"type\",\"admin_id\"],\"properties\":{\"message_type\":{\"type\":\"string\",\"enum\":[\"close\",\"open\",\"snoozed\",\"assignment\"]},\"type\":{\"type\":\"string\",\"enum\":[\"admin\"]},\"admin_id\":{\"type\":\"string\",\"x-mockingbird-resource-ref\":{\"type\":\"admin\",\"missing\":\"9999999\"}},\"body\":{\"type\":\"string\",\"maxLength\":400},\"snoozed_until\":{\"type\":\"integer\",\"minimum\":1600000000,\"maximum\":1900000000},\"assignee_id\":{\"type\":\"string\",\"x-mockingbird-resource-ref\":{\"type\":\"admin\",\"missing\":\"9999999\"}}}}}}},\"responses\":{\"200\":{\"description\":\"The conversation, with the new part\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/Conversation\"}}}},\"400\":{\"$ref\":\"#/components/responses/BadRequest\"},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"},\"404\":{\"$ref\":\"#/components/responses/NotFound\"}}}},\"/admins\":{\"get\":{\"operationId\":\"ListAdmins\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"responses\":{\"200\":{\"description\":\"The workspace's admins\",\"content\":{\"application/json\":{\"schema\":{\"type\":\"object\",\"required\":[\"type\",\"admins\"],\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"admin.list\"]},\"admins\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/Admin\"}}}}}}},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"}}}},\"/me\":{\"get\":{\"operationId\":\"GetMe\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"responses\":{\"200\":{\"description\":\"The admin that owns the access token\",\"content\":{\"application/json\":{\"schema\":{\"type\":\"object\",\"required\":[\"type\",\"id\",\"email\",\"app\"],\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"admin\"]},\"id\":{\"type\":\"string\"},\"name\":{\"type\":\"string\"},\"email\":{\"type\":\"string\"},\"email_verified\":{\"type\":\"boolean\"},\"has_inbox_seat\":{\"type\":\"boolean\"},\"avatar\":{\"type\":\"object\"},\"app\":{\"type\":\"object\",\"required\":[\"type\",\"id_code\"],\"properties\":{\"type\":{\"type\":\"string\"},\"id_code\":{\"type\":\"string\"},\"name\":{\"type\":\"string\"},\"created_at\":{\"type\":\"integer\"},\"secure\":{\"type\":\"boolean\"},\"identity_verification\":{\"type\":\"boolean\"},\"timezone\":{\"type\":\"string\"},\"region\":{\"type\":\"string\"}}}}}}}},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"}}}}},\"components\":{\"securitySchemes\":{\"bearerAuth\":{\"type\":\"http\",\"scheme\":\"bearer\"}},\"parameters\":{\"ConversationId\":{\"name\":\"conversation_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"x-mockingbird-resource-ref\":{\"type\":\"conversation\",\"missing\":\"999999999999999\"}}},\"DisplayAs\":{\"name\":\"display_as\",\"in\":\"query\",\"schema\":{\"type\":\"string\",\"enum\":[\"plaintext\"]}}},\"responses\":{\"BadRequest\":{\"description\":\"Invalid parameters\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ErrorList\"}}}},\"Unauthorized\":{\"description\":\"Missing or invalid access token\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ErrorList\"}}}},\"NotFound\":{\"description\":\"Unknown resource\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ErrorList\"}}}},\"Conflict\":{\"description\":\"A contact with that external_id or email already exists (or an idempotency conflict)\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ErrorList\"}}}}},\"schemas\":{\"ErrorList\":{\"type\":\"object\",\"required\":[\"type\",\"errors\"],\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"error.list\"]},\"request_id\":{\"type\":\"string\",\"x-mockingbird-volatile\":{\"kind\":\"token\"}},\"errors\":{\"type\":\"array\",\"minItems\":1,\"items\":{\"type\":\"object\",\"required\":[\"code\",\"message\"],\"properties\":{\"code\":{\"type\":\"string\"},\"message\":{\"type\":\"string\"}}}}}},\"Pagination\":{\"type\":\"object\",\"properties\":{\"per_page\":{\"type\":\"integer\",\"minimum\":1,\"maximum\":150},\"starting_after\":{\"type\":\"string\",\"maxLength\":80}}},\"ContactFilter\":{\"type\":\"object\",\"required\":[\"field\",\"operator\",\"value\"],\"properties\":{\"field\":{\"type\":\"string\",\"enum\":[\"external_id\",\"email\",\"id\",\"name\",\"role\",\"phone\"]},\"operator\":{\"type\":\"string\",\"enum\":[\"=\",\"!=\",\"~\",\"!~\",\"^\",\"$\",\"IN\",\"NIN\"]},\"value\":{\"oneOf\":[{\"type\":\"string\",\"maxLength\":80},{\"type\":\"array\",\"maxItems\":3,\"items\":{\"type\":\"string\",\"maxLength\":80}}]}}},\"ContactQuery\":{\"oneOf\":[{\"$ref\":\"#/components/schemas/ContactFilter\"},{\"type\":\"object\",\"required\":[\"operator\",\"value\"],\"properties\":{\"operator\":{\"type\":\"string\",\"enum\":[\"AND\",\"OR\"]},\"value\":{\"type\":\"array\",\"minItems\":1,\"maxItems\":3,\"items\":{\"$ref\":\"#/components/schemas/ContactFilter\"}}}}]},\"ConversationFilter\":{\"type\":\"object\",\"required\":[\"field\",\"operator\",\"value\"],\"properties\":{\"field\":{\"type\":\"string\",\"enum\":[\"id\",\"contact_ids\",\"admin_assignee_id\",\"team_assignee_id\",\"state\",\"open\",\"read\",\"created_at\",\"updated_at\",\"source.author.email\",\"source.delivered_as\"]},\"operator\":{\"type\":\"string\",\"enum\":[\"=\",\"!=\",\"<\",\">\",\"~\",\"IN\",\"NIN\"]},\"value\":{\"oneOf\":[{\"type\":\"string\",\"maxLength\":80},{\"type\":\"integer\"},{\"type\":\"boolean\"},{\"type\":\"array\",\"maxItems\":3,\"items\":{\"type\":\"string\",\"maxLength\":80}}]}}},\"ConversationQuery\":{\"oneOf\":[{\"$ref\":\"#/components/schemas/ConversationFilter\"},{\"type\":\"object\",\"required\":[\"operator\",\"value\"],\"properties\":{\"operator\":{\"type\":\"string\",\"enum\":[\"AND\",\"OR\"]},\"value\":{\"type\":\"array\",\"minItems\":1,\"maxItems\":3,\"items\":{\"$ref\":\"#/components/schemas/ConversationFilter\"}}}}]},\"CustomAttributes\":{\"type\":\"object\",\"maxProperties\":30,\"additionalProperties\":{\"type\":[\"string\",\"number\",\"boolean\",\"null\"]}},\"ContactCreate\":{\"type\":\"object\",\"properties\":{\"role\":{\"type\":\"string\",\"enum\":[\"user\",\"lead\"]},\"external_id\":{\"description\":\"Any string. The first branch steers the walk generator toward a few values, so random walks reach the duplicate (409) path.\",\"anyOf\":[{\"type\":\"string\",\"pattern\":\"^[1-4]$\"},{\"type\":\"string\",\"minLength\":1,\"maxLength\":64}]},\"email\":{\"type\":\"string\",\"format\":\"email\",\"maxLength\":120},\"name\":{\"type\":[\"string\",\"null\"],\"maxLength\":80},\"phone\":{\"type\":[\"string\",\"null\"],\"maxLength\":40},\"signed_up_at\":{\"type\":[\"integer\",\"null\"],\"minimum\":1000000000,\"maximum\":1900000000},\"last_seen_at\":{\"type\":[\"integer\",\"null\"],\"minimum\":1000000000,\"maximum\":1900000000},\"custom_attributes\":{\"$ref\":\"#/components/schemas/CustomAttributes\"}}},\"ContactUpdate\":{\"allOf\":[{\"$ref\":\"#/components/schemas/ContactCreate\"}]},\"ReplyBody\":{\"type\":\"object\",\"required\":[\"message_type\",\"type\"],\"properties\":{\"message_type\":{\"type\":\"string\",\"enum\":[\"comment\",\"note\",\"quick_reply\"]},\"type\":{\"type\":\"string\",\"enum\":[\"user\",\"admin\"]},\"body\":{\"type\":\"string\",\"maxLength\":400},\"intercom_user_id\":{\"type\":\"string\",\"x-mockingbird-resource-ref\":{\"type\":\"contact\",\"missing\":0}},\"user_id\":{\"type\":\"string\",\"maxLength\":64},\"email\":{\"type\":\"string\",\"maxLength\":120},\"admin_id\":{\"type\":\"string\",\"x-mockingbird-resource-ref\":{\"type\":\"admin\",\"missing\":\"9999999\"}},\"created_at\":{\"type\":\"integer\",\"minimum\":1600000000,\"maximum\":1900000000},\"attachment_urls\":{\"type\":\"array\",\"maxItems\":3,\"items\":{\"type\":\"string\",\"maxLength\":200}},\"attachment_files\":{\"type\":\"array\",\"maxItems\":3,\"items\":{\"type\":\"object\",\"required\":[\"content_type\",\"data\",\"name\"],\"properties\":{\"content_type\":{\"type\":\"string\",\"maxLength\":80},\"data\":{\"type\":\"string\",\"maxLength\":400},\"name\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":80}}}}}},\"Contact\":{\"type\":\"object\",\"required\":[\"type\",\"id\",\"role\",\"created_at\",\"updated_at\",\"custom_attributes\"],\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"contact\"]},\"id\":{\"type\":\"string\",\"x-mockingbird-resource\":{\"type\":\"contact\",\"identity\":true}},\"workspace_id\":{\"type\":\"string\"},\"external_id\":{\"type\":[\"string\",\"null\"]},\"role\":{\"type\":\"string\"},\"email\":{\"type\":[\"string\",\"null\"]},\"phone\":{\"type\":[\"string\",\"null\"]},\"name\":{\"type\":[\"string\",\"null\"]},\"avatar\":{\"type\":[\"string\",\"null\"]},\"owner_id\":{\"type\":[\"integer\",\"null\"]},\"has_hard_bounced\":{\"type\":\"boolean\"},\"marked_email_as_spam\":{\"type\":\"boolean\"},\"unsubscribed_from_emails\":{\"type\":\"boolean\"},\"created_at\":{\"type\":\"integer\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"updated_at\":{\"type\":\"integer\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"signed_up_at\":{\"type\":[\"integer\",\"null\"]},\"last_seen_at\":{\"type\":[\"integer\",\"null\"]},\"custom_attributes\":{\"type\":\"object\"},\"tags\":{\"type\":\"object\"},\"notes\":{\"type\":\"object\"},\"companies\":{\"type\":\"object\"},\"location\":{\"type\":\"object\"},\"social_profiles\":{\"type\":\"object\"}}},\"Pages\":{\"type\":\"object\",\"required\":[\"type\",\"page\",\"per_page\",\"total_pages\"],\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"pages\"]},\"page\":{\"type\":\"integer\"},\"per_page\":{\"type\":\"integer\"},\"total_pages\":{\"type\":\"integer\"},\"next\":{\"type\":\"object\",\"required\":[\"page\",\"starting_after\"],\"properties\":{\"page\":{\"type\":\"integer\"},\"starting_after\":{\"type\":\"string\"}}}}},\"ContactList\":{\"type\":\"object\",\"required\":[\"type\",\"data\",\"total_count\",\"pages\"],\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"list\"]},\"data\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/Contact\"}},\"total_count\":{\"type\":\"integer\"},\"pages\":{\"$ref\":\"#/components/schemas/Pages\"}}},\"Author\":{\"type\":\"object\",\"required\":[\"type\",\"id\"],\"properties\":{\"type\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"name\":{\"type\":[\"string\",\"null\"]},\"email\":{\"type\":[\"string\",\"null\"]}}},\"Attachment\":{\"type\":\"object\",\"required\":[\"type\",\"name\",\"url\",\"content_type\"],\"properties\":{\"type\":{\"type\":\"string\"},\"name\":{\"type\":\"string\"},\"url\":{\"type\":\"string\"},\"content_type\":{\"type\":\"string\"},\"filesize\":{\"type\":\"integer\"},\"width\":{\"type\":[\"integer\",\"null\"]},\"height\":{\"type\":[\"integer\",\"null\"]}}},\"ConversationPart\":{\"type\":\"object\",\"required\":[\"type\",\"id\",\"part_type\",\"created_at\",\"author\"],\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"conversation_part\"]},\"id\":{\"type\":\"string\"},\"part_type\":{\"type\":\"string\"},\"body\":{\"type\":[\"string\",\"null\"]},\"created_at\":{\"type\":\"integer\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"updated_at\":{\"type\":\"integer\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"notified_at\":{\"type\":\"integer\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"assigned_to\":{\"type\":[\"object\",\"null\"]},\"author\":{\"$ref\":\"#/components/schemas/Author\"},\"attachments\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/Attachment\"}},\"external_id\":{\"type\":[\"string\",\"null\"]},\"redacted\":{\"type\":\"boolean\"}}},\"Conversation\":{\"type\":\"object\",\"required\":[\"type\",\"id\",\"created_at\",\"updated_at\",\"open\",\"state\",\"read\",\"source\",\"contacts\"],\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"conversation\"]},\"id\":{\"type\":\"string\",\"x-mockingbird-resource\":{\"type\":\"conversation\",\"identity\":true}},\"title\":{\"type\":[\"string\",\"null\"]},\"created_at\":{\"type\":\"integer\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"updated_at\":{\"type\":\"integer\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"waiting_since\":{\"type\":[\"integer\",\"null\"],\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"snoozed_until\":{\"type\":[\"integer\",\"null\"]},\"open\":{\"type\":\"boolean\"},\"state\":{\"type\":\"string\",\"enum\":[\"open\",\"closed\",\"snoozed\"]},\"read\":{\"type\":\"boolean\"},\"priority\":{\"type\":\"string\"},\"admin_assignee_id\":{\"type\":[\"integer\",\"null\"]},\"team_assignee_id\":{\"type\":[\"string\",\"null\"]},\"tags\":{\"type\":\"object\"},\"conversation_rating\":{\"type\":[\"object\",\"null\"]},\"source\":{\"type\":\"object\",\"required\":[\"type\",\"id\",\"delivered_as\",\"body\",\"author\"],\"properties\":{\"type\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"delivered_as\":{\"type\":\"string\"},\"subject\":{\"type\":\"string\"},\"body\":{\"type\":[\"string\",\"null\"]},\"author\":{\"$ref\":\"#/components/schemas/Author\"},\"attachments\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/Attachment\"}},\"url\":{\"type\":[\"string\",\"null\"]},\"redacted\":{\"type\":\"boolean\"}}},\"contacts\":{\"type\":\"object\",\"required\":[\"type\",\"contacts\"],\"properties\":{\"type\":{\"type\":\"string\"},\"contacts\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"required\":[\"type\",\"id\"],\"properties\":{\"type\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"external_id\":{\"type\":[\"string\",\"null\"]}}}}}},\"teammates\":{\"type\":\"object\"},\"custom_attributes\":{\"type\":\"object\"},\"first_contact_reply\":{\"type\":[\"object\",\"null\"]},\"sla_applied\":{\"type\":[\"object\",\"null\"]},\"statistics\":{\"type\":[\"object\",\"null\"]},\"ai_agent_participated\":{\"type\":\"boolean\"},\"conversation_parts\":{\"type\":\"object\",\"required\":[\"type\",\"conversation_parts\",\"total_count\"],\"properties\":{\"type\":{\"type\":\"string\"},\"conversation_parts\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ConversationPart\"}},\"total_count\":{\"type\":\"integer\"}}}}},\"ConversationList\":{\"type\":\"object\",\"required\":[\"type\",\"pages\",\"total_count\",\"conversations\"],\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"conversation.list\"]},\"pages\":{\"$ref\":\"#/components/schemas/Pages\"},\"total_count\":{\"type\":\"integer\"},\"conversations\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/Conversation\"}}}},\"Message\":{\"type\":\"object\",\"required\":[\"type\",\"id\",\"created_at\",\"body\",\"message_type\",\"conversation_id\"],\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"user_message\"]},\"id\":{\"type\":\"string\"},\"created_at\":{\"type\":\"integer\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"body\":{\"type\":\"string\"},\"message_type\":{\"type\":\"string\",\"enum\":[\"inapp\"]},\"conversation_id\":{\"type\":\"string\",\"x-mockingbird-resource\":{\"type\":\"conversation\",\"identity\":true}}}},\"Admin\":{\"type\":\"object\",\"required\":[\"type\",\"id\",\"name\",\"email\"],\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"admin\"]},\"id\":{\"type\":\"string\",\"x-mockingbird-resource\":{\"type\":\"admin\",\"identity\":true}},\"name\":{\"type\":\"string\"},\"email\":{\"type\":\"string\"},\"job_title\":{\"type\":[\"string\",\"null\"]},\"away_mode_enabled\":{\"type\":\"boolean\"},\"away_mode_reassign\":{\"type\":\"boolean\"},\"has_inbox_seat\":{\"type\":\"boolean\"},\"team_ids\":{\"type\":\"array\",\"items\":{\"type\":\"integer\"}}}}}}}`) as OpenAPIDocument\n\nexport type OperationId = \"SearchContacts\" | \"CreateContact\" | \"GetContact\" | \"UpdateContact\" | \"CreateConversation\" | \"SearchConversations\" | \"GetConversation\" | \"UpdateConversation\" | \"ReplyConversation\" | \"ManageConversation\" | \"ListAdmins\" | \"GetMe\"\nexport type SupportedOperationId = \"SearchContacts\" | \"CreateContact\" | \"GetContact\" | \"UpdateContact\" | \"CreateConversation\" | \"SearchConversations\" | \"GetConversation\" | \"UpdateConversation\" | \"ReplyConversation\" | \"ManageConversation\" | \"ListAdmins\" | \"GetMe\"\nexport const operationIds = [\"SearchContacts\",\"CreateContact\",\"GetContact\",\"UpdateContact\",\"CreateConversation\",\"SearchConversations\",\"GetConversation\",\"UpdateConversation\",\"ReplyConversation\",\"ManageConversation\",\"ListAdmins\",\"GetMe\"] as const\nexport const supportedOperationIds = [\"SearchContacts\",\"CreateContact\",\"GetContact\",\"UpdateContact\",\"CreateConversation\",\"SearchConversations\",\"GetConversation\",\"UpdateConversation\",\"ReplyConversation\",\"ManageConversation\",\"ListAdmins\",\"GetMe\"] as const\n", "import { fromBase64, toBase64 } from \"@crvouga/mockingbird-service\"\n\n/**\n * Intercom's search query language, shared by contact and conversation search: a filter\n * `{field, operator, value}` or a compound `{operator: \"AND\" | \"OR\", value: [query, \u2026]}`,\n * nested up to two levels.\n */\n\nexport type Filter = { field: string; operator: string; value: unknown }\nexport type Compound = { operator: \"AND\" | \"OR\"; value: Query[] }\nexport type Query = Filter | Compound\n\nexport class QueryError extends Error {}\n\nconst FILTER_OPERATORS = [\"=\", \"!=\", \"IN\", \"NIN\", \"<\", \">\", \"~\", \"!~\", \"^\", \"$\"]\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\n/** Parse and validate a query against the searchable fields. */\nexport const parseQuery = (value: unknown, fields: readonly string[], depth = 0): Query => {\n if (!isRecord(value)) throw new QueryError(\"query must be an object\")\n const operator = value.operator\n if (operator === \"AND\" || operator === \"OR\") {\n if (depth >= 2) throw new QueryError(\"queries can be nested at most two levels deep\")\n if (!Array.isArray(value.value) || value.value.length === 0) {\n throw new QueryError(`${operator} requires a non-empty value array`)\n }\n return { operator, value: value.value.map((each) => parseQuery(each, fields, depth + 1)) }\n }\n if (typeof value.field !== \"string\") throw new QueryError(\"query field is required\")\n const custom = value.field.startsWith(\"custom_attributes.\")\n if (!fields.includes(value.field) && !(custom && fields.includes(\"custom_attributes.*\"))) {\n throw new QueryError(`${value.field} is not a searchable field`)\n }\n if (typeof operator !== \"string\" || !FILTER_OPERATORS.includes(operator)) {\n throw new QueryError(`operator ${String(operator)} is not supported`)\n }\n if ((operator === \"IN\" || operator === \"NIN\") !== Array.isArray(value.value)) {\n throw new QueryError(\n `operator ${operator} ${Array.isArray(value.value) ? \"does not take\" : \"requires\"} an array value`,\n )\n }\n if (value.value === undefined) throw new QueryError(\"query value is required\")\n return { field: value.field, operator, value: value.value }\n}\n\nconst same = (actual: unknown, expected: unknown): boolean => {\n if (actual === null || actual === undefined) return expected === null || expected === \"null\"\n if (Array.isArray(actual)) return actual.some((each) => same(each, expected))\n return String(actual).toLowerCase() === String(expected).toLowerCase()\n}\n\nconst text = (value: unknown) =>\n value === null || value === undefined ? \"\" : String(value).toLowerCase()\n\nconst matchFilter = (filter: Filter, resolve: (field: string) => unknown): boolean => {\n const actual = resolve(filter.field)\n const expected = filter.value\n switch (filter.operator) {\n case \"=\":\n return same(actual, expected)\n case \"!=\":\n return !same(actual, expected)\n case \"IN\":\n return (expected as unknown[]).some((each) => same(actual, each))\n case \"NIN\":\n return !(expected as unknown[]).some((each) => same(actual, each))\n case \"<\":\n return actual !== null && actual !== undefined && Number(actual) < Number(expected)\n case \">\":\n return actual !== null && actual !== undefined && Number(actual) > Number(expected)\n case \"~\":\n return text(actual).includes(text(expected))\n case \"!~\":\n return !text(actual).includes(text(expected))\n case \"^\":\n return text(actual).startsWith(text(expected))\n case \"$\":\n return text(actual).endsWith(text(expected))\n default:\n return false\n }\n}\n\nexport const matches = (query: Query, resolve: (field: string) => unknown): boolean => {\n if (\"field\" in query) return matchFilter(query, resolve)\n return query.operator === \"AND\"\n ? query.value.every((each) => matches(each, resolve))\n : query.value.some((each) => matches(each, resolve))\n}\n\n/** Opaque cursors: base64 of `[offset]`, the shape Intercom's own cursors have. */\nexport const encodeCursor = (offset: number): string =>\n toBase64(new TextEncoder().encode(`[${offset}]`))\n\nexport const decodeCursor = (cursor: string): number => {\n try {\n const parsed = JSON.parse(new TextDecoder().decode(fromBase64(cursor))) as unknown\n if (Array.isArray(parsed) && Number.isInteger(parsed[0]) && (parsed[0] as number) >= 0) {\n return parsed[0] as number\n }\n } catch {\n // fall through\n }\n throw new QueryError(\"starting_after is not a valid cursor\")\n}\n\nexport type Page<T> = {\n items: T[]\n pages: {\n type: \"pages\"\n page: number\n per_page: number\n total_pages: number\n next?: { page: number; starting_after: string }\n }\n}\n\nexport const paginate = <T>(\n items: readonly T[],\n pagination: unknown,\n defaultPerPage: number,\n): Page<T> => {\n const options = isRecord(pagination) ? pagination : {}\n const perPage = options.per_page === undefined ? defaultPerPage : Number(options.per_page)\n if (!Number.isInteger(perPage) || perPage < 1 || perPage > 150) {\n throw new QueryError(\"per_page must be between 1 and 150\")\n }\n const offset =\n typeof options.starting_after === \"string\" && options.starting_after.length > 0\n ? decodeCursor(options.starting_after)\n : 0\n const slice = items.slice(offset, offset + perPage)\n const page = Math.floor(offset / perPage) + 1\n const total = Math.max(1, Math.ceil(items.length / perPage))\n const hasMore = offset + perPage < items.length\n return {\n items: slice,\n pages: {\n type: \"pages\",\n page,\n per_page: perPage,\n total_pages: total,\n ...(hasMore\n ? { next: { page: page + 1, starting_after: encodeCursor(offset + perPage) } }\n : {}),\n },\n }\n}\n\n// \u2500\u2500\u2500 Message bodies \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst escapeHtml = (value: string) =>\n value.replace(/&/g, \"&\").replace(/</g, \"<\").replace(/>/g, \">\").replace(/\"/g, \""\")\n\n/** A body as Intercom stores it: HTML as given, plain text wrapped in paragraphs. */\nexport const toHtml = (body: string): string => {\n if (/<[a-z][\\s\\S]*>/i.test(body)) return body\n return body\n .split(/\\r?\\n/)\n .map((line) => `<p>${escapeHtml(line)}</p>`)\n .join(\"\")\n}\n\n/** `?display_as=plaintext`: paragraphs and breaks become newlines, tags go, entities decode. */\nexport const toPlaintext = (html: string | null): string | null => {\n if (html === null) return null\n return html\n .replace(/<\\/p>\\s*<p[^>]*>/gi, \"\\n\")\n .replace(/<br\\s*\\/?>/gi, \"\\n\")\n .replace(/<[^>]*>/g, \"\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/"/g, '\"')\n .replace(/'/g, \"'\")\n .replace(/ /g, \" \")\n .replace(/&/g, \"&\")\n .trim()\n}\n", "import { Collection, opaqueToken } from \"@crvouga/mockingbird-service\"\nimport type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\n\nexport type ContactRecord = {\n id: string\n external_id: string | null\n role: \"user\" | \"lead\"\n email: string | null\n phone: string | null\n name: string | null\n created_at: number\n updated_at: number\n signed_up_at: number | null\n last_seen_at: number | null\n custom_attributes: Record<string, unknown>\n}\n\nexport type Author = {\n type: \"user\" | \"admin\" | \"bot\"\n id: string\n name: string | null\n email: string | null\n}\n\n/** Attachment metadata only: the bytes a caller uploads are never stored. */\nexport type AttachmentRecord = {\n type: \"upload\"\n name: string\n url: string\n content_type: string\n filesize: number\n width: null\n height: null\n}\n\nexport type PartRecord = {\n type: \"conversation_part\"\n id: string\n part_type: \"comment\" | \"note\" | \"quick_reply\" | \"close\" | \"open\" | \"snoozed\" | \"assignment\"\n /** HTML, as Intercom stores it. */\n body: string | null\n created_at: number\n updated_at: number\n notified_at: number\n assigned_to: { type: \"admin\"; id: string } | null\n author: Author\n attachments: AttachmentRecord[]\n external_id: null\n redacted: false\n}\n\nexport type ConversationRecord = {\n id: string\n contactId: string\n created_at: number\n updated_at: number\n waiting_since: number | null\n snoozed_until: number | null\n state: \"open\" | \"closed\" | \"snoozed\"\n /** Whether the contact has read the latest admin message. */\n read: boolean\n title: string | null\n admin_assignee_id: number | null\n /** Admins who took part, for `teammates`. */\n teammates: string[]\n custom_attributes: Record<string, unknown>\n source: {\n type: \"conversation\"\n id: string\n delivered_as: \"customer_initiated\" | \"admin_initiated\"\n subject: string\n body: string\n author: Author\n attachments: AttachmentRecord[]\n url: null\n redacted: false\n }\n parts: PartRecord[]\n}\n\nexport type AdminRecord = {\n type: \"admin\"\n id: string\n name: string\n email: string\n job_title: string | null\n away_mode_enabled: boolean\n away_mode_reassign: boolean\n has_inbox_seat: boolean\n team_ids: number[]\n}\n\n/** Per-namespace knobs, set through `PUT /__admin/settings`; cleared on reset. */\nexport type Settings = {\n /** Only these access tokens are accepted; empty means any non-empty token is. */\n tokens: string[]\n /**\n * Custom data attributes the workspace defines. Intercom rejects writes of undefined ones;\n * `null` (the default) accepts any.\n */\n customAttributes: string[] | null\n}\n\nexport const DEFAULT_SETTINGS: Settings = { tokens: [], customAttributes: null }\n\nexport const DEFAULT_ADMINS: readonly AdminRecord[] = [\n {\n type: \"admin\",\n id: \"1000001\",\n name: \"Mock Support\",\n email: \"support@mock.intercom.local\",\n job_title: \"Member Support\",\n away_mode_enabled: false,\n away_mode_reassign: false,\n has_inbox_seat: true,\n team_ids: [],\n },\n {\n type: \"admin\",\n id: \"1000002\",\n name: \"Mock Clinician\",\n email: \"clinician@mock.intercom.local\",\n job_title: \"Longevity Specialist\",\n away_mode_enabled: false,\n away_mode_reassign: false,\n has_inbox_seat: true,\n team_ids: [],\n },\n]\n\nconst hex = (input: string, length: number) =>\n [...opaqueToken(input, length)].map((c) => (c.charCodeAt(0) % 16).toString(16)).join(\"\")\n\nexport class IntercomState {\n readonly contacts: Collection<ContactRecord>\n readonly conversations: Collection<ConversationRecord>\n readonly admins: Collection<AdminRecord>\n readonly settings: Collection<Settings>\n readonly counters: Collection<number>\n readonly workspaceId: string\n\n constructor(\n sqlite: SqliteClient,\n private readonly namespace: string,\n private readonly seed: { admins: readonly AdminRecord[]; settings: Partial<Settings> },\n ) {\n this.contacts = new Collection(sqlite, namespace, \"contacts\")\n this.conversations = new Collection(sqlite, namespace, \"conversations\")\n this.admins = new Collection(sqlite, namespace, \"admins\")\n this.settings = new Collection(sqlite, namespace, \"settings\")\n this.counters = new Collection(sqlite, namespace, \"counters\")\n this.workspaceId = \"mockapp\"\n this.ensureSeeded()\n }\n\n ensureSeeded(): void {\n if (this.admins.count() === 0) {\n for (const admin of this.seed.admins) this.admins.insert(admin.id, admin)\n }\n if (!this.settings.has(\"settings\")) {\n this.settings.insert(\"settings\", { ...DEFAULT_SETTINGS, ...this.seed.settings })\n }\n }\n\n current(): Settings {\n return this.settings.get(\"settings\") ?? DEFAULT_SETTINGS\n }\n\n update(patch: Partial<Settings>): Settings {\n const next = { ...this.current(), ...patch }\n this.settings.insert(\"settings\", next)\n return next\n }\n\n /** The next value of a named counter (1, 2, \u2026), reset with the namespace. */\n next(name: string): number {\n const value = (this.counters.get(name) ?? 0) + 1\n this.counters.insert(name, value)\n return value\n }\n\n /** A 24-hex contact id, like Intercom's. */\n nextContactId(): string {\n return hex(`intercom:contact:${this.namespace}:${this.next(\"contact\")}`, 24)\n }\n\n /** A numeric-string conversation id, like Intercom's. */\n nextConversationId(): string {\n return String(215_470_000_000_000 + this.next(\"conversation\"))\n }\n\n nextPartId(): string {\n return String(30_000_000_000 + this.next(\"part\"))\n }\n\n nextMessageId(): string {\n return String(40_000_000_000 + this.next(\"message\"))\n }\n\n nextRequestId(): string {\n return `req_${hex(`intercom:request:${this.namespace}:${this.next(\"request\")}`, 20)}`\n }\n\n nextNotificationId(): string {\n return `notif_${hex(`intercom:notification:${this.namespace}:${this.next(\"notification\")}`, 32)}`\n }\n\n findContact(where: (contact: ContactRecord) => boolean): ContactRecord | undefined {\n return this.contacts.list({ order: \"oldest\", where }).at(0)?.value\n }\n}\n", "import {\n type AdminRoutes,\n bearerToken,\n type Clock,\n createRuntime as createServiceRuntime,\n createWebhookHub,\n type FaultPreset,\n hmac,\n type RequestLog,\n type ServiceRuntime,\n signers,\n type WebhookEndpoint,\n type WebhookHub,\n} from \"@crvouga/mockingbird-service\"\nimport type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\nimport { document } from \"./generated/openapi.js\"\nimport { INTERCOM_NAMESPACE, IntercomAPI, IntercomError } from \"./index.js\"\nimport { toHtml } from \"./query.js\"\nimport type { AdminRecord, Settings } from \"./state.js\"\n\n/** The header Intercom signs webhooks with (our receivers read it lower-cased). */\nexport const HUB_SIGNATURE_HEADER = \"X-Hub-Signature\"\n\n/** `sha1=<hex HMAC-SHA1(secret, rawBody)>`, Intercom's webhook signature. */\nexport const signHub = async (secret: string, body: string): Promise<string> =>\n `sha1=${await hmac(\"SHA-1\", secret, body, \"hex\")}`\n\n/** The topics a webhook endpoint receives unless it lists its own `events`. */\nconst DEFAULT_TOPICS = [\n \"conversation.admin.replied\",\n \"conversation.admin.closed\",\n \"conversation.admin.opened\",\n \"conversation.admin.single.created\",\n]\n\nconst errorBody = (code: string, message: string) => ({\n type: \"error.list\",\n request_id: \"req_mockingbird_fault\",\n errors: [{ code, message }],\n})\n\n/**\n * Every named Intercom misbehaviour our consumers branch on, switched on with\n * `POST /__admin/faults {\"preset\": \"<name>\"}` (add `count` to limit it).\n */\nexport const INTERCOM_PRESETS: Record<string, FaultPreset> = {\n rate_limited: {\n description:\n \"Every call answers 429 rate_limit_exceeded (the messaging adapter maps it to 429)\",\n rules: [\n {\n status: 429,\n body: errorBody(\"rate_limit_exceeded\", \"Rate Limit Exceeded\"),\n headers: { \"X-RateLimit-Limit\": \"10000\", \"X-RateLimit-Remaining\": \"0\" },\n },\n ],\n },\n server_error: {\n description: \"Every call answers 500 (the messaging adapter throws)\",\n rules: [{ status: 500, body: errorBody(\"server_error\", \"Server Error\") }],\n },\n service_unavailable: {\n description: \"Every call answers 503\",\n rules: [{ status: 503, body: errorBody(\"service_unavailable\", \"Service Unavailable\") }],\n },\n unauthorized: {\n description: \"Every call answers 401 unauthorized\",\n rules: [{ status: 401, body: errorBody(\"unauthorized\", \"Access Token Invalid\") }],\n },\n contact_stale_404: {\n description:\n \"The next conversation search answers 404, as when a cached contact id went stale: the adapter re-resolves the contact and retries once\",\n rules: [\n {\n operationId: \"SearchConversations\",\n status: 404,\n body: errorBody(\"not_found\", \"User Not Found\"),\n count: 1,\n },\n ],\n },\n search_unavailable: {\n description: \"Conversation search answers `conversations: null` (the admin inbox answers 503)\",\n rules: [{ operationId: \"SearchConversations\", effect: \"search_unavailable\" }],\n },\n repeated_cursor: {\n description:\n \"Conversation search always answers the same next cursor (the admin inbox detects the loop and answers 503)\",\n rules: [{ operationId: \"SearchConversations\", effect: \"repeated_cursor\" }],\n },\n webhook_duplicate: {\n description: \"The next webhook is delivered twice (receivers dedupe on the notification id)\",\n webhook: { mode: \"duplicate\" },\n },\n webhook_reorder: {\n description: \"The next two webhooks arrive swapped\",\n webhook: { mode: \"reorder\" },\n },\n webhook_drop: {\n description: \"The next webhook is never delivered\",\n webhook: { mode: \"drop\" },\n },\n}\n\nexport type IntercomRuntimeOptions = {\n sqlite?: SqliteClient\n clock?: Clock\n /** Real-time clock for webhook freshness/signing; injectable for deterministic tests. */\n wallClock?: () => number\n seed?: number | string\n adminKey?: string\n onLog?: (entry: RequestLog) => void\n admins?: readonly AdminRecord[]\n settings?: Partial<Settings>\n /**\n * Where webhooks go: the backend's `POST /messaging/webhook` and the EMR's\n * `POST /v1/webhooks/intercom`, signed with `secret` (the app's `INTERCOM_WEBHOOK_SECRET`).\n */\n webhooks?: {\n urls: readonly string[]\n secret?: string\n /** Topics to deliver; default the admin replied/closed/opened/single.created topics. */\n events?: readonly string[]\n retryDelaysMs?: readonly number[]\n fetch?: (request: Request) => Promise<Response>\n }\n}\n\nexport type IntercomRuntime = ServiceRuntime<IntercomAPI> & { readonly webhooks: WebhookHub }\n\nconst json = (status: number, body: unknown) =>\n new Response(JSON.stringify(body), { status, headers: { \"content-type\": \"application/json\" } })\nconst adminError = (status: number, message: string) =>\n json(status, { error: { type: \"mockingbird_admin\", message } })\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\nconst guard = (run: () => Response): Response => {\n try {\n return run()\n } catch (error) {\n if (error instanceof IntercomError) return adminError(error.status, error.message)\n throw error\n }\n}\n\nconst adminRoutes = (runtime: ServiceRuntime<IntercomAPI>): AdminRoutes => {\n const api = (namespace: string) => runtime.instance(namespace)\n const conversation = (namespace: string, id: string) => api(namespace).state.conversations.get(id)\n const defaultAdmin = (namespace: string) =>\n api(namespace).state.admins.list({ order: \"oldest\" }).at(0)?.value.id ?? \"\"\n return {\n \"GET /contacts\": ({ namespace }) => json(200, { contacts: api(namespace).contacts() }),\n \"GET /conversations\": ({ namespace }) =>\n json(200, { conversations: api(namespace).conversations() }),\n \"POST /conversations\": ({ body, namespace }) =>\n guard(() => {\n if (!isRecord(body) || typeof body.body !== \"string\") {\n return adminError(400, 'expected {\"contactId\" | \"externalId\", \"adminId\"?, \"body\"}')\n }\n const state = api(namespace).state\n const contactId =\n typeof body.contactId === \"string\"\n ? body.contactId\n : typeof body.externalId === \"string\"\n ? state.findContact((c) => c.external_id === body.externalId)?.id\n : undefined\n if (!contactId) return adminError(404, \"no such contact\")\n const created = api(namespace).startAdminConversation({\n contactId,\n adminId: typeof body.adminId === \"string\" ? body.adminId : defaultAdmin(namespace),\n body: body.body,\n })\n return json(201, created)\n }),\n \"POST /conversations/:id/admin-reply\": ({ params, body, namespace }) =>\n guard(() => {\n const found = conversation(namespace, params.id as string)\n if (!found) return adminError(404, `no conversation ${params.id}`)\n if (!isRecord(body) || typeof body.body !== \"string\") {\n return adminError(\n 400,\n 'expected {\"adminId\"?, \"body\", \"messageType\"?: \"comment\" | \"note\"}',\n )\n }\n const instance = api(namespace)\n const author = instance.state.admins.get(\n typeof body.adminId === \"string\" ? body.adminId : defaultAdmin(namespace),\n )\n if (!author) return adminError(404, `no admin ${String(body.adminId)}`)\n const next = instance.appendPart(found, {\n partType: body.messageType === \"note\" ? \"note\" : \"comment\",\n author: { type: \"admin\", id: author.id, name: author.name, email: author.email },\n body: toHtml(body.body),\n })\n return json(200, next)\n }),\n \"POST /conversations/:id/close\": ({ params, body, namespace }) =>\n guard(() => {\n const found = conversation(namespace, params.id as string)\n if (!found) return adminError(404, `no conversation ${params.id}`)\n const adminId =\n isRecord(body) && typeof body.adminId === \"string\"\n ? body.adminId\n : defaultAdmin(namespace)\n return json(200, api(namespace).manage(found, { action: \"close\", adminId }))\n }),\n \"POST /conversations/:id/open\": ({ params, body, namespace }) =>\n guard(() => {\n const found = conversation(namespace, params.id as string)\n if (!found) return adminError(404, `no conversation ${params.id}`)\n const adminId =\n isRecord(body) && typeof body.adminId === \"string\"\n ? body.adminId\n : defaultAdmin(namespace)\n return json(200, api(namespace).manage(found, { action: \"open\", adminId }))\n }),\n \"PUT /admins\": ({ body, namespace }) => {\n const list = Array.isArray(body) ? body : isRecord(body) ? body.admins : undefined\n if (!Array.isArray(list) || !list.every((a) => isRecord(a) && typeof a.id === \"string\")) {\n return adminError(400, \"expected [{id, name, email}, \u2026]\")\n }\n const state = api(namespace).state\n for (const row of state.admins.list()) state.admins.delete(row.id)\n for (const each of list as Record<string, unknown>[]) {\n state.admins.insert(String(each.id), {\n type: \"admin\",\n id: String(each.id),\n name: String(each.name ?? `Admin ${each.id}`),\n email: String(each.email ?? `admin${each.id}@mock.intercom.local`),\n job_title: typeof each.job_title === \"string\" ? each.job_title : null,\n away_mode_enabled: each.away_mode_enabled === true,\n away_mode_reassign: false,\n has_inbox_seat: true,\n team_ids: [],\n })\n }\n return json(200, { admins: state.admins.list({ order: \"oldest\" }).map((row) => row.value) })\n },\n \"GET /settings\": ({ namespace }) => json(200, api(namespace).state.current()),\n \"PUT /settings\": ({ body, namespace }) => {\n if (!isRecord(body)) return adminError(400, \"expected a JSON object\")\n const patch: Partial<Settings> = {}\n if (body.tokens !== undefined) {\n if (!Array.isArray(body.tokens)) return adminError(400, \"tokens: string[]\")\n patch.tokens = body.tokens.map(String)\n }\n if (body.customAttributes !== undefined) {\n if (body.customAttributes !== null && !Array.isArray(body.customAttributes)) {\n return adminError(400, \"customAttributes: string[] | null\")\n }\n patch.customAttributes =\n body.customAttributes === null ? null : body.customAttributes.map(String)\n }\n return json(200, api(namespace).state.update(patch))\n },\n }\n}\n\n/**\n * The Intercom mock with Mockingbird's full service contract: `/health`, `/__admin/*`,\n * namespaces by header, by `/ns/<name>` path prefix, or by access token\n * (`PUT /__admin/credentials {\"credentials\": {\"<INTERCOM_ACCESS_TOKEN>\": \"<namespace>\"}}`),\n * clock control, fault presets, `X-Hub-Signature`-signed webhooks and a request journal\n * (metadata only: never message bodies).\n */\nexport const createRuntime = (options: IntercomRuntimeOptions = {}): IntercomRuntime => {\n const hooks = options.webhooks\n const hub = createWebhookHub({\n signer: signers.custom(async ({ body, secret }) =>\n secret ? { [HUB_SIGNATURE_HEADER]: await signHub(secret, body) } : {},\n ),\n ...(hooks?.retryDelaysMs ? { retryDelaysMs: hooks.retryDelaysMs } : {}),\n ...(hooks?.fetch ? { fetch: hooks.fetch } : {}),\n ...(options.wallClock ? { now: options.wallClock } : {}),\n endpoints: (hooks?.urls ?? []).map(\n (url, index): WebhookEndpoint => ({\n id: `we_intercom_${index}`,\n url,\n ...(hooks?.secret ? { secret: hooks.secret } : {}),\n events: [...(hooks?.events ?? DEFAULT_TOPICS)],\n }),\n ),\n })\n const runtime = createServiceRuntime<IntercomAPI>({\n name: INTERCOM_NAMESPACE,\n document,\n ...(options.sqlite ? { sqlite: options.sqlite } : {}),\n ...(options.clock ? { clock: options.clock } : {}),\n ...(options.seed !== undefined ? { seed: options.seed } : {}),\n ...(options.adminKey !== undefined ? { adminKey: options.adminKey } : {}),\n ...(options.onLog ? { onLog: options.onLog } : {}),\n credential: bearerToken,\n presets: INTERCOM_PRESETS,\n webhooks: hub,\n create: ({ sqlite, namespace, publicNamespace, clock }) =>\n new IntercomAPI({\n sqlite,\n namespace,\n now: clock.now,\n ...(options.wallClock ? { wallClock: options.wallClock } : {}),\n ...(options.admins ? { admins: options.admins } : {}),\n ...(options.settings ? { settings: options.settings } : {}),\n onWebhook: (notification) =>\n hub.publish({\n namespace: publicNamespace,\n type: notification.topic,\n body: notification as unknown as Record<string, unknown>,\n id: notification.id,\n }),\n }),\n describe: () => ({ webhooks: hub.endpoints(\"default\").length > 0 ? \"on\" : \"off\" }),\n admin: adminRoutes,\n })\n return Object.assign(runtime, { webhooks: hub })\n}\n", "import type { FetchAPI } from \"@crvouga/mockingbird-core\"\nimport {\n type APIOptions,\n annotateResponse,\n bearerToken,\n bodyIssues,\n bootSqlite,\n createService,\n defineOperations,\n faultEffect,\n fromBase64,\n HttpError,\n IdempotencyStore,\n jsonRes,\n type OperationContext,\n requestFingerprint,\n type Service,\n} from \"@crvouga/mockingbird-service\"\nimport type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\nimport type { Hono } from \"hono\"\nimport { document, type SupportedOperationId } from \"./generated/openapi.js\"\nimport {\n encodeCursor,\n matches,\n paginate,\n parseQuery,\n QueryError,\n toHtml,\n toPlaintext,\n} from \"./query.js\"\nimport {\n type AdminRecord,\n type AttachmentRecord,\n type Author,\n type ContactRecord,\n type ConversationRecord,\n DEFAULT_ADMINS,\n IntercomState,\n type PartRecord,\n type Settings,\n} from \"./state.js\"\n\nexport type { FetchAPI } from \"@crvouga/mockingbird-core\"\nexport type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\nexport type { OperationId, SupportedOperationId } from \"./generated/openapi.js\"\nexport { document, operationIds, supportedOperationIds } from \"./generated/openapi.js\"\nexport type { Query } from \"./query.js\"\nexport { decodeCursor, encodeCursor, toHtml, toPlaintext } from \"./query.js\"\nexport type {\n AdminRecord,\n AttachmentRecord,\n Author,\n ContactRecord,\n ConversationRecord,\n PartRecord,\n Settings,\n} from \"./state.js\"\nexport { DEFAULT_ADMINS, DEFAULT_SETTINGS } from \"./state.js\"\n\nexport const INTERCOM_NAMESPACE = \"intercom\"\n\n/** The webhook topics the mock sends. */\nexport const INTERCOM_TOPICS = [\n \"conversation.admin.replied\",\n \"conversation.admin.closed\",\n \"conversation.admin.opened\",\n \"conversation.admin.snoozed\",\n \"conversation.admin.assigned\",\n \"conversation.admin.single.created\",\n] as const\nexport type IntercomTopic = (typeof INTERCOM_TOPICS)[number]\n\n/** The body Intercom posts to a webhook subscription (`type: notification_event`). */\nexport type IntercomNotification = {\n type: \"notification_event\"\n app_id: string\n data: { type: \"notification_event_data\"; item: Record<string, unknown> }\n links: Record<string, never>\n id: string\n topic: IntercomTopic\n delivery_status: \"pending\"\n delivery_attempts: number\n delivered_at: number\n first_sent_at: number\n created_at: number\n self: null\n}\n\nexport type IntercomAPIOptions = APIOptions & {\n /** Admins every namespace starts with. Default: {@link DEFAULT_ADMINS}. */\n admins?: readonly AdminRecord[]\n /** Initial per-namespace settings (accepted tokens, defined custom attributes). */\n settings?: Partial<Settings>\n /** Called for every webhook-worthy event; the runtime signs and delivers it. */\n onWebhook?: (notification: IntercomNotification) => void\n /** Wall clock used for receiver freshness checks. Defaults to `Date.now`. */\n wallClock?: () => number\n}\n\nconst CONTACT_FIELDS = [\n \"id\",\n \"external_id\",\n \"email\",\n \"name\",\n \"phone\",\n \"role\",\n \"created_at\",\n \"updated_at\",\n \"signed_up_at\",\n \"last_seen_at\",\n \"custom_attributes.*\",\n]\n\nconst CONVERSATION_FIELDS = [\n \"id\",\n \"contact_ids\",\n \"teammate_ids\",\n \"admin_assignee_id\",\n \"team_assignee_id\",\n \"state\",\n \"open\",\n \"read\",\n \"priority\",\n \"title\",\n \"created_at\",\n \"updated_at\",\n \"waiting_since\",\n \"source.id\",\n \"source.type\",\n \"source.delivered_as\",\n \"source.subject\",\n \"source.body\",\n \"source.author.id\",\n \"source.author.type\",\n \"source.author.name\",\n \"source.author.email\",\n]\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\nconst str = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.length > 0 ? value : undefined\n\n/** Admin-side outcomes of a reply or state change, surfaced to admin routes. */\nexport class IntercomError extends Error {\n constructor(\n readonly status: number,\n readonly code: string,\n message: string,\n ) {\n super(message)\n }\n}\n\n/**\n * Stateful mock of the Intercom REST API (2.11): contacts, conversations, admins.\n *\n * Admin replies and close/open (from the API or from the admin plane) emit the signed\n * `notification_event` webhooks our backend and EMR receivers verify.\n */\nexport class IntercomAPI implements FetchAPI {\n readonly app: Hono\n readonly sqlite: SqliteClient\n readonly state: IntercomState\n private readonly service: Service\n private readonly idempotency: IdempotencyStore\n private readonly now: () => number\n private readonly wallClock: () => number\n private readonly onWebhook: ((notification: IntercomNotification) => void) | undefined\n\n constructor(options: IntercomAPIOptions = {}) {\n const sqlite = bootSqlite(options.sqlite)\n const namespace = options.namespace ?? INTERCOM_NAMESPACE\n this.now = options.now ?? (() => Date.now())\n this.wallClock = options.wallClock ?? Date.now\n this.onWebhook = options.onWebhook\n this.state = new IntercomState(sqlite, namespace, {\n admins: options.admins ?? DEFAULT_ADMINS,\n settings: options.settings ?? {},\n })\n this.idempotency = new IdempotencyStore(sqlite, namespace)\n const handlers = defineOperations<SupportedOperationId>({\n SearchContacts: (context) => this.searchContacts(context),\n CreateContact: (context) => this.createContact(context),\n GetContact: (context) => {\n const contact = this.state.contacts.get(context.params.contact_id ?? \"\")\n return contact\n ? annotateResponse(jsonRes(200, this.contactBody(contact)), {\n ids: { contactId: contact.id },\n })\n : this.error(404, \"not_found\", \"User Not Found\")\n },\n UpdateContact: (context) => this.updateContact(context),\n CreateConversation: (context) => this.createConversation(context),\n UpdateConversation: (context) => this.updateConversation(context),\n ReplyConversation: (context) => this.reply(context),\n ManageConversation: (context) => this.manageConversation(context),\n GetConversation: (context) =>\n this.withConversation(context, (conversation) =>\n jsonRes(\n 200,\n this.conversationBody(conversation, {\n plaintext: context.query.display_as === \"plaintext\",\n parts: conversation.parts,\n }),\n ),\n ),\n SearchConversations: (context) => this.searchConversations(context),\n ListAdmins: () =>\n jsonRes(200, {\n type: \"admin.list\",\n admins: this.state.admins.list({ order: \"oldest\" }).map((row) => row.value),\n }),\n GetMe: () =>\n jsonRes(200, {\n type: \"admin\",\n id: \"1000000\",\n name: \"Mockingbird API\",\n email: \"api@mock.intercom.local\",\n email_verified: true,\n has_inbox_seat: false,\n avatar: { type: \"avatar\", image_url: null },\n app: {\n type: \"app\",\n id_code: this.state.workspaceId,\n name: \"Mockingbird\",\n created_at: 1_600_000_000,\n secure: false,\n identity_verification: false,\n timezone: \"America/Los_Angeles\",\n region: \"US\",\n },\n }),\n })\n this.service = createService({\n document,\n handlers,\n sqlite,\n namespace,\n now: this.now,\n notFound: () => this.error(404, \"not_found\", \"Resource Not Found\"),\n onError: (thrown) => {\n if (thrown instanceof HttpError) return thrown.toResponse()\n if (thrown instanceof QueryError)\n return this.error(400, \"parameter_invalid\", thrown.message)\n if (thrown instanceof IntercomError)\n return this.error(thrown.status, thrown.code, thrown.message)\n throw thrown\n },\n before: (context) => {\n const token = bearerToken(context.request)\n if (!token) return this.error(401, \"unauthorized\", \"Access Token Required\")\n const tokens = this.state.current().tokens\n if (tokens.length > 0 && !tokens.includes(token)) {\n return this.error(401, \"unauthorized\", \"Access Token Invalid\")\n }\n const version = context.request.headers.get(\"intercom-version\")\n if (version !== null && !/^(\\d+\\.\\d+|Unstable)$/.test(version.trim())) {\n return this.error(\n 400,\n \"intercom_version_invalid\",\n \"The requested version could not be found\",\n )\n }\n return undefined\n },\n })\n this.app = this.service.app\n this.sqlite = this.service.sqlite\n }\n\n fetch(request: Request): Promise<Response> {\n return this.service.fetch(request)\n }\n\n async reset(): Promise<void> {\n await this.service.reset()\n this.state.ensureSeeded()\n }\n\n private seconds(): number {\n return Math.floor(this.now() / 1000)\n }\n\n /** Intercom's error envelope. */\n error(status: number, code: string, message: string): Response {\n return jsonRes(status, {\n type: \"error.list\",\n request_id: this.state.nextRequestId(),\n errors: [{ code, message }],\n })\n }\n\n private json(context: OperationContext): Record<string, unknown> {\n const issues = bodyIssues(context)\n if (issues.length > 0) {\n const first = issues[0] as { path: string; message: string }\n const missing = /^missing required property (.+)$/.exec(first.message)\n throw missing\n ? new IntercomError(\n 400,\n \"parameter_not_found\",\n `${[first.path, missing[1]].filter(Boolean).join(\".\")} is required`,\n )\n : new IntercomError(400, \"parameter_invalid\", `${first.path || \"body\"} ${first.message}`)\n }\n return context.body.kind === \"json\" && isRecord(context.body.value) ? context.body.value : {}\n }\n\n // \u2500\u2500\u2500 Contacts \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n contactBody(contact: ContactRecord) {\n const list = (url: string) => ({ type: \"list\", data: [], url, total_count: 0, has_more: false })\n return {\n type: \"contact\",\n id: contact.id,\n workspace_id: this.state.workspaceId,\n external_id: contact.external_id,\n role: contact.role,\n email: contact.email,\n phone: contact.phone,\n name: contact.name,\n avatar: null,\n owner_id: null,\n social_profiles: { type: \"list\", data: [] },\n has_hard_bounced: false,\n marked_email_as_spam: false,\n unsubscribed_from_emails: false,\n created_at: contact.created_at,\n updated_at: contact.updated_at,\n signed_up_at: contact.signed_up_at,\n last_seen_at: contact.last_seen_at,\n last_replied_at: null,\n last_contacted_at: null,\n last_email_opened_at: null,\n last_email_clicked_at: null,\n language_override: null,\n browser: null,\n browser_version: null,\n browser_language: null,\n os: null,\n location: { type: \"location\", country: null, region: null, city: null },\n custom_attributes: contact.custom_attributes,\n tags: list(`/contacts/${contact.id}/tags`),\n notes: list(`/contacts/${contact.id}/notes`),\n companies: list(`/contacts/${contact.id}/companies`),\n }\n }\n\n private contactField(contact: ContactRecord, field: string): unknown {\n if (field.startsWith(\"custom_attributes.\")) {\n return contact.custom_attributes[field.slice(\"custom_attributes.\".length)]\n }\n return (contact as unknown as Record<string, unknown>)[field]\n }\n\n private searchContacts(context: OperationContext): Response {\n const body = this.json(context)\n const query = parseQuery(body.query, CONTACT_FIELDS)\n const found = this.state.contacts\n .list({ order: \"oldest\" })\n .map((row) => row.value)\n .filter((contact) => matches(query, (field) => this.contactField(contact, field)))\n const page = paginate(found, body.pagination, 50)\n return jsonRes(200, {\n type: \"list\",\n data: page.items.map((contact) => this.contactBody(contact)),\n total_count: found.length,\n pages: page.pages,\n })\n }\n\n private checkCustomAttributes(attributes: unknown): Record<string, unknown> {\n if (attributes === undefined) return {}\n const defined = this.state.current().customAttributes\n const given = isRecord(attributes) ? attributes : {}\n if (defined !== null) {\n const unknown = Object.keys(given).find((key) => !defined.includes(key))\n if (unknown !== undefined) {\n throw new IntercomError(\n 400,\n \"parameter_invalid\",\n `Custom attribute '${unknown}' does not exist`,\n )\n }\n }\n return given\n }\n\n /** The contact another contact's identifiers would collide with (users only). */\n private duplicateOf(\n candidate: { role: string; external_id: string | null; email: string | null },\n except?: string,\n ): ContactRecord | undefined {\n if (candidate.role !== \"user\") return undefined\n return this.state.findContact(\n (other) =>\n other.id !== except &&\n other.role === \"user\" &&\n ((candidate.external_id !== null && other.external_id === candidate.external_id) ||\n (candidate.email !== null &&\n other.email !== null &&\n other.email.toLowerCase() === candidate.email.toLowerCase())),\n )\n }\n\n private createContact(context: OperationContext): Response {\n const body = this.json(context)\n const role = body.role === \"lead\" ? \"lead\" : \"user\"\n const externalId = str(body.external_id) ?? null\n const email = str(body.email) ?? null\n if (role === \"user\" && externalId === null && email === null) {\n return this.error(400, \"parameter_invalid\", \"A user contact requires an email or external_id\")\n }\n const customAttributes = this.checkCustomAttributes(body.custom_attributes)\n const duplicate = this.duplicateOf({ role, external_id: externalId, email })\n if (duplicate) {\n return annotateResponse(\n this.error(\n 409,\n \"conflict\",\n `A contact matching those details already exists with id=${duplicate.id}`,\n ),\n { ids: { contactId: duplicate.id } },\n )\n }\n const now = this.seconds()\n const contact: ContactRecord = {\n id: this.state.nextContactId(),\n external_id: externalId,\n role,\n email,\n phone: str(body.phone) ?? null,\n name: str(body.name) ?? null,\n created_at: now,\n updated_at: now,\n signed_up_at: typeof body.signed_up_at === \"number\" ? body.signed_up_at : null,\n last_seen_at: typeof body.last_seen_at === \"number\" ? body.last_seen_at : null,\n custom_attributes: customAttributes,\n }\n this.state.contacts.insert(contact.id, contact)\n return annotateResponse(jsonRes(200, this.contactBody(contact)), {\n ids: { contactId: contact.id },\n })\n }\n\n private updateContact(context: OperationContext): Response {\n const existing = this.state.contacts.get(context.params.contact_id ?? \"\")\n if (!existing) return this.error(404, \"not_found\", \"User Not Found\")\n const body = this.json(context)\n const customAttributes = this.checkCustomAttributes(body.custom_attributes)\n const next: ContactRecord = {\n ...existing,\n ...(body.role === \"user\" || body.role === \"lead\" ? { role: body.role } : {}),\n ...(\"external_id\" in body ? { external_id: str(body.external_id) ?? null } : {}),\n ...(\"email\" in body ? { email: str(body.email) ?? null } : {}),\n ...(\"name\" in body ? { name: str(body.name) ?? null } : {}),\n ...(\"phone\" in body ? { phone: str(body.phone) ?? null } : {}),\n ...(typeof body.signed_up_at === \"number\" || body.signed_up_at === null\n ? { signed_up_at: body.signed_up_at }\n : {}),\n ...(typeof body.last_seen_at === \"number\" || body.last_seen_at === null\n ? { last_seen_at: body.last_seen_at }\n : {}),\n custom_attributes: { ...existing.custom_attributes, ...customAttributes },\n updated_at: this.seconds(),\n }\n const duplicate = this.duplicateOf(next, existing.id)\n if (duplicate) {\n return this.error(\n 409,\n \"conflict\",\n `A contact matching those details already exists with id=${duplicate.id}`,\n )\n }\n this.state.contacts.update(existing.id, next)\n return annotateResponse(jsonRes(200, this.contactBody(next)), { ids: { contactId: next.id } })\n }\n\n // \u2500\u2500\u2500 Conversations \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private withConversation(\n context: OperationContext,\n handle: (conversation: ConversationRecord) => Response | Promise<Response>,\n ): Response | Promise<Response> {\n const conversation = this.state.conversations.get(context.params.conversation_id ?? \"\")\n if (!conversation) return this.error(404, \"not_found\", \"Resource Not Found\")\n return handle(conversation)\n }\n\n /**\n * A conversation as Intercom serializes it. `parts` is omitted in search results, as the\n * real API does; `plaintext` renders bodies for `?display_as=plaintext`.\n */\n conversationBody(\n conversation: ConversationRecord,\n options: { plaintext?: boolean; parts?: readonly PartRecord[] } = {},\n ) {\n const render = (body: string | null) => (options.plaintext ? toPlaintext(body) : body)\n const contact = this.state.contacts.get(conversation.contactId)\n return {\n type: \"conversation\",\n id: conversation.id,\n title: conversation.title,\n created_at: conversation.created_at,\n updated_at: conversation.updated_at,\n waiting_since: conversation.waiting_since,\n snoozed_until: conversation.snoozed_until,\n open: conversation.state !== \"closed\",\n state: conversation.state,\n read: conversation.read,\n priority: \"not_priority\",\n admin_assignee_id: conversation.admin_assignee_id,\n team_assignee_id: null,\n tags: { type: \"tag.list\", tags: [] },\n conversation_rating: null,\n source: { ...conversation.source, body: render(conversation.source.body) },\n contacts: {\n type: \"contact.list\",\n contacts: [\n {\n type: \"contact\",\n id: conversation.contactId,\n external_id: contact?.external_id ?? null,\n },\n ],\n },\n teammates: {\n type: \"admin.list\",\n admins: conversation.teammates.map((id) => ({ type: \"admin\", id })),\n },\n custom_attributes: conversation.custom_attributes,\n first_contact_reply: null,\n sla_applied: null,\n statistics: null,\n ai_agent_participated: false,\n ...(options.parts\n ? {\n conversation_parts: {\n type: \"conversation_part.list\",\n conversation_parts: options.parts.map((part) => ({\n ...part,\n body: render(part.body),\n })),\n total_count: options.parts.length,\n },\n }\n : {}),\n }\n }\n\n private authorOf(contact: ContactRecord): Author {\n return { type: \"user\", id: contact.id, name: contact.name, email: contact.email }\n }\n\n private adminAuthor(adminId: unknown): Author {\n const admin = typeof adminId === \"string\" ? this.state.admins.get(adminId) : undefined\n if (!admin) throw new IntercomError(404, \"not_found\", \"Admin Not Found\")\n return { type: \"admin\", id: admin.id, name: admin.name, email: admin.email }\n }\n\n private createConversation(context: OperationContext): Promise<Response> | Response {\n const body = this.json(context)\n const create = () => {\n const from = body.from as { type: string; id: string }\n const contact = this.state.contacts.get(from.id)\n if (!contact) return this.error(404, \"not_found\", \"User Not Found\")\n const now = this.seconds()\n const conversation: ConversationRecord = {\n id: this.state.nextConversationId(),\n contactId: contact.id,\n created_at: now,\n updated_at: now,\n waiting_since: now,\n snoozed_until: null,\n state: \"open\",\n read: true,\n title: null,\n admin_assignee_id: null,\n teammates: [],\n custom_attributes: {},\n source: {\n type: \"conversation\",\n id: this.state.nextMessageId(),\n delivered_as: \"customer_initiated\",\n subject: \"\",\n body: toHtml(String(body.body)),\n author: this.authorOf(contact),\n attachments: [],\n url: null,\n redacted: false,\n },\n parts: [],\n }\n this.state.conversations.insert(conversation.id, conversation)\n return annotateResponse(\n jsonRes(200, {\n type: \"user_message\",\n id: conversation.source.id,\n created_at: now,\n body: conversation.source.body,\n message_type: \"inapp\",\n conversation_id: conversation.id,\n }),\n { ids: { contactId: contact.id, conversationId: conversation.id } },\n )\n }\n const key = context.request.headers.get(\"idempotency-key\")\n if (!key) return create()\n return this.idempotency.run(\n key,\n requestFingerprint(\"POST\", \"/conversations\", body),\n {\n mismatch: () =>\n this.error(409, \"conflict\", \"Idempotency-Key was already used with different parameters\"),\n conflict: () =>\n this.error(409, \"conflict\", \"A request with this Idempotency-Key is still in progress\"),\n },\n create,\n )\n }\n\n private updateConversation(context: OperationContext): Response | Promise<Response> {\n return this.withConversation(context, (conversation) => {\n const body = this.json(context)\n const next: ConversationRecord = {\n ...conversation,\n ...(typeof body.read === \"boolean\" ? { read: body.read } : {}),\n ...(typeof body.title === \"string\" ? { title: body.title } : {}),\n custom_attributes: {\n ...conversation.custom_attributes,\n ...(isRecord(body.custom_attributes) ? body.custom_attributes : {}),\n },\n updated_at: this.seconds(),\n }\n this.state.conversations.update(conversation.id, next)\n return annotateResponse(\n jsonRes(\n 200,\n this.conversationBody(next, {\n plaintext: context.query.display_as === \"plaintext\",\n parts: next.parts,\n }),\n ),\n { ids: { conversationId: next.id } },\n )\n })\n }\n\n private async readReply(context: OperationContext): Promise<{\n fields: Record<string, unknown>\n attachments: Omit<AttachmentRecord, \"url\">[]\n urls: string[]\n }> {\n if (context.body.kind === \"bytes\" || context.body.kind === \"text\") {\n const contentType = context.request.headers.get(\"content-type\") ?? \"\"\n if (!contentType.toLowerCase().startsWith(\"multipart/form-data\")) {\n throw new IntercomError(400, \"parameter_invalid\", \"Unsupported content type\")\n }\n let form: FormData\n try {\n const raw =\n context.body.kind === \"bytes\"\n ? context.body.value\n : new TextEncoder().encode(context.body.value)\n form = await new Response(raw as BodyInit, {\n headers: { \"content-type\": contentType },\n }).formData()\n } catch {\n throw new IntercomError(400, \"parameter_invalid\", \"Malformed multipart body\")\n }\n const fields: Record<string, unknown> = {}\n const attachments: Omit<AttachmentRecord, \"url\">[] = []\n for (const [name, value] of form.entries()) {\n const entry = value as unknown as string | Blob\n if (typeof entry === \"string\") {\n fields[name] = entry\n } else if (name === \"attachment_files[]\" || name === \"attachment_files\") {\n attachments.push({\n type: \"upload\",\n name: (entry as Blob & { name?: string }).name || \"attachment\",\n content_type: entry.type || \"application/octet-stream\",\n filesize: entry.size,\n width: null,\n height: null,\n })\n }\n }\n return { fields, attachments, urls: [] }\n }\n const fields = this.json(context)\n const attachments = (Array.isArray(fields.attachment_files) ? fields.attachment_files : []).map(\n (file) => {\n const entry = file as { content_type: string; name: string; data: string }\n let size: number\n try {\n size = fromBase64(entry.data).byteLength\n } catch {\n throw new IntercomError(\n 400,\n \"parameter_invalid\",\n `attachment ${entry.name} is not valid base64`,\n )\n }\n return {\n type: \"upload\" as const,\n name: entry.name,\n content_type: entry.content_type,\n filesize: size,\n width: null,\n height: null,\n }\n },\n )\n const urls = (Array.isArray(fields.attachment_urls) ? fields.attachment_urls : []).map(String)\n return { fields, attachments, urls }\n }\n\n private async reply(context: OperationContext): Promise<Response> {\n const conversation = this.state.conversations.get(context.params.conversation_id ?? \"\")\n if (!conversation) return this.error(404, \"not_found\", \"Resource Not Found\")\n const { fields, attachments, urls } = await this.readReply(context)\n const messageType = fields.message_type\n if (messageType !== \"comment\" && messageType !== \"note\" && messageType !== \"quick_reply\") {\n return this.error(\n 400,\n \"parameter_invalid\",\n \"message_type must be comment, note or quick_reply\",\n )\n }\n let author: Author\n if (fields.type === \"user\") {\n if (messageType !== \"comment\") {\n return this.error(\n 400,\n \"parameter_invalid\",\n \"A user can only reply with message_type comment\",\n )\n }\n const contact =\n (str(fields.intercom_user_id) &&\n this.state.contacts.get(fields.intercom_user_id as string)) ||\n (str(fields.user_id) && this.state.findContact((c) => c.external_id === fields.user_id)) ||\n (str(fields.email) &&\n this.state.findContact(\n (c) => c.email?.toLowerCase() === String(fields.email).toLowerCase(),\n )) ||\n undefined\n if (!contact) return this.error(404, \"not_found\", \"User Not Found\")\n author = this.authorOf(contact)\n } else if (fields.type === \"admin\") {\n author = this.adminAuthor(fields.admin_id)\n } else {\n return this.error(400, \"parameter_invalid\", \"type must be user or admin\")\n }\n const total = attachments.length + urls.length\n if (total > 10) return this.error(400, \"parameter_invalid\", \"At most 10 attachments per reply\")\n const body = str(fields.body)\n if (body === undefined && total === 0)\n return this.error(400, \"parameter_not_found\", \"Body is required\")\n const partId = this.state.nextPartId()\n const stored: AttachmentRecord[] = [\n ...attachments.map((a, index) => ({\n ...a,\n url: `https://downloads.intercomcdn.com/i/o/${partId}/${index}/${encodeURIComponent(a.name)}`,\n })),\n ...urls.map((url) => ({\n type: \"upload\" as const,\n name: url.split(\"/\").pop() || \"attachment\",\n url,\n content_type: \"application/octet-stream\",\n filesize: 0,\n width: null,\n height: null,\n })),\n ]\n const next = this.appendPart(conversation, {\n id: partId,\n partType: messageType,\n author,\n body: body === undefined ? null : toHtml(body),\n attachments: stored,\n })\n return annotateResponse(jsonRes(200, this.conversationBody(next, { parts: next.parts })), {\n ids: { conversationId: next.id, partId },\n })\n }\n\n /** Add a comment/note part, update read/state, and fire `conversation.admin.replied`. */\n appendPart(\n conversation: ConversationRecord,\n input: {\n id?: string\n partType: \"comment\" | \"note\" | \"quick_reply\"\n author: Author\n body: string | null\n attachments?: AttachmentRecord[]\n },\n ): ConversationRecord {\n const now = this.seconds()\n const part: PartRecord = {\n type: \"conversation_part\",\n id: input.id ?? this.state.nextPartId(),\n part_type: input.partType,\n body: input.body,\n created_at: now,\n updated_at: now,\n notified_at: now,\n assigned_to: null,\n author: input.author,\n attachments: input.attachments ?? [],\n external_id: null,\n redacted: false,\n }\n const byAdmin = input.author.type === \"admin\"\n const visible = input.partType !== \"note\"\n const next: ConversationRecord = {\n ...conversation,\n parts: [...conversation.parts, part],\n updated_at: now,\n ...(byAdmin\n ? {\n teammates: conversation.teammates.includes(input.author.id)\n ? conversation.teammates\n : [...conversation.teammates, input.author.id],\n ...(visible ? { read: false, waiting_since: null } : {}),\n }\n : { read: true, waiting_since: now, state: \"open\" as const, snoozed_until: null }),\n }\n this.state.conversations.update(conversation.id, next)\n if (byAdmin && visible) this.notify(\"conversation.admin.replied\", next, [part])\n return next\n }\n\n private manageConversation(context: OperationContext): Response | Promise<Response> {\n return this.withConversation(context, (conversation) => {\n const body = this.json(context)\n const next = this.manage(conversation, {\n action: body.message_type as \"close\" | \"open\" | \"snoozed\" | \"assignment\",\n adminId: String(body.admin_id),\n ...(str(body.body) ? { body: body.body as string } : {}),\n ...(typeof body.snoozed_until === \"number\" ? { snoozedUntil: body.snoozed_until } : {}),\n ...(body.assignee_id !== undefined ? { assigneeId: String(body.assignee_id) } : {}),\n })\n return annotateResponse(jsonRes(200, this.conversationBody(next, { parts: next.parts })), {\n ids: { conversationId: next.id, partId: next.parts.at(-1)?.id ?? \"\" },\n })\n })\n }\n\n /** Close, open, snooze or assign as an admin; close and open fire their webhooks. */\n manage(\n conversation: ConversationRecord,\n input: {\n action: \"close\" | \"open\" | \"snoozed\" | \"assignment\"\n adminId: string\n body?: string\n snoozedUntil?: number\n assigneeId?: string\n },\n ): ConversationRecord {\n const author = this.adminAuthor(input.adminId)\n const now = this.seconds()\n if (input.action === \"snoozed\" && input.snoozedUntil === undefined) {\n throw new IntercomError(400, \"parameter_not_found\", \"snoozed_until is required\")\n }\n let assignee: AdminRecord | undefined\n if (input.action === \"assignment\") {\n if (input.assigneeId === undefined) {\n throw new IntercomError(400, \"parameter_not_found\", \"assignee_id is required\")\n }\n assignee = input.assigneeId === \"0\" ? undefined : this.state.admins.get(input.assigneeId)\n if (input.assigneeId !== \"0\" && !assignee) {\n throw new IntercomError(404, \"not_found\", \"Admin Not Found\")\n }\n }\n const part: PartRecord = {\n type: \"conversation_part\",\n id: this.state.nextPartId(),\n part_type: input.action,\n body: input.body === undefined ? null : toHtml(input.body),\n created_at: now,\n updated_at: now,\n notified_at: now,\n assigned_to: assignee ? { type: \"admin\", id: assignee.id } : null,\n author,\n attachments: [],\n external_id: null,\n redacted: false,\n }\n const next: ConversationRecord = {\n ...conversation,\n parts: [...conversation.parts, part],\n updated_at: now,\n ...(input.action === \"close\" ? { state: \"closed\" as const, snoozed_until: null } : {}),\n ...(input.action === \"open\" ? { state: \"open\" as const, snoozed_until: null } : {}),\n ...(input.action === \"snoozed\"\n ? { state: \"snoozed\" as const, snoozed_until: input.snoozedUntil ?? null }\n : {}),\n ...(input.action === \"assignment\"\n ? { admin_assignee_id: assignee ? Number(assignee.id) : null }\n : {}),\n }\n this.state.conversations.update(conversation.id, next)\n const topic = {\n close: \"conversation.admin.closed\",\n open: \"conversation.admin.opened\",\n snoozed: \"conversation.admin.snoozed\",\n assignment: \"conversation.admin.assigned\",\n }[input.action] as IntercomTopic\n this.notify(topic, next, [part])\n return next\n }\n\n /** An admin-initiated conversation (Intercom's outbound message): fires `admin.single.created`. */\n startAdminConversation(input: {\n contactId: string\n adminId: string\n body: string\n }): ConversationRecord {\n const contact = this.state.contacts.get(input.contactId)\n if (!contact) throw new IntercomError(404, \"not_found\", \"User Not Found\")\n const author = this.adminAuthor(input.adminId)\n const now = this.seconds()\n const conversation: ConversationRecord = {\n id: this.state.nextConversationId(),\n contactId: contact.id,\n created_at: now,\n updated_at: now,\n waiting_since: null,\n snoozed_until: null,\n state: \"open\",\n read: false,\n title: null,\n admin_assignee_id: null,\n teammates: [author.id],\n custom_attributes: {},\n source: {\n type: \"conversation\",\n id: this.state.nextMessageId(),\n delivered_as: \"admin_initiated\",\n subject: \"\",\n body: toHtml(input.body),\n author,\n attachments: [],\n url: null,\n redacted: false,\n },\n parts: [],\n }\n this.state.conversations.insert(conversation.id, conversation)\n this.notify(\"conversation.admin.single.created\", conversation, [])\n return conversation\n }\n\n private conversationField(conversation: ConversationRecord, field: string): unknown {\n switch (field) {\n case \"contact_ids\":\n return [conversation.contactId]\n case \"teammate_ids\":\n return conversation.teammates\n case \"open\":\n return conversation.state !== \"closed\"\n case \"team_assignee_id\":\n return null\n case \"priority\":\n return \"not_priority\"\n default: {\n if (field.startsWith(\"source.\")) {\n let value: unknown = conversation.source\n for (const key of field.slice(\"source.\".length).split(\".\")) {\n value = isRecord(value) ? value[key] : undefined\n }\n return value\n }\n return (conversation as unknown as Record<string, unknown>)[field]\n }\n }\n }\n\n private searchConversations(context: OperationContext): Response {\n const body = this.json(context)\n const query = parseQuery(body.query, CONVERSATION_FIELDS)\n const sortField = str(body.sort_field) ?? \"updated_at\"\n const descending = body.sort_order !== \"ascending\"\n const found = this.state.conversations\n .list({ order: \"oldest\" })\n .map((row) => row.value)\n .filter((conversation) =>\n matches(query, (field) => this.conversationField(conversation, field)),\n )\n .sort((a, b) => {\n const x = Number(this.conversationField(a, sortField) ?? 0)\n const y = Number(this.conversationField(b, sortField) ?? 0)\n return (\n (descending ? y - x : x - y) ||\n (descending ? Number(b.id) - Number(a.id) : Number(a.id) - Number(b.id))\n )\n })\n const page = paginate(found, body.pagination, 20)\n const plaintext = context.query.display_as === \"plaintext\"\n if (faultEffect(context.request, \"search_unavailable\") !== undefined) {\n return jsonRes(200, {\n type: \"conversation.list\",\n pages: page.pages,\n total_count: found.length,\n conversations: null,\n })\n }\n const pages =\n faultEffect(context.request, \"repeated_cursor\") !== undefined\n ? {\n ...page.pages,\n next: { page: page.pages.page + 1, starting_after: encodeCursor(1_000_000) },\n }\n : page.pages\n return jsonRes(200, {\n type: \"conversation.list\",\n pages,\n total_count: found.length,\n conversations: page.items.map((conversation) =>\n this.conversationBody(conversation, { plaintext }),\n ),\n })\n }\n\n /**\n * Build and emit a `notification_event`. The item is the conversation with only the new\n * part(s), whose timestamps \u2014 like the envelope's \u2014 are wall-clock time, never the mock\n * clock: the EMR receiver rejects parts older than 5 minutes against its own clock.\n */\n private notify(\n topic: IntercomTopic,\n conversation: ConversationRecord,\n parts: PartRecord[],\n ): void {\n if (!this.onWebhook) return\n const wall = Math.floor(this.wallClock() / 1000)\n const item = this.conversationBody(conversation, {\n parts: parts.map((part) => ({\n ...part,\n created_at: wall,\n updated_at: wall,\n notified_at: wall,\n })),\n })\n this.onWebhook({\n type: \"notification_event\",\n app_id: this.state.workspaceId,\n data: { type: \"notification_event_data\", item },\n links: {},\n id: this.state.nextNotificationId(),\n topic,\n delivery_status: \"pending\",\n delivery_attempts: 1,\n delivered_at: 0,\n first_sent_at: wall,\n created_at: wall,\n self: null,\n })\n }\n\n /** Every conversation, oldest first (admin inspection). */\n conversations(): ConversationRecord[] {\n return this.state.conversations.list({ order: \"oldest\" }).map((row) => row.value)\n }\n\n contacts(): ContactRecord[] {\n return this.state.contacts.list({ order: \"oldest\" }).map((row) => row.value)\n }\n}\n\nexport type { IntercomRuntime, IntercomRuntimeOptions } from \"./runtime.js\"\nexport { createRuntime, HUB_SIGNATURE_HEADER, INTERCOM_PRESETS, signHub } from \"./runtime.js\"\n"],
|
|
5
|
+
"mappings": ";AAgCO,IAAM,cAAc,CAAC,SAAuB,KAAK,QAAc;AACpE,MAAI,WAAW;AACf,MAAI;AACJ,QAAM,MAAM,MAAM,YAAY,OAAM,IAAK;AACzC,SAAO;IACL;IACA,KAAK,CAAC,YAAW;AACf,UAAI,aAAa;AAAW,mBAAW;;AAClC,mBAAW,UAAU,OAAM;IAClC;IACA,SAAS,CAAC,YAAW;AACnB,UAAI,aAAa;AAAW,oBAAY;;AACnC,oBAAY;IACnB;IACA,QAAQ,MAAK;AACX,iBAAW,IAAG;IAChB;IACA,UAAU,MAAK;AACb,UAAI,aAAa;AAAW;AAC5B,iBAAW,WAAW,OAAM;AAC5B,iBAAW;IACb;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AA,MACN;AAAA,MACA,aAAa,MAAM;AAAA,MACnB,eAAe,KAAK,MAAM;AAAA,QAAI,CAAC,iBAC7B,KAAK,iBAAiB,cAAc,EAAE,UAAU,CAAC;AAAA,MACnD;AAAA,IACF,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOQ,OACN,OACA,cACA,OACM;AACN,QAAI,CAAC,KAAK,UAAW;AACrB,UAAM,OAAO,KAAK,MAAM,KAAK,UAAU,IAAI,GAAI;AAC/C,UAAM,OAAO,KAAK,iBAAiB,cAAc;AAAA,MAC/C,OAAO,MAAM,IAAI,CAAC,UAAU;AAAA,QAC1B,GAAG;AAAA,QACH,YAAY;AAAA,QACZ,YAAY;AAAA,QACZ,aAAa;AAAA,MACf,EAAE;AAAA,IACJ,CAAC;AACD,SAAK,UAAU;AAAA,MACb,MAAM;AAAA,MACN,QAAQ,KAAK,MAAM;AAAA,MACnB,MAAM,EAAE,MAAM,2BAA2B,KAAK;AAAA,MAC9C,OAAO,CAAC;AAAA,MACR,IAAI,KAAK,MAAM,mBAAmB;AAAA,MAClC;AAAA,MACA,iBAAiB;AAAA,MACjB,mBAAmB;AAAA,MACnB,cAAc;AAAA,MACd,eAAe;AAAA,MACf,YAAY;AAAA,MACZ,MAAM;AAAA,IACR,CAAC;AAAA,EACH;AAAA;AAAA,EAGA,gBAAsC;AACpC,WAAO,KAAK,MAAM,cAAc,KAAK,EAAE,OAAO,SAAS,CAAC,EAAE,IAAI,CAAC,QAAQ,IAAI,KAAK;AAAA,EAClF;AAAA,EAEA,WAA4B;AAC1B,WAAO,KAAK,MAAM,SAAS,KAAK,EAAE,OAAO,SAAS,CAAC,EAAE,IAAI,CAAC,QAAQ,IAAI,KAAK;AAAA,EAC7E;AACF;",
|
|
6
|
+
"names": ["text", "next", "document", "document", "document", "document", "matches", "text", "text", "isRecord", "document", "inFlight", "id", "json", "adminError", "isRecord", "BRANCH_PATTERN", "document", "snapshot", "branch", "url", "response", "isRecord", "matches", "json", "adminError", "isRecord", "createRuntime", "isRecord", "matches", "fields", "attachments"]
|
|
7
|
+
}
|