@crvouga/mockingbird-service-junction 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -5
- package/README.md +222 -21
- package/dist/{chunk-MD4KYEIM.js → chunk-C2UGIPPM.js} +2 -2
- package/dist/{chunk-4C6VYRJN.js → chunk-ISDNA2TU.js} +8 -3
- package/dist/chunk-ISDNA2TU.js.map +7 -0
- package/dist/{chunk-KKNULV7X.js → chunk-KLBGX23P.js} +76 -8
- package/dist/chunk-KLBGX23P.js.map +7 -0
- package/dist/{chunk-MA3HSUVD.js → chunk-NFWUEPW4.js} +1856 -778
- package/dist/chunk-NFWUEPW4.js.map +7 -0
- package/dist/cli.js +4 -4
- package/dist/corpus.d.ts +10 -2
- package/dist/corpus.js +2 -2
- package/dist/index.d.ts +322 -49
- package/dist/index.js +34 -2
- package/dist/server.d.ts +242 -10
- package/dist/server.js +4 -4
- package/package.json +1 -1
- package/dist/chunk-4C6VYRJN.js.map +0 -7
- package/dist/chunk-KKNULV7X.js.map +0 -7
- package/dist/chunk-MA3HSUVD.js.map +0 -7
- /package/dist/{chunk-MD4KYEIM.js.map → chunk-C2UGIPPM.js.map} +0 -0
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../core/src/clock.ts", "../../core/src/collection.ts", "../../core/src/control.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/ids.ts", "../../core/src/metrics.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/runtime.ts", "../src/generated/openapi.ts", "../src/catalog.ts", "../src/state.ts", "../src/lab-accounts.ts", "../src/scheduling.ts", "../src/orders.ts", "../src/results.ts", "../src/seed-from.ts", "../src/users.ts", "../src/admin.ts", "../src/coverage-corpus.ts", "../src/reshape.ts", "../src/prefetch.ts", "../src/corpus-tools.ts", "../src/webhooks.ts", "../src/runtime.ts", "../src/verify.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 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 { Metrics } from \"./metrics.js\"\nimport type { NamespaceSnapshot } from \"./snapshot.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 clock: Clock\n faults: FaultRegistry\n metrics: Metrics\n defaultNamespace: string\n namespaces(): string[]\n reset(namespace: string | \"*\"): Promise<void>\n snapshot(namespace: string): NamespaceSnapshot\n restore(namespace: string, snapshot: NamespaceSnapshot): void\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}\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 const snapshots = new Map<string, NamespaceSnapshot>()\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.status !== \"number\") {\n return adminError(400, \"a fault needs a numeric status\")\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 snapshot = context.snapshot(namespace)\n snapshotCounter++\n const id = `snap_${snapshotCounter}`\n snapshots.set(id, snapshot)\n return json(201, { id, namespace, records: snapshot.records.length })\n },\n \"POST /snapshots/:id/restore\": ({ params, namespace }) => {\n const snapshot = snapshots.get(params.id as string)\n if (!snapshot) return adminError(404, `no snapshot ${params.id}`)\n context.restore(namespace, snapshot)\n return json(200, { status: \"ok\", id: params.id, namespace })\n },\n \"DELETE /snapshots/:id\": ({ params }) =>\n snapshots.delete(params.id as string)\n ? json(200, { status: \"ok\" })\n : adminError(404, `no snapshot ${params.id}`),\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: Date.now() - 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 * 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 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 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 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}\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 * The fault this request should get, or `undefined` to let it through.\n * Consumes one of the matching rule's remaining uses.\n */\n take(candidate: FaultCandidate): Promise<{ id: string; response: Response } | undefined>\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 headers = { \"content-type\": \"application/json\", ...rule.headers }\n if (typeof rule.body === \"string\")\n return new Response(rule.body, { status: rule.status, headers })\n const body = rule.body === undefined ? { detail: \"Injected by Mockingbird\" } : rule.body\n return new Response(JSON.stringify(body), { status: rule.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 = (rng: Rng = createRng(0)): 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 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 if (entry.rule.delayMs !== undefined && entry.rule.delayMs > 0) {\n await new Promise((resolve) => setTimeout(resolve, entry.rule.delayMs))\n }\n return { id: entry.rule.id, response: faultResponse(entry.rule) }\n }\n return undefined\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 { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\n\nconst ALPHABET = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\"\n\n/** FNV-1a over a string, mixed once more so consecutive counters look unrelated. */\nconst mix = (input: string): number => {\n let hash = 0x811c9dc5\n for (let i = 0; i < input.length; i++) {\n hash ^= input.charCodeAt(i)\n hash = Math.imul(hash, 0x01000193) >>> 0\n }\n hash ^= hash >>> 16\n hash = Math.imul(hash, 0x85ebca6b) >>> 0\n hash ^= hash >>> 13\n return hash >>> 0\n}\n\n/** Deterministic, opaque-looking alphanumeric token of `length` characters derived from `input`. */\nexport const opaqueToken = (input: string, length: number): string => {\n let out = \"\"\n let round = 0\n while (out.length < length) {\n let hash = mix(`${input}:${round++}`)\n for (let i = 0; i < 5 && out.length < length; i++) {\n out += ALPHABET.charAt(hash % ALPHABET.length)\n hash = Math.floor(hash / ALPHABET.length)\n }\n }\n return out\n}\n\n/**\n * Sequential id source persisted in SQLite. Ids are deterministic for a given\n * sequence history (`cus_` + 14 opaque chars), so reproductions stay stable.\n */\nexport class IdSequence {\n constructor(\n private readonly sqlite: SqliteClient,\n private readonly namespace: string,\n private readonly salt = \"mockingbird\",\n ) {}\n\n next(prefix: string, length = 14): string {\n return this.sqlite.transaction(() => {\n const row = this.sqlite\n .prepare(\n \"SELECT value FROM mockingbird_sequences WHERE namespace = ? AND name = ? AND kind = 'id'\",\n )\n .get<{ value: number }>(this.namespace, prefix)\n const value = (row?.value ?? 0) + 1\n this.sqlite\n .prepare(\n `INSERT INTO mockingbird_sequences (namespace, name, kind, value) VALUES (?, ?, 'id', ?)\n ON CONFLICT(namespace, name, kind) DO UPDATE SET value = excluded.value`,\n )\n .run(this.namespace, prefix, value)\n return `${prefix}${opaqueToken(`${this.salt}:${prefix}:${value}`, length)}`\n })\n }\n}\n", "/** 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}\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", "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 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 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 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\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 */\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", "import type { FetchAPI } 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 { createFaultRegistry, type FaultRegistry } from \"./faults.js\"\nimport { createMetrics, type Metrics, type RequestLog } from \"./metrics.js\"\nimport { createRng, type Rng } from \"./rng.js\"\nimport { bootSqlite } from \"./service.js\"\nimport { type NamespaceSnapshot, restoreNamespace, snapshotNamespace } from \"./snapshot.js\"\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}\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 rng: Rng\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}\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\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 faults = createFaultRegistry(createRng(options.seed ?? 0))\n const metrics = createMetrics()\n const instances = new Map<string, T>()\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 instance = (name: string = DEFAULT_NAMESPACE): T => {\n const existing = instances.get(name)\n if (existing) return existing\n if (!NAMESPACE_PATTERN.test(name)) {\n throw new RangeError(`namespace must match ${NAMESPACE_PATTERN}: ${JSON.stringify(name)}`)\n }\n const created = options.create({\n namespace: storageNamespace(name),\n publicNamespace: name,\n sqlite,\n clock,\n rng,\n })\n instances.set(name, created)\n return created\n }\n\n const reset = async (name: string = DEFAULT_NAMESPACE): Promise<void> => {\n if (name === \"*\") {\n for (const each of instances.values()) await each.reset()\n return\n }\n const target = instances.get(name)\n if (target) await target.reset()\n else clearNamespace(sqlite, storageNamespace(name))\n }\n\n const snapshot = (name: string = DEFAULT_NAMESPACE): NamespaceSnapshot => {\n instance(name)\n return snapshotNamespace(sqlite, storageNamespace(name))\n }\n\n const restore = (from: NamespaceSnapshot, name: string = DEFAULT_NAMESPACE): void => {\n instance(name)\n restoreNamespace(sqlite, storageNamespace(name), from)\n }\n\n const runtime: ServiceRuntime<T> = {\n name: options.name,\n sqlite,\n clock,\n faults,\n metrics,\n rng,\n instance,\n namespaces: () => [...instances.keys()].sort(),\n reset,\n snapshot,\n restore,\n fetch: async (request) => {\n const handled = await control.handle(request)\n if (handled) return handled\n const started = performance.now()\n const url = new URL(request.url)\n const namespace = control.namespaceOf(request)\n const operationId = operationIdFor(request, url.pathname)\n const log = (status: number, faultId?: string) => {\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((performance.now() - started) * 100) / 100,\n unmatched: options.document !== undefined && operationId === undefined,\n ...(faultId !== undefined ? { faultId } : {}),\n }\n metrics.record(entry)\n options.onLog?.(entry)\n }\n if (!NAMESPACE_PATTERN.test(namespace)) {\n log(400)\n return 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 const faulted = await faults.take({\n operationId,\n method: request.method,\n path: url.pathname,\n namespace,\n })\n if (faulted) {\n log(faulted.response.status, faulted.id)\n return faulted.response\n }\n const response = await instance(namespace).fetch(request)\n log(response.status)\n return response\n },\n }\n\n const control = createControlPlane({\n name: options.name,\n startedAt: Date.now(),\n clock,\n faults,\n metrics,\n defaultNamespace: DEFAULT_NAMESPACE,\n namespaces: runtime.namespaces,\n reset,\n snapshot: (name) => snapshot(name),\n restore: (name, from) => restore(from, name),\n describe: options.describe ?? (() => ({})),\n routes: options.admin?.(runtime) ?? {},\n adminKey: options.adminKey,\n })\n\n return runtime\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\":\"Junction API (Mockingbird subset)\",\"description\":\"Stateful mock subset of the Junction (Vital) API.\\\\nDocs: https://docs.junction.com/\\\\nAuth: https://docs.junction.com/api-details/junction-api\\\\nCreate user: https://docs.junction.com/api-reference/user/create-user\\\\nGet user: https://docs.junction.com/api-reference/user/get-user\\\\nDelete user: https://docs.junction.com/api-reference/user/delete-user\\\\nResolve user: https://docs.junction.com/api-reference/user/resolve-user\\\\nUpdate user: https://docs.junction.com/api-reference/user/patch-user\\\\nGet users: https://docs.junction.com/api-reference/user/get-users\\\\nCreate order: https://docs.junction.com/api-reference/lab-testing/create-order\\\\nGet order: https://docs.junction.com/api-reference/lab-testing/get-order\\\\nGet orders: https://docs.junction.com/api-reference/lab-testing/get-orders\\\\nGet order transaction: https://docs.junction.com/api-reference/lab-testing/order-transactions/get-order-transaction\\\\nGet order transaction result: https://docs.junction.com/api-reference/lab-testing/results/get-order-transaction-results\\\\nLab tests: https://docs.junction.com/api-reference/lab-testing/tests-paginated\\\\nAppointment availability: https://docs.junction.com/api-reference/lab-testing/appointments/get-appointment-availability\\\\nBook appointment: https://docs.junction.com/api-reference/lab-testing/appointments/book-appointment\\\\nGet appointment: https://docs.junction.com/api-reference/lab-testing/appointments/get-appointment\\\\nReschedule appointment: https://docs.junction.com/api-reference/lab-testing/appointments/reschedule-appointment\\\\nCancel appointment: https://docs.junction.com/api-reference/lab-testing/appointments/cancel-appointment\\\\nAppointment cancellation reasons: https://docs.junction.com/api-reference/lab-testing/appointments/get-appointment-cancellation-reasons\\\\nArea info: https://docs.junction.com/api-reference/lab-testing/service-areas/get-area-info\\\\nPSC info: https://docs.junction.com/api-reference/lab-testing/service-areas/get-psc-info\\\\nLab locations: https://docs.junction.com/api-reference/lab-testing/service-areas/get-lab-locations\\\\nRaw results: https://docs.junction.com/api-reference/lab-testing/results/get-lab-results\\\\nResult metadata: https://docs.junction.com/api-reference/lab-testing/results/get-lab-results-metadata\\\\nResult PDF: https://docs.junction.com/api-reference/lab-testing/results/get-lab-result-pdf\\\\nRequisition form PDF: https://docs.junction.com/api-reference/lab-testing/orders/get-requisition-form\\\\nList labs: https://docs.junction.com/api-reference/lab-testing/tests/get-labs\\\\nTest markers: https://docs.junction.com/api-reference/lab-testing/tests/get-markers-for-lab-test\\\\nOrder-set markers: https://docs.junction.com/api-reference/lab-testing/results/get-order-set-markers\\\\nLatest user info: https://docs.junction.com/api-reference/user/get-latest-user-info\\\\n\",\"version\":\"0.4.758\",\"x-mockingbird-upstream\":{\"docs\":\"https://docs.junction.com/\",\"note\":\"Hand-authored subset from Junction public OpenAPI snippets in the docs.\"}},\"servers\":[{\"url\":\"https://api.sandbox.us.junction.com\"}],\"security\":[{\"apiKeyAuth\":[]}],\"paths\":{\"/v2/user\":{\"post\":{\"operationId\":\"create_user_v2_user_post\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/UserCreateBody\"}}}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ClientFacingUser\"}}}},\"400\":{\"description\":\"Bad Request\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ClientUserIDConflictResponse\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}},\"get\":{\"operationId\":\"get_teams_users_v2_user_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"parameters\":[{\"name\":\"offset\",\"in\":\"query\",\"required\":false,\"schema\":{\"type\":\"integer\"}},{\"name\":\"limit\",\"in\":\"query\",\"required\":false,\"schema\":{\"type\":\"integer\",\"maximum\":500}}],\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/PaginatedUsersResponse\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"500\":{\"description\":\"Internal Server Error\",\"content\":{\"text/plain\":{\"schema\":{\"type\":\"string\"}}}}}}},\"/v2/user/{user_id}\":{\"parameters\":[{\"name\":\"user_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"user\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"get\":{\"operationId\":\"get_user_v2_user__user_id__get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ClientFacingUser\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}},\"delete\":{\"operationId\":\"delete_user_v2_user__user_id__delete\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/UserSuccessResponse\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}},\"patch\":{\"operationId\":\"patch_user_v2_user__user_id__patch\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/UserPatchBody\"}}}},\"responses\":{\"204\":{\"description\":\"Successful Response\"},\"400\":{\"description\":\"Nothing to patch\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"409\":{\"description\":\"Conflict\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v2/user/resolve/{client_user_id}\":{\"parameters\":[{\"name\":\"client_user_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"minLength\":1}}],\"get\":{\"operationId\":\"get_user_by_client_user_id_v2_user_resolve__client_user_id__get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/ClientFacingUser\"},{\"$ref\":\"#/components/schemas/PaginatedUsersResponse\"}]}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v2/user/{user_id}/info\":{\"parameters\":[{\"name\":\"user_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"user\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"patch\":{\"operationId\":\"patch_user_info_v2_user__user_id__info_patch\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/UserInfoPatchBody\"}}}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/UserInfo\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v2/user/{user_id}/info/latest\":{\"parameters\":[{\"name\":\"user_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"user\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"get\":{\"operationId\":\"get_latest_user_info_user_v2_user__user_id__info_latest_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/UserInfo\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/lab_test\":{\"get\":{\"operationId\":\"get_paginated_lab_tests_for_team_v3_lab_test_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/LabTestResourcesResponse\"}}}}}}},\"/v3/lab_test/lab_account\":{\"get\":{\"operationId\":\"get_team_lab_accounts_v3_lab_test_lab_account_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"lab-account inventory is fixture-owned; the mock models the documented shape, filters and routing rules, not a live account inventory\"}},\"parameters\":[{\"name\":\"lab_account_id\",\"in\":\"query\",\"required\":false,\"schema\":{\"anyOf\":[{\"type\":\"string\",\"format\":\"uuid\"},{\"type\":\"null\"}]}},{\"name\":\"status\",\"in\":\"query\",\"required\":false,\"schema\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/LabAccountStatus\"},{\"type\":\"null\"}]}}],\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/GetTeamLabAccountsResponse\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/lab_tests/{lab_test_id}\":{\"parameters\":[{\"name\":\"lab_test_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"lab_test\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"get\":{\"operationId\":\"get_lab_test_for_team_v3_lab_tests__lab_test_id__get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ClientFacingLabTest\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/lab_tests/labs\":{\"get\":{\"operationId\":\"get_labs_v3_lab_tests_labs_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ClientFacingLab\"}}}}}}}},\"/v3/lab_tests/{lab_test_id}/markers\":{\"parameters\":[{\"name\":\"lab_test_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"lab_test\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}},{\"name\":\"page\",\"in\":\"query\",\"required\":false,\"schema\":{\"type\":\"integer\",\"minimum\":1,\"default\":1}},{\"name\":\"size\",\"in\":\"query\",\"required\":false,\"schema\":{\"type\":\"integer\",\"minimum\":1,\"maximum\":100,\"default\":50}},{\"name\":\"provider_id\",\"in\":\"query\",\"required\":false,\"schema\":{\"type\":\"string\"}}],\"get\":{\"operationId\":\"get_markers_for_lab_test_v3_lab_tests__lab_test_id__markers_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/GetMarkersResponse\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/lab_tests/list_order_set_markers\":{\"post\":{\"operationId\":\"list_order_set_markers_v3_lab_tests_list_order_set_markers_post\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ListOrderSetMarkersRequest\"}}}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/GetMarkersResponse\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order\":{\"post\":{\"operationId\":\"create_order_v3_order_post\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/CreateOrderRequest\"}}}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/PostOrderResponse\"}}}},\"400\":{\"description\":\"Bad Request\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"500\":{\"description\":\"Internal Server Error\"}}}},\"/v3/order/area/info\":{\"get\":{\"operationId\":\"get_area_info_v3_order_area_info_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"central_labs presence, within_radius counts and getlabs market coverage are provider-owned geo data that a mock cannot replicate per-zip; covered by the client-parity scenario shape checks instead\"}},\"parameters\":[{\"name\":\"zip_code\",\"in\":\"query\",\"required\":true,\"schema\":{\"type\":\"string\",\"pattern\":\"^\\\\\\\\d{5}(?:-?\\\\\\\\d{4})?$\"}},{\"name\":\"radius\",\"in\":\"query\",\"required\":false,\"schema\":{\"$ref\":\"#/components/schemas/AllowedRadius\"}},{\"name\":\"lab_account_id\",\"in\":\"query\",\"required\":false,\"description\":\"Lab Account ID to use for availability checks\",\"schema\":{\"anyOf\":[{\"type\":\"string\",\"format\":\"uuid\"},{\"type\":\"null\"}]}}],\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/AreaInfo\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/psc/info\":{\"get\":{\"operationId\":\"get_psc_info_v3_order_psc_info_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"patient_service_centers are real site inventories per zip (thousands of sites, result-capped at 30) that a fixture mock cannot replicate per-zip; covered by the client-parity scenario shape checks instead\"}},\"parameters\":[{\"name\":\"zip_code\",\"in\":\"query\",\"required\":true,\"schema\":{\"type\":\"string\",\"pattern\":\"^\\\\\\\\d{5}$\"}},{\"name\":\"lab_id\",\"in\":\"query\",\"required\":true,\"schema\":{\"type\":\"integer\"}},{\"name\":\"radius\",\"in\":\"query\",\"required\":false,\"schema\":{\"$ref\":\"#/components/schemas/AllowedRadius\"}},{\"name\":\"capabilities\",\"in\":\"query\",\"required\":false,\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/LabLocationCapability\"}}}],\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/PscInfo\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/phlebotomy/appointment/availability\":{\"post\":{\"operationId\":\"get_phlebotomy_appointment_availability_v3_order_phlebotomy_appointment_availability_post\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"availability slots are provider-side data whose values shift between sandbox calls; covered by the mock-internal scheduling property suite instead\"}},\"parameters\":[{\"name\":\"start_date\",\"in\":\"query\",\"required\":false,\"schema\":{\"type\":\"string\",\"format\":\"date\"}}],\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/UsAddress\"}}}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/AppointmentAvailabilitySlots\"}}}},\"400\":{\"description\":\"Availability not bookable for this address\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"404\":{\"description\":\"No availability found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/phlebotomy/appointment/cancellation-reasons\":{\"get\":{\"operationId\":\"get_phlebotomy_appointment_cancellation_reason_v3_order_phlebotomy_appointment_cancellation_reasons_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ClientFacingAppointmentCancellationReason\"}}}}}}}},\"/v3/order/psc/appointment/availability\":{\"post\":{\"operationId\":\"get_psc_appointment_availability_v3_order_psc_appointment_availability_post\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"availability slots are provider-side data whose values shift between sandbox calls; covered by the mock-internal scheduling property suite instead\"}},\"parameters\":[{\"name\":\"lab\",\"in\":\"query\",\"required\":true,\"schema\":{\"$ref\":\"#/components/schemas/AppointmentPscLabs\"}},{\"name\":\"start_date\",\"in\":\"query\",\"required\":false,\"schema\":{\"type\":\"string\",\"format\":\"date\"}},{\"name\":\"site_codes\",\"in\":\"query\",\"required\":false,\"schema\":{\"type\":\"string\",\"description\":\"JSON-encoded array of site codes\"}},{\"name\":\"zip_code\",\"in\":\"query\",\"required\":false,\"schema\":{\"type\":\"string\"}},{\"name\":\"radius\",\"in\":\"query\",\"required\":false,\"schema\":{\"$ref\":\"#/components/schemas/AllowedRadius\"}},{\"name\":\"allow_stale\",\"in\":\"query\",\"required\":false,\"schema\":{\"type\":\"boolean\"}}],\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/AppointmentAvailabilitySlots\"}}}},\"400\":{\"description\":\"Availability not bookable for this address\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"404\":{\"description\":\"No slots found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/psc/appointment/cancellation-reasons\":{\"get\":{\"operationId\":\"get_psc_appointment_cancellation_reason_v3_order_psc_appointment_cancellation_reasons_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ClientFacingAppointmentCancellationReason\"}}}}}}}},\"/v3/order/{order_id}/phlebotomy/appointment\":{\"parameters\":[{\"name\":\"order_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"get\":{\"operationId\":\"get_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"appointment payloads embed provider-side slot data; covered by the mock-internal scheduling property suite instead\"}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ClientFacingAppointment\"}}}},\"404\":{\"description\":\"No appointment for this order\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/{order_id}/phlebotomy/appointment/book\":{\"parameters\":[{\"name\":\"order_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"post\":{\"operationId\":\"book_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_book_post\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"booking depends on live provider slot state; covered by the mock-internal scheduling property suite instead\"}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/AppointmentBookingRequest\"}}}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ClientFacingAppointment\"}}}},\"400\":{\"description\":\"Booking failed\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"404\":{\"description\":\"Order not found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/{order_id}/phlebotomy/appointment/reschedule\":{\"parameters\":[{\"name\":\"order_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"patch\":{\"operationId\":\"reschedule_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_reschedule_patch\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"rescheduling depends on live provider slot state; covered by the mock-internal scheduling property suite instead\"}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/AppointmentRescheduleRequest\"}}}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ClientFacingAppointment\"}}}},\"400\":{\"description\":\"Invalid or expired booking key\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"404\":{\"description\":\"No appointment for this order\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/{order_id}/phlebotomy/appointment/cancel\":{\"parameters\":[{\"name\":\"order_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"patch\":{\"operationId\":\"cancel_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_cancel_patch\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"cancellation depends on live provider appointment state; covered by the mock-internal scheduling property suite instead\"}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/PhlebotomyAppointmentCancelRequest\"}}}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ClientFacingAppointment\"}}}},\"400\":{\"description\":\"Invalid cancellation reason\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"404\":{\"description\":\"No appointment for this order\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/{order_id}/psc/appointment\":{\"parameters\":[{\"name\":\"order_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"get\":{\"operationId\":\"get_psc_appointment_v3_order__order_id__psc_appointment_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"appointment payloads embed provider-side slot data; covered by the mock-internal scheduling property suite instead\"}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ClientFacingAppointment\"}}}},\"404\":{\"description\":\"No appointment for this order\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/{order_id}/psc/appointment/book\":{\"parameters\":[{\"name\":\"order_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"post\":{\"operationId\":\"book_psc_appointment_v3_order__order_id__psc_appointment_book_post\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"booking depends on live provider slot state; covered by the mock-internal scheduling property suite instead\"}},\"parameters\":[{\"name\":\"x-idempotency-key\",\"in\":\"header\",\"required\":false,\"schema\":{\"type\":\"string\"}}],\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/PscAppointmentBookingRequest\"}}}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ClientFacingAppointment\"}}}},\"400\":{\"description\":\"Booking failed\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"404\":{\"description\":\"Order not found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/{order_id}/psc/appointment/reschedule\":{\"parameters\":[{\"name\":\"order_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"patch\":{\"operationId\":\"reschedule_psc_appointment_v3_order__order_id__psc_appointment_reschedule_patch\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"rescheduling depends on live provider slot state; covered by the mock-internal scheduling property suite instead\"}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/AppointmentRescheduleRequest\"}}}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ClientFacingAppointment\"}}}},\"400\":{\"description\":\"Invalid or expired booking key\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"404\":{\"description\":\"No appointment for this order\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/{order_id}/psc/appointment/cancel\":{\"parameters\":[{\"name\":\"order_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"patch\":{\"operationId\":\"cancel_psc_appointment_v3_order__order_id__psc_appointment_cancel_patch\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"cancellation depends on live provider appointment state; covered by the mock-internal scheduling property suite instead\"}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/PscAppointmentCancelRequest\"}}}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ClientFacingAppointment\"}}}},\"400\":{\"description\":\"Invalid cancellation reason\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"404\":{\"description\":\"No appointment for this order\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/{order_id}\":{\"parameters\":[{\"name\":\"order_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"get\":{\"operationId\":\"get_order_v3_order__order_id__get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/ClientFacingOrder\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/{order_id}/cancel\":{\"parameters\":[{\"name\":\"order_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"post\":{\"operationId\":\"cancel_order_v3_order__order_id__cancel_post\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/PostOrderResponse\"}}}},\"400\":{\"description\":\"Order is not in a cancellable status\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/{order_id}/test\":{\"parameters\":[{\"name\":\"order_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"post\":{\"operationId\":\"simulate_order_v3_order__order_id__test_post\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"parameters\":[{\"name\":\"final_status\",\"in\":\"query\",\"required\":true,\"schema\":{\"type\":\"string\",\"enum\":[\"received.walk_in_test.ordered\",\"received.walk_in_test.requisition_created\",\"received.walk_in_test.requisition_bypassed\",\"completed.walk_in_test.completed\",\"sample_with_lab.walk_in_test.partial_results\",\"failed.walk_in_test.sample_error\",\"cancelled.walk_in_test.cancelled\",\"collecting_sample.walk_in_test.appointment_pending\",\"collecting_sample.walk_in_test.appointment_scheduled\",\"collecting_sample.walk_in_test.appointment_cancelled\",\"collecting_sample.walk_in_test.redraw_available\",\"received.at_home_phlebotomy.ordered\",\"received.at_home_phlebotomy.requisition_created\",\"received.at_home_phlebotomy.requisition_bypassed\",\"collecting_sample.at_home_phlebotomy.appointment_pending\",\"collecting_sample.at_home_phlebotomy.appointment_scheduled\",\"collecting_sample.at_home_phlebotomy.draw_completed\",\"collecting_sample.at_home_phlebotomy.appointment_cancelled\",\"completed.at_home_phlebotomy.completed\",\"sample_with_lab.at_home_phlebotomy.partial_results\",\"cancelled.at_home_phlebotomy.cancelled\",\"failed.at_home_phlebotomy.sample_error\",\"received.testkit.ordered\",\"received.testkit.awaiting_registration\",\"received.testkit.requisition_created\",\"received.testkit.requisition_bypassed\",\"received.testkit.registered\",\"collecting_sample.testkit.transit_customer\",\"collecting_sample.testkit.out_for_delivery\",\"collecting_sample.testkit.with_customer\",\"collecting_sample.testkit.transit_lab\",\"sample_with_lab.testkit.delivered_to_lab\",\"sample_with_lab.testkit.lab_processing_blocked\",\"completed.testkit.completed\",\"failed.testkit.failure_to_deliver_to_customer\",\"failed.testkit.failure_to_deliver_to_lab\",\"failed.testkit.sample_error\",\"failed.testkit.lost\",\"cancelled.testkit.cancelled\",\"cancelled.testkit.do_not_process\",\"collecting_sample.testkit.problem_in_transit_customer\",\"collecting_sample.testkit.problem_in_transit_lab\",\"received.on_site_collection.ordered\",\"received.on_site_collection.requisition_created\",\"received.on_site_collection.requisition_bypassed\",\"sample_with_lab.on_site_collection.draw_completed\",\"completed.on_site_collection.completed\",\"cancelled.on_site_collection.cancelled\",\"sample_with_lab.on_site_collection.partial_results\",\"failed.on_site_collection.sample_error\",\"completed.walk_in_test.corrected\",\"completed.at_home_phlebotomy.corrected\",\"completed.on_site_collection.corrected\",\"completed.testkit.corrected\"]}},{\"name\":\"delay\",\"in\":\"query\",\"required\":false,\"schema\":{\"type\":\"integer\",\"minimum\":0,\"description\":\"Seconds to defer the status transition\"}}],\"requestBody\":{\"required\":false,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/SimulationFlags\"}}}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"text/plain\":{\"schema\":{\"type\":\"string\",\"examples\":[\"Success\"]}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/{order_id}/result\":{\"parameters\":[{\"name\":\"order_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"get\":{\"operationId\":\"get_result_raw_v3_order__order_id__result_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"results carry provider-side specimen data; covered by the mock-internal results property suite instead\"}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/LabResultsRaw\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/{order_id}/result/metadata\":{\"parameters\":[{\"name\":\"order_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"get\":{\"operationId\":\"get_result_metadata_v3_order__order_id__result_metadata_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/LabResultsMetadata\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/{order_id}/result/pdf\":{\"parameters\":[{\"name\":\"order_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"get\":{\"operationId\":\"get_result_pdf_v3_order__order_id__result_pdf_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"PDF bytes are provider-rendered; compared by shape (byteLength) only in the scenario script\"}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/pdf\":{\"schema\":{\"type\":\"string\",\"format\":\"binary\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order/{order_id}/requisition/pdf\":{\"parameters\":[{\"name\":\"order_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"get\":{\"operationId\":\"get_order_requisition_pdf_v3_order__order_id__requisition_pdf_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"PDF bytes are provider-rendered; compared by shape (byteLength) only in the scenario script\"}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/pdf\":{\"schema\":{\"type\":\"string\",\"format\":\"binary\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/orders\":{\"get\":{\"operationId\":\"get_orders_v3_orders_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"parameters\":[{\"name\":\"user_id\",\"in\":\"query\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"user\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}},{\"name\":\"page\",\"in\":\"query\",\"required\":false,\"schema\":{\"type\":\"integer\",\"minimum\":1,\"default\":1}},{\"name\":\"size\",\"in\":\"query\",\"required\":false,\"schema\":{\"type\":\"integer\",\"minimum\":1,\"maximum\":100,\"default\":50}}],\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/GetOrdersResponse\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}},\"422\":{\"description\":\"Validation Error\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order_transaction/{transaction_id}\":{\"parameters\":[{\"name\":\"transaction_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order_transaction\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"get\":{\"operationId\":\"get_order_transaction_v3_order_transaction__transaction_id__get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"order transactions are not available to the sandbox team (feature not available)\"}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/GetOrderTransactionResponse\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}},\"/v3/order_transaction/{transaction_id}/result\":{\"parameters\":[{\"name\":\"transaction_id\",\"in\":\"path\",\"required\":true,\"schema\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order_transaction\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}],\"get\":{\"operationId\":\"get_order_transaction_result_v3_order_transaction__transaction_id__result_get\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":false,\"safe\":true,\"reason\":\"lab results are not available to the sandbox team (feature not available)\"}},\"responses\":{\"200\":{\"description\":\"Successful Response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/LabResultsRaw\"}}}},\"404\":{\"description\":\"Not Found\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/HTTPValidationError\"}}}}}}}},\"components\":{\"securitySchemes\":{\"apiKeyAuth\":{\"type\":\"apiKey\",\"in\":\"header\",\"name\":\"x-vital-api-key\"}},\"schemas\":{\"UserCreateBody\":{\"type\":\"object\",\"required\":[\"client_user_id\"],\"properties\":{\"client_user_id\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":64,\"examples\":[\"mbr_8891\",\"patient-1042\",\"user.profile_52\"]},\"fallback_time_zone\":{\"type\":[\"string\",\"null\"],\"enum\":[\"America/Los_Angeles\",\"America/New_York\",\"Europe/London\",\"UTC\",null]}}},\"ClientFacingUser\":{\"type\":\"object\",\"required\":[\"user_id\",\"team_id\",\"client_user_id\",\"created_on\",\"connected_sources\",\"fallback_time_zone\"],\"properties\":{\"user_id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource\":{\"type\":\"user\",\"identity\":true},\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"team_id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-volatile\":{\"kind\":\"account\"}},\"client_user_id\":{\"type\":\"string\"},\"created_on\":{\"type\":\"string\",\"format\":\"date-time\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"connected_sources\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"additionalProperties\":true}},\"fallback_time_zone\":{\"type\":[\"object\",\"null\"],\"properties\":{\"id\":{\"type\":\"string\"},\"source_slug\":{\"type\":\"string\"},\"updated_at\":{\"type\":\"string\",\"format\":\"date-time\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}}}},\"fallback_birth_date\":{\"type\":[\"object\",\"null\"],\"properties\":{\"value\":{\"type\":\"string\"},\"source_slug\":{\"type\":\"string\"},\"updated_at\":{\"type\":\"string\",\"format\":\"date-time\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}}}},\"ingestion_start\":{\"type\":[\"string\",\"null\"]},\"ingestion_end\":{\"type\":[\"string\",\"null\"]}}},\"UserInfoPatchBody\":{\"type\":\"object\",\"properties\":{\"first_name\":{\"type\":[\"string\",\"null\"]},\"last_name\":{\"type\":[\"string\",\"null\"]},\"dob\":{\"type\":[\"string\",\"null\"]},\"gender\":{\"type\":[\"string\",\"null\"]},\"phone_number\":{\"type\":[\"string\",\"null\"]},\"email\":{\"type\":[\"string\",\"null\"]},\"address\":{\"type\":[\"object\",\"null\"],\"additionalProperties\":true}}},\"UserInfo\":{\"type\":\"object\",\"additionalProperties\":true},\"ClientUserIDConflictResponse\":{\"type\":\"object\",\"required\":[\"detail\"],\"properties\":{\"detail\":{\"type\":\"object\",\"required\":[\"error_type\",\"error_message\",\"user_id\",\"created_on\"],\"properties\":{\"error_type\":{\"type\":\"string\"},\"error_message\":{\"type\":\"string\"},\"user_id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"created_on\":{\"type\":\"string\",\"format\":\"date-time\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}}}}}},\"UserSuccessResponse\":{\"type\":\"object\",\"required\":[\"success\"],\"properties\":{\"success\":{\"type\":\"boolean\"}}},\"PaginatedUsersResponse\":{\"type\":\"object\",\"required\":[\"users\",\"total\",\"offset\",\"limit\"],\"properties\":{\"users\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ClientFacingUser\"}},\"total\":{\"type\":\"integer\"},\"offset\":{\"type\":\"integer\"},\"limit\":{\"type\":\"integer\"}}},\"UserPatchBody\":{\"type\":\"object\",\"properties\":{\"fallback_time_zone\":{\"type\":[\"string\",\"null\"]},\"fallback_birth_date\":{\"type\":[\"string\",\"null\"],\"format\":\"date\"},\"ingestion_start\":{\"type\":[\"string\",\"null\"],\"format\":\"date\"},\"ingestion_end\":{\"type\":[\"string\",\"null\"],\"format\":\"date\"},\"client_user_id\":{\"type\":[\"string\",\"null\"]}}},\"LabTestCollectionMethod\":{\"type\":\"string\",\"enum\":[\"testkit\",\"walk_in_test\",\"at_home_phlebotomy\",\"on_site_collection\"]},\"LabTestSampleType\":{\"type\":\"string\",\"enum\":[\"dried_blood_spot\",\"arm_collector\",\"serum\",\"saliva\",\"urine\",\"stool\"]},\"LabTestStatus\":{\"type\":\"string\",\"enum\":[\"active\",\"pending_approval\",\"inactive\"]},\"MarkerType\":{\"type\":\"string\",\"enum\":[\"biomarker\",\"panel\"]},\"ClientFacingLab\":{\"type\":\"object\",\"required\":[\"id\",\"slug\",\"name\",\"first_line_address\",\"city\",\"zipcode\",\"collection_methods\",\"sample_types\"],\"properties\":{\"id\":{\"type\":\"integer\",\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"slug\":{\"type\":\"string\"},\"name\":{\"type\":\"string\"},\"first_line_address\":{\"type\":\"string\"},\"city\":{\"type\":\"string\"},\"zipcode\":{\"type\":\"string\"},\"collection_methods\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/LabTestCollectionMethod\"}},\"sample_types\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/LabTestSampleType\"}},\"logo_url\":{\"type\":[\"string\",\"null\"]}}},\"ClientFacingMarker\":{\"type\":\"object\",\"required\":[\"id\",\"name\",\"slug\"],\"properties\":{\"id\":{\"type\":\"integer\",\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"name\":{\"type\":\"string\"},\"slug\":{\"type\":\"string\"},\"description\":{\"type\":[\"string\",\"null\"]},\"lab_id\":{\"type\":[\"integer\",\"null\"]},\"provider_id\":{\"type\":[\"string\",\"null\"]},\"type\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/MarkerType\"},{\"type\":\"null\"}]},\"unit\":{\"type\":[\"string\",\"null\"]},\"price\":{\"type\":[\"string\",\"null\"]},\"aoe\":{\"anyOf\":[{\"type\":\"object\",\"additionalProperties\":true},{\"type\":\"null\"}]},\"a_la_carte_enabled\":{\"type\":\"boolean\",\"default\":false},\"common_tat_days\":{\"type\":[\"integer\",\"null\"]},\"worst_case_tat_days\":{\"type\":[\"integer\",\"null\"]},\"is_orderable\":{\"type\":[\"boolean\",\"null\"],\"default\":true}}},\"ClientFacingLabTest\":{\"type\":\"object\",\"required\":[\"id\",\"slug\",\"name\",\"sample_type\",\"method\",\"price\",\"is_active\",\"status\",\"lab\",\"markers\"],\"properties\":{\"id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource\":{\"type\":\"lab_test\",\"identity\":true}},\"slug\":{\"type\":\"string\",\"x-mockingbird-volatile\":{\"kind\":\"token\"}},\"name\":{\"type\":\"string\",\"x-mockingbird-volatile\":{\"kind\":\"token\"}},\"sample_type\":{\"$ref\":\"#/components/schemas/LabTestSampleType\"},\"method\":{\"$ref\":\"#/components/schemas/LabTestCollectionMethod\"},\"price\":{\"type\":\"number\"},\"is_active\":{\"type\":\"boolean\"},\"status\":{\"$ref\":\"#/components/schemas/LabTestStatus\"},\"fasting\":{\"type\":\"boolean\",\"default\":false},\"lab\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/ClientFacingLab\"},{\"type\":\"null\"}]},\"markers\":{\"anyOf\":[{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ClientFacingMarker\"}},{\"type\":\"null\"}]},\"is_delegated\":{\"type\":\"boolean\",\"default\":false},\"auto_generated\":{\"type\":\"boolean\",\"default\":false},\"has_collection_instructions\":{\"type\":[\"boolean\",\"null\"]},\"common_tat_days\":{\"type\":[\"integer\",\"null\"]},\"worst_case_tat_days\":{\"type\":[\"integer\",\"null\"]}}},\"LabTestResourcesResponse\":{\"type\":\"object\",\"required\":[\"data\",\"next_cursor\"],\"properties\":{\"data\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ClientFacingLabTest\"}},\"next_cursor\":{\"type\":[\"string\",\"null\"]}}},\"LabAccountStatus\":{\"type\":\"string\",\"enum\":[\"active\",\"pending\",\"suspended\",\"ready_to_launch\"]},\"LabAccountDelegatedFlow\":{\"type\":\"string\",\"enum\":[\"order_delegated\",\"result_delegated\",\"fully_delegated\",\"not_delegated\"]},\"USState\":{\"type\":\"string\",\"enum\":[\"AL\",\"AK\",\"AZ\",\"AR\",\"CA\",\"CO\",\"CT\",\"DE\",\"FL\",\"GA\",\"HI\",\"ID\",\"IL\",\"IN\",\"IA\",\"KS\",\"KY\",\"LA\",\"ME\",\"MD\",\"MA\",\"MI\",\"MN\",\"MS\",\"MO\",\"MT\",\"NE\",\"NV\",\"NH\",\"NJ\",\"NM\",\"NY\",\"NC\",\"ND\",\"OH\",\"OK\",\"OR\",\"PA\",\"RI\",\"SC\",\"SD\",\"TN\",\"TX\",\"UT\",\"VT\",\"VA\",\"WA\",\"WV\",\"WI\",\"WY\"]},\"Labs\":{\"type\":\"string\",\"enum\":[\"ayumetrix\",\"spiriplex\",\"ussl\",\"quest\",\"sonora_quest\",\"labcorp\",\"bioreference\",\"us_biotek\",\"manual\",\"sanocardio\",\"ihd\",\"nexus\",\"my_uti\",\"crl\",\"mtl\"]},\"ClientFacingLabAccount\":{\"type\":\"object\",\"required\":[\"id\",\"lab\",\"status\",\"delegated_flow\",\"provider_account_id\",\"allowed_billing\",\"team_id_allowlist\"],\"properties\":{\"id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource\":{\"type\":\"lab_account\",\"identity\":true}},\"lab\":{\"$ref\":\"#/components/schemas/Labs\"},\"org_id\":{\"anyOf\":[{\"type\":\"string\",\"format\":\"uuid\"},{\"type\":\"null\"}]},\"status\":{\"$ref\":\"#/components/schemas/LabAccountStatus\"},\"delegated_flow\":{\"$ref\":\"#/components/schemas/LabAccountDelegatedFlow\"},\"provider_account_id\":{\"type\":\"string\"},\"account_name\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}]},\"default_clinical_notes\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}]},\"business_units\":{\"anyOf\":[{\"type\":\"array\",\"items\":{\"type\":\"string\"}},{\"type\":\"null\"}]},\"allowed_billing\":{\"type\":\"object\",\"propertyNames\":{\"$ref\":\"#/components/schemas/Billing\"},\"additionalProperties\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/USState\"}}},\"team_id_allowlist\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"format\":\"uuid\"}}}},\"GetTeamLabAccountsResponse\":{\"type\":\"object\",\"required\":[\"data\"],\"properties\":{\"data\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ClientFacingLabAccount\"}}}},\"ClientFacingResult\":{\"type\":\"object\",\"required\":[\"name\",\"slug\",\"type\"],\"properties\":{\"name\":{\"type\":\"string\"},\"slug\":{\"type\":\"string\"},\"provider_id\":{\"type\":[\"string\",\"null\"]},\"type\":{\"$ref\":\"#/components/schemas/ResultType\"},\"value\":{\"type\":[\"number\",\"null\"]},\"unit\":{\"type\":[\"string\",\"null\"]},\"low_value\":{\"type\":[\"number\",\"null\"]},\"high_value\":{\"type\":[\"number\",\"null\"]},\"string_value\":{\"type\":[\"string\",\"null\"]},\"coded_value\":{\"type\":[\"string\",\"null\"]},\"is_abnormal\":{\"type\":\"boolean\",\"default\":false},\"notes\":{\"type\":[\"string\",\"null\"]}}},\"GetMarkersResponse\":{\"type\":\"object\",\"required\":[\"markers\"],\"properties\":{\"markers\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ClientFacingMarkerComplete\"}},\"total\":{\"type\":[\"integer\",\"null\"]},\"page\":{\"type\":[\"integer\",\"null\"]},\"size\":{\"type\":[\"integer\",\"null\"]},\"pages\":{\"type\":[\"integer\",\"null\"]}}},\"ClientFacingExpectedResult\":{\"type\":\"object\",\"required\":[\"id\",\"name\",\"slug\",\"required\"],\"properties\":{\"id\":{\"type\":\"integer\",\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"name\":{\"type\":\"string\"},\"slug\":{\"type\":\"string\"},\"lab_id\":{\"type\":[\"integer\",\"null\"]},\"provider_id\":{\"type\":[\"string\",\"null\"]},\"required\":{\"type\":\"boolean\"},\"loinc\":{\"type\":[\"object\",\"null\"],\"required\":[\"id\",\"name\",\"slug\",\"code\"],\"properties\":{\"id\":{\"type\":\"integer\",\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"name\":{\"type\":\"string\"},\"slug\":{\"type\":\"string\"},\"code\":{\"type\":\"string\"},\"unit\":{\"type\":[\"string\",\"null\"]}}}}},\"ClientFacingMarkerComplete\":{\"type\":\"object\",\"required\":[\"id\",\"name\",\"slug\",\"expected_results\"],\"properties\":{\"id\":{\"type\":\"integer\",\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"name\":{\"type\":\"string\"},\"slug\":{\"type\":\"string\"},\"description\":{\"type\":[\"string\",\"null\"]},\"lab_id\":{\"type\":[\"integer\",\"null\"]},\"provider_id\":{\"type\":[\"string\",\"null\"]},\"type\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/MarkerType\"},{\"type\":\"null\"}]},\"unit\":{\"type\":[\"string\",\"null\"]},\"price\":{\"type\":[\"string\",\"null\"]},\"a_la_carte_enabled\":{\"type\":\"boolean\",\"default\":false},\"common_tat_days\":{\"type\":[\"integer\",\"null\"]},\"worst_case_tat_days\":{\"type\":[\"integer\",\"null\"]},\"is_orderable\":{\"type\":[\"boolean\",\"null\"],\"default\":true},\"expected_results\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ClientFacingExpectedResult\"}}}},\"ListOrderSetMarkersRequest\":{\"type\":\"object\",\"required\":[\"order_set_id\"],\"properties\":{\"order_set_id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order_transaction\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}},\"provider_id\":{\"type\":[\"string\",\"null\"]}}},\"AllowedRadius\":{\"type\":\"integer\",\"enum\":[10,20,25,50,100]},\"AppointmentPscLabs\":{\"type\":\"string\",\"enum\":[\"quest\"]},\"AppointmentProvider\":{\"type\":\"string\",\"enum\":[\"getlabs\",\"phlebfinders\",\"quest\"]},\"AppointmentType\":{\"type\":\"string\",\"enum\":[\"phlebotomy\",\"patient_service_center\"]},\"AppointmentStatus\":{\"type\":\"string\",\"enum\":[\"confirmed\",\"pending\",\"reserved\",\"in_progress\",\"completed\",\"cancelled\"]},\"AppointmentEventStatus\":{\"type\":\"string\",\"enum\":[\"pending\",\"reserved\",\"scheduled\",\"completed\",\"cancelled\",\"in_progress\"]},\"AppointmentServiceType\":{\"type\":\"string\",\"enum\":[\"appointment-ready\",\"appointment-request\"]},\"Billing\":{\"type\":\"string\",\"enum\":[\"client_bill\",\"commercial_insurance\",\"patient_bill_passthrough\",\"patient_bill\"]},\"LabLocationCapability\":{\"type\":\"string\",\"enum\":[\"stat\",\"appointment_scheduling_via_junction\",\"appointment_scheduling_with_lab\"]},\"LngLat\":{\"type\":\"object\",\"required\":[\"lng\",\"lat\"],\"properties\":{\"lng\":{\"type\":\"number\"},\"lat\":{\"type\":\"number\"}}},\"UsAddress\":{\"type\":\"object\",\"required\":[\"first_line\",\"city\",\"state\",\"zip_code\"],\"properties\":{\"first_line\":{\"type\":\"string\",\"minLength\":1},\"second_line\":{\"type\":[\"string\",\"null\"]},\"city\":{\"type\":\"string\",\"minLength\":1},\"state\":{\"type\":\"string\",\"minLength\":1},\"zip_code\":{\"type\":\"string\",\"minLength\":1},\"unit\":{\"type\":[\"string\",\"null\"]}}},\"AppointmentLocation\":{\"type\":\"object\",\"required\":[\"location\",\"address\",\"code\",\"name\"],\"properties\":{\"location\":{\"$ref\":\"#/components/schemas/LngLat\"},\"distance\":{\"type\":[\"number\",\"null\"]},\"address\":{\"$ref\":\"#/components/schemas/UsAddress\"},\"code\":{\"type\":\"string\"},\"name\":{\"type\":\"string\"},\"iana_timezone\":{\"type\":[\"string\",\"null\"]}}},\"TimeSlot\":{\"type\":\"object\",\"required\":[\"start\",\"end\",\"price\",\"is_priority\",\"num_appointments_available\"],\"properties\":{\"booking_key\":{\"type\":[\"string\",\"null\"],\"x-mockingbird-resource\":{\"type\":\"booking_key\",\"identity\":true},\"x-mockingbird-volatile\":{\"kind\":\"token\"}},\"start\":{\"type\":\"string\",\"format\":\"date-time\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"end\":{\"type\":\"string\",\"format\":\"date-time\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"expires_at\":{\"type\":[\"string\",\"null\"],\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"price\":{\"type\":\"number\"},\"is_priority\":{\"type\":\"boolean\"},\"num_appointments_available\":{\"type\":\"integer\"}}},\"DaySlots\":{\"type\":\"object\",\"required\":[\"date\",\"slots\"],\"properties\":{\"location\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/AppointmentLocation\"},{\"type\":\"null\"}]},\"date\":{\"type\":\"string\",\"format\":\"date\"},\"slots\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/TimeSlot\"}}}},\"AppointmentAvailabilitySlots\":{\"type\":\"object\",\"required\":[\"slots\"],\"properties\":{\"slots\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/DaySlots\"}},\"timezone\":{\"type\":[\"string\",\"null\"]}}},\"AppointmentBookingRequest\":{\"type\":\"object\",\"required\":[\"booking_key\"],\"properties\":{\"booking_key\":{\"type\":\"string\",\"minLength\":1,\"x-mockingbird-resource-ref\":{\"type\":\"booking_key\"}}}},\"AppointmentRescheduleRequest\":{\"type\":\"object\",\"required\":[\"booking_key\"],\"properties\":{\"booking_key\":{\"type\":\"string\",\"minLength\":1,\"x-mockingbird-resource-ref\":{\"type\":\"booking_key\"}}}},\"PscAppointmentBookingRequest\":{\"type\":\"object\",\"required\":[\"booking_key\",\"site_code\"],\"properties\":{\"booking_key\":{\"type\":\"string\",\"minLength\":1,\"x-mockingbird-resource-ref\":{\"type\":\"booking_key\"}},\"site_code\":{\"type\":\"string\",\"minLength\":1}}},\"PhlebotomyAppointmentCancelRequest\":{\"type\":\"object\",\"required\":[\"cancellation_reason_id\"],\"properties\":{\"cancellation_reason_id\":{\"type\":\"string\",\"minLength\":1},\"notes\":{\"type\":[\"string\",\"null\"]}}},\"PscAppointmentCancelRequest\":{\"type\":\"object\",\"required\":[\"cancellationReasonId\"],\"properties\":{\"cancellationReasonId\":{\"type\":\"string\",\"minLength\":1},\"note\":{\"type\":[\"string\",\"null\"]}}},\"ClientFacingAppointmentEvent\":{\"type\":\"object\",\"required\":[\"created_at\",\"status\"],\"properties\":{\"created_at\":{\"type\":\"string\",\"format\":\"date-time\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"status\":{\"$ref\":\"#/components/schemas/AppointmentEventStatus\"},\"data\":{\"anyOf\":[{\"type\":\"object\",\"additionalProperties\":true},{\"type\":\"null\"}]}}},\"ClientFacingAppointment\":{\"type\":\"object\",\"required\":[\"id\",\"user_id\",\"order_id\",\"address\",\"location\",\"type\",\"provider\",\"status\",\"provider_id\",\"can_reschedule\",\"event_status\",\"events\"],\"properties\":{\"id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource\":{\"type\":\"appointment\",\"identity\":true},\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"user_id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"user\"}},\"order_id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"order\"}},\"address\":{\"$ref\":\"#/components/schemas/UsAddress\"},\"location\":{\"$ref\":\"#/components/schemas/LngLat\"},\"start_at\":{\"anyOf\":[{\"type\":\"string\",\"format\":\"date-time\"},{\"type\":\"null\"}],\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"end_at\":{\"anyOf\":[{\"type\":\"string\",\"format\":\"date-time\"},{\"type\":\"null\"}],\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"iana_timezone\":{\"type\":[\"string\",\"null\"]},\"type\":{\"$ref\":\"#/components/schemas/AppointmentType\"},\"provider\":{\"$ref\":\"#/components/schemas/AppointmentProvider\"},\"status\":{\"$ref\":\"#/components/schemas/AppointmentStatus\"},\"provider_id\":{\"type\":\"string\",\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"external_id\":{\"type\":[\"string\",\"null\"],\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"can_reschedule\":{\"type\":\"boolean\"},\"event_status\":{\"$ref\":\"#/components/schemas/AppointmentEventStatus\"},\"event_data\":{\"anyOf\":[{\"type\":\"object\",\"additionalProperties\":true},{\"type\":\"null\"}]},\"order_transaction_id\":{\"type\":[\"string\",\"null\"],\"x-mockingbird-resource-ref\":{\"type\":\"order_transaction\"}},\"appointment_notes\":{\"type\":[\"string\",\"null\"]},\"events\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ClientFacingAppointmentEvent\"}}}},\"ClientFacingAppointmentCancellationReason\":{\"type\":\"object\",\"required\":[\"id\",\"name\",\"is_refundable\"],\"properties\":{\"id\":{\"type\":\"string\",\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"name\":{\"type\":\"string\"},\"is_refundable\":{\"type\":\"boolean\"}}},\"PhlebotomyAreaInfo\":{\"type\":\"object\",\"required\":[\"is_served\",\"providers\"],\"properties\":{\"is_served\":{\"type\":\"boolean\"},\"providers\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/PhlebotomyProviderInfo\"}}}},\"PhlebotomyProviderInfo\":{\"type\":\"object\",\"required\":[\"name\",\"service_types\"],\"properties\":{\"name\":{\"$ref\":\"#/components/schemas/AppointmentProvider\"},\"service_types\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/AppointmentServiceType\"}}}},\"PscAreaInfoDetails\":{\"type\":\"object\",\"required\":[\"appointment_with_vital\",\"within_radius\",\"radius\"],\"properties\":{\"appointment_with_vital\":{\"type\":\"boolean\"},\"within_radius\":{\"type\":\"number\"},\"radius\":{\"type\":\"string\"},\"capabilities\":{\"type\":[\"array\",\"null\"],\"items\":{\"$ref\":\"#/components/schemas/LabLocationCapability\"}}}},\"PscAreaInfo\":{\"type\":\"object\",\"required\":[\"patient_service_centers\",\"supported_bill_types\",\"lab_id\"],\"properties\":{\"patient_service_centers\":{\"$ref\":\"#/components/schemas/PscAreaInfoDetails\"},\"supported_bill_types\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/Billing\"}},\"lab_id\":{\"type\":\"integer\"}}},\"AreaInfo\":{\"type\":\"object\",\"required\":[\"zip_code\",\"phlebotomy\",\"central_labs\"],\"properties\":{\"zip_code\":{\"type\":\"string\"},\"phlebotomy\":{\"$ref\":\"#/components/schemas/PhlebotomyAreaInfo\"},\"central_labs\":{\"type\":\"object\",\"additionalProperties\":{\"$ref\":\"#/components/schemas/PscAreaInfo\"}}}},\"LabLocationMetadata\":{\"type\":\"object\",\"required\":[\"name\",\"state\",\"city\",\"zip_code\",\"first_line\"],\"properties\":{\"name\":{\"type\":\"string\"},\"state\":{\"type\":\"string\"},\"city\":{\"type\":\"string\"},\"zip_code\":{\"type\":\"string\"},\"first_line\":{\"type\":\"string\"},\"second_line\":{\"type\":[\"string\",\"null\"]},\"phone_number\":{\"type\":[\"string\",\"null\"]},\"fax_number\":{\"type\":[\"string\",\"null\"]},\"hours\":{\"type\":[\"object\",\"null\"],\"additionalProperties\":true}}},\"ClientFacingLabLocation\":{\"type\":\"object\",\"required\":[\"metadata\",\"distance\",\"site_code\",\"supported_bill_types\",\"location\",\"capabilities\"],\"properties\":{\"metadata\":{\"$ref\":\"#/components/schemas/LabLocationMetadata\"},\"distance\":{\"type\":\"number\"},\"site_code\":{\"type\":\"string\"},\"supported_bill_types\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/Billing\"}},\"location\":{\"$ref\":\"#/components/schemas/LngLat\"},\"capabilities\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/LabLocationCapability\"}}}},\"PscInfo\":{\"type\":\"object\",\"required\":[\"lab_id\",\"slug\",\"patient_service_centers\"],\"properties\":{\"lab_id\":{\"type\":\"integer\"},\"slug\":{\"type\":\"string\"},\"patient_service_centers\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ClientFacingLabLocation\"}}}},\"OrderTopLevelStatus\":{\"type\":\"string\",\"enum\":[\"received\",\"collecting_sample\",\"sample_with_lab\",\"completed\",\"cancelled\",\"failed\"]},\"OrderLowLevelStatus\":{\"type\":\"string\",\"enum\":[\"ordered\",\"requisition_created\",\"requisition_bypassed\",\"transit_customer\",\"out_for_delivery\",\"with_customer\",\"transit_lab\",\"delivered_to_lab\",\"completed\",\"failure_to_deliver_to_lab\",\"failure_to_deliver_to_customer\",\"problem_in_transit_lab\",\"problem_in_transit_customer\",\"sample_error\",\"appointment_scheduled\",\"appointment_cancelled\",\"appointment_pending\",\"draw_completed\",\"cancelled\",\"lost\",\"do_not_process\",\"partial_results\",\"awaiting_registration\",\"registered\",\"redraw_available\",\"corrected\",\"lab_processing_blocked\"]},\"OrderStatus\":{\"type\":\"string\",\"enum\":[\"received.walk_in_test.ordered\",\"received.walk_in_test.requisition_created\",\"received.walk_in_test.requisition_bypassed\",\"completed.walk_in_test.completed\",\"sample_with_lab.walk_in_test.partial_results\",\"failed.walk_in_test.sample_error\",\"cancelled.walk_in_test.cancelled\",\"collecting_sample.walk_in_test.appointment_pending\",\"collecting_sample.walk_in_test.appointment_scheduled\",\"collecting_sample.walk_in_test.appointment_cancelled\",\"collecting_sample.walk_in_test.redraw_available\",\"received.at_home_phlebotomy.ordered\",\"received.at_home_phlebotomy.requisition_created\",\"received.at_home_phlebotomy.requisition_bypassed\",\"collecting_sample.at_home_phlebotomy.appointment_pending\",\"collecting_sample.at_home_phlebotomy.appointment_scheduled\",\"collecting_sample.at_home_phlebotomy.draw_completed\",\"collecting_sample.at_home_phlebotomy.appointment_cancelled\",\"completed.at_home_phlebotomy.completed\",\"sample_with_lab.at_home_phlebotomy.partial_results\",\"cancelled.at_home_phlebotomy.cancelled\",\"failed.at_home_phlebotomy.sample_error\",\"received.testkit.ordered\",\"received.testkit.awaiting_registration\",\"received.testkit.requisition_created\",\"received.testkit.requisition_bypassed\",\"received.testkit.registered\",\"collecting_sample.testkit.transit_customer\",\"collecting_sample.testkit.out_for_delivery\",\"collecting_sample.testkit.with_customer\",\"collecting_sample.testkit.transit_lab\",\"sample_with_lab.testkit.delivered_to_lab\",\"sample_with_lab.testkit.lab_processing_blocked\",\"completed.testkit.completed\",\"failed.testkit.failure_to_deliver_to_customer\",\"failed.testkit.failure_to_deliver_to_lab\",\"failed.testkit.sample_error\",\"failed.testkit.lost\",\"cancelled.testkit.cancelled\",\"cancelled.testkit.do_not_process\",\"collecting_sample.testkit.problem_in_transit_customer\",\"collecting_sample.testkit.problem_in_transit_lab\",\"received.on_site_collection.ordered\",\"received.on_site_collection.requisition_created\",\"received.on_site_collection.requisition_bypassed\",\"sample_with_lab.on_site_collection.draw_completed\",\"completed.on_site_collection.completed\",\"cancelled.on_site_collection.cancelled\",\"sample_with_lab.on_site_collection.partial_results\",\"failed.on_site_collection.sample_error\",\"completed.walk_in_test.corrected\",\"completed.at_home_phlebotomy.corrected\",\"completed.on_site_collection.corrected\",\"completed.testkit.corrected\"]},\"OrderStatusDetail\":{\"type\":\"string\",\"enum\":[\"fulfillment_error\",\"date_of_collection_unspecified\",\"demographic_information_unspecified\",\"demographic_information_mismatch\",\"sample_quantity_not_sufficient\",\"sample_contaminated\",\"sample_stability_exceeded\",\"sample_hemolyzed\",\"sample_improper_collection\"]},\"OrderTransactionStatus\":{\"type\":\"string\",\"enum\":[\"active\",\"completed\",\"cancelled\"]},\"ClientFacingOrderEvent\":{\"type\":\"object\",\"required\":[\"id\",\"created_at\",\"status\"],\"properties\":{\"id\":{\"type\":\"integer\",\"x-mockingbird-volatile\":{\"kind\":\"opaque\"}},\"created_at\":{\"type\":\"string\",\"format\":\"date-time\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"status\":{\"$ref\":\"#/components/schemas/OrderStatus\"},\"status_detail\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/OrderStatusDetail\"},{\"type\":\"null\"}]}}},\"ShippingAddress\":{\"type\":\"object\",\"required\":[\"receiver_name\",\"first_line\",\"city\",\"state\",\"zip\",\"country\",\"phone_number\"],\"properties\":{\"receiver_name\":{\"type\":\"string\"},\"first_line\":{\"type\":\"string\"},\"second_line\":{\"type\":[\"string\",\"null\"]},\"city\":{\"type\":\"string\"},\"state\":{\"type\":\"string\"},\"zip\":{\"type\":\"string\"},\"country\":{\"type\":\"string\"},\"phone_number\":{\"type\":\"string\"}}},\"ClientFacingPhysician\":{\"type\":\"object\",\"required\":[\"first_name\",\"last_name\",\"npi\"],\"properties\":{\"first_name\":{\"type\":\"string\"},\"last_name\":{\"type\":\"string\"},\"npi\":{\"type\":\"string\"}}},\"ClientFacingShipment\":{\"type\":\"object\",\"required\":[\"id\",\"outbound_tracking_number\",\"outbound_tracking_url\",\"inbound_tracking_number\",\"inbound_tracking_url\",\"outbound_courier\",\"inbound_courier\",\"notes\"],\"properties\":{\"id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"outbound_tracking_number\":{\"type\":[\"string\",\"null\"]},\"outbound_tracking_url\":{\"type\":[\"string\",\"null\"]},\"inbound_tracking_number\":{\"type\":[\"string\",\"null\"]},\"inbound_tracking_url\":{\"type\":[\"string\",\"null\"]},\"outbound_courier\":{\"type\":[\"string\",\"null\"]},\"inbound_courier\":{\"type\":[\"string\",\"null\"]},\"notes\":{\"type\":[\"string\",\"null\"]}}},\"ClientFacingTestkitOrder\":{\"type\":\"object\",\"required\":[\"id\",\"shipment\",\"created_at\",\"updated_at\"],\"properties\":{\"id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"shipment\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/ClientFacingShipment\"},{\"type\":\"null\"}],\"x-mockingbird-volatile\":{\"kind\":\"opaque\"}},\"created_at\":{\"type\":\"string\",\"format\":\"date-time\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"updated_at\":{\"type\":\"string\",\"format\":\"date-time\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}}}},\"ClientFacingWalkInOrder\":{\"type\":\"object\",\"required\":[\"id\",\"appointment_id\",\"created_at\",\"updated_at\"],\"properties\":{\"id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"appointment_id\":{\"anyOf\":[{\"type\":\"string\",\"format\":\"uuid\"},{\"type\":\"null\"}]},\"created_at\":{\"type\":\"string\",\"format\":\"date-time\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"updated_at\":{\"type\":\"string\",\"format\":\"date-time\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}}}},\"ClientFacingTestKitOrderDetails\":{\"type\":\"object\",\"required\":[\"type\"],\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"testkit\",\"walk_in_test\",\"at_home_phlebotomy\",\"on_site_collection\"]},\"data\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/ClientFacingTestkitOrder\"},{\"$ref\":\"#/components/schemas/ClientFacingWalkInOrder\"},{\"type\":\"null\"}]}}},\"ClientFacingPatientDetailsCompatible\":{\"type\":\"object\",\"required\":[\"first_name\",\"last_name\",\"dob\",\"gender\",\"phone_number\",\"email\"],\"properties\":{\"first_name\":{\"type\":\"string\",\"minLength\":1,\"pattern\":\"^[a-zA-Z0-9][a-zA-Z0-9 .,'-]*$\",\"examples\":[\"Ada\",\"Chris\",\"Maria\",\"Jun\"]},\"last_name\":{\"type\":\"string\",\"minLength\":1,\"pattern\":\"^[a-zA-Z0-9][a-zA-Z0-9 .,'-]*$\",\"examples\":[\"Lovelace\",\"Vouga\",\"Delgado\",\"Park\"]},\"dob\":{\"type\":\"string\",\"format\":\"date-time\",\"examples\":[\"1990-06-15T00:00:00.000Z\",\"1983-02-02T00:00:00.000Z\"]},\"gender\":{\"type\":\"string\",\"minLength\":1,\"pattern\":\"\\\\\\\\S\",\"examples\":[\"male\",\"female\",\"other\",\"prefer_not_to_say\"]},\"phone_number\":{\"type\":\"string\",\"minLength\":1,\"pattern\":\"^\\\\\\\\+1[2-9]\\\\\\\\d{9}$\",\"examples\":[\"+14155550123\",\"+12125550987\",\"+13105554444\"]},\"email\":{\"type\":\"string\",\"format\":\"email\",\"minLength\":1,\"examples\":[\"ada@example.com\",\"chris@example.com\",\"maria@example.com\"]}}},\"PatientAddressCompatible\":{\"type\":\"object\",\"required\":[\"first_line\",\"city\",\"state\",\"zip\",\"country\"],\"properties\":{\"receiver_name\":{\"type\":\"string\",\"default\":\"\",\"examples\":[\"Ada Lovelace\",\"Chris Vouga\"]},\"first_line\":{\"type\":\"string\",\"minLength\":1,\"pattern\":\"\\\\\\\\S\",\"examples\":[\"1 Main St\",\"450 Market St\",\"88 Kearny St\"]},\"second_line\":{\"type\":[\"string\",\"null\"]},\"city\":{\"type\":\"string\",\"minLength\":1,\"pattern\":\"\\\\\\\\S\",\"examples\":[\"San Diego\",\"San Francisco\",\"New York\"]},\"state\":{\"type\":\"string\",\"minLength\":1,\"enum\":[\"AL\",\"AK\",\"AZ\",\"AR\",\"CA\",\"CO\",\"CT\",\"DE\",\"FL\",\"GA\",\"HI\",\"ID\",\"IL\",\"IN\",\"IA\",\"KS\",\"KY\",\"LA\",\"ME\",\"MD\",\"MA\",\"MI\",\"MN\",\"MS\",\"MO\",\"MT\",\"NE\",\"NV\",\"NH\",\"NJ\",\"NM\",\"NY\",\"NC\",\"ND\",\"OH\",\"OK\",\"OR\",\"PA\",\"RI\",\"SC\",\"SD\",\"TN\",\"TX\",\"UT\",\"VT\",\"VA\",\"WA\",\"WV\",\"WI\",\"WY\"]},\"zip\":{\"type\":\"string\",\"pattern\":\"^\\\\\\\\d{5}(-\\\\\\\\d{4})?$\",\"examples\":[\"92101\",\"94105\",\"10001\"]},\"country\":{\"type\":\"string\",\"minLength\":1,\"pattern\":\"\\\\\\\\S\",\"examples\":[\"US\"]},\"access_notes\":{\"type\":[\"string\",\"null\"],\"examples\":[null]},\"phone_number\":{\"type\":[\"string\",\"null\"],\"examples\":[\"+14155550123\",null]}}},\"AoeAnswerRequest\":{\"type\":\"object\",\"required\":[\"marker_id\",\"question_id\",\"answer\"],\"properties\":{\"marker_id\":{\"type\":\"integer\",\"examples\":[2075,1975]},\"question_id\":{\"type\":\"integer\",\"examples\":[1]},\"answer\":{\"type\":\"string\",\"minLength\":1,\"examples\":[\"No\",\"Yes\"]}}},\"ClientFacingOrderInTransaction\":{\"type\":\"object\",\"required\":[\"id\",\"created_at\",\"updated_at\"],\"properties\":{\"id\":{\"type\":\"string\",\"format\":\"uuid\"},\"low_level_status\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/OrderLowLevelStatus\"},{\"type\":\"null\"}]},\"low_level_status_created_at\":{\"anyOf\":[{\"type\":\"string\",\"format\":\"date-time\"},{\"type\":\"null\"}],\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"created_at\":{\"type\":\"string\",\"format\":\"date-time\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"updated_at\":{\"type\":\"string\",\"format\":\"date-time\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}}}},\"ClientFacingOrderTransaction\":{\"type\":\"object\",\"required\":[\"id\",\"status\",\"orders\"],\"properties\":{\"id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource\":{\"type\":\"order_transaction\",\"identity\":true},\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"status\":{\"$ref\":\"#/components/schemas/OrderTransactionStatus\"},\"orders\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ClientFacingOrderInTransaction\"}}}},\"OrderSummary\":{\"type\":\"object\",\"required\":[\"id\",\"last_status\",\"last_status_created_at\",\"updated_at\",\"created_at\"],\"properties\":{\"id\":{\"type\":\"string\",\"format\":\"uuid\"},\"origin\":{\"anyOf\":[{\"type\":\"string\",\"enum\":[\"initial\",\"redraw\",\"recreation\"]},{\"type\":\"null\"}]},\"parent_id\":{\"anyOf\":[{\"type\":\"string\",\"format\":\"uuid\"},{\"type\":\"null\"}]},\"last_status\":{\"$ref\":\"#/components/schemas/OrderLowLevelStatus\"},\"last_status_created_at\":{\"type\":\"string\",\"format\":\"date-time\"},\"updated_at\":{\"type\":\"string\",\"format\":\"date-time\"},\"created_at\":{\"type\":\"string\",\"format\":\"date-time\"}}},\"GetOrderTransactionResponse\":{\"type\":\"object\",\"required\":[\"id\",\"team_id\",\"status\"],\"properties\":{\"id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource\":{\"type\":\"order_transaction\",\"identity\":true},\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"team_id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-volatile\":{\"kind\":\"account\"}},\"status\":{\"$ref\":\"#/components/schemas/OrderTransactionStatus\"},\"orders\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/OrderSummary\"}}}},\"ClientFacingOrder\":{\"type\":\"object\",\"required\":[\"user_id\",\"id\",\"team_id\",\"patient_details\",\"patient_address\",\"lab_test\",\"details\",\"sample_id\",\"notes\",\"created_at\",\"updated_at\",\"events\",\"last_event\",\"health_insurance_id\",\"requisition_form_url\",\"shipping_details\",\"has_abn\"],\"properties\":{\"user_id\":{\"type\":\"string\",\"format\":\"uuid\"},\"id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource\":{\"type\":\"order\",\"identity\":true},\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"team_id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-volatile\":{\"kind\":\"account\"}},\"patient_details\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/ClientFacingPatientDetailsCompatible\"},{\"type\":\"null\"}]},\"patient_address\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/PatientAddressCompatible\"},{\"type\":\"null\"}]},\"lab_test\":{\"$ref\":\"#/components/schemas/ClientFacingLabTest\"},\"details\":{\"$ref\":\"#/components/schemas/ClientFacingTestKitOrderDetails\"},\"sample_id\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}],\"x-mockingbird-volatile\":{\"kind\":\"opaque\"}},\"notes\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}]},\"clinical_notes\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}]},\"created_at\":{\"type\":\"string\",\"format\":\"date-time\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"updated_at\":{\"type\":\"string\",\"format\":\"date-time\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"events\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ClientFacingOrderEvent\"}},\"status\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/OrderTopLevelStatus\"},{\"type\":\"null\"}],\"x-mockingbird-volatile\":{\"kind\":\"opaque\"}},\"last_event\":{\"$ref\":\"#/components/schemas/ClientFacingOrderEvent\"},\"physician\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/ClientFacingPhysician\"},{\"type\":\"null\"}]},\"health_insurance_id\":{\"anyOf\":[{\"type\":\"string\",\"format\":\"uuid\"},{\"type\":\"null\"}]},\"requisition_form_url\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}],\"x-mockingbird-volatile\":{\"kind\":\"url\"}},\"priority\":{\"type\":\"boolean\",\"default\":false},\"shipping_details\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/ShippingAddress\"},{\"type\":\"null\"}]},\"activate_by\":{\"anyOf\":[{\"type\":\"string\",\"format\":\"date\"},{\"type\":\"null\"}]},\"passthrough\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}]},\"billing_type\":{\"type\":\"string\",\"enum\":[\"client_bill\",\"commercial_insurance\",\"patient_bill_passthrough\",\"patient_bill\",\"upfront_payment\"],\"default\":\"client_bill\"},\"icd_codes\":{\"anyOf\":[{\"type\":\"array\",\"items\":{\"type\":\"string\"}},{\"type\":\"null\"}]},\"has_abn\":{\"type\":\"boolean\"},\"interpretation\":{\"anyOf\":[{\"type\":\"string\",\"enum\":[\"normal\",\"abnormal\",\"critical\",\"unknown\"]},{\"type\":\"null\"}]},\"has_missing_results\":{\"anyOf\":[{\"type\":\"boolean\"},{\"type\":\"null\"}]},\"expected_result_by_date\":{\"anyOf\":[{\"type\":\"string\",\"format\":\"date\"},{\"type\":\"null\"}]},\"worst_case_result_by_date\":{\"anyOf\":[{\"type\":\"string\",\"format\":\"date\"},{\"type\":\"null\"}]},\"origin\":{\"anyOf\":[{\"type\":\"string\",\"enum\":[\"initial\",\"redraw\",\"recreation\"]},{\"type\":\"null\"}]},\"order_transaction\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/ClientFacingOrderTransaction\"},{\"type\":\"null\"}]}}},\"OrderSetRequest\":{\"type\":\"object\",\"required\":[\"lab_test_ids\"],\"properties\":{\"lab_test_ids\":{\"type\":\"array\",\"minItems\":1,\"items\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"lab_test\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}}}}},\"CreateOrderRequest\":{\"type\":\"object\",\"required\":[\"user_id\",\"patient_details\",\"patient_address\",\"order_set\"],\"properties\":{\"user_id\":{\"type\":\"string\",\"format\":\"uuid\",\"x-mockingbird-resource-ref\":{\"type\":\"user\",\"missing\":\"00000000-0000-4000-8000-000000000000\"}},\"patient_details\":{\"$ref\":\"#/components/schemas/ClientFacingPatientDetailsCompatible\"},\"patient_address\":{\"$ref\":\"#/components/schemas/PatientAddressCompatible\"},\"order_set\":{\"$ref\":\"#/components/schemas/OrderSetRequest\"},\"clinical_notes\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}]},\"passthrough\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}]},\"collection_method\":{\"$ref\":\"#/components/schemas/LabTestCollectionMethod\"},\"lab_account_id\":{\"anyOf\":[{\"type\":\"string\",\"format\":\"uuid\"},{\"type\":\"null\"}]},\"idempotency_key\":{\"type\":[\"string\",\"null\"]},\"idempotency_error\":{\"type\":[\"string\",\"null\"]},\"aoe_answers\":{\"type\":[\"array\",\"null\"],\"items\":{\"$ref\":\"#/components/schemas/AoeAnswerRequest\"}}}},\"PostOrderResponse\":{\"type\":\"object\",\"required\":[\"order\",\"status\",\"message\"],\"properties\":{\"order\":{\"$ref\":\"#/components/schemas/ClientFacingOrder\"},\"status\":{\"type\":\"string\"},\"message\":{\"type\":\"string\"}}},\"ResultType\":{\"type\":\"string\",\"enum\":[\"numeric\",\"range\",\"comment\",\"coded_value\"]},\"ParentBiomarkerData\":{\"type\":\"object\",\"required\":[\"marker_id\",\"name\",\"slug\"],\"properties\":{\"marker_id\":{\"type\":\"integer\"},\"name\":{\"type\":\"string\"},\"slug\":{\"type\":\"string\"},\"provider_id\":{\"type\":[\"string\",\"null\"]}}},\"BiomarkerResult\":{\"type\":\"object\",\"required\":[\"name\",\"result\",\"type\"],\"properties\":{\"name\":{\"type\":\"string\"},\"slug\":{\"type\":\"string\",\"default\":\"\"},\"value\":{\"anyOf\":[{\"type\":\"number\"},{\"type\":\"null\"}]},\"result\":{\"type\":\"string\"},\"type\":{\"$ref\":\"#/components/schemas/ResultType\"},\"unit\":{\"type\":[\"string\",\"null\"]},\"timestamp\":{\"anyOf\":[{\"type\":\"string\",\"format\":\"date-time\"},{\"type\":\"null\"}],\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"notes\":{\"type\":[\"string\",\"null\"]},\"reference_range\":{\"type\":[\"string\",\"null\"]},\"min_range_value\":{\"type\":[\"number\",\"null\"]},\"max_range_value\":{\"type\":[\"number\",\"null\"]},\"is_above_max_range\":{\"type\":[\"boolean\",\"null\"]},\"is_below_min_range\":{\"type\":[\"boolean\",\"null\"]},\"interpretation\":{\"type\":\"string\",\"default\":\"normal\"},\"source_interpretation\":{\"type\":\"string\",\"default\":\"\"},\"loinc\":{\"type\":[\"string\",\"null\"]},\"loinc_slug\":{\"type\":[\"string\",\"null\"]},\"provider_id\":{\"type\":[\"string\",\"null\"]},\"source_markers\":{\"anyOf\":[{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ParentBiomarkerData\"}},{\"type\":\"null\"}]},\"performing_laboratory\":{\"type\":[\"string\",\"null\"]},\"source_sample_id\":{\"type\":[\"string\",\"null\"]}}},\"FailureType\":{\"type\":\"string\",\"enum\":[\"quantity_not_sufficient_failure\",\"collection_process_failure\",\"drop_off_failure\",\"internal_lab_failure\",\"order_entry_failure\",\"non_failure\",\"unknown_failure\",\"patient_condition_failure\",\"missing_result_calc_failure\",\"missing_demo_aoe_calc_failure\",\"insufficient_volume\"]},\"MissingBiomarkerResult\":{\"type\":\"object\",\"required\":[\"name\",\"slug\",\"inferred_failure_type\"],\"properties\":{\"name\":{\"type\":\"string\"},\"slug\":{\"type\":\"string\"},\"inferred_failure_type\":{\"$ref\":\"#/components/schemas/FailureType\"},\"note\":{\"type\":[\"string\",\"null\"]},\"loinc\":{\"type\":[\"string\",\"null\"]},\"loinc_slug\":{\"type\":[\"string\",\"null\"]},\"provider_id\":{\"type\":[\"string\",\"null\"]},\"source_markers\":{\"anyOf\":[{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ParentBiomarkerData\"}},{\"type\":\"null\"}]}}},\"SampleData\":{\"type\":\"object\",\"properties\":{\"sample_id\":{\"type\":[\"string\",\"null\"]},\"control_number\":{\"type\":[\"string\",\"null\"]},\"date_collected\":{\"type\":[\"string\",\"null\"]},\"date_received\":{\"type\":[\"string\",\"null\"]},\"date_reported\":{\"type\":[\"string\",\"null\"]},\"performing_laboratories\":{\"anyOf\":[{\"type\":\"object\",\"additionalProperties\":true},{\"type\":\"null\"}]},\"clinical_information\":{\"anyOf\":[{\"type\":\"object\",\"additionalProperties\":true},{\"type\":\"null\"}]}}},\"LabResultsMetadata\":{\"type\":\"object\",\"required\":[\"age\",\"dob\",\"patient\",\"date_reported\",\"specimen_number\"],\"properties\":{\"age\":{\"type\":\"string\",\"x-mockingbird-volatile\":{\"kind\":\"token\"}},\"dob\":{\"type\":\"string\",\"x-mockingbird-volatile\":{\"kind\":\"token\"}},\"clia_#\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}]},\"patient\":{\"type\":\"string\",\"x-mockingbird-volatile\":{\"kind\":\"token\"}},\"provider\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}],\"x-mockingbird-volatile\":{\"kind\":\"token\"}},\"laboratory\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}],\"x-mockingbird-volatile\":{\"kind\":\"token\"}},\"date_reported\":{\"type\":\"string\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"date_collected\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}],\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"specimen_number\":{\"type\":\"string\",\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"date_received\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}],\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"status\":{\"type\":\"string\",\"default\":\"final\"},\"interpretation\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}]},\"patient_id\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}],\"x-mockingbird-volatile\":{\"kind\":\"id\"}},\"account_id\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"null\"}],\"x-mockingbird-volatile\":{\"kind\":\"id\"}}}},\"LabResultsRaw\":{\"type\":\"object\",\"required\":[\"metadata\",\"results\"],\"properties\":{\"metadata\":{\"$ref\":\"#/components/schemas/LabResultsMetadata\"},\"results\":{\"anyOf\":[{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/BiomarkerResult\"}},{\"type\":\"object\",\"additionalProperties\":true}],\"x-mockingbird-volatile\":{\"kind\":\"opaque\"}},\"missing_results\":{\"anyOf\":[{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/MissingBiomarkerResult\"}},{\"type\":\"null\"}],\"x-mockingbird-volatile\":{\"kind\":\"opaque\"}},\"sample_information\":{\"anyOf\":[{\"type\":\"object\",\"additionalProperties\":{\"$ref\":\"#/components/schemas/SampleData\"}},{\"type\":\"null\"}],\"x-mockingbird-volatile\":{\"kind\":\"opaque\"}},\"order_transaction\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/ClientFacingOrderTransaction\"},{\"type\":\"null\"}]}}},\"SimulationFlags\":{\"type\":\"object\",\"properties\":{\"interpretation\":{\"anyOf\":[{\"type\":\"string\",\"enum\":[\"normal\",\"abnormal\",\"critical\",\"unknown\"]},{\"type\":\"null\"}]},\"result_types\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ResultType\"}},\"has_missing_results\":{\"type\":\"boolean\"}}},\"GetOrdersResponse\":{\"type\":\"object\",\"required\":[\"orders\"],\"properties\":{\"orders\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/ClientFacingOrder\"}},\"total\":{\"anyOf\":[{\"type\":\"integer\"},{\"type\":\"null\"}]},\"page\":{\"anyOf\":[{\"type\":\"integer\"},{\"type\":\"null\"}]},\"size\":{\"anyOf\":[{\"type\":\"integer\"},{\"type\":\"null\"}]}}},\"HTTPValidationError\":{\"type\":\"object\",\"properties\":{\"detail\":{\"title\":\"Detail\"}}}}}}`) as OpenAPIDocument\n\nexport type OperationId = \"get_teams_users_v2_user_get\" | \"create_user_v2_user_post\" | \"get_user_v2_user__user_id__get\" | \"delete_user_v2_user__user_id__delete\" | \"patch_user_v2_user__user_id__patch\" | \"get_user_by_client_user_id_v2_user_resolve__client_user_id__get\" | \"patch_user_info_v2_user__user_id__info_patch\" | \"get_latest_user_info_user_v2_user__user_id__info_latest_get\" | \"get_paginated_lab_tests_for_team_v3_lab_test_get\" | \"get_team_lab_accounts_v3_lab_test_lab_account_get\" | \"get_lab_test_for_team_v3_lab_tests__lab_test_id__get\" | \"get_labs_v3_lab_tests_labs_get\" | \"get_markers_for_lab_test_v3_lab_tests__lab_test_id__markers_get\" | \"list_order_set_markers_v3_lab_tests_list_order_set_markers_post\" | \"create_order_v3_order_post\" | \"get_area_info_v3_order_area_info_get\" | \"get_psc_info_v3_order_psc_info_get\" | \"get_phlebotomy_appointment_availability_v3_order_phlebotomy_appointment_availability_post\" | \"get_phlebotomy_appointment_cancellation_reason_v3_order_phlebotomy_appointment_cancellation_reasons_get\" | \"get_psc_appointment_availability_v3_order_psc_appointment_availability_post\" | \"get_psc_appointment_cancellation_reason_v3_order_psc_appointment_cancellation_reasons_get\" | \"get_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_get\" | \"book_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_book_post\" | \"reschedule_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_reschedule_patch\" | \"cancel_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_cancel_patch\" | \"get_psc_appointment_v3_order__order_id__psc_appointment_get\" | \"book_psc_appointment_v3_order__order_id__psc_appointment_book_post\" | \"reschedule_psc_appointment_v3_order__order_id__psc_appointment_reschedule_patch\" | \"cancel_psc_appointment_v3_order__order_id__psc_appointment_cancel_patch\" | \"get_order_v3_order__order_id__get\" | \"cancel_order_v3_order__order_id__cancel_post\" | \"simulate_order_v3_order__order_id__test_post\" | \"get_result_raw_v3_order__order_id__result_get\" | \"get_result_metadata_v3_order__order_id__result_metadata_get\" | \"get_result_pdf_v3_order__order_id__result_pdf_get\" | \"get_order_requisition_pdf_v3_order__order_id__requisition_pdf_get\" | \"get_orders_v3_orders_get\" | \"get_order_transaction_v3_order_transaction__transaction_id__get\" | \"get_order_transaction_result_v3_order_transaction__transaction_id__result_get\"\nexport type SupportedOperationId = \"get_teams_users_v2_user_get\" | \"create_user_v2_user_post\" | \"get_user_v2_user__user_id__get\" | \"delete_user_v2_user__user_id__delete\" | \"patch_user_v2_user__user_id__patch\" | \"get_user_by_client_user_id_v2_user_resolve__client_user_id__get\" | \"patch_user_info_v2_user__user_id__info_patch\" | \"get_latest_user_info_user_v2_user__user_id__info_latest_get\" | \"get_paginated_lab_tests_for_team_v3_lab_test_get\" | \"get_team_lab_accounts_v3_lab_test_lab_account_get\" | \"get_lab_test_for_team_v3_lab_tests__lab_test_id__get\" | \"get_labs_v3_lab_tests_labs_get\" | \"get_markers_for_lab_test_v3_lab_tests__lab_test_id__markers_get\" | \"list_order_set_markers_v3_lab_tests_list_order_set_markers_post\" | \"create_order_v3_order_post\" | \"get_area_info_v3_order_area_info_get\" | \"get_psc_info_v3_order_psc_info_get\" | \"get_phlebotomy_appointment_availability_v3_order_phlebotomy_appointment_availability_post\" | \"get_phlebotomy_appointment_cancellation_reason_v3_order_phlebotomy_appointment_cancellation_reasons_get\" | \"get_psc_appointment_availability_v3_order_psc_appointment_availability_post\" | \"get_psc_appointment_cancellation_reason_v3_order_psc_appointment_cancellation_reasons_get\" | \"get_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_get\" | \"book_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_book_post\" | \"reschedule_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_reschedule_patch\" | \"cancel_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_cancel_patch\" | \"get_psc_appointment_v3_order__order_id__psc_appointment_get\" | \"book_psc_appointment_v3_order__order_id__psc_appointment_book_post\" | \"reschedule_psc_appointment_v3_order__order_id__psc_appointment_reschedule_patch\" | \"cancel_psc_appointment_v3_order__order_id__psc_appointment_cancel_patch\" | \"get_order_v3_order__order_id__get\" | \"cancel_order_v3_order__order_id__cancel_post\" | \"simulate_order_v3_order__order_id__test_post\" | \"get_result_raw_v3_order__order_id__result_get\" | \"get_result_metadata_v3_order__order_id__result_metadata_get\" | \"get_result_pdf_v3_order__order_id__result_pdf_get\" | \"get_order_requisition_pdf_v3_order__order_id__requisition_pdf_get\" | \"get_orders_v3_orders_get\" | \"get_order_transaction_v3_order_transaction__transaction_id__get\" | \"get_order_transaction_result_v3_order_transaction__transaction_id__result_get\"\nexport const operationIds = [\"get_teams_users_v2_user_get\",\"create_user_v2_user_post\",\"get_user_v2_user__user_id__get\",\"delete_user_v2_user__user_id__delete\",\"patch_user_v2_user__user_id__patch\",\"get_user_by_client_user_id_v2_user_resolve__client_user_id__get\",\"patch_user_info_v2_user__user_id__info_patch\",\"get_latest_user_info_user_v2_user__user_id__info_latest_get\",\"get_paginated_lab_tests_for_team_v3_lab_test_get\",\"get_team_lab_accounts_v3_lab_test_lab_account_get\",\"get_lab_test_for_team_v3_lab_tests__lab_test_id__get\",\"get_labs_v3_lab_tests_labs_get\",\"get_markers_for_lab_test_v3_lab_tests__lab_test_id__markers_get\",\"list_order_set_markers_v3_lab_tests_list_order_set_markers_post\",\"create_order_v3_order_post\",\"get_area_info_v3_order_area_info_get\",\"get_psc_info_v3_order_psc_info_get\",\"get_phlebotomy_appointment_availability_v3_order_phlebotomy_appointment_availability_post\",\"get_phlebotomy_appointment_cancellation_reason_v3_order_phlebotomy_appointment_cancellation_reasons_get\",\"get_psc_appointment_availability_v3_order_psc_appointment_availability_post\",\"get_psc_appointment_cancellation_reason_v3_order_psc_appointment_cancellation_reasons_get\",\"get_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_get\",\"book_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_book_post\",\"reschedule_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_reschedule_patch\",\"cancel_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_cancel_patch\",\"get_psc_appointment_v3_order__order_id__psc_appointment_get\",\"book_psc_appointment_v3_order__order_id__psc_appointment_book_post\",\"reschedule_psc_appointment_v3_order__order_id__psc_appointment_reschedule_patch\",\"cancel_psc_appointment_v3_order__order_id__psc_appointment_cancel_patch\",\"get_order_v3_order__order_id__get\",\"cancel_order_v3_order__order_id__cancel_post\",\"simulate_order_v3_order__order_id__test_post\",\"get_result_raw_v3_order__order_id__result_get\",\"get_result_metadata_v3_order__order_id__result_metadata_get\",\"get_result_pdf_v3_order__order_id__result_pdf_get\",\"get_order_requisition_pdf_v3_order__order_id__requisition_pdf_get\",\"get_orders_v3_orders_get\",\"get_order_transaction_v3_order_transaction__transaction_id__get\",\"get_order_transaction_result_v3_order_transaction__transaction_id__result_get\"] as const\nexport const supportedOperationIds = [\"get_teams_users_v2_user_get\",\"create_user_v2_user_post\",\"get_user_v2_user__user_id__get\",\"delete_user_v2_user__user_id__delete\",\"patch_user_v2_user__user_id__patch\",\"get_user_by_client_user_id_v2_user_resolve__client_user_id__get\",\"patch_user_info_v2_user__user_id__info_patch\",\"get_latest_user_info_user_v2_user__user_id__info_latest_get\",\"get_paginated_lab_tests_for_team_v3_lab_test_get\",\"get_team_lab_accounts_v3_lab_test_lab_account_get\",\"get_lab_test_for_team_v3_lab_tests__lab_test_id__get\",\"get_labs_v3_lab_tests_labs_get\",\"get_markers_for_lab_test_v3_lab_tests__lab_test_id__markers_get\",\"list_order_set_markers_v3_lab_tests_list_order_set_markers_post\",\"create_order_v3_order_post\",\"get_area_info_v3_order_area_info_get\",\"get_psc_info_v3_order_psc_info_get\",\"get_phlebotomy_appointment_availability_v3_order_phlebotomy_appointment_availability_post\",\"get_phlebotomy_appointment_cancellation_reason_v3_order_phlebotomy_appointment_cancellation_reasons_get\",\"get_psc_appointment_availability_v3_order_psc_appointment_availability_post\",\"get_psc_appointment_cancellation_reason_v3_order_psc_appointment_cancellation_reasons_get\",\"get_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_get\",\"book_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_book_post\",\"reschedule_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_reschedule_patch\",\"cancel_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_cancel_patch\",\"get_psc_appointment_v3_order__order_id__psc_appointment_get\",\"book_psc_appointment_v3_order__order_id__psc_appointment_book_post\",\"reschedule_psc_appointment_v3_order__order_id__psc_appointment_reschedule_patch\",\"cancel_psc_appointment_v3_order__order_id__psc_appointment_cancel_patch\",\"get_order_v3_order__order_id__get\",\"cancel_order_v3_order__order_id__cancel_post\",\"simulate_order_v3_order__order_id__test_post\",\"get_result_raw_v3_order__order_id__result_get\",\"get_result_metadata_v3_order__order_id__result_metadata_get\",\"get_result_pdf_v3_order__order_id__result_pdf_get\",\"get_order_requisition_pdf_v3_order__order_id__requisition_pdf_get\",\"get_orders_v3_orders_get\",\"get_order_transaction_v3_order_transaction__transaction_id__get\",\"get_order_transaction_result_v3_order_transaction__transaction_id__result_get\"] as const\n", "/** Lab-test catalog mirrored from the Junction sandbox (`GET /v3/lab_test`). */\nexport type CatalogMarker = {\n id: number\n name: string\n slug: string\n description: string | null\n lab_id: number | null\n provider_id: string | null\n type: string | null\n unit: string | null\n price: string | null\n aoe: unknown\n a_la_carte_enabled: boolean\n common_tat_days: number | null\n worst_case_tat_days: number | null\n is_orderable: boolean | null\n}\n\nexport type ExpectedResultLoinc = {\n id: number\n name: string\n slug: string\n code: string\n unit: string | null\n}\n\nexport type ExpectedResult = {\n id: number\n name: string\n slug: string\n lab_id: number | null\n provider_id: string | null\n required: boolean\n loinc: ExpectedResultLoinc | null\n}\n\nexport type LabTestRecord = {\n id: string\n slug: string\n name: string\n sample_type: string\n method: string\n price: number\n is_active: boolean\n status: string\n fasting: boolean\n lab: Record<string, unknown>\n markers: CatalogMarker[] | null\n is_delegated: boolean\n auto_generated: boolean\n has_collection_instructions: boolean | null\n common_tat_days: number | null\n worst_case_tat_days: number | null\n}\n\nexport const LAB_TEST_CATALOG: readonly LabTestRecord[] = [\n {\n id: \"c533549c-1e62-4afe-9a0e-0567a9b2bcc2\",\n slug: \"comprehensive_metabolic_panel\",\n name: \"CMP\",\n sample_type: \"serum\",\n method: \"walk_in_test\",\n price: 0,\n is_active: true,\n status: \"active\",\n fasting: false,\n lab: {\n id: 6,\n slug: \"labcorp\",\n name: \"Labcorp\",\n first_line_address: \"Labcorp\",\n city: \"San Diego\",\n zipcode: \"92128\",\n collection_methods: [\"at_home_phlebotomy\", \"walk_in_test\", \"on_site_collection\"],\n sample_types: [\"serum\", \"saliva\", \"urine\"],\n logo_url: null,\n },\n markers: [\n {\n id: 2075,\n name: \"Comp. Metabolic Panel (14)\",\n slug: \"comp-metabolic-panel-14\",\n description: \"Comp. Metabolic Panel (14)\",\n lab_id: 6,\n provider_id: \"322000\",\n type: \"biomarker\",\n unit: null,\n price: \"N/A\",\n aoe: {\n questions: [\n {\n id: 1,\n required: false,\n code: \"FSTING\",\n value: \"FASTING\",\n type: \"choice\",\n sequence: 1,\n answers: [\n { id: 1, code: \"N\", value: \"No\" },\n { id: 2, code: \"Y\", value: \"Yes\" },\n ],\n constraint: null,\n default: null,\n },\n ],\n },\n a_la_carte_enabled: true,\n common_tat_days: 3,\n worst_case_tat_days: 5,\n is_orderable: true,\n },\n ],\n is_delegated: false,\n auto_generated: false,\n has_collection_instructions: false,\n common_tat_days: 3,\n worst_case_tat_days: 5,\n },\n {\n id: \"0cb9f34f-c3df-4a13-8ca1-19429a82611b\",\n slug: \"general_wellness_female_002\",\n name: \"Female General Wellness\",\n sample_type: \"dried_blood_spot\",\n method: \"testkit\",\n price: 45,\n is_active: true,\n status: \"active\",\n fasting: false,\n lab: {\n id: 3,\n slug: \"ussl\",\n name: \"USSL\",\n first_line_address: \"15150 Avenue of Science, Suite 100\",\n city: \"San Diego\",\n zipcode: \"92128\",\n collection_methods: [\"testkit\"],\n sample_types: [\"dried_blood_spot\"],\n logo_url: null,\n },\n markers: null,\n is_delegated: false,\n auto_generated: false,\n has_collection_instructions: false,\n common_tat_days: null,\n worst_case_tat_days: null,\n },\n {\n id: \"b439efda-1e07-4d2c-8afb-51771c7cc0cb\",\n slug: \"lipid_panel_athome\",\n name: \"Lipid Panel: At Home\",\n sample_type: \"serum\",\n method: \"at_home_phlebotomy\",\n price: 0,\n is_active: true,\n status: \"active\",\n fasting: false,\n lab: {\n id: 6,\n slug: \"labcorp\",\n name: \"Labcorp\",\n first_line_address: \"Labcorp\",\n city: \"San Diego\",\n zipcode: \"92128\",\n collection_methods: [\"at_home_phlebotomy\", \"walk_in_test\", \"on_site_collection\"],\n sample_types: [\"serum\", \"saliva\", \"urine\"],\n logo_url: null,\n },\n markers: [\n {\n id: 1975,\n name: \"Lipid Panel\",\n slug: \"lipid-panel\",\n description: \"Lipid Panel\",\n lab_id: 6,\n provider_id: \"303756\",\n type: \"biomarker\",\n unit: null,\n price: \"N/A\",\n aoe: {\n questions: [\n {\n id: 1,\n required: false,\n code: \"FSTING\",\n value: \"FASTING\",\n type: \"choice\",\n sequence: 1,\n answers: [\n { id: 1, code: \"N\", value: \"No\" },\n { id: 2, code: \"Y\", value: \"Yes\" },\n ],\n constraint: null,\n default: null,\n },\n ],\n },\n a_la_carte_enabled: true,\n common_tat_days: 3,\n worst_case_tat_days: 5,\n is_orderable: true,\n },\n ],\n is_delegated: false,\n auto_generated: false,\n has_collection_instructions: false,\n common_tat_days: 3,\n worst_case_tat_days: 5,\n },\n]\n\nexport const labTestById = (id: string): LabTestRecord | undefined =>\n LAB_TEST_CATALOG.find((test) => test.id === id)\n\n/**\n * Team lab inventory mirrored from the sandbox (`GET /v3/lab_tests/labs`). The endpoint\n * returns the team's full lab list \u2014 not just the labs referenced by catalog tests \u2014 in\n * this exact order.\n */\nexport const TEAM_LABS: readonly Record<string, unknown>[] = [\n {\n id: 24,\n slug: \"my_uti\",\n name: \"MyUTI\",\n first_line_address: \"No Address\",\n city: \"Chicago\",\n zipcode: \"00000\",\n collection_methods: [\"testkit\"],\n sample_types: [\"dried_blood_spot\"],\n logo_url: null,\n },\n {\n id: 25,\n slug: \"sonora_quest\",\n name: \"Sonora Quest\",\n first_line_address: \"1255 West Washington Street\",\n city: \"Tempe\",\n zipcode: \"85281\",\n collection_methods: [\"at_home_phlebotomy\", \"walk_in_test\", \"on_site_collection\"],\n sample_types: [\"serum\", \"saliva\", \"urine\"],\n logo_url: null,\n },\n {\n id: 26,\n slug: \"crl\",\n name: \"CRL\",\n first_line_address: \"11711 W 83rd Terrace\",\n city: \"Lenexa\",\n zipcode: \"66214\",\n collection_methods: [\"testkit\"],\n sample_types: [\"arm_collector\"],\n logo_url: null,\n },\n {\n id: 27,\n slug: \"mtl\",\n name: \"Molecular Testing Labs\",\n first_line_address: \"14401 SE 1st Street\",\n city: \"Vancouver\",\n zipcode: \"98684\",\n collection_methods: [\"testkit\"],\n sample_types: [\"saliva\"],\n logo_url: null,\n },\n {\n id: 22,\n slug: \"nexus\",\n name: \"Nexus\",\n first_line_address: \"313 Pleasant Street\",\n city: \"Watertown\",\n zipcode: \"02472\",\n collection_methods: [\"testkit\"],\n sample_types: [\"urine\", \"dried_blood_spot\"],\n logo_url: null,\n },\n {\n id: 17,\n slug: \"precision_analytical\",\n name: \"Precision Analytical\",\n first_line_address: \"3138 NE Rivergate Street\",\n city: \"McMinnville\",\n zipcode: \"97128\",\n collection_methods: [\"testkit\"],\n sample_types: [\"dried_blood_spot\"],\n logo_url: null,\n },\n {\n id: 20,\n slug: \"boston_heart_at_home_kit\",\n name: \"Boston Heart At-Home Kit\",\n first_line_address: \"200 Crossing Boulevard\",\n city: \"Framingham\",\n zipcode: \"01702\",\n collection_methods: [\"testkit\"],\n sample_types: [\"dried_blood_spot\", \"saliva\"],\n logo_url: null,\n },\n {\n id: 7,\n slug: \"diagnosticsolutions\",\n name: \"Diagnostic Solutions\",\n first_line_address: \" 5895 Shiloh Rd\",\n city: \"Alpharetta\",\n zipcode: \"30005\",\n collection_methods: [\"at_home_phlebotomy\", \"walk_in_test\", \"testkit\"],\n sample_types: [\"serum\", \"dried_blood_spot\", \"saliva\"],\n logo_url: null,\n },\n {\n id: 8,\n slug: \"cellsciencesystems\",\n name: \"Cell Science Systems\",\n first_line_address: \"852 S. Military Trail\",\n city: \"Deerfield Beach\",\n zipcode: \"33442\",\n collection_methods: [\"at_home_phlebotomy\", \"walk_in_test\", \"testkit\"],\n sample_types: [\"serum\", \"dried_blood_spot\", \"saliva\"],\n logo_url: null,\n },\n {\n id: 6,\n slug: \"labcorp\",\n name: \"Labcorp\",\n first_line_address: \"Labcorp\",\n city: \"San Diego\",\n zipcode: \"92128\",\n collection_methods: [\"at_home_phlebotomy\", \"walk_in_test\", \"on_site_collection\"],\n sample_types: [\"serum\", \"saliva\", \"urine\"],\n logo_url: null,\n },\n {\n id: 13,\n slug: \"bioreference\",\n name: \"BioReference\",\n first_line_address: \"481 Edward H Ross Dr\",\n city: \"Elmwood park\",\n zipcode: \"07407\",\n collection_methods: [\"walk_in_test\", \"at_home_phlebotomy\", \"on_site_collection\"],\n sample_types: [\"serum\", \"saliva\", \"urine\"],\n logo_url: null,\n },\n {\n id: 40,\n slug: \"us_biotek\",\n name: \"US Biotek\",\n first_line_address: \"16020 Linden Ave N\",\n city: \"Shoreline\",\n zipcode: \"98133\",\n collection_methods: [\"testkit\"],\n sample_types: [\"dried_blood_spot\"],\n logo_url: null,\n },\n {\n id: 21,\n slug: \"ihd\",\n name: \"IHD\",\n first_line_address: \"1936 E Deere Ave. Suite 115\",\n city: \"Santa Ana\",\n zipcode: \"92705\",\n collection_methods: [\"testkit\", \"at_home_phlebotomy\", \"walk_in_test\"],\n sample_types: [\"urine\", \"serum\"],\n logo_url: null,\n },\n {\n id: 4,\n slug: \"quest\",\n name: \"Quest\",\n first_line_address: \"Quest\",\n city: \"San Diego\",\n zipcode: \"92128\",\n collection_methods: [\"at_home_phlebotomy\", \"walk_in_test\", \"on_site_collection\"],\n sample_types: [\"serum\", \"saliva\", \"urine\"],\n logo_url: null,\n },\n {\n id: 23,\n slug: \"sanocardio\",\n name: \"SanoCardio\",\n first_line_address: \"N/A\",\n city: \"N/a\",\n zipcode: \"N/A\",\n collection_methods: [\"testkit\"],\n sample_types: [\"dried_blood_spot\"],\n logo_url: null,\n },\n {\n id: 1,\n slug: \"ayumetrix\",\n name: \"Ayumetrix\",\n first_line_address: \"17387 SW 63rd Ave\",\n city: \"Lake Oswego\",\n zipcode: \"97035\",\n collection_methods: [\"testkit\"],\n sample_types: [\"dried_blood_spot\", \"saliva\"],\n logo_url: null,\n },\n {\n id: 9,\n slug: \"genova\",\n name: \"Genova Diagnostics\",\n first_line_address: \" P.O. Box 3220\",\n city: \"Asheville\",\n zipcode: \"28802\",\n collection_methods: [\"at_home_phlebotomy\", \"walk_in_test\", \"testkit\"],\n sample_types: [\"serum\", \"dried_blood_spot\", \"saliva\"],\n logo_url: null,\n },\n {\n id: 14,\n slug: \"zrt\",\n name: \"ZRT Laboratory\",\n first_line_address: \"8605 SW Creekside Pl\",\n city: \"Beaverton\",\n zipcode: \"97008\",\n collection_methods: [\"testkit\"],\n sample_types: [\"serum\", \"dried_blood_spot\", \"saliva\"],\n logo_url: null,\n },\n {\n id: 3,\n slug: \"ussl\",\n name: \"USSL\",\n first_line_address: \"15150 Avenue of Science, Suite 100\",\n city: \"San Diego\",\n zipcode: \"92128\",\n collection_methods: [\"testkit\"],\n sample_types: [\"dried_blood_spot\"],\n logo_url: null,\n },\n {\n id: 2,\n slug: \"spiriplex\",\n name: \"Spiriplex\",\n first_line_address: \"100 Tri State International #100\",\n city: \"Lincolnshire\",\n zipcode: \"60069\",\n collection_methods: [\"testkit\"],\n sample_types: [\"dried_blood_spot\"],\n logo_url: null,\n },\n]\n\n/** Panel constituents mirrored from the sandbox (`GET /v3/lab_tests/{id}/markers`). */\nexport const EXPECTED_RESULTS: Readonly<Record<string, readonly ExpectedResult[]>> = {\n \"b439efda-1e07-4d2c-8afb-51771c7cc0cb\": [\n {\n id: 1109,\n name: \"Cholesterol, Total\",\n slug: \"cholesterol-total\",\n lab_id: 6,\n provider_id: \"001065\",\n required: true,\n loinc: {\n id: 11940,\n name: \"Cholesterol [Mass/Vol]\",\n slug: \"cholesterol-mass-vol\",\n code: \"2093-3\",\n unit: \"mg/dL\",\n },\n },\n {\n id: 1110,\n name: \"HDL Cholesterol\",\n slug: \"hdl-cholesterol\",\n lab_id: 6,\n provider_id: \"011817\",\n required: true,\n loinc: {\n id: 11858,\n name: \"Cholesterol in HDL [Mass/Vol]\",\n slug: \"cholesterol-in-hdl-mass-vol\",\n code: \"2085-9\",\n unit: \"mg/dL\",\n },\n },\n {\n id: 1112,\n name: \"Triglycerides\",\n slug: \"triglycerides\",\n lab_id: 6,\n provider_id: \"001172\",\n required: true,\n loinc: {\n id: 16384,\n name: \"Triglyceride [Mass/Vol]\",\n slug: \"triglyceride-mass-vol\",\n code: \"2571-8\",\n unit: \"mg/dL\",\n },\n },\n {\n id: 242764,\n name: \"LDL Calc Comment:\",\n slug: \"ldl-calc-comment\",\n lab_id: 6,\n provider_id: \"011926\",\n required: true,\n loinc: {\n id: 53832,\n name: \"Service comment [Interp]\",\n slug: \"service-comment-interp\",\n code: \"8251-1\",\n unit: null,\n },\n },\n {\n id: 242780,\n name: \"VLDL Cholesterol Cal\",\n slug: \"vldl-cholesterol-cal\",\n lab_id: 6,\n provider_id: \"011925\",\n required: true,\n loinc: {\n id: 5062,\n name: \"Cholesterol in VLDL Calc [Mass/Vol]\",\n slug: \"cholesterol-in-vldl-calc-mass-vol\",\n code: \"13458-5\",\n unit: \"mg/dL\",\n },\n },\n {\n id: 242790,\n name: \"LDL Chol Calc (NIH)\",\n slug: \"ldl-chol-calc-nih\",\n lab_id: 6,\n provider_id: \"012065\",\n required: true,\n loinc: {\n id: 5060,\n name: \"Cholesterol in LDL Calc [Mass/Vol]\",\n slug: \"cholesterol-in-ldl-calc-mass-vol\",\n code: \"13457-7\",\n unit: \"mg/dL\",\n },\n },\n ],\n \"c533549c-1e62-4afe-9a0e-0567a9b2bcc2\": [\n {\n id: 364,\n name: \"AST (SGOT)\",\n slug: \"ast-sgot\",\n lab_id: 6,\n provider_id: \"001123\",\n required: true,\n loinc: {\n id: 10684,\n name: \"AST [Catalytic activity/Vol]\",\n slug: \"ast-catalytic-activity-vol\",\n code: \"1920-8\",\n unit: \"U/L\",\n },\n },\n {\n id: 471,\n name: \"ALT (SGPT)\",\n slug: \"alt-sgpt\",\n lab_id: 6,\n provider_id: \"001545\",\n required: true,\n loinc: {\n id: 9362,\n name: \"ALT [Catalytic activity/Vol]\",\n slug: \"alt-catalytic-activity-vol\",\n code: \"1742-6\",\n unit: \"U/L\",\n },\n },\n {\n id: 1045,\n name: \"BUN\",\n slug: \"bun\",\n lab_id: 6,\n provider_id: \"001040\",\n required: true,\n loinc: {\n id: 19958,\n name: \"Urea nitrogen [Mass/Vol]\",\n slug: \"urea-nitrogen-mass-vol\",\n code: \"3094-0\",\n unit: \"mg/dL\",\n },\n },\n {\n id: 1050,\n name: \"eGFR\",\n slug: \"egfr\",\n lab_id: 6,\n provider_id: \"100779\",\n required: true,\n loinc: {\n id: 61049,\n name: \"GFR/1.73 sq M.predicted Creatinine-based formula (CKD-EPI 2021) (S/P/Bld) [Vol rate/Area]\",\n slug: \"gfr-1-73-sq-m-predicted-creatinine-based-formula-ckd-epi-2021-s-p-bld-vol-rate-area\",\n code: \"98979-8\",\n unit: \"mL/min/{1.73_m2}\",\n },\n },\n {\n id: 1051,\n name: \"Creatinine\",\n slug: \"creatinine\",\n lab_id: 6,\n provider_id: \"001370\",\n required: true,\n loinc: {\n id: 12675,\n name: \"Creatinine [Mass/Vol]\",\n slug: \"creatinine-mass-vol\",\n code: \"2160-0\",\n unit: \"mg/dL\",\n },\n },\n {\n id: 1238,\n name: \"Protein, Total\",\n slug: \"protein-total\",\n lab_id: 6,\n provider_id: \"001073\",\n required: true,\n loinc: {\n id: 18410,\n name: \"Protein [Mass/Vol]\",\n slug: \"protein-mass-vol\",\n code: \"2885-2\",\n unit: \"g/dL\",\n },\n },\n {\n id: 1266,\n name: \"Calcium\",\n slug: \"calcium\",\n lab_id: 6,\n provider_id: \"001016\",\n required: true,\n loinc: {\n id: 9833,\n name: \"Calcium [Mass/Vol]\",\n slug: \"calcium-mass-vol\",\n code: \"17861-6\",\n unit: \"mg/dL\",\n },\n },\n {\n id: 1267,\n name: \"BUN/Creatinine Ratio\",\n slug: \"bun-creatinine-ratio\",\n lab_id: 6,\n provider_id: \"011577\",\n required: true,\n loinc: {\n id: 19962,\n name: \"Urea nitrogen/Creatinine [Mass ratio]\",\n slug: \"urea-nitrogen-creatinine-mass-ratio\",\n code: \"3097-3\",\n unit: \"mg/mg{creat}\",\n },\n },\n {\n id: 1268,\n name: \"Carbon Dioxide, Total\",\n slug: \"carbon-dioxide-total\",\n lab_id: 6,\n provider_id: \"001578\",\n required: true,\n loinc: {\n id: 11320,\n name: \"CO2 [Moles/Vol]\",\n slug: \"co2-moles-vol\",\n code: \"2028-9\",\n unit: \"mmol/L\",\n },\n },\n {\n id: 1269,\n name: \"Glucose\",\n slug: \"glucose\",\n lab_id: 6,\n provider_id: \"001032\",\n required: true,\n loinc: {\n id: 14491,\n name: \"Glucose [Mass/Vol]\",\n slug: \"glucose-mass-vol\",\n code: \"2345-7\",\n unit: \"mg/dL\",\n },\n },\n {\n id: 1270,\n name: \"Potassium\",\n slug: \"potassium\",\n lab_id: 6,\n provider_id: \"001180\",\n required: true,\n loinc: {\n id: 18272,\n name: \"Potassium [Moles/Vol]\",\n slug: \"potassium-moles-vol\",\n code: \"2823-3\",\n unit: \"mmol/L\",\n },\n },\n {\n id: 1271,\n name: \"Sodium\",\n slug: \"sodium\",\n lab_id: 6,\n provider_id: \"001198\",\n required: true,\n loinc: {\n id: 18724,\n name: \"Sodium [Moles/Vol]\",\n slug: \"sodium-moles-vol\",\n code: \"2951-2\",\n unit: \"mmol/L\",\n },\n },\n {\n id: 1272,\n name: \"Chloride\",\n slug: \"chloride\",\n lab_id: 6,\n provider_id: \"001206\",\n required: true,\n loinc: {\n id: 11738,\n name: \"Chloride [Moles/Vol]\",\n slug: \"chloride-moles-vol\",\n code: \"2075-0\",\n unit: \"mmol/L\",\n },\n },\n {\n id: 1370,\n name: \"Bilirubin, Total\",\n slug: \"bilirubin-total\",\n lab_id: 6,\n provider_id: \"001099\",\n required: true,\n loinc: {\n id: 11239,\n name: \"Bilirubin [Mass/Vol]\",\n slug: \"bilirubin-mass-vol\",\n code: \"1975-2\",\n unit: \"mg/dL\",\n },\n },\n {\n id: 1956,\n name: \"Albumin\",\n slug: \"albumin\",\n lab_id: 6,\n provider_id: \"001081\",\n required: true,\n loinc: {\n id: 9462,\n name: \"Albumin [Mass/Vol]\",\n slug: \"albumin-mass-vol\",\n code: \"1751-7\",\n unit: \"g/dL\",\n },\n },\n {\n id: 2304,\n name: \"Globulin, Total\",\n slug: \"globulin-total\",\n lab_id: 6,\n provider_id: \"012039\",\n required: true,\n loinc: {\n id: 2951,\n name: \"Globulin Calc (S) [Mass/Vol]\",\n slug: \"globulin-calc-s-mass-vol\",\n code: \"10834-0\",\n unit: \"g/L\",\n },\n },\n {\n id: 13,\n name: \"Alkaline Phosphatase\",\n slug: \"alkaline-phosphatase\",\n lab_id: 6,\n provider_id: \"001107\",\n required: true,\n loinc: {\n id: 45530,\n name: \"ALP [Catalytic activity/Vol]\",\n slug: \"alp-catalytic-activity-vol\",\n code: \"6768-6\",\n unit: \"U/L\",\n },\n },\n ],\n}\n\nexport const expectedResultsFor = (labTestId: string): readonly ExpectedResult[] =>\n EXPECTED_RESULTS[labTestId] ?? []\n", "import { Collection, IdSequence, opaqueToken } from \"@crvouga/mockingbird-service\"\nimport type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\nimport {\n EXPECTED_RESULTS,\n type ExpectedResult,\n LAB_TEST_CATALOG,\n type LabTestRecord,\n TEAM_LABS,\n} from \"./catalog.js\"\n\nexport type { CatalogMarker, ExpectedResult, LabTestRecord } from \"./catalog.js\"\nexport { expectedResultsFor, LAB_TEST_CATALOG, labTestById, TEAM_LABS } from \"./catalog.js\"\n\nexport type GetCacheEntry = {\n status: number\n headers: Record<string, string>\n body: unknown\n}\n\nconst sortedQueryString = (params: URLSearchParams): string => {\n const entries = [...params.entries()].sort(([leftKey, leftValue], [rightKey, rightValue]) => {\n const keyOrder = leftKey.localeCompare(rightKey)\n return keyOrder === 0 ? leftValue.localeCompare(rightValue) : keyOrder\n })\n return new URLSearchParams(entries).toString()\n}\n\nexport const observationCacheKey = (url: URL | string, method = \"GET\", body?: unknown): string => {\n const parsed = typeof url === \"string\" ? new URL(url, \"https://observation.local\") : url\n const query = sortedQueryString(parsed.searchParams)\n const pathAndQuery = `${parsed.pathname}${query ? `?${query}` : \"\"}`\n const head = `${method.toUpperCase()} ${pathAndQuery}`\n if (body === undefined) return head\n return `${head} ${JSON.stringify(body)}`\n}\n\nexport type UserInfoRecord = Record<string, unknown>\n\nexport type AppointmentModality = \"phlebotomy\" | \"patient_service_center\"\nexport type AppointmentProviderName = \"getlabs\" | \"phlebfinders\" | \"quest\"\nexport type AppointmentStatus =\n | \"confirmed\"\n | \"pending\"\n | \"reserved\"\n | \"in_progress\"\n | \"completed\"\n | \"cancelled\"\nexport type AppointmentEventStatus =\n | \"pending\"\n | \"reserved\"\n | \"scheduled\"\n | \"completed\"\n | \"cancelled\"\n | \"in_progress\"\n\nexport type AppointmentEventRecord = {\n created_at: string\n status: AppointmentEventStatus\n data: Record<string, unknown> | null\n}\n\nexport type AppointmentRecord = {\n id: string\n order_id: string\n user_id: string\n provider_id: string\n external_id: string | null\n type: AppointmentModality\n provider: AppointmentProviderName\n status: AppointmentStatus\n event_status: AppointmentEventStatus\n start_at: string | null\n end_at: string | null\n iana_timezone: string | null\n address: Record<string, unknown>\n location: { lng: number; lat: number }\n can_reschedule: boolean\n booking_key: string | null\n site_code: string | null\n appointment_notes: string | null\n order_transaction_id: string | null\n event_data: Record<string, unknown> | null\n events: AppointmentEventRecord[]\n created_at: string\n updated_at: string\n}\n\nexport type BookingKeyRecord = {\n key: string\n start: string\n end: string\n expires_at: string | null\n price: number\n is_priority: boolean\n num_appointments_available: number\n modality: AppointmentModality\n provider: AppointmentProviderName\n site_code: string | null\n zip_code: string\n address: Record<string, unknown>\n location: { lng: number; lat: number }\n consumed_by_order_id: string | null\n created_at: string\n}\n\nexport type PendingSimulateTransition = {\n order_id: string\n due_at: number\n final_status: string\n flags: Record<string, unknown> | null\n}\n\nexport type JunctionWebhookEvent = {\n event_type: \"labtest.order.created\" | \"labtest.order.updated\" | \"labtest.appointment.updated\"\n data: Record<string, unknown>\n team_id: string\n user_id: string\n client_user_id: string\n}\n\nexport type WebhookEventRecord = {\n sequence: number\n event: JunctionWebhookEvent\n}\n\nexport type WebhookDeliveryAttempt = {\n message_id: string\n event: JunctionWebhookEvent\n attempt: number\n scheduled_at: string\n timeout_ms: number\n acknowledged: boolean\n}\n\nexport const WEBHOOK_RETRY_DELAYS_MS = [\n 0, 5_000, 300_000, 1_800_000, 7_200_000, 18_000_000, 36_000_000, 36_000_000,\n] as const\n\nconst clone = <T>(value: T): T => JSON.parse(JSON.stringify(value)) as T\n\nconst seededRandom = (seed: number) => {\n let value = seed >>> 0\n return () => {\n value = (value * 1664525 + 1013904223) >>> 0\n return value / 0x1_0000_0000\n }\n}\n\nexport type UserRecord = {\n user_id: string\n team_id: string\n client_user_id: string\n created_on: string\n connected_sources: unknown[]\n fallback_time_zone: { id: string; source_slug: string; updated_at: string } | null\n fallback_birth_date: { value: string; source_slug: string; updated_at: string } | null\n ingestion_start: string | null\n ingestion_end: string | null\n}\n\n/** Fixed mock team id \u2014 volatile on the real side, stable in the mock. */\nexport const MOCK_TEAM_ID = \"11111111-1111-4111-8111-111111111111\"\n\n/** Deterministic UUID derived from a salt + sequence (version/variant bits fixed). */\nexport const deterministicUuid = (input: string): string => {\n const raw = opaqueToken(input, 32)\n let hex = \"\"\n for (let i = 0; i < raw.length && hex.length < 32; i++) {\n hex += (raw.charCodeAt(i) % 16).toString(16)\n }\n hex = hex.padEnd(32, \"0\").slice(0, 32)\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-8${hex.slice(17, 20)}-${hex.slice(20, 32)}`\n}\n\nexport type OrderEventRecord = {\n id: number\n created_at: string\n status: string\n status_detail: null\n}\n\nexport type OrderTransactionEmbed = {\n id: string\n status: \"active\" | \"completed\" | \"cancelled\"\n orders: Array<{\n id: string\n low_level_status: string\n low_level_status_created_at: string\n origin: string\n parent_id: null\n created_at: string\n updated_at: string\n }>\n}\n\nexport type OrderRecord = {\n id: string\n user_id: string\n team_id: string\n patient_details: Record<string, unknown>\n patient_address: Record<string, unknown>\n lab_test: LabTestRecord\n details: Record<string, unknown>\n sample_id: string | null\n notes: null\n clinical_notes: string | null\n passthrough: string | null\n /** Echoed from the request's opaque provider account id; absent when the order had none. */\n lab_account_id?: string\n created_at: string\n updated_at: string\n events: OrderEventRecord[]\n status: string\n last_event: OrderEventRecord\n physician: { first_name: string; last_name: string; npi: string }\n health_insurance_id: null\n requisition_form_url: string | null\n shipping_details: null\n has_abn: boolean\n billing_type: string\n priority: boolean\n activate_by: null\n icd_codes: string[] | null\n interpretation: string | null\n has_missing_results: boolean | null\n result_types: string[] | null\n expected_result_by_date: string | null\n worst_case_result_by_date: string | null\n origin: string\n order_transaction: OrderTransactionEmbed\n}\n\n/**\n * A lab account as the ordering rules read it. Structurally `LabAccountRecord` from\n * lab-accounts.ts, restated here because that module imports this one.\n */\nexport type StoredLabAccount = {\n id: string\n lab: string\n org_id: string | null\n status: \"active\" | \"pending\" | \"suspended\" | \"ready_to_launch\"\n delegated_flow: \"order_delegated\" | \"result_delegated\" | \"fully_delegated\" | \"not_delegated\"\n provider_account_id: string\n account_name: string | null\n default_clinical_notes: string | null\n business_units: string[] | null\n allowed_billing: Record<string, readonly string[]>\n team_id_allowlist: readonly string[]\n}\n\n/**\n * A chosen result for one order, installed through the admin API. Replaces the\n * generated biomarker lines, so a suite can assert on an exact payload \u2014 an abnormal\n * panel, a critical value, a missing marker \u2014 instead of whatever the generator made.\n */\nexport type ResultFixture = {\n /** The fixture's name, for logs and `GET /__admin/results`. */\n name: string\n results?: unknown[]\n missing_results?: unknown[] | null\n interpretation?: string\n /** Served from `GET /v3/order/{id}/result/pdf` instead of the generated PDF. */\n pdf_base64?: string\n}\n\n/**\n * How serviceability reads answer a ZIP the loaded corpus has no record for.\n *\n * - `synthetic`: invent plausible coverage. Right for property tests that walk random ZIPs.\n * - `corpus`: refuse with a documented Mockingbird error. Right for a mock standing in for\n * the vendor, where invented coverage would silently disagree with production.\n */\nexport type GeoMode = \"synthetic\" | \"corpus\"\n\nexport type WebhookPublisher = (event: JunctionWebhookEvent) => void\n\nexport type JunctionWebhookOptions = {\n seed?: number\n jitterRatio?: number\n timeoutMs?: number\n}\n\nexport class JunctionState {\n private readonly publishEvent: WebhookPublisher | undefined\n private readonly webhookRandom: () => number\n private readonly webhookJitterRatio: number\n private readonly webhookTimeoutMs: number\n readonly users: Collection<UserRecord>\n readonly ids: IdSequence\n readonly byClientId: Collection<{ user_id: string }>\n readonly deletedUsers: Collection<{ user_id: string }>\n readonly userInfo: Collection<UserInfoRecord>\n readonly orders: Collection<OrderRecord>\n readonly orderIdempotency: Collection<{\n order_id: string\n response: unknown\n fingerprint: string\n }>\n readonly cancelIdempotency: Collection<{ order_id: string; response: unknown }>\n\n readonly appointments: Collection<AppointmentRecord>\n readonly appointmentsByOrder: Collection<{ appointment_id: string }>\n readonly bookingKeys: Collection<BookingKeyRecord>\n readonly pendingSimulateTransitions: Collection<PendingSimulateTransition>\n\n readonly orderByTransaction: Collection<{ order_id: string }>\n readonly webhookEvents: Collection<WebhookEventRecord>\n readonly webhookDeliveryAttempts: Collection<WebhookDeliveryAttempt>\n\n readonly labTests: Collection<LabTestRecord>\n readonly labs: Collection<Record<string, unknown>>\n readonly labAccounts: Collection<StoredLabAccount>\n readonly resultFixtures: Collection<ResultFixture>\n readonly expectedResults: Collection<ExpectedResult[]>\n readonly getCache: Collection<GetCacheEntry>\n\n /** Configuration, not data: set by JunctionAPI and re-applied on reset. */\n geoMode: GeoMode = \"synthetic\"\n /** ZIPs the loaded corpus has serviceability records for. */\n coveredZips: ReadonlySet<string> = new Set()\n /** Identifies the loaded corpus in errors and `/health`. */\n corpusLabel: string | undefined\n /**\n * The loaded corpus's recorded reads. Immutable and shared by every namespace, so it\n * lives outside SQLite: copying hundreds of large bodies into each namespace would\n * make a new namespace cost seconds, and snapshots would copy them too.\n */\n corpusObservations: ReadonlyMap<string, GetCacheEntry> = new Map()\n\n constructor(\n sqlite: SqliteClient,\n namespace: string,\n publisher?: WebhookPublisher,\n webhookOptions: JunctionWebhookOptions = {},\n ) {\n this.publishEvent = publisher\n this.webhookRandom = seededRandom(webhookOptions.seed ?? 0x4a554e43)\n this.webhookJitterRatio = Math.max(0, Math.min(webhookOptions.jitterRatio ?? 0.1, 1))\n this.webhookTimeoutMs = Math.max(1, webhookOptions.timeoutMs ?? 15_000)\n this.users = new Collection(sqlite, namespace, \"users\")\n this.byClientId = new Collection(sqlite, namespace, \"users_by_client\")\n this.deletedUsers = new Collection(sqlite, namespace, \"users_deleted\")\n this.userInfo = new Collection(sqlite, namespace, \"user_info\")\n this.orders = new Collection(sqlite, namespace, \"orders\")\n this.orderIdempotency = new Collection(sqlite, namespace, \"orders_idempotency\")\n this.cancelIdempotency = new Collection(sqlite, namespace, \"cancel_idempotency\")\n this.appointments = new Collection(sqlite, namespace, \"appointments\")\n this.appointmentsByOrder = new Collection(sqlite, namespace, \"appointments_by_order\")\n this.bookingKeys = new Collection(sqlite, namespace, \"booking_keys\")\n this.pendingSimulateTransitions = new Collection(\n sqlite,\n namespace,\n \"pending_simulate_transitions\",\n )\n this.orderByTransaction = new Collection(sqlite, namespace, \"orders_by_transaction\")\n this.webhookEvents = new Collection(sqlite, namespace, \"webhook_events\")\n this.webhookDeliveryAttempts = new Collection(sqlite, namespace, \"webhook_delivery_attempts\")\n this.labTests = new Collection(sqlite, namespace, \"lab_tests\")\n this.labs = new Collection(sqlite, namespace, \"labs\")\n this.labAccounts = new Collection(sqlite, namespace, \"lab_accounts\")\n this.resultFixtures = new Collection(sqlite, namespace, \"result_fixtures\")\n this.expectedResults = new Collection(sqlite, namespace, \"expected_results\")\n this.getCache = new Collection(sqlite, namespace, \"get_cache\")\n this.ids = new IdSequence(sqlite, namespace, \"junction\")\n this.seedDefaultCatalog()\n }\n\n seedDefaultCatalog(): void {\n this.replaceCatalog({\n labTests: [...LAB_TEST_CATALOG],\n labs: [...TEAM_LABS],\n expectedResults: Object.fromEntries(\n Object.entries(EXPECTED_RESULTS).map(([id, results]) => [id, [...results]]),\n ),\n })\n }\n\n private clearCollection<T>(collection: Collection<T>): void {\n for (const entry of collection.list()) collection.delete(entry.id)\n }\n\n labKeyOf(lab: Record<string, unknown>): string {\n if (lab.id !== undefined && lab.id !== null) return String(lab.id)\n if (typeof lab.slug === \"string\" && lab.slug.length > 0) return lab.slug\n return opaqueToken(`junction:lab:${JSON.stringify(lab)}`, 16)\n }\n\n labTestById(id: string): LabTestRecord | undefined {\n return this.labTests.get(id)\n }\n\n upsertLabTest(test: LabTestRecord, expectedResults?: readonly ExpectedResult[]): void {\n const existing = this.labTests.get(test.id)\n let next = clone(test)\n if (existing) {\n const incomingMarkers = next.markers?.length ?? 0\n const existingMarkers = existing.markers?.length ?? 0\n // Order embeds are often thinner than catalog GETs \u2014 keep richer marker/method\n // data so create_order method matching stays aligned with Vital.\n if (incomingMarkers === 0 && existingMarkers > 0) {\n next = { ...next, markers: existing.markers }\n }\n if (\n (typeof next.method !== \"string\" || next.method.length === 0) &&\n typeof existing.method === \"string\" &&\n existing.method.length > 0\n ) {\n next = { ...next, method: existing.method }\n }\n if (existing.auto_generated !== true && next.auto_generated === true) {\n next = {\n ...next,\n auto_generated: false,\n method: existing.method,\n name: existing.name,\n slug: existing.slug,\n }\n }\n this.labTests.update(test.id, next)\n } else {\n this.labTests.insert(test.id, next)\n }\n // Never clobber seeded panel expansions (e.g. Lipid \u2192 6 LOINCs) when callers\n // only pass the lab_test envelope from an order payload.\n if (expectedResults === undefined && this.expectedResults.get(test.id)) return\n const fromNested = (next.markers ?? []).flatMap((marker) => {\n const nested = (marker as { expected_results?: unknown }).expected_results\n if (!Array.isArray(nested) || nested.length === 0) return []\n return nested.filter(\n (entry): entry is ExpectedResult =>\n typeof entry === \"object\" && entry !== null && !Array.isArray(entry),\n )\n })\n const expected =\n expectedResults ??\n (fromNested.length > 0\n ? fromNested\n : (next.markers ?? []).map((marker) => ({\n id: marker.id,\n name: marker.name,\n slug: marker.slug,\n lab_id: marker.lab_id,\n provider_id: marker.provider_id,\n required: true,\n loinc: null,\n })))\n if (this.expectedResults.get(test.id)) this.expectedResults.update(test.id, [...expected])\n else this.expectedResults.insert(test.id, [...expected])\n }\n\n listLabTests(): LabTestRecord[] {\n return this.labTests.list({ order: \"oldest\" }).map((entry) => entry.value)\n }\n\n listLabs(): Record<string, unknown>[] {\n return this.labs.list({ order: \"oldest\" }).map((entry) => entry.value)\n }\n\n listLabAccounts(): StoredLabAccount[] {\n return this.labAccounts.list({ order: \"oldest\" }).map((entry) => entry.value)\n }\n\n expectedResultsFor(labTestId: string): ExpectedResult[] {\n return this.expectedResults.get(labTestId) ?? []\n }\n\n replaceCatalog(input: {\n labTests: readonly LabTestRecord[]\n labs: readonly Record<string, unknown>[]\n expectedResults: Readonly<Record<string, readonly ExpectedResult[]>>\n }): void {\n this.clearCollection(this.labTests)\n this.clearCollection(this.labs)\n this.clearCollection(this.expectedResults)\n for (const test of input.labTests) this.labTests.insert(test.id, clone(test))\n for (const lab of input.labs) this.labs.insert(this.labKeyOf(lab), clone(lab))\n for (const [labTestId, results] of Object.entries(input.expectedResults)) {\n this.expectedResults.insert(labTestId, clone([...results]))\n }\n }\n\n replaceLabAccounts(entries: readonly StoredLabAccount[]): void {\n this.clearCollection(this.labAccounts)\n for (const entry of entries) this.labAccounts.insert(entry.id, clone(entry))\n }\n\n putGetCache(key: string, entry: GetCacheEntry): void {\n this.getCache.insert(key, clone(entry))\n }\n\n /** A recorded read: one seeded into this namespace first, then the shared corpus. */\n getGetCache(key: string): GetCacheEntry | undefined {\n const entry = this.getCache.get(key) ?? this.corpusObservations.get(key)\n return entry ? clone(entry) : undefined\n }\n\n installGetCache(entries: Iterable<[string, GetCacheEntry]>): void {\n for (const [key, entry] of entries) this.putGetCache(key, entry)\n }\n\n /**\n * Materialize booking_key records from a cached availability payload so subsequent\n * book/reschedule calls succeed against observation-seeded mocks.\n */\n hydrateBookingKeysFromAvailability(\n body: unknown,\n nowMs: number,\n zipCode = \"00000\",\n modalityHint?: AppointmentModality,\n ): void {\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) return\n const root = body as Record<string, unknown>\n const dayBuckets: unknown[] = []\n if (Array.isArray(root.days)) dayBuckets.push(...root.days)\n if (Array.isArray(root.slots)) dayBuckets.push(...root.slots)\n const slotEntries: unknown[] = []\n for (const day of dayBuckets) {\n if (typeof day !== \"object\" || day === null || Array.isArray(day)) {\n slotEntries.push(day)\n continue\n }\n const daySlots = (day as Record<string, unknown>).slots\n if (Array.isArray(daySlots)) slotEntries.push(...daySlots)\n else if (typeof (day as Record<string, unknown>).booking_key === \"string\") {\n slotEntries.push(day)\n }\n }\n const zip = /^\\d{5}/.test(zipCode) ? zipCode.slice(0, 5) : \"00000\"\n const zipPrefix = Number(zip.slice(0, 3))\n const cityState =\n zipPrefix >= 850 && zipPrefix <= 865\n ? { city: \"Phoenix\", state: \"AZ\" }\n : zipPrefix >= 900\n ? { city: \"Los Angeles\", state: \"CA\" }\n : zipPrefix >= 800\n ? { city: \"Denver\", state: \"CO\" }\n : zipPrefix >= 600\n ? { city: \"Chicago\", state: \"IL\" }\n : zipPrefix >= 300 && zipPrefix < 400\n ? { city: \"Atlanta\", state: \"GA\" }\n : { city: \"New York\", state: \"NY\" }\n const location =\n zip === \"85004\"\n ? { lat: 33.6242904, lng: -111.9283407 }\n : {\n lat: 30 + (zipPrefix % 20) * 0.4,\n lng: -120 + (zipPrefix % 30) * 0.5,\n }\n for (const entry of slotEntries) {\n if (typeof entry !== \"object\" || entry === null || Array.isArray(entry)) continue\n const slot = entry as Record<string, unknown>\n const bookingKey = typeof slot.booking_key === \"string\" ? slot.booking_key : \"\"\n if (bookingKey === \"\" || this.bookingKeys.get(bookingKey)) continue\n const start = typeof slot.start === \"string\" ? slot.start : new Date(nowMs).toISOString()\n const end =\n typeof slot.end === \"string\" ? slot.end : new Date(nowMs + 45 * 60_000).toISOString()\n const modality: AppointmentModality =\n modalityHint ??\n (typeof slot.site_code === \"string\" && slot.site_code.length > 0\n ? \"patient_service_center\"\n : \"phlebotomy\")\n this.bookingKeys.insert(bookingKey, {\n key: bookingKey,\n start,\n end,\n expires_at: typeof slot.expires_at === \"string\" ? slot.expires_at : null,\n price: typeof slot.price === \"number\" ? slot.price : 0,\n is_priority: slot.is_priority === true,\n num_appointments_available:\n typeof slot.num_appointments_available === \"number\" ? slot.num_appointments_available : 1,\n modality,\n provider: modality === \"patient_service_center\" ? \"quest\" : \"getlabs\",\n site_code: typeof slot.site_code === \"string\" ? slot.site_code : null,\n zip_code: zip,\n address: {\n first_line: \"1 Main St\",\n second_line: \"\",\n city: cityState.city,\n state: cityState.state,\n zip_code: zip,\n unit: null,\n access_notes: null,\n },\n location,\n consumed_by_order_id: null,\n created_at: new Date(nowMs).toISOString(),\n })\n }\n }\n\n cacheKeyForRequest(\n method: string,\n pathname: string,\n searchParams?: URLSearchParams | string | Record<string, string> | null,\n body?: unknown,\n ): string {\n const params = new URLSearchParams()\n if (searchParams instanceof URLSearchParams) {\n for (const [key, value] of searchParams.entries()) params.append(key, value)\n } else if (typeof searchParams === \"string\") {\n const raw = searchParams.startsWith(\"?\") ? searchParams.slice(1) : searchParams\n for (const [key, value] of new URLSearchParams(raw).entries()) params.append(key, value)\n } else if (searchParams && typeof searchParams === \"object\") {\n for (const [key, value] of Object.entries(searchParams)) params.append(key, value)\n }\n const query = sortedQueryString(params)\n const url = `https://observation.local${pathname}${query ? `?${query}` : \"\"}`\n return observationCacheKey(url, method, body)\n }\n\n insertUser(user: UserRecord): void {\n this.users.insert(user.user_id, clone(user))\n this.byClientId.insert(user.client_user_id, { user_id: user.user_id })\n }\n\n insertOrder(order: OrderRecord): void {\n this.orders.insert(order.id, clone(order))\n const transactionId = order.order_transaction?.id\n if (typeof transactionId === \"string\" && transactionId.length > 0) {\n this.orderByTransaction.insert(transactionId, { order_id: order.id })\n }\n }\n\n insertAppointment(appointment: AppointmentRecord): void {\n this.appointments.insert(appointment.id, clone(appointment))\n this.appointmentsByOrder.insert(appointment.order_id, { appointment_id: appointment.id })\n }\n\n nextUserId(): string {\n for (let attempt = 0; attempt < 64; attempt += 1) {\n const token = this.ids.next(\"usr_\")\n const id = deterministicUuid(`junction:user:${token}`)\n if (!this.users.has(id) && !this.deletedUsers.has(id)) return id\n }\n const token = this.ids.next(\"usr_\")\n return deterministicUuid(`junction:user:post-seed:${token}:${this.users.list().length}`)\n }\n\n nextOrderId(): string {\n for (let attempt = 0; attempt < 64; attempt += 1) {\n const token = this.ids.next(\"ord_\")\n const id = deterministicUuid(`junction:order:${token}`)\n if (!this.orders.has(id)) return id\n }\n const token = this.ids.next(\"ord_\")\n return deterministicUuid(`junction:order:post-seed:${token}:${this.orders.list().length}`)\n }\n\n nextAppointmentId(): string {\n for (let attempt = 0; attempt < 64; attempt += 1) {\n const token = this.ids.next(\"apt_\")\n const id = deterministicUuid(`junction:appointment:${token}`)\n if (!this.appointments.has(id)) return id\n }\n const token = this.ids.next(\"apt_\")\n return deterministicUuid(\n `junction:appointment:post-seed:${token}:${this.appointments.list().length}`,\n )\n }\n\n bookingKeyFor(input: string): string {\n return deterministicUuid(`junction:booking:${input}`)\n }\n\n appointmentProviderIdFor(input: string): string {\n return opaqueToken(`junction:appointment-provider:${input}`, 12)\n }\n\n transactionIdFor(orderId: string): string {\n return deterministicUuid(`junction:transaction:${orderId}`)\n }\n\n testkitIdFor(orderId: string): string {\n return deterministicUuid(`junction:testkit:${orderId}`)\n }\n\n publishWebhook(event: JunctionWebhookEvent, now = Date.now()): void {\n const sequence = this.webhookEvents.nextSequence()\n const snapshot = clone(event)\n this.webhookEvents.insert(String(sequence), { sequence, event: snapshot })\n const messageId = deterministicUuid(`junction:webhook:${sequence}`)\n for (const [index, delay] of WEBHOOK_RETRY_DELAYS_MS.entries()) {\n const jitter =\n delay === 0 ? 0 : delay * this.webhookJitterRatio * (this.webhookRandom() * 2 - 1)\n const scheduledAt = new Date(now + Math.max(0, Math.round(delay + jitter))).toISOString()\n this.webhookDeliveryAttempts.insert(`${messageId}:${index + 1}`, {\n message_id: messageId,\n event: clone(snapshot),\n attempt: index + 1,\n scheduled_at: scheduledAt,\n timeout_ms: this.webhookTimeoutMs,\n acknowledged: index === 0,\n })\n }\n this.publishEvent?.(snapshot)\n }\n\n webhookEventsInOrder(): JunctionWebhookEvent[] {\n return this.webhookEvents.list({ order: \"oldest\" }).map((entry) => clone(entry.value.event))\n }\n\n webhookDeliveryAttemptsInOrder(): WebhookDeliveryAttempt[] {\n return this.webhookDeliveryAttempts.list({ order: \"oldest\" }).map((entry) => clone(entry.value))\n }\n\n publishOrderWebhook(\n order: OrderRecord,\n eventType: JunctionWebhookEvent[\"event_type\"],\n now = Date.now(),\n ): void {\n const user = this.users.get(order.user_id)\n if (!user) return\n this.publishWebhook(\n {\n event_type: eventType,\n data: order as unknown as Record<string, unknown>,\n team_id: order.team_id,\n user_id: order.user_id,\n client_user_id: user.client_user_id,\n },\n now,\n )\n }\n\n publishAppointmentWebhook(\n appointment: AppointmentRecord,\n teamId: string,\n now = Date.now(),\n ): void {\n const user = this.users.get(appointment.user_id)\n if (!user) return\n this.publishWebhook(\n {\n event_type: \"labtest.appointment.updated\",\n data: appointment as unknown as Record<string, unknown>,\n team_id: teamId,\n user_id: appointment.user_id,\n client_user_id: user.client_user_id,\n },\n now,\n )\n }\n\n queueSimulateTransition(transition: PendingSimulateTransition): void {\n this.pendingSimulateTransitions.insert(\n `${transition.order_id}:${transition.due_at}`,\n transition,\n )\n }\n\n /** Apply any simulate transitions whose delay has elapsed; called lazily on reads. */\n applyDueSimulateTransitions(\n nowMs: number,\n apply: (order: OrderRecord, finalStatus: string, flags: Record<string, unknown> | null) => void,\n ): void {\n for (const entry of this.pendingSimulateTransitions.list({ order: \"oldest\" })) {\n const transition = entry.value\n if (transition.due_at > nowMs) continue\n const order = this.orders.get(transition.order_id)\n if (order) apply(order, transition.final_status, transition.flags)\n this.pendingSimulateTransitions.delete(entry.id)\n }\n }\n\n isoNow(now: () => number): string {\n return new Date(now()).toISOString().replace(/\\.\\d{3}Z$/, \"+00:00\")\n }\n}\n", "/**\n * Team-level lab-account fixtures.\n *\n * Mirrors https://docs.junction.com/lab/overview/lab-accounts for a team-scoped API key:\n * the `ClientFacingLabAccount` shape, the account filters, the four documented selection\n * branches when `lab_account_id` is omitted, and the `allowed_billing` rules.\n *\n * No fixture is placed on `ussl` \u2014 an account there would flip that lab from the\n * platform branch to the linked branches and change shipped order behavior. The\n * branch-fixture labs (`nexus`, `mtl`, `crl`, `ihd`) have no catalog lab tests, so the\n * property suite seeds synthetic tests for them.\n */\nimport { HttpError, opaqueToken } from \"@crvouga/mockingbird-service\"\nimport { TEAM_LABS } from \"./catalog.js\"\nimport { deterministicUuid, MOCK_TEAM_ID } from \"./state.js\"\n\nexport type LabAccountStatus = \"active\" | \"pending\" | \"suspended\" | \"ready_to_launch\"\nexport type LabAccountDelegatedFlow =\n | \"order_delegated\"\n | \"result_delegated\"\n | \"fully_delegated\"\n | \"not_delegated\"\n\nexport type LabAccountRecord = {\n id: string\n lab: string\n org_id: string | null\n status: LabAccountStatus\n delegated_flow: LabAccountDelegatedFlow\n provider_account_id: string\n account_name: string | null\n default_clinical_notes: string | null\n business_units: string[] | null\n allowed_billing: Record<string, readonly string[]>\n team_id_allowlist: readonly string[]\n}\n\n/** The 50 `USState` values from the docs, alphabetical by state name. */\nexport const US_STATES: readonly string[] = [\n \"AL\",\n \"AK\",\n \"AZ\",\n \"AR\",\n \"CA\",\n \"CO\",\n \"CT\",\n \"DE\",\n \"FL\",\n \"GA\",\n \"HI\",\n \"ID\",\n \"IL\",\n \"IN\",\n \"IA\",\n \"KS\",\n \"KY\",\n \"LA\",\n \"ME\",\n \"MD\",\n \"MA\",\n \"MI\",\n \"MN\",\n \"MS\",\n \"MO\",\n \"MT\",\n \"NE\",\n \"NV\",\n \"NH\",\n \"NJ\",\n \"NM\",\n \"NY\",\n \"NC\",\n \"ND\",\n \"OH\",\n \"OK\",\n \"OR\",\n \"PA\",\n \"RI\",\n \"SC\",\n \"SD\",\n \"TN\",\n \"TX\",\n \"UT\",\n \"VT\",\n \"VA\",\n \"WA\",\n \"WV\",\n \"WI\",\n \"WY\",\n]\n\nexport const ALL_BILLING_STATES: readonly string[] = US_STATES\n\n/** `billing_type` values the vendored create-order body accepts. */\nexport const BILLING_TYPES = [\n \"client_bill\",\n \"commercial_insurance\",\n \"patient_bill_passthrough\",\n \"patient_bill\",\n \"upfront_payment\",\n] as const\n\nexport const LAB_ACCOUNT_STATUSES: readonly LabAccountStatus[] = [\n \"active\",\n \"pending\",\n \"suspended\",\n \"ready_to_launch\",\n]\n\nexport const MOCK_ORG_ID = deterministicUuid(\"junction:org:mock\")\n\n/** Junction platform accounts support every billing type in every state. */\nconst PLATFORM_BILLING: Record<string, readonly string[]> = Object.fromEntries(\n BILLING_TYPES.map((type) => [type, ALL_BILLING_STATES]),\n)\n\nconst CLIENT_BILL_ONLY: Record<string, readonly string[]> = { client_bill: ALL_BILLING_STATES }\n\nconst account = (\n key: string,\n lab: string,\n fields: Pick<LabAccountRecord, \"status\" | \"allowed_billing\" | \"team_id_allowlist\"> &\n Partial<Pick<LabAccountRecord, \"account_name\" | \"business_units\" | \"org_id\">>,\n): LabAccountRecord => ({\n id: deterministicUuid(`junction:lab-account:${key}`),\n lab,\n org_id: fields.org_id ?? MOCK_ORG_ID,\n status: fields.status,\n delegated_flow: \"not_delegated\",\n provider_account_id: opaqueToken(`junction:lab-account-provider:${key}`, 16),\n account_name: fields.account_name ?? null,\n default_clinical_notes: null,\n business_units: fields.business_units ?? null,\n allowed_billing: fields.allowed_billing,\n team_id_allowlist: fields.team_id_allowlist,\n})\n\nexport const TEAM_LAB_ACCOUNTS: readonly LabAccountRecord[] = [\n // Branch 2: exactly one active account linked for `quest`; the commercial-insurance\n // state rule lives on this account.\n account(\"quest-primary\", \"quest\", {\n status: \"active\",\n account_name: \"Quest Diagnostics \u2014 primary\",\n business_units: [\"core\", \"specialty\"],\n allowed_billing: {\n client_bill: ALL_BILLING_STATES,\n commercial_insurance: [\"AZ\", \"CA\"],\n },\n team_id_allowlist: [MOCK_TEAM_ID],\n }),\n // Listed but never selected; exercises `status` filters and the explicit-id rejection.\n account(\"quest-pending\", \"quest\", {\n status: \"pending\",\n account_name: \"Quest Diagnostics \u2014 pending\",\n allowed_billing: CLIENT_BILL_ONLY,\n team_id_allowlist: [MOCK_TEAM_ID],\n }),\n // Branch 3: multiple active accounts linked for `nexus`.\n account(\"nexus-a\", \"nexus\", {\n status: \"active\",\n account_name: \"Nexus \u2014 A\",\n allowed_billing: CLIENT_BILL_ONLY,\n team_id_allowlist: [MOCK_TEAM_ID],\n }),\n account(\"nexus-b\", \"nexus\", {\n status: \"active\",\n account_name: \"Nexus \u2014 B\",\n allowed_billing: CLIENT_BILL_ONLY,\n team_id_allowlist: [MOCK_TEAM_ID],\n }),\n // Branch 4: linked accounts, none active.\n account(\"mtl-suspended\", \"mtl\", {\n status: \"suspended\",\n account_name: \"Molecular Testing Labs \u2014 suspended\",\n allowed_billing: CLIENT_BILL_ONLY,\n team_id_allowlist: [MOCK_TEAM_ID],\n }),\n account(\"mtl-pending\", \"mtl\", {\n status: \"pending\",\n allowed_billing: CLIENT_BILL_ONLY,\n team_id_allowlist: [MOCK_TEAM_ID],\n }),\n // `status` filter coverage for the enum's last value.\n account(\"crl-ready\", \"crl\", {\n status: \"ready_to_launch\",\n allowed_billing: CLIENT_BILL_ONLY,\n team_id_allowlist: [MOCK_TEAM_ID],\n }),\n // Org-owned account of another team: absent from the team listing, rejected when used.\n account(\"ihd-other-team\", \"ihd\", {\n status: \"active\",\n account_name: \"IHD \u2014 other team\",\n allowed_billing: CLIENT_BILL_ONLY,\n team_id_allowlist: [],\n }),\n]\n\n/** Every lab slug in the team lab inventory \u2014 these labs have a Junction platform account. */\nexport const PLATFORM_ACCOUNT_LABS: readonly string[] = TEAM_LABS.map((lab) => String(lab.slug))\n\nexport const labAccountById = (\n id: string,\n accounts: readonly LabAccountRecord[] = TEAM_LAB_ACCOUNTS,\n): LabAccountRecord | undefined => accounts.find((entry) => entry.id === id)\n\n/** Team-linked accounts for a lab, in configured order. */\nexport const linkedLabAccounts = (\n labSlug: string,\n teamId: string,\n accounts: readonly LabAccountRecord[] = TEAM_LAB_ACCOUNTS,\n): LabAccountRecord[] =>\n accounts.filter((entry) => entry.lab === labSlug && entry.team_id_allowlist.includes(teamId))\n\nexport const effectiveBilling = (\n account: LabAccountRecord | \"platform\",\n): Record<string, readonly string[]> =>\n account === \"platform\" ? PLATFORM_BILLING : account.allowed_billing\n\n/**\n * The documented selection rules, in order: an explicit id must exist, be linked to the\n * team, match the ordered lab and be active; with no id, linked accounts are evaluated\n * against the four documented branches.\n */\nexport const selectLabAccount = (\n labSlug: string,\n requestedId: string | null,\n teamId: string,\n accounts: readonly LabAccountRecord[] = TEAM_LAB_ACCOUNTS,\n): LabAccountRecord | \"platform\" => {\n if (requestedId !== null) {\n const linked = labAccountById(requestedId, accounts)\n if (!linked) throw new HttpError(400, { detail: \"Lab account does not exist\" })\n if (!linked.team_id_allowlist.includes(teamId))\n throw new HttpError(400, { detail: \"Lab account is not linked to your team\" })\n if (linked.lab !== labSlug)\n throw new HttpError(400, { detail: `Lab account is not associated with lab ${labSlug}` })\n if (linked.status !== \"active\")\n throw new HttpError(400, { detail: \"Lab account is not active\" })\n return linked\n }\n const candidates = linkedLabAccounts(labSlug, teamId, accounts)\n if (candidates.length === 0) {\n if (PLATFORM_ACCOUNT_LABS.includes(labSlug)) return \"platform\"\n throw new HttpError(400, { detail: `No active lab account is available for lab ${labSlug}` })\n }\n const active = candidates.filter((entry) => entry.status === \"active\")\n if (active.length === 1) return active[0] as LabAccountRecord\n if (active.length > 1)\n throw new HttpError(400, {\n detail:\n \"Multiple active lab accounts are linked to your team for this lab; provide lab_account_id\",\n })\n throw new HttpError(400, { detail: \"No active lab account is available for this lab\" })\n}\n\n/** Render only the documented `ClientFacingLabAccount` keys. */\nexport const renderLabAccount = (entry: LabAccountRecord): Record<string, unknown> => ({\n id: entry.id,\n lab: entry.lab,\n org_id: entry.org_id,\n status: entry.status,\n delegated_flow: entry.delegated_flow,\n provider_account_id: entry.provider_account_id,\n account_name: entry.account_name,\n default_clinical_notes: entry.default_clinical_notes,\n business_units: entry.business_units === null ? null : [...entry.business_units],\n allowed_billing: Object.fromEntries(\n Object.entries(entry.allowed_billing).map(([type, states]) => [type, [...states]]),\n ),\n team_id_allowlist: [...entry.team_id_allowlist],\n})\n\n/**\n * A lab account as a consumer configures it. Mirrors `ClientFacingLabAccount`, with\n * every field but `id` and `lab` optional, plus a `states` shorthand for the common\n * case of an account that client-bills in a fixed set of states.\n */\nexport type LabAccountInput = {\n id: string\n /** Lab slug, e.g. `\"quest\"`, `\"labcorp\"`, `\"bioreference\"`. */\n lab: string\n status?: LabAccountStatus\n delegated_flow?: LabAccountDelegatedFlow\n account_name?: string | null\n provider_account_id?: string\n org_id?: string | null\n business_units?: string[] | null\n default_clinical_notes?: string | null\n /** Billing type \u2192 states it is allowed in. Takes precedence over `states`. */\n allowed_billing?: Record<string, readonly string[]>\n /** Shorthand for `allowed_billing: { client_bill: states }`. Default: every state. */\n states?: readonly string[]\n /** Teams the account is linked to. Default: the mock team, so it is selectable. */\n team_id_allowlist?: readonly string[]\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\nconst stringList = (value: unknown): string[] | undefined =>\n Array.isArray(value) && value.every((entry) => typeof entry === \"string\")\n ? [...(value as string[])]\n : undefined\n\n/** Normalize a consumer's configuration into the record the ordering rules read. */\nexport const labAccountFromInput = (input: LabAccountInput): LabAccountRecord => {\n if (typeof input.id !== \"string\" || input.id === \"\")\n throw new TypeError(\"lab account needs a non-empty id\")\n if (typeof input.lab !== \"string\" || input.lab === \"\")\n throw new TypeError(`lab account ${input.id} needs a lab slug`)\n for (const state of input.states ?? []) {\n if (!US_STATES.includes(state))\n throw new TypeError(`lab account ${input.id}: ${state} is not a US state code`)\n }\n return {\n id: input.id,\n lab: input.lab.toLowerCase(),\n org_id: input.org_id === undefined ? MOCK_ORG_ID : input.org_id,\n status: input.status ?? \"active\",\n delegated_flow: input.delegated_flow ?? \"not_delegated\",\n provider_account_id:\n input.provider_account_id ?? opaqueToken(`junction:lab-account-provider:${input.id}`, 16),\n account_name: input.account_name ?? null,\n default_clinical_notes: input.default_clinical_notes ?? null,\n business_units: input.business_units ?? null,\n allowed_billing: input.allowed_billing ?? { client_bill: input.states ?? ALL_BILLING_STATES },\n team_id_allowlist: input.team_id_allowlist ?? [MOCK_TEAM_ID],\n }\n}\n\n/**\n * Read a `ClientFacingLabAccount` from a real team's listing (a pulled corpus).\n *\n * The listing only returns accounts linked to the calling team, so each one is linked\n * to the mock team too \u2014 the real team id is kept alongside, never replaced.\n */\nexport const labAccountFromClientFacing = (\n value: Record<string, unknown>,\n): LabAccountRecord | undefined => {\n if (typeof value.id !== \"string\" || typeof value.lab !== \"string\") return undefined\n const billing: Record<string, readonly string[]> = {}\n if (isRecord(value.allowed_billing)) {\n for (const [type, states] of Object.entries(value.allowed_billing)) {\n const list = stringList(states)\n if (list) billing[type] = list\n }\n }\n const allowlist = stringList(value.team_id_allowlist) ?? []\n return {\n id: value.id,\n lab: value.lab.toLowerCase(),\n org_id: typeof value.org_id === \"string\" ? value.org_id : null,\n status: LAB_ACCOUNT_STATUSES.includes(value.status as LabAccountStatus)\n ? (value.status as LabAccountStatus)\n : \"active\",\n delegated_flow:\n typeof value.delegated_flow === \"string\"\n ? (value.delegated_flow as LabAccountDelegatedFlow)\n : \"not_delegated\",\n provider_account_id:\n typeof value.provider_account_id === \"string\"\n ? value.provider_account_id\n : opaqueToken(`junction:lab-account-provider:${value.id}`, 16),\n account_name: typeof value.account_name === \"string\" ? value.account_name : null,\n default_clinical_notes:\n typeof value.default_clinical_notes === \"string\" ? value.default_clinical_notes : null,\n business_units: stringList(value.business_units) ?? null,\n allowed_billing: billing,\n team_id_allowlist: allowlist.includes(MOCK_TEAM_ID) ? allowlist : [...allowlist, MOCK_TEAM_ID],\n }\n}\n", "/**\n * Appointment scheduling surface: phlebotomy + PSC availability/booking lifecycle,\n * cancellation reasons, area serviceability, and PSC site info.\n *\n * Slot data is generated deterministically (seeded by zip/site/date), so walks are\n * reproducible without any provider-side state.\n */\nimport {\n HttpError,\n jsonRes,\n type OperationContext,\n opaqueToken,\n} from \"@crvouga/mockingbird-service\"\nimport { type LabAccountRecord, labAccountById } from \"./lab-accounts.js\"\nimport type {\n AppointmentEventRecord,\n AppointmentModality,\n AppointmentRecord,\n BookingKeyRecord,\n JunctionState,\n} from \"./state.js\"\nimport { MOCK_TEAM_ID } from \"./state.js\"\n\n/** Status of the unknown-ZIP error: unused by Junction, and not retried by HTTP clients. */\nexport const UNKNOWN_ZIP_STATUS = 424\nexport const UNKNOWN_ZIP_ERROR_TYPE = \"MOCKINGBIRD_UNKNOWN_ZIP\"\n\n/**\n * In `corpus` geo mode, refuse a ZIP the corpus has no serviceability record for.\n *\n * The error is deliberately not Junction-shaped in status: a consumer that classifies\n * vendor errors must not mistake a fixture gap for a real validation failure and carry\n * on. It fails loudly, and says how to close the gap.\n */\nconst requireCoveredZip = (state: JunctionState, zip: string): void => {\n if (state.geoMode !== \"corpus\" || state.coveredZips.has(zip)) return\n throw new HttpError(UNKNOWN_ZIP_STATUS, {\n detail: {\n error_type: UNKNOWN_ZIP_ERROR_TYPE,\n error_message: `ZIP ${zip} is not in the loaded Junction corpus (${String(state.coveredZips.size)} ZIPs covered). Record it with \\`mockingbird-junction corpus pull --zip ${zip}\\`, or serve with --geo synthetic to invent coverage.`,\n zip_code: zip,\n corpus: state.corpusLabel ?? null,\n },\n })\n}\n\nconst cachedResponse = (state: JunctionState, context: OperationContext) => {\n const body =\n context.request.method.toUpperCase() === \"GET\" ||\n context.request.method.toUpperCase() === \"HEAD\"\n ? undefined\n : context.body.kind === \"json\"\n ? context.body.value\n : context.body.kind === \"form\"\n ? context.body.value\n : undefined\n const key = state.cacheKeyForRequest(\n context.request.method,\n context.url.pathname,\n context.url.searchParams,\n body,\n )\n const cached = state.getGetCache(key)\n if (!cached) return undefined\n if (key.toLowerCase().includes(\"availability\")) {\n materializeAvailabilityBookingKeys(state, context, cached.body)\n rotateAvailabilityBookingKeys(state, cached.body, context.now())\n }\n const headers = new Headers(cached.headers)\n // The recorded body is served uncompressed, so drop transfer/encoding headers captured\n // from the sandbox response or a client would try to decompress plain JSON.\n headers.delete(\"content-encoding\")\n headers.delete(\"content-length\")\n headers.delete(\"transfer-encoding\")\n if (!headers.has(\"content-type\")) headers.set(\"content-type\", \"application/json\")\n return new Response(JSON.stringify(cached.body), { status: cached.status, headers })\n}\n\n/**\n * Ensure booking_key records exist for a cached availability response.\n * Prefer deterministic slot generation (rich address/provider), then fill any remaining\n * oracle keys from the cached body using the request zip.\n */\nconst materializeAvailabilityBookingKeys = (\n state: JunctionState,\n context: OperationContext,\n cachedBody: unknown,\n) => {\n const requestBody =\n context.body.kind === \"json\" &&\n typeof context.body.value === \"object\" &&\n context.body.value !== null &&\n !Array.isArray(context.body.value)\n ? (context.body.value as Record<string, unknown>)\n : {}\n const zip =\n typeof requestBody.zip_code === \"string\" && /^\\d{5}/.test(requestBody.zip_code)\n ? requestBody.zip_code.slice(0, 5)\n : \"85004\"\n const path = context.url.pathname\n const modalityHint = path.includes(\"psc\")\n ? (\"patient_service_center\" as const)\n : path.includes(\"phlebotomy\")\n ? (\"phlebotomy\" as const)\n : undefined\n state.hydrateBookingKeysFromAvailability(cachedBody, context.now(), zip, modalityHint)\n // Normalize address/provider/modality on oracle keys so book/reschedule match generated shape.\n if (typeof cachedBody === \"object\" && cachedBody !== null && !Array.isArray(cachedBody)) {\n const root = cachedBody as Record<string, unknown>\n const dayBuckets: unknown[] = []\n if (Array.isArray(root.days)) dayBuckets.push(...root.days)\n if (Array.isArray(root.slots)) dayBuckets.push(...root.slots)\n for (const day of dayBuckets) {\n if (typeof day !== \"object\" || day === null || Array.isArray(day)) continue\n const daySlots = (day as Record<string, unknown>).slots\n const slots = Array.isArray(daySlots) ? daySlots : [day]\n for (const entry of slots) {\n if (typeof entry !== \"object\" || entry === null || Array.isArray(entry)) continue\n const slot = entry as Record<string, unknown>\n const bookingKey = typeof slot.booking_key === \"string\" ? slot.booking_key : \"\"\n if (!bookingKey) continue\n const record = state.bookingKeys.get(bookingKey)\n if (!record) continue\n if (modalityHint) record.modality = modalityHint\n record.zip_code = zip\n record.provider = record.modality === \"patient_service_center\" ? \"quest\" : \"getlabs\"\n record.address = addressFromAvailabilityRequest(requestBody, zip)\n record.location = zipLocation(zip)\n state.bookingKeys.update(bookingKey, record)\n }\n }\n }\n}\n\n/**\n * Vital mints fresh booking_key values on every availability response while the slot\n * skeleton stays stable, and previously issued keys remain bookable. Mirror that: each\n * serve registers a new record per slot position (deriving slot facts from the current\n * record for that position) and rewrites the served body, leaving stale keys bookable\n * until consumed/expired.\n */\nconst rotateAvailabilityBookingKeys = (\n state: JunctionState,\n cachedBody: unknown,\n nowMs: number,\n): void => {\n if (typeof cachedBody !== \"object\" || cachedBody === null || Array.isArray(cachedBody)) return\n const root = cachedBody as Record<string, unknown>\n const dayBuckets: unknown[] = []\n if (Array.isArray(root.days)) dayBuckets.push(...root.days)\n if (Array.isArray(root.slots)) dayBuckets.push(...root.slots)\n for (const day of dayBuckets) {\n if (typeof day !== \"object\" || day === null || Array.isArray(day)) continue\n const daySlots = (day as Record<string, unknown>).slots\n const slots = Array.isArray(daySlots) ? daySlots : [day]\n for (let index = 0; index < slots.length; index += 1) {\n const slot = slots[index]\n if (typeof slot !== \"object\" || slot === null || Array.isArray(slot)) continue\n const entry = slot as Record<string, unknown>\n const sealedKey = typeof entry.booking_key === \"string\" ? entry.booking_key : \"\"\n if (!sealedKey) continue\n const sealed = state.bookingKeys.get(sealedKey)\n if (!sealed) continue\n const freshKey = bookingKeyRotationFor(state, sealedKey, nowMs, index)\n const record: BookingKeyRecord = {\n ...sealed,\n key: freshKey,\n consumed_by_order_id: null,\n created_at: new Date(nowMs).toISOString(),\n }\n state.bookingKeys.insert(freshKey, record)\n entry.booking_key = freshKey\n }\n }\n}\n\n/**\n * Derive a fresh, unused booking key for a rotated slot. Mixing the sealed key, clock,\n * slot index, and an attempt counter keeps re-serves unique even under frozen test\n * clocks where consecutive serves share the same millisecond.\n */\nconst bookingKeyRotationFor = (\n state: JunctionState,\n sealedKey: string,\n nowMs: number,\n index: number,\n): string => {\n for (let attempt = 0; attempt < 64; attempt += 1) {\n const candidate = state.bookingKeyFor(`rotation:${sealedKey}:${nowMs}:${index}:${attempt}`)\n if (!state.bookingKeys.has(candidate)) return candidate\n }\n return state.bookingKeyFor(\n `rotation:${sealedKey}:${nowMs}:${index}:fallback:${state.bookingKeys.list().length}`,\n )\n}\n\n/**\n * Rotation for the generated (cache-miss) availability paths: newly created slot\n * records are replaced with fresh records on every serve so repeated reads mint\n * fresh keys like the oracle, and the served body carries only the fresh keys.\n * When `override` is given (phlebotomy \u2014 Vital echoes the availability request\n * address on book), the fresh record's address/location/zip are re-aligned.\n */\nconst rotateGeneratedAvailabilityKeys = (\n state: JunctionState,\n days: Array<Record<string, unknown>>,\n nowMs: number,\n override?: {\n address: Record<string, unknown>\n location: { lng: number; lat: number }\n zip: string\n },\n): void => {\n for (const day of days) {\n const slots = Array.isArray(day.slots) ? day.slots : []\n for (let index = 0; index < slots.length; index += 1) {\n const slot = slots[index]\n if (typeof slot !== \"object\" || slot === null || Array.isArray(slot)) continue\n const entry = slot as Record<string, unknown>\n const currentKey = typeof entry.booking_key === \"string\" ? entry.booking_key : \"\"\n if (!currentKey) continue\n const current = state.bookingKeys.get(currentKey)\n if (!current) continue\n const freshKey = bookingKeyRotationFor(state, currentKey, nowMs, index)\n const record: BookingKeyRecord = {\n ...current,\n key: freshKey,\n ...(override ?? {}),\n consumed_by_order_id: null,\n created_at: new Date(nowMs).toISOString(),\n }\n state.bookingKeys.insert(freshKey, record)\n entry.booking_key = freshKey\n }\n }\n}\n\nconst PHLEBOTOMY_PROVIDERS = [\"getlabs\", \"phlebfinders\"] as const\ntype PhlebotomyProviderName = (typeof PHLEBOTOMY_PROVIDERS)[number]\n\nconst zipTimezone = (zip: string): string => {\n const prefix = Number(zip.slice(0, 3))\n if (!Number.isFinite(prefix) || prefix === 0) return \"America/New_York\"\n if (prefix < 500) return \"America/New_York\"\n if (prefix < 800) return \"America/Chicago\"\n // Arizona does not observe DST \u2014 Vital uses America/Phoenix for 850\u2013865.\n if (prefix >= 850 && prefix <= 865) return \"America/Phoenix\"\n if (prefix < 900) return \"America/Denver\"\n return \"America/Los_Angeles\"\n}\n\n/** Known Vital sandbox centroids for booking location parity. */\nconst ZIP_LOCATION: Readonly<Record<string, { lat: number; lng: number }>> = {\n \"85004\": { lat: 33.6242904, lng: -111.9283407 },\n}\n\nconst zipLocation = (zip: string): { lat: number; lng: number } => {\n const known = ZIP_LOCATION[zip.slice(0, 5)]\n if (known) return { ...known }\n // Deterministic fallback centroid so unknown zips stay stable across runs.\n const prefix = Number(zip.slice(0, 3)) || 0\n return {\n lat: 30 + (prefix % 20) * 0.4,\n lng: -120 + (prefix % 30) * 0.5,\n }\n}\n\nconst cityStateForZip = (zip: string): { city: string; state: string } => {\n const tz = zipTimezone(zip)\n if (tz === \"America/Phoenix\") return { city: \"Phoenix\", state: \"AZ\" }\n if (tz === \"America/Los_Angeles\") return { city: \"Los Angeles\", state: \"CA\" }\n if (tz === \"America/Denver\") return { city: \"Denver\", state: \"CO\" }\n if (tz === \"America/Chicago\") return { city: \"Chicago\", state: \"IL\" }\n return { city: \"New York\", state: \"NY\" }\n}\n\nexport const addressFromAvailabilityRequest = (\n requestBody: Record<string, unknown>,\n zip: string,\n): Record<string, unknown> => {\n const { city, state } = cityStateForZip(zip)\n const firstLine =\n typeof requestBody.first_line === \"string\" && requestBody.first_line.length > 0\n ? requestBody.first_line\n : \"1 Main St\"\n const secondLine =\n typeof requestBody.second_line === \"string\"\n ? requestBody.second_line\n : requestBody.second_line === null\n ? \"\"\n : \"\"\n return {\n first_line: firstLine,\n second_line: secondLine,\n city:\n typeof requestBody.city === \"string\" && requestBody.city.length > 0 ? requestBody.city : city,\n state:\n typeof requestBody.state === \"string\" && requestBody.state.length > 0\n ? requestBody.state\n : state,\n zip_code:\n typeof requestBody.zip_code === \"string\" && /^\\d{5}/.test(requestBody.zip_code)\n ? requestBody.zip_code.slice(0, 5)\n : zip,\n unit: typeof requestBody.unit === \"string\" ? requestBody.unit : null,\n access_notes: null,\n }\n}\n\nconst seededRandom = (seed: number): (() => number) => {\n let value = seed >>> 0 || 1\n return () => {\n value = (value * 1664525 + 1013904223) >>> 0\n return value / 0x1_0000_0000\n }\n}\n\nconst seedFor = (parts: ReadonlyArray<string | number>): number => {\n let hash = 0x811c9dc5\n for (const part of parts) {\n const text = String(part)\n for (let i = 0; i < text.length; i++) {\n hash ^= text.charCodeAt(i)\n hash = Math.imul(hash, 0x01000193) >>> 0\n }\n }\n return hash >>> 0\n}\n\nconst isoDate = (date: Date): string => date.toISOString().slice(0, 10)\n\nconst addDays = (iso: string, days: number): string => {\n const date = new Date(`${iso}T00:00:00Z`)\n date.setUTCDate(date.getUTCDate() + days)\n return isoDate(date)\n}\n\nconst SCHEDULED_ORDER_EVENT: Record<AppointmentModality, string> = {\n phlebotomy: \"collecting_sample.at_home_phlebotomy.appointment_scheduled\",\n patient_service_center: \"collecting_sample.walk_in_test.appointment_scheduled\",\n}\n\nconst CANCELLED_ORDER_EVENT: Record<AppointmentModality, string> = {\n phlebotomy: \"collecting_sample.at_home_phlebotomy.appointment_cancelled\",\n patient_service_center: \"collecting_sample.walk_in_test.appointment_cancelled\",\n}\n\nexport const CANCELLATION_REASONS = [\n {\n id: \"5c0257ef-6fea-4a22-b20a-3ddab573d5c9\",\n name: \"Did not fast for appointment\",\n is_refundable: true,\n },\n { id: \"448c519c-64b4-4497-ae73-622fa93371b3\", name: \"Do not trust company\", is_refundable: true },\n {\n id: \"d378e152-12d1-433e-9dd1-e0410f9331dc\",\n name: \"Getlabs cannot deliver to my preferred lab\",\n is_refundable: true,\n },\n { id: \"7be75f90-303d-4656-8eed-9bd3e20cb2cc\", name: \"Getlabs - late\", is_refundable: true },\n {\n id: \"ae3ec4dc-387c-42ac-835a-bf88fc4e411b\",\n name: \"Getlabs -Phleb Out Sick\",\n is_refundable: true,\n },\n {\n id: \"e2396e00-dd49-4f38-a395-51d6304c3312\",\n name: \"Getlabs rescheduled time does not work for patient\",\n is_refundable: true,\n },\n { id: \"5330c863-ac80-4316-901b-d305d0df74d5\", name: \"No longer interested\", is_refundable: true },\n { id: \"2b9f23fd-163e-4483-bb10-90c74a67e0dc\", name: \"Other\", is_refundable: true },\n {\n id: \"98f861dd-fe61-4817-a9d6-1b99b19cd0fb\",\n name: \"Provider asked me to cancel\",\n is_refundable: true,\n },\n {\n id: \"7dfd7da5-ed6e-40bb-a7e4-c8003f0c10a9\",\n name: \"Scheduled for wrong patient\",\n is_refundable: true,\n },\n {\n id: \"796da8c8-e654-4347-8ded-1026410c1976\",\n name: \"Scheduled time no longer works\",\n is_refundable: true,\n },\n {\n id: \"ba02af35-a34f-4a7a-abe5-5f766e8f6cd1\",\n name: \"Unable to get lab order from provider\",\n is_refundable: true,\n },\n {\n id: \"0c9425db-f11e-49c5-b976-3c0d1d4a4ea8\",\n name: \"Wanted to book in-person appointment\",\n is_refundable: true,\n },\n {\n id: \"2599a0ea-0b4a-42fe-8df6-d8f7c68182e7\",\n name: \"Went to lab for appointment\",\n is_refundable: true,\n },\n] as const\n\n/** PSC offers a single cancellation reason in the sandbox. */\nexport const PSC_CANCELLATION_REASONS = [\n { id: \"226a6520-667c-495f-8500-c20722d231d0\", name: \"Other\", is_refundable: true },\n] as const\n\n/** The phlebotomy reason named \"Other\" requires explanatory notes. */\nexport const OTHER_CANCELLATION_REASON_ID = \"2b9f23fd-163e-4483-bb10-90c74a67e0dc\"\n\nconst PSC_LABS = [\n {\n lab_id: 25,\n slug: \"sonora_quest\",\n supported_bill_types: [\"client_bill\"],\n capabilities: [\"appointment_scheduling_via_junction\"],\n },\n {\n lab_id: 6,\n slug: \"labcorp\",\n supported_bill_types: [\"client_bill\", \"commercial_insurance\", \"patient_bill\"],\n capabilities: [],\n },\n {\n lab_id: 13,\n slug: \"bioreference\",\n supported_bill_types: [\"patient_bill_passthrough\"],\n capabilities: [],\n },\n {\n lab_id: 4,\n slug: \"quest\",\n supported_bill_types: [\"client_bill\", \"commercial_insurance\", \"patient_bill\"],\n capabilities: [\"appointment_scheduling_via_junction\"],\n },\n] as const\n\n/** Lab 3 (USSL) exists in the catalog but is excluded from PSC info in the sandbox. */\nexport const UNSUPPORTED_PSC_LAB_ID = 3\n\nconst AREA_LAB_BILLS: Readonly<Record<string, readonly string[]>> = {\n sonora_quest: [\"client_bill\"],\n labcorp: [\"client_bill\", \"commercial_insurance\", \"patient_bill\"],\n bioreference: [\"patient_bill_passthrough\"],\n quest: [\"client_bill\", \"commercial_insurance\", \"patient_bill\"],\n}\n\nconst AREA_LABS: ReadonlyArray<{\n slug: string\n lab_id: number\n appointment_with_vital: boolean\n capabilities: readonly string[]\n}> = [\n { slug: \"sonora_quest\", lab_id: 25, appointment_with_vital: true, capabilities: [] },\n { slug: \"labcorp\", lab_id: 6, appointment_with_vital: false, capabilities: [] },\n { slug: \"bioreference\", lab_id: 13, appointment_with_vital: false, capabilities: [] },\n {\n slug: \"quest\",\n lab_id: 4,\n appointment_with_vital: true,\n capabilities: [\"appointment_scheduling_via_junction\"],\n },\n]\n\n/** Zips where getlabs phlebotomy is offered (mirrors sandbox coverage). */\nconst PHLEBOTOMY_SERVED_PREFIXES: readonly number[] = [850, 900, 303, 917, 891]\n\nconst phlebotomyServed = (zip: string): boolean => {\n const prefix = Number(zip.slice(0, 3))\n return PHLEBOTOMY_SERVED_PREFIXES.includes(prefix)\n}\n\n/**\n * Deterministic PSC inventory model: the true number of sites within the radius is a\n * seeded function of zip + lab scaled by radius (the sandbox derives it from real geo\n * data); `psc/info` returns the nearest sites capped at 30. Unserviced zip prefixes\n * (000, 96x territories with no national-lab coverage) have no inventory.\n */\nconst UNSERVICED_PSC_PREFIXES: readonly number[] = [0]\n\nconst withinRadiusFor = (zip: string, labSlug: string, radius: number): number => {\n if (UNSERVICED_PSC_PREFIXES.includes(Number(zip.slice(0, 3)))) return 0\n const seed = seedFor([\"psc-count\", zip, labSlug])\n const fraction = seededRandom(seed)()\n return Math.round(fraction * radius * 1.6)\n}\n\nconst PSC_SITE_NAMES = [\"Downtown\", \"Midtown\", \"Harbor\", \"Central\", \"University\", \"Parkside\"]\nconst PSC_SITE_HOURS: Readonly<Record<string, string>> = {\n monday: \"08:00-17:00\",\n tuesday: \"08:00-17:00\",\n wednesday: \"08:00-17:00\",\n thursday: \"08:00-17:00\",\n friday: \"08:00-14:00\",\n}\n\nconst pscSiteFor = (zip: string, labSlug: string, index: number, radius: number) => {\n const random = seededRandom(seedFor([\"psc-site\", zip, labSlug, index]))\n const prefix = Number(zip.slice(0, 3))\n const state = prefix >= 900 ? \"CA\" : prefix >= 600 ? \"CO\" : prefix >= 300 ? \"GA\" : \"NY\"\n const city = PSC_SITE_NAMES[index % PSC_SITE_NAMES.length]\n const siteCodeSeed = seededRandom(seedFor([\"psc-code\", labSlug, index]))\n const siteCode =\n labSlug === \"quest\" || labSlug === \"sonora_quest\"\n ? Array.from({ length: 3 }, () =>\n String.fromCharCode(65 + Math.floor(siteCodeSeed() * 26)),\n ).join(\"\")\n : String(10_000 + Math.floor(siteCodeSeed() * 89_999))\n return {\n name: `${labSlug.replace(\"_\", \" \")} - ${city}`,\n state,\n city,\n zip_code: zip,\n first_line: `${100 + Math.floor(random() * 800)} Main St`,\n phone_number: `+1${200 + Math.floor(random() * 700)}555${String(1000 + Math.floor(random() * 8999))}`,\n hours: PSC_SITE_HOURS,\n distance: Math.round((0.5 + random() * radius) * 10) / 10,\n site_code: siteCode,\n location: {\n lng: -122.4 + (random() - 0.5) * 0.2,\n lat: 37.77 + (random() - 0.5) * 0.2,\n },\n }\n}\n\n/**\n * Deterministic area model: `within_radius` mirrors the PSC inventory count per lab, the\n * phlebotomy section mirrors getlabs market coverage, and central_labs always lists the\n * four national labs with their billing/capability profiles.\n *\n * With a lab account, the availability check is scoped to that account: `central_labs`\n * contains only the account's lab (empty when the account's lab has no area profile) and\n * `supported_bill_types` comes from the account's `allowed_billing` keys.\n */\nconst areaInfoFor = (zip: string, radius: number, account: LabAccountRecord | null = null) => {\n const served = phlebotomyServed(zip)\n const centralLabs: Record<string, unknown> = {}\n const labs = account === null ? AREA_LABS : AREA_LABS.filter((lab) => lab.slug === account.lab)\n for (const lab of labs) {\n centralLabs[lab.slug] = {\n patient_service_centers: {\n appointment_with_vital: lab.appointment_with_vital,\n within_radius: withinRadiusFor(zip, lab.slug, radius),\n radius: String(radius),\n capabilities: [...lab.capabilities],\n },\n supported_bill_types:\n account === null\n ? [...(AREA_LAB_BILLS[lab.slug] ?? [])]\n : Object.keys(account.allowed_billing),\n lab_id: lab.lab_id,\n }\n }\n return {\n zip_code: zip,\n phlebotomy: {\n is_served: served,\n providers: served ? [{ name: \"getlabs\", service_types: [\"appointment-ready\"] }] : [],\n },\n central_labs: centralLabs,\n }\n}\n\nconst jsonObject = (context: OperationContext): Record<string, unknown> => {\n const body = context.body\n const value = body.kind === \"json\" ? body.value : undefined\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new HttpError(422, {\n detail: [\n {\n type: \"model_attributes_type\",\n loc: [\"body\"],\n msg: \"Input should be a valid dictionary or object to extract fields from\",\n input: value,\n },\n ],\n })\n }\n return value as Record<string, unknown>\n}\n\nconst isUuid = (value: string): boolean =>\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)\n\nconst uuidError = (value: string, loc: string[]) => {\n const characters = Array.from(value)\n const invalidIndex = characters.findIndex((character) => !/^[0-9a-f-]$/i.test(character))\n const error =\n invalidIndex >= 0\n ? `invalid character: expected an optional prefix of \\`urn:uuid:\\` followed by [0-9a-fA-F-], found \\`${characters[invalidIndex]}\\` at ${invalidIndex + 1}`\n : `invalid length: expected length 32 for simple format, found ${value.replaceAll(\"-\", \"\").length}`\n return {\n type: \"uuid_parsing\",\n loc,\n msg: `Input should be a valid UUID, ${error}`,\n input: value,\n ctx: { error },\n }\n}\n\nconst ALLOWED_RADII = [10, 20, 25, 50, 100] as const\nconst DEFAULT_RADIUS = 25\n\nconst radiusOf = (context: OperationContext): number => {\n const raw = context.query.radius\n if (raw === undefined) return DEFAULT_RADIUS\n const value = typeof raw === \"string\" && /^\\d+$/.test(raw) ? Number(raw) : Number.NaN\n if (!ALLOWED_RADII.includes(value as (typeof ALLOWED_RADII)[number])) {\n throw new HttpError(422, {\n detail: [\n {\n type: \"enum\",\n loc: [\"query\", \"radius\"],\n msg: \"Input should be '10', '20', '25', '50' or '100'\",\n input: raw,\n ctx: { expected: \"'10', '20', '25', '50' or '100'\" },\n },\n ],\n })\n }\n return value\n}\n\nconst zipCodeOf = (context: OperationContext, required: boolean): string | undefined => {\n const raw = context.query.zip_code\n if (raw === undefined) {\n if (required) {\n throw new HttpError(422, {\n detail: [\n {\n type: \"missing\",\n loc: [\"query\", \"zip_code\"],\n msg: \"Field required\",\n input: undefined,\n },\n ],\n })\n }\n return undefined\n }\n if (typeof raw !== \"string\") throw new HttpError(422, { detail: \"zip_code must be a string\" })\n return raw\n}\n\n/**\n * Optional `lab_account_id` for an availability check: it must be a UUID, exist for this\n * team, and be active \u2014 the same account rules Create Order applies.\n */\nconst labAccountOf = (context: OperationContext): LabAccountRecord | null => {\n const raw = context.query.lab_account_id\n if (raw === undefined) return null\n if (typeof raw !== \"string\" || !isUuid(raw)) {\n throw new HttpError(422, {\n detail: [uuidError(typeof raw === \"string\" ? raw : String(raw), [\"query\", \"lab_account_id\"])],\n })\n }\n const account = labAccountById(raw)\n if (!account?.team_id_allowlist.includes(MOCK_TEAM_ID))\n throw new HttpError(404, { detail: \"Lab account does not exist\" })\n if (account.status !== \"active\") throw new HttpError(400, { detail: \"Lab account is not active\" })\n return account\n}\n\nconst startDateOf = (context: OperationContext, nowMs: number): string => {\n const raw = context.query.start_date\n if (raw === undefined) return addDays(isoDate(new Date(nowMs)), 1)\n if (typeof raw !== \"string\" || !/^\\d{4}-\\d{2}-\\d{2}$/.test(raw)) {\n throw new HttpError(422, {\n detail: [\n {\n type: \"date_from_datetime_parsing\",\n loc: [\"query\", \"start_date\"],\n msg: \"Input should be a valid date or datetime, invalid character in year\",\n input: raw,\n ctx: { error: \"invalid character in year\" },\n },\n ],\n })\n }\n return raw\n}\n\nconst appointmentOfOrder = (\n state: JunctionState,\n orderId: string,\n): AppointmentRecord | undefined => {\n const binding = state.appointmentsByOrder.get(orderId)\n if (!binding) return undefined\n return state.appointments.get(binding.appointment_id)\n}\n\nconst renderAppointment = (appointment: AppointmentRecord): Record<string, unknown> => ({\n id: appointment.id,\n user_id: appointment.user_id,\n order_id: appointment.order_id,\n address: appointment.address,\n location: appointment.location,\n start_at: appointment.start_at,\n end_at: appointment.end_at,\n iana_timezone: appointment.iana_timezone,\n type: appointment.type,\n provider: appointment.provider,\n status: appointment.status,\n provider_id: appointment.provider_id,\n external_id: appointment.external_id,\n can_reschedule: appointment.can_reschedule,\n event_status: appointment.event_status,\n event_data: appointment.event_data,\n order_transaction_id: appointment.order_transaction_id,\n appointment_notes: appointment.appointment_notes,\n events: appointment.events,\n})\n\ntype SlotSeed = {\n bookingKey: string\n start: string\n end: string\n expiresAt: string\n price: number\n isPriority: boolean\n numAppointmentsAvailable: number\n modality: AppointmentModality\n provider: \"getlabs\" | \"phlebfinders\" | \"quest\"\n siteCode: string | null\n zipCode: string\n address: Record<string, unknown>\n location: { lng: number; lat: number }\n}\n\nconst phlebotomyAddress = (zip: string): Record<string, unknown> => {\n const { city, state } = cityStateForZip(zip)\n return {\n first_line: \"1 Main St\",\n second_line: \"\",\n city,\n state,\n zip_code: zip,\n unit: null,\n access_notes: null,\n }\n}\n\nconst persistSlot = (state: JunctionState, seed: SlotSeed, nowMs: number): BookingKeyRecord => {\n const record: BookingKeyRecord = {\n key: seed.bookingKey,\n start: seed.start,\n end: seed.end,\n expires_at: seed.expiresAt,\n price: seed.price,\n is_priority: seed.isPriority,\n num_appointments_available: seed.numAppointmentsAvailable,\n modality: seed.modality,\n provider: seed.provider,\n site_code: seed.siteCode,\n zip_code: seed.zipCode,\n address: seed.address,\n location: seed.location,\n consumed_by_order_id: null,\n created_at: new Date(nowMs).toISOString(),\n }\n state.bookingKeys.insert(seed.bookingKey, record)\n return record\n}\n\nconst generatePhlebotomySlots = (\n state: JunctionState,\n zip: string,\n startDate: string,\n provider: PhlebotomyProviderName,\n nowMs: number,\n): { timezone: string; days: Array<Record<string, unknown>> } => {\n const random = seededRandom(seedFor([\"phlebotomy\", provider, zip, startDate]))\n const timezone = zipTimezone(zip)\n const days: Array<Record<string, unknown>> = []\n for (let day = 0; day < 3; day++) {\n const date = addDays(startDate, day)\n const slots: Array<Record<string, unknown>> = []\n const slotCount = 2 + Math.floor(random() * 3)\n for (let slot = 0; slot < slotCount; slot++) {\n const hour = 8 + Math.floor(random() * 8)\n const minute = random() < 0.5 ? 0 : 30\n const start = new Date(`${date}T00:00:00Z`)\n start.setUTCHours(hour, minute, 0, 0)\n if (start.getTime() <= nowMs) continue\n const end = new Date(start.getTime() + 45 * 60_000)\n const salt = `${provider}:${zip}:${date}:${start.toISOString()}`\n const seed: SlotSeed = {\n bookingKey: state.bookingKeyFor(salt),\n start: start.toISOString(),\n end: end.toISOString(),\n expiresAt: new Date(start.getTime() - 60 * 60_000).toISOString(),\n price: random() < 0.5 ? 0 : 30,\n isPriority: random() < 0.3,\n numAppointmentsAvailable: 1 + Math.floor(random() * 4),\n modality: \"phlebotomy\",\n provider,\n siteCode: null,\n zipCode: zip,\n address: phlebotomyAddress(zip),\n location: zipLocation(zip),\n }\n const record = persistSlot(state, seed, nowMs)\n slots.push({\n booking_key: record.key,\n start: record.start,\n end: record.end,\n expires_at: record.expires_at,\n price: record.price,\n is_priority: record.is_priority,\n num_appointments_available: record.num_appointments_available,\n })\n }\n if (slots.length > 0) days.push({ date, slots })\n }\n return { timezone, days }\n}\n\nconst generatePscSlots = (\n state: JunctionState,\n zip: string,\n startDate: string,\n siteCodes: string[] | null,\n nowMs: number,\n): { timezone: string; days: Array<Record<string, unknown>> } => {\n const siteCount = Math.max(withinRadiusFor(zip, \"quest\", 25), 1)\n const sites = Array.from({ length: Math.min(siteCount, 30) }, (_, index) =>\n pscSiteFor(zip, \"quest\", index, 25),\n ).filter((site) => siteCodes === null || siteCodes.includes(site.site_code))\n const random = seededRandom(seedFor([\"psc\", zip, startDate, (siteCodes ?? []).sort().join(\"|\")]))\n const timezone = zipTimezone(zip)\n const days: Array<Record<string, unknown>> = []\n for (let day = 0; day < 3; day++) {\n const date = addDays(startDate, day)\n const slots: Array<Record<string, unknown>> = []\n const slotCount = 2 + Math.floor(random() * 3)\n for (let slot = 0; slot < slotCount; slot++) {\n const hour = 7 + Math.floor(random() * 9)\n const minute = random() < 0.5 ? 0 : 30\n const start = new Date(`${date}T00:00:00Z`)\n start.setUTCHours(hour, minute, 0, 0)\n if (start.getTime() <= nowMs) continue\n const end = new Date(start.getTime() + 15 * 60_000)\n const site = sites.length > 0 ? sites[slot % sites.length] : undefined\n const salt = `psc:${zip}:${site?.site_code ?? \"none\"}:${date}:${start.toISOString()}`\n const seed: SlotSeed = {\n bookingKey: state.bookingKeyFor(salt),\n start: start.toISOString(),\n end: end.toISOString(),\n expiresAt: new Date(start.getTime() - 60 * 60_000).toISOString(),\n price: 0,\n isPriority: false,\n numAppointmentsAvailable: 1 + Math.floor(random() * 6),\n modality: \"patient_service_center\",\n provider: \"quest\",\n siteCode: site?.site_code ?? null,\n zipCode: zip,\n address: site\n ? {\n first_line: site.first_line,\n second_line: null,\n city: site.city,\n state: site.state,\n zip_code: site.zip_code,\n unit: null,\n }\n : phlebotomyAddress(zip),\n location: site?.location ?? zipLocation(zip),\n }\n const record = persistSlot(state, seed, nowMs)\n slots.push({\n booking_key: record.key,\n start: record.start,\n end: record.end,\n expires_at: record.expires_at,\n price: record.price,\n is_priority: record.is_priority,\n num_appointments_available: record.num_appointments_available,\n site_code: record.site_code,\n })\n }\n if (slots.length > 0) days.push({ date, slots })\n }\n return { timezone, days }\n}\n\nfunction notFound(message: string): never {\n throw new HttpError(404, { detail: message })\n}\n\nfunction invalidBookingKey(): never {\n throw new HttpError(400, { detail: \"Invalid or expired booking key\" })\n}\n\ntype Order = NonNullable<ReturnType<JunctionState[\"orders\"][\"get\"]>>\n\nconst requireOrder = (\n state: JunctionState,\n orderId: string,\n context: OperationContext,\n missingMessage = \"This order doesn't exist.\",\n): Order => {\n if (!isUuid(orderId)) {\n throw new HttpError(422, { detail: [uuidError(orderId, [\"path\", \"order_id\"])] })\n }\n const order: Order | undefined = state.orders.get(orderId)\n if (order === undefined) notFound(missingMessage)\n const loaded: Order = order\n state.applyDueSimulateTransitions(context.now(), (_due, finalStatus, flags) => {\n applySimulateTransition(state, loaded, finalStatus, flags, context)\n })\n const fresh: Order | undefined = state.orders.get(orderId)\n if (fresh === undefined) notFound(missingMessage)\n return fresh\n}\n\nconst orderCollectionMethod = (order: Order): string => {\n if (typeof order.lab_test.method === \"string\" && order.lab_test.method.length > 0) {\n return order.lab_test.method\n }\n if (typeof order.details?.type === \"string\" && order.details.type.length > 0) {\n return order.details.type\n }\n return \"\"\n}\n\nconst requirePhlebotomyCapableOrder = (order: Order): void => {\n if (orderCollectionMethod(order) !== \"at_home_phlebotomy\") {\n notFound(\"This order doesn't have a phlebotomy order.\")\n }\n}\n\nconst requirePscCapableOrder = (order: Order): void => {\n const method = orderCollectionMethod(order)\n if (method !== \"walk_in_test\" && method !== \"on_site_collection\") {\n notFound(\"This order is not a walk-in phlebotomy order.\")\n }\n}\n\nconst requireOrderHasRequisition = (order: Order): void => {\n const hasRequisition = order.events.some(\n (entry) => typeof entry.status === \"string\" && entry.status.endsWith(\".requisition_created\"),\n )\n if (hasRequisition) return\n const lowLevel =\n typeof order.last_event?.status === \"string\"\n ? (order.last_event.status.split(\".\").at(-1) ?? order.last_event.status)\n : typeof order.status === \"string\" && order.status.length > 0\n ? order.status\n : \"ordered\"\n throw new HttpError(400, {\n detail: `This order does not have a requisition, it's still in state ${lowLevel}.`,\n })\n}\n\nconst appendOrderStatusEvent = (\n state: JunctionState,\n order: Order,\n status: string,\n context: Pick<OperationContext, \"now\">,\n): void => {\n const now = state.isoNow(context.now)\n const eventId =\n Number.parseInt(opaqueToken(`junction:order-event:${order.id}:${order.events.length}`, 8), 16) %\n 1_000_000_000 || order.events.length + 1\n const event = {\n id: eventId,\n created_at: now,\n status,\n status_detail: null,\n }\n order.status = status.split(\".\")[0] ?? order.status\n order.updated_at = now\n order.events.push(event)\n order.last_event = event\n if (status.endsWith(\".requisition_created\")) {\n if (order.sample_id === null) {\n order.sample_id = opaqueToken(`junction:sample:${order.id}`, 12).toUpperCase()\n }\n if (order.requisition_form_url === null) {\n order.requisition_form_url = `https://storage.googleapis.com/vital_labs_sandbox/mock/requisition_forms/${order.id}_${order.sample_id}.pdf`\n }\n }\n const transactionOrder = order.order_transaction.orders.find((entry) => entry.id === order.id)\n if (transactionOrder) {\n transactionOrder.low_level_status = status.split(\".\").at(-1) ?? status\n transactionOrder.low_level_status_created_at = new Date(context.now()).toISOString()\n transactionOrder.updated_at = new Date(context.now()).toISOString()\n }\n if (status.startsWith(\"completed\")) order.order_transaction.status = \"completed\"\n if (status.startsWith(\"cancelled\")) order.order_transaction.status = \"cancelled\"\n}\n\nconst applySimulationFlags = (order: Order, flags: Record<string, unknown> | null): boolean => {\n if (!flags) return false\n let changed = false\n if (typeof flags.interpretation === \"string\") {\n order.interpretation = flags.interpretation\n changed = true\n }\n if (typeof flags.has_missing_results === \"boolean\") {\n order.has_missing_results = flags.has_missing_results\n changed = true\n }\n if (Array.isArray(flags.result_types)) {\n order.result_types = flags.result_types as string[]\n changed = true\n }\n return changed\n}\n\n/**\n * Mirror api.sandbox.tryvital.io `/v3/order/{id}/test` semantics (probed 2026-09):\n * - First call on a fresh order always creates `received.{method}.requisition_created`.\n * - `at_home_phlebotomy` (and other non-walk-in methods): further `/test` calls are no-ops.\n * - `walk_in_test` after requisition:\n * - matching `appointment_*` / `requisition_created` \u2192 no-op\n * - matching `partial_results` \u2192 append partial only (default interpretation normal)\n * - matching `ordered` / `completed` / `cancelled`, or any mismatched-method status \u2192\n * jump through partial then completed (+ result date fields)\n * - `failed.*` \u2192 append the failed status\n */\n/** Set the expected and worst-case result dates from the lab test's turnaround times. */\nconst markExpectedResultDates = (order: Order, nowMs: number): void => {\n const now = new Date(nowMs)\n const commonDays =\n typeof order.lab_test.common_tat_days === \"number\" && order.lab_test.common_tat_days > 0\n ? order.lab_test.common_tat_days\n : 3\n const worstDays =\n typeof order.lab_test.worst_case_tat_days === \"number\" && order.lab_test.worst_case_tat_days > 0\n ? order.lab_test.worst_case_tat_days\n : 5\n const expected = new Date(now)\n expected.setUTCDate(expected.getUTCDate() + commonDays)\n const worst = new Date(now)\n worst.setUTCDate(worst.getUTCDate() + worstDays)\n order.expected_result_by_date = expected.toISOString().slice(0, 10)\n order.worst_case_result_by_date = worst.toISOString().slice(0, 10)\n}\n\nconst applySimulateTransition = (\n state: JunctionState,\n order: Order,\n finalStatus: string,\n flags: Record<string, unknown> | null,\n context: OperationContext,\n): void => {\n const orderMethod =\n typeof order.lab_test.method === \"string\" && order.lab_test.method.length > 0\n ? order.lab_test.method\n : typeof order.details?.type === \"string\" && order.details.type.length > 0\n ? order.details.type\n : \"at_home_phlebotomy\"\n const hasCancelled = order.events.some((entry) =>\n typeof entry.status === \"string\" ? entry.status.startsWith(\"cancelled.\") : false,\n )\n if (hasCancelled) return\n\n const hasRequisition = order.events.some((entry) =>\n typeof entry.status === \"string\" ? entry.status.endsWith(\".requisition_created\") : false,\n )\n const hasPartial = order.events.some((entry) =>\n typeof entry.status === \"string\" ? entry.status.endsWith(\".partial_results\") : false,\n )\n const hasCompleted = order.events.some((entry) =>\n typeof entry.status === \"string\" ? entry.status.endsWith(\".completed\") : false,\n )\n\n const requestedParts = finalStatus.split(\".\")\n const requestedMethod =\n requestedParts.length >= 3 ? (requestedParts[1] ?? orderMethod) : orderMethod\n const methodMismatch = requestedMethod !== orderMethod\n const normalizedTarget = (() => {\n if (requestedParts.length >= 3)\n return `${requestedParts[0]}.${orderMethod}.${requestedParts.slice(2).join(\".\")}`\n return finalStatus\n })()\n const targetTail = normalizedTarget.split(\".\").at(-1) ?? normalizedTarget\n\n let statusesToApply: string[] = []\n let applyFlags = false\n let markCompleteDates = false\n\n if (!hasRequisition) {\n statusesToApply = [`received.${orderMethod}.requisition_created`]\n } else if (orderMethod === \"walk_in_test\") {\n if (hasCompleted) {\n statusesToApply = []\n } else if (normalizedTarget.startsWith(\"failed.\")) {\n statusesToApply = [normalizedTarget]\n } else if (\n !methodMismatch &&\n (targetTail === \"appointment_pending\" ||\n targetTail === \"appointment_scheduled\" ||\n targetTail === \"appointment_cancelled\" ||\n targetTail === \"redraw_available\" ||\n targetTail === \"requisition_created\" ||\n targetTail === \"requisition_bypassed\")\n ) {\n statusesToApply = []\n } else if (!methodMismatch && targetTail === \"partial_results\") {\n if (!hasPartial) statusesToApply = [`sample_with_lab.${orderMethod}.partial_results`]\n applyFlags = true\n if (!flags || typeof flags.interpretation !== \"string\") {\n order.interpretation = order.interpretation ?? \"normal\"\n }\n } else {\n // ordered / completed / cancelled / mismatched-method \u2192 complete jump\n statusesToApply = []\n if (!hasPartial) statusesToApply.push(`sample_with_lab.${orderMethod}.partial_results`)\n statusesToApply.push(`completed.${orderMethod}.completed`)\n applyFlags = true\n markCompleteDates = true\n if (!flags || typeof flags.interpretation !== \"string\") {\n order.interpretation = order.interpretation ?? \"normal\"\n }\n }\n }\n\n if (statusesToApply.length === 0 && !applyFlags && !markCompleteDates) return\n\n for (const status of statusesToApply) {\n appendOrderStatusEvent(state, order, status, context)\n }\n if (applyFlags) applySimulationFlags(order, flags)\n if (markCompleteDates) markExpectedResultDates(order, context.now())\n state.orders.update(order.id, order)\n state.publishOrderWebhook(order, \"labtest.order.updated\", context.now())\n}\n\nconst linkAppointmentToOrder = (\n state: JunctionState,\n order: Order,\n appointment: AppointmentRecord,\n status: string,\n nowIso: string,\n): void => {\n const data = order.details.data as Record<string, unknown> | null | undefined\n if (data && typeof data === \"object\") {\n data.appointment_id = appointment.id\n data.updated_at = nowIso\n }\n const event = {\n id: order.events.length + 1,\n created_at: nowIso,\n status,\n status_detail: null,\n }\n order.status = status.split(\".\")[0] ?? order.status\n order.updated_at = nowIso\n order.events.push(event)\n order.last_event = event\n const transactionOrder = order.order_transaction.orders.find((entry) => entry.id === order.id)\n if (transactionOrder) {\n transactionOrder.low_level_status = status.split(\".\").at(-1) ?? status\n transactionOrder.low_level_status_created_at = nowIso\n transactionOrder.updated_at = nowIso\n }\n state.orders.update(order.id, order)\n state.publishOrderWebhook(order, \"labtest.order.updated\")\n}\n\nconst appendAppointmentEvent = (\n appointment: AppointmentRecord,\n status: AppointmentEventRecord[\"status\"],\n at: string,\n): AppointmentEventRecord => {\n const event: AppointmentEventRecord = { created_at: at, status, data: null }\n appointment.events.push(event)\n appointment.event_status = status\n return event\n}\n\nconst cancelAppointment = (\n state: JunctionState,\n appointment: AppointmentRecord,\n order: Order,\n nowMs: number,\n): AppointmentRecord => {\n const nowIso = state.isoNow(() => nowMs)\n appointment.status = \"cancelled\"\n appendAppointmentEvent(appointment, \"cancelled\", nowIso)\n state.appointments.update(appointment.id, appointment)\n const eventStatus = CANCELLED_ORDER_EVENT[appointment.type]\n const event = {\n id: order.events.length + 1,\n created_at: nowIso,\n status: eventStatus,\n status_detail: null,\n }\n order.status = \"collecting_sample\"\n order.updated_at = nowIso\n order.events.push(event)\n order.last_event = event\n state.orders.update(order.id, order)\n state.publishAppointmentWebhook(appointment, order.team_id, nowMs)\n state.publishOrderWebhook(order, \"labtest.order.updated\", nowMs)\n return appointment\n}\n\nexport const schedulingHandlers = (state: JunctionState) => ({\n get_phlebotomy_appointment_cancellation_reason_v3_order_phlebotomy_appointment_cancellation_reasons_get:\n async () => jsonRes(200, CANCELLATION_REASONS),\n\n get_psc_appointment_cancellation_reason_v3_order_psc_appointment_cancellation_reasons_get:\n async () => jsonRes(200, PSC_CANCELLATION_REASONS),\n\n get_area_info_v3_order_area_info_get: async (context: OperationContext) => {\n const hit = cachedResponse(state, context)\n if (hit) return hit\n const rawZip = zipCodeOf(context, true) ?? \"\"\n const radius = radiusOf(context)\n if (!/^\\d{5}(?:-?\\d{4})?$/.test(rawZip)) {\n throw new HttpError(422, {\n detail: [\n {\n type: \"string_pattern_mismatch\",\n loc: [\"query\", \"zip_code\"],\n msg: \"String should match pattern '^\\\\d{5}(?:-?\\\\d{4})?$'\",\n input: rawZip,\n ctx: { pattern: \"^\\\\d{5}(?:-?\\\\d{4})?$\" },\n },\n ],\n })\n }\n const zip = rawZip.slice(0, 5)\n requireCoveredZip(state, zip)\n return jsonRes(200, areaInfoFor(zip, radius, labAccountOf(context)))\n },\n\n get_psc_info_v3_order_psc_info_get: async (context: OperationContext) => {\n const hit = cachedResponse(state, context)\n if (hit) return hit\n const zip = zipCodeOf(context, true) ?? \"\"\n const labIdRaw = context.query.lab_id\n if (labIdRaw === undefined) {\n throw new HttpError(422, {\n detail: [\n {\n type: \"missing\",\n loc: [\"query\", \"lab_id\"],\n msg: \"Field required\",\n input: undefined,\n },\n ],\n })\n }\n if (typeof labIdRaw !== \"string\" || !/^-?\\d+$/.test(labIdRaw)) {\n throw new HttpError(422, {\n detail: [\n {\n type: \"int_parsing\",\n loc: [\"query\", \"lab_id\"],\n msg: \"Input should be a valid integer, unable to parse string as an integer\",\n input: labIdRaw,\n ctx: { error: {} },\n },\n ],\n })\n }\n if (!/^\\d{5}$/.test(zip)) {\n throw new HttpError(422, {\n detail: [\n {\n type: \"string_pattern_mismatch\",\n loc: [\"query\", \"zip_code\"],\n msg: \"String should match pattern '^\\\\d{5}$'\",\n input: zip,\n ctx: { pattern: \"^\\\\d{5}$\" },\n },\n ],\n })\n }\n const labId = Number(labIdRaw)\n const radius = radiusOf(context)\n const capabilitiesRaw = context.query.capabilities\n const capabilityList = Array.isArray(capabilitiesRaw)\n ? capabilitiesRaw.map(String)\n : capabilitiesRaw !== undefined\n ? [String(capabilitiesRaw)]\n : []\n const knownCapabilities = [\n \"stat\",\n \"appointment_scheduling_via_junction\",\n \"appointment_scheduling_with_lab\",\n ]\n if (capabilityList.some((capability) => !knownCapabilities.includes(capability))) {\n throw new HttpError(422, {\n detail: [\n {\n type: \"enum\",\n loc: [\"query\", \"capabilities\", 0],\n msg: \"Input should be 'stat', 'appointment_scheduling_via_junction' or 'appointment_scheduling_with_lab'\",\n input: capabilityList,\n ctx: {\n expected:\n \"'stat', 'appointment_scheduling_via_junction' or 'appointment_scheduling_with_lab'\",\n },\n },\n ],\n })\n }\n const lab = PSC_LABS.find((entry) => entry.lab_id === labId)\n if (labId === UNSUPPORTED_PSC_LAB_ID) {\n throw new HttpError(404, { detail: \"Lab not supported for PSC info.\" })\n }\n if (!lab) {\n throw new HttpError(404, { detail: \"Lab not found.\" })\n }\n requireCoveredZip(state, zip)\n // The sandbox returns the nearest sites within the radius, capped at 30 entries; the\n // mock synthesizes a deterministic inventory of the same contract.\n const within = withinRadiusFor(zip, lab.slug, radius)\n const centerCount = Math.min(within, 30)\n const centers = Array.from({ length: centerCount }, (_, index) => {\n const site = pscSiteFor(zip, lab.slug, index, radius)\n return {\n metadata: {\n name: site.name,\n state: site.state,\n city: site.city,\n zip_code: site.zip_code,\n first_line: site.first_line,\n second_line: null,\n phone_number: site.phone_number,\n fax_number: null,\n hours: site.hours,\n },\n distance: site.distance,\n site_code: site.site_code,\n supported_bill_types: [...lab.supported_bill_types],\n location: site.location,\n capabilities: [...lab.capabilities],\n }\n })\n return jsonRes(200, {\n lab_id: labId,\n slug: lab.slug,\n patient_service_centers: centers,\n })\n },\n\n get_phlebotomy_appointment_availability_v3_order_phlebotomy_appointment_availability_post: async (\n context: OperationContext,\n ) => {\n const hit = cachedResponse(state, context)\n if (hit) return hit\n const body = jsonObject(context)\n const zip = typeof body.zip_code === \"string\" ? body.zip_code : \"\"\n if (!/^\\d{5}$/.test(zip)) {\n throw new HttpError(422, {\n detail: [\n {\n type: \"value_error\",\n loc: [\"body\", \"zip_code\"],\n msg: `Value error, Invalid zip code: ${zip}`,\n input: body.zip_code,\n ctx: { error: {} },\n },\n ],\n })\n }\n if (typeof body.first_line !== \"string\" || typeof body.city !== \"string\") {\n throw new HttpError(422, {\n detail: [\n {\n type: \"missing\",\n loc: [\"body\", \"first_line\"],\n msg: \"Field required\",\n input: body,\n },\n ],\n })\n }\n requireCoveredZip(state, zip)\n const startDate = startDateOf(context, context.now())\n const { timezone, days } = generatePhlebotomySlots(\n state,\n zip,\n startDate,\n \"getlabs\",\n context.now(),\n )\n if (days.length === 0) notFound(\"No availability found\")\n // Align booking-key address/location with the availability request (Vital echoes it on book).\n rotateGeneratedAvailabilityKeys(state, days, context.now(), {\n address: addressFromAvailabilityRequest(body, zip),\n location: zipLocation(zip),\n zip,\n })\n return jsonRes(200, { timezone, slots: days })\n },\n\n get_psc_appointment_availability_v3_order_psc_appointment_availability_post: async (\n context: OperationContext,\n ) => {\n const hit = cachedResponse(state, context)\n if (hit) return hit\n const lab = context.query.lab\n if (lab !== \"quest\") {\n throw new HttpError(422, {\n detail: [\n {\n type: \"enum\",\n loc: [\"query\", \"lab\"],\n msg: \"Input should be 'quest'\",\n input: lab,\n ctx: { expected: \"'quest'\" },\n },\n ],\n })\n }\n const zip = zipCodeOf(context, false)\n const startDate = startDateOf(context, context.now())\n const siteCodesRaw = context.query.site_codes\n let siteCodes: string[] | null = null\n if (siteCodesRaw !== undefined) {\n if (typeof siteCodesRaw !== \"string\") {\n throw new HttpError(422, { detail: \"site_codes must be a JSON array string\" })\n }\n try {\n const parsed: unknown = JSON.parse(siteCodesRaw)\n if (!Array.isArray(parsed) || parsed.some((entry) => typeof entry !== \"string\")) {\n throw new Error(\"not an array of strings\")\n }\n siteCodes = parsed as string[]\n } catch {\n throw new HttpError(422, { detail: \"site_codes must be a JSON array of strings\" })\n }\n }\n if (zip !== undefined) requireCoveredZip(state, zip)\n const { timezone, days } = generatePscSlots(\n state,\n zip ?? \"\",\n startDate,\n siteCodes,\n context.now(),\n )\n if (days.length === 0) notFound(\"No slots found\")\n rotateGeneratedAvailabilityKeys(state, days, context.now())\n return jsonRes(200, { timezone, slots: days })\n },\n\n get_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_get: async (\n context: OperationContext,\n ) => {\n const orderId = context.params.order_id ?? \"\"\n const order = requireOrder(state, orderId, context)\n const appointment = appointmentOfOrder(state, order.id)\n if (appointment?.type !== \"phlebotomy\") notFound(\"No appointment for this order\")\n return jsonRes(200, renderAppointment(appointment))\n },\n\n get_psc_appointment_v3_order__order_id__psc_appointment_get: async (\n context: OperationContext,\n ) => {\n const orderId = context.params.order_id ?? \"\"\n const order = requireOrder(state, orderId, context)\n const appointment = appointmentOfOrder(state, order.id)\n if (appointment?.type !== \"patient_service_center\") notFound(\"No appointment for this order\")\n return jsonRes(200, renderAppointment(appointment))\n },\n\n book_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_book_post: async (\n context: OperationContext,\n ) => {\n const orderId = context.params.order_id ?? \"\"\n const order = requireOrder(state, orderId, context)\n requirePhlebotomyCapableOrder(order)\n requireOrderHasRequisition(order)\n const existing = appointmentOfOrder(state, order.id)\n if (existing && existing.status !== \"cancelled\") {\n throw new HttpError(400, { detail: \"Appointment already booked for this order\" })\n }\n const body = jsonObject(context)\n const bookingKey = typeof body.booking_key === \"string\" ? body.booking_key : \"\"\n const record = bookingKey === \"\" ? undefined : state.bookingKeys.get(bookingKey)\n if (\n record?.modality !== \"phlebotomy\" ||\n record.consumed_by_order_id !== null ||\n (record.expires_at !== null && new Date(record.expires_at).getTime() <= context.now())\n ) {\n invalidBookingKey()\n }\n const nowIso = state.isoNow(context.now)\n const appointmentId = state.nextAppointmentId()\n const appointment: AppointmentRecord = {\n id: appointmentId,\n order_id: order.id,\n user_id: order.user_id,\n provider_id: state.appointmentProviderIdFor(`${order.id}:${bookingKey}`),\n external_id: `getlabs-${state.appointmentProviderIdFor(orderId)}`,\n type: \"phlebotomy\",\n provider: record.provider as AppointmentRecord[\"provider\"],\n // Vital quirk: top-level status + events[0].status are pending, but event_status is scheduled.\n status: \"pending\",\n event_status: \"scheduled\",\n start_at: record.start,\n end_at: record.end,\n iana_timezone: zipTimezone(record.zip_code),\n address: record.address,\n location: record.location,\n can_reschedule: true,\n booking_key: record.key,\n site_code: null,\n appointment_notes: null,\n order_transaction_id: order.order_transaction.id,\n event_data: null,\n events: [],\n created_at: nowIso,\n updated_at: nowIso,\n }\n appendAppointmentEvent(appointment, \"pending\", nowIso)\n appointment.event_status = \"scheduled\"\n state.appointments.insert(appointmentId, appointment)\n state.appointmentsByOrder.insert(order.id, { appointment_id: appointmentId })\n record.consumed_by_order_id = order.id\n state.bookingKeys.update(record.key, record)\n linkAppointmentToOrder(state, order, appointment, SCHEDULED_ORDER_EVENT.phlebotomy, nowIso)\n state.publishAppointmentWebhook(appointment, order.team_id, context.now())\n return jsonRes(200, renderAppointment(appointment))\n },\n\n book_psc_appointment_v3_order__order_id__psc_appointment_book_post: async (\n context: OperationContext,\n ) => {\n const orderId = context.params.order_id ?? \"\"\n const order = requireOrder(state, orderId, context)\n requirePscCapableOrder(order)\n requireOrderHasRequisition(order)\n const idempotencyKey = context.request.headers.get(\"x-idempotency-key\")\n if (idempotencyKey !== null && idempotencyKey !== \"\") {\n const replay = state.cancelIdempotency.get(`psc-book:${idempotencyKey}`)\n if (replay) return jsonRes(200, replay.response)\n }\n const existing = appointmentOfOrder(state, order.id)\n if (existing && existing.status !== \"cancelled\") {\n throw new HttpError(400, { detail: \"Appointment already booked for this order\" })\n }\n const body = jsonObject(context)\n const bookingKey = typeof body.booking_key === \"string\" ? body.booking_key : \"\"\n const siteCode = typeof body.site_code === \"string\" ? body.site_code : \"\"\n if (siteCode === \"\") {\n throw new HttpError(400, { detail: \"site_code is required for PSC appointments\" })\n }\n const record = bookingKey === \"\" ? undefined : state.bookingKeys.get(bookingKey)\n if (\n record === undefined ||\n (record.modality === \"patient_service_center\" &&\n record.consumed_by_order_id !== null &&\n record.consumed_by_order_id !== order.id) ||\n (record.expires_at !== null && new Date(record.expires_at).getTime() <= context.now())\n ) {\n invalidBookingKey()\n }\n if (record.modality !== \"patient_service_center\") {\n throw new HttpError(400, { detail: \"Booking key is not a patient service center slot\" })\n }\n if (record.site_code !== null && record.site_code !== siteCode) {\n throw new HttpError(400, { detail: \"Booking key does not match the requested site\" })\n }\n const nowIso = state.isoNow(context.now)\n const appointmentId = state.nextAppointmentId()\n const appointment: AppointmentRecord = {\n id: appointmentId,\n order_id: order.id,\n user_id: order.user_id,\n provider_id: state.appointmentProviderIdFor(`${order.id}:${record.key}`),\n external_id: `quest-${state.appointmentProviderIdFor(orderId)}`,\n type: \"patient_service_center\",\n provider: \"quest\",\n status: \"confirmed\",\n event_status: \"scheduled\",\n start_at: record.start,\n end_at: record.end,\n iana_timezone: zipTimezone(record.zip_code),\n address: record.address,\n location: record.location,\n can_reschedule: true,\n booking_key: record.key,\n site_code: siteCode,\n appointment_notes: null,\n order_transaction_id: order.order_transaction.id,\n event_data: null,\n events: [],\n created_at: nowIso,\n updated_at: nowIso,\n }\n appendAppointmentEvent(appointment, \"scheduled\", nowIso)\n state.appointments.insert(appointmentId, appointment)\n state.appointmentsByOrder.insert(order.id, { appointment_id: appointmentId })\n record.consumed_by_order_id = order.id\n state.bookingKeys.update(record.key, record)\n linkAppointmentToOrder(\n state,\n order,\n appointment,\n SCHEDULED_ORDER_EVENT.patient_service_center,\n nowIso,\n )\n state.publishAppointmentWebhook(appointment, order.team_id, context.now())\n const response = renderAppointment(appointment)\n if (idempotencyKey !== null && idempotencyKey !== \"\") {\n state.cancelIdempotency.insert(`psc-book:${idempotencyKey}`, {\n order_id: order.id,\n response,\n })\n }\n return jsonRes(200, response)\n },\n\n reschedule_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_reschedule_patch:\n async (context: OperationContext) => {\n const orderId = context.params.order_id ?? \"\"\n const order = requireOrder(state, orderId, context)\n const body = jsonObject(context)\n const bookingKey = typeof body.booking_key === \"string\" ? body.booking_key : \"\"\n const appointment = appointmentOfOrder(state, order.id)\n if (appointment?.type !== \"phlebotomy\") notFound(\"No appointment for this order\")\n if (appointment.status === \"cancelled\")\n throw new HttpError(400, { detail: \"Cannot reschedule a cancelled appointment\" })\n const record = bookingKey === \"\" ? undefined : state.bookingKeys.get(bookingKey)\n if (\n record === undefined ||\n record.modality !== \"phlebotomy\" ||\n (record.consumed_by_order_id !== null && record.consumed_by_order_id !== order.id) ||\n (record.expires_at !== null && new Date(record.expires_at).getTime() <= context.now())\n ) {\n invalidBookingKey()\n }\n const nowIso = state.isoNow(context.now)\n appointment.start_at = record.start\n appointment.end_at = record.end\n appointment.iana_timezone = zipTimezone(record.zip_code)\n appointment.address = record.address\n appointment.location = record.location\n appointment.booking_key = record.key\n appendAppointmentEvent(appointment, \"scheduled\", nowIso)\n state.appointments.update(appointment.id, appointment)\n record.consumed_by_order_id = order.id\n state.bookingKeys.update(record.key, record)\n state.publishAppointmentWebhook(appointment, order.team_id, context.now())\n return jsonRes(200, renderAppointment(appointment))\n },\n\n reschedule_psc_appointment_v3_order__order_id__psc_appointment_reschedule_patch: async (\n context: OperationContext,\n ) => {\n const orderId = context.params.order_id ?? \"\"\n const order = requireOrder(state, orderId, context)\n const body = jsonObject(context)\n const bookingKey = typeof body.booking_key === \"string\" ? body.booking_key : \"\"\n const appointment = appointmentOfOrder(state, order.id)\n if (appointment?.type !== \"patient_service_center\") notFound(\"No appointment for this order\")\n if (appointment.status === \"cancelled\")\n throw new HttpError(400, { detail: \"Cannot reschedule a cancelled appointment\" })\n const record = bookingKey === \"\" ? undefined : state.bookingKeys.get(bookingKey)\n if (\n record === undefined ||\n record.modality !== \"patient_service_center\" ||\n (record.consumed_by_order_id !== null && record.consumed_by_order_id !== order.id) ||\n (record.expires_at !== null && new Date(record.expires_at).getTime() <= context.now())\n ) {\n invalidBookingKey()\n }\n if (record.site_code !== null && appointment.site_code !== record.site_code) {\n throw new HttpError(400, { detail: \"Booking key does not match the appointment site\" })\n }\n const nowIso = state.isoNow(context.now)\n appointment.start_at = record.start\n appointment.end_at = record.end\n appointment.iana_timezone = zipTimezone(record.zip_code)\n appointment.address = record.address\n appointment.location = record.location\n appointment.booking_key = record.key\n appendAppointmentEvent(appointment, \"scheduled\", nowIso)\n state.appointments.update(appointment.id, appointment)\n record.consumed_by_order_id = order.id\n state.bookingKeys.update(record.key, record)\n state.publishAppointmentWebhook(appointment, order.team_id, context.now())\n return jsonRes(200, renderAppointment(appointment))\n },\n\n cancel_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_cancel_patch: async (\n context: OperationContext,\n ) => {\n const orderId = context.params.order_id ?? \"\"\n const order = requireOrder(state, orderId, context)\n const body = jsonObject(context)\n const reasonId =\n typeof body.cancellation_reason_id === \"string\" ? body.cancellation_reason_id : \"\"\n const appointment = appointmentOfOrder(state, order.id)\n if (appointment?.type !== \"phlebotomy\") notFound(\"No appointment for this order\")\n const reason = CANCELLATION_REASONS.find((entry) => entry.id === reasonId)\n if (!reason) {\n throw new HttpError(400, { detail: \"Invalid cancellation reason id\" })\n }\n if (reasonId === OTHER_CANCELLATION_REASON_ID && typeof body.notes !== \"string\") {\n throw new HttpError(400, { detail: \"notes is required for reason 'Other'\" })\n }\n if (appointment.status === \"cancelled\") return jsonRes(200, renderAppointment(appointment))\n appointment.appointment_notes = typeof body.notes === \"string\" ? body.notes : null\n cancelAppointment(state, appointment, order, context.now())\n return jsonRes(200, renderAppointment(appointment))\n },\n\n cancel_psc_appointment_v3_order__order_id__psc_appointment_cancel_patch: async (\n context: OperationContext,\n ) => {\n const orderId = context.params.order_id ?? \"\"\n const order = requireOrder(state, orderId, context)\n const body = jsonObject(context)\n const reasonId = typeof body.cancellationReasonId === \"string\" ? body.cancellationReasonId : \"\"\n const appointment = appointmentOfOrder(state, order.id)\n if (appointment?.type !== \"patient_service_center\") notFound(\"No appointment for this order\")\n const reason = PSC_CANCELLATION_REASONS.find((entry) => entry.id === reasonId)\n if (!reason) {\n throw new HttpError(400, { detail: \"Invalid cancellation reason id\" })\n }\n if (appointment.status === \"cancelled\") return jsonRes(200, renderAppointment(appointment))\n appointment.appointment_notes = typeof body.note === \"string\" ? body.note : null\n cancelAppointment(state, appointment, order, context.now())\n return jsonRes(200, renderAppointment(appointment))\n },\n})\n\n/** Cancels any active appointment linked to `orderId`; used by order cancellation cascade. */\nexport const cascadeCancelAppointments = (\n state: JunctionState,\n orderId: string,\n nowMs: number,\n): void => {\n const appointment = appointmentOfOrder(state, orderId)\n if (!appointment || appointment.status === \"cancelled\") return\n const order = state.orders.get(orderId)\n if (!order) return\n cancelAppointment(state, appointment, order, nowMs)\n}\n\n/**\n * Put an order straight into `status`, as the admin API does. Unlike `simulate_order`\n * it skips the sandbox's stepwise rules, but it records the same event, dates and\n * appointment cascade and publishes the same webhook a real transition does.\n */\nexport const forceOrderStatus = (\n state: JunctionState,\n order: Order,\n status: string,\n flags: Record<string, unknown> | null,\n context: Pick<OperationContext, \"now\">,\n): void => {\n const hasRequisition = order.events.some((entry) =>\n typeof entry.status === \"string\" ? entry.status.endsWith(\".requisition_created\") : false,\n )\n if (!hasRequisition && !status.startsWith(\"received.\")) {\n // A real order passes through requisition before anything else; keep the ids it mints.\n appendOrderStatusEvent(\n state,\n order,\n `received.${status.split(\".\")[1]}.requisition_created`,\n context,\n )\n }\n appendOrderStatusEvent(state, order, status, context)\n if (flags) applySimulationFlags(order, flags)\n if (status.startsWith(\"completed.\")) markExpectedResultDates(order, context.now())\n state.orders.update(order.id, order)\n if (status.startsWith(\"cancelled.\")) cascadeCancelAppointments(state, order.id, context.now())\n state.publishOrderWebhook(order, \"labtest.order.updated\", context.now())\n}\n\nexport { applySimulateTransition, appointmentOfOrder, renderAppointment, requireOrder }\n", "import type { FormValue } from \"@crvouga/mockingbird-http-codec\"\nimport {\n HttpError,\n jsonRes,\n type OperationContext,\n opaqueToken,\n} from \"@crvouga/mockingbird-service\"\nimport {\n effectiveBilling,\n LAB_ACCOUNT_STATUSES,\n type LabAccountStatus,\n renderLabAccount,\n selectLabAccount,\n} from \"./lab-accounts.js\"\nimport { applySimulateTransition, cascadeCancelAppointments } from \"./scheduling.js\"\nimport type { JunctionState, OrderRecord } from \"./state.js\"\nimport { deterministicUuid, MOCK_TEAM_ID } from \"./state.js\"\n\nconst RESULT_TYPES = [\"numeric\", \"range\", \"comment\", \"coded_value\"] as const\nconst INTERPRETATIONS = [\"normal\", \"abnormal\", \"critical\", \"unknown\"] as const\n\nconst simulationFlagsOf = (context: OperationContext): Record<string, unknown> | null => {\n const body = context.body\n if (body.kind !== \"json\") return null\n const value = body.value\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return null\n const raw = value as Record<string, unknown>\n const flags: Record<string, unknown> = {}\n if (\n typeof raw.interpretation === \"string\" &&\n INTERPRETATIONS.includes(raw.interpretation as never)\n )\n flags.interpretation = raw.interpretation\n if (Array.isArray(raw.result_types)) {\n const types = raw.result_types.filter(\n (entry): entry is string =>\n typeof entry === \"string\" && RESULT_TYPES.includes(entry as never),\n )\n if (types.length > 0) flags.result_types = types\n }\n if (typeof raw.has_missing_results === \"boolean\")\n flags.has_missing_results = raw.has_missing_results\n return Object.keys(flags).length > 0 ? flags : null\n}\n\ntype AoeQuestion = {\n id: number\n required: boolean\n code: string\n value: string\n type: string\n sequence: number\n answers: Array<{ id: number; code: string; value: string }>\n constraint: unknown\n default: unknown\n}\n\nconst aoeQuestion = (\n state: JunctionState,\n markerId: number,\n questionId: number,\n): AoeQuestion | undefined => {\n for (const test of state.listLabTests()) {\n for (const marker of test.markers ?? []) {\n if (marker.id !== markerId) continue\n const aoe = marker.aoe as { questions?: AoeQuestion[] } | null | undefined\n if (!aoe) return undefined\n return aoe.questions?.find((question) => question.id === questionId) ?? undefined\n }\n }\n return undefined\n}\n\nfunction notFound(message: string): never {\n throw new HttpError(404, { detail: message })\n}\n\nconst queryInt = (context: OperationContext, name: string, fallback: number): number => {\n const raw = context.query[name]\n if (raw === undefined) return fallback\n if (typeof raw !== \"string\" || !/^-?\\d+$/.test(raw))\n throw new HttpError(422, { detail: `${name} must be an integer` })\n return Number(raw)\n}\n\nconst MARKERS_DEFAULT_SIZE = 50\nconst MARKERS_MAX_SIZE = 100\n\nconst markersBoundsError = (name: string, value: string, bound: \"ge\" | \"le\", limit: number) => ({\n type: bound === \"ge\" ? \"greater_than_equal\" : \"less_than_equal\",\n loc: [\"query\", name],\n msg: `Input should be ${bound === \"ge\" ? \"greater than or equal to\" : \"less than or equal to\"} ${limit}`,\n input: value,\n ctx: bound === \"ge\" ? { ge: limit } : { le: limit },\n})\n\nconst parseMarkersInt = (raw: FormValue | undefined, name: string, fallback: number): number => {\n if (raw === undefined) return fallback\n if (typeof raw !== \"string\" || !/^-?\\d+$/.test(raw)) {\n throw new HttpError(422, {\n detail: [\n {\n type: \"int_parsing\",\n loc: [\"query\", name],\n msg: \"Input should be a valid integer, unable to parse string as an integer\",\n input: raw,\n },\n ],\n })\n }\n return Number(raw)\n}\n\n/**\n * Pagination mirrors the sandbox markers endpoints: `total` counts the returned page,\n * `pages` is ceil(overall/size) over the whole marker list, and page/size accept\n * 1..100 with 422s outside those bounds.\n */\nconst paginateMarkers = (\n query: OperationContext[\"query\"],\n markers: readonly Record<string, unknown>[],\n) => {\n const page = parseMarkersInt(query.page, \"page\", 1)\n const size = parseMarkersInt(query.size, \"size\", MARKERS_DEFAULT_SIZE)\n if (page < 1) {\n throw new HttpError(422, {\n detail: [markersBoundsError(\"page\", String(page), \"ge\", 1)],\n })\n }\n if (size < 1 || size > MARKERS_MAX_SIZE) {\n throw new HttpError(422, {\n detail: [\n markersBoundsError(\n \"size\",\n String(size),\n size < 1 ? \"ge\" : \"le\",\n size < 1 ? 1 : MARKERS_MAX_SIZE,\n ),\n ],\n })\n }\n const start = (page - 1) * size\n const pageMarkers = markers.slice(start, start + size)\n const pages = Math.ceil(markers.length / size)\n return {\n markers: pageMarkers,\n total: pageMarkers.length,\n page,\n size,\n pages,\n }\n}\n\nconst jsonObject = (context: OperationContext): Record<string, unknown> => {\n const body = context.body\n const value = body.kind === \"json\" ? body.value : undefined\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new HttpError(422, {\n detail: [\n {\n type: \"model_attributes_type\",\n loc: [\"body\"],\n msg: \"Input should be a valid dictionary or object to extract fields from\",\n input: value,\n },\n ],\n })\n }\n return value as Record<string, unknown>\n}\n\n/** Pydantic `str_strip_whitespace`: trim every string value before validation and use. */\nconst trimStrings = (value: unknown): unknown => {\n if (typeof value === \"string\") return value.trim()\n if (Array.isArray(value)) return value.map(trimStrings)\n if (typeof value === \"object\" && value !== null) {\n const out: Record<string, unknown> = {}\n for (const [key, entry] of Object.entries(value)) out[key] = trimStrings(entry)\n return out\n }\n return value\n}\n\nconst patientDetails = (input: Record<string, unknown>): Record<string, unknown> => ({\n ...input,\n dob:\n typeof input.dob === \"string\" && /^\\d{4}-\\d{2}-\\d{2}$/.test(input.dob)\n ? `${input.dob}T00:00:00+00:00`\n : input.dob,\n medical_proxy: null,\n race: null,\n ethnicity: null,\n sexual_orientation: null,\n gender_identity: null,\n})\n\nconst patientAddress = (input: Record<string, unknown>): Record<string, unknown> => ({\n ...input,\n second_line: null,\n access_notes: null,\n})\n\nconst missingError = (loc: Array<string | number>, input: unknown) => ({\n type: \"missing\",\n loc,\n msg: \"Field required\",\n input,\n})\n\nconst stringTypeError = (loc: string[], value: unknown) => ({\n type: \"string_type\",\n loc,\n msg: \"Input should be a valid string\",\n input: value,\n})\n\nconst stringTooShortError = (loc: string[], value: string) => ({\n type: \"string_too_short\",\n loc,\n msg: \"String should have at least 1 character\",\n input: value,\n ctx: { min_length: 1 },\n})\n\nconst patternError = (loc: string[], value: unknown, pattern: string) => ({\n type: \"string_pattern_mismatch\",\n loc,\n msg: `String should match pattern '${pattern}'`,\n input: value,\n ctx: { pattern },\n})\n\nconst stateError = (value: unknown) => ({\n type: \"value_error\",\n loc: [\"body\", \"patient_address\", \"state\"],\n msg: `Value error, Invalid state: ${value}`,\n input: value,\n ctx: { error: {} },\n})\n\nconst phoneError = (loc: string[], value: unknown) => ({\n type: \"value_error\",\n loc,\n msg: `Value error, Invalid phone number: ${value}`,\n input: value,\n ctx: { error: {} },\n})\n\nconst isUuid = (value: string): boolean =>\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)\n\nconst uuidError = (value: string, index?: number, loc?: string[]) => {\n const characters = Array.from(value)\n const invalidIndex = characters.findIndex((character) => !/^[0-9a-f-]$/i.test(character))\n const error =\n invalidIndex >= 0\n ? `invalid character: expected an optional prefix of \\`urn:uuid:\\` followed by [0-9a-fA-F-], found \\`${characters[invalidIndex]}\\` at ${invalidIndex + 1}`\n : `invalid length: expected length 32 for simple format, found ${value.replaceAll(\"-\", \"\").length}`\n return {\n type: \"uuid_parsing\",\n loc:\n loc ??\n (index === undefined\n ? [\"body\", \"lab_account_id\"]\n : [\"body\", \"order_set\", \"lab_test_ids\", index]),\n msg: `Input should be a valid UUID, ${error}`,\n input: value,\n ctx: { error },\n }\n}\n\n/** `GET /v3/lab_test/lab_account` query filters: Pydantic-shaped 422s, then exact match. */\nconst labAccountIdFilter = (context: OperationContext): string | null => {\n const raw = context.query.lab_account_id\n if (raw === undefined) return null\n if (typeof raw === \"string\" && isUuid(raw)) return raw\n throw new HttpError(422, {\n detail: [\n uuidError(typeof raw === \"string\" ? raw : String(raw), undefined, [\n \"query\",\n \"lab_account_id\",\n ]),\n ],\n })\n}\n\nconst labAccountStatusFilter = (context: OperationContext): LabAccountStatus | null => {\n const raw = context.query.status\n if (raw === undefined) return null\n if (typeof raw === \"string\" && LAB_ACCOUNT_STATUSES.includes(raw as LabAccountStatus)) {\n return raw as LabAccountStatus\n }\n throw new HttpError(422, {\n detail: [\n {\n type: \"enum\",\n loc: [\"query\", \"status\"],\n msg: \"Input should be 'active', 'pending', 'suspended' or 'ready_to_launch'\",\n input: raw,\n ctx: { expected: \"'active', 'pending', 'suspended' or 'ready_to_launch'\" },\n },\n ],\n })\n}\n\nconst isValidPhone = (value: string): boolean => {\n const digits = value.replace(/\\D/g, \"\")\n if (digits.length < 10 || digits.length > 15) return false\n if (/[a-zA-Z]/.test(value)) return false\n if (digits.length === 10 || digits.length === 11) {\n const area = digits.length === 11 ? digits.slice(1, 4) : digits.slice(0, 3)\n if (area[0] === \"0\" || area[0] === \"1\") return false\n }\n return true\n}\n\nconst isValidName = (value: string): boolean => {\n if (!/^[a-zA-Z0-9][a-zA-Z0-9 .,'-]*$/.test(value)) return false\n if (/\\s\\s/.test(value)) return false\n return true\n}\n\nconst nameError = (field: string, value: unknown) => ({\n type: \"value_error\",\n loc: [\"body\", \"patient_details\", field],\n msg: \"Value error, The field must start with a letter (a-z or A-Z or 0-9) and can only contain -,. special characters, but cannot start with a space or hyphen.\",\n input: value,\n ctx: { error: {} },\n})\n\nconst pyIso = (value: string): string => {\n const d = new Date(value)\n const iso = d.toISOString()\n const [date, time = \"\"] = iso.split(\"T\")\n const match = time.match(/\\.(\\d+)Z$/)\n const ms = (match?.[1] ?? \"000\").padEnd(6, \"0\")\n return `${date}T${time.slice(0, 8)}.${ms}+00:00`\n}\n\nconst orderValidation = (body: Record<string, unknown>): unknown[] => {\n const errors: unknown[] = []\n const userId = body.user_id\n if (userId === undefined) errors.push(missingError([\"body\", \"user_id\"], body))\n else if (typeof userId !== \"string\") errors.push(stringTypeError([\"body\", \"user_id\"], userId))\n else if (!isUuid(userId)) errors.push(uuidError(userId))\n const labAccountId = body.lab_account_id\n if (typeof labAccountId === \"string\" && labAccountId.trim().length === 0) {\n errors.push({\n type: \"string_too_short\",\n loc: [\"body\", \"lab_account_id\"],\n msg: \"String should have at least 1 character\",\n input: labAccountId,\n })\n }\n const os = body.order_set\n const osWrongType =\n os !== undefined && (typeof os !== \"object\" || os === null || Array.isArray(os))\n if (osWrongType) {\n errors.push({\n type: \"model_attributes_type\",\n loc: [\"body\", \"order_set\"],\n msg: \"Input should be a valid dictionary or object to extract fields from\",\n input: os,\n })\n } else if (os !== undefined) {\n const o = os as Record<string, unknown>\n const ids = o.lab_test_ids\n if (ids === undefined) errors.push(missingError([\"body\", \"order_set\", \"lab_test_ids\"], o))\n else if (!Array.isArray(ids)) {\n errors.push({\n type: \"list_type\",\n loc: [\"body\", \"order_set\", \"lab_test_ids\"],\n msg: \"Input should be a valid list\",\n input: ids,\n })\n } else {\n ids.forEach((id, index) => {\n if (typeof id !== \"string\" || !isUuid(id)) errors.push(uuidError(String(id), index))\n })\n }\n }\n const pd = body.patient_details\n if (pd === undefined) {\n errors.push(missingError([\"body\", \"patient_details\"], body))\n } else if (typeof pd !== \"object\" || pd === null || Array.isArray(pd)) {\n errors.push({\n type: \"model_attributes_type\",\n loc: [\"body\", \"patient_details\"],\n msg: \"Input should be a valid dictionary or object to extract fields from\",\n input: pd,\n })\n } else {\n const p = pd as Record<string, unknown>\n for (const field of [\"first_name\", \"last_name\", \"dob\", \"gender\", \"phone_number\", \"email\"]) {\n if (p[field] === undefined) errors.push(missingError([\"body\", \"patient_details\", field], p))\n else if (field === \"gender\" && p[field] === null) {\n errors.push({\n type: \"value_error\",\n loc: [\"body\", \"patient_details\", \"gender\"],\n msg: \"Value error, gender cannot be None.\",\n input: null,\n ctx: { error: {} },\n })\n } else if (field === \"phone_number\" && p[field] === null) {\n errors.push({\n type: \"value_error\",\n loc: [\"body\", \"patient_details\", \"phone_number\"],\n msg: \"Value error, Phone number cannot be None\",\n input: null,\n ctx: { error: {} },\n })\n } else if (field === \"dob\" && typeof p[field] === \"number\") {\n const asSeconds = Math.abs(p[field] as number) < 1e12\n const normalized = new Date((p[field] as number) * (asSeconds ? 1000 : 1))\n .toISOString()\n .replace(/\\.\\d{3}Z$/, \"+00:00\")\n .replace(/Z$/, \"+00:00\")\n errors.push({\n type: \"date_from_datetime_inexact\",\n loc: [\"body\", \"patient_details\", \"dob\"],\n msg: \"Datetimes provided to dates should have zero time - e.g. be exact dates\",\n input: normalized,\n })\n } else if (field === \"dob\" && (p[field] === null || typeof p[field] === \"object\")) {\n errors.push({\n type: \"value_error\",\n loc: [\"body\", \"patient_details\", \"dob\"],\n msg: \"Value error, date of birth is not specified.\",\n input: p[field],\n ctx: { error: {} },\n })\n } else if (typeof p[field] !== \"string\")\n errors.push(stringTypeError([\"body\", \"patient_details\", field], p[field]))\n else if (\n (field === \"first_name\" || field === \"last_name\") &&\n typeof p[field] === \"string\" &&\n p[field].length === 0\n )\n errors.push(stringTooShortError([\"body\", \"patient_details\", field], p[field]))\n else if (\n (field === \"first_name\" || field === \"last_name\") &&\n !isValidName(p[field] as string)\n )\n errors.push(nameError(field, p[field]))\n else if (field === \"email\") {\n const emailError = userEmailError(p[field] as string)\n if (emailError) errors.push(emailError)\n } else if (field === \"dob\") {\n const dobError = orderDobError(p[field] as string)\n if (dobError) errors.push(dobError)\n } else if (field === \"phone_number\" && !isValidPhone(p[field] as string)) {\n errors.push(phoneError([\"body\", \"patient_details\", \"phone_number\"], p[field]))\n }\n }\n }\n const pa = body.patient_address\n if (pa === undefined) {\n errors.push(missingError([\"body\", \"patient_address\"], body))\n } else if (typeof pa !== \"object\" || pa === null || Array.isArray(pa)) {\n errors.push({\n type: \"model_attributes_type\",\n loc: [\"body\", \"patient_address\"],\n msg: \"Input should be a valid dictionary or object to extract fields from\",\n input: pa,\n })\n } else {\n const a = pa as Record<string, unknown>\n for (const field of [\"first_line\", \"city\", \"state\", \"zip\", \"country\"]) {\n if (a[field] === undefined) errors.push(missingError([\"body\", \"patient_address\", field], a))\n else if (typeof a[field] !== \"string\")\n errors.push(stringTypeError([\"body\", \"patient_address\", field], a[field]))\n }\n if (typeof a.state === \"string\" && !/^[A-Z]{2}$/.test(a.state)) {\n errors.push(stateError(a.state))\n }\n if (typeof a.zip === \"string\" && !/^\\d{5}(-\\d{4})?$/.test(a.zip)) {\n errors.push(patternError([\"body\", \"patient_address\", \"zip\"], a.zip, \"^\\\\d{5}(-\\\\d{4})?$\"))\n }\n if (typeof a.phone_number === \"string\" && !isValidPhone(a.phone_number)) {\n errors.push(phoneError([\"body\", \"patient_address\", \"phone_number\"], a.phone_number))\n }\n }\n return errors\n}\n\n/** Sandbox email validation for `patient_details.email` (only the missing-@ sign case is reachable here). */\nconst userEmailError = (value: string) => {\n if (!value.includes(\"@\")) {\n return {\n type: \"value_error\",\n loc: [\"body\", \"patient_details\", \"email\"],\n msg: \"value is not a valid email address: An email address must have an @-sign.\",\n input: value,\n ctx: { reason: \"An email address must have an @-sign.\" },\n }\n }\n return undefined\n}\n\n/**\n * Sandbox dob validation for create_order: many string formats are accepted\n * (`1990-01-01`, `1990-01`, `1990/01/01`, `19900101`, ...); exact zero-time datetimes are\n * accepted, non-zero times produce `date_from_datetime_inexact` with a normalized input,\n * and unmatchable strings produce the \"Could not match\" value error.\n */\nconst orderDobError = (dob: string) => {\n if (/^\\d{4}-\\d{2}-\\d{2}T/.test(dob)) {\n if (/^\\d{4}-\\d{2}-\\d{2}T00:00:00/.test(dob)) {\n const dateOnly = dob.slice(0, 10)\n if (new Date(`${dateOnly}T00:00:00Z`).getTime() > Date.now()) {\n return {\n type: \"value_error\",\n loc: [\"body\", \"patient_details\", \"dob\"],\n msg: \"Value error, dob cannot be in the future\",\n input: `${dateOnly}T00:00:00+00:00`,\n ctx: { error: {} },\n }\n }\n return undefined\n }\n return {\n type: \"date_from_datetime_inexact\",\n loc: [\"body\", \"patient_details\", \"dob\"],\n msg: \"Datetimes provided to dates should have zero time - e.g. be exact dates\",\n input: pyIso(dob),\n }\n }\n if (/^\\d{4}-\\d{2}-\\d{2}$/.test(dob)) {\n const [year = \"0\", month = \"0\", day = \"0\"] = dob.split(\"-\")\n const monthNumber = Number(month)\n const dayNumber = Number(day)\n if (monthNumber < 1 || monthNumber > 12) {\n return {\n type: \"value_error\",\n loc: [\"body\", \"patient_details\", \"dob\"],\n msg: `Value error, month must be in 1..12, not ${monthNumber}`,\n input: dob,\n ctx: { error: {} },\n }\n }\n const daysInMonth = new Date(Date.UTC(Number(year), monthNumber, 0)).getUTCDate()\n if (dayNumber < 1 || dayNumber > daysInMonth) {\n return {\n type: \"value_error\",\n loc: [\"body\", \"patient_details\", \"dob\"],\n msg: `Value error, day ${dayNumber} must be in range 1..${daysInMonth} for month ${monthNumber} in year ${year}`,\n input: dob,\n ctx: { error: {} },\n }\n }\n if (new Date(`${dob}T00:00:00Z`).getTime() > Date.now()) {\n return {\n type: \"value_error\",\n loc: [\"body\", \"patient_details\", \"dob\"],\n msg: \"Value error, dob cannot be in the future\",\n input: `${dob}T00:00:00+00:00`,\n ctx: { error: {} },\n }\n }\n return undefined\n }\n return {\n type: \"value_error\",\n loc: [\"body\", \"patient_details\", \"dob\"],\n msg:\n \"Value error, Could not match input '\" +\n dob +\n \"' to any of the following formats: YYYY-MM-DD, YYYY-M-DD, YYYY-M-D, YYYY/MM/DD, YYYY/M/DD, YYYY/M/D, YYYY.MM.DD, YYYY.M.DD, YYYY.M.D, YYYYMMDD, YYYY-DDDD, YYYYDDDD, YYYY-MM, YYYY/MM, YYYY.MM, YYYY, W.\",\n input: dob,\n ctx: { error: {} },\n }\n}\n\nconst aoeValidationError = (\n state: JunctionState,\n body: Record<string, unknown>,\n): string | undefined => {\n const answers = body.aoe_answers\n if (!Array.isArray(answers)) return undefined\n for (const answer of answers) {\n if (typeof answer !== \"object\" || answer === null || Array.isArray(answer)) continue\n const record = answer as Record<string, unknown>\n if (typeof record.marker_id !== \"number\") continue\n const marker = state\n .listLabTests()\n .flatMap((test) => test.markers ?? [])\n .find((entry) => entry.id === record.marker_id)\n if (!marker?.aoe) return `Marker id ${record.marker_id} does not have AOE.`\n const question = aoeQuestion(state, record.marker_id, record.question_id as number)\n if (!question)\n return `Invalid question_id ${String(record.question_id)} for marker id ${record.marker_id}.`\n const answerCode = typeof record.answer === \"string\" ? record.answer.toUpperCase() : \"\"\n if (!question.answers.some((entry) => entry.code === answerCode))\n return `Invalid answer ${answerCode} for question ${question.value}.`\n }\n return undefined\n}\n\nconst METHOD_DETAILS = (method: string, id: string, at: string) => {\n switch (method) {\n case \"testkit\":\n return {\n type: \"testkit\",\n data: { id, shipment: null, created_at: at, updated_at: at },\n }\n case \"walk_in_test\":\n case \"on_site_collection\":\n return {\n type: method,\n data: { id, appointment_id: null, created_at: at, updated_at: at },\n }\n default:\n return {\n type: method,\n data: { id, appointment_id: null, created_at: at, updated_at: at },\n }\n }\n}\n\nconst PHYSICIAN = { first_name: \"Leo\", last_name: \"Damasco\", npi: \"1134326366\" }\n\n/** Sandbox Labcorp rejects these patient states (`Lab Labcorp does not support state XX`). */\nconst LAB_UNSUPPORTED_STATES: Readonly<Record<string, readonly string[]>> = {\n labcorp: [\"NY\", \"NJ\", \"RI\"],\n}\n\n/** Low-level events that Junction allows transitioning to `cancelled.*.cancelled`. */\nconst CANCELLABLE_ORDER_EVENTS = new Set([\n \"received.walk_in_test.ordered\",\n \"received.walk_in_test.requisition_created\",\n \"received.walk_in_test.requisition_bypassed\",\n \"collecting_sample.walk_in_test.appointment_scheduled\",\n \"collecting_sample.walk_in_test.appointment_cancelled\",\n \"collecting_sample.walk_in_test.appointment_pending\",\n \"received.at_home_phlebotomy.ordered\",\n \"received.at_home_phlebotomy.requisition_created\",\n \"received.at_home_phlebotomy.requisition_bypassed\",\n \"collecting_sample.at_home_phlebotomy.appointment_pending\",\n \"collecting_sample.at_home_phlebotomy.appointment_scheduled\",\n \"collecting_sample.at_home_phlebotomy.appointment_cancelled\",\n \"collecting_sample.at_home_phlebotomy.draw_completed\",\n \"received.testkit.ordered\",\n \"received.testkit.awaiting_registration\",\n \"received.testkit.requisition_created\",\n \"received.testkit.requisition_bypassed\",\n \"received.testkit.testkit_registered\",\n \"received.on_site_collection.ordered\",\n \"received.on_site_collection.requisition_created\",\n \"received.on_site_collection.requisition_bypassed\",\n \"collecting_sample.on_site_collection.draw_completed\",\n])\n\nconst labStateSupportError = (\n labTest: { lab?: Record<string, unknown> | null },\n state: unknown,\n): string | undefined => {\n if (typeof state !== \"string\" || state.length === 0) return undefined\n const lab = labTest.lab\n if (!lab || typeof lab !== \"object\") return undefined\n const slug = typeof lab.slug === \"string\" ? lab.slug.toLowerCase() : \"\"\n const name = typeof lab.name === \"string\" ? lab.name : \"Lab\"\n const unsupported = LAB_UNSUPPORTED_STATES[slug]\n if (!unsupported) return undefined\n const normalized = state.trim().toUpperCase()\n if (!unsupported.includes(normalized)) return undefined\n return `Lab ${name} does not support state ${normalized}`\n}\nconst FINAL_STATUSES = [\n \"received.walk_in_test.ordered\",\n \"received.walk_in_test.requisition_created\",\n \"received.walk_in_test.requisition_bypassed\",\n \"completed.walk_in_test.completed\",\n \"sample_with_lab.walk_in_test.partial_results\",\n \"failed.walk_in_test.sample_error\",\n \"cancelled.walk_in_test.cancelled\",\n \"collecting_sample.walk_in_test.appointment_pending\",\n \"collecting_sample.walk_in_test.appointment_scheduled\",\n \"collecting_sample.walk_in_test.appointment_cancelled\",\n \"collecting_sample.walk_in_test.redraw_available\",\n \"received.at_home_phlebotomy.ordered\",\n \"received.at_home_phlebotomy.requisition_created\",\n \"received.at_home_phlebotomy.requisition_bypassed\",\n \"collecting_sample.at_home_phlebotomy.appointment_pending\",\n \"collecting_sample.at_home_phlebotomy.appointment_scheduled\",\n \"collecting_sample.at_home_phlebotomy.draw_completed\",\n \"collecting_sample.at_home_phlebotomy.appointment_cancelled\",\n \"completed.at_home_phlebotomy.completed\",\n \"sample_with_lab.at_home_phlebotomy.partial_results\",\n \"cancelled.at_home_phlebotomy.cancelled\",\n \"failed.at_home_phlebotomy.sample_error\",\n \"received.testkit.ordered\",\n \"received.testkit.awaiting_registration\",\n \"received.testkit.requisition_created\",\n \"received.testkit.requisition_bypassed\",\n \"received.testkit.registered\",\n \"collecting_sample.testkit.transit_customer\",\n \"collecting_sample.testkit.out_for_delivery\",\n \"collecting_sample.testkit.with_customer\",\n \"collecting_sample.testkit.transit_lab\",\n \"sample_with_lab.testkit.delivered_to_lab\",\n \"sample_with_lab.testkit.lab_processing_blocked\",\n \"completed.testkit.completed\",\n \"failed.testkit.failure_to_deliver_to_customer\",\n \"failed.testkit.failure_to_deliver_to_lab\",\n \"failed.testkit.sample_error\",\n \"failed.testkit.lost\",\n \"cancelled.testkit.cancelled\",\n \"cancelled.testkit.do_not_process\",\n \"collecting_sample.testkit.problem_in_transit_customer\",\n \"collecting_sample.testkit.problem_in_transit_lab\",\n \"received.on_site_collection.ordered\",\n \"received.on_site_collection.requisition_created\",\n \"received.on_site_collection.requisition_bypassed\",\n \"sample_with_lab.on_site_collection.draw_completed\",\n \"completed.on_site_collection.completed\",\n \"cancelled.on_site_collection.cancelled\",\n \"sample_with_lab.on_site_collection.partial_results\",\n \"failed.on_site_collection.sample_error\",\n \"completed.walk_in_test.corrected\",\n \"completed.at_home_phlebotomy.corrected\",\n \"completed.on_site_collection.corrected\",\n \"completed.testkit.corrected\",\n] as const\n\nconst finalStatusError = (value: string) => ({\n type: \"enum\",\n loc: [\"query\", \"final_status\"],\n msg: `Input should be ${FINAL_STATUSES.map((status) => `'${status}'`)\n .join(\", \")\n .replace(/, ([^,]*)$/, \" or $1\")}`,\n input: value,\n ctx: { expected: FINAL_STATUSES.map((status) => `'${status}'`).join(\", \") },\n})\n\nexport const orderHandlers = (state: JunctionState) => ({\n get_paginated_lab_tests_for_team_v3_lab_test_get: async () =>\n jsonRes(200, {\n data: state.listLabTests().filter((test) => test.auto_generated !== true),\n next_cursor: null,\n }),\n\n get_lab_test_for_team_v3_lab_tests__lab_test_id__get: async (context: OperationContext) => {\n const id = context.params.lab_test_id ?? \"\"\n const test = state.labTestById(id)\n if (!test) notFound(\"Lab test does not exist\")\n return jsonRes(200, test)\n },\n\n get_labs_v3_lab_tests_labs_get: async () => jsonRes(200, state.listLabs()),\n\n get_team_lab_accounts_v3_lab_test_lab_account_get: async (context: OperationContext) => {\n const requestedId = labAccountIdFilter(context)\n const status = labAccountStatusFilter(context)\n const data = state\n .listLabAccounts()\n .filter((entry) => entry.team_id_allowlist.includes(MOCK_TEAM_ID))\n .filter((entry) => requestedId === null || entry.id === requestedId)\n .filter((entry) => status === null || entry.status === status)\n .map(renderLabAccount)\n return jsonRes(200, { data })\n },\n\n get_markers_for_lab_test_v3_lab_tests__lab_test_id__markers_get: async (\n context: OperationContext,\n ) => {\n const id = context.params.lab_test_id ?? \"\"\n const test = state.labTestById(id)\n if (!test) notFound(\"Lab test does not exist\")\n const expected = state.expectedResultsFor(id)\n const markers = (test.markers ?? []).map((marker) => ({\n ...marker,\n expected_results: expected,\n }))\n return jsonRes(200, paginateMarkers(context.query, markers))\n },\n\n list_order_set_markers_v3_lab_tests_list_order_set_markers_post: async (\n context: OperationContext,\n ) => {\n const body = jsonObject(context)\n const orderSetId = body.order_set_id\n if (typeof orderSetId !== \"string\" || !isUuid(orderSetId)) {\n throw new HttpError(422, {\n detail: [uuidError(String(orderSetId ?? \"\"), 0, [\"body\", \"order_set_id\"])],\n })\n }\n const binding = state.orderByTransaction.get(orderSetId)\n const order = binding ? state.orders.get(binding.order_id) : undefined\n if (!order) notFound(\"Order set not found\")\n const providerId = typeof body.provider_id === \"string\" ? body.provider_id : null\n const markers = (order.lab_test.markers ?? [])\n .filter((marker) => providerId === null || marker.provider_id === providerId)\n .map((marker) => ({\n ...marker,\n expected_results: state.expectedResultsFor(order.lab_test.id),\n }))\n return jsonRes(200, paginateMarkers(context.query, markers))\n },\n\n create_order_v3_order_post: async (context: OperationContext) => {\n const rawBody = jsonObject(context)\n const body = trimStrings(rawBody) as Record<string, unknown>\n body.aoe_answers = rawBody.aoe_answers\n const patient = rawBody.patient_details\n if (typeof patient === \"object\" && patient !== null && !Array.isArray(patient)) {\n const details = patient as Record<string, unknown>\n const crashes = Object.entries(details).some(([key, value]) => {\n if (\n (key === \"first_name\" || key === \"last_name\") &&\n (typeof value === \"number\" || typeof value === \"boolean\")\n )\n return true\n if (key === \"gender\" && value !== null && typeof value !== \"string\") return true\n if (key === \"phone_number\" && value !== null && typeof value !== \"string\") return true\n if (key === \"dob\" && typeof value === \"boolean\") return true\n return false\n })\n if (crashes) {\n return new Response(\"Internal Server Error\", {\n status: 500,\n headers: { \"content-type\": \"text/plain; charset=utf-8\" },\n })\n }\n }\n const errors = orderValidation(body)\n if (errors.length > 0) throw new HttpError(422, { detail: errors })\n const rawAddress = body.patient_address\n if (\n typeof rawAddress === \"object\" &&\n rawAddress !== null &&\n !Array.isArray(rawAddress) &&\n typeof (rawAddress as Record<string, unknown>).country === \"string\" &&\n /[^A-Za-z ]/.test((rawAddress as Record<string, string>).country ?? \"\")\n ) {\n return new Response(\"Internal Server Error\", {\n status: 500,\n headers: { \"content-type\": \"text/plain; charset=utf-8\" },\n })\n }\n const userId = body.user_id\n if (typeof userId !== \"string\") throw new HttpError(422, { detail: \"user_id must be a string\" })\n if (!state.users.has(userId) && !state.deletedUsers.has(userId))\n notFound(\"User does not exist on this team\")\n const phone = (body.patient_details as Record<string, unknown> | undefined)?.phone_number\n if (typeof phone === \"string\" && /^\\+1\\d{10}$/.test(phone) && phone.slice(2, 5) === \"555\") {\n throw new HttpError(400, { detail: \"Phone number is not correct\" })\n }\n if (body.collection_method === \"testkit\")\n throw new HttpError(400, { detail: \"Cannot set collection_method to TESTKIT\" })\n const aoeError = aoeValidationError(state, body)\n if (aoeError) throw new HttpError(400, { detail: aoeError })\n const rawOrderSet = body.order_set\n if (rawOrderSet === undefined && body.lab_test_id === undefined) {\n throw new HttpError(400, { detail: \"Either lab_test_id or order_set must be set\" })\n }\n if (\n typeof rawOrderSet === \"object\" &&\n rawOrderSet !== null &&\n !Array.isArray(rawOrderSet) &&\n (rawOrderSet as Record<string, unknown>).lab_test_ids === undefined &&\n (rawOrderSet as Record<string, unknown>).add_on === undefined\n ) {\n throw new HttpError(400, { detail: \"lab_test_ids or add_on must be set in order_set\" })\n }\n const details = body.patient_details as Record<string, unknown>\n const address = body.patient_address as Record<string, unknown>\n const labTestIds = Array.isArray((body.order_set as Record<string, unknown>).lab_test_ids)\n ? ((body.order_set as Record<string, unknown>).lab_test_ids as unknown[])\n : []\n // Vital: empty lab_test_ids \u2192 \"No markers found\u2026\"; unknown id \u2192 \"Test does not exist\";\n // known panels with markers:null (e.g. Female General Wellness) still create successfully.\n if (labTestIds.length === 0) {\n throw new HttpError(400, {\n detail: \"No markers found for the supplied lab tests. Please check the lab test ids\",\n })\n }\n const resolved = labTestIds.map((id) =>\n typeof id === \"string\" ? state.labTestById(id) : undefined,\n )\n if (resolved.some((test) => test === undefined)) {\n throw new HttpError(400, { detail: \"Test does not exist\" })\n }\n const labTests = resolved as NonNullable<(typeof resolved)[number]>[]\n const methods = new Set(\n labTests.map((test) =>\n typeof test.method === \"string\" && test.method.length > 0 ? test.method : \"\",\n ),\n )\n if (methods.size > 1) {\n throw new HttpError(400, {\n detail: \"Cannot order with lab tests with multiple collection methods\",\n })\n }\n const labTest = labTests[0]\n if (!labTest) throw new HttpError(400, { detail: \"Test does not exist\" })\n\n const stateError = labStateSupportError(labTest, address.state)\n if (stateError) throw new HttpError(400, { detail: stateError })\n\n // Lab-account routing: the account must be active, linked to the team and associated\n // with the ordered lab; with no explicit id, linked accounts decide the branch.\n const labSlug = typeof labTest.lab?.slug === \"string\" ? labTest.lab.slug.toLowerCase() : \"\"\n const labAccount = selectLabAccount(\n labSlug,\n typeof body.lab_account_id === \"string\" ? body.lab_account_id : null,\n MOCK_TEAM_ID,\n state.listLabAccounts(),\n )\n const billingType =\n typeof body.billing_type === \"string\" && body.billing_type !== \"\"\n ? body.billing_type\n : \"client_bill\"\n const allowedStates = effectiveBilling(labAccount)[billingType]\n if (!allowedStates)\n throw new HttpError(400, {\n detail: `Billing type ${billingType} is not supported by the lab account used for this order`,\n })\n const patientState = String(address.state ?? \"\")\n .trim()\n .toUpperCase()\n if (patientState !== \"\" && !allowedStates.includes(patientState))\n throw new HttpError(400, {\n detail: `Billing type ${billingType} is not available in state ${patientState} for the lab account used for this order`,\n })\n const icdCodes = Array.isArray(body.icd_codes) ? ([...body.icd_codes] as string[]) : null\n if (billingType === \"commercial_insurance\" && (icdCodes === null || icdCodes.length === 0))\n throw new HttpError(400, {\n detail: \"Commercial insurance orders require at least one ICD code in icd_codes\",\n })\n\n const nowIso = state.isoNow(context.now)\n const nowMicro = new Date(context.now()).toISOString()\n const orderId = state.nextOrderId()\n const transactionId = state.transactionIdFor(orderId)\n const method =\n typeof body.collection_method === \"string\" ? body.collection_method : labTest.method\n // Sandbox: same collection_method as the panel \u2192 embed the panel as-is (even when\n // markers are null). Different method requires markers to synthesize auto_generated.\n const nativeMethod =\n typeof labTest.method === \"string\" && labTest.method.length > 0 ? labTest.method : method\n const markerCount = labTests.reduce((sum, test) => sum + (test.markers?.length ?? 0), 0)\n if (method !== nativeMethod && markerCount === 0) {\n throw new HttpError(400, {\n detail: \"No markers found for the supplied lab tests. Please check the lab test ids\",\n })\n }\n const idempotencyKey = body.idempotency_key\n const requestFingerprint = JSON.stringify(body)\n if (typeof idempotencyKey === \"string\" && idempotencyKey.length > 0) {\n const replay = state.orderIdempotency.get(idempotencyKey)\n if (replay) {\n if (replay.fingerprint !== requestFingerprint)\n throw new HttpError(400, {\n detail: \"Idempotency key was reused with a different request\",\n })\n return jsonRes(200, replay.response)\n }\n }\n const eventStatus = `received.${method}.ordered`\n const eventId =\n Number.parseInt(opaqueToken(`junction:order-event:${orderId}`, 8), 16) % 1_000_000_000 || 1\n const event = {\n id: eventId,\n created_at: nowIso,\n status: eventStatus,\n status_detail: null,\n }\n let orderLabTest: typeof labTest\n if (method === nativeMethod) {\n orderLabTest = labTest\n } else {\n const markerFingerprint = (test: { markers?: Array<{ id: number }> | null }) =>\n (test.markers ?? [])\n .map((marker) => marker.id)\n .sort((a, b) => a - b)\n .join(\",\")\n const sourceFingerprint = markerFingerprint(labTest)\n const existingAuto = state\n .listLabTests()\n .find(\n (test) =>\n test.auto_generated === true &&\n test.method === method &&\n markerFingerprint(test) === sourceFingerprint,\n )\n const orderLabTestKey = `${labTest.id}:${method}`\n const orderLabTestName =\n existingAuto?.name ?? opaqueToken(`junction:order-lab-name:${orderLabTestKey}`, 16)\n orderLabTest = existingAuto ?? {\n ...labTest,\n id: deterministicUuid(`junction:order-lab-test:${orderLabTestKey}`),\n method,\n auto_generated: true,\n name: orderLabTestName,\n slug: `afd62b39-${orderLabTestName}`,\n }\n }\n const order: OrderRecord = {\n id: orderId,\n user_id: userId,\n team_id: MOCK_TEAM_ID,\n patient_details: patientDetails(details as Record<string, unknown>),\n patient_address: patientAddress(address as Record<string, unknown>),\n lab_test: orderLabTest,\n details: METHOD_DETAILS(method, state.testkitIdFor(orderId), nowIso),\n sample_id: null,\n notes: null,\n clinical_notes: typeof body.clinical_notes === \"string\" ? body.clinical_notes : null,\n passthrough: typeof body.passthrough === \"string\" ? body.passthrough : null,\n ...(typeof body.lab_account_id === \"string\" ? { lab_account_id: body.lab_account_id } : {}),\n created_at: nowIso,\n updated_at: nowIso,\n events: [event],\n status: \"received\",\n last_event: event,\n physician: PHYSICIAN,\n health_insurance_id: null,\n requisition_form_url: null,\n shipping_details: null,\n has_abn: false,\n billing_type: billingType,\n priority: false,\n activate_by: null,\n icd_codes: icdCodes,\n interpretation: null,\n has_missing_results: null,\n result_types: null,\n expected_result_by_date: null,\n worst_case_result_by_date: null,\n origin: \"initial\",\n order_transaction: {\n id: transactionId,\n status: \"active\",\n orders: [\n {\n id: orderId,\n low_level_status: \"ordered\",\n low_level_status_created_at: nowMicro,\n origin: \"initial\",\n parent_id: null,\n created_at: nowMicro,\n updated_at: nowMicro,\n },\n ],\n },\n }\n state.orders.insert(orderId, order)\n state.orderByTransaction.insert(transactionId, { order_id: orderId })\n state.upsertLabTest(\n orderLabTest,\n orderLabTest.id === labTest.id ? undefined : state.expectedResultsFor(labTest.id),\n )\n const demographics = {\n first_name: details.first_name ?? null,\n last_name: details.last_name ?? null,\n dob: details.dob ?? null,\n gender: details.gender ?? null,\n phone_number: details.phone_number ?? null,\n email: details.email ?? null,\n gender_identity: null,\n sexual_orientation: null,\n race: null,\n ethnicity: null,\n medical_proxy: null,\n address: {\n first_line: address.first_line ?? \"\",\n second_line: typeof address.second_line === \"string\" ? address.second_line : \"\",\n country: address.country ?? \"\",\n zip: address.zip ?? \"\",\n city: address.city ?? \"\",\n state: address.state ?? \"\",\n access_notes: null,\n },\n }\n if (state.userInfo.get(userId)) state.userInfo.update(userId, demographics)\n else state.userInfo.insert(userId, demographics)\n const responseOrder = { ...order } as Record<string, unknown>\n if (responseOrder.result_types === null) delete responseOrder.result_types\n const response = {\n order: responseOrder,\n status: \"success\",\n message: \"Order created successfully\",\n }\n if (typeof idempotencyKey === \"string\" && idempotencyKey.length > 0)\n state.orderIdempotency.insert(idempotencyKey, {\n order_id: orderId,\n response,\n fingerprint: requestFingerprint,\n })\n state.publishOrderWebhook(order, \"labtest.order.created\", context.now())\n return jsonRes(200, response)\n },\n\n cancel_order_v3_order__order_id__cancel_post: async (context: OperationContext) => {\n const id = context.params.order_id ?? \"\"\n const order = state.orders.get(id)\n if (!order) notFound(\"Order doesn't exist\")\n const alreadyCancelled = order.events.some(\n (entry) => typeof entry.status === \"string\" && entry.status.startsWith(\"cancelled.\"),\n )\n if (alreadyCancelled) {\n const responseOrder = { ...order } as Record<string, unknown>\n if (responseOrder.result_types === null) delete responseOrder.result_types\n return jsonRes(200, {\n order: responseOrder,\n status: \"success\",\n message: \"order already cancelled\",\n })\n }\n const lastEvent = order.last_event ?? order.events[order.events.length - 1]\n const lowLevel = typeof lastEvent?.status === \"string\" ? lastEvent.status : \"\"\n if (!CANCELLABLE_ORDER_EVENTS.has(lowLevel)) {\n throw new HttpError(400, {\n detail:\n \"This order is not in a Cancellable Status. Refer to the documentation to check the order lifecycle (https://docs.tryvital.io/lab/workflow/lab-test-lifecycle).\",\n })\n }\n const now = state.isoNow(context.now)\n const method =\n typeof order.lab_test.method === \"string\" && order.lab_test.method.length > 0\n ? order.lab_test.method\n : typeof order.details?.type === \"string\" && order.details.type.length > 0\n ? order.details.type\n : \"at_home_phlebotomy\"\n order.status = \"cancelled\"\n order.updated_at = now\n const event = {\n id: order.events.length + 1,\n created_at: now,\n status: `cancelled.${method}.cancelled`,\n status_detail: null,\n }\n order.events.push(event)\n order.last_event = event\n order.order_transaction.status = \"cancelled\"\n const transactionOrder = order.order_transaction.orders[0]\n if (transactionOrder) {\n transactionOrder.low_level_status = \"cancelled\"\n transactionOrder.updated_at = new Date(context.now()).toISOString()\n }\n state.orders.update(id, order)\n state.publishOrderWebhook(order, \"labtest.order.updated\", context.now())\n // Junction auto-cancels mobile phlebotomy appointments on order cancel, but\n // leaves walk-in PSC appointments alone (patient may already be en route).\n if (method === \"at_home_phlebotomy\") {\n cascadeCancelAppointments(state, id, context.now())\n }\n const responseOrder = { ...order } as Record<string, unknown>\n if (responseOrder.result_types === null) delete responseOrder.result_types\n const response = {\n order: responseOrder,\n status: \"success\",\n message: \"order cancelled\",\n }\n return jsonRes(200, response)\n },\n\n simulate_order_v3_order__order_id__test_post: async (context: OperationContext) => {\n const id = context.params.order_id ?? \"\"\n const finalStatus = context.query.final_status\n if (!isUuid(id))\n throw new HttpError(422, { detail: [uuidError(id, undefined, [\"path\", \"order_id\"])] })\n if (\n finalStatus !== undefined &&\n (typeof finalStatus !== \"string\" ||\n !FINAL_STATUSES.includes(finalStatus as (typeof FINAL_STATUSES)[number]))\n )\n throw new HttpError(422, { detail: [finalStatusError(String(finalStatus ?? \"\"))] })\n const delayRaw = context.query.delay\n let delaySeconds = 0\n if (delayRaw !== undefined) {\n if (typeof delayRaw !== \"string\" || !/^\\d+$/.test(delayRaw))\n throw new HttpError(422, { detail: \"delay must be a non-negative integer\" })\n delaySeconds = Number(delayRaw)\n }\n const body = context.body\n if (body.kind === \"json\") {\n const value = body.value\n if (typeof value !== \"object\" || Array.isArray(value)) {\n throw new HttpError(422, {\n detail: [\n {\n type: \"model_attributes_type\",\n loc: [\"body\"],\n msg: \"Input should be a valid dictionary or object to extract fields from\",\n input: value,\n },\n ],\n })\n }\n }\n const order = state.orders.get(id)\n if (!order) notFound(\"Order doesn't exist\")\n if (\n typeof finalStatus !== \"string\" ||\n !FINAL_STATUSES.includes(finalStatus as (typeof FINAL_STATUSES)[number])\n )\n throw new HttpError(422, { detail: [finalStatusError(String(finalStatus ?? \"\"))] })\n const flags = simulationFlagsOf(context)\n if (delaySeconds > 0) {\n state.queueSimulateTransition({\n order_id: id,\n due_at: context.now() + delaySeconds * 1000,\n final_status: finalStatus,\n flags,\n })\n return jsonRes(200, \"Success\")\n }\n applySimulateTransition(state, order, finalStatus, flags, context)\n return jsonRes(200, \"Success\")\n },\n\n get_order_v3_order__order_id__get: async (context: OperationContext) => {\n const id = context.params.order_id ?? \"\"\n const order = state.orders.get(id)\n if (!order) notFound(\"This order doesn't exist\")\n state.applyDueSimulateTransitions(context.now(), (due, finalStatus, flags) => {\n applySimulateTransition(state, due, finalStatus, flags, context)\n })\n const fresh = state.orders.get(id)\n if (!fresh) notFound(\"This order doesn't exist\")\n const body = { ...fresh } as Record<string, unknown>\n if (body.result_types === null) delete body.result_types\n return jsonRes(200, body)\n },\n\n get_orders_v3_orders_get: async (context: OperationContext) => {\n const page = queryInt(context, \"page\", 1)\n const size = queryInt(context, \"size\", 50)\n if (page < 1 || size < 1 || size > 100)\n throw new HttpError(422, { detail: \"page must be >= 1 and size must be 1..100\" })\n const userId = context.query.user_id\n if (userId !== undefined && typeof userId !== \"string\")\n throw new HttpError(422, { detail: \"user_id must be a string\" })\n if (userId !== undefined && !state.users.has(userId) && !state.deletedUsers.has(userId))\n notFound(\"User does not exist on this team\")\n let all = state.orders.list({ order: \"oldest\" })\n if (userId !== undefined) all = all.filter((entry) => entry.value.user_id === userId)\n // Sandbox lists by updated_at desc (not created_at) \u2014 wrong order breaks\n // seedParity identity pairing on list pages, which then poisons get_order.\n all = [...all].sort((left, right) => {\n const leftAt = Date.parse(String(left.value.updated_at ?? left.value.created_at ?? \"\")) || 0\n const rightAt =\n Date.parse(String(right.value.updated_at ?? right.value.created_at ?? \"\")) || 0\n if (rightAt !== leftAt) return rightAt - leftAt\n // Frozen clocks make updated_at ties common; seq matches sandbox insertion order.\n return right.seq - left.seq\n })\n const pageItems = all.slice((page - 1) * size, page * size)\n return jsonRes(200, {\n orders: pageItems.map((entry) => {\n const order = { ...entry.value } as Record<string, unknown>\n if (order.result_types === null) delete order.result_types\n return order\n }),\n total: all.length,\n page,\n size,\n })\n },\n\n get_order_transaction_v3_order_transaction__transaction_id__get: async (\n context: OperationContext,\n ) => {\n const id = context.params.transaction_id ?? \"\"\n const binding = state.orderByTransaction.get(id)\n const order = binding ? state.orders.get(binding.order_id) : undefined\n if (!order) notFound(\"Order transaction not found\")\n return jsonRes(200, {\n id,\n team_id: MOCK_TEAM_ID,\n status: order.order_transaction.status,\n orders: [orderSummary(order)],\n })\n },\n\n get_order_transaction_result_v3_order_transaction__transaction_id__result_get: async (\n context: OperationContext,\n ) => {\n const id = context.params.transaction_id ?? \"\"\n const binding = state.orderByTransaction.get(id)\n const order = binding ? state.orders.get(binding.order_id) : undefined\n if (!order) notFound(\"Order transaction not found\")\n const user = order.user_id ? state.users.get(order.user_id) : undefined\n return jsonRes(200, {\n metadata: {\n age: \"41\",\n dob: \"1983-06-23\",\n patient: user?.client_user_id ?? order.user_id,\n date_reported: \"2024-11-02\",\n specimen_number: opaqueToken(`junction:specimen:${order.id}`, 24),\n status: \"final\",\n laboratory: \"Mockingbird Central Lab\",\n provider: null,\n interpretation: null,\n patient_id: null,\n account_id: null,\n date_collected: null,\n date_received: null,\n \"clia_#\": null,\n },\n results: biomarker(order, order.created_at),\n missing_results: null,\n sample_information: null,\n order_transaction: order.order_transaction,\n })\n },\n})\n\nconst orderSummary = (order: OrderRecord) => {\n const transactionOrder = order.order_transaction.orders.find((entry) => entry.id === order.id)\n return {\n id: order.id,\n origin: transactionOrder?.origin ?? \"initial\",\n parent_id: transactionOrder?.parent_id ?? null,\n last_status: transactionOrder?.low_level_status ?? \"ordered\",\n last_status_created_at: transactionOrder?.low_level_status_created_at ?? order.created_at,\n updated_at: order.updated_at,\n created_at: order.created_at,\n }\n}\n\nconst biomarker = (order: OrderRecord, created_at: string) =>\n (order.lab_test.markers ?? []).map((marker) => ({\n name: marker.name,\n slug: marker.slug,\n result: marker.slug,\n type: \"numeric\",\n unit: marker.unit,\n timestamp: created_at,\n reference_range: null,\n interpretation: \"normal\",\n performing_laboratory: \"Mockingbird Central Lab\",\n source_sample_id: null,\n }))\n", "/** Lab-results surface: raw results, metadata, and deterministic PDF artifacts. */\nimport {\n HttpError,\n jsonRes,\n type OperationContext,\n opaqueToken,\n} from \"@crvouga/mockingbird-service\"\nimport { applySimulateTransition, requireOrder } from \"./scheduling.js\"\nimport type { JunctionState, OrderRecord } from \"./state.js\"\n\nconst RESULT_TYPES = [\"numeric\", \"range\", \"comment\", \"coded_value\"] as const\ntype ResultType = (typeof RESULT_TYPES)[number]\n\nconst INTERPRETATIONS = [\"normal\", \"abnormal\", \"critical\", \"unknown\"] as const\ntype Interpretation = (typeof INTERPRETATIONS)[number]\n\n/** Statuses from which results exist (sample has been drawn and reported). */\nconst RESULT_READY_STATUSES = [\"sample_with_lab\", \"completed\"]\n\nconst resultsReady = (order: OrderRecord): boolean =>\n RESULT_READY_STATUSES.some((prefix) => order.status.startsWith(prefix)) ||\n order.last_event.status.endsWith(\"draw_completed\")\n\nconst parseInterpretation = (value: unknown): Interpretation =>\n INTERPRETATIONS.includes(value as Interpretation) ? (value as Interpretation) : \"normal\"\n\nconst pickResultType = (value: unknown, index: number): ResultType => {\n if (Array.isArray(value) && value.length > 0) {\n const entry = value[index % value.length]\n if (typeof entry === \"string\" && RESULT_TYPES.includes(entry as ResultType))\n return entry as ResultType\n }\n return \"numeric\"\n}\n\nconst numericValueFor = (slug: string): number => {\n let hash = 0\n for (let i = 0; i < slug.length; i++) hash = (hash * 31 + slug.charCodeAt(i)) % 1000\n return Math.round((40 + (hash % 160)) * 10) / 10\n}\n\ntype BiomarkerLine = {\n name: string\n slug: string\n result: string\n type: ResultType\n value: number | null\n unit: string | null\n timestamp: string\n reference_range: string | null\n interpretation: Interpretation\n performing_laboratory: string\n source_sample_id: string | null\n notes: string | null\n string_value: string | null\n coded_value: string | null\n low_value: number | null\n high_value: number | null\n provider_id: string | null\n}\n\nconst biomarkerLines = (order: OrderRecord, flags: SimulationFlagsState): BiomarkerLine[] => {\n const collected = order.last_event.created_at\n return (order.lab_test.markers ?? []).map((marker, index) => {\n const type = pickResultType(flags.resultTypes, index)\n const base: BiomarkerLine = {\n name: marker.name,\n slug: marker.slug,\n result: marker.slug,\n type,\n value: null,\n unit: marker.unit,\n timestamp: collected,\n reference_range: null,\n interpretation: flags.interpretation,\n performing_laboratory: \"Mockingbird Central Lab\",\n source_sample_id: order.sample_id,\n notes: null,\n string_value: null,\n coded_value: null,\n low_value: null,\n high_value: null,\n provider_id: marker.provider_id,\n }\n if (type === \"numeric\") {\n base.value = numericValueFor(marker.slug)\n base.result = String(base.value)\n base.reference_range = \"0-200\"\n base.low_value = 0\n base.high_value = 200\n } else if (type === \"range\") {\n base.low_value = 0\n base.high_value = 200\n base.value = numericValueFor(marker.slug)\n base.reference_range = \"0-200\"\n base.result = `${base.low_value}-${base.high_value}`\n } else if (type === \"comment\") {\n base.string_value = \"No abnormal findings reported.\"\n base.result = base.string_value\n } else {\n base.coded_value = flags.interpretation === \"normal\" ? \"N\" : \"A\"\n base.result = base.coded_value\n }\n return base\n })\n}\n\nexport type SimulationFlagsState = {\n interpretation: Interpretation\n resultTypes: readonly string[] | null\n hasMissingResults: boolean\n}\n\nconst flagsOf = (order: OrderRecord): SimulationFlagsState => {\n const raw = order.result_types\n const resultTypes =\n Array.isArray(raw) && raw.length > 0\n ? raw.filter((entry): entry is string => typeof entry === \"string\")\n : null\n return {\n interpretation: parseInterpretation(order.interpretation),\n resultTypes,\n hasMissingResults: order.has_missing_results === true,\n }\n}\n\nconst ageFromDob = (dob: string, nowIso: string) => {\n const born = Date.parse(`${dob}T00:00:00.000Z`)\n const now = Date.parse(nowIso)\n if (!Number.isFinite(born) || !Number.isFinite(now) || now < born) return \"0\"\n const years = Math.floor((now - born) / (365.25 * 24 * 60 * 60 * 1000))\n return String(Math.max(0, years))\n}\n\nconst metadataOf = (order: OrderRecord, _userClient: string) => {\n const details = order.patient_details ?? {}\n const first =\n typeof details.first_name === \"string\" && details.first_name.length > 0\n ? details.first_name\n : \"Patient\"\n const last =\n typeof details.last_name === \"string\" && details.last_name.length > 0 ? details.last_name : \"\"\n const dob = typeof details.dob === \"string\" && details.dob.length > 0 ? details.dob : \"1990-01-01\"\n const labName =\n order.lab_test.lab && typeof order.lab_test.lab.name === \"string\"\n ? order.lab_test.lab.name\n : \"Labcorp\"\n const reportedAt = order.last_event.created_at\n return {\n age: ageFromDob(dob, reportedAt),\n dob,\n patient: `${first} ${last}`.trim(),\n date_reported: reportedAt,\n specimen_number: opaqueToken(`junction:specimen:${order.id}`, 24),\n status: \"final\",\n laboratory: labName,\n provider: order.physician\n ? `${order.physician.first_name} ${order.physician.last_name}`.trim()\n : null,\n interpretation: order.interpretation,\n patient_id: order.user_id,\n account_id: null,\n date_collected: reportedAt,\n date_received: reportedAt,\n \"clia_#\": null,\n }\n}\n\n/** Minimal single-page PDF with a deterministic title; valid enough for byte-shape checks. */\nconst deterministicPdf = (title: string): Uint8Array => {\n const text = `BT /F1 14 Tf 72 720 Td (${title}) Tj ET`\n const objects = [\n \"<< /Type /Catalog /Pages 2 0 R >>\",\n \"<< /Type /Pages /Kids [3 0 R] /Count 1 >>\",\n \"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>\",\n `<< /Length ${text.length} >>\\nstream\\n${text}\\nendstream`,\n \"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\",\n ]\n let body = \"%PDF-1.4\\n\"\n const offsets: number[] = []\n objects.forEach((entry, index) => {\n offsets.push(body.length)\n body += `${index + 1} 0 obj\\n${entry}\\nendobj\\n`\n })\n const xrefStart = body.length\n body += `xref\\n0 ${objects.length + 1}\\n0000000000 65535 f \\n`\n for (const offset of offsets) body += `${String(offset).padStart(10, \"0\")} 00000 n \\n`\n body += `trailer\\n<< /Size ${objects.length + 1} /Root 1 0 R >>\\nstartxref\\n${xrefStart}\\n%%EOF\\n`\n return new TextEncoder().encode(body)\n}\n\nfunction resultsNotAvailable(orderId: string): never {\n throw new HttpError(404, {\n detail: `Results are not available for order - ${orderId}. Did you receive a webhook for this order?`,\n })\n}\n\nexport const resultsHandlers = (state: JunctionState) => ({\n get_result_raw_v3_order__order_id__result_get: async (context: OperationContext) => {\n const orderId = context.params.order_id ?? \"\"\n const order = requireOrder(state, orderId, context, \"Order not found\")\n const user = state.users.get(order.user_id)\n if (!resultsReady(order)) resultsNotAvailable(order.id)\n const flags = flagsOf(order)\n const fixture = state.resultFixtures.get(order.id)\n const results = fixture?.results ?? biomarkerLines(order, flags)\n const missing =\n fixture?.missing_results !== undefined\n ? fixture.missing_results\n : flags.hasMissingResults\n ? [\n {\n name: (order.lab_test.markers ?? [])[0]?.name ?? \"Unknown marker\",\n slug: (order.lab_test.markers ?? [])[0]?.slug ?? \"unknown-marker\",\n inferred_failure_type: \"quantity_not_sufficient_failure\",\n note: \"Specimen quantity was not sufficient to run this marker.\",\n loinc: null,\n loinc_slug: null,\n provider_id: (order.lab_test.markers ?? [])[0]?.provider_id ?? null,\n source_markers: null,\n },\n ]\n : null\n return jsonRes(200, {\n metadata: metadataOf(order, user?.client_user_id ?? order.user_id),\n results,\n missing_results: missing,\n sample_information: {\n [order.sample_id ?? opaqueToken(`junction:sample:${order.id}`, 16)]: {\n sample_id: order.sample_id ?? opaqueToken(`junction:sample:${order.id}`, 16),\n control_number: order.sample_id,\n date_collected: order.last_event.created_at,\n date_received: order.last_event.created_at,\n date_reported: order.last_event.created_at,\n performing_laboratories: null,\n clinical_information: null,\n },\n },\n order_transaction: order.order_transaction,\n })\n },\n\n get_result_metadata_v3_order__order_id__result_metadata_get: async (\n context: OperationContext,\n ) => {\n const orderId = context.params.order_id ?? \"\"\n const order = requireOrder(state, orderId, context, \"Order not found\")\n if (!resultsReady(order)) resultsNotAvailable(order.id)\n const user = state.users.get(order.user_id)\n return jsonRes(200, metadataOf(order, user?.client_user_id ?? order.user_id))\n },\n\n get_result_pdf_v3_order__order_id__result_pdf_get: async (context: OperationContext) => {\n const orderId = context.params.order_id ?? \"\"\n const order = requireOrder(state, orderId, context, \"Order not found\")\n if (!resultsReady(order)) resultsNotAvailable(order.id)\n const fixturePdf = state.resultFixtures.get(order.id)?.pdf_base64\n const bytes =\n fixturePdf !== undefined\n ? Uint8Array.from(atob(fixturePdf), (char) => char.charCodeAt(0))\n : deterministicPdf(`Lab results ${order.id}`)\n return new Response(bytes as unknown as BodyInit, {\n status: 200,\n headers: { \"content-type\": \"application/pdf\" },\n })\n },\n\n get_order_requisition_pdf_v3_order__order_id__requisition_pdf_get: async (\n context: OperationContext,\n ) => {\n const orderId = context.params.order_id ?? \"\"\n const order = requireOrder(state, orderId, context, \"This order doesn't exist\")\n const bytes = deterministicPdf(`Requisition ${order.id}`)\n return new Response(bytes as unknown as BodyInit, {\n status: 200,\n headers: { \"content-type\": \"application/pdf\" },\n })\n },\n})\n\nexport { applySimulateTransition }\n", "import { addressFromAvailabilityRequest } from \"./scheduling.js\"\nimport type {\n AppointmentModality,\n AppointmentRecord,\n ExpectedResult,\n GetCacheEntry,\n JunctionState,\n LabTestRecord,\n OrderRecord,\n UserInfoRecord,\n UserRecord,\n} from \"./state.js\"\n\nexport type SeedSource = {\n fetch: (request: Request) => Promise<Response>\n baseUrl: string\n headers: Record<string, string>\n}\n\nexport type SeedObservations = {\n getCache?: ReadonlyMap<string, GetCacheEntry>\n}\n\nexport type SeedReport = {\n users: number\n orders: number\n appointments: number\n catalogTests: number\n labs: number\n cacheEntries: number\n}\n\nconst clone = <T>(value: T): T => JSON.parse(JSON.stringify(value)) as T\n\n/**\n * Parse the availability POST body embedded in an observation cache key\n * (`\"<METHOD> <path>?<query> <JSON body>\"`).\n */\nconst parseAvailabilityRequestBody = (cacheKey: string): Record<string, unknown> | undefined => {\n const jsonStart = cacheKey.indexOf(\" {\")\n if (jsonStart === -1) return undefined\n try {\n const parsed: unknown = JSON.parse(cacheKey.slice(jsonStart + 1))\n if (typeof parsed === \"object\" && parsed !== null && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>\n }\n } catch {\n return undefined\n }\n return undefined\n}\n\n/**\n * Vital echoes the availability request address on book/reschedule. Re-stamp every\n * booking-key record hydrated from one availability observation so its address matches\n * the availability request \u2014 the oracle's behavior for both modalities.\n */\nconst alignBookingKeyAddresses = (\n state: JunctionState,\n body: unknown,\n requestBody: Record<string, unknown>,\n zip: string,\n modalityHint?: AppointmentModality,\n): void => {\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) return\n const root = body as Record<string, unknown>\n const dayBuckets: unknown[] = []\n if (Array.isArray(root.days)) dayBuckets.push(...root.days)\n if (Array.isArray(root.slots)) dayBuckets.push(...root.slots)\n for (const day of dayBuckets) {\n const slots = Array.isArray((day as Record<string, unknown>)?.slots)\n ? ((day as Record<string, unknown>).slots as unknown[])\n : [day]\n for (const slot of slots) {\n if (typeof slot !== \"object\" || slot === null || Array.isArray(slot)) continue\n const bookingKey = (slot as Record<string, unknown>).booking_key\n if (typeof bookingKey !== \"string\" || bookingKey === \"\") continue\n const record = state.bookingKeys.get(bookingKey)\n if (!record || (modalityHint !== undefined && record.modality !== modalityHint)) continue\n record.address = addressFromAvailabilityRequest(requestBody, zip)\n state.bookingKeys.update(bookingKey, record)\n }\n }\n}\n\nconst request = async (\n source: SeedSource,\n method: string,\n path: string,\n init: RequestInit = {},\n): Promise<Response> => {\n const url = new URL(path, source.baseUrl.endsWith(\"/\") ? source.baseUrl : `${source.baseUrl}/`)\n const headers = new Headers(init.headers)\n for (const [name, value] of Object.entries(source.headers)) headers.set(name, value)\n return source.fetch(new Request(url, { ...init, method, headers }))\n}\n\nconst readJson = async (response: Response): Promise<unknown> => {\n if (response.status === 204) return null\n const text = await response.text()\n if (text.trim() === \"\") return null\n try {\n return JSON.parse(text) as unknown\n } catch {\n return text\n }\n}\n\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined\n\nconst asString = (value: unknown): string | undefined =>\n typeof value === \"string\" ? value : undefined\n\nconst mapUser = (value: unknown): UserRecord | undefined => {\n const record = asRecord(value)\n if (!record) return undefined\n const userId = asString(record.user_id)\n const clientUserId = asString(record.client_user_id)\n if (!userId || !clientUserId) return undefined\n return {\n user_id: userId,\n team_id: asString(record.team_id) ?? \"00000000-0000-4000-8000-000000000000\",\n client_user_id: clientUserId,\n created_on: asString(record.created_on) ?? new Date(0).toISOString(),\n connected_sources: Array.isArray(record.connected_sources) ? record.connected_sources : [],\n fallback_time_zone:\n typeof record.fallback_time_zone === \"object\" && record.fallback_time_zone !== null\n ? (record.fallback_time_zone as UserRecord[\"fallback_time_zone\"])\n : null,\n fallback_birth_date:\n typeof record.fallback_birth_date === \"object\" && record.fallback_birth_date !== null\n ? (record.fallback_birth_date as UserRecord[\"fallback_birth_date\"])\n : null,\n ingestion_start: asString(record.ingestion_start) ?? null,\n ingestion_end: asString(record.ingestion_end) ?? null,\n }\n}\n\nexport const mapLabTest = (value: unknown): LabTestRecord | undefined => {\n const record = asRecord(value)\n if (!record) return undefined\n const id = asString(record.id)\n if (!id) return undefined\n return clone(record) as LabTestRecord\n}\n\nconst mapOrder = (value: unknown): OrderRecord | undefined => {\n const record = asRecord(value)\n if (!record) return undefined\n const id = asString(record.id)\n const userId = asString(record.user_id)\n if (!id || !userId) return undefined\n return clone(record) as OrderRecord\n}\n\nconst mapAppointment = (\n value: unknown,\n orderId: string,\n userId: string,\n): AppointmentRecord | undefined => {\n const record = asRecord(value)\n if (!record) return undefined\n const id = asString(record.id)\n if (!id) return undefined\n return {\n ...(clone(record) as AppointmentRecord),\n id,\n order_id: asString(record.order_id) ?? orderId,\n user_id: asString(record.user_id) ?? userId,\n }\n}\n\nconst demographicsFromOrder = (order: OrderRecord): UserInfoRecord => {\n const details =\n order.patient_details && typeof order.patient_details === \"object\"\n ? (order.patient_details as Record<string, unknown>)\n : {}\n const address =\n order.patient_address && typeof order.patient_address === \"object\"\n ? (order.patient_address as Record<string, unknown>)\n : {}\n return {\n first_name: details.first_name ?? null,\n last_name: details.last_name ?? null,\n dob: details.dob ?? null,\n gender: details.gender ?? null,\n phone_number: details.phone_number ?? null,\n email: details.email ?? null,\n gender_identity: null,\n sexual_orientation: null,\n race: null,\n ethnicity: null,\n medical_proxy: null,\n address: {\n first_line: address.first_line ?? \"\",\n second_line: typeof address.second_line === \"string\" ? address.second_line : \"\",\n country: address.country ?? \"\",\n zip: address.zip ?? \"\",\n city: address.city ?? \"\",\n state: address.state ?? \"\",\n access_notes: null,\n },\n }\n}\n\nconst ensureUserInfoForOrder = async (\n state: JunctionState,\n source: SeedSource,\n order: OrderRecord,\n): Promise<void> => {\n if (state.userInfo.get(order.user_id)) return\n const infoResponse = await request(source, \"GET\", `/v2/user/${order.user_id}/info/latest`)\n if (infoResponse.ok) {\n const info = asRecord(await readJson(infoResponse))\n if (info) {\n state.userInfo.insert(order.user_id, info as UserInfoRecord)\n return\n }\n }\n state.userInfo.insert(order.user_id, demographicsFromOrder(order))\n}\n\nconst expectedFromMarkers = (labTest: LabTestRecord): ExpectedResult[] => {\n const markers = labTest.markers ?? []\n return markers.map((marker) => ({\n id: marker.id,\n name: marker.name,\n slug: marker.slug,\n lab_id: marker.lab_id,\n provider_id: marker.provider_id,\n required: true,\n loinc: null,\n }))\n}\n\nexport const expectedFromMarkersResponse = async (\n source: SeedSource,\n test: LabTestRecord,\n): Promise<ExpectedResult[]> => {\n const markersResponse = await request(source, \"GET\", `/v3/lab_tests/${test.id}/markers`)\n if (!markersResponse.ok) return expectedFromMarkers(test)\n const markersPayload = asRecord(await readJson(markersResponse))\n const markers = markersPayload?.markers\n if (!Array.isArray(markers) || markers.length === 0) return expectedFromMarkers(test)\n const expected: ExpectedResult[] = []\n const cleaned: NonNullable<LabTestRecord[\"markers\"]> = []\n for (const entry of markers) {\n const record = asRecord(entry)\n if (!record) continue\n const expectedField = record.expected_results\n if (Array.isArray(expectedField) && expectedField.length > 0 && expected.length === 0) {\n for (const item of expectedField) {\n const expectedRecord = asRecord(item)\n if (expectedRecord) expected.push(clone(expectedRecord) as ExpectedResult)\n }\n }\n const { expected_results: _ignored, ...rest } = record\n cleaned.push(rest as NonNullable<LabTestRecord[\"markers\"]>[number])\n }\n test.markers = cleaned\n return expected.length > 0 ? expected : expectedFromMarkers(test)\n}\n\nexport const ensureLabTests = async (\n state: JunctionState,\n source: SeedSource,\n ids: readonly string[],\n): Promise<number> => {\n let added = 0\n for (const id of ids) {\n if (!id) continue\n const response = await request(source, \"GET\", `/v3/lab_tests/${id}`)\n if (!response.ok) continue\n const test = mapLabTest(await readJson(response))\n if (!test) continue\n const expected = await expectedFromMarkersResponse(source, test)\n const existed = Boolean(state.labTestById(id))\n state.upsertLabTest(test, expected)\n if (!existed) added += 1\n }\n return added\n}\n\n/**\n * Pull any warmup-registered orders that user-list seeding missed (e.g. orders whose\n * user was deleted during warmup and therefore no longer appears in `/v2/user`).\n */\nexport const ensureOrders = async (\n state: JunctionState,\n source: SeedSource,\n ids: readonly string[],\n): Promise<number> => {\n let added = 0\n for (const id of ids) {\n if (!id) continue\n const orderResponse = await request(source, \"GET\", `/v3/order/${id}`)\n if (!orderResponse.ok) continue\n const order = mapOrder(await readJson(orderResponse))\n if (!order) continue\n if (!state.users.has(order.user_id) && !state.deletedUsers.has(order.user_id)) {\n const userResponse = await request(source, \"GET\", `/v2/user/${order.user_id}`)\n if (userResponse.ok) {\n const user = mapUser(await readJson(userResponse))\n if (user) state.insertUser(user)\n } else {\n state.deletedUsers.insert(order.user_id, { user_id: order.user_id })\n }\n }\n const existed = Boolean(state.orders.get(id))\n if (existed) state.orders.update(id, order)\n else state.insertOrder(order)\n if (order.lab_test?.id) state.upsertLabTest(order.lab_test)\n await ensureUserInfoForOrder(state, source, order)\n if (!existed) added += 1\n }\n return added\n}\n\nexport const seedFrom = async (\n state: JunctionState,\n source: SeedSource,\n observations?: SeedObservations,\n): Promise<SeedReport> => {\n let cacheEntries = 0\n if (observations?.getCache) {\n state.installGetCache(observations.getCache)\n cacheEntries = observations.getCache.size\n const nowMs = Date.now()\n for (const [key, entry] of observations.getCache) {\n if (!key.toLowerCase().includes(\"availability\")) continue\n const zipMatch = key.match(/\"zip_code\":\"(\\d{5})\"/)\n const modality = key.toLowerCase().includes(\"psc\")\n ? (\"patient_service_center\" as const)\n : key.toLowerCase().includes(\"phlebotomy\")\n ? (\"phlebotomy\" as const)\n : undefined\n const zip = zipMatch?.[1] ?? \"85004\"\n state.hydrateBookingKeysFromAvailability(entry.body, nowMs, zip, modality)\n // Vital echoes the availability request address on book/reschedule. Align the\n // freshly hydrated oracle-key records with the request address embedded in the\n // observation cache key so book/reschedule render the same address as the\n // oracle instead of the hydrate placeholder.\n const requestBody = parseAvailabilityRequestBody(key)\n if (requestBody) alignBookingKeyAddresses(state, entry.body, requestBody, zip, modality)\n }\n }\n\n const labTests: LabTestRecord[] = []\n let cursor: string | null = null\n for (;;) {\n const path =\n cursor === null ? \"/v3/lab_test\" : `/v3/lab_test?next_cursor=${encodeURIComponent(cursor)}`\n const response = await request(source, \"GET\", path)\n if (!response.ok) break\n const payload = asRecord(await readJson(response))\n const data = payload?.data\n if (Array.isArray(data)) {\n for (const entry of data) {\n const test = mapLabTest(entry)\n if (test) labTests.push(test)\n }\n }\n cursor = asString(payload?.next_cursor) ?? null\n if (cursor === null) break\n }\n\n const labsResponse = await request(source, \"GET\", \"/v3/lab_tests/labs\")\n const labsPayload = labsResponse.ok ? await readJson(labsResponse) : []\n const labs = Array.isArray(labsPayload)\n ? labsPayload.filter(\n (entry): entry is Record<string, unknown> =>\n typeof entry === \"object\" && entry !== null && !Array.isArray(entry),\n )\n : []\n\n const expectedResults: Record<string, ExpectedResult[]> = {}\n for (const test of labTests) {\n expectedResults[test.id] = await expectedFromMarkersResponse(source, test)\n }\n\n if (labTests.length > 0 || labs.length > 0) {\n const currentTests = state.listLabTests()\n const currentLabs = state.listLabs()\n const currentExpected = Object.fromEntries(\n currentTests.map((test) => [test.id, state.expectedResultsFor(test.id)]),\n )\n state.replaceCatalog({\n labTests: labTests.length > 0 ? labTests : currentTests,\n labs: labs.length > 0 ? labs : currentLabs,\n expectedResults: Object.keys(expectedResults).length > 0 ? expectedResults : currentExpected,\n })\n }\n\n let users = 0\n let orders = 0\n let appointments = 0\n const pendingOrders: Array<{\n order: OrderRecord\n appointments: AppointmentRecord[]\n /** Position in the oracle's newest-first team-wide list \u2014 the oracle's own tie order. */\n listPosition?: number\n }> = []\n let offset = 0\n const limit = 100\n for (;;) {\n const listResponse = await request(source, \"GET\", `/v2/user?offset=${offset}&limit=${limit}`)\n if (!listResponse.ok) break\n const listPayload = asRecord(await readJson(listResponse))\n const listed = Array.isArray(listPayload?.users) ? listPayload.users : []\n if (listed.length === 0) break\n for (const entry of listed) {\n const listedUser = mapUser(entry)\n if (!listedUser) continue\n const detailResponse = await request(source, \"GET\", `/v2/user/${listedUser.user_id}`)\n const user = detailResponse.ok\n ? (mapUser(await readJson(detailResponse)) ?? listedUser)\n : listedUser\n state.insertUser(user)\n users += 1\n\n const infoResponse = await request(source, \"GET\", `/v2/user/${user.user_id}/info/latest`)\n if (infoResponse.ok) {\n const info = asRecord(await readJson(infoResponse))\n if (info) state.userInfo.insert(user.user_id, info as UserInfoRecord)\n }\n\n let page = 1\n for (;;) {\n const ordersResponse = await request(\n source,\n \"GET\",\n `/v3/orders?user_id=${encodeURIComponent(user.user_id)}&page=${page}&size=100`,\n )\n if (!ordersResponse.ok) break\n const ordersPayload = asRecord(await readJson(ordersResponse))\n const orderEntries = Array.isArray(ordersPayload?.orders)\n ? ordersPayload.orders\n : Array.isArray(ordersPayload?.data)\n ? ordersPayload.data\n : []\n if (orderEntries.length === 0) break\n for (const orderEntry of orderEntries) {\n const summary = asRecord(orderEntry)\n const orderId = asString(summary?.id) ?? asString(summary?.order_id)\n if (!orderId) continue\n const orderResponse = await request(source, \"GET\", `/v3/order/${orderId}`)\n if (!orderResponse.ok) continue\n const order = mapOrder(await readJson(orderResponse))\n if (!order) continue\n const orderAppointments: AppointmentRecord[] = []\n for (const modality of [\"phlebotomy\", \"psc\"] as const) {\n const path =\n modality === \"phlebotomy\"\n ? `/v3/order/${order.id}/phlebotomy/appointment`\n : `/v3/order/${order.id}/psc/appointment`\n const appointmentResponse = await request(source, \"GET\", path)\n if (!appointmentResponse.ok) continue\n const appointment = mapAppointment(\n await readJson(appointmentResponse),\n order.id,\n order.user_id,\n )\n if (!appointment) continue\n orderAppointments.push(appointment)\n }\n pendingOrders.push({ order, appointments: orderAppointments })\n }\n const total = typeof ordersPayload?.total === \"number\" ? ordersPayload.total : undefined\n if (total !== undefined && page * 100 >= total) break\n if (orderEntries.length < 100) break\n page += 1\n }\n }\n offset += listed.length\n if (listed.length < limit) break\n }\n\n // Team-wide order pass: /v2/user can be empty while orphan orders remain\n // (users deleted, orders retained). List payloads are full ClientFacingOrder\n // objects, so we can seed without per-id GETs.\n {\n let page = 1\n for (;;) {\n const ordersResponse = await request(source, \"GET\", `/v3/orders?page=${page}&size=100`)\n if (!ordersResponse.ok) break\n const ordersPayload = asRecord(await readJson(ordersResponse))\n const orderEntries = Array.isArray(ordersPayload?.orders)\n ? ordersPayload.orders\n : Array.isArray(ordersPayload?.data)\n ? ordersPayload.data\n : []\n if (orderEntries.length === 0) break\n let listPosition = (page - 1) * 100\n for (const orderEntry of orderEntries) {\n const order = mapOrder(orderEntry)\n if (!order) continue\n // Do not resurrect users that are absent from /v2/user \u2014 orphan orders\n // keep their user_id but the team user list must match sandbox membership.\n if (!state.users.has(order.user_id) && !state.deletedUsers.has(order.user_id)) {\n state.deletedUsers.insert(order.user_id, { user_id: order.user_id })\n }\n listPosition += 1\n const existing = pendingOrders.find((pending) => pending.order.id === order.id)\n if (existing) {\n // Team-wide list order is the oracle's own tie order \u2014 restamp even for\n // orders first discovered through the per-user pass.\n existing.listPosition = listPosition\n continue\n }\n pendingOrders.push({ order, appointments: [], listPosition })\n }\n const total = typeof ordersPayload?.total === \"number\" ? ordersPayload.total : undefined\n if (total !== undefined && page * 100 >= total) break\n if (orderEntries.length < 100) break\n page += 1\n }\n }\n\n // Insert oldest-first so collection seq matches the oracle's list order: primary key\n // is updated_at asc, ties follow the oracle's newest-first list position (reversed),\n // because the sandbox orders same-instant rows by creation order there too.\n pendingOrders.sort((left, right) => {\n const leftAt = Date.parse(String(left.order.updated_at ?? left.order.created_at ?? \"\")) || 0\n const rightAt = Date.parse(String(right.order.updated_at ?? right.order.created_at ?? \"\")) || 0\n if (leftAt !== rightAt) return leftAt - rightAt\n if (left.listPosition !== undefined && right.listPosition !== undefined) {\n return right.listPosition - left.listPosition\n }\n // Orders discovered only via per-user detail fetches keep id order as a stable fallback.\n return left.order.id.localeCompare(right.order.id)\n })\n for (const pending of pendingOrders) {\n const labTest = pending.order.lab_test\n if (labTest?.id && (labTest.markers?.length ?? 0) === 0) {\n const expected = await expectedFromMarkersResponse(source, labTest)\n pending.order.lab_test = labTest\n if (state.orders.get(pending.order.id)) {\n state.orders.update(pending.order.id, pending.order)\n }\n state.upsertLabTest(labTest, expected)\n }\n if (state.orders.get(pending.order.id)) {\n state.orders.update(pending.order.id, pending.order)\n if (pending.order.lab_test?.id) state.upsertLabTest(pending.order.lab_test)\n continue\n }\n state.insertOrder(pending.order)\n if (pending.order.lab_test?.id) state.upsertLabTest(pending.order.lab_test)\n await ensureUserInfoForOrder(state, source, pending.order)\n orders += 1\n for (const appointment of pending.appointments) {\n if (state.appointments.get(appointment.id)) continue\n state.insertAppointment(appointment)\n appointments += 1\n }\n }\n\n // Refresh panels that still lack markers so create_order matches Vital.\n await ensureLabTests(\n state,\n source,\n state\n .listLabTests()\n .filter((test) => (test.markers?.length ?? 0) === 0)\n .map((test) => test.id),\n )\n\n return {\n users,\n orders,\n appointments,\n catalogTests: state.listLabTests().length,\n labs: state.listLabs().length,\n cacheEntries,\n }\n}\n", "import { HttpError, jsonRes, type OperationContext } from \"@crvouga/mockingbird-service\"\nimport type { JunctionState, UserRecord } from \"./state.js\"\nimport { MOCK_TEAM_ID } from \"./state.js\"\n\nconst jsonBody = (context: OperationContext): Record<string, unknown> => {\n const body = context.body\n const value = body.kind === \"json\" ? body.value : undefined\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new HttpError(422, {\n detail: [\n {\n type: \"model_attributes_type\",\n loc: [\"body\"],\n msg: \"Input should be a valid dictionary or object to extract fields from\",\n input: value,\n },\n ],\n })\n }\n return value as Record<string, unknown>\n}\n\nconst render = (user: UserRecord, rawEnd = false) => ({\n user_id: user.user_id,\n team_id: user.team_id,\n client_user_id: user.client_user_id,\n created_on: user.created_on,\n connected_sources: user.connected_sources,\n fallback_time_zone: user.fallback_time_zone,\n fallback_birth_date: user.fallback_birth_date,\n ingestion_start: user.ingestion_start,\n ingestion_end: rawEnd\n ? user.ingestion_end\n : user.ingestion_start === null\n ? null\n : (user.ingestion_end ?? \"0001-01-01\"),\n})\n\nconst listUsers = (state: JunctionState, offset: number, limit: number) => {\n // Sandbox lists by created_on desc; same-second ties follow creation order\n // (collection newest), not UUID lexicographic order.\n const all = [...state.users.list({ order: \"newest\" })].sort((left, right) => {\n const leftAt = Date.parse(String(left.value.created_on ?? \"\")) || 0\n const rightAt = Date.parse(String(right.value.created_on ?? \"\")) || 0\n if (rightAt !== leftAt) return rightAt - leftAt\n return 0\n })\n const users = all.slice(offset, offset + limit).map((entry) => render(entry.value, true))\n return {\n users,\n total: users.length === 0 ? 0 : all.length,\n offset,\n limit,\n }\n}\n\nconst isValidUuid = (value: string): boolean =>\n /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(value)\n\nfunction notFound(detail: string): never {\n throw new HttpError(404, { detail })\n}\n\nconst queryInt = (context: OperationContext, name: string, fallback: number): number => {\n const raw = context.query[name]\n if (raw === undefined) return fallback\n if (typeof raw !== \"string\" || !/^-?\\d+$/.test(raw))\n throw new HttpError(422, { detail: `${name} must be an integer` })\n return Number(raw)\n}\n\nconst isValidIanaTimezone = (value: string): boolean => {\n try {\n new Intl.DateTimeFormat(\"en-US\", { timeZone: value })\n return true\n } catch {\n return false\n }\n}\n\nconst isValidDate = (value: string): boolean => {\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(value)) return false\n const [year, month, day] = value.split(\"-\").map(Number)\n const y = year ?? 0\n const m = month ?? 0\n const d = day ?? 0\n const date = new Date(Date.UTC(y, m - 1, d))\n return date.getUTCFullYear() === y && date.getUTCMonth() === m - 1 && date.getUTCDate() === d\n}\n\nconst stringError = (path: string, value: unknown) => ({\n type: \"string_type\",\n loc: [\"body\", ...path.split(\".\")],\n msg: \"Input should be a valid string\",\n input: value,\n})\n\nconst missingError = (path: string, input: unknown) => ({\n type: \"missing\",\n loc: [\"body\", ...path.split(\".\")],\n msg: \"Field required\",\n input,\n})\n\nconst dateError = (path: string, value: unknown) => {\n const input = String(value)\n if (input.length <= 7) {\n return {\n type: \"date_from_datetime_parsing\",\n loc: [\"body\", ...path.split(\".\")],\n msg: \"Input should be a valid date or datetime, input is too short\",\n input: value,\n ctx: { error: \"input is too short\" },\n }\n }\n return {\n type: \"date_from_datetime_parsing\",\n loc: [\"body\", ...path.split(\".\")],\n msg: \"Input should be a valid date or datetime, invalid character in year\",\n input: value,\n ctx: { error: \"invalid character in year\" },\n }\n}\n\n/** Pydantic-style email validation mirroring the sandbox's error reasons. */\nconst emailErrorOf = (value: string): { msg: string; reason: string } | undefined => {\n if (!value.includes(\"@\")) {\n return {\n msg: \"value is not a valid email address: An email address must have an @-sign.\",\n reason: \"An email address must have an @-sign.\",\n }\n }\n const [local = \"\", ...domainParts] = value.split(\"@\")\n const domain = domainParts.join(\"@\")\n if (local === \"\") {\n return {\n msg: \"value is not a valid email address: There must be something before the @-sign.\",\n reason: \"There must be something before the @-sign.\",\n }\n }\n if (domain === \"\") {\n return {\n msg: \"value is not a valid email address: There must be something after the @-sign.\",\n reason: \"There must be something after the @-sign.\",\n }\n }\n if (/\\s/.test(local)) {\n return {\n msg: `value is not a valid email address: The email address contains invalid characters before the @-sign: ${describeLocalChar(local)}.`,\n reason: `The email address contains invalid characters before the @-sign: ${describeLocalChar(local)}.`,\n }\n }\n if (domain.includes(\"@\") || /[^a-zA-Z0-9.\\-_]/.test(domain)) {\n return {\n msg: `value is not a valid email address: The part after the @-sign contains invalid characters: '@'.`,\n reason: `The part after the @-sign contains invalid characters: '@'.`,\n }\n }\n if (!domain.includes(\".\")) {\n return {\n msg: \"value is not a valid email address: The part after the @-sign is not valid. It should have a period.\",\n reason: \"The part after the @-sign is not valid. It should have a period.\",\n }\n }\n return undefined\n}\n\nconst describeLocalChar = (local: string): string => {\n for (const character of local) {\n if (/\\s/.test(character)) return character === \" \" ? \"SPACE\" : \"WS\"\n }\n return characterDescription(local)\n}\n\nconst characterDescription = (value: string): string => {\n for (const character of value) {\n if (!/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]/.test(character)) {\n const code = character.codePointAt(0) ?? 0\n if (code > 126) return \"NON printable\"\n return `'${character}'`\n }\n }\n return \"SPACE\"\n}\n\nconst emailValidationError = (value: string) => {\n const error = emailErrorOf(value)\n if (!error) return undefined\n return {\n type: \"value_error\",\n loc: [\"body\", \"email\"],\n msg: error.msg,\n input: value,\n ctx: { reason: error.reason },\n }\n}\n\n/** Pydantic date parsing mirroring the sandbox's `date` field error taxonomy. */\nconst dobValidationError = (value: unknown) => {\n if (typeof value === \"string\") {\n const codePoints = [...value]\n if (codePoints.some((character) => (character.codePointAt(0) ?? 0) > 127)) {\n return {\n type: \"date_from_datetime_parsing\",\n loc: [\"body\", \"dob\"],\n msg: \"Input should be a valid date or datetime, invalid character in year\",\n input: value,\n ctx: { error: \"invalid character in year\" },\n }\n }\n if (/^\\d+$/.test(value)) {\n return {\n type: \"date_from_datetime_inexact\",\n loc: [\"body\", \"dob\"],\n msg: \"Datetimes provided to dates should have zero time - e.g. be exact dates\",\n input: value,\n }\n }\n if (value.length < 10) {\n return {\n type: \"date_from_datetime_parsing\",\n loc: [\"body\", \"dob\"],\n msg: \"Input should be a valid date or datetime, input is too short\",\n input: value,\n ctx: { error: \"input is too short\" },\n }\n }\n const iso = value.match(/^(\\d{4})([-/])(\\d{2}|[^-])\\2(\\d{2}|[^-]*)(.*)$/)\n if (iso === null) {\n // Pydantic/speedate: once four year digits are consumed, a non-`-` next\n // character is reported as a separator error (not an invalid year char).\n if (/^\\d{4}/.test(value)) {\n return {\n type: \"date_from_datetime_parsing\",\n loc: [\"body\", \"dob\"],\n msg: \"Input should be a valid date or datetime, invalid date separator, expected `-`\",\n input: value,\n ctx: { error: \"invalid date separator, expected `-`\" },\n }\n }\n return {\n type: \"date_from_datetime_parsing\",\n loc: [\"body\", \"dob\"],\n msg: \"Input should be a valid date or datetime, invalid character in year\",\n input: value,\n ctx: { error: \"invalid character in year\" },\n }\n }\n const [, year = \"\", separator = \"-\", monthRaw = \"\", dayRaw = \"\", rest = \"\"] = iso\n if (separator !== \"-\") {\n return {\n type: \"date_from_datetime_parsing\",\n loc: [\"body\", \"dob\"],\n msg: \"Input should be a valid date or datetime, invalid date separator, expected `-`\",\n input: value,\n ctx: { error: \"invalid date separator, expected `-`\" },\n }\n }\n if (!/^\\d+$/.test(year ?? \"\")) {\n return {\n type: \"date_from_datetime_parsing\",\n loc: [\"body\", \"dob\"],\n msg: \"Input should be a valid date or datetime, invalid character in year\",\n input: value,\n ctx: { error: \"invalid character in year\" },\n }\n }\n if (!/^\\d+$/.test(monthRaw ?? \"\")) {\n return {\n type: \"date_from_datetime_parsing\",\n loc: [\"body\", \"dob\"],\n msg: \"Input should be a valid date or datetime, invalid character in month\",\n input: value,\n ctx: { error: \"invalid character in month\" },\n }\n }\n if (!/^\\d+$/.test(dayRaw ?? \"\")) {\n return {\n type: \"date_from_datetime_parsing\",\n loc: [\"body\", \"dob\"],\n msg: \"Input should be a valid date or datetime, invalid character in day\",\n input: value,\n ctx: { error: \"invalid character in day\" },\n }\n }\n const month = Number(monthRaw)\n if (month < 1 || month > 12) {\n return {\n type: \"date_from_datetime_parsing\",\n loc: [\"body\", \"dob\"],\n msg: \"Input should be a valid date or datetime, month value is outside expected range of 1-12\",\n input: value,\n ctx: { error: \"month value is outside expected range of 1-12\" },\n }\n }\n const day = Number(dayRaw)\n const yearNumber = Number(year)\n const daysInMonth = new Date(Date.UTC(yearNumber, month, 0)).getUTCDate()\n if (day < 1 || day > daysInMonth) {\n return {\n type: \"date_from_datetime_parsing\",\n loc: [\"body\", \"dob\"],\n msg: \"Input should be a valid date or datetime, day value is outside expected range\",\n input: value,\n ctx: { error: \"day value is outside expected range\" },\n }\n }\n if (rest !== \"\" && !/^T00:00:00(\\.\\d+)?(Z|[+-]\\d{2}:\\d{2})?$/.test(rest)) {\n return {\n type: \"date_from_datetime_inexact\",\n loc: [\"body\", \"dob\"],\n msg: \"Datetimes provided to dates should have zero time - e.g. be exact dates\",\n input: value,\n }\n }\n return undefined\n }\n if (typeof value === \"number\") {\n return {\n type: \"date_from_datetime_inexact\",\n loc: [\"body\", \"dob\"],\n msg: \"Datetimes provided to dates should have zero time - e.g. be exact dates\",\n input: value,\n }\n }\n return {\n type: \"date_type\",\n loc: [\"body\", \"dob\"],\n msg: \"Input should be a valid date\",\n input: value,\n }\n}\n\nconst userInfoValidationErrors = (body: Record<string, unknown>): unknown[] => {\n const errors: unknown[] = []\n const push = (error: unknown) => {\n if (error) errors.push(error)\n }\n\n // Field-by-field, in the sandbox's fixed order; each field emits its missing OR\n // type/value error before moving to the next.\n for (const field of [\"first_name\", \"last_name\"] as const) {\n const value = body[field]\n if (value === undefined) push(missingError(field, body))\n else if (typeof value !== \"string\") push(stringError(field, value))\n }\n\n const email = body.email\n if (email === undefined) push(missingError(\"email\", body))\n else if (typeof email !== \"string\") push(stringError(\"email\", email))\n else push(emailValidationError(email))\n\n const phone = body.phone_number\n if (phone === undefined) push(missingError(\"phone_number\", body))\n else if (phone === null) {\n push({\n type: \"value_error\",\n loc: [\"body\", \"phone_number\"],\n msg: \"Value error, Phone number cannot be None\",\n input: null,\n ctx: { error: {} },\n })\n } else if (typeof phone === \"string\") {\n const digits = phone.replace(/\\D/g, \"\")\n if (digits.length < 10 || !/^[\\d\\s()+-]*$/.test(phone)) {\n push({\n type: \"value_error\",\n loc: [\"body\", \"phone_number\"],\n msg: `Value error, Invalid phone number: ${phone}`,\n input: phone,\n ctx: { error: {} },\n })\n }\n }\n\n const gender = body.gender\n if (gender === undefined) push(missingError(\"gender\", body))\n else if (typeof gender !== \"string\") push(stringError(\"gender\", gender))\n\n if (body.dob === undefined) push(missingError(\"dob\", body))\n else push(dobValidationError(body.dob))\n\n const address = body.address\n if (address === undefined) push(missingError(\"address\", body))\n else if (address === null || typeof address !== \"object\" || Array.isArray(address)) {\n push({\n type: \"model_attributes_type\",\n loc: [\"body\", \"address\"],\n msg: \"Input should be a valid dictionary or object to extract fields from\",\n input: address,\n })\n } else {\n const addressRecord = address as Record<string, unknown>\n for (const field of [\"first_line\", \"country\", \"zip\", \"city\", \"state\"] as const) {\n const value = addressRecord[field]\n if (value === undefined) push(missingError(`address.${field}`, addressRecord))\n else if (typeof value !== \"string\") push(stringError(`address.${field}`, value))\n }\n if (addressRecord.second_line !== undefined && typeof addressRecord.second_line !== \"string\") {\n push(stringError(\"address.second_line\", addressRecord.second_line))\n }\n }\n return errors\n}\n\nexport const userHandlers = (state: JunctionState) => ({\n patch_user_info_v2_user__user_id__info_patch: async (context: OperationContext) => {\n const id = context.params.user_id ?? \"\"\n const body = jsonBody(context)\n const errors = userInfoValidationErrors(body)\n if (errors.length > 0) throw new HttpError(422, { detail: errors })\n if (!state.users.has(id)) notFound(\"User not found\")\n const existing = state.userInfo.get(id) ?? {}\n const rawAddress =\n typeof body.address === \"object\" && body.address !== null && !Array.isArray(body.address)\n ? (body.address as Record<string, unknown>)\n : undefined\n const info = {\n ...existing,\n ...body,\n ...(rawAddress === undefined\n ? {}\n : {\n address: {\n first_line: rawAddress.first_line ?? \"\",\n second_line: typeof rawAddress.second_line === \"string\" ? rawAddress.second_line : \"\",\n country: rawAddress.country ?? \"\",\n zip: rawAddress.zip ?? \"\",\n city: rawAddress.city ?? \"\",\n state: rawAddress.state ?? \"\",\n access_notes:\n typeof rawAddress.access_notes === \"string\" ? rawAddress.access_notes : null,\n },\n }),\n }\n state.userInfo.insert(id, info)\n return jsonRes(200, info)\n },\n\n create_user_v2_user_post: async (context: OperationContext) => {\n const body = jsonBody(context)\n const clientUserId = body.client_user_id\n if (clientUserId === undefined) {\n throw new HttpError(422, {\n detail: [\n {\n type: \"missing\",\n loc: [\"body\", \"client_user_id\"],\n msg: \"Field required\",\n input: body,\n },\n ],\n })\n }\n if (typeof clientUserId !== \"string\") {\n throw new HttpError(422, {\n detail: [\n {\n type: \"string_type\",\n loc: [\"body\", \"client_user_id\"],\n msg: \"Input should be a valid string\",\n input: clientUserId,\n },\n ],\n })\n }\n const existing = state.byClientId.get(clientUserId)\n if (existing) {\n const user = state.users.get(existing.user_id)\n throw new HttpError(400, {\n detail: {\n error_type: \"INVALID_REQUEST\",\n error_message: \"Client user id already exists.\",\n user_id: existing.user_id,\n created_on: user?.created_on ?? state.isoNow(context.now),\n },\n })\n }\n const userId = state.nextUserId()\n const createdOn = state.isoNow(context.now)\n const tz =\n typeof body.fallback_time_zone === \"string\"\n ? { id: body.fallback_time_zone, source_slug: \"manual\", updated_at: createdOn }\n : null\n const user: UserRecord = {\n user_id: userId,\n team_id: MOCK_TEAM_ID,\n client_user_id: clientUserId,\n created_on: createdOn,\n connected_sources: [],\n fallback_time_zone: tz,\n fallback_birth_date: null,\n ingestion_start: null,\n ingestion_end: null,\n }\n state.users.insert(userId, user)\n state.byClientId.insert(clientUserId, { user_id: userId })\n return jsonRes(200, render(user))\n },\n\n get_user_v2_user__user_id__get: async (context: OperationContext) => {\n const id = context.params.user_id ?? \"\"\n if (!isValidUuid(id)) {\n throw new HttpError(422, {\n detail: `Invalid format for parameter user_id: error unmarshaling '${id}' text as *uuid.UUID: invalid UUID length: ${id.length}`,\n })\n }\n const user = state.users.get(id)\n if (user) return jsonRes(200, render(user))\n if (state.deletedUsers.has(id)) {\n throw new HttpError(404, { detail: \"You have scheduled this user for deletion.\" })\n }\n notFound(\"Not found\")\n },\n\n delete_user_v2_user__user_id__delete: async (context: OperationContext) => {\n const id = context.params.user_id ?? \"\"\n const user = state.users.get(id)\n if (!user) {\n if (state.deletedUsers.has(id)) {\n throw new HttpError(404, {\n detail: \"The user has been scheduled for deletion as per your previous request\",\n })\n }\n notFound(\"The user does not or no longer exists in this team\")\n }\n state.users.delete(id)\n state.byClientId.delete(user.client_user_id)\n state.deletedUsers.insert(id, { user_id: id })\n return jsonRes(200, { success: true })\n },\n\n get_user_by_client_user_id_v2_user_resolve__client_user_id__get: async (\n context: OperationContext,\n ) => {\n const clientUserId = context.params.client_user_id ?? \"\"\n const binding = state.byClientId.get(clientUserId)\n if (!binding) notFound(\"User not found\")\n const user = state.users.get(binding.user_id)\n if (!user) notFound(\"User not found\")\n return jsonRes(200, render(user))\n },\n\n patch_user_v2_user__user_id__patch: async (context: OperationContext) => {\n const id = context.params.user_id ?? \"\"\n const user = state.users.get(id)\n if (!user) {\n if (state.deletedUsers.has(id)) {\n throw new HttpError(404, {\n detail: \"The user has been scheduled for deletion as per your previous request\",\n })\n }\n notFound(\"The user does not or no longer exists in this team\")\n }\n const body = jsonBody(context)\n const now = state.isoNow(context.now)\n const patchable = [\n \"client_user_id\",\n \"fallback_time_zone\",\n \"fallback_birth_date\",\n \"ingestion_start\",\n \"ingestion_end\",\n ]\n if (!patchable.some((key) => body[key] !== undefined)) {\n throw new HttpError(400, { detail: \"Nothing to patch\" })\n }\n const validationError = (): unknown => {\n const tz = body.fallback_time_zone\n if (tz !== undefined && tz !== null) {\n if (typeof tz !== \"string\") return stringError(\"fallback_time_zone\", tz)\n if (!isValidIanaTimezone(tz)) {\n return {\n type: \"value_error\",\n loc: [\"body\", \"fallback_time_zone\"],\n msg: `Value error, Invalid IANA time zone: ${tz}`,\n input: tz,\n ctx: { error: {} },\n }\n }\n }\n const birth = body.fallback_birth_date\n if (birth !== undefined && birth !== null) {\n if (typeof birth !== \"string\") return stringError(\"fallback_birth_date\", birth)\n if (!isValidDate(birth)) return dateError(\"fallback_birth_date\", birth)\n }\n const start = body.ingestion_start\n if (start !== undefined && start !== null) {\n if (typeof start !== \"string\") return stringError(\"ingestion_start\", start)\n if (!isValidDate(start)) return dateError(\"ingestion_start\", start)\n }\n const end = body.ingestion_end\n if (end !== undefined && end !== null) {\n if (typeof end !== \"string\") return stringError(\"ingestion_end\", end)\n if (!isValidDate(end)) return dateError(\"ingestion_end\", end)\n }\n const cid = body.client_user_id\n if (cid !== undefined) {\n if (cid === null) {\n return {\n type: \"value_error\",\n loc: [\"body\"],\n msg: \"Value error, client_user_id is not a field that can be reset to null.\",\n input: body,\n ctx: { error: {} },\n }\n }\n if (typeof cid !== \"string\") return stringError(\"client_user_id\", cid)\n }\n return undefined\n }\n const error = validationError()\n if (error) throw new HttpError(422, { detail: [error] })\n if (body.client_user_id !== undefined) {\n const raw = body.client_user_id as string\n const taken = state.byClientId.get(raw)\n if (taken && taken.user_id !== id)\n throw new HttpError(409, { detail: \"Client user id already exists\" })\n state.byClientId.delete(user.client_user_id)\n state.byClientId.insert(raw, { user_id: id })\n user.client_user_id = raw\n }\n if (body.fallback_time_zone !== undefined) {\n const raw = body.fallback_time_zone\n user.fallback_time_zone =\n typeof raw === \"string\" ? { id: raw, source_slug: \"manual\", updated_at: now } : null\n }\n if (body.fallback_birth_date !== undefined) {\n const raw = body.fallback_birth_date\n user.fallback_birth_date =\n typeof raw === \"string\" ? { value: raw, source_slug: \"manual\", updated_at: now } : null\n }\n const startProvided = body.ingestion_start !== undefined\n const endProvided = body.ingestion_end !== undefined\n if (startProvided) {\n const raw = body.ingestion_start\n user.ingestion_start = typeof raw === \"string\" ? raw : null\n }\n if (endProvided) {\n const rawEnd = body.ingestion_end\n user.ingestion_end = typeof rawEnd === \"string\" ? rawEnd : null\n }\n state.users.update(id, user)\n return new Response(null, { status: 204 })\n },\n\n get_latest_user_info_user_v2_user__user_id__info_latest_get: async (\n context: OperationContext,\n ) => {\n const id = context.params.user_id ?? \"\"\n if (!isValidUuid(id)) {\n throw new HttpError(422, {\n detail: `Invalid format for parameter user_id: error unmarshaling '${id}' text as *uuid.UUID: invalid UUID length: ${id.length}`,\n })\n }\n if (!state.users.has(id) && !state.deletedUsers.has(id)) notFound(\"User not found\")\n const info = state.userInfo.get(id)\n if (!info) notFound(\"User demographics data not found\")\n return jsonRes(200, info)\n },\n\n get_teams_users_v2_user_get: async (context: OperationContext) => {\n const offset = queryInt(context, \"offset\", 0)\n const limit = queryInt(context, \"limit\", 100)\n if (offset < 0 || limit < 0 || limit > 500) {\n throw new HttpError(500, \"Internal Server Error\", { \"content-type\": \"text/plain\" })\n }\n return jsonRes(200, listUsers(state, offset, limit))\n },\n})\n", "import {\n type AdminRequest,\n type AdminRoutes,\n type FaultRule,\n jsonRes,\n type ServiceRuntime,\n} from \"@crvouga/mockingbird-service\"\nimport type { JunctionAPI } from \"./index.js\"\nimport type { LabAccountInput } from \"./lab-accounts.js\"\nimport type { GeoMode, ResultFixture } from \"./state.js\"\nimport type { WebhookDispatcher } from \"./webhooks.js\"\n\n/**\n * Every order status the contract defines, by collection method (from the vendored\n * OpenAPI enum). An admin transition may only target a status real Junction can emit.\n */\nexport const ORDER_STATUSES_BY_METHOD: Readonly<Record<string, readonly string[]>> = {\n at_home_phlebotomy: [\n \"received.ordered\",\n \"received.requisition_created\",\n \"received.requisition_bypassed\",\n \"collecting_sample.appointment_pending\",\n \"collecting_sample.appointment_scheduled\",\n \"collecting_sample.appointment_cancelled\",\n \"collecting_sample.draw_completed\",\n \"sample_with_lab.partial_results\",\n \"completed.completed\",\n \"completed.corrected\",\n \"cancelled.cancelled\",\n \"failed.sample_error\",\n ],\n on_site_collection: [\n \"received.ordered\",\n \"received.requisition_created\",\n \"received.requisition_bypassed\",\n \"sample_with_lab.draw_completed\",\n \"sample_with_lab.partial_results\",\n \"completed.completed\",\n \"completed.corrected\",\n \"cancelled.cancelled\",\n \"failed.sample_error\",\n ],\n testkit: [\n \"received.ordered\",\n \"received.awaiting_registration\",\n \"received.registered\",\n \"received.requisition_created\",\n \"received.requisition_bypassed\",\n \"collecting_sample.transit_customer\",\n \"collecting_sample.out_for_delivery\",\n \"collecting_sample.with_customer\",\n \"collecting_sample.transit_lab\",\n \"collecting_sample.problem_in_transit_customer\",\n \"collecting_sample.problem_in_transit_lab\",\n \"sample_with_lab.delivered_to_lab\",\n \"sample_with_lab.lab_processing_blocked\",\n \"completed.completed\",\n \"completed.corrected\",\n \"cancelled.cancelled\",\n \"cancelled.do_not_process\",\n \"failed.sample_error\",\n \"failed.failure_to_deliver_to_customer\",\n \"failed.failure_to_deliver_to_lab\",\n \"failed.lost\",\n ],\n walk_in_test: [\n \"received.ordered\",\n \"received.requisition_created\",\n \"received.requisition_bypassed\",\n \"collecting_sample.appointment_pending\",\n \"collecting_sample.appointment_scheduled\",\n \"collecting_sample.appointment_cancelled\",\n \"collecting_sample.redraw_available\",\n \"sample_with_lab.partial_results\",\n \"completed.completed\",\n \"completed.corrected\",\n \"cancelled.cancelled\",\n \"failed.sample_error\",\n ],\n}\n\n/**\n * Friendly transition targets, per method, mapped onto the contract's own statuses.\n * A name is absent for a method when no real status means it \u2014 walk-in tests have no\n * draw event, so `collected` is refused there rather than approximated.\n */\nexport const TRANSITION_ALIASES: Readonly<Record<string, Readonly<Record<string, string>>>> = {\n at_home_phlebotomy: {\n requisition_created: \"received.requisition_created\",\n scheduled: \"collecting_sample.appointment_scheduled\",\n collected: \"collecting_sample.draw_completed\",\n partial_results: \"sample_with_lab.partial_results\",\n completed: \"completed.completed\",\n corrected: \"completed.corrected\",\n cancelled: \"cancelled.cancelled\",\n failed: \"failed.sample_error\",\n },\n on_site_collection: {\n requisition_created: \"received.requisition_created\",\n collected: \"sample_with_lab.draw_completed\",\n at_lab: \"sample_with_lab.draw_completed\",\n partial_results: \"sample_with_lab.partial_results\",\n completed: \"completed.completed\",\n corrected: \"completed.corrected\",\n cancelled: \"cancelled.cancelled\",\n failed: \"failed.sample_error\",\n },\n testkit: {\n requisition_created: \"received.requisition_created\",\n shipped: \"collecting_sample.transit_customer\",\n delivered: \"collecting_sample.with_customer\",\n collected: \"collecting_sample.transit_lab\",\n at_lab: \"sample_with_lab.delivered_to_lab\",\n completed: \"completed.completed\",\n corrected: \"completed.corrected\",\n cancelled: \"cancelled.cancelled\",\n failed: \"failed.sample_error\",\n },\n walk_in_test: {\n requisition_created: \"received.requisition_created\",\n scheduled: \"collecting_sample.appointment_scheduled\",\n partial_results: \"sample_with_lab.partial_results\",\n completed: \"completed.completed\",\n corrected: \"completed.corrected\",\n cancelled: \"cancelled.cancelled\",\n failed: \"failed.sample_error\",\n },\n}\n\n/**\n * Named results, as the flags `simulate_order` accepts. They steer the generator, so\n * the payload keeps Junction's exact shape; `PUT /__admin/results/{order}` installs an\n * exact payload instead.\n */\nexport const RESULT_FIXTURES: Readonly<Record<string, Record<string, unknown>>> = {\n normal: { interpretation: \"normal\" },\n abnormal: { interpretation: \"abnormal\" },\n critical: { interpretation: \"critical\" },\n missing_results: { interpretation: \"normal\", has_missing_results: true },\n}\n\n/**\n * Junction failure modes a suite can switch on by name. `sandbox_user_quota` reproduces\n * the shared-sandbox error byte for byte (message as observed from a real sandbox team);\n * the others are shape-plausible, not verified against Junction.\n */\nexport const FAULT_PRESETS: Readonly<Record<string, Omit<FaultRule, \"id\">>> = {\n sandbox_user_quota: {\n operationId: \"create_user_v2_user_post\",\n status: 400,\n body: {\n detail: {\n error_type: \"INVALID_REQUEST\",\n error_message: \"You have reached the maximum of 50 Sandbox users\",\n },\n },\n },\n rate_limited: {\n status: 429,\n body: { detail: \"Too Many Requests\" },\n headers: { \"retry-after\": \"1\" },\n },\n server_error: { status: 500, body: { detail: \"Internal Server Error\" } },\n bad_gateway: { status: 502, body: { detail: \"Bad Gateway\" } },\n unavailable: { status: 503, body: { detail: \"Service Unavailable\" } },\n}\n\nconst methodOf = (order: { lab_test: { method?: unknown }; details?: { type?: unknown } }) =>\n typeof order.lab_test.method === \"string\" && order.lab_test.method !== \"\"\n ? order.lab_test.method\n : typeof order.details?.type === \"string\" && order.details.type !== \"\"\n ? order.details.type\n : \"at_home_phlebotomy\"\n\n/** Resolve a target (`completed`, `completed.completed`, or a full status) for a method. */\nexport const resolveTransition = (\n method: string,\n target: string,\n): { status: string } | { error: string } => {\n const allowed = ORDER_STATUSES_BY_METHOD[method]\n if (!allowed) return { error: `unknown collection method ${method}` }\n const alias = TRANSITION_ALIASES[method]?.[target]\n const short = alias ?? (target.split(\".\").length === 3 ? null : target)\n if (short !== null && allowed.includes(short)) {\n const [phase, event] = short.split(\".\")\n return { status: `${phase}.${method}.${event}` }\n }\n if (target.split(\".\").length === 3) {\n const [phase, targetMethod, event] = target.split(\".\")\n if (targetMethod === method && allowed.includes(`${phase}.${event}`)) return { status: target }\n }\n const names = Object.keys(TRANSITION_ALIASES[method] ?? {})\n return {\n error: `${JSON.stringify(target)} is not a ${method} status. Use one of: ${names.join(\", \")}, or a full status such as ${allowed\n .slice(0, 2)\n .map((s) => `${s.split(\".\")[0]}.${method}.${s.split(\".\")[1]}`)\n .join(\", \")}`,\n }\n}\n\nconst adminError = (status: number, message: string) =>\n jsonRes(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\nexport type JunctionAdminOptions = {\n webhooks: WebhookDispatcher | undefined\n}\n\n/** Junction's admin routes, served under `/__admin` next to the shared ones. */\nexport const junctionAdminRoutes =\n (options: JunctionAdminOptions) =>\n (runtime: ServiceRuntime<JunctionAPI>): AdminRoutes => {\n const api = (request: AdminRequest) => runtime.instance(request.namespace)\n return {\n \"GET /orders\": (request) =>\n jsonRes(200, {\n orders: api(request)\n .orders()\n .map((order) => ({\n id: order.id,\n user_id: order.user_id,\n method: methodOf(order),\n status: order.last_event.status,\n updated_at: order.updated_at,\n })),\n }),\n\n \"POST /orders/:id/transition\": (request) => {\n const body = isRecord(request.body) ? request.body : {}\n const order = api(request).order(request.params.id as string)\n if (!order) return adminError(404, `no order ${request.params.id} in ${request.namespace}`)\n if (typeof body.to !== \"string\") {\n return adminError(400, 'body needs \"to\": a status like \"completed\" or \"at_lab\"')\n }\n const method = methodOf(order)\n const resolved = resolveTransition(method, body.to)\n if (\"error\" in resolved) return adminError(400, resolved.error)\n let flags = isRecord(body.flags) ? body.flags : null\n if (typeof body.result === \"string\") {\n const named = RESULT_FIXTURES[body.result]\n if (!named) {\n return adminError(\n 400,\n `no result fixture ${body.result}; one of ${Object.keys(RESULT_FIXTURES).join(\", \")}`,\n )\n }\n flags = { ...named, ...flags }\n }\n const updated = api(request).transitionOrder(order.id, resolved.status, {\n now: runtime.clock.now,\n flags,\n })\n return jsonRes(200, {\n id: order.id,\n status: updated?.last_event.status,\n events: updated?.events,\n })\n },\n\n \"GET /result-fixtures\": () => jsonRes(200, { fixtures: RESULT_FIXTURES }),\n \"GET /results/:id\": (request) => {\n const fixture = api(request).resultFixture(request.params.id as string)\n return fixture ? jsonRes(200, fixture) : adminError(404, \"no result fixture for that order\")\n },\n \"PUT /results/:id\": (request) => {\n if (!isRecord(request.body)) return adminError(400, \"expected a result fixture object\")\n const fixture = { name: \"custom\", ...request.body } as ResultFixture\n if (fixture.results !== undefined && !Array.isArray(fixture.results)) {\n return adminError(400, \"results must be an array of result lines\")\n }\n return api(request).installResultFixture(request.params.id as string, fixture)\n ? jsonRes(200, fixture)\n : adminError(404, `no order ${request.params.id} in ${request.namespace}`)\n },\n\n \"GET /lab-accounts\": (request) => jsonRes(200, { data: api(request).labAccounts() }),\n \"PUT /lab-accounts\": (request) => {\n const body = isRecord(request.body) ? request.body : {}\n if (body.accounts !== null && !Array.isArray(body.accounts)) {\n return adminError(400, 'body needs \"accounts\": an array, or null to restore the default')\n }\n try {\n const accounts = body.accounts === null ? undefined : (body.accounts as LabAccountInput[])\n return jsonRes(200, { data: api(request).configureLabAccounts(accounts) })\n } catch (error) {\n return adminError(400, error instanceof Error ? error.message : String(error))\n }\n },\n\n \"GET /corpus\": (request) =>\n jsonRes(200, {\n corpus: api(request).corpusInfo() ?? null,\n geo: api(request).geoMode,\n }),\n \"PUT /geo\": (request) => {\n const mode = isRecord(request.body) ? request.body.mode : undefined\n if (mode !== \"corpus\" && mode !== \"synthetic\") {\n return adminError(400, 'body needs \"mode\": \"corpus\" or \"synthetic\"')\n }\n api(request).geoMode = mode as GeoMode\n return jsonRes(200, { geo: mode })\n },\n\n \"GET /webhooks/events\": (request) => jsonRes(200, { events: api(request).webhookEvents() }),\n \"GET /webhooks\": (request) =>\n options.webhooks\n ? jsonRes(200, { deliveries: options.webhooks.deliveries(request.namespace) })\n : adminError(\n 409,\n \"webhook delivery is off; serve with --webhook-url and --webhook-secret\",\n ),\n \"POST /webhooks/:id/replay\": async (request) => {\n if (!options.webhooks) return adminError(409, \"webhook delivery is off\")\n const delivery = await options.webhooks.replay(request.params.id as string)\n return delivery\n ? jsonRes(200, delivery)\n : adminError(404, `no message ${request.params.id}`)\n },\n \"POST /webhooks/flush\": async () => {\n if (!options.webhooks) return adminError(409, \"webhook delivery is off\")\n await options.webhooks.flush()\n return jsonRes(200, { status: \"ok\" })\n },\n\n \"GET /faults/presets\": () => jsonRes(200, { presets: FAULT_PRESETS }),\n \"POST /faults/presets/:name\": (request) => {\n const preset = FAULT_PRESETS[request.params.name as string]\n if (!preset) {\n return adminError(\n 404,\n `no preset ${request.params.name}; one of ${Object.keys(FAULT_PRESETS).join(\", \")}`,\n )\n }\n const overrides = isRecord(request.body) ? request.body : {}\n const rule = runtime.faults.add({\n namespace: request.namespace,\n ...preset,\n ...overrides,\n id: typeof overrides.id === \"string\" ? overrides.id : (request.params.name as string),\n } as FaultRule)\n return jsonRes(201, rule)\n },\n }\n }\n", "/** High-signal ZIPs for availability prefetch (full routing corpus still used for area/psc). */\nexport const PSC_AVAILABILITY_ZIPS = [\n \"85004\",\n \"85234\",\n \"11050\",\n \"10006\",\n \"90012\",\n \"96101\",\n \"92101\",\n \"60601\",\n \"33130\",\n \"98104\",\n \"75034\",\n \"07030\",\n] as const\n\n/**\n * Phlebotomy availability is only served for a narrow Vital sandbox set.\n * Probed: 85004 works; broader scheduling zips often 400. Keep prefetch/reshape sealed.\n */\nexport const PHLEBOTOMY_AVAILABILITY_ZIPS = [\"85004\"] as const\n\n/** City/state/first_line seals so availability cache keys match Vital + prefetch. */\nexport const ZIP_ADDRESSES: Readonly<\n Record<string, { first_line: string; city: string; state: string }>\n> = {\n \"85004\": { first_line: \"1 N Central Ave\", city: \"Phoenix\", state: \"AZ\" },\n \"85234\": { first_line: \"1 Main St\", city: \"Gilbert\", state: \"AZ\" },\n \"11050\": { first_line: \"1 Main St\", city: \"Port Washington\", state: \"NY\" },\n \"10006\": { first_line: \"1 Main St\", city: \"New York\", state: \"NY\" },\n \"90012\": { first_line: \"200 N Spring St\", city: \"Los Angeles\", state: \"CA\" },\n \"96101\": { first_line: \"1 Main St\", city: \"Alturas\", state: \"CA\" },\n \"92101\": { first_line: \"1 Main St\", city: \"San Diego\", state: \"CA\" },\n \"60601\": { first_line: \"121 N LaSalle St\", city: \"Chicago\", state: \"IL\" },\n \"33130\": { first_line: \"3500 Pan American Dr\", city: \"Miami\", state: \"FL\" },\n \"98104\": { first_line: \"1 Main St\", city: \"Seattle\", state: \"WA\" },\n \"75034\": { first_line: \"1 Main St\", city: \"Frisco\", state: \"TX\" },\n \"07030\": { first_line: \"1 Main St\", city: \"Hoboken\", state: \"NJ\" },\n}\n\nexport const availabilityAddressForZip = (zip: string) => {\n const known = ZIP_ADDRESSES[zip]\n return {\n first_line: known?.first_line ?? \"1 Main St\",\n second_line: null as string | null,\n city: known?.city ?? \"Phoenix\",\n state: known?.state ?? \"AZ\",\n zip_code: zip,\n unit: null as string | null,\n }\n}\n\n/**\n * Curated real ZIPs used as this package's parity coverage corpus (one per US state plus DC,\n * plus scheduling pins). Prefetched into the observation cache so area/PSC parity is sealed\n * for those geos.\n */\nexport const COVERAGE_ZIPS = [\n \"02108\",\n \"02903\",\n \"03101\",\n \"04101\",\n \"05401\",\n \"06103\",\n \"07030\",\n \"11050\",\n \"17316\",\n \"19107\",\n \"19801\",\n \"20001\",\n \"21201\",\n \"23219\",\n \"25301\",\n \"28202\",\n \"29201\",\n \"30303\",\n \"33130\",\n \"35203\",\n \"37219\",\n \"39201\",\n \"40202\",\n \"43215\",\n \"46204\",\n \"47630\",\n \"48226\",\n \"50309\",\n \"53202\",\n \"54977\",\n \"55415\",\n \"57104\",\n \"58102\",\n \"59101\",\n \"60601\",\n \"64106\",\n \"67202\",\n \"68102\",\n \"70112\",\n \"72201\",\n \"73102\",\n \"75034\",\n \"77002\",\n \"80202\",\n \"82001\",\n \"83702\",\n \"84111\",\n \"85004\",\n \"85234\",\n \"87102\",\n \"89101\",\n \"90012\",\n \"96101\",\n \"96813\",\n \"97204\",\n \"98104\",\n \"99501\",\n] as const\n\n/** Lab ids exercised by walk-in / PSC parity flows (quest, labcorp, bioreference, sonora). */\nexport const PSC_LAB_IDS = [4, 6, 13, 25] as const\n\n/** Sealed patient + address shapes for order parity (avoids junk 422 divergence). */\nexport const COVERAGE_ORDER_ADDRESSES = [\n {\n first_line: \"1 N Central Ave\",\n city: \"Phoenix\",\n state: \"AZ\",\n zip: \"85004\",\n country: \"US\",\n },\n {\n first_line: \"200 N Spring St\",\n city: \"Los Angeles\",\n state: \"CA\",\n zip: \"90012\",\n country: \"US\",\n },\n {\n first_line: \"121 N LaSalle St\",\n city: \"Chicago\",\n state: \"IL\",\n zip: \"60601\",\n country: \"US\",\n },\n {\n first_line: \"1 Main St\",\n city: \"Port Washington\",\n state: \"NY\",\n zip: \"11050\",\n country: \"US\",\n },\n {\n first_line: \"3500 Pan American Dr\",\n city: \"Miami\",\n state: \"FL\",\n zip: \"33130\",\n country: \"US\",\n },\n {\n first_line: \"1437 Bannock St\",\n city: \"Denver\",\n state: \"CO\",\n zip: \"80202\",\n country: \"US\",\n },\n] as const\n\nexport const COVERAGE_PATIENT = {\n first_name: \"Ada\",\n last_name: \"Lovelace\",\n dob: \"1990-01-01\",\n gender: \"female\",\n phone_number: \"+14155551234\",\n email: \"ada.lovelace@example.com\",\n} as const\n", "import type { ExploreRng, ExploreState, LogicalCommand } from \"@crvouga/mockingbird-commands\"\nimport {\n availabilityAddressForZip,\n COVERAGE_ORDER_ADDRESSES,\n COVERAGE_PATIENT,\n COVERAGE_ZIPS,\n PHLEBOTOMY_AVAILABILITY_ZIPS,\n PSC_AVAILABILITY_ZIPS,\n PSC_LAB_IDS,\n} from \"./coverage-corpus.js\"\nimport { CANCELLATION_REASONS, PSC_CANCELLATION_REASONS } from \"./scheduling.js\"\n\nconst GEO_AREA = \"get_area_info_v3_order_area_info_get\"\nconst GEO_PSC = \"get_psc_info_v3_order_psc_info_get\"\nconst AVAIL_PHLEB =\n \"get_phlebotomy_appointment_availability_v3_order_phlebotomy_appointment_availability_post\"\nconst AVAIL_PSC = \"get_psc_appointment_availability_v3_order_psc_appointment_availability_post\"\n\n/** Stable address fields so availability observation-cache keys match prefetch (85004). */\nexport const AVAILABILITY_ADDRESS = {\n first_line: \"1 N Central Ave\",\n second_line: null as string | null,\n city: \"Phoenix\",\n state: \"AZ\",\n unit: null as string | null,\n} as const\n\n/** Far-future start date so slots are always generated relative to frozen test clocks. */\nexport const AVAILABILITY_START_DATE = \"2099-06-15\"\n\nconst pickZip = (rng: ExploreRng, zips: readonly string[]) =>\n zips[rng.nextInt(Math.max(0, zips.length - 1))] ?? zips[0] ?? \"85004\"\n\nconst pickLabId = (rng: ExploreRng, labs: readonly number[]) =>\n labs[rng.nextInt(Math.max(0, labs.length - 1))] ?? labs[0] ?? 4\n\nconst availabilityBody = (zip: string) => availabilityAddressForZip(zip)\n\n/**\n * Pin geo / availability params onto the coverage corpus so observation-cache hits stay\n * sealed during seedParity compare walks.\n */\nexport const reshapeCoverageGeoCommand = (\n command: LogicalCommand,\n _state: ExploreState,\n rng: ExploreRng,\n options?: {\n zips?: readonly string[]\n schedulingZips?: readonly string[]\n phlebotomyZips?: readonly string[]\n labIds?: readonly number[]\n },\n): LogicalCommand => {\n const zips = options?.zips ?? COVERAGE_ZIPS\n const schedulingZips = options?.schedulingZips ?? PSC_AVAILABILITY_ZIPS\n const phlebotomyZips = options?.phlebotomyZips ?? PHLEBOTOMY_AVAILABILITY_ZIPS\n const labIds = options?.labIds ?? PSC_LAB_IDS\n const id = command.operationId\n\n if (id === \"create_order_v3_order_post\") {\n const address =\n COVERAGE_ORDER_ADDRESSES[rng.nextInt(COVERAGE_ORDER_ADDRESSES.length - 1)] ??\n COVERAGE_ORDER_ADDRESSES[0]\n const raw =\n typeof command.body === \"object\" && command.body !== null && !Array.isArray(command.body)\n ? (command.body as Record<string, unknown>)\n : {}\n const rawOrderSet =\n typeof raw.order_set === \"object\" && raw.order_set !== null && !Array.isArray(raw.order_set)\n ? (raw.order_set as Record<string, unknown>)\n : {}\n const rawIds = Array.isArray(rawOrderSet.lab_test_ids) ? rawOrderSet.lab_test_ids : []\n const labTestId =\n rawIds.find(\n (entry) =>\n (typeof entry === \"string\" && entry.length > 0) ||\n (typeof entry === \"object\" &&\n entry !== null &&\n !Array.isArray(entry) &&\n (entry as Record<string, unknown>).$mockingbird === \"ref\"),\n ) ??\n (typeof raw.lab_test_id === \"string\" ||\n (typeof raw.lab_test_id === \"object\" &&\n raw.lab_test_id !== null &&\n !Array.isArray(raw.lab_test_id) &&\n (raw.lab_test_id as Record<string, unknown>).$mockingbird === \"ref\")\n ? raw.lab_test_id\n : undefined)\n // Junction and the mock default collection_method to the panel's native method.\n // Random mismatches force sandbox auto_generated lab_tests whose UUIDs Vital\n // allocates opaquely; keep a low rate so we still exercise that path after seed.\n const methods = [\"at_home_phlebotomy\", \"walk_in_test\"] as const\n const forceMismatch = rng.next() < 0.12\n const body: Record<string, unknown> = {\n user_id: raw.user_id,\n patient_details: { ...COVERAGE_PATIENT },\n patient_address: {\n receiver_name: \"Ada Lovelace\",\n first_line: address?.first_line,\n city: address?.city,\n state: address?.state,\n zip: address?.zip,\n country: address?.country,\n phone_number: COVERAGE_PATIENT.phone_number,\n },\n order_set: labTestId === undefined ? { lab_test_ids: [] } : { lab_test_ids: [labTestId] },\n clinical_notes: null,\n passthrough: null,\n aoe_answers: null,\n lab_account_id: null,\n }\n if (forceMismatch) {\n body.collection_method = methods[rng.nextInt(methods.length - 1)] ?? \"at_home_phlebotomy\"\n }\n return {\n ...command,\n body,\n mediaType: command.mediaType ?? \"application/json\",\n invalid: undefined,\n }\n }\n if (id === \"get_teams_users_v2_user_get\") {\n // Team user lists are newest-first with same-second ties; across seed + lockstep\n // creates the 2nd+ slots are still racy. Parity only needs membership/total \u2014\n // pin limit=1 so we compare the newest user + totals without slot races.\n const raw =\n typeof command.parameters === \"object\" && command.parameters !== null\n ? (command.parameters as Record<string, unknown>)\n : {}\n const offsetRaw = raw.offset\n const offset =\n typeof offsetRaw === \"string\" && /^-?\\d+$/.test(offsetRaw) ? Number(offsetRaw) : 0\n return {\n ...command,\n parameters: {\n offset: String(Math.max(0, offset)),\n limit: \"1\",\n },\n invalid: undefined,\n }\n }\n if (id === GEO_AREA) {\n return {\n ...command,\n parameters: { zip_code: pickZip(rng, zips) },\n }\n }\n if (id === GEO_PSC) {\n return {\n ...command,\n parameters: {\n zip_code: pickZip(rng, zips),\n lab_id: String(pickLabId(rng, labIds)),\n },\n }\n }\n if (id === AVAIL_PHLEB) {\n const zip = pickZip(rng, phlebotomyZips)\n return {\n ...command,\n parameters: {\n start_date: AVAILABILITY_START_DATE,\n },\n body: availabilityBody(zip),\n mediaType: command.mediaType ?? \"application/json\",\n invalid: undefined,\n }\n }\n if (id === AVAIL_PSC) {\n const zip = pickZip(rng, schedulingZips)\n return {\n ...command,\n parameters: {\n lab: \"quest\",\n start_date: AVAILABILITY_START_DATE,\n },\n body: availabilityBody(zip),\n mediaType: command.mediaType ?? \"application/json\",\n invalid: undefined,\n }\n }\n if (id === \"simulate_order_v3_order__order_id__test_post\") {\n const statuses = [\n \"received.at_home_phlebotomy.ordered\",\n \"collecting_sample.at_home_phlebotomy.appointment_scheduled\",\n \"sample_with_lab.at_home_phlebotomy.partial_results\",\n \"completed.at_home_phlebotomy.completed\",\n \"received.walk_in_test.ordered\",\n \"collecting_sample.walk_in_test.appointment_scheduled\",\n \"completed.walk_in_test.completed\",\n ] as const\n return {\n ...command,\n parameters: {\n order_id: command.parameters?.order_id,\n final_status: statuses[rng.nextInt(statuses.length - 1)] ?? statuses[0],\n },\n body: {},\n mediaType: \"application/json\",\n invalid: undefined,\n }\n }\n if (\n id === \"cancel_phlebotomy_appointment_v3_order__order_id__phlebotomy_appointment_cancel_patch\"\n ) {\n const reason =\n CANCELLATION_REASONS.find((entry) => entry.name !== \"Other\") ?? CANCELLATION_REASONS[0]\n return {\n ...command,\n body: {\n cancellation_reason_id: reason?.id ?? \"5c0257ef-6fea-4a22-b20a-3ddab573d5c9\",\n notes: null,\n },\n mediaType: command.mediaType ?? \"application/json\",\n invalid: undefined,\n }\n }\n if (id === \"cancel_psc_appointment_v3_order__order_id__psc_appointment_cancel_patch\") {\n const reason = PSC_CANCELLATION_REASONS[0]\n return {\n ...command,\n body: {\n cancellationReasonId: reason?.id ?? \"5c0257ef-6fea-4a22-b20a-3ddab573d5c9\",\n note: null,\n },\n mediaType: command.mediaType ?? \"application/json\",\n invalid: undefined,\n }\n }\n return command\n}\n", "import type { SeedCacheEntry } from \"@crvouga/mockingbird-parity\"\nimport {\n availabilityAddressForZip,\n COVERAGE_ZIPS,\n PHLEBOTOMY_AVAILABILITY_ZIPS,\n PSC_AVAILABILITY_ZIPS,\n PSC_LAB_IDS,\n} from \"./coverage-corpus.js\"\nimport { AVAILABILITY_START_DATE } from \"./reshape.js\"\nimport { observationCacheKey } from \"./state.js\"\n\nexport type PrefetchTarget = {\n baseUrl: string\n fetch: (request: Request) => Promise<Response>\n headers: () => Promise<Record<string, string>> | Record<string, string>\n}\n\nexport const recordObservation = async (\n target: PrefetchTarget,\n method: string,\n pathAndQuery: string,\n getCache: Map<string, SeedCacheEntry>,\n body?: unknown,\n): Promise<unknown> => {\n const headers: Record<string, string> = {\n ...(await target.headers()),\n accept: \"application/json\",\n }\n if (body !== undefined) headers[\"content-type\"] = \"application/json\"\n const url = `${target.baseUrl}${pathAndQuery}`\n const response = await target.fetch(\n new Request(url, {\n method,\n headers,\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n }),\n )\n const text = await response.text()\n let parsed: unknown = text\n try {\n parsed = text === \"\" ? undefined : (JSON.parse(text) as unknown)\n } catch {\n parsed = text\n }\n const headerRecord: Record<string, string> = {}\n response.headers.forEach((value, name) => {\n headerRecord[name.toLowerCase()] = value\n })\n const cacheKey = observationCacheKey(url, method, body)\n // Seal-once: a walk-local warmup seal for this request is authoritative \u2014 prefetch\n // must not clobber it, because the oracle rotates booking_key per serve and only the\n // sealed observation's keys were paired into the walk's resource table.\n if (getCache.has(cacheKey)) return getCache.get(cacheKey)?.body\n getCache.set(cacheKey, {\n status: response.status,\n headers: headerRecord,\n body: parsed,\n })\n return parsed\n}\n\n/**\n * Seal coverage-corpus routing ZIPs + availability POSTs into the seed observation cache.\n * Call after warmup, before `seedFrom`, so compare walks can forceInclude geo/scheduling reads.\n */\nexport const prefetchCoverageObservations = async (args: {\n real: PrefetchTarget\n getCache: Map<string, SeedCacheEntry>\n zips?: readonly string[]\n /** ZIPs that also get PSC availability POST seals. Defaults to scheduling corpus. */\n schedulingZips?: readonly string[]\n /** ZIPs for phlebotomy availability (narrow served set). Defaults to PHLEBOTOMY_ZIPS. */\n phlebotomyZips?: readonly string[]\n labIds?: readonly number[]\n /** Also prefetch phlebotomy + PSC availability. Default true. */\n includeAvailability?: boolean\n sleep?: (ms: number) => Promise<void>\n minIntervalMs?: number\n}) => {\n const zips = args.zips ?? COVERAGE_ZIPS\n const schedulingZips = args.schedulingZips ?? PSC_AVAILABILITY_ZIPS\n const phlebotomyZips = args.phlebotomyZips ?? PHLEBOTOMY_AVAILABILITY_ZIPS\n const labIds = args.labIds ?? PSC_LAB_IDS\n const includeAvailability = args.includeAvailability !== false\n const sleep = args.sleep ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)))\n const gap = args.minIntervalMs ?? 50\n\n for (const zip of zips) {\n await recordObservation(args.real, \"GET\", `/v3/order/area/info?zip_code=${zip}`, args.getCache)\n await sleep(gap)\n for (const labId of labIds) {\n await recordObservation(\n args.real,\n \"GET\",\n `/v3/order/psc/info?zip_code=${zip}&lab_id=${labId}`,\n args.getCache,\n )\n await sleep(gap)\n }\n }\n\n if (!includeAvailability) return\n for (const zip of phlebotomyZips) {\n const body = availabilityAddressForZip(zip)\n await recordObservation(\n args.real,\n \"POST\",\n `/v3/order/phlebotomy/appointment/availability?start_date=${AVAILABILITY_START_DATE}`,\n args.getCache,\n body,\n )\n await sleep(gap)\n }\n for (const zip of schedulingZips) {\n const body = availabilityAddressForZip(zip)\n await recordObservation(\n args.real,\n \"POST\",\n `/v3/order/psc/appointment/availability?lab=quest&start_date=${AVAILABILITY_START_DATE}`,\n args.getCache,\n body,\n )\n await sleep(gap)\n }\n}\n\n/** Extract every `central_labs[*].lab_id` from an area-serviceability body. */\nconst labIdsFromAreaBody = (body: unknown): number[] => {\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) return []\n const central = (body as Record<string, unknown>).central_labs\n if (central === null || typeof central !== \"object\") return []\n const entries = Array.isArray(central)\n ? central\n : Object.values(central as Record<string, unknown>)\n const ids: number[] = []\n for (const entry of entries) {\n if (typeof entry !== \"object\" || entry === null || Array.isArray(entry)) continue\n const labId = (entry as Record<string, unknown>).lab_id\n if (typeof labId === \"number\" && Number.isInteger(labId)) ids.push(labId)\n }\n return ids\n}\n\n/**\n * Record the parameter-stable provider reads a sealed corpus covers: area serviceability and\n * PSC site inventory for every coverage ZIP, in both the SDK-shaped `radius=100` request and\n * the bare query the parity walks use. Availability is deliberately not recorded \u2014 its slot\n * dates and single-use `booking_key`s can never match a live cache key.\n */\nexport const recordSandboxCorpus = async (args: {\n real: PrefetchTarget\n getCache: Map<string, SeedCacheEntry>\n zips?: readonly string[]\n labIds?: readonly number[]\n sleep?: (ms: number) => Promise<void>\n minIntervalMs?: number\n}): Promise<{ observations: number; labIds: number[] }> => {\n const zips = args.zips ?? COVERAGE_ZIPS\n const sleep = args.sleep ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)))\n const gap = args.minIntervalMs ?? 50\n const discovered = new Set<number>(args.labIds ?? PSC_LAB_IDS)\n\n for (const zip of zips) {\n for (const path of [\n `/v3/order/area/info?zip_code=${zip}&radius=100`,\n `/v3/order/area/info?zip_code=${zip}`,\n ]) {\n const body = await recordObservation(args.real, \"GET\", path, args.getCache)\n for (const labId of labIdsFromAreaBody(body)) discovered.add(labId)\n await sleep(gap)\n }\n }\n\n const labIds = [...discovered].sort((a, b) => a - b)\n for (const zip of zips) {\n for (const labId of labIds) {\n for (const path of [\n `/v3/order/psc/info?zip_code=${zip}&lab_id=${labId}&radius=100`,\n `/v3/order/psc/info?zip_code=${zip}&lab_id=${labId}`,\n ]) {\n await recordObservation(args.real, \"GET\", path, args.getCache)\n await sleep(gap)\n }\n }\n }\n\n return { observations: args.getCache.size, labIds }\n}\n", "import { COVERAGE_ZIPS } from \"./coverage-corpus.js\"\nimport { type PrefetchTarget, recordObservation, recordSandboxCorpus } from \"./prefetch.js\"\nimport { SEALED_CORPUS_VERSION, type SealedCorpus } from \"./sealed-corpus.js\"\nimport { expectedFromMarkersResponse, mapLabTest, type SeedSource } from \"./seed-from.js\"\nimport type { ExpectedResult, GetCacheEntry, LabTestRecord } from \"./state.js\"\n\nexport const DEFAULT_JUNCTION_BASE_URL = \"https://api.sandbox.tryvital.io\"\n\n/** Key prefixes of sandbox team keys. `corpus pull` and `verify` refuse any other key. */\nexport const SANDBOX_KEY_PREFIXES = [\"sk_us_\", \"sk_eu_\"] as const\n\nexport const isSandboxKey = (key: string): boolean =>\n SANDBOX_KEY_PREFIXES.some((prefix) => key.startsWith(prefix))\n\nexport type PullCorpusOptions = {\n apiKey: string\n baseUrl?: string\n /** ZIPs to record area and PSC coverage for. Default: the shipped coverage set. */\n zips?: readonly string[]\n /**\n * Refresh only `zips` on top of this corpus, keeping everything else. How a single\n * ZIP is added to a committed corpus without re-recording the whole thing.\n */\n base?: SealedCorpus\n /** Skip the team's catalog and lab accounts (coverage only). */\n coverageOnly?: boolean\n fetch?: (request: Request) => Promise<Response>\n /** Pause between vendor calls, to stay under rate limits. Default 50 ms. */\n minIntervalMs?: number\n onProgress?: (message: string) => void\n}\n\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined\n\n/** `GET /v3/lab_test/lab_account` answers `{ data: [...] }`; older recordings saved a bare array. */\nconst listOf = (body: unknown): Record<string, unknown>[] => {\n const items = Array.isArray(body) ? body : asRecord(body)?.data\n return Array.isArray(items)\n ? items.map(asRecord).filter((entry): entry is Record<string, unknown> => !!entry)\n : []\n}\n\n/** JSON with object keys sorted, so equal content always serializes identically. */\nexport const canonicalJson = (value: unknown): string =>\n JSON.stringify(value, (_key, inner: unknown) => {\n const record = asRecord(inner)\n if (!record) return inner\n return Object.fromEntries(\n Object.keys(record)\n .sort()\n .map((key) => [key, record[key]]),\n )\n })\n\n/** SHA-256 over a corpus's content \u2014 not its recording time \u2014 so a re-pull of unchanged data matches. */\nexport const fingerprintCorpus = async (corpus: SealedCorpus): Promise<string> => {\n const content = canonicalJson({\n observations: corpus.observations,\n catalog: corpus.catalog,\n labAccounts: corpus.labAccounts,\n })\n const digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(content))\n return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")\n}\n\n/** Record a sealed corpus from a real Junction team. Read-only: it only issues GETs. */\nexport const pullCorpus = async (options: PullCorpusOptions): Promise<SealedCorpus> => {\n const baseUrl = (options.baseUrl ?? DEFAULT_JUNCTION_BASE_URL).replace(/\\/$/, \"\")\n const send = options.fetch ?? ((request: Request) => fetch(request))\n const headers = { \"x-vital-api-key\": options.apiKey }\n const gap = options.minIntervalMs ?? 50\n const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))\n const progress = options.onProgress ?? (() => {})\n const real: PrefetchTarget = { baseUrl, fetch: send, headers: () => headers }\n const source: SeedSource = { baseUrl, fetch: send, headers }\n const getCache = new Map<string, GetCacheEntry>()\n\n const zips = options.zips ?? (options.base ? [] : COVERAGE_ZIPS)\n if (zips.length > 0) {\n progress(`recording area + PSC coverage for ${zips.length} ZIP(s)`)\n const { labIds } = await recordSandboxCorpus({ real, getCache, zips, minIntervalMs: gap })\n progress(`coverage recorded across ${labIds.length} PSC lab(s)`)\n }\n\n let catalog = options.base?.catalog ?? { labTests: [], labs: [], expectedResults: {} }\n let labAccounts = options.base?.labAccounts ?? []\n if (!options.coverageOnly) {\n progress(\"recording lab-test catalog\")\n const labTests: LabTestRecord[] = []\n let cursor: string | null = null\n for (;;) {\n const path =\n cursor === null ? \"/v3/lab_test\" : `/v3/lab_test?next_cursor=${encodeURIComponent(cursor)}`\n const body = asRecord(await recordObservation(real, \"GET\", path, getCache))\n for (const entry of Array.isArray(body?.data) ? body.data : []) {\n const test = mapLabTest(entry)\n if (test) labTests.push(test)\n }\n cursor = typeof body?.next_cursor === \"string\" ? body.next_cursor : null\n if (cursor === null) break\n await sleep(gap)\n }\n const labs = listOf(await recordObservation(real, \"GET\", \"/v3/lab_tests/labs\", getCache))\n const expectedResults: Record<string, ExpectedResult[]> = {}\n for (const test of labTests) {\n await recordObservation(real, \"GET\", `/v3/lab_tests/${test.id}/markers`, getCache)\n expectedResults[test.id] = await expectedFromMarkersResponse(source, test)\n await sleep(gap)\n }\n catalog = { labTests, labs, expectedResults }\n progress(`catalog: ${labTests.length} lab test(s), ${labs.length} lab(s)`)\n labAccounts = listOf(await recordObservation(real, \"GET\", \"/v3/lab_test/lab_account\", getCache))\n progress(`lab accounts: ${labAccounts.length}`)\n }\n\n const observations = Object.fromEntries(\n [...Object.entries(options.base?.observations ?? {}), ...getCache.entries()].sort(([a], [b]) =>\n a < b ? -1 : a > b ? 1 : 0,\n ),\n )\n const corpus: SealedCorpus = {\n version: SEALED_CORPUS_VERSION,\n recordedAt: new Date().toISOString(),\n source: baseUrl,\n observations,\n catalog,\n labAccounts,\n }\n corpus.fingerprint = await fingerprintCorpus(corpus)\n return corpus\n}\n\nexport type SetDiff = { added: string[]; removed: string[]; changed: string[] }\n\nexport type CorpusDiff = {\n identical: boolean\n observations: SetDiff\n labTests: SetDiff\n labAccounts: SetDiff\n zips: { added: string[]; removed: string[] }\n}\n\nconst diffById = <T>(before: Iterable<[string, T]>, after: Iterable<[string, T]>): SetDiff => {\n const a = new Map(before)\n const b = new Map(after)\n const sorted = (values: string[]) => values.sort()\n return {\n added: sorted([...b.keys()].filter((key) => !a.has(key))),\n removed: sorted([...a.keys()].filter((key) => !b.has(key))),\n changed: sorted(\n [...b.keys()].filter(\n (key) => a.has(key) && canonicalJson(a.get(key)) !== canonicalJson(b.get(key)),\n ),\n ),\n }\n}\n\nconst zipsOf = (corpus: SealedCorpus): Set<string> =>\n new Set(\n Object.keys(corpus.observations).flatMap((key) => {\n const zip = /\\/v3\\/order\\/(?:area|psc)\\/info\\?.*zip_code=(\\d{5})/.exec(key)?.[1]\n return zip ? [zip] : []\n }),\n )\n\n/** What changed between two recordings: coverage, catalog, accounts and raw observations. */\nexport const diffCorpus = (before: SealedCorpus, after: SealedCorpus): CorpusDiff => {\n const observations = diffById(\n Object.entries(before.observations),\n Object.entries(after.observations),\n )\n const labTests = diffById(\n before.catalog.labTests.map((test) => [test.id, test] as [string, unknown]),\n after.catalog.labTests.map((test) => [test.id, test] as [string, unknown]),\n )\n const accountEntries = (corpus: SealedCorpus) =>\n corpus.labAccounts.map((account) => [String(account.id), account] as [string, unknown])\n const labAccounts = diffById(accountEntries(before), accountEntries(after))\n const beforeZips = zipsOf(before)\n const afterZips = zipsOf(after)\n const zips = {\n added: [...afterZips].filter((zip) => !beforeZips.has(zip)).sort(),\n removed: [...beforeZips].filter((zip) => !afterZips.has(zip)).sort(),\n }\n const empty = (d: SetDiff) => d.added.length + d.removed.length + d.changed.length === 0\n return {\n identical: empty(observations) && empty(labTests) && empty(labAccounts),\n observations,\n labTests,\n labAccounts,\n zips,\n }\n}\n", "import { opaqueToken } from \"@crvouga/mockingbird-service\"\nimport { type JunctionWebhookEvent, WEBHOOK_RETRY_DELAYS_MS } from \"./state.js\"\n\n/**\n * Signed webhook delivery, the way Junction delivers through Svix.\n *\n * Signing lives here, next to the events, so a consumer never hand-rolls it. The\n * signature is standard Svix \u2014 `v1,` + base64 HMAC-SHA256, keyed by the base64 part of\n * `whsec_\u2026`, over `\"<svix-id>.<svix-timestamp>.<body>\"` \u2014 so the official `svix`\n * verifier, and a receiver written for real Junction webhooks, accept it unchanged.\n */\nexport type WebhookEndpoint = {\n url: string\n /** Svix signing secret, `whsec_<base64>`. A bare base64 secret is accepted too. */\n secret: string\n /**\n * Delay before each attempt, in ms; the first entry delays the first attempt. Default:\n * Svix's schedule (immediately, 5 s, 5 min, 30 min, 2 h, 5 h, 10 h, 10 h).\n */\n retryDelaysMs?: readonly number[]\n /** Abort an attempt that takes longer than this. Default 15 s, like Svix. */\n timeoutMs?: number\n /** Added to every delivery, e.g. a routing scope for a shared receiver. */\n headers?: Record<string, string>\n fetch?: (request: Request) => Promise<Response>\n}\n\nexport type WebhookAttempt = {\n attempt: number\n /** Wall-clock time of the attempt, ISO-8601. */\n at: string\n /** Receiver's status code, or `null` when the request never completed. */\n status: number | null\n error: string | null\n durationMs: number\n}\n\nexport type WebhookDelivery = {\n messageId: string\n namespace: string\n event: JunctionWebhookEvent\n state: \"pending\" | \"delivered\" | \"failed\"\n attempts: WebhookAttempt[]\n}\n\nexport type WebhookDispatcher = {\n /** Queue an event for delivery. Returns immediately; delivery runs in the background. */\n publish(event: JunctionWebhookEvent, namespace: string): WebhookDelivery\n deliveries(namespace?: string): WebhookDelivery[]\n /** Deliver a message again now, as a new attempt, whatever its state. */\n replay(messageId: string): Promise<WebhookDelivery | undefined>\n /** Run every pending retry now instead of waiting out its delay. */\n flush(): Promise<void>\n /** Resolve once no delivery is in flight. */\n idle(): Promise<void>\n /** Cancel pending retries and forget every delivery. */\n clear(namespace?: string): void\n}\n\nconst encoder = new TextEncoder()\n\nconst base64 = (bytes: ArrayBuffer): string => {\n let binary = \"\"\n for (const byte of new Uint8Array(bytes)) binary += String.fromCharCode(byte)\n return btoa(binary)\n}\n\nconst secretBytes = (secret: string): Uint8Array => {\n const raw = secret.startsWith(\"whsec_\") ? secret.slice(\"whsec_\".length) : secret\n try {\n return Uint8Array.from(atob(raw), (char) => char.charCodeAt(0))\n } catch {\n throw new TypeError(\"webhook secret must be whsec_<base64> (as Svix issues it)\")\n }\n}\n\n/** The `svix-signature` value for one message: `v1,<base64 HMAC-SHA256>`. */\nexport const signSvix = async (\n secret: string,\n messageId: string,\n timestampSeconds: number,\n body: string,\n): Promise<string> => {\n const key = await crypto.subtle.importKey(\n \"raw\",\n secretBytes(secret) as BufferSource,\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n )\n const signed = await crypto.subtle.sign(\n \"HMAC\",\n key,\n encoder.encode(`${messageId}.${timestampSeconds}.${body}`),\n )\n return `v1,${base64(signed)}`\n}\n\n/**\n * Check a delivery's signature the way the `svix` verifier does: any `v1,` entry in the\n * space-separated header matches, and the timestamp is within `toleranceSeconds`.\n */\nexport const verifySvix = async (\n secret: string,\n headers: { \"svix-id\": string; \"svix-timestamp\": string; \"svix-signature\": string },\n body: string,\n options: { toleranceSeconds?: number; now?: () => number } = {},\n): Promise<boolean> => {\n const timestamp = Number.parseInt(headers[\"svix-timestamp\"], 10)\n if (!Number.isFinite(timestamp)) return false\n const nowSeconds = Math.floor((options.now ?? Date.now)() / 1000)\n if (Math.abs(nowSeconds - timestamp) > (options.toleranceSeconds ?? 300)) return false\n const expected = await signSvix(secret, headers[\"svix-id\"], timestamp, body)\n return headers[\"svix-signature\"].split(\" \").some((entry) => entry === expected)\n}\n\ntype Pending = { delivery: WebhookDelivery; timer: ReturnType<typeof setTimeout> | undefined }\n\n/** Keep a long retry from holding the process open, where the runtime supports it. */\nconst unref = (timer: ReturnType<typeof setTimeout>) => {\n ;(timer as { unref?: () => void }).unref?.()\n}\n\nexport const createWebhookDispatcher = (endpoint: WebhookEndpoint): WebhookDispatcher => {\n // Validate up front so a bad secret fails at boot, not on the first event.\n secretBytes(endpoint.secret)\n const delays = endpoint.retryDelaysMs ?? WEBHOOK_RETRY_DELAYS_MS\n const timeoutMs = endpoint.timeoutMs ?? 15_000\n const send = endpoint.fetch ?? ((request: Request) => fetch(request))\n const deliveries = new Map<string, WebhookDelivery>()\n const pending = new Map<string, Pending>()\n const inFlight = new Set<Promise<void>>()\n let sequence = 0\n\n const attempt = async (delivery: WebhookDelivery): Promise<boolean> => {\n const body = JSON.stringify(delivery.event)\n // Wall-clock, never the mock clock: receivers reject timestamps outside ~5 minutes\n // of their own clock, and an advanced mock clock would fail every delivery.\n const timestamp = Math.floor(Date.now() / 1000)\n const started = Date.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 }\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), timeoutMs)\n try {\n const response = await send(\n new Request(endpoint.url, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...endpoint.headers,\n \"svix-id\": delivery.messageId,\n \"svix-timestamp\": String(timestamp),\n \"svix-signature\": await signSvix(endpoint.secret, delivery.messageId, timestamp, body),\n },\n body,\n signal: controller.signal,\n }),\n )\n record.status = response.status\n await response.body?.cancel()\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 clearTimeout(timer)\n record.durationMs = Date.now() - started\n delivery.attempts.push(record)\n }\n // Svix treats any 2xx as delivered and retries everything else.\n return record.status !== null && record.status >= 200 && record.status < 300\n }\n\n const track = (work: Promise<void>) => {\n inFlight.add(work)\n void work.finally(() => inFlight.delete(work))\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.messageId)\n return\n }\n const run = () => {\n pending.delete(delivery.messageId)\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 run()\n return\n }\n const timer = setTimeout(run, delay)\n unref(timer)\n pending.set(delivery.messageId, { delivery, timer })\n }\n\n return {\n publish(event, namespace) {\n sequence++\n const delivery: WebhookDelivery = {\n messageId: `msg_${opaqueToken(`junction:webhook:${namespace}:${sequence}`, 27)}`,\n namespace,\n event,\n state: \"pending\",\n attempts: [],\n }\n deliveries.set(delivery.messageId, delivery)\n schedule(delivery)\n return delivery\n },\n deliveries: (namespace) =>\n [...deliveries.values()].filter((d) => namespace === undefined || d.namespace === namespace),\n async replay(messageId) {\n const delivery = deliveries.get(messageId)\n if (!delivery) return undefined\n const queued = pending.get(messageId)\n if (queued?.timer !== undefined) clearTimeout(queued.timer)\n pending.delete(messageId)\n const ok = await attempt(delivery)\n delivery.state = ok ? \"delivered\" : \"failed\"\n return delivery\n },\n async flush() {\n for (const [id, queued] of [...pending]) {\n if (queued.timer !== undefined) clearTimeout(queued.timer)\n pending.delete(id)\n track(\n attempt(queued.delivery).then((ok) => {\n if (ok) queued.delivery.state = \"delivered\"\n else schedule(queued.delivery)\n }),\n )\n }\n await Promise.all([...inFlight])\n },\n async idle() {\n while (inFlight.size > 0) await Promise.all([...inFlight])\n },\n clear(namespace) {\n for (const [id, delivery] of [...deliveries]) {\n if (namespace !== undefined && delivery.namespace !== namespace) continue\n const queued = pending.get(id)\n if (queued?.timer !== undefined) clearTimeout(queued.timer)\n pending.delete(id)\n deliveries.delete(id)\n }\n },\n }\n}\n", "import {\n type Clock,\n createRuntime as createServiceRuntime,\n type RequestLog,\n type ServiceRuntime,\n} from \"@crvouga/mockingbird-service\"\nimport type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\nimport { junctionAdminRoutes } from \"./admin.js\"\nimport { document } from \"./generated/openapi.js\"\nimport { JUNCTION_NAMESPACE, JunctionAPI } from \"./index.js\"\nimport type { LabAccountInput } from \"./lab-accounts.js\"\nimport type { SealedCorpus } from \"./sealed-corpus.js\"\nimport type { GeoMode, WebhookPublisher } from \"./state.js\"\nimport {\n createWebhookDispatcher,\n type WebhookDispatcher,\n type WebhookEndpoint,\n} from \"./webhooks.js\"\n\nexport type JunctionRuntimeOptions = {\n /**\n * Recorded vendor data every namespace starts from. The served mock loads the corpus\n * shipped at `@crvouga/mockingbird-service-junction/corpus` unless told otherwise.\n */\n corpus?: SealedCorpus\n /** Default: `corpus` when a corpus is loaded, otherwise `synthetic`. */\n geo?: GeoMode\n /** The team's lab accounts; see {@link JunctionAPIOptions.labAccounts}. */\n labAccounts?: readonly LabAccountInput[]\n /** Deliver signed webhooks here, with Svix's retry schedule. */\n webhooks?: WebhookEndpoint\n /** Called in-process for every webhook event, delivered or not. */\n onWebhook?: (event: Parameters<WebhookPublisher>[0], namespace: string) => void\n sqlite?: SqliteClient\n clock?: Clock\n /** Seeds fault rates and webhook retry jitter. */\n seed?: number | string\n /** Require `x-mockingbird-admin-key` on `/__admin/*`. */\n adminKey?: string\n onLog?: (entry: RequestLog) => void\n}\n\nexport type JunctionRuntime = ServiceRuntime<JunctionAPI> & {\n /** Signed delivery, when `webhooks` was configured. */\n readonly webhooks: WebhookDispatcher | undefined\n}\n\n/**\n * The Junction mock with Mockingbird's full service contract: unauthenticated\n * `/health`, the `/__admin/*` control plane, per-request namespaces\n * (`x-mockingbird-namespace`), clock control, fault injection and request metrics.\n * Runtime-neutral: serve it with any Fetch-native server, or use `./server` for Node.\n */\nexport const createRuntime = (options: JunctionRuntimeOptions = {}): JunctionRuntime => {\n const webhooks = options.webhooks ? createWebhookDispatcher(options.webhooks) : undefined\n const runtime: ServiceRuntime<JunctionAPI> = createServiceRuntime<JunctionAPI>({\n name: JUNCTION_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 create: ({ namespace, publicNamespace, sqlite, clock, rng }) => {\n const api = new JunctionAPI({\n sqlite,\n namespace,\n now: clock.now,\n webhook: { seed: rng.seed },\n ...(options.corpus ? { corpus: options.corpus } : {}),\n ...(options.geo ? { geo: options.geo } : {}),\n ...(options.labAccounts ? { labAccounts: options.labAccounts } : {}),\n onWebhook: (event) => {\n options.onWebhook?.(event, publicNamespace)\n webhooks?.publish(event, publicNamespace)\n },\n })\n // A namespace reset also forgets that namespace's deliveries and pending retries.\n const reset = api.reset.bind(api)\n api.reset = async () => {\n webhooks?.clear(publicNamespace)\n await reset()\n }\n return api\n },\n describe: (): Record<string, unknown> => {\n const info = runtime.instance().corpusInfo()\n return {\n corpus: info?.label ?? null,\n geo: runtime.instance().geoMode,\n webhooks: webhooks ? \"on\" : \"off\",\n }\n },\n admin: junctionAdminRoutes({ webhooks }),\n })\n return Object.assign(runtime, { webhooks })\n}\n", "import { canonicalJson, DEFAULT_JUNCTION_BASE_URL } from \"./corpus-tools.js\"\nimport type { SealedCorpus } from \"./sealed-corpus.js\"\n\n/**\n * Differential verification: the same requests against real Junction and the mock,\n * with every divergence reported. Two checks:\n *\n * - drift: each recorded corpus observation re-fetched from the real API. A stale\n * entry means the corpus no longer matches production and should be re-pulled.\n * - scenario: a fixed script of stateful calls (users, catalog, serviceability, and\n * optionally orders) run against both sides, comparing status codes, response\n * shapes, and \u2014 for the documented error bodies \u2014 exact bytes.\n *\n * Only a sandbox team should be used: the scenario creates, and always deletes, one\n * user (and, with `orders`, places and cancels one order).\n */\nexport type VerifyOptions = {\n realKey: string\n realUrl?: string\n /** The mock under test, e.g. `createRuntime({ corpus })`. */\n mock: { fetch(request: Request): Promise<Response> }\n corpus: SealedCorpus\n /** Re-fetch at most this many observations (spread evenly). Default: all of them. */\n sample?: number\n /** Skip the drift check. */\n skipDrift?: boolean\n /** Also place, read and cancel an order on the real team. */\n orders?: boolean\n fetch?: (request: Request) => Promise<Response>\n minIntervalMs?: number\n onProgress?: (message: string) => void\n}\n\nexport type Divergence = {\n check: string\n kind: \"status\" | \"shape\" | \"body\" | \"error\"\n /** JSON path of the first difference, when there is one. */\n at?: string\n real: unknown\n mock: unknown\n}\n\nexport type VerifyReport = {\n ok: boolean\n drift: { checked: number; stale: number }\n scenario: { steps: number; divergent: number }\n divergences: Divergence[]\n}\n\ntype Side = \"real\" | \"mock\"\ntype Reply = { status: number; body: unknown }\n\nconst readReply = async (response: Response): Promise<Reply> => {\n const text = await response.text()\n try {\n return { status: response.status, body: text === \"\" ? null : JSON.parse(text) }\n } catch {\n return { status: response.status, body: text }\n }\n}\n\n/** The structure of a JSON value: object keys and value types, never the values. */\nexport const shapeOf = (value: unknown): unknown => {\n if (value === null) return \"null\"\n if (Array.isArray(value)) return value.length === 0 ? [] : [shapeOf(value[0])]\n if (typeof value === \"object\") {\n const record = value as Record<string, unknown>\n return Object.fromEntries(\n Object.keys(record)\n .sort()\n .map((key) => [key, shapeOf(record[key])]),\n )\n }\n return typeof value\n}\n\n/** Path to the first place two JSON values differ, or `undefined` when they are equal. */\nexport const firstDifference = (a: unknown, b: unknown, path = \"$\"): string | undefined => {\n if (canonicalJson(a) === canonicalJson(b)) return undefined\n if (typeof a !== \"object\" || typeof b !== \"object\" || a === null || b === null) return path\n if (Array.isArray(a) !== Array.isArray(b)) return path\n const keys = new Set([...Object.keys(a), ...Object.keys(b)])\n for (const key of [...keys].sort()) {\n const at = Array.isArray(a) ? `${path}[${key}]` : `${path}.${key}`\n const found = firstDifference(\n (a as Record<string, unknown>)[key],\n (b as Record<string, unknown>)[key],\n at,\n )\n if (found) return found\n }\n return path\n}\n\ntype Context = { clientUserId: string; userId?: string; orderId?: string }\n\ntype Step = {\n name: string\n /** `exact`: bodies must match byte for byte; `shape`: structure and types only. */\n compare: \"exact\" | \"shape\"\n skip?: (ctx: Record<Side, Context>) => boolean\n request(ctx: Context): { method: string; path: string; body?: unknown }\n capture?(reply: Reply, ctx: Context): void\n}\n\nconst scenario = (corpus: SealedCorpus, withOrders: boolean): Step[] => {\n const zip =\n Object.keys(corpus.observations)\n .map((key) => /\\/v3\\/order\\/area\\/info\\?.*zip_code=(\\d{5})/.exec(key)?.[1])\n .find((found) => found !== undefined) ?? \"92101\"\n const labTestId = corpus.catalog.labTests[0]?.id\n const steps: Step[] = [\n {\n name: \"user.create\",\n compare: \"shape\",\n request: (ctx) => ({\n method: \"POST\",\n path: \"/v2/user\",\n body: { client_user_id: ctx.clientUserId },\n }),\n capture: (reply, ctx) => {\n const id = (reply.body as { user_id?: unknown } | null)?.user_id\n if (typeof id === \"string\") ctx.userId = id\n },\n },\n {\n name: \"user.create duplicate\",\n compare: \"shape\",\n request: (ctx) => ({\n method: \"POST\",\n path: \"/v2/user\",\n body: { client_user_id: ctx.clientUserId },\n }),\n },\n {\n name: \"user.get\",\n compare: \"shape\",\n request: (ctx) => ({ method: \"GET\", path: `/v2/user/${ctx.userId}` }),\n },\n {\n name: \"user.getByClientUserId\",\n compare: \"shape\",\n request: (ctx) => ({ method: \"GET\", path: `/v2/user/resolve/${ctx.clientUserId}` }),\n },\n {\n name: \"user.get unknown (documented 404 body)\",\n compare: \"exact\",\n request: () => ({ method: \"GET\", path: \"/v2/user/00000000-0000-4000-8000-000000000000\" }),\n },\n {\n name: \"user.getByClientUserId unknown (documented 404 body)\",\n compare: \"exact\",\n request: (ctx) => ({ method: \"GET\", path: `/v2/user/resolve/${ctx.clientUserId}-missing` }),\n },\n {\n name: \"labs\",\n compare: \"shape\",\n request: () => ({ method: \"GET\", path: \"/v3/lab_tests/labs\" }),\n },\n {\n name: `area info ${zip}`,\n compare: \"exact\",\n request: () => ({ method: \"GET\", path: `/v3/order/area/info?zip_code=${zip}&radius=100` }),\n },\n ]\n if (withOrders && labTestId) {\n steps.push(\n {\n name: \"order.create\",\n compare: \"shape\",\n request: (ctx) => ({\n method: \"POST\",\n path: \"/v3/order\",\n body: {\n user_id: ctx.userId,\n patient_details: {\n first_name: \"Mockingbird\",\n last_name: \"Verify\",\n dob: \"1990-01-01\",\n gender: \"female\",\n phone_number: \"+14155551234\",\n email: \"verify@example.com\",\n },\n patient_address: {\n first_line: \"1 Main St\",\n city: \"San Diego\",\n state: \"CA\",\n zip: \"92101\",\n country: \"US\",\n },\n order_set: { lab_test_ids: [labTestId] },\n },\n }),\n capture: (reply, ctx) => {\n const id = (reply.body as { order?: { id?: unknown } } | null)?.order?.id\n if (typeof id === \"string\") ctx.orderId = id\n },\n },\n {\n name: \"order.get\",\n compare: \"shape\",\n skip: (ctx) => !ctx.real.orderId || !ctx.mock.orderId,\n request: (ctx) => ({ method: \"GET\", path: `/v3/order/${ctx.orderId}` }),\n },\n {\n name: \"order.cancel\",\n compare: \"shape\",\n skip: (ctx) => !ctx.real.orderId || !ctx.mock.orderId,\n request: (ctx) => ({ method: \"POST\", path: `/v3/order/${ctx.orderId}/cancel` }),\n },\n )\n }\n steps.push({\n name: \"user.delete\",\n compare: \"shape\",\n request: (ctx) => ({ method: \"DELETE\", path: `/v2/user/${ctx.userId}` }),\n capture: (_reply, ctx) => {\n delete ctx.userId\n },\n })\n return steps\n}\n\nexport const verifyAgainstReal = async (options: VerifyOptions): Promise<VerifyReport> => {\n const realUrl = (options.realUrl ?? DEFAULT_JUNCTION_BASE_URL).replace(/\\/$/, \"\")\n const send = options.fetch ?? ((request: Request) => fetch(request))\n const gap = options.minIntervalMs ?? 50\n const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))\n const progress = options.onProgress ?? (() => {})\n const divergences: Divergence[] = []\n\n const call = async (side: Side, method: string, path: string, body?: unknown): Promise<Reply> => {\n const base = side === \"real\" ? realUrl : \"http://mock.mockingbird.local\"\n const request = new Request(`${base}${path}`, {\n method,\n headers: {\n \"x-vital-api-key\": side === \"real\" ? options.realKey : \"sk_us_mockingbird_verify\",\n ...(body !== undefined ? { \"content-type\": \"application/json\" } : {}),\n },\n ...(body !== undefined ? { body: JSON.stringify(body) } : {}),\n })\n const response = side === \"real\" ? await send(request) : await options.mock.fetch(request)\n return readReply(response)\n }\n\n // \u2500\u2500 drift \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n let checked = 0\n let stale = 0\n if (!options.skipDrift) {\n const keys = Object.keys(options.corpus.observations).filter((key) => key.startsWith(\"GET \"))\n const limit = options.sample ?? keys.length\n const stride = Math.max(1, Math.floor(keys.length / Math.max(1, limit)))\n const picked = keys.filter((_, index) => index % stride === 0).slice(0, limit)\n progress(`drift: re-fetching ${picked.length} of ${keys.length} recorded observations`)\n for (const key of picked) {\n const path = key.slice(\"GET \".length)\n const recorded = options.corpus.observations[key]\n if (!recorded) continue\n checked++\n try {\n const live = await call(\"real\", \"GET\", path)\n if (live.status !== recorded.status) {\n stale++\n divergences.push({\n check: `drift ${key}`,\n kind: \"status\",\n real: live.status,\n mock: recorded.status,\n })\n } else {\n const at = firstDifference(live.body, recorded.body)\n if (at) {\n stale++\n divergences.push({\n check: `drift ${key}`,\n kind: \"body\",\n at,\n real: live.body,\n mock: recorded.body,\n })\n }\n }\n } catch (error) {\n stale++\n divergences.push({ check: `drift ${key}`, kind: \"error\", real: String(error), mock: null })\n }\n await sleep(gap)\n }\n }\n\n // \u2500\u2500 scenario \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const clientUserId = `mockingbird-verify-${Date.now().toString(36)}`\n const ctx: Record<Side, Context> = { real: { clientUserId }, mock: { clientUserId } }\n const steps = scenario(options.corpus, options.orders === true)\n let ran = 0\n let divergent = 0\n progress(`scenario: ${steps.length} steps as client_user_id ${clientUserId}`)\n try {\n for (const step of steps) {\n if (step.skip?.(ctx)) continue\n ran++\n const replies = {} as Record<Side, Reply>\n for (const side of [\"real\", \"mock\"] as const) {\n const { method, path, body } = step.request(ctx[side])\n replies[side] = await call(side, method, path, body)\n step.capture?.(replies[side], ctx[side])\n }\n const { real, mock } = replies\n let divergence: Divergence | undefined\n if (real.status !== mock.status) {\n divergence = { check: step.name, kind: \"status\", real: real.status, mock: mock.status }\n } else if (step.compare === \"exact\") {\n const at = firstDifference(real.body, mock.body)\n if (at)\n divergence = { check: step.name, kind: \"body\", at, real: real.body, mock: mock.body }\n } else {\n const at = firstDifference(shapeOf(real.body), shapeOf(mock.body))\n if (at) {\n divergence = {\n check: step.name,\n kind: \"shape\",\n at,\n real: shapeOf(real.body),\n mock: shapeOf(mock.body),\n }\n }\n }\n if (divergence) {\n divergent++\n divergences.push(divergence)\n }\n progress(` ${divergence ? \"DIVERGED\" : \"ok\"} ${step.name}`)\n await sleep(gap)\n }\n } finally {\n // Never leave the verify user behind on the real team: it counts against the sandbox cap.\n if (ctx.real.orderId) {\n await call(\"real\", \"POST\", `/v3/order/${ctx.real.orderId}/cancel`).catch(() => undefined)\n }\n if (ctx.real.userId) {\n await call(\"real\", \"DELETE\", `/v2/user/${ctx.real.userId}`).catch(() => undefined)\n }\n }\n\n return {\n ok: divergences.length === 0,\n drift: { checked, stale },\n scenario: { steps: ran, divergent },\n divergences,\n }\n}\n", "import type { FetchAPI } from \"@crvouga/mockingbird-core\"\nimport {\n type APIOptions,\n bootSqlite,\n createService,\n defineOperations,\n HttpError,\n jsonRes,\n opaqueToken,\n type Service,\n} from \"@crvouga/mockingbird-service\"\nimport type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\nimport type { Hono } from \"hono\"\nimport { document, type SupportedOperationId } from \"./generated/openapi.js\"\nimport {\n type LabAccountInput,\n labAccountFromClientFacing,\n labAccountFromInput,\n TEAM_LAB_ACCOUNTS,\n} from \"./lab-accounts.js\"\nimport { orderHandlers } from \"./orders.js\"\nimport { resultsHandlers } from \"./results.js\"\nimport { forceOrderStatus, schedulingHandlers } from \"./scheduling.js\"\nimport type { SealedCorpus } from \"./sealed-corpus.js\"\nimport {\n ensureLabTests as ensureLabTestsFrom,\n ensureOrders as ensureOrdersFrom,\n type SeedObservations,\n type SeedReport,\n type SeedSource,\n seedFrom as seedStateFrom,\n} from \"./seed-from.js\"\nimport {\n type GeoMode,\n type GetCacheEntry,\n JunctionState,\n type JunctionWebhookEvent,\n type JunctionWebhookOptions,\n type OrderRecord,\n type ResultFixture,\n type StoredLabAccount,\n type WebhookPublisher,\n} from \"./state.js\"\nimport { userHandlers } from \"./users.js\"\n\nexport type { FetchAPI } from \"@crvouga/mockingbird-core\"\nexport type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\nexport type { JunctionAdminOptions } from \"./admin.js\"\nexport {\n FAULT_PRESETS,\n ORDER_STATUSES_BY_METHOD,\n RESULT_FIXTURES,\n resolveTransition,\n TRANSITION_ALIASES,\n} from \"./admin.js\"\nexport type { CorpusDiff, PullCorpusOptions, SetDiff } from \"./corpus-tools.js\"\nexport {\n DEFAULT_JUNCTION_BASE_URL,\n diffCorpus,\n fingerprintCorpus,\n isSandboxKey,\n pullCorpus,\n SANDBOX_KEY_PREFIXES,\n} from \"./corpus-tools.js\"\nexport {\n COVERAGE_ZIPS,\n PHLEBOTOMY_AVAILABILITY_ZIPS,\n PSC_AVAILABILITY_ZIPS,\n PSC_LAB_IDS,\n} from \"./coverage-corpus.js\"\nexport type { OperationId, SupportedOperationId } from \"./generated/openapi.js\"\nexport { document, operationIds, supportedOperationIds } from \"./generated/openapi.js\"\nexport type {\n LabAccountDelegatedFlow,\n LabAccountInput,\n LabAccountRecord,\n LabAccountStatus,\n} from \"./lab-accounts.js\"\nexport { labAccountFromInput, TEAM_LAB_ACCOUNTS, US_STATES } from \"./lab-accounts.js\"\nexport { prefetchCoverageObservations } from \"./prefetch.js\"\nexport {\n AVAILABILITY_ADDRESS,\n AVAILABILITY_START_DATE,\n reshapeCoverageGeoCommand,\n} from \"./reshape.js\"\nexport type { JunctionRuntime, JunctionRuntimeOptions } from \"./runtime.js\"\nexport { createRuntime } from \"./runtime.js\"\nexport { UNKNOWN_ZIP_ERROR_TYPE, UNKNOWN_ZIP_STATUS } from \"./scheduling.js\"\nexport {\n parseSealedCorpus,\n SEALED_CORPUS_VERSION,\n type SealedCorpus,\n} from \"./sealed-corpus.js\"\nexport type { SeedObservations, SeedReport, SeedSource } from \"./seed-from.js\"\nexport type {\n GeoMode,\n GetCacheEntry,\n JunctionWebhookEvent,\n JunctionWebhookOptions,\n OrderRecord,\n ResultFixture,\n StoredLabAccount,\n WebhookPublisher,\n} from \"./state.js\"\nexport { observationCacheKey } from \"./state.js\"\nexport type { Divergence, VerifyOptions, VerifyReport } from \"./verify.js\"\nexport { verifyAgainstReal } from \"./verify.js\"\nexport type {\n WebhookAttempt,\n WebhookDelivery,\n WebhookDispatcher,\n WebhookEndpoint,\n} from \"./webhooks.js\"\nexport { createWebhookDispatcher, signSvix, verifySvix } from \"./webhooks.js\"\n\nexport const JUNCTION_NAMESPACE = \"junction\"\n\n/**\n * Stateful mock of the Junction (Vital) API user and lab-testing surfaces.\n *\n * Docs: https://docs.junction.com/\n * Auth: `x-vital-api-key` \u2014 https://docs.junction.com/api-details/junction-api\n */\nexport type JunctionAPIOptions = APIOptions & {\n onWebhook?: WebhookPublisher\n webhook?: JunctionWebhookOptions\n /** Install a recorded corpus at construction; it is re-applied on every `reset()`. */\n corpus?: SealedCorpus\n /**\n * How serviceability reads answer a ZIP the corpus does not cover. Default: `corpus`\n * when a corpus is given (refuse, loudly), otherwise `synthetic` (invent coverage).\n */\n geo?: GeoMode\n /**\n * The team's lab accounts, replacing the built-in fixtures (and any from the corpus).\n * `create_order` routes, accepts and rejects `lab_account_id` against these.\n */\n labAccounts?: readonly LabAccountInput[]\n}\n\n/** What a loaded corpus covers, for `/health` and startup logs. */\nexport type CorpusInfo = {\n label: string\n recordedAt: string\n source: string\n observations: number\n labTests: number\n labAccounts: number\n zips: number\n}\n\nconst observationMaps = new WeakMap<SealedCorpus, ReadonlyMap<string, GetCacheEntry>>()\n\n/** One read-only map per corpus object, shared by every namespace that loads it. */\nconst observationsOf = (corpus: SealedCorpus): ReadonlyMap<string, GetCacheEntry> => {\n let map = observationMaps.get(corpus)\n if (!map) {\n map = new Map(Object.entries(corpus.observations))\n observationMaps.set(corpus, map)\n }\n return map\n}\n\n/** A ZIP appears in a corpus when an area or PSC observation was recorded for it. */\nconst coveredZipsOf = (corpus: SealedCorpus): Set<string> => {\n const zips = new Set<string>()\n for (const key of Object.keys(corpus.observations)) {\n if (!/ \\/v3\\/order\\/(?:area|psc)\\/info\\?/.test(key)) continue\n const zip = /[?&]zip_code=(\\d{5})/.exec(key)?.[1]\n if (zip) zips.add(zip)\n }\n return zips\n}\n\n/** A short, stable name for a corpus: its recording date plus a digest of what it holds. */\nexport const corpusLabel = (corpus: SealedCorpus): string => {\n const digest =\n corpus.fingerprint ??\n opaqueToken(\n JSON.stringify([\n Object.keys(corpus.observations).sort(),\n corpus.catalog.labTests.map((test) => test.id).sort(),\n corpus.labAccounts.map((account) => account.id).sort(),\n ]),\n 12,\n )\n return `v${String(corpus.version)}-${corpus.recordedAt.slice(0, 10)}-${digest.slice(0, 12)}`\n}\n\nexport class JunctionAPI implements FetchAPI {\n readonly app: Hono\n readonly sqlite: SqliteClient\n private readonly service: Service\n private readonly state: JunctionState\n private corpus: SealedCorpus | undefined\n private labAccountConfig: StoredLabAccount[] | undefined\n\n constructor(options: JunctionAPIOptions = {}) {\n const sqlite = bootSqlite(options.sqlite)\n const namespace = options.namespace ?? JUNCTION_NAMESPACE\n const state = new JunctionState(sqlite, namespace, options.onWebhook, options.webhook)\n this.state = state\n const handlers = defineOperations<SupportedOperationId>({\n ...userHandlers(state),\n ...orderHandlers(state),\n ...schedulingHandlers(state),\n ...resultsHandlers(state),\n })\n this.service = createService({\n document,\n handlers,\n sqlite,\n namespace,\n now: options.now,\n notFound: () => jsonRes(404, { detail: \"Not Found\" }),\n onError: (error) => {\n if (error instanceof HttpError) return error.toResponse()\n throw error\n },\n before: (context) =>\n context.request.headers.has(\"x-vital-api-key\")\n ? undefined\n : jsonRes(401, { detail: \"Missing x-vital-api-key\" }),\n })\n this.app = this.service.app\n this.sqlite = this.service.sqlite\n this.labAccountConfig = options.labAccounts?.map(labAccountFromInput)\n if (options.corpus) this.installCorpus(options.corpus)\n else this.seedLabAccounts()\n state.geoMode = options.geo ?? (options.corpus ? \"corpus\" : \"synthetic\")\n }\n\n fetch(request: Request): Promise<Response> {\n return this.service.fetch(normalizePath(request))\n }\n\n async reset(): Promise<void> {\n await this.service.reset()\n if (this.corpus) {\n this.installCorpus(this.corpus)\n return\n }\n this.state.seedDefaultCatalog()\n this.seedLabAccounts()\n }\n\n /**\n * Install a sealed sandbox recording: seed the observation cache and replace the catalog,\n * labs, and lab accounts with the recording's exact values. Re-applied on `reset()`.\n */\n installCorpus(corpus: SealedCorpus): void {\n this.state.corpusObservations = observationsOf(corpus)\n if (corpus.catalog.labTests.length > 0) {\n this.state.replaceCatalog(corpus.catalog)\n }\n this.corpus = corpus\n this.state.coveredZips = coveredZipsOf(corpus)\n this.state.corpusLabel = corpusLabel(corpus)\n this.seedLabAccounts()\n }\n\n /**\n * Which lab accounts the ordering rules see, in order of precedence: the configured\n * ones, then a corpus's real accounts, then the built-in fixtures (which a corpus\n * recorded from a team with no accounts leaves in place).\n */\n private seedLabAccounts(): void {\n const recorded = (this.corpus?.labAccounts ?? [])\n .map(labAccountFromClientFacing)\n .filter((entry): entry is StoredLabAccount => entry !== undefined)\n this.state.replaceLabAccounts(\n this.labAccountConfig ?? (recorded.length > 0 ? recorded : [...TEAM_LAB_ACCOUNTS]),\n )\n }\n\n /** Replace the team's lab accounts; `undefined` restores the default. Kept across resets. */\n configureLabAccounts(accounts: readonly LabAccountInput[] | undefined): StoredLabAccount[] {\n this.labAccountConfig = accounts?.map(labAccountFromInput)\n this.seedLabAccounts()\n return this.state.listLabAccounts()\n }\n\n labAccounts(): StoredLabAccount[] {\n return this.state.listLabAccounts()\n }\n\n corpusInfo(): CorpusInfo | undefined {\n const corpus = this.corpus\n if (!corpus) return undefined\n return {\n label: corpusLabel(corpus),\n recordedAt: corpus.recordedAt,\n source: corpus.source,\n observations: Object.keys(corpus.observations).length,\n labTests: corpus.catalog.labTests.length,\n labAccounts: corpus.labAccounts.length,\n zips: this.state.coveredZips.size,\n }\n }\n\n get geoMode(): GeoMode {\n return this.state.geoMode\n }\n\n set geoMode(mode: GeoMode) {\n this.state.geoMode = mode\n }\n\n order(id: string): OrderRecord | undefined {\n return this.state.orders.get(id)\n }\n\n orders(): OrderRecord[] {\n return this.state.orders.list({ order: \"oldest\" }).map((entry) => entry.value)\n }\n\n /**\n * Put an order straight into a status (a full `<status>.<method>.<event>` value) and\n * publish the webhook a real transition would. `flags` takes the same keys as\n * `simulate_order`'s body: `interpretation`, `result_types`, `has_missing_results`.\n */\n transitionOrder(\n id: string,\n status: string,\n options: { now: () => number; flags?: Record<string, unknown> | null },\n ): OrderRecord | undefined {\n const order = this.state.orders.get(id)\n if (!order) return undefined\n forceOrderStatus(this.state, order, status, options.flags ?? null, { now: options.now })\n return this.state.orders.get(id)\n }\n\n /** Serve `fixture` as this order's results, replacing the generated ones. */\n installResultFixture(orderId: string, fixture: ResultFixture): boolean {\n const order = this.state.orders.get(orderId)\n if (!order) return false\n if (fixture.interpretation !== undefined) {\n order.interpretation = fixture.interpretation\n this.state.orders.update(orderId, order)\n }\n this.state.resultFixtures.insert(orderId, fixture)\n return true\n }\n\n resultFixture(orderId: string): ResultFixture | undefined {\n return this.state.resultFixtures.get(orderId)\n }\n\n seedFrom(source: SeedSource, observations?: SeedObservations): Promise<SeedReport> {\n return seedStateFrom(this.state, source, observations)\n }\n\n ensureLabTests(source: SeedSource, ids: readonly string[]): Promise<number> {\n return ensureLabTestsFrom(this.state, source, ids)\n }\n\n ensureOrders(source: SeedSource, ids: readonly string[]): Promise<number> {\n return ensureOrdersFrom(this.state, source, ids)\n }\n\n markUserDeleted(userId: string): void {\n this.state.users.delete(userId)\n this.state.deletedUsers.insert(userId, { user_id: userId })\n }\n\n webhookEvents(): JunctionWebhookEvent[] {\n return this.state.webhookEventsInOrder()\n }\n\n webhookDeliveryAttempts() {\n return this.state.webhookDeliveryAttemptsInOrder()\n }\n}\n\n/** Collapse `.`/`..` path segments the way the real server does before routing. */\nconst normalizePath = (request: Request): Request => {\n if (!request.url.includes(\"/./\") && !request.url.includes(\"/../\") && !/%2f/i.test(request.url)) {\n return request\n }\n const url = new URL(request.url)\n const pathname = url.pathname.replace(/%2f/gi, \"/\")\n const segments = pathname.split(\"/\")\n const out: string[] = []\n for (const segment of segments) {\n if (segment === \".\") continue\n if (segment === \"..\") {\n out.pop()\n continue\n }\n out.push(segment)\n }\n while (out.length > 1 && out[out.length - 1] === \"\") out.pop()\n const normalized = out.join(\"/\")\n if (normalized === url.pathname) return request\n const next = new URL(url)\n next.pathname = normalized\n return new Request(next, request)\n}\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,IAA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AAAA,EACnD;AAAA,EAEA,aAAa,QAAoB,KAAyC;AACxE,WAAO,aAAiB,KAAK,OAAO,QAAQ,GAAG;AAAA,EACjD;AAAA,EAEA,gBAAgB,QAAsB;AACpC,SAAK,MAAM,MAAM,OAAO,MAAM;AAC9B,SAAK,MAAM,aAAa,OAAO,QAAQ,EAAE,SAAS,OAAO,CAAC;AAAA,EAC5D;AAAA,EAEA,gBAAwC;AACtC,WAAO,KAAK,MAAM,qBAAqB;AAAA,EACzC;AAAA,EAEA,0BAA0B;AACxB,WAAO,KAAK,MAAM,+BAA+B;AAAA,EACnD;AACF;AAGA,IAAM,gBAAgB,CAACD,aAA8B;AACnD,MAAI,CAACA,SAAQ,IAAI,SAAS,KAAK,KAAK,CAACA,SAAQ,IAAI,SAAS,MAAM,KAAK,CAAC,OAAO,KAAKA,SAAQ,GAAG,GAAG;AAC9F,WAAOA;AAAA,EACT;AACA,QAAM,MAAM,IAAI,IAAIA,SAAQ,GAAG;AAC/B,QAAM,WAAW,IAAI,SAAS,QAAQ,SAAS,GAAG;AAClD,QAAM,WAAW,SAAS,MAAM,GAAG;AACnC,QAAM,MAAgB,CAAC;AACvB,aAAW,WAAW,UAAU;AAC9B,QAAI,YAAY,IAAK;AACrB,QAAI,YAAY,MAAM;AACpB,UAAI,IAAI;AACR;AAAA,IACF;AACA,QAAI,KAAK,OAAO;AAAA,EAClB;AACA,SAAO,IAAI,SAAS,KAAK,IAAI,IAAI,SAAS,CAAC,MAAM,GAAI,KAAI,IAAI;AAC7D,QAAM,aAAa,IAAI,KAAK,GAAG;AAC/B,MAAI,eAAe,IAAI,SAAU,QAAOA;AACxC,QAAM,OAAO,IAAI,IAAI,GAAG;AACxB,OAAK,WAAW;AAChB,SAAO,IAAI,QAAQ,MAAMA,QAAO;AAClC;",
|
|
6
|
-
"names": ["request", "document", "document", "isRecord", "document", "request", "document", "request", "token", "account", "isRecord", "seededRandom", "account", "notFound", "jsonObject", "isUuid", "uuidError", "details", "stateError", "responseOrder", "RESULT_TYPES", "INTERPRETATIONS", "clone", "readJson", "seedFrom", "notFound", "queryInt", "missingError", "user", "adminError", "isRecord", "request", "asRecord", "request", "account", "request", "createRuntime", "request", "account", "request", "seedFrom"]
|
|
7
|
-
}
|