@crvouga/mockingbird-service-otel 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,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", "../../../http/codec/src/form.ts", "../../../http/codec/src/content.ts", "../../core/src/http.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/webhooks.ts", "../../core/src/runtime.ts", "../src/generated/openapi.ts", "../src/otlp.ts", "../src/protobuf.ts", "../src/sql.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", "/**\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 { 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", "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", "// 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\":\"OTLP/HTTP collector and OpenObserve search (Mockingbird subset)\",\"description\":\"An OTLP/HTTP receiver (traces, logs, metrics; JSON and protobuf) in front of the\\\\nOpenObserve (O2) search API, over one store: a test emits a span or a structured \\`event\\`\\\\nlog and queries it back with the same SQL our clients send.\\\\n\",\"version\":\"1\",\"x-mockingbird-upstream\":{\"note\":\"OTLP/HTTP per opentelemetry-proto v1 (https://opentelemetry.io/docs/specs/otlp/); the O2 routes follow OpenObserve's API (/api-doc/openapi.json, v0.92) trimmed to what our clients call.\"}},\"servers\":[{\"url\":\"https://otel.gogeviti.com\"},{\"url\":\"https://observe.gogeviti.com\"}],\"security\":[{\"bearerAuth\":[]}],\"paths\":{\"/v1/traces\":{\"post\":{\"operationId\":\"ExportTraces\",\"summary\":\"OTLP/HTTP trace export (ExportTraceServiceRequest)\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":false}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ExportTraceServiceRequest\"}},\"application/x-protobuf\":{\"schema\":{\"type\":\"string\",\"format\":\"binary\"}}}},\"responses\":{\"200\":{\"description\":\"Accepted. JSON requests get \\`{partialSuccess: {}}\\`; protobuf requests get an empty protobuf response.\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ExportResponse\"}},\"application/x-protobuf\":{\"schema\":{\"type\":\"string\",\"format\":\"binary\"}}}},\"400\":{\"description\":\"Undecodable payload\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/RpcStatus\"}}}},\"401\":{\"description\":\"Missing or unknown bearer token\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/RpcStatus\"}}}},\"415\":{\"description\":\"Neither application/json nor application/x-protobuf\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/RpcStatus\"}}}},\"429\":{\"description\":\"Throttled (retried by the SDK), with retry-after\",\"headers\":{\"retry-after\":{\"schema\":{\"type\":\"string\"}}},\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/RpcStatus\"}}}},\"500\":{\"description\":\"Collector error (not retried by the SDK)\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/RpcStatus\"}}}},\"502\":{\"description\":\"Bad gateway (retried)\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/RpcStatus\"}}}},\"503\":{\"description\":\"Unavailable (retried)\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/RpcStatus\"}}}},\"504\":{\"description\":\"Gateway timeout (retried)\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/RpcStatus\"}}}}}}},\"/v1/logs\":{\"post\":{\"operationId\":\"ExportLogs\",\"summary\":\"OTLP/HTTP log export (ExportLogsServiceRequest)\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":false}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ExportLogsServiceRequest\"}},\"application/x-protobuf\":{\"schema\":{\"type\":\"string\",\"format\":\"binary\"}}}},\"responses\":{\"200\":{\"description\":\"Accepted. JSON requests get \\`{partialSuccess: {}}\\`; protobuf requests get an empty protobuf response.\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ExportResponse\"}},\"application/x-protobuf\":{\"schema\":{\"type\":\"string\",\"format\":\"binary\"}}}},\"400\":{\"description\":\"Undecodable payload\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/RpcStatus\"}}}},\"401\":{\"description\":\"Missing or unknown bearer token\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/RpcStatus\"}}}},\"415\":{\"description\":\"Neither application/json nor application/x-protobuf\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/RpcStatus\"}}}},\"429\":{\"description\":\"Throttled (retried by the SDK), with retry-after\",\"headers\":{\"retry-after\":{\"schema\":{\"type\":\"string\"}}},\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/RpcStatus\"}}}},\"500\":{\"description\":\"Collector error (not retried by the SDK)\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/RpcStatus\"}}}},\"502\":{\"description\":\"Bad gateway (retried)\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/RpcStatus\"}}}},\"503\":{\"description\":\"Unavailable (retried)\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/RpcStatus\"}}}},\"504\":{\"description\":\"Gateway timeout (retried)\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/RpcStatus\"}}}}}}},\"/v1/metrics\":{\"post\":{\"operationId\":\"ExportMetrics\",\"summary\":\"OTLP/HTTP metrics export: accepted and counted, never stored\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":false}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ExportMetricsServiceRequest\"}},\"application/x-protobuf\":{\"schema\":{\"type\":\"string\",\"format\":\"binary\"}}}},\"responses\":{\"200\":{\"description\":\"Accepted. JSON requests get \\`{partialSuccess: {}}\\`; protobuf requests get an empty protobuf response.\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ExportResponse\"}},\"application/x-protobuf\":{\"schema\":{\"type\":\"string\",\"format\":\"binary\"}}}},\"400\":{\"description\":\"Undecodable payload\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/RpcStatus\"}}}},\"401\":{\"description\":\"Missing or unknown bearer token\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/RpcStatus\"}}}},\"415\":{\"description\":\"Neither application/json nor application/x-protobuf\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/RpcStatus\"}}}},\"429\":{\"description\":\"Throttled (retried by the SDK), with retry-after\",\"headers\":{\"retry-after\":{\"schema\":{\"type\":\"string\"}}},\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/RpcStatus\"}}}},\"500\":{\"description\":\"Collector error (not retried by the SDK)\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/RpcStatus\"}}}},\"502\":{\"description\":\"Bad gateway (retried)\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/RpcStatus\"}}}},\"503\":{\"description\":\"Unavailable (retried)\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/RpcStatus\"}}}},\"504\":{\"description\":\"Gateway timeout (retried)\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/RpcStatus\"}}}}}}},\"/api/organizations\":{\"get\":{\"operationId\":\"ListOrganizations\",\"summary\":\"O2: the organizations the Basic user belongs to (display name \u2192 identifier)\",\"security\":[{\"basicAuth\":[]}],\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"responses\":{\"200\":{\"description\":\"Organizations\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/Organizations\"}}}},\"401\":{\"description\":\"Bad Basic credentials, or an org the user cannot see \u2014 including an org's display name in place of its identifier\",\"content\":{\"text/plain\":{\"schema\":{\"type\":\"string\"}}}}}}},\"/api/{org}/streams\":{\"parameters\":[{\"name\":\"org\",\"in\":\"path\",\"required\":true,\"description\":\"The org **identifier** (not its display name)\",\"schema\":{\"type\":\"string\",\"x-mockingbird-resource-ref\":{\"type\":\"organization\",\"missing\":\"no-such-org\"}}}],\"get\":{\"operationId\":\"ListStreams\",\"summary\":\"O2: the org's streams of one type\",\"security\":[{\"basicAuth\":[]}],\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"parameters\":[{\"name\":\"type\",\"in\":\"query\",\"required\":false,\"schema\":{\"type\":\"string\",\"enum\":[\"logs\",\"traces\"]}}],\"responses\":{\"200\":{\"description\":\"Streams\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/StreamList\"}}}},\"401\":{\"description\":\"Bad Basic credentials, or an org the user cannot see \u2014 including an org's display name in place of its identifier\",\"content\":{\"text/plain\":{\"schema\":{\"type\":\"string\"}}}}}}},\"/api/{org}/streams/{stream}/schema\":{\"parameters\":[{\"name\":\"org\",\"in\":\"path\",\"required\":true,\"description\":\"The org **identifier** (not its display name)\",\"schema\":{\"type\":\"string\",\"x-mockingbird-resource-ref\":{\"type\":\"organization\",\"missing\":\"no-such-org\"}}},{\"name\":\"stream\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"enum\":[\"default\",\"other\"]}}],\"get\":{\"operationId\":\"GetStreamSchema\",\"summary\":\"O2: a stream's schema (\\`schema[].name\\` are the queryable, lowercased, flattened fields)\",\"security\":[{\"basicAuth\":[]}],\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"parameters\":[{\"name\":\"type\",\"in\":\"query\",\"required\":false,\"schema\":{\"type\":\"string\",\"enum\":[\"logs\",\"traces\"]}}],\"responses\":{\"200\":{\"description\":\"Schema\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/StreamSchema\"}}}},\"401\":{\"description\":\"Bad Basic credentials, or an org the user cannot see \u2014 including an org's display name in place of its identifier\",\"content\":{\"text/plain\":{\"schema\":{\"type\":\"string\"}}}},\"404\":{\"description\":\"Nothing has been ingested into this stream\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/O2Error\"}}}}}}},\"/api/{org}/_search\":{\"parameters\":[{\"name\":\"org\",\"in\":\"path\",\"required\":true,\"description\":\"The org **identifier** (not its display name)\",\"schema\":{\"type\":\"string\",\"x-mockingbird-resource-ref\":{\"type\":\"organization\",\"missing\":\"no-such-org\"}}}],\"post\":{\"operationId\":\"Search\",\"summary\":\"O2: SQL search over a stream\",\"security\":[{\"basicAuth\":[]}],\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"parameters\":[{\"name\":\"type\",\"in\":\"query\",\"required\":false,\"schema\":{\"type\":\"string\",\"enum\":[\"logs\",\"traces\"]}}],\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"type\":\"object\",\"required\":[\"query\"],\"properties\":{\"query\":{\"type\":\"object\",\"required\":[\"sql\"],\"properties\":{\"sql\":{\"anyOf\":[{\"type\":\"string\",\"enum\":[\"SELECT * FROM \\\\\"default\\\\\" WHERE event IS NOT NULL ORDER BY _timestamp DESC\",\"SELECT * FROM \\\\\"default\\\\\" WHERE event IN ('checkout_completed') ORDER BY _timestamp DESC\",\"SELECT service_name, count(*) AS n FROM \\\\\"default\\\\\" GROUP BY service_name ORDER BY n DESC\",\"SELECT * FROM \\\\\"default\\\\\" WHERE severity_text IN ('ERROR', 'FATAL')\",\"SELECT * FROM \\\\\"default\\\\\" WHERE clientUserId = '1'\"]},{\"type\":\"string\",\"maxLength\":200}]},\"start_time\":{\"type\":\"integer\",\"minimum\":0,\"description\":\"\u00B5s since epoch\"},\"end_time\":{\"type\":\"integer\",\"minimum\":0,\"description\":\"\u00B5s since epoch\"},\"from\":{\"type\":\"integer\",\"minimum\":0,\"maximum\":100},\"size\":{\"type\":\"integer\",\"minimum\":-1,\"maximum\":1000}}},\"search_type\":{\"type\":\"string\",\"maxLength\":20}}}}}},\"responses\":{\"200\":{\"description\":\"Hits\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/SearchResponse\"}}}},\"400\":{\"description\":\"Unsupported SQL, or an unknown field (O2 lowercases every field; a camelCase column is unknown)\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/O2Error\"}}}},\"401\":{\"description\":\"Bad Basic credentials, or an org the user cannot see \u2014 including an org's display name in place of its identifier\",\"content\":{\"text/plain\":{\"schema\":{\"type\":\"string\"}}}}}}}},\"components\":{\"securitySchemes\":{\"bearerAuth\":{\"type\":\"http\",\"scheme\":\"bearer\"},\"basicAuth\":{\"type\":\"http\",\"scheme\":\"basic\"}},\"schemas\":{\"KeyValue\":{\"type\":\"object\",\"required\":[\"key\",\"value\"],\"properties\":{\"key\":{\"type\":\"string\",\"enum\":[\"service.name\",\"event\",\"clientUserId\",\"http.method\",\"deployment.environment.name\",\"attempt\"]},\"value\":{\"type\":\"object\",\"properties\":{\"stringValue\":{\"type\":\"string\",\"maxLength\":20},\"intValue\":{\"type\":[\"string\",\"integer\"]},\"boolValue\":{\"type\":\"boolean\"},\"doubleValue\":{\"type\":\"number\"}}}}},\"ExportTraceServiceRequest\":{\"type\":\"object\",\"properties\":{\"resourceSpans\":{\"type\":\"array\",\"maxItems\":2,\"items\":{\"type\":\"object\",\"properties\":{\"resource\":{\"type\":\"object\",\"properties\":{\"attributes\":{\"type\":\"array\",\"maxItems\":4,\"items\":{\"$ref\":\"#/components/schemas/KeyValue\"}}}},\"scopeSpans\":{\"type\":\"array\",\"maxItems\":2,\"items\":{\"type\":\"object\",\"properties\":{\"scope\":{\"type\":\"object\",\"properties\":{\"name\":{\"type\":\"string\",\"maxLength\":20}}},\"spans\":{\"type\":\"array\",\"maxItems\":3,\"items\":{\"type\":\"object\",\"required\":[\"traceId\",\"spanId\",\"name\"],\"properties\":{\"traceId\":{\"type\":\"string\",\"pattern\":\"^[0-9a-f]{32}$\"},\"spanId\":{\"type\":\"string\",\"pattern\":\"^[0-9a-f]{16}$\"},\"parentSpanId\":{\"type\":\"string\",\"pattern\":\"^[0-9a-f]{16}$\"},\"name\":{\"type\":\"string\",\"maxLength\":30},\"kind\":{\"type\":\"integer\",\"minimum\":0,\"maximum\":5},\"startTimeUnixNano\":{\"type\":\"string\",\"pattern\":\"^1[0-9]{18}$\"},\"endTimeUnixNano\":{\"type\":\"string\",\"pattern\":\"^1[0-9]{18}$\"},\"attributes\":{\"type\":\"array\",\"maxItems\":4,\"items\":{\"$ref\":\"#/components/schemas/KeyValue\"}},\"status\":{\"type\":\"object\",\"properties\":{\"code\":{\"type\":\"integer\",\"minimum\":0,\"maximum\":2},\"message\":{\"type\":\"string\",\"maxLength\":40}}}}}}}}}}}}}},\"ExportLogsServiceRequest\":{\"type\":\"object\",\"properties\":{\"resourceLogs\":{\"type\":\"array\",\"maxItems\":2,\"items\":{\"type\":\"object\",\"properties\":{\"resource\":{\"type\":\"object\",\"properties\":{\"attributes\":{\"type\":\"array\",\"maxItems\":4,\"items\":{\"$ref\":\"#/components/schemas/KeyValue\"}}}},\"scopeLogs\":{\"type\":\"array\",\"maxItems\":2,\"items\":{\"type\":\"object\",\"properties\":{\"scope\":{\"type\":\"object\",\"properties\":{\"name\":{\"type\":\"string\",\"maxLength\":20}}},\"logRecords\":{\"type\":\"array\",\"maxItems\":3,\"items\":{\"type\":\"object\",\"properties\":{\"timeUnixNano\":{\"type\":\"string\",\"pattern\":\"^1[0-9]{18}$\"},\"observedTimeUnixNano\":{\"type\":\"string\",\"pattern\":\"^1[0-9]{18}$\"},\"severityNumber\":{\"type\":\"integer\",\"minimum\":0,\"maximum\":24},\"severityText\":{\"type\":\"string\",\"enum\":[\"TRACE\",\"DEBUG\",\"INFO\",\"WARN\",\"ERROR\",\"FATAL\",\"info\",\"error\"]},\"body\":{\"type\":\"object\",\"properties\":{\"stringValue\":{\"type\":\"string\",\"maxLength\":40}}},\"attributes\":{\"type\":\"array\",\"maxItems\":4,\"items\":{\"$ref\":\"#/components/schemas/KeyValue\"}},\"traceId\":{\"type\":\"string\",\"pattern\":\"^[0-9a-f]{32}$\"},\"spanId\":{\"type\":\"string\",\"pattern\":\"^[0-9a-f]{16}$\"}}}}}}}}}}}},\"ExportMetricsServiceRequest\":{\"type\":\"object\",\"properties\":{\"resourceMetrics\":{\"type\":\"array\",\"maxItems\":2,\"items\":{\"type\":\"object\",\"properties\":{\"resource\":{\"type\":\"object\",\"properties\":{\"attributes\":{\"type\":\"array\",\"maxItems\":4,\"items\":{\"$ref\":\"#/components/schemas/KeyValue\"}}}},\"scopeMetrics\":{\"type\":\"array\",\"maxItems\":2,\"items\":{\"type\":\"object\",\"properties\":{\"metrics\":{\"type\":\"array\",\"maxItems\":3,\"items\":{\"type\":\"object\",\"properties\":{\"name\":{\"type\":\"string\",\"maxLength\":30},\"unit\":{\"type\":\"string\",\"maxLength\":10}}}}}}}}}}}},\"ExportResponse\":{\"type\":\"object\",\"required\":[\"partialSuccess\"],\"properties\":{\"partialSuccess\":{\"type\":\"object\",\"properties\":{\"rejectedSpans\":{\"type\":[\"string\",\"integer\"]},\"rejectedLogRecords\":{\"type\":[\"string\",\"integer\"]},\"rejectedDataPoints\":{\"type\":[\"string\",\"integer\"]},\"errorMessage\":{\"type\":\"string\"}}}}},\"RpcStatus\":{\"type\":\"object\",\"required\":[\"code\",\"message\"],\"properties\":{\"code\":{\"type\":\"integer\"},\"message\":{\"type\":\"string\"}}},\"O2Error\":{\"type\":\"object\",\"required\":[\"code\",\"message\"],\"properties\":{\"code\":{\"type\":\"integer\"},\"message\":{\"type\":\"string\"},\"error_detail\":{\"type\":\"string\"}}},\"Organizations\":{\"type\":\"object\",\"required\":[\"data\"],\"properties\":{\"data\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"required\":[\"identifier\",\"name\"],\"properties\":{\"id\":{\"type\":\"integer\"},\"identifier\":{\"type\":\"string\",\"x-mockingbird-resource\":{\"type\":\"organization\",\"identity\":true}},\"name\":{\"type\":\"string\"},\"type\":{\"type\":\"string\"}}}}}},\"StreamList\":{\"type\":\"object\",\"required\":[\"list\"],\"properties\":{\"list\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"required\":[\"name\",\"stream_type\"],\"properties\":{\"name\":{\"type\":\"string\"},\"stream_type\":{\"type\":\"string\"},\"storage_type\":{\"type\":\"string\"},\"stats\":{\"type\":\"object\"}}}}}},\"StreamSchema\":{\"type\":\"object\",\"required\":[\"name\",\"stream_type\",\"schema\"],\"properties\":{\"name\":{\"type\":\"string\"},\"stream_type\":{\"type\":\"string\"},\"storage_type\":{\"type\":\"string\"},\"stats\":{\"type\":\"object\"},\"schema\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"required\":[\"name\",\"type\"],\"properties\":{\"name\":{\"type\":\"string\"},\"type\":{\"type\":\"string\",\"enum\":[\"Utf8\",\"Int64\",\"Float64\",\"Boolean\"]}}}},\"settings\":{\"type\":\"object\"}}},\"SearchResponse\":{\"type\":\"object\",\"required\":[\"took\",\"hits\",\"total\",\"from\",\"size\"],\"properties\":{\"took\":{\"type\":\"integer\",\"x-mockingbird-volatile\":{\"kind\":\"opaque\"}},\"hits\":{\"type\":\"array\",\"items\":{\"type\":\"object\"}},\"total\":{\"type\":\"integer\"},\"from\":{\"type\":\"integer\"},\"size\":{\"type\":\"integer\"},\"scan_size\":{\"type\":\"integer\"},\"scan_records\":{\"type\":\"integer\"},\"is_partial\":{\"type\":\"boolean\"},\"cached_ratio\":{\"type\":\"integer\"}}}}}}`) as OpenAPIDocument\n\nexport type OperationId = \"ExportTraces\" | \"ExportLogs\" | \"ExportMetrics\" | \"ListOrganizations\" | \"ListStreams\" | \"GetStreamSchema\" | \"Search\"\nexport type SupportedOperationId = \"ExportTraces\" | \"ExportLogs\" | \"ExportMetrics\" | \"ListOrganizations\" | \"ListStreams\" | \"GetStreamSchema\" | \"Search\"\nexport const operationIds = [\"ExportTraces\",\"ExportLogs\",\"ExportMetrics\",\"ListOrganizations\",\"ListStreams\",\"GetStreamSchema\",\"Search\"] as const\nexport const supportedOperationIds = [\"ExportTraces\",\"ExportLogs\",\"ExportMetrics\",\"ListOrganizations\",\"ListStreams\",\"GetStreamSchema\",\"Search\"] as const\n", "/**\n * OTLP export requests (JSON, or protobuf decoded to the same shape) \u2192 the flat rows\n * OpenObserve stores. O2 lowercases every field name and flattens it (`http.status_code` \u2192\n * `http_status_code`); resource attributes get a `service_` prefix (`service.version` \u2192\n * `service_service_version`, `deployment.environment.name` \u2192\n * `service_deployment_environment_name`) except `service.name`, which is `service_name`.\n * Null-valued fields are dropped.\n */\n\nexport type Scalar = string | number | boolean\nexport type Row = Record<string, Scalar>\n\ntype Json = Record<string, unknown>\n\nconst isRecord = (value: unknown): value is Json =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\n/** OTLP/JSON is lowerCamelCase; accept the proto snake_case spelling too. */\nconst pick = (object: Json, camel: string): unknown => {\n if (object[camel] !== undefined) return object[camel]\n const snake = camel.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`)\n return object[snake]\n}\n\nconst list = (object: Json, camel: string): Json[] => {\n const value = pick(object, camel)\n return Array.isArray(value) ? value.filter(isRecord) : []\n}\n\n/** O2's field-name normalisation: lowercase, every other character becomes `_`. */\nexport const formatKey = (key: string): string => key.toLowerCase().replace(/[^a-z0-9_]/g, \"_\")\n\n/** Nanoseconds from a decimal string, a number, or protobufjs `{low, high}` long bits. */\nconst nanos = (value: unknown): bigint => {\n try {\n if (typeof value === \"string\" && /^\\d+$/.test(value)) return BigInt(value)\n if (typeof value === \"number\" && Number.isFinite(value)) return BigInt(Math.trunc(value))\n if (isRecord(value) && typeof value.low === \"number\" && typeof value.high === \"number\") {\n return (BigInt(value.high >>> 0) << 32n) | BigInt(value.low >>> 0)\n }\n } catch {\n // Fall through: not a timestamp.\n }\n return 0n\n}\n\n/** Ids are hex in OTLP/JSON; older encoders sent base64, which is converted. */\nconst id = (value: unknown, bytes: number): string | undefined => {\n if (typeof value !== \"string\" || value === \"\") return undefined\n let hex = value.toLowerCase()\n if (!new RegExp(`^[0-9a-f]{${bytes * 2}}$`).test(hex)) {\n try {\n hex = Array.from(atob(value), (c) => c.charCodeAt(0).toString(16).padStart(2, \"0\")).join(\"\")\n } catch {\n return undefined\n }\n }\n return /^0+$/.test(hex) ? undefined : hex\n}\n\ntype Value = Scalar | null | { [key: string]: Value }\n\nconst anyValue = (value: unknown): Value => {\n if (!isRecord(value)) return null\n const string = pick(value, \"stringValue\")\n if (typeof string === \"string\") return string\n const bool = pick(value, \"boolValue\")\n if (typeof bool === \"boolean\") return bool\n const int = pick(value, \"intValue\")\n if (typeof int === \"string\" || typeof int === \"number\") return Number(int)\n const double = pick(value, \"doubleValue\")\n if (typeof double === \"number\") return double\n const bytes = pick(value, \"bytesValue\")\n if (typeof bytes === \"string\") return bytes\n const array = pick(value, \"arrayValue\")\n if (isRecord(array)) {\n return JSON.stringify(list(array, \"values\").map((v) => plain(anyValue(v))))\n }\n const kvlist = pick(value, \"kvlistValue\")\n if (isRecord(kvlist)) {\n const out: { [key: string]: Value } = {}\n for (const kv of list(kvlist, \"values\")) {\n if (typeof kv.key === \"string\") out[kv.key] = anyValue(kv.value)\n }\n return out\n }\n return null\n}\n\nconst plain = (value: Value): unknown =>\n value !== null && typeof value === \"object\"\n ? Object.fromEntries(Object.entries(value).map(([k, v]) => [k, plain(v)]))\n : value\n\n/** Flatten `KeyValue[]` into `row` under O2's names; nested kvlists join with `_`. */\nconst flattenInto = (row: Row, attributes: Json[], prefix = \"\"): void => {\n const put = (key: string, value: Value) => {\n if (value === null) return\n if (typeof value === \"object\") {\n for (const [k, v] of Object.entries(value)) put(`${key}_${formatKey(k)}`, v)\n return\n }\n row[key] = value\n }\n for (const kv of attributes) {\n if (typeof kv.key !== \"string\" || kv.key === \"\") continue\n put(`${prefix}${formatKey(kv.key)}`, anyValue(kv.value))\n }\n}\n\n/** The raw resource attributes (for routing) and their O2 columns. */\nconst resourceColumns = (group: Json): { attributes: Record<string, Scalar>; columns: Row } => {\n const resource = pick(group, \"resource\")\n const kvs = isRecord(resource) ? list(resource, \"attributes\") : []\n const attributes: Record<string, Scalar> = {}\n const columns: Row = {}\n for (const kv of kvs) {\n if (typeof kv.key !== \"string\") continue\n const value = anyValue(kv.value)\n if (value !== null && typeof value !== \"object\") attributes[kv.key] = value\n if (kv.key === \"service.name\") {\n if (value !== null && typeof value !== \"object\") columns.service_name = value\n } else flattenInto(columns, [kv], \"service_\")\n }\n return { attributes, columns }\n}\n\nexport type IngestedRow = {\n /** Raw resource attributes, used to route the row to an org. */\n resource: Record<string, Scalar>\n row: Row\n /** The log had a non-empty body (stored only with `keepBodies`). */\n hadBody: boolean\n}\n\nconst bodyText = (value: Value): string | null => {\n if (value === null) return null\n if (typeof value === \"string\") return value\n if (typeof value === \"object\") return JSON.stringify(plain(value))\n return String(value)\n}\n\n/**\n * `ExportLogsServiceRequest` \u2192 one row per log record. The body is dropped unless\n * `keepBodies` (our logging policy: a body can hold a prompt or PHI; attributes and `event`\n * are what tests assert on).\n */\nexport const logRows = (\n request: Json,\n options: { keepBodies: boolean; nowMs: number },\n): IngestedRow[] => {\n const out: IngestedRow[] = []\n for (const group of list(request, \"resourceLogs\")) {\n const { attributes, columns } = resourceColumns(group)\n for (const scoped of list(group, \"scopeLogs\")) {\n for (const record of list(scoped, \"logRecords\")) {\n const row: Row = { ...columns }\n flattenInto(row, list(record, \"attributes\"))\n const time =\n nanos(pick(record, \"timeUnixNano\")) || nanos(pick(record, \"observedTimeUnixNano\"))\n row._timestamp = time > 0n ? Number(time / 1000n) : options.nowMs * 1000\n const severityText = pick(record, \"severityText\")\n if (typeof severityText === \"string\" && severityText !== \"\") {\n row.severity_text = severityText\n }\n const severityNumber = Number(pick(record, \"severityNumber\") ?? 0)\n if (Number.isFinite(severityNumber) && severityNumber > 0) {\n row.severity_number = severityNumber\n }\n const traceId = id(pick(record, \"traceId\"), 16)\n if (traceId) row.trace_id = traceId\n const spanId = id(pick(record, \"spanId\"), 8)\n if (spanId) row.span_id = spanId\n const eventName = pick(record, \"eventName\")\n if (typeof eventName === \"string\" && eventName !== \"\") row.event_name = eventName\n const body = bodyText(anyValue(pick(record, \"body\")))\n const hadBody = body !== null && body !== \"\"\n if (hadBody && options.keepBodies) row.body = body as string\n out.push({ resource: attributes, row, hadBody })\n }\n }\n }\n return out\n}\n\nconst STATUS = [\"UNSET\", \"OK\", \"ERROR\"] as const\n\n/** `ExportTraceServiceRequest` \u2192 one row per span, in O2's traces-stream columns. */\nexport const spanRows = (request: Json, options: { nowMs: number }): IngestedRow[] => {\n const out: IngestedRow[] = []\n for (const group of list(request, \"resourceSpans\")) {\n const { attributes, columns } = resourceColumns(group)\n for (const scoped of list(group, \"scopeSpans\")) {\n for (const span of list(scoped, \"spans\")) {\n const row: Row = { ...columns }\n flattenInto(row, list(span, \"attributes\"))\n const start = nanos(pick(span, \"startTimeUnixNano\"))\n const end = nanos(pick(span, \"endTimeUnixNano\"))\n const startNs = start > 0n ? start : BigInt(options.nowMs) * 1_000_000n\n const endNs = end > 0n ? end : startNs\n row.start_time = Number(startNs)\n row.end_time = Number(endNs)\n row.duration = Number((endNs - startNs) / 1000n)\n row._timestamp = Number(startNs / 1000n)\n const traceId = id(pick(span, \"traceId\"), 16)\n if (traceId) row.trace_id = traceId\n const spanId = id(pick(span, \"spanId\"), 8)\n if (spanId) row.span_id = spanId\n const parent = id(pick(span, \"parentSpanId\"), 8)\n if (parent) {\n row.reference_parent_span_id = parent\n row.reference_ref_type = \"ChildOf\"\n }\n const name = pick(span, \"name\")\n if (typeof name === \"string\") row.operation_name = name\n row.span_kind = String(Number(pick(span, \"kind\") ?? 0))\n const status = pick(span, \"status\")\n const code = isRecord(status) ? Number(pick(status, \"code\") ?? 0) : 0\n row.span_status = STATUS[code] ?? \"UNSET\"\n const events = list(span, \"events\").map((event) => {\n const flat: Row = {}\n flattenInto(flat, list(event, \"attributes\"))\n return {\n name: typeof event.name === \"string\" ? event.name : \"\",\n _timestamp: Number(nanos(pick(event, \"timeUnixNano\")) / 1000n),\n ...flat,\n }\n })\n row.events = JSON.stringify(events)\n const scope = pick(scoped, \"scope\")\n if (isRecord(scope) && typeof scope.name === \"string\" && scope.name !== \"\") {\n row.instrumentation_library_name = scope.name\n }\n out.push({ resource: attributes, row, hadBody: false })\n }\n }\n }\n return out\n}\n\n/** How many metric streams an OTLP/JSON metrics export carries (counted, never stored). */\nexport const metricCount = (request: Json): number =>\n list(request, \"resourceMetrics\").reduce(\n (total, group) =>\n total +\n list(group, \"scopeMetrics\").reduce((sum, scoped) => sum + list(scoped, \"metrics\").length, 0),\n 0,\n )\n", "/**\n * A minimal protobuf wire-format decoder for the two OTLP export requests the receiver accepts\n * as `application/x-protobuf` (`ExportTraceServiceRequest`, `ExportLogsServiceRequest`). It\n * decodes only the fields the store keeps and skips the rest, and produces the same shape as\n * OTLP/JSON (lowerCamelCase keys, hex ids, 64-bit integers as decimal strings), so one\n * normaliser handles both encodings. No dependencies.\n *\n * Field numbers follow opentelemetry-proto v1 (`common.proto`, `resource.proto`,\n * `trace.proto`, `logs.proto`).\n */\n\nexport class ProtobufError extends Error {\n constructor(message: string) {\n super(`invalid protobuf: ${message}`)\n this.name = \"ProtobufError\"\n }\n}\n\ntype Json = Record<string, unknown>\n\nconst utf8 = new TextDecoder(\"utf-8\", { fatal: false })\n\nclass Reader {\n pos = 0\n constructor(private readonly buf: Uint8Array) {}\n\n get done(): boolean {\n return this.pos >= this.buf.length\n }\n\n varint(): bigint {\n let result = 0n\n let shift = 0n\n for (let i = 0; i < 10; i++) {\n if (this.pos >= this.buf.length) throw new ProtobufError(\"truncated varint\")\n const byte = this.buf[this.pos++] as number\n result |= BigInt(byte & 0x7f) << shift\n if ((byte & 0x80) === 0) return result\n shift += 7n\n }\n throw new ProtobufError(\"varint longer than 10 bytes\")\n }\n\n fixed64(): bigint {\n const bytes = this.take(8)\n let result = 0n\n for (let i = 7; i >= 0; i--) result = (result << 8n) | BigInt(bytes[i] as number)\n return result\n }\n\n fixed32(): number {\n const bytes = this.take(4)\n return new DataView(bytes.buffer, bytes.byteOffset, 4).getUint32(0, true)\n }\n\n double(): number {\n const bytes = this.take(8)\n return new DataView(bytes.buffer, bytes.byteOffset, 8).getFloat64(0, true)\n }\n\n bytes(): Uint8Array {\n return this.take(Number(this.varint()))\n }\n\n take(length: number): Uint8Array {\n if (length < 0 || this.pos + length > this.buf.length) {\n throw new ProtobufError(\"length-delimited field runs past the end\")\n }\n const out = this.buf.subarray(this.pos, this.pos + length)\n this.pos += length\n return out\n }\n\n skip(wireType: number): void {\n if (wireType === 0) this.varint()\n else if (wireType === 1) this.take(8)\n else if (wireType === 2) this.bytes()\n else if (wireType === 5) this.take(4)\n else throw new ProtobufError(`unsupported wire type ${wireType}`)\n }\n}\n\ntype FieldHandler = (field: number, wireType: number, reader: Reader) => boolean\n\n/** Walk a message's fields; the handler returns false for fields it does not read. */\nconst walk = (bytes: Uint8Array, handler: FieldHandler): void => {\n const reader = new Reader(bytes)\n while (!reader.done) {\n const key = Number(reader.varint())\n const field = key >>> 3\n const wireType = key & 7\n if (field === 0) throw new ProtobufError(\"field number 0\")\n if (!handler(field, wireType, reader)) reader.skip(wireType)\n }\n}\n\nconst hex = (bytes: Uint8Array): string =>\n Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\")\n\nconst base64 = (bytes: Uint8Array): string => {\n let binary = \"\"\n for (const byte of bytes) binary += String.fromCharCode(byte)\n return btoa(binary)\n}\n\n/** Two's-complement int64 from a varint. */\nconst int64 = (value: bigint): string => BigInt.asIntN(64, value).toString()\n\nconst decodeAnyValue = (bytes: Uint8Array): Json => {\n let out: Json = {}\n walk(bytes, (field, wire, r) => {\n if (field === 1 && wire === 2) out = { stringValue: utf8.decode(r.bytes()) }\n else if (field === 2 && wire === 0) out = { boolValue: r.varint() !== 0n }\n else if (field === 3 && wire === 0) out = { intValue: int64(r.varint()) }\n else if (field === 4 && wire === 1) out = { doubleValue: r.double() }\n else if (field === 5 && wire === 2) out = { arrayValue: { values: decodeValues(r.bytes()) } }\n else if (field === 6 && wire === 2) {\n out = { kvlistValue: { values: decodeKeyValues(r.bytes()) } }\n } else if (field === 7 && wire === 2) out = { bytesValue: base64(r.bytes()) }\n else return false\n return true\n })\n return out\n}\n\n/** `ArrayValue { repeated AnyValue values = 1 }`. */\nconst decodeValues = (bytes: Uint8Array): Json[] => {\n const values: Json[] = []\n walk(bytes, (field, wire, r) => {\n if (field !== 1 || wire !== 2) return false\n values.push(decodeAnyValue(r.bytes()))\n return true\n })\n return values\n}\n\n/** `KeyValueList { repeated KeyValue values = 1 }`. */\nconst decodeKeyValues = (bytes: Uint8Array): Json[] => {\n const values: Json[] = []\n walk(bytes, (field, wire, r) => {\n if (field !== 1 || wire !== 2) return false\n values.push(decodeKeyValue(r.bytes()))\n return true\n })\n return values\n}\n\nconst decodeKeyValue = (bytes: Uint8Array): Json => {\n const kv: Json = { key: \"\" }\n walk(bytes, (field, wire, r) => {\n if (field === 1 && wire === 2) kv.key = utf8.decode(r.bytes())\n else if (field === 2 && wire === 2) kv.value = decodeAnyValue(r.bytes())\n else return false\n return true\n })\n return kv\n}\n\n/** `Resource { repeated KeyValue attributes = 1 }`. */\nconst decodeResource = (bytes: Uint8Array): Json => {\n const attributes: Json[] = []\n walk(bytes, (field, wire, r) => {\n if (field !== 1 || wire !== 2) return false\n attributes.push(decodeKeyValue(r.bytes()))\n return true\n })\n return { attributes }\n}\n\n/** `InstrumentationScope { string name = 1; string version = 2 }`. */\nconst decodeScope = (bytes: Uint8Array): Json => {\n const scope: Json = {}\n walk(bytes, (field, wire, r) => {\n if (field === 1 && wire === 2) scope.name = utf8.decode(r.bytes())\n else if (field === 2 && wire === 2) scope.version = utf8.decode(r.bytes())\n else return false\n return true\n })\n return scope\n}\n\nconst decodeEvent = (bytes: Uint8Array): Json => {\n const event: Json = { attributes: [] }\n walk(bytes, (field, wire, r) => {\n if (field === 1 && wire === 1) event.timeUnixNano = r.fixed64().toString()\n else if (field === 2 && wire === 2) event.name = utf8.decode(r.bytes())\n else if (field === 3 && wire === 2) {\n ;(event.attributes as Json[]).push(decodeKeyValue(r.bytes()))\n } else return false\n return true\n })\n return event\n}\n\nconst decodeStatus = (bytes: Uint8Array): Json => {\n const status: Json = {}\n walk(bytes, (field, wire, r) => {\n if (field === 2 && wire === 2) status.message = utf8.decode(r.bytes())\n else if (field === 3 && wire === 0) status.code = Number(r.varint())\n else return false\n return true\n })\n return status\n}\n\nconst decodeSpan = (bytes: Uint8Array): Json => {\n const span: Json = { attributes: [], events: [] }\n walk(bytes, (field, wire, r) => {\n if (field === 1 && wire === 2) span.traceId = hex(r.bytes())\n else if (field === 2 && wire === 2) span.spanId = hex(r.bytes())\n else if (field === 3 && wire === 2) span.traceState = utf8.decode(r.bytes())\n else if (field === 4 && wire === 2) span.parentSpanId = hex(r.bytes())\n else if (field === 5 && wire === 2) span.name = utf8.decode(r.bytes())\n else if (field === 6 && wire === 0) span.kind = Number(r.varint())\n else if (field === 7 && wire === 1) span.startTimeUnixNano = r.fixed64().toString()\n else if (field === 8 && wire === 1) span.endTimeUnixNano = r.fixed64().toString()\n else if (field === 9 && wire === 2) {\n ;(span.attributes as Json[]).push(decodeKeyValue(r.bytes()))\n } else if (field === 11 && wire === 2) (span.events as Json[]).push(decodeEvent(r.bytes()))\n else if (field === 15 && wire === 2) span.status = decodeStatus(r.bytes())\n else if (field === 16 && wire === 5) span.flags = r.fixed32()\n else return false\n return true\n })\n return span\n}\n\nconst decodeLogRecord = (bytes: Uint8Array): Json => {\n const log: Json = { attributes: [] }\n walk(bytes, (field, wire, r) => {\n if (field === 1 && wire === 1) log.timeUnixNano = r.fixed64().toString()\n else if (field === 2 && wire === 0) log.severityNumber = Number(r.varint())\n else if (field === 3 && wire === 2) log.severityText = utf8.decode(r.bytes())\n else if (field === 5 && wire === 2) log.body = decodeAnyValue(r.bytes())\n else if (field === 6 && wire === 2) {\n ;(log.attributes as Json[]).push(decodeKeyValue(r.bytes()))\n } else if (field === 8 && wire === 5) log.flags = r.fixed32()\n else if (field === 9 && wire === 2) log.traceId = hex(r.bytes())\n else if (field === 10 && wire === 2) log.spanId = hex(r.bytes())\n else if (field === 11 && wire === 1) log.observedTimeUnixNano = r.fixed64().toString()\n else if (field === 12 && wire === 2) log.eventName = utf8.decode(r.bytes())\n else return false\n return true\n })\n return log\n}\n\n/**\n * `{resource, scope<Kind>s: [{scope, <items>}]}`: the one nesting shape traces and logs share\n * (`ResourceSpans`/`ScopeSpans`, `ResourceLogs`/`ScopeLogs`).\n */\nconst decodeResourceGroup = (\n bytes: Uint8Array,\n scopeKey: string,\n itemsKey: string,\n decodeItem: (bytes: Uint8Array) => Json,\n): Json => {\n const group: Json = { [scopeKey]: [] }\n walk(bytes, (field, wire, r) => {\n if (field === 1 && wire === 2) group.resource = decodeResource(r.bytes())\n else if (field === 2 && wire === 2) {\n const scoped: Json = { [itemsKey]: [] }\n walk(r.bytes(), (f, w, inner) => {\n if (f === 1 && w === 2) scoped.scope = decodeScope(inner.bytes())\n else if (f === 2 && w === 2) (scoped[itemsKey] as Json[]).push(decodeItem(inner.bytes()))\n else return false\n return true\n })\n ;(group[scopeKey] as Json[]).push(scoped)\n } else return false\n return true\n })\n return group\n}\n\n/** `ExportTraceServiceRequest` \u2192 OTLP/JSON `{resourceSpans: [...]}`. */\nexport const decodeTraceRequest = (bytes: Uint8Array): { resourceSpans: Json[] } => {\n const resourceSpans: Json[] = []\n walk(bytes, (field, wire, r) => {\n if (field !== 1 || wire !== 2) return false\n resourceSpans.push(decodeResourceGroup(r.bytes(), \"scopeSpans\", \"spans\", decodeSpan))\n return true\n })\n return { resourceSpans }\n}\n\n/** `ExportLogsServiceRequest` \u2192 OTLP/JSON `{resourceLogs: [...]}`. */\nexport const decodeLogsRequest = (bytes: Uint8Array): { resourceLogs: Json[] } => {\n const resourceLogs: Json[] = []\n walk(bytes, (field, wire, r) => {\n if (field !== 1 || wire !== 2) return false\n resourceLogs.push(decodeResourceGroup(r.bytes(), \"scopeLogs\", \"logRecords\", decodeLogRecord))\n return true\n })\n return { resourceLogs }\n}\n\n/** Count `ResourceMetrics` entries in an `ExportMetricsServiceRequest` without decoding them. */\nexport const countMetricsRequest = (bytes: Uint8Array): number => {\n let count = 0\n walk(bytes, (field, wire, r) => {\n if (field !== 1 || wire !== 2) return false\n r.bytes()\n count++\n return true\n })\n return count\n}\n", "/**\n * The subset of OpenObserve's SQL our clients send to `POST /api/{org}/_search`:\n *\n * SELECT * | <expr> [AS alias], \u2026 FROM \"<stream>\"\n * [WHERE <predicate>] [GROUP BY <expr>, \u2026] [HAVING <predicate>]\n * [ORDER BY <expr> [ASC|DESC], \u2026] [LIMIT n [OFFSET m]]\n *\n * Predicates: `AND`/`OR`/`NOT`, parentheses, `=`, `!=`/`<>`, `<`, `<=`, `>`, `>=`,\n * `IS [NOT] NULL`, `[NOT] IN (\u2026)`, `[NOT] LIKE`/`ILIKE`, `[NOT] BETWEEN \u2026 AND \u2026`.\n * Functions: `str_match`, `str_match_ignore_case`, `match_all`, `re_match`, `lower`, `upper`,\n * `tostring`, `length`, `coalesce`, and the aggregates `count(*)`, `count([DISTINCT] x)`,\n * `min`, `max`, `sum`, `avg`.\n *\n * Column names are matched exactly (O2 stores them lowercased, so `clientUserId` is an unknown\n * field); a column the stream's schema has never seen is a 400, as on the real server.\n */\nimport type { Row, Scalar } from \"./otlp.js\"\n\nexport class SqlError extends Error {\n constructor(\n message: string,\n readonly kind: \"syntax\" | \"unknown_field\" = \"syntax\",\n ) {\n super(message)\n this.name = \"SqlError\"\n }\n}\n\ntype Token =\n | { t: \"ident\"; v: string; quoted: boolean }\n | { t: \"str\"; v: string }\n | { t: \"num\"; v: number }\n | { t: \"op\"; v: string }\n\nconst tokenize = (sql: string): Token[] => {\n const tokens: Token[] = []\n let i = 0\n while (i < sql.length) {\n const c = sql[i] as string\n if (/\\s/.test(c)) {\n i++\n continue\n }\n if (c === \"-\" && sql[i + 1] === \"-\") {\n while (i < sql.length && sql[i] !== \"\\n\") i++\n continue\n }\n if (c === \"'\") {\n let value = \"\"\n i++\n for (;;) {\n if (i >= sql.length) throw new SqlError(\"unterminated string literal\")\n if (sql[i] === \"'\") {\n if (sql[i + 1] === \"'\") {\n value += \"'\"\n i += 2\n continue\n }\n i++\n break\n }\n value += sql[i++]\n }\n tokens.push({ t: \"str\", v: value })\n continue\n }\n if (c === '\"') {\n const end = sql.indexOf('\"', i + 1)\n if (end < 0) throw new SqlError(\"unterminated quoted identifier\")\n tokens.push({ t: \"ident\", v: sql.slice(i + 1, end), quoted: true })\n i = end + 1\n continue\n }\n const number = /^\\d+(\\.\\d+)?/.exec(sql.slice(i))\n if (number) {\n tokens.push({ t: \"num\", v: Number(number[0]) })\n i += number[0].length\n continue\n }\n const word = /^[A-Za-z_][A-Za-z0-9_]*/.exec(sql.slice(i))\n if (word) {\n tokens.push({ t: \"ident\", v: word[0], quoted: false })\n i += word[0].length\n continue\n }\n const op = /^(<=|>=|<>|!=|=|<|>|\\(|\\)|,|\\*|;|\\+|-)/.exec(sql.slice(i))\n if (op) {\n tokens.push({ t: \"op\", v: op[0] })\n i += op[0].length\n continue\n }\n throw new SqlError(`unexpected character ${JSON.stringify(c)}`)\n }\n return tokens\n}\n\nexport type Expr =\n | { k: \"lit\"; v: Scalar | null }\n | { k: \"col\"; name: string }\n | { k: \"star\" }\n | { k: \"fn\"; name: string; args: Expr[]; distinct: boolean }\n | { k: \"not\"; e: Expr }\n | { k: \"and\" | \"or\"; l: Expr; r: Expr }\n | { k: \"cmp\"; op: string; l: Expr; r: Expr }\n | { k: \"null\"; e: Expr; not: boolean }\n | { k: \"in\"; e: Expr; list: Expr[]; not: boolean }\n | { k: \"like\"; e: Expr; pattern: Expr; not: boolean; ci: boolean }\n | { k: \"between\"; e: Expr; lo: Expr; hi: Expr; not: boolean }\n\nexport type SelectItem = { expr: Expr; alias: string | undefined; text: string }\n\nexport type Query = {\n star: boolean\n items: SelectItem[]\n stream: string\n where: Expr | undefined\n groupBy: Expr[]\n having: Expr | undefined\n orderBy: { expr: Expr; desc: boolean }[]\n limit: number | undefined\n offset: number\n}\n\nconst KEYWORDS = new Set([\n \"select\",\n \"from\",\n \"where\",\n \"group\",\n \"by\",\n \"having\",\n \"order\",\n \"limit\",\n \"offset\",\n \"and\",\n \"or\",\n \"not\",\n \"is\",\n \"null\",\n \"in\",\n \"like\",\n \"ilike\",\n \"between\",\n \"as\",\n \"asc\",\n \"desc\",\n \"distinct\",\n \"true\",\n \"false\",\n])\n\nconst AGGREGATES = new Set([\"count\", \"min\", \"max\", \"sum\", \"avg\"])\nconst FUNCTIONS = new Set([\n ...AGGREGATES,\n \"str_match\",\n \"str_match_ignore_case\",\n \"match_all\",\n \"match_all_ignore_case\",\n \"re_match\",\n \"lower\",\n \"upper\",\n \"tostring\",\n \"length\",\n \"coalesce\",\n])\n\nclass Parser {\n private pos = 0\n constructor(private readonly tokens: Token[]) {}\n\n private peek(offset = 0): Token | undefined {\n return this.tokens[this.pos + offset]\n }\n\n private isKeyword(word: string, offset = 0): boolean {\n const token = this.peek(offset)\n return token?.t === \"ident\" && !token.quoted && token.v.toLowerCase() === word\n }\n\n private isOp(op: string): boolean {\n const token = this.peek()\n return token?.t === \"op\" && token.v === op\n }\n\n private keyword(word: string): void {\n if (!this.isKeyword(word)) throw new SqlError(`expected ${word.toUpperCase()}`)\n this.pos++\n }\n\n private op(op: string): void {\n if (!this.isOp(op)) throw new SqlError(`expected ${op}`)\n this.pos++\n }\n\n private accept(word: string): boolean {\n if (!this.isKeyword(word)) return false\n this.pos++\n return true\n }\n\n parse(): Query {\n this.keyword(\"select\")\n this.accept(\"distinct\")\n let star = false\n const items: SelectItem[] = []\n do {\n if (this.isOp(\"*\")) {\n this.pos++\n star = true\n continue\n }\n const start = this.pos\n const expr = this.expr()\n const end = this.pos\n let alias: string | undefined\n if (this.accept(\"as\")) alias = this.identifier()\n else {\n const next = this.peek()\n if (next?.t === \"ident\" && (next.quoted || !KEYWORDS.has(next.v.toLowerCase()))) {\n alias = this.identifier()\n }\n }\n items.push({ expr, alias, text: this.text(start, end) })\n } while (this.isOp(\",\") && ++this.pos)\n this.keyword(\"from\")\n const stream = this.identifier()\n let where: Expr | undefined\n if (this.accept(\"where\")) where = this.expr()\n const groupBy: Expr[] = []\n if (this.accept(\"group\")) {\n this.keyword(\"by\")\n do groupBy.push(this.expr())\n while (this.isOp(\",\") && ++this.pos)\n }\n let having: Expr | undefined\n if (this.accept(\"having\")) having = this.expr()\n const orderBy: { expr: Expr; desc: boolean }[] = []\n if (this.accept(\"order\")) {\n this.keyword(\"by\")\n do {\n const expr = this.expr()\n const desc = this.accept(\"desc\")\n if (!desc) this.accept(\"asc\")\n orderBy.push({ expr, desc })\n } while (this.isOp(\",\") && ++this.pos)\n }\n let limit: number | undefined\n let offset = 0\n if (this.accept(\"limit\")) limit = this.integer()\n if (this.accept(\"offset\")) offset = this.integer()\n if (this.isOp(\";\")) this.pos++\n if (this.pos < this.tokens.length) throw new SqlError(\"unexpected tokens after the query\")\n return { star, items, stream, where, groupBy, having, orderBy, limit, offset }\n }\n\n private text(from: number, to: number): string {\n return this.tokens\n .slice(from, to)\n .map((t) => (t.t === \"str\" ? `'${t.v}'` : String(t.v)))\n .join(\"\")\n .toLowerCase()\n }\n\n private integer(): number {\n const token = this.peek()\n if (token?.t !== \"num\" || !Number.isInteger(token.v)) throw new SqlError(\"expected an integer\")\n this.pos++\n return token.v\n }\n\n private identifier(): string {\n const token = this.peek()\n if (token?.t !== \"ident\") throw new SqlError(\"expected an identifier\")\n this.pos++\n return token.v\n }\n\n private expr(): Expr {\n let left = this.and()\n while (this.accept(\"or\")) left = { k: \"or\", l: left, r: this.and() }\n return left\n }\n\n private and(): Expr {\n let left = this.not()\n while (this.accept(\"and\")) left = { k: \"and\", l: left, r: this.not() }\n return left\n }\n\n private not(): Expr {\n if (this.accept(\"not\")) return { k: \"not\", e: this.not() }\n return this.predicate()\n }\n\n private predicate(): Expr {\n const e = this.primary()\n if (this.accept(\"is\")) {\n const not = this.accept(\"not\")\n this.keyword(\"null\")\n return { k: \"null\", e, not }\n }\n const not =\n this.isKeyword(\"not\") &&\n (this.isKeyword(\"in\", 1) ||\n this.isKeyword(\"like\", 1) ||\n this.isKeyword(\"ilike\", 1) ||\n this.isKeyword(\"between\", 1))\n if (not) this.pos++\n if (this.accept(\"in\")) {\n this.op(\"(\")\n const list: Expr[] = []\n do list.push(this.primary())\n while (this.isOp(\",\") && ++this.pos)\n this.op(\")\")\n return { k: \"in\", e, list, not }\n }\n if (this.isKeyword(\"like\") || this.isKeyword(\"ilike\")) {\n const ci = this.isKeyword(\"ilike\")\n this.pos++\n return { k: \"like\", e, pattern: this.primary(), not, ci }\n }\n if (this.accept(\"between\")) {\n const lo = this.primary()\n this.keyword(\"and\")\n return { k: \"between\", e, lo, hi: this.primary(), not }\n }\n if (not) throw new SqlError(\"expected IN, LIKE or BETWEEN after NOT\")\n const token = this.peek()\n if (token?.t === \"op\" && [\"=\", \"!=\", \"<>\", \"<\", \"<=\", \">\", \">=\"].includes(token.v)) {\n this.pos++\n return { k: \"cmp\", op: token.v === \"<>\" ? \"!=\" : token.v, l: e, r: this.primary() }\n }\n return e\n }\n\n private primary(): Expr {\n const token = this.peek()\n if (!token) throw new SqlError(\"unexpected end of query\")\n if (token.t === \"str\") {\n this.pos++\n return { k: \"lit\", v: token.v }\n }\n if (token.t === \"num\") {\n this.pos++\n return { k: \"lit\", v: token.v }\n }\n if (token.t === \"op\" && token.v === \"-\") {\n this.pos++\n const next = this.peek()\n if (next?.t !== \"num\") throw new SqlError(\"expected a number after -\")\n this.pos++\n return { k: \"lit\", v: -next.v }\n }\n if (token.t === \"op\" && token.v === \"(\") {\n this.pos++\n const inner = this.expr()\n this.op(\")\")\n return inner\n }\n if (token.t === \"op\" && token.v === \"*\") {\n this.pos++\n return { k: \"star\" }\n }\n if (token.t === \"ident\") {\n this.pos++\n if (!token.quoted) {\n const lower = token.v.toLowerCase()\n if (lower === \"null\") return { k: \"lit\", v: null }\n if (lower === \"true\" || lower === \"false\") return { k: \"lit\", v: lower === \"true\" }\n if (this.isOp(\"(\")) {\n if (!FUNCTIONS.has(lower)) throw new SqlError(`unsupported function ${token.v}`)\n this.pos++\n const distinct = this.accept(\"distinct\")\n const args: Expr[] = []\n if (!this.isOp(\")\")) {\n do args.push(this.expr())\n while (this.isOp(\",\") && ++this.pos)\n }\n this.op(\")\")\n return { k: \"fn\", name: lower, args, distinct }\n }\n if (KEYWORDS.has(lower)) throw new SqlError(`unexpected keyword ${token.v.toUpperCase()}`)\n }\n return { k: \"col\", name: token.v }\n }\n throw new SqlError(`unexpected ${token.v}`)\n }\n}\n\nexport const parseSql = (sql: string): Query => new Parser(tokenize(sql)).parse()\n\n/** Every column a query reads, minus select aliases (which ORDER BY / HAVING may name). */\nexport const referencedColumns = (query: Query): string[] => {\n const aliases = new Set(query.items.map((i) => i.alias).filter(Boolean) as string[])\n const out = new Set<string>()\n const visit = (e: Expr | undefined, aliasOk: boolean) => {\n if (!e) return\n switch (e.k) {\n case \"col\":\n if (!(aliasOk && aliases.has(e.name))) out.add(e.name)\n return\n case \"fn\":\n for (const a of e.args) visit(a, aliasOk)\n return\n case \"not\":\n case \"null\":\n visit(e.e, aliasOk)\n return\n case \"and\":\n case \"or\":\n case \"cmp\":\n visit(e.l, aliasOk)\n visit(e.r, aliasOk)\n return\n case \"in\":\n visit(e.e, aliasOk)\n for (const x of e.list) visit(x, aliasOk)\n return\n case \"like\":\n visit(e.e, aliasOk)\n visit(e.pattern, aliasOk)\n return\n case \"between\":\n visit(e.e, aliasOk)\n visit(e.lo, aliasOk)\n visit(e.hi, aliasOk)\n return\n default:\n return\n }\n }\n for (const item of query.items) visit(item.expr, false)\n visit(query.where, false)\n for (const g of query.groupBy) visit(g, true)\n visit(query.having, true)\n for (const o of query.orderBy) visit(o.expr, true)\n return [...out]\n}\n\ntype Value = Scalar | null\n\nconst hasAggregate = (e: Expr): boolean => {\n switch (e.k) {\n case \"fn\":\n return AGGREGATES.has(e.name) || e.args.some(hasAggregate)\n case \"not\":\n case \"null\":\n return hasAggregate(e.e)\n case \"and\":\n case \"or\":\n case \"cmp\":\n return hasAggregate(e.l) || hasAggregate(e.r)\n default:\n return false\n }\n}\n\n/** A string that reads as a date, compared against a \u00B5s timestamp column. */\nconst asMicros = (value: string): number | undefined => {\n if (/^\\d+(\\.\\d+)?$/.test(value)) return Number(value)\n const ms = Date.parse(value)\n return Number.isNaN(ms) ? undefined : ms * 1000\n}\n\nconst compare = (a: Value, b: Value): number | null => {\n if (a === null || b === null) return null\n if (typeof a === \"number\" && typeof b === \"string\") {\n const n = asMicros(b)\n return n === undefined ? String(a).localeCompare(b) : a - n\n }\n if (typeof a === \"string\" && typeof b === \"number\") {\n const n = asMicros(a)\n return n === undefined ? a.localeCompare(String(b)) : n - b\n }\n if (typeof a === \"number\" && typeof b === \"number\") return a - b\n if (typeof a === \"boolean\" || typeof b === \"boolean\") return String(a) === String(b) ? 0 : 1\n return a < b ? -1 : a > b ? 1 : 0\n}\n\nconst likeRegex = (pattern: string, ci: boolean) =>\n new RegExp(\n `^${pattern\n .replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(/%/g, \".*\")\n .replace(/_/g, \".\")}$`,\n ci ? \"is\" : \"s\",\n )\n\nconst text = (v: Value): string | null => (v === null ? null : String(v))\n\ntype Context = { row: Row; group?: Row[]; aliases?: Record<string, Value> }\n\nconst truthy = (v: Value): boolean => v === true\n\nexport const evaluate = (e: Expr, ctx: Context): Value => {\n switch (e.k) {\n case \"lit\":\n return e.v\n case \"col\":\n if (ctx.aliases && e.name in ctx.aliases) return ctx.aliases[e.name] ?? null\n return ctx.row[e.name] ?? null\n case \"star\":\n return null\n case \"not\": {\n const v = evaluate(e.e, ctx)\n return v === null ? null : !truthy(v)\n }\n case \"and\": {\n const l = evaluate(e.l, ctx)\n if (l === false) return false\n const r = evaluate(e.r, ctx)\n if (r === false) return false\n return l === null || r === null ? null : truthy(l) && truthy(r)\n }\n case \"or\": {\n const l = evaluate(e.l, ctx)\n if (truthy(l)) return true\n const r = evaluate(e.r, ctx)\n if (truthy(r)) return true\n return l === null || r === null ? null : false\n }\n case \"cmp\": {\n const c = compare(evaluate(e.l, ctx), evaluate(e.r, ctx))\n if (c === null) return null\n switch (e.op) {\n case \"=\":\n return c === 0\n case \"!=\":\n return c !== 0\n case \"<\":\n return c < 0\n case \"<=\":\n return c <= 0\n case \">\":\n return c > 0\n default:\n return c >= 0\n }\n }\n case \"null\": {\n const isNull = evaluate(e.e, ctx) === null\n return e.not ? !isNull : isNull\n }\n case \"in\": {\n const v = evaluate(e.e, ctx)\n if (v === null) return null\n const found = e.list.some((x) => compare(v, evaluate(x, ctx)) === 0)\n return e.not ? !found : found\n }\n case \"like\": {\n const v = text(evaluate(e.e, ctx))\n const p = text(evaluate(e.pattern, ctx))\n if (v === null || p === null) return null\n const matched = likeRegex(p, e.ci).test(v)\n return e.not ? !matched : matched\n }\n case \"between\": {\n const v = evaluate(e.e, ctx)\n const lo = compare(v, evaluate(e.lo, ctx))\n const hi = compare(v, evaluate(e.hi, ctx))\n if (lo === null || hi === null) return null\n const inside = lo >= 0 && hi <= 0\n return e.not ? !inside : inside\n }\n case \"fn\":\n return call(e, ctx)\n }\n}\n\nconst call = (e: Extract<Expr, { k: \"fn\" }>, ctx: Context): Value => {\n if (AGGREGATES.has(e.name)) {\n const rows = ctx.group ?? [ctx.row]\n const arg = e.args[0]\n if (e.name === \"count\") {\n if (!arg || arg.k === \"star\") return rows.length\n const values = rows.map((row) => evaluate(arg, { row })).filter((v) => v !== null)\n return e.distinct ? new Set(values.map((v) => JSON.stringify(v))).size : values.length\n }\n if (!arg) throw new SqlError(`${e.name}() needs an argument`)\n const values = rows.map((row) => evaluate(arg, { row })).filter((v) => v !== null)\n if (values.length === 0) return null\n if (e.name === \"min\" || e.name === \"max\") {\n return values.reduce((best, v) => {\n const c = compare(v, best) ?? 0\n return (e.name === \"min\" ? c < 0 : c > 0) ? v : best\n })\n }\n const numbers = values.map(Number).filter((n) => Number.isFinite(n))\n const sum = numbers.reduce((a, b) => a + b, 0)\n return e.name === \"sum\" ? sum : numbers.length === 0 ? null : sum / numbers.length\n }\n const args = e.args.map((a) => evaluate(a, ctx))\n const [a, b] = args\n switch (e.name) {\n case \"str_match\":\n return a === null || b === null ? false : String(a).includes(String(b))\n case \"str_match_ignore_case\":\n return a === null || b === null\n ? false\n : String(a).toLowerCase().includes(String(b).toLowerCase())\n case \"match_all\":\n case \"match_all_ignore_case\": {\n if (a === null) return false\n const needle = String(a).toLowerCase()\n return Object.values(ctx.row).some(\n (v) => typeof v === \"string\" && v.toLowerCase().includes(needle),\n )\n }\n case \"re_match\":\n if (a === null || b === null) return false\n try {\n return new RegExp(String(b)).test(String(a))\n } catch {\n throw new SqlError(`invalid regular expression ${String(b)}`)\n }\n case \"lower\":\n return a === null || a === undefined ? null : String(a).toLowerCase()\n case \"upper\":\n return a === null || a === undefined ? null : String(a).toUpperCase()\n case \"tostring\":\n return a === null || a === undefined ? null : String(a)\n case \"length\":\n return a === null || a === undefined ? null : [...String(a)].length\n case \"coalesce\":\n return args.find((v) => v !== null) ?? null\n default:\n throw new SqlError(`unsupported function ${e.name}`)\n }\n}\n\nconst columnName = (item: SelectItem): string =>\n item.alias ?? (item.expr.k === \"col\" ? item.expr.name : item.text)\n\nconst project = (query: Query, ctx: Context): Record<string, Value> => {\n const out: Record<string, Value> = {}\n if (query.star) Object.assign(out, ctx.row)\n for (const item of query.items) out[columnName(item)] = evaluate(item.expr, ctx)\n return out\n}\n\nconst sortBy = <T>(items: T[], keys: { desc: boolean; value: (item: T) => Value }[]): T[] =>\n [...items].sort((x, y) => {\n for (const key of keys) {\n const a = key.value(x)\n const b = key.value(y)\n if (a === null && b === null) continue\n if (a === null) return 1\n if (b === null) return -1\n const c = compare(a, b) ?? 0\n if (c !== 0) return key.desc ? -c : c\n }\n return 0\n })\n\n/** Drop null columns, as O2's JSON writer does. */\nconst compact = (row: Record<string, Value>): Row => {\n const out: Row = {}\n for (const [key, value] of Object.entries(row)) if (value !== null) out[key] = value\n return out\n}\n\n/** Run a parsed query over rows already filtered to the stream and time window. */\nexport const execute = (query: Query, rows: Row[]): Row[] => {\n const where = query.where\n const matched = where ? rows.filter((row) => truthy(evaluate(where, { row }))) : rows\n const aggregated = query.groupBy.length > 0 || query.items.some((item) => hasAggregate(item.expr))\n let output: Record<string, Value>[]\n if (aggregated) {\n if (query.star) throw new SqlError(\"SELECT * cannot be combined with GROUP BY or aggregates\")\n const groups = new Map<string, Row[]>()\n if (query.groupBy.length === 0) groups.set(\"\", matched)\n for (const row of query.groupBy.length > 0 ? matched : []) {\n const key = JSON.stringify(query.groupBy.map((g) => evaluate(g, { row })))\n groups.set(key, [...(groups.get(key) ?? []), row])\n }\n output = []\n for (const group of groups.values()) {\n const ctx: Context = { row: group[0] ?? {}, group }\n const projected = project(query, ctx)\n const having = query.having\n if (having && !truthy(evaluate(having, { ...ctx, aliases: projected }))) continue\n output.push(projected)\n }\n output = sortBy(\n output,\n query.orderBy.map((o) => ({\n desc: o.desc,\n value: (r) => evaluate(o.expr, { row: {}, aliases: r }),\n })),\n )\n } else {\n const aliasExprs = new Map(\n query.items.filter((i) => i.alias).map((i) => [i.alias as string, i.expr]),\n )\n const order =\n query.orderBy.length > 0\n ? query.orderBy\n : [{ expr: { k: \"col\", name: \"_timestamp\" } as Expr, desc: true }]\n const sorted = sortBy(\n matched,\n order.map((o) => ({\n desc: o.desc,\n value: (row: Row) =>\n evaluate(\n o.expr.k === \"col\" && aliasExprs.has(o.expr.name)\n ? (aliasExprs.get(o.expr.name) as Expr)\n : o.expr,\n { row },\n ),\n })),\n )\n output = sorted.map((row) => project(query, { row }))\n }\n const start = query.offset\n const end = query.limit === undefined ? undefined : start + query.limit\n return output.slice(start, end).map(compact)\n}\n", "import { Collection } from \"@crvouga/mockingbird-service\"\nimport type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\nimport type { Row, Scalar } from \"./otlp.js\"\n\nexport type StreamType = \"logs\" | \"traces\"\n\n/** One ingested log record or span, as O2 stores it, in one org's stream. */\nexport type StoredRow = {\n /** Org identifier (not display name). */\n org: string\n stream: string\n type: StreamType\n row: Row\n}\n\n/** An O2 organization: queries route by `identifier`; `name` is what the UI shows. */\nexport type Organization = { identifier: string; name: string }\n\n/** Per-namespace knobs, set through `PUT /__admin/settings`; cleared on reset. */\nexport type Settings = {\n /** Bearer tokens the OTLP receiver accepts. Empty: any bearer token (none is a 401). */\n ingestTokens: string[]\n /** Basic-auth users the search API accepts. Empty: any Basic credentials (none is a 401). */\n searchUsers: { username: string; password: string }[]\n organizations: Organization[]\n /**\n * Where exports land, by display name: `deployment.environment.name` (or\n * `deployment.environment`) equal to a key here picks that org; anything else goes to\n * `default`. Mirrors the collector's production/dev-org split.\n */\n routing: { byEnvironment: Record<string, string>; default: string }\n /** Keep log bodies (local debugging only; they can hold prompts or PHI). */\n keepBodies: boolean\n}\n\nexport const DEFAULT_ORGANIZATIONS: readonly Organization[] = [\n { identifier: \"default\", name: \"default\" },\n { identifier: \"30rBqcDevOrg7Hn2KmQ4xW9sLtY\", name: \"development\" },\n { identifier: \"3HSzeProdOrg5Jd8VpN1cR6gTfB\", name: \"production\" },\n]\n\nexport const DEFAULT_SETTINGS: Settings = {\n ingestTokens: [],\n searchUsers: [],\n organizations: [...DEFAULT_ORGANIZATIONS],\n routing: { byEnvironment: { production: \"production\" }, default: \"development\" },\n keepBodies: false,\n}\n\n/** Column name \u2192 O2 (Arrow) type name, as `\u2026/schema` reports it. */\nexport type SchemaFields = Record<string, \"Utf8\" | \"Int64\" | \"Float64\" | \"Boolean\">\n\nexport type MetricCounters = { requests: number; bytes: number; metrics: number }\n\nexport const typeOf = (value: Scalar): SchemaFields[string] =>\n typeof value === \"boolean\"\n ? \"Boolean\"\n : typeof value === \"number\"\n ? Number.isInteger(value)\n ? \"Int64\"\n : \"Float64\"\n : \"Utf8\"\n\nexport class OtelState {\n readonly rows: Collection<StoredRow>\n readonly schemas: Collection<SchemaFields>\n readonly counters: Collection<MetricCounters>\n readonly settings: Collection<Settings>\n\n constructor(\n sqlite: SqliteClient,\n namespace: string,\n private readonly seed: { settings: Partial<Settings> },\n ) {\n this.rows = new Collection(sqlite, namespace, \"rows\")\n this.schemas = new Collection(sqlite, namespace, \"schemas\")\n this.counters = new Collection(sqlite, namespace, \"counters\")\n this.settings = new Collection(sqlite, namespace, \"settings\")\n this.ensureSeeded()\n }\n\n ensureSeeded(): void {\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 org an export lands in, from its resource attributes. */\n routeOrg(resource: Record<string, Scalar>): string {\n const settings = this.current()\n const environment = String(\n resource[\"deployment.environment.name\"] ?? resource[\"deployment.environment\"] ?? \"\",\n )\n const name = settings.routing.byEnvironment[environment] ?? settings.routing.default\n const org = settings.organizations.find((o) => o.name === name || o.identifier === name)\n return org?.identifier ?? name\n }\n\n private schemaKey(org: string, stream: string, type: StreamType): string {\n return `${org}|${stream}|${type}`\n }\n\n schema(org: string, stream: string, type: StreamType): SchemaFields | undefined {\n return this.schemas.get(this.schemaKey(org, stream, type))\n }\n\n streams(org: string, type: StreamType): string[] {\n return this.schemas\n .list({ order: \"oldest\" })\n .map((r) => r.id.split(\"|\"))\n .filter(([o, , t]) => o === org && t === type)\n .map(([, stream]) => stream as string)\n }\n\n /** Store a row and widen its stream's schema (null-valued fields never appear). */\n ingest(row: StoredRow, extraFields: SchemaFields = {}): void {\n this.rows.insert(`${row.type}:${this.rows.nextSequence()}`, row)\n const key = this.schemaKey(row.org, row.stream, row.type)\n const fields: SchemaFields = { ...(this.schemas.get(key) ?? { _timestamp: \"Int64\" }) }\n let changed = !this.schemas.has(key)\n for (const [name, value] of Object.entries({ ...row.row })) {\n if (!(name in fields)) {\n fields[name] = typeOf(value)\n changed = true\n }\n }\n for (const [name, type] of Object.entries(extraFields)) {\n if (!(name in fields)) {\n fields[name] = type\n changed = true\n }\n }\n if (changed) this.schemas.insert(key, fields)\n }\n\n list(filter: (row: StoredRow) => boolean): StoredRow[] {\n return this.rows\n .list({ order: \"oldest\", where: (value) => filter(value) })\n .map((stored) => stored.value)\n }\n\n count(metrics: number, bytes: number): MetricCounters {\n const current = this.counters.get(\"metrics\") ?? { requests: 0, bytes: 0, metrics: 0 }\n const next = {\n requests: current.requests + 1,\n bytes: current.bytes + bytes,\n metrics: current.metrics + metrics,\n }\n this.counters.insert(\"metrics\", next)\n return next\n }\n\n metrics(): MetricCounters {\n return this.counters.get(\"metrics\") ?? { requests: 0, bytes: 0, metrics: 0 }\n }\n}\n", "import {\n type AdminRoutes,\n type Clock,\n createRuntime as createServiceRuntime,\n type FaultPreset,\n type RequestLog,\n type ServiceRuntime,\n} from \"@crvouga/mockingbird-service\"\nimport type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\nimport { document } from \"./generated/openapi.js\"\nimport { adminRow, OTEL_NAMESPACE, OtelAPI, otelCredential } from \"./index.js\"\nimport { formatKey, type Row } from \"./otlp.js\"\nimport type { Organization, Settings, StoredRow } from \"./state.js\"\n\nconst rpc = (code: number, message: string) => ({ code, message })\n\n/**\n * Every named collector misbehaviour our exporters branch on, switched on with\n * `POST /__admin/faults {\"preset\": \"<name>\"}` (add `count` to limit it). The SDK retries 429,\n * 502, 503 and 504 (honouring `retry-after`) and drops everything else.\n */\nexport const OTEL_PRESETS: Record<string, FaultPreset> = {\n rate_limited: {\n description: \"Exports answer 429 with retry-after: 1 (the SDK retries)\",\n rules: [\n {\n pathPrefix: \"/v1/\",\n status: 429,\n headers: { \"retry-after\": \"1\" },\n body: rpc(8, \"rate limited\"),\n },\n ],\n },\n bad_gateway: {\n description: \"Exports answer 502 (the SDK retries)\",\n rules: [{ pathPrefix: \"/v1/\", status: 502, body: rpc(14, \"bad gateway\") }],\n },\n unavailable: {\n description: \"Exports answer 503 (the SDK retries)\",\n rules: [{ pathPrefix: \"/v1/\", status: 503, body: rpc(14, \"unavailable\") }],\n },\n gateway_timeout: {\n description: \"Exports answer 504 (the SDK retries)\",\n rules: [{ pathPrefix: \"/v1/\", status: 504, body: rpc(4, \"deadline exceeded\") }],\n },\n server_error: {\n description: \"Exports answer 500 (the SDK drops the batch: not retryable)\",\n rules: [{ pathPrefix: \"/v1/\", status: 500, body: rpc(13, \"internal error\") }],\n },\n unauthorized: {\n description: \"Exports answer 401 as if OTEL_AUTH_TOKEN were wrong (dropped, never retried)\",\n rules: [{ pathPrefix: \"/v1/\", status: 401, body: rpc(16, \"Unauthenticated\") }],\n },\n partial_success: {\n description:\n \"Exports answer 200 with partialSuccess rejecting every item (JSON only); nothing is stored\",\n rules: [{ pathPrefix: \"/v1/\", effect: \"partial_success\" }],\n },\n search_unavailable: {\n description: \"O2 search answers 503 (our clients degrade: empty hops, error result)\",\n rules: [\n { operationId: \"Search\", status: 503, body: { code: 503, message: \"Service Unavailable\" } },\n ],\n },\n}\n\nexport type OtelRuntimeOptions = {\n sqlite?: SqliteClient\n clock?: Clock\n seed?: number | string\n adminKey?: string\n onLog?: (entry: RequestLog) => void\n settings?: Partial<Settings>\n}\n\nexport type OtelRuntime = ServiceRuntime<OtelAPI>\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\n/** Loose match of a `where` value against a stored column (numbers and strings compare as text). */\nconst same = (a: unknown, b: unknown): boolean =>\n a !== undefined && a !== null && String(a) === String(b)\n\n/**\n * `where` keys are taken as the emitter wrote them (`clientUserId`, `service.name`) or as O2\n * stores them (`clientuserid`, `service_name`); both resolve to the stored column.\n */\nconst matchesWhere = (row: Row, where: Record<string, unknown>): boolean =>\n Object.entries(where).every(([key, value]) => {\n if (key in row) return same(row[key], value)\n const formatted = formatKey(key)\n if (formatted in row) return same(row[formatted], value)\n return same(row[`service_${formatted}`], value)\n })\n\nconst WAIT_POLL_MS = 20\nconst MAX_WAIT_MS = 60_000\n\nconst adminRoutes = (runtime: ServiceRuntime<OtelAPI>): AdminRoutes => {\n const select = (\n namespace: string,\n kind: \"log\" | \"span\",\n where: Record<string, unknown>,\n org?: string | null,\n ): StoredRow[] => {\n const api = runtime.instance(namespace)\n return (kind === \"log\" ? api.logs() : api.spans()).filter(\n (stored) =>\n (org === undefined || org === null || stored.org === org) &&\n matchesWhere(stored.row, where),\n )\n }\n return {\n \"GET /logs\": ({ url, namespace }) => {\n const where: Record<string, unknown> = {}\n const service = url.searchParams.get(\"service\")\n const event = url.searchParams.get(\"event\")\n const trace = url.searchParams.get(\"trace_id\")\n if (service !== null) where.service_name = service\n if (event !== null) where.event = event\n if (trace !== null) where.trace_id = trace\n const severity = url.searchParams.get(\"severity\")?.toLowerCase()\n const logs = select(namespace, \"log\", where, url.searchParams.get(\"org\")).filter(\n (stored) =>\n severity === undefined ||\n String(stored.row.severity_text ?? \"\").toLowerCase() === severity,\n )\n return json(200, { logs: logs.map(adminRow) })\n },\n \"GET /spans\": ({ url, namespace }) => {\n const where: Record<string, unknown> = {}\n const service = url.searchParams.get(\"service\")\n const name = url.searchParams.get(\"name\")\n const trace = url.searchParams.get(\"trace_id\")\n if (service !== null) where.service_name = service\n if (name !== null) where.operation_name = name\n if (trace !== null) where.trace_id = trace\n return json(200, {\n spans: select(namespace, \"span\", where, url.searchParams.get(\"org\")).map(adminRow),\n })\n },\n /**\n * `{kind: \"log\"|\"span\", where: {event: \"\u2026\"}, count?: 1, timeoutMs?: 5000, org?}`:\n * long-polls until `count` rows match, then answers them; 408 with what matched so far.\n */\n \"POST /wait\": async ({ body, namespace }) => {\n if (!isRecord(body)) return adminError(400, 'expected {\"kind\": \"log\", \"where\": {...}}')\n const kind = body.kind ?? \"log\"\n if (kind !== \"log\" && kind !== \"span\") return adminError(400, 'kind must be \"log\" or \"span\"')\n const where = body.where ?? {}\n if (!isRecord(where)) return adminError(400, \"where must be an object of column: value\")\n const count = typeof body.count === \"number\" && body.count > 0 ? body.count : 1\n const timeoutMs = Math.min(\n typeof body.timeoutMs === \"number\" && body.timeoutMs >= 0 ? body.timeoutMs : 5_000,\n MAX_WAIT_MS,\n )\n const org = typeof body.org === \"string\" ? body.org : undefined\n const deadline = Date.now() + timeoutMs\n for (;;) {\n const matched = select(namespace, kind, where, org)\n if (matched.length >= count) {\n return json(200, { matched: matched.map(adminRow), count: matched.length })\n }\n if (Date.now() >= deadline) {\n return json(408, {\n error: {\n type: \"mockingbird_admin\",\n message: `timed out after ${timeoutMs} ms: ${matched.length}/${count} ${kind}s matched`,\n },\n matched: matched.map(adminRow),\n count: matched.length,\n })\n }\n await new Promise((resolve) => setTimeout(resolve, WAIT_POLL_MS))\n }\n },\n \"GET /otlp-metrics\": ({ namespace }) => json(200, runtime.instance(namespace).state.metrics()),\n \"GET /settings\": ({ namespace }) => json(200, runtime.instance(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.ingestTokens !== undefined) {\n if (!Array.isArray(body.ingestTokens)) return adminError(400, \"ingestTokens: string[]\")\n patch.ingestTokens = body.ingestTokens.map(String)\n }\n if (body.searchUsers !== undefined) {\n if (!Array.isArray(body.searchUsers) || !body.searchUsers.every(isRecord)) {\n return adminError(400, \"searchUsers: [{username, password}]\")\n }\n patch.searchUsers = body.searchUsers.map((u) => ({\n username: String(u.username),\n password: String(u.password ?? \"\"),\n }))\n }\n if (body.organizations !== undefined) {\n if (\n !Array.isArray(body.organizations) ||\n !body.organizations.every(\n (o) => isRecord(o) && typeof o.identifier === \"string\" && typeof o.name === \"string\",\n )\n ) {\n return adminError(400, \"organizations: [{identifier, name}]\")\n }\n patch.organizations = body.organizations as Organization[]\n }\n if (body.routing !== undefined) {\n const routing = body.routing\n if (\n !isRecord(routing) ||\n typeof routing.default !== \"string\" ||\n !isRecord(routing.byEnvironment)\n ) {\n return adminError(\n 400,\n \"routing: {byEnvironment: {<env>: <org name>}, default: <org name>}\",\n )\n }\n patch.routing = {\n default: routing.default,\n byEnvironment: Object.fromEntries(\n Object.entries(routing.byEnvironment).map(([k, v]) => [k, String(v)]),\n ),\n }\n }\n if (body.keepBodies !== undefined) {\n if (typeof body.keepBodies !== \"boolean\") return adminError(400, \"keepBodies: boolean\")\n patch.keepBodies = body.keepBodies\n }\n return json(200, runtime.instance(namespace).state.update(patch))\n },\n }\n}\n\n/**\n * The OTLP collector + OpenObserve search mock with Mockingbird's full service contract:\n * `/health`, `/__admin/*` (logs, spans, wait), namespaces by header, by `/ns/<name>` path\n * prefix, or by credential (the OTLP bearer token or the O2 Basic username), clock control and\n * fault presets.\n */\nexport const createRuntime = (options: OtelRuntimeOptions = {}): OtelRuntime =>\n createServiceRuntime<OtelAPI>({\n name: OTEL_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: otelCredential,\n presets: OTEL_PRESETS,\n create: ({ sqlite, namespace, clock }) =>\n new OtelAPI({\n sqlite,\n namespace,\n now: clock.now,\n ...(options.settings ? { settings: options.settings } : {}),\n }),\n describe: () => ({ keepBodies: options.settings?.keepBodies === true }),\n admin: adminRoutes,\n })\n", "import type { FetchAPI } from \"@crvouga/mockingbird-core\"\nimport {\n type APIOptions,\n annotateResponse,\n basicAuth,\n bearerToken,\n bootSqlite,\n createService,\n defineOperations,\n faultEffect,\n HttpError,\n jsonRes,\n type OperationContext,\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 { logRows, metricCount, type Row, spanRows } from \"./otlp.js\"\nimport {\n countMetricsRequest,\n decodeLogsRequest,\n decodeTraceRequest,\n ProtobufError,\n} from \"./protobuf.js\"\nimport { execute, parseSql, referencedColumns, SqlError } from \"./sql.js\"\nimport { OtelState, type Settings, type StoredRow, type StreamType } 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 { IngestedRow, Row, Scalar } from \"./otlp.js\"\nexport { formatKey, logRows, spanRows } from \"./otlp.js\"\nexport { decodeLogsRequest, decodeTraceRequest, ProtobufError } from \"./protobuf.js\"\nexport type { Expr, Query } from \"./sql.js\"\nexport { execute, parseSql, referencedColumns, SqlError } from \"./sql.js\"\nexport type {\n MetricCounters,\n Organization,\n SchemaFields,\n Settings,\n StoredRow,\n StreamType,\n} from \"./state.js\"\nexport { DEFAULT_ORGANIZATIONS, DEFAULT_SETTINGS } from \"./state.js\"\n\nexport const OTEL_NAMESPACE = \"otel\"\n\nexport type OtelAPIOptions = APIOptions & {\n /** Initial per-namespace settings (tokens, users, orgs, routing, keepBodies). */\n settings?: Partial<Settings>\n}\n\nconst PROTOBUF = \"application/x-protobuf\"\n\n/**\n * The credential a request carries, for `PUT /__admin/credentials`: the OTLP bearer token\n * (`OTEL_AUTH_TOKEN`) or the O2 Basic-auth username (from `O2_BASIC_AUTH`). Map both to the\n * same namespace so a worker's exports and searches meet.\n */\nexport const otelCredential = (request: Request): string | undefined =>\n bearerToken(request) ?? basicAuth(request)?.username\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\nconst mediaType = (request: Request) =>\n request.headers.get(\"content-type\")?.split(\";\")[0]?.trim().toLowerCase() ?? \"\"\n\n/** google.rpc.Status, the OTLP error body (code 16 = UNAUTHENTICATED, 3 = INVALID_ARGUMENT). */\nconst rpcStatus = (status: number, code: number, message: string) =>\n jsonRes(status, { code, message })\n\nconst unauthorized = () =>\n new Response(\"Unauthorized Access\", {\n status: 401,\n headers: { \"content-type\": \"text/plain; charset=utf-8\" },\n })\n\nconst o2Error = (status: number, message: string) => jsonRes(status, { code: status, message })\n\n/**\n * Stateful mock of an OTLP/HTTP collector and the OpenObserve search API over one store.\n *\n * Exports land as O2-shaped rows in the org their `deployment.environment.name` routes to;\n * `POST /api/{org}/_search` runs our clients' SQL over them, so a test can emit a structured\n * `event` log and read it back exactly as the ops feed and the investigation agent do.\n */\nexport class OtelAPI implements FetchAPI {\n readonly app: Hono\n readonly sqlite: SqliteClient\n readonly state: OtelState\n private readonly service: Service\n private readonly now: () => number\n\n constructor(options: OtelAPIOptions = {}) {\n const sqlite = bootSqlite(options.sqlite)\n const namespace = options.namespace ?? OTEL_NAMESPACE\n this.now = options.now ?? (() => Date.now())\n this.state = new OtelState(sqlite, namespace, { settings: options.settings ?? {} })\n const handlers = defineOperations<SupportedOperationId>({\n ExportTraces: (context) => this.export(context, \"traces\"),\n ExportLogs: (context) => this.export(context, \"logs\"),\n ExportMetrics: (context) => this.export(context, \"metrics\"),\n ListOrganizations: () => this.organizations(),\n ListStreams: (context) => this.streams(context),\n GetStreamSchema: (context) => this.schema(context),\n Search: (context) => this.search(context),\n })\n this.service = createService({\n document,\n handlers,\n sqlite,\n namespace,\n now: this.now,\n notFound: () => jsonRes(404, { code: 404, message: \"Not Found\" }),\n onError: (error) => {\n if (error instanceof HttpError) return error.toResponse()\n throw error\n },\n before: (context) => this.gate(context),\n })\n this.app = this.service.app\n this.sqlite = this.service.sqlite\n }\n\n /** Inflate `content-encoding: gzip` bodies (the exporters' `compression: \"gzip\"`). */\n async fetch(request: Request): Promise<Response> {\n const encoding = request.headers.get(\"content-encoding\")?.toLowerCase()\n if (encoding !== \"gzip\" || request.body === null) return this.service.fetch(request)\n let inflated: ArrayBuffer\n try {\n inflated = await new Response(\n request.body.pipeThrough(new DecompressionStream(\"gzip\")),\n ).arrayBuffer()\n } catch {\n return rpcStatus(400, 3, \"invalid gzip body\")\n }\n const headers = new Headers(request.headers)\n headers.delete(\"content-encoding\")\n headers.delete(\"content-length\")\n return this.service.fetch(\n new Request(request.url, { method: request.method, headers, body: inflated }),\n )\n }\n\n async reset(): Promise<void> {\n await this.service.reset()\n this.state.ensureSeeded()\n }\n\n /** Every stored log row (with its org and stream), oldest first. */\n logs(): StoredRow[] {\n return this.state.list((r) => r.type === \"logs\")\n }\n\n /** Every stored span row, oldest first. */\n spans(): StoredRow[] {\n return this.state.list((r) => r.type === \"traces\")\n }\n\n private settings(): Settings {\n return this.state.current()\n }\n\n private gate(context: OperationContext): Response | undefined {\n const operationId = context.operation.operationId\n if (operationId.startsWith(\"Export\")) {\n const token = bearerToken(context.request)\n const accepted = this.settings().ingestTokens\n if (!token || (accepted.length > 0 && !accepted.includes(token))) {\n return rpcStatus(401, 16, \"Unauthenticated\")\n }\n return undefined\n }\n const credentials = basicAuth(context.request)\n if (!credentials) return unauthorized()\n const users = this.settings().searchUsers\n if (\n users.length > 0 &&\n !users.some((u) => u.username === credentials.username && u.password === credentials.password)\n ) {\n return unauthorized()\n }\n const org = context.params.org\n // Real O2 routes by identifier: a display name (or any unknown org) is a bare 401.\n if (org !== undefined && !this.settings().organizations.some((o) => o.identifier === org)) {\n return unauthorized()\n }\n return undefined\n }\n\n private decode(\n context: OperationContext,\n kind: \"traces\" | \"logs\" | \"metrics\",\n ): { payload: Record<string, unknown>; protobuf: boolean; bytes: number } | Response {\n const type = mediaType(context.request)\n const body = context.body\n if (type === PROTOBUF) {\n const bytes = body.kind === \"bytes\" ? body.value : new Uint8Array(0)\n try {\n const payload =\n kind === \"traces\"\n ? decodeTraceRequest(bytes)\n : kind === \"logs\"\n ? decodeLogsRequest(bytes)\n : { resourceMetrics: new Array(countMetricsRequest(bytes)).fill({}) }\n return { payload, protobuf: true, bytes: bytes.length }\n } catch (error) {\n if (error instanceof ProtobufError) return rpcStatus(400, 3, error.message)\n throw error\n }\n }\n if (type !== \"application/json\") {\n return rpcStatus(415, 3, `unsupported content type ${type || \"(none)\"}`)\n }\n if (body.kind === \"empty\") return { payload: {}, protobuf: false, bytes: 0 }\n if (body.kind !== \"json\" || !isRecord(body.value)) {\n return rpcStatus(400, 3, \"request body is not an OTLP/JSON export request\")\n }\n return { payload: body.value, protobuf: false, bytes: JSON.stringify(body.value).length }\n }\n\n private export(context: OperationContext, kind: \"traces\" | \"logs\" | \"metrics\"): Response {\n const decoded = this.decode(context, kind)\n if (decoded instanceof Response) return decoded\n const { payload, protobuf } = decoded\n const ok = (partial: Record<string, unknown> = {}) =>\n protobuf\n ? new Response(new Uint8Array(0), { status: 200, headers: { \"content-type\": PROTOBUF } })\n : jsonRes(200, { partialSuccess: partial })\n if (kind === \"metrics\") {\n const count =\n protobuf && Array.isArray(payload.resourceMetrics)\n ? payload.resourceMetrics.length\n : metricCount(payload)\n this.state.count(count, decoded.bytes)\n return ok()\n }\n const nowMs = this.now()\n const rows =\n kind === \"traces\"\n ? spanRows(payload, { nowMs })\n : logRows(payload, { keepBodies: this.settings().keepBodies, nowMs })\n const rejected = faultEffect(context.request, \"partial_success\")\n if (rejected !== undefined) {\n const key = kind === \"traces\" ? \"rejectedSpans\" : \"rejectedLogRecords\"\n return ok({\n [key]: String(rows.length),\n errorMessage: String(rejected.message ?? \"rejected by Mockingbird partial_success\"),\n })\n }\n const stream = context.request.headers.get(\"stream-name\")?.trim() || \"default\"\n const type: StreamType = kind === \"traces\" ? \"traces\" : \"logs\"\n const orgs = new Set<string>()\n // One transaction per export: a transaction per row makes a large batch crawl.\n this.sqlite.transaction(() => {\n for (const ingested of rows) {\n const org = this.state.routeOrg(ingested.resource)\n orgs.add(org)\n this.state.ingest(\n { org, stream, type, row: ingested.row },\n ingested.hadBody ? { body: \"Utf8\" } : {},\n )\n }\n })\n return annotateResponse(ok(), {\n ids: {\n accepted: String(rows.length),\n ...(orgs.size > 0 ? { org: [...orgs].join(\",\") } : {}),\n },\n })\n }\n\n private organizations(): Response {\n return jsonRes(200, {\n data: this.settings().organizations.map((org, index) => ({\n id: index + 1,\n identifier: org.identifier,\n name: org.name,\n type: org.identifier === \"default\" ? \"default\" : \"custom\",\n })),\n })\n }\n\n private streamType(context: OperationContext): StreamType {\n return context.url.searchParams.get(\"type\") === \"traces\" ? \"traces\" : \"logs\"\n }\n\n private streams(context: OperationContext): Response {\n const org = context.params.org as string\n const type = this.streamType(context)\n return jsonRes(200, {\n list: this.state.streams(org, type).map((name) => ({\n name,\n stream_type: type,\n storage_type: \"disk\",\n stats: {\n doc_num: this.state.list((r) => r.org === org && r.stream === name && r.type === type)\n .length,\n },\n })),\n })\n }\n\n private schema(context: OperationContext): Response {\n const org = context.params.org as string\n const stream = context.params.stream as string\n const type = this.streamType(context)\n const fields = this.state.schema(org, stream, type)\n if (!fields) return o2Error(404, `stream ${stream} not found`)\n const names = Object.keys(fields).sort((a, b) =>\n a === \"_timestamp\" ? -1 : b === \"_timestamp\" ? 1 : a.localeCompare(b),\n )\n return jsonRes(200, {\n name: stream,\n stream_type: type,\n storage_type: \"disk\",\n stats: {\n doc_num: this.state.list((r) => r.org === org && r.stream === stream && r.type === type)\n .length,\n },\n schema: names.map((name) => ({ name, type: fields[name] })),\n settings: { partition_keys: {}, full_text_search_keys: [], data_retention: 30 },\n })\n }\n\n private search(context: OperationContext): Response {\n const org = context.params.org as string\n const body = context.body.kind === \"json\" ? context.body.value : undefined\n const query = isRecord(body) && isRecord(body.query) ? body.query : undefined\n if (!query || typeof query.sql !== \"string\") {\n return o2Error(400, \"Search SQL not supported: query.sql is required\")\n }\n let parsed: ReturnType<typeof parseSql>\n try {\n parsed = parseSql(query.sql)\n } catch (error) {\n if (error instanceof SqlError)\n return o2Error(400, `Search SQL not supported: ${error.message}`)\n throw error\n }\n const type = this.streamType(context)\n const from = typeof query.from === \"number\" && query.from > 0 ? query.from : 0\n const size = typeof query.size === \"number\" ? query.size : -1\n const empty = (hits: Row[], total: number, scanned: number) =>\n annotateResponse(\n jsonRes(200, {\n took: 1,\n hits,\n total,\n from,\n size,\n cached_ratio: 0,\n scan_size: 0,\n scan_records: scanned,\n is_partial: false,\n }),\n { ids: { org } },\n )\n const fields = this.state.schema(org, parsed.stream, type)\n if (!fields) return empty([], 0, 0)\n const unknown = referencedColumns(parsed).find((name) => !(name in fields))\n if (unknown !== undefined) {\n return o2Error(\n 400,\n `Search SQL execute error: Schema error: No field named ${unknown}. Valid fields are ${Object.keys(fields).sort().join(\", \")}.`,\n )\n }\n const start = typeof query.start_time === \"number\" ? query.start_time : 0\n const end = typeof query.end_time === \"number\" && query.end_time > 0 ? query.end_time : Infinity\n const rows = this.state\n .list((r) => r.org === org && r.stream === parsed.stream && r.type === type)\n .map((r) => r.row)\n .filter((row) => {\n const ts = Number(row._timestamp)\n return ts >= start && ts <= end\n })\n let hits: Row[]\n try {\n hits = execute(parsed, rows)\n } catch (error) {\n if (error instanceof SqlError)\n return o2Error(400, `Search SQL not supported: ${error.message}`)\n throw error\n }\n const page = size < 0 ? hits.slice(from) : hits.slice(from, from + size)\n return empty(page, hits.length, rows.length)\n }\n}\n\n/** A stored row as the admin routes show it: its org and stream beside its columns. */\nexport const adminRow = (stored: StoredRow): Row => ({\n _org: stored.org,\n _stream: stored.stream,\n ...stored.row,\n})\n\nexport type { OtelRuntime, OtelRuntimeOptions } from \"./runtime.js\"\nexport { createRuntime, OTEL_PRESETS } 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;IACA,OAAO,MAAK;AACV,iBAAW;AACX,iBAAW;IACb;IACA,OAAO,OAAO,EAAE,KAAK,IAAG,GAAI,QAAQ,aAAa,QAAW,SAAQ;;AAExE;;;AC1CM,IAAO,aAAP,MAAiB;EAEF;EACA;EACA;EAHnB,YACmB,QACA,WACA,MAAY;AAFZ,SAAA,SAAA;AACA,SAAA,YAAA;AACA,SAAA,OAAA;EAChB;EAEK,oBAAiB;AACvB,UAAM,MAAM,KAAK,OACd,QACC,kGAAkG,EAEnG,IAAuB,KAAK,WAAW,KAAK,IAAI;AACnD,UAAM,QAAQ,KAAK,SAAS,KAAK;AACjC,SAAK,OACF,QACC;iFACyE,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",
6
+ "names": ["id", "text", "id", "next", "id", "document", "document", "text", "mediaType", "text", "id", "isRecord", "document", "id", "json", "adminError", "isRecord", "list", "BRANCH_PATTERN", "compare", "document", "snapshot", "branch", "url", "response", "id", "list", "isRecord", "hex", "put", "utf8", "not", "list", "values", "a", "b", "json", "adminError", "isRecord", "createRuntime", "isRecord", "hits"]
7
+ }