@lpdjs/firestore-repo-service 2.6.45 → 2.6.47

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/servers/utils/security-headers.ts","../../../src/shared/date-config.ts","../../../src/servers/admin/index-url.ts","../../../src/servers/crud/handlers.ts","../../../src/servers/crud/openapi.ts","../../../src/servers/hono/types.ts","../../../src/servers/hono/errors.ts","../../../src/servers/hono/openapi.ts","../../../src/servers/hono/docs-auth.ts","../../../src/servers/hono/services.ts","../../../src/servers/hono/server.ts","../../../src/servers/crud/index.ts"],"names":["security_headers_exports","__export","DEFAULT_HTML_CSP","securityHeaders","opts","csp","frameOptions","referrerPolicy","cacheControl","_req","res","next","ADMIN_CDN","GSTATIC","init_security_headers","__esmMin","currentMode","getDateHandling","isTimestampLike","v","coerceToDate","value","Timestamp","d","maybeNormalize","RANGE_OPS","ARRAY_OPS","toIndexOrder","dir","collectionIdFromPath","path","segments","buildIndexUrl","projectId","collectionId","isGroup","filters","sort","fields","seen","buildExemptionUrl","lastDir","buildCompositeUrl","databaseId","resource","payload","pbString","pbInt","f","pbMessage","encodeIndexField","urlDbId","encoded","toBase64","extractIndexUrl","message","pbVarint","n","out","pbTag","fieldNumber","wireType","bytes","bin","b64","field","extractProjectId","ref","r","candidates","c","isMissingIndexError","err","fe","toQueryError","ctx","isIndex","indexUrl","colId","sendJson","data","status","sendSuccess","meta","sendError","error","sendQueryError","fallbackMessage","verbose","qe","_idChars","generateFirestoreId","id","randomBytes","i","byte","wrapDateSchemas","schema","def","typeName","z","shape","wrapped","k","inner","dflt","pickSchemaFields","systemKeys","picked","source","topLevel","validateData","partial","targetSchema","partialSchema","e","parseFilters","query","filterableFields","allowedFields","opMap","key","rawVal","val","match","op","opKey","parsedVal","parseValue","num","serializeCursor","snapshot","deserializeCursor","entry","cursor","cursorObj","docPath","docId","colRef","firestore","createCrudHandlers","registry","basePath","assertRule","rule","applyRowFilter","user","params","docs","filter","doc","userOf","getRepoEntry","repoName","parts","part","extractPathArgs","pathKey","fullPath","args","fetchDocById","getterName","getter","handleList","ctxFilters","ctxSort","pageSize","direction","orderBy","orderDir","selectStr","select","s","includes","inc","queryOptions","finalValue","fieldSchema","parsed","parsedArray","hasError","errorMessage","item","itemParsed","messages","result","responseData","handleQuery","body","w","validIncludes","allowed","invalid","group","o","handleGet","handleCreate","validation","customError","created","missingKeys","parentIds","handleUpdate","existingDoc","pathArgs","updated","handleDelete","handleOptions","handleBatch","batch","results","zodToJsonSchema","metadata","getOpenApiMetadata","schemaRef","name","errorResponse","description","successResponse","dataSchema","listResponse","itemSchema","paginationParams","filterParams","ops","opDescriptions","descDetail","queryBodySchema","buildPathsForEntry","base","modelSchemaName","createSchemaName","updateSchemaName","paths","tag","collectionPath","documentPath","idParam","capitalize","singularize","docOps","generateOpenAPISpec","options","title","version","servers","auth","schemas","allPaths","tags","modelName","createName","updateName","buildShape","fieldList","top","createShape","updateShape","entryPaths","securitySchemes","security","ValidationError","zodError","BadRequestError","OutputValidationError","formatZodIssues","defaultErrorResponse","extendZodWithOpenApi","DEFAULT_RESPONSE_DESCRIPTION","DEFAULT_ERROR_DESCRIPTION","defaultSource","method","resolveSuccessSchema","routeOutput","interceptor","normalizeErrorResponse","cfg","buildOpenApiDocument","routes","config","OpenAPIRegistry","scheme","route","joinPath","requestBody","buildRequestBody","requestQuery","buildQueryOrParam","requestParams","operationId","makeOperationId","successSchema","responses","code","convertExpressPathToOpenApi","OpenApiGeneratorV31","target","left","right","merged","cleaned","renderDocsHtml","specUrl","safeUrl","isDocsAuthExtension","als","AsyncLocalStorage","createRequestContextMiddleware","EMPTY_SERVICES","HonoServer","Hono","filterRoutes","globalMws","mw","getRequestListener","onRequest","httpsOptions","handler","interceptorConfig","validateOutput","middlewares","makeRouteHandler","interceptorFn","httpMethod","specPath","docsPath","fullSpecPath","fullDocsPath","guards","ext","authDir","dirOf","relativeSpecUrl","relativeUrlFromTo","isInterceptorConfig","api","idx","from","to","fromSegs","toSegs","common","ups","services","errorHandler","logger","inputSchema","outputSchema","servicesArg","applyErrorHandler","handled","callNext","raw","readPayload","checked","text","createCrudServer","repos","parseBody","securityHeadersOpt","resolvedSchema","orderableFields","mutableFields","createFields","fc","roles","role","parentKeys","pk","handlers","openapi","openapiOpts","_specCache","getSpec","server","base0","adapter","resolve","fakeReq"],"mappings":"gzBAAA,IAAAA,EAAAA,CAAA,GAAAC,EAAAA,CAAAD,EAAAA,CAAA,sBAAAE,EAAAA,CAAA,eAAA,CAAA,IAAAC,EAAAA,CAAAA,CAAAA,CAsEO,SAASA,EAAAA,CAAgBC,CAAAA,CAA+B,EAAC,CAAG,CACjE,IAAMC,CAAAA,CAAMD,CAAAA,CAAK,MAAQ,MAAA,CAAYF,EAAAA,CAAmBE,CAAAA,CAAK,GAAA,CACvDE,CAAAA,CAAeF,CAAAA,CAAK,eAAiB,MAAA,CAAY,MAAA,CAASA,EAAK,YAAA,CAC/DG,CAAAA,CACJH,EAAK,cAAA,GAAmB,MAAA,CAAY,aAAA,CAAgBA,CAAAA,CAAK,cAAA,CACrDI,CAAAA,CACJJ,EAAK,YAAA,GAAiB,MAAA,CAAY,mBAAA,CAAsBA,CAAAA,CAAK,YAAA,CAE/D,aAAcK,CAAAA,CAAcC,CAAAA,CAAaC,CAAAA,GAA8B,CACjE,OAAOD,CAAAA,EAAK,WAAc,UAAA,GAC5BA,CAAAA,CAAI,UAAU,wBAAA,CAA0B,SAAS,EAC7CJ,CAAAA,EAAcI,CAAAA,CAAI,SAAA,CAAU,iBAAA,CAAmBJ,CAAY,CAAA,CAC3DC,GAAgBG,CAAAA,CAAI,SAAA,CAAU,iBAAA,CAAmBH,CAAc,CAAA,CAC/DC,CAAAA,EAAcE,EAAI,SAAA,CAAU,eAAA,CAAiBF,CAAY,CAAA,CACzDH,CAAAA,EAAKK,CAAAA,CAAI,UAAU,yBAAA,CAA2BL,CAAG,GAEvD,MAAMM,CAAAA,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,MAAM,IAAI,OAAA,CAAeE,CAAAA,EAAY,CACnC,IAAMC,CAAAA,CAAUpT,EAAE,GAAA,CAAI,GAAA,CAKtBkT,EAAQE,CAAAA,CAJQ,CACd,SAAA,CAAW,CAACnR,CAAAA,CAAWpF,CAAAA,GAAcmD,EAAE,MAAA,CAAOiC,CAAAA,CAAGpF,CAAC,CAAA,CAClD,YAAA,CAAeoF,GAAcjC,CAAAA,CAAE,GAAA,CAAI,OAAA,CAAQ,MAAA,CAAOiC,CAAC,CACrD,EAC0B,IAAMkR,CAAAA,EAAS,EAC3C,CAAC,EACD,MAAM9W,CAAAA,GACR,CAAC,EACH,CAEA,IAAMkT,CAAAA,CAAUyD,CAAAA,CAAO,WAAA,CACvB,OAAAzD,CAAAA,CAAQ,IAAA,CAAOwD,EACXzD,CAAAA,GAAcC,CAAAA,CAAQ,YAAA,CAAeD,CAAAA,CAAAA,CAElCC,CACT","file":"index.js","sourcesContent":["/**\n * Default security-headers middleware for the bundled HTTP servers.\n *\n * Addresses issues #12 (no security headers / clickjacking / cache leakage)\n * and #13 (no CSP bounding the CDN origins loaded by the admin & login pages).\n *\n * The middleware is framework-agnostic: it only touches `res.setHeader`\n * (present on Node's `ServerResponse` and the shims used by the admin/CRUD\n * routers) and always calls `next()`.\n */\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyReq = any;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyRes = any;\ntype Next = () => void | Promise<void>;\n\n/** CDN/script origins the bundled admin UI and login page load from. */\nconst ADMIN_CDN = \"https://cdn.jsdelivr.net\";\nconst GSTATIC = \"https://www.gstatic.com\";\n\n/**\n * Reasonable default Content-Security-Policy for the bundled **HTML** pages\n * (admin UI + login). Allows the specific CDN origins the pages need and\n * forbids framing entirely. `'unsafe-inline'`/`'unsafe-eval'` are required by\n * the Tailwind browser build and the small inline bootstrap scripts.\n */\nexport const DEFAULT_HTML_CSP = [\n \"default-src 'self'\",\n `script-src 'self' 'unsafe-inline' 'unsafe-eval' ${ADMIN_CDN} ${GSTATIC}`,\n `style-src 'self' 'unsafe-inline' ${ADMIN_CDN}`,\n `connect-src 'self' ${GSTATIC} https://*.googleapis.com https://*.firebaseio.com https://identitytoolkit.googleapis.com`,\n \"img-src 'self' data:\",\n \"font-src 'self' data:\",\n \"frame-ancestors 'none'\",\n \"base-uri 'self'\",\n \"form-action 'self'\",\n].join(\"; \");\n\nexport interface SecurityHeadersOptions {\n /**\n * Content-Security-Policy value. Pass a string to override, or `false` to\n * omit the header entirely. Defaults to {@link DEFAULT_HTML_CSP} for HTML\n * servers (admin/login) and is omitted for pure JSON APIs unless provided.\n */\n csp?: string | false;\n /**\n * `X-Frame-Options` value. Default `\"DENY\"`. Pass `false` to omit (e.g. when\n * the app must be embedded in a trusted iframe — prefer a CSP\n * `frame-ancestors` allowlist instead).\n */\n frameOptions?: string | false;\n /** `Referrer-Policy` value. Default `\"no-referrer\"`. */\n referrerPolicy?: string | false;\n /**\n * `Cache-Control` value. Default `\"private, no-store\"` to keep private data\n * out of shared proxy caches. Pass `false` to leave caching to handlers.\n */\n cacheControl?: string | false;\n}\n\n/**\n * Build a middleware that sets a baseline of security response headers.\n *\n * @example\n * ```ts\n * router.use(securityHeaders()); // HTML-safe defaults\n * router.use(securityHeaders({ csp: false })); // JSON API (no CSP)\n * ```\n */\nexport function securityHeaders(opts: SecurityHeadersOptions = {}) {\n const csp = opts.csp === undefined ? DEFAULT_HTML_CSP : opts.csp;\n const frameOptions = opts.frameOptions === undefined ? \"DENY\" : opts.frameOptions;\n const referrerPolicy =\n opts.referrerPolicy === undefined ? \"no-referrer\" : opts.referrerPolicy;\n const cacheControl =\n opts.cacheControl === undefined ? \"private, no-store\" : opts.cacheControl;\n\n return async (_req: AnyReq, res: AnyRes, next: Next): Promise<void> => {\n if (typeof res?.setHeader === \"function\") {\n res.setHeader(\"X-Content-Type-Options\", \"nosniff\");\n if (frameOptions) res.setHeader(\"X-Frame-Options\", frameOptions);\n if (referrerPolicy) res.setHeader(\"Referrer-Policy\", referrerPolicy);\n if (cacheControl) res.setHeader(\"Cache-Control\", cacheControl);\n if (csp) res.setHeader(\"Content-Security-Policy\", csp);\n }\n await next();\n };\n}\n","import { Timestamp } from \"firebase-admin/firestore\";\n\nexport type DateHandlingMode = \"preserve\" | \"normalize\";\n\nlet currentMode: DateHandlingMode = \"preserve\";\n\nexport function setDateHandling(mode: DateHandlingMode): void {\n currentMode = mode;\n}\n\nexport function getDateHandling(): DateHandlingMode {\n return currentMode;\n}\n\nfunction isTimestampLike(\n v: unknown,\n): v is { _seconds: number; _nanoseconds: number } {\n return (\n typeof v === \"object\" &&\n v !== null &&\n typeof (v as { _seconds?: unknown })._seconds === \"number\" &&\n typeof (v as { _nanoseconds?: unknown })._nanoseconds === \"number\"\n );\n}\n\nexport function coerceToDate(value: unknown): Date | null {\n if (value === null || value === undefined) return null;\n if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value;\n if (value instanceof Timestamp) return value.toDate();\n if (isTimestampLike(value)) {\n return new Date(\n value._seconds * 1000 + Math.floor(value._nanoseconds / 1e6),\n );\n }\n if (typeof value === \"string\") {\n const d = new Date(value);\n return Number.isNaN(d.getTime()) ? null : d;\n }\n if (typeof value === \"number\") {\n const d = new Date(value);\n return Number.isNaN(d.getTime()) ? null : d;\n }\n return null;\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n if (typeof v !== \"object\" || v === null) return false;\n const proto = Object.getPrototypeOf(v);\n return proto === Object.prototype || proto === null;\n}\n\nexport function normalizeTimestamps<T>(value: T): T {\n if (value instanceof Timestamp) return value.toDate() as unknown as T;\n if (Array.isArray(value)) {\n return value.map((v) => normalizeTimestamps(v)) as unknown as T;\n }\n if (isPlainObject(value)) {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) {\n out[k] = normalizeTimestamps(v);\n }\n return out as unknown as T;\n }\n return value;\n}\n\nexport function maybeNormalize<T>(value: T): T {\n return currentMode === \"normalize\" ? normalizeTimestamps(value) : value;\n}\n","/**\n * Generates a Firebase Console URL to create a composite index OR a\n * single-field index exemption.\n *\n * When Firestore throws FAILED_PRECONDITION (code 9) for missing indexes,\n * the error message sometimes includes a creation link (regular collections)\n * but often does NOT include it (collection groups). This utility builds the\n * link from the query context so the admin UI can always present it.\n *\n * Two URL shapes are produced depending on the query:\n *\n * - **Composite index** (≥ 2 indexed fields, or any COLLECTION-scope multi-field\n * query). Encoded as a JSON `create_composite=` parameter under\n * `/v1/r/project/{p}/firestore/indexes`.\n *\n * - **Single-field exemption** (exactly one indexed field on a COLLECTION_GROUP\n * query — Firestore disables single-field collection-group indexes by\n * default and requires an explicit exemption). Encoded as a base64\n * protobuf `create_exemption=` parameter under\n * `/project/{p}/firestore/databases/-default-/indexes/automatic`.\n */\n\nimport type {\n FilterState,\n QueryError,\n SortState,\n WhereOp,\n} from \"./components/types\";\n\n// ── Types ────────────────────────────────────────────────────────────────────\n\ninterface IndexField {\n fieldPath: string;\n order?: \"ASCENDING\" | \"DESCENDING\";\n arrayConfig?: \"CONTAINS\";\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────\n\nconst RANGE_OPS = new Set<WhereOp>([\"<\", \"<=\", \">\", \">=\", \"!=\"]);\nconst ARRAY_OPS = new Set<WhereOp>([\"array-contains\", \"array-contains-any\"]);\n\nfunction toIndexOrder(dir?: \"asc\" | \"desc\"): \"ASCENDING\" | \"DESCENDING\" {\n return dir === \"desc\" ? \"DESCENDING\" : \"ASCENDING\";\n}\n\n/**\n * Extract the collection ID (last path segment) from a Firestore path.\n * e.g. \"posts/{postId}/comments\" → \"comments\"\n */\nexport function collectionIdFromPath(path: string): string {\n const segments = path.split(\"/\").filter(Boolean);\n return segments[segments.length - 1] ?? path;\n}\n\n// ── Main ─────────────────────────────────────────────────────────────────────\n\n/**\n * Build a Firebase Console URL that pre-fills the composite-index creation form.\n *\n * @param projectId - GCP project ID (e.g. \"firestore-repo-services\")\n * @param collectionId - Firestore collection ID (e.g. \"posts\", \"comments\")\n * @param isGroup - Whether this is a collection group query\n * @param filters - Active filter states from the admin UI\n * @param sort - Active sort state (optional)\n * @returns - Full HTTPS URL to the Firebase Console index wizard\n */\nexport function buildIndexUrl(\n projectId: string,\n collectionId: string,\n isGroup: boolean,\n filters: FilterState[],\n sort?: SortState,\n): string {\n const fields: IndexField[] = [];\n const seen = new Set<string>();\n\n // 1. Equality filters first (order doesn't matter for equality)\n for (const f of filters) {\n if (f.op === \"==\" || f.op === \"in\" || f.op === \"not-in\") {\n if (seen.has(f.field)) continue;\n seen.add(f.field);\n fields.push({ fieldPath: f.field, order: \"ASCENDING\" });\n }\n }\n\n // 2. Array operators\n for (const f of filters) {\n if (ARRAY_OPS.has(f.op)) {\n if (seen.has(f.field)) continue;\n seen.add(f.field);\n fields.push({ fieldPath: f.field, arrayConfig: \"CONTAINS\" });\n }\n }\n\n // 3. Range / inequality filters\n for (const f of filters) {\n if (RANGE_OPS.has(f.op)) {\n if (seen.has(f.field)) continue;\n seen.add(f.field);\n // Use the sort direction if the range field matches the orderBy field\n const dir =\n sort?.field === f.field ? toIndexOrder(sort.dir) : \"ASCENDING\";\n fields.push({ fieldPath: f.field, order: dir });\n }\n }\n\n // 4. OrderBy fields not already covered by filters\n if (sort && !seen.has(sort.field)) {\n fields.push({ fieldPath: sort.field, order: toIndexOrder(sort.dir) });\n }\n\n // ── Single-field collection-group exemption ──────────────────────────────\n // Firestore disables single-field collection-group indexes by default; you\n // must create an explicit \"field exemption\". The Firebase Console wizard\n // for that uses a totally different URL (`create_exemption=`) with its own\n // protobuf shape — see buildExemptionUrl below.\n if (fields.length === 1 && isGroup) {\n return buildExemptionUrl(projectId, collectionId, fields[0]!);\n }\n\n // ── Composite index ──────────────────────────────────────────────────────\n // Firebase Console encodes composite indexes as a base64 protobuf payload\n // under `create_composite=`. Every composite index implicitly ends with\n // `__name__` as a tie-breaker, so we always append it (matches what the\n // Console itself produces).\n const lastDir =\n sort && fields.some((f) => f.fieldPath === sort.field)\n ? toIndexOrder(sort.dir)\n : \"ASCENDING\";\n fields.push({ fieldPath: \"__name__\", order: lastDir });\n\n return buildCompositeUrl(projectId, collectionId, isGroup, fields);\n}\n\n/**\n * Build a Firebase Console URL that pre-fills the composite index creation\n * form for either a regular collection or a collection-group query.\n *\n * The URL uses a base64-encoded protobuf payload (the same shape the Console\n * itself produces when you click \"Add index\" in the UI). Schema:\n *\n * message CompositeIndex {\n * string resource_path = 1; // projects/.../collectionGroups/{cg}/indexes/_\n * int32 query_scope = 2; // 1 = COLLECTION, 2 = COLLECTION_GROUP\n * repeated IndexField fields = 3;\n * }\n */\nexport function buildCompositeUrl(\n projectId: string,\n collectionId: string,\n isGroup: boolean,\n fields: IndexField[],\n databaseId: string = \"(default)\",\n): string {\n const resource = `projects/${projectId}/databases/${databaseId}/collectionGroups/${collectionId}/indexes/_`;\n\n const payload: number[] = [\n ...pbString(1, resource),\n ...pbInt(2, isGroup ? 2 : 1),\n ];\n for (const f of fields) {\n payload.push(...pbMessage(3, encodeIndexField(f)));\n }\n\n const urlDbId = databaseId === \"(default)\" ? \"-default-\" : databaseId;\n const encoded = encodeURIComponent(toBase64(payload));\n return `https://console.firebase.google.com/project/${projectId}/firestore/databases/${urlDbId}/indexes?create_composite=${encoded}`;\n}\n\n/**\n * Try to extract an index-creation URL from a Firestore error message.\n * Returns `undefined` if no URL is found.\n */\nexport function extractIndexUrl(message: string): string | undefined {\n const match = message.match(\n /https:\\/\\/console\\.firebase\\.google\\.com[^\\s)\"]*/,\n );\n return match?.[0];\n}\n\n// ── Single-field exemption URL (collection-group) ────────────────────────────\n\n/**\n * Minimal protobuf encoder for the field-exemption payload used by the\n * Firebase Console URL `?create_exemption=…`.\n *\n * Wire format (subset):\n * tag = (field_number << 3) | wire_type\n * wire types: 0 = varint, 2 = length-delimited\n *\n * Schema we encode (reverse-engineered from real Firebase Console URLs):\n * message FieldExemption {\n * string resource_path = 1; // projects/.../fields/{field}\n * int32 query_scope = 2; // 1 = COLLECTION, 2 = COLLECTION_GROUP\n * IndexConfig index = 3;\n * }\n * message IndexConfig {\n * string field_path = 1;\n * int32 order = 2; // 1 = ASCENDING, 2 = DESCENDING\n * int32 array_config = 3; // 1 = CONTAINS (mutually exclusive with order)\n * }\n */\nfunction pbVarint(n: number): number[] {\n const out: number[] = [];\n let v = n >>> 0;\n while (v >= 0x80) {\n out.push((v & 0x7f) | 0x80);\n v >>>= 7;\n }\n out.push(v & 0x7f);\n return out;\n}\n\nfunction pbTag(fieldNumber: number, wireType: 0 | 2): number {\n return (fieldNumber << 3) | wireType;\n}\n\nfunction pbString(fieldNumber: number, value: string): number[] {\n const bytes = Array.from(new TextEncoder().encode(value));\n return [pbTag(fieldNumber, 2), ...pbVarint(bytes.length), ...bytes];\n}\n\nfunction pbInt(fieldNumber: number, value: number): number[] {\n return [pbTag(fieldNumber, 0), ...pbVarint(value)];\n}\n\nfunction pbMessage(fieldNumber: number, payload: number[]): number[] {\n return [pbTag(fieldNumber, 2), ...pbVarint(payload.length), ...payload];\n}\n\n/** Encode an IndexField submessage: { field_path:1, order:2 OR array_config:3 } */\nfunction encodeIndexField(f: IndexField): number[] {\n const out: number[] = [...pbString(1, f.fieldPath)];\n if (f.arrayConfig === \"CONTAINS\") {\n out.push(...pbInt(3, 1));\n } else {\n out.push(...pbInt(2, f.order === \"DESCENDING\" ? 2 : 1));\n }\n return out;\n}\n\nfunction toBase64(bytes: number[]): string {\n // Standard base64 (no padding) — matches what Firebase Console produces.\n // Use Buffer when available (Node), otherwise fall back to btoa.\n const bin = String.fromCharCode(...bytes);\n let b64: string;\n if (typeof Buffer !== \"undefined\") {\n b64 = Buffer.from(bytes).toString(\"base64\");\n } else if (typeof btoa !== \"undefined\") {\n b64 = btoa(bin);\n } else {\n throw new Error(\"No base64 encoder available\");\n }\n return b64.replace(/=+$/, \"\");\n}\n\n/**\n * Build a Firebase Console URL that pre-fills the single-field index\n * exemption form for a collection-group query.\n */\nexport function buildExemptionUrl(\n projectId: string,\n collectionId: string,\n field: IndexField,\n databaseId: string = \"(default)\",\n): string {\n const resource = `projects/${projectId}/databases/${databaseId}/collectionGroups/${collectionId}/fields/${field.fieldPath}`;\n\n const payload: number[] = [\n ...pbString(1, resource),\n ...pbInt(2, 2), // COLLECTION_GROUP\n ...pbMessage(3, encodeIndexField(field)),\n ];\n\n // Database ID for the URL path: \"(default)\" → \"-default-\",\n // any other ID is used as-is (Firebase Console uses the bare ID).\n const urlDbId = databaseId === \"(default)\" ? \"-default-\" : databaseId;\n\n // create_exemption is base64 (URL-safe characters only — `+` and `/` are\n // valid in query string values per RFC, and Firebase accepts them, but we\n // URL-encode just to be safe).\n const encoded = encodeURIComponent(toBase64(payload));\n return `https://console.firebase.google.com/project/${projectId}/firestore/databases/${urlDbId}/indexes/automatic?create_exemption=${encoded}`;\n}\n\n// ── Project ID extraction ────────────────────────────────────────────────────\n\n/**\n * Robustly extract the GCP project ID from a Firestore reference.\n * Falls back through several known locations across firebase-admin versions\n * and finally to standard environment variables.\n */\nexport function extractProjectId(ref: unknown): string | undefined {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const r = ref as any;\n const candidates: unknown[] = [\n r?.firestore?.projectId,\n r?.firestore?.app?.options?.projectId,\n r?.firestore?._settings?.projectId,\n r?.firestore?.databaseId?.projectId,\n r?._firestore?.projectId,\n ];\n for (const c of candidates) {\n if (typeof c === \"string\" && c.length > 0) return c;\n }\n const env =\n process.env[\"GCLOUD_PROJECT\"] ||\n process.env[\"GOOGLE_CLOUD_PROJECT\"] ||\n process.env[\"FIREBASE_PROJECT_ID\"];\n return env || undefined;\n}\n\n// ── Centralized error → QueryError conversion ────────────────────────────────\n\n/**\n * Context required to build a fallback index URL when Firestore does not\n * include one in its error (typical for collection-group queries).\n */\nexport interface QueryErrorContext {\n /** Repository ref (CollectionReference / Query) used to extract project id */\n ref: unknown;\n /** Firestore collection path of the repo (e.g. \"posts/{postId}/comments\") */\n path: string;\n /** Whether the repo is a collection-group */\n isGroup: boolean;\n /** Active where filters at the time of the failed query */\n filters: FilterState[];\n /** Active orderBy state at the time of the failed query (if any) */\n sort?: SortState;\n}\n\n/**\n * Detect whether an unknown error thrown by Firestore is a missing-index\n * (`FAILED_PRECONDITION` / code 9) error.\n */\nexport function isMissingIndexError(err: unknown): boolean {\n const fe = err as { code?: number; message?: string } | null | undefined;\n if (!fe) return false;\n if (fe.code === 9) return true;\n return typeof fe.message === \"string\"\n ? fe.message.includes(\"requires an index\")\n : false;\n}\n\n/**\n * Convert a Firestore error into a typed `QueryError` with a guaranteed\n * `indexUrl` for missing-index cases (extracted from the message when\n * present, otherwise rebuilt from the query context — necessary for\n * collection-group queries where the SDK omits the link).\n *\n * Returns `null` when `err` is falsy.\n */\nexport function toQueryError(\n err: unknown,\n ctx: QueryErrorContext,\n): QueryError {\n const fe = (err ?? {}) as { code?: number; message?: string };\n const isIndex = isMissingIndexError(err);\n\n let indexUrl: string | undefined;\n if (isIndex) {\n indexUrl = fe.message ? extractIndexUrl(fe.message) : undefined;\n if (!indexUrl) {\n const projectId = extractProjectId(ctx.ref);\n if (projectId) {\n const colId = collectionIdFromPath(ctx.path);\n indexUrl = buildIndexUrl(\n projectId,\n colId,\n ctx.isGroup,\n ctx.filters,\n ctx.sort,\n );\n }\n }\n }\n\n return {\n type: isIndex ? \"index\" : \"error\",\n message: isIndex\n ? \"This query requires a composite index that does not exist yet.\"\n : (fe.message ?? \"Query failed\"),\n indexUrl,\n };\n}\n","/**\n * HTTP route handlers for the CRUD API server.\n *\n * Routes:\n * GET /:repoName → list documents (paginated)\n * GET /:repoName/:id → get single document\n * POST /:repoName → create document\n * PUT /:repoName/:id → update document (full)\n * PATCH /:repoName/:id → update document (partial)\n * DELETE /:repoName/:id → delete document\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { z } from \"zod\";\nimport {\n coerceToDate,\n getDateHandling,\n maybeNormalize,\n} from \"../../shared/date-config\";\nimport { toQueryError, type QueryErrorContext } from \"../admin/index-url\";\nimport type {\n ApiResponse,\n CrudRepoEntry,\n CrudRepoRegistry,\n ListResponseData,\n QueryRequestBody,\n} from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Response helpers\n// ---------------------------------------------------------------------------\n\nfunction sendJson<T>(c: any, data: ApiResponse<T>, status = 200) {\n const payload = maybeNormalize(data);\n return c.json(payload, status as any);\n}\n\nfunction sendSuccess<T>(\n c: any,\n data: T,\n meta?: ApiResponse[\"meta\"],\n status = 200,\n) {\n return sendJson(c, { success: true, data, meta }, status);\n}\n\nfunction sendError(c: any, error: string, status = 400) {\n return sendJson(c, { success: false, error }, status);\n}\n\n/**\n * Send a structured error response. When the underlying Firestore error is a\n * missing-index (`FAILED_PRECONDITION` / code 9), include `errorType: \"index\"`\n * and an `indexUrl` pointing to the Firebase Console index-creation wizard —\n * crucial for collection-group queries where the SDK omits the link.\n */\nfunction sendQueryError(\n c: any,\n err: unknown,\n ctx: QueryErrorContext,\n fallbackMessage: string,\n verbose: boolean,\n) {\n const qe = toQueryError(err, ctx);\n const isIndex = qe.type === \"index\";\n const status = isIndex ? 424 : 500;\n const message = isIndex\n ? qe.message\n : verbose && err instanceof Error\n ? err.message\n : fallbackMessage;\n const payload: ApiResponse = { success: false, error: message };\n if (isIndex) {\n payload.errorType = \"index\";\n if (qe.indexUrl) payload.indexUrl = qe.indexUrl;\n }\n return sendJson(c, payload, status);\n}\n\n// ---------------------------------------------------------------------------\n// ID generation\n// ---------------------------------------------------------------------------\n\nconst _idChars =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n\n/**\n * Generate a random 20-char alphanumeric ID matching Firestore's native format.\n *\n * Uses a CSPRNG (`crypto.randomBytes`) — not `Math.random()` — so generated\n * ids are unpredictable, matching Firestore's own `doc().id`. Rejection\n * sampling (dropping the biased tail `>= 62*4`) keeps the distribution uniform\n * across the 62-char alphabet.\n */\nfunction generateFirestoreId(): string {\n let id = \"\";\n while (id.length < 20) {\n const bytes = randomBytes(20);\n for (let i = 0; i < bytes.length && id.length < 20; i++) {\n const byte = bytes[i]!;\n if (byte >= _idChars.length * 4) continue; // drop biased tail (248..255)\n id += _idChars.charAt(byte % _idChars.length);\n }\n }\n return id;\n}\n\n// ---------------------------------------------------------------------------\n// Zod schema helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Recursively wrap z.date() with z.preprocess(coerceToDate) so that ISO strings,\n * Firestore Timestamps and {_seconds,_nanoseconds} payloads are accepted as input.\n * Only invoked when global date handling mode is \"normalize\".\n */\nfunction wrapDateSchemas(schema: z.ZodType): z.ZodType {\n const def = (schema as any)._def ?? (schema as any).def;\n if (!def) return schema;\n const typeName = def.typeName ?? def.type;\n\n if (typeName === \"ZodDate\" || typeName === \"date\") {\n return z.preprocess((v) => coerceToDate(v) ?? v, schema as z.ZodDate);\n }\n if (typeName === \"ZodObject\" || typeName === \"object\") {\n const shape = (schema as z.ZodObject<any>).shape;\n const wrapped: Record<string, z.ZodType> = {};\n for (const [k, v] of Object.entries(shape)) {\n wrapped[k] = wrapDateSchemas(v as z.ZodType);\n }\n return z.object(wrapped);\n }\n if (typeName === \"ZodArray\" || typeName === \"array\") {\n const inner = def.element ?? def.type;\n if (inner) return z.array(wrapDateSchemas(inner));\n }\n if (typeName === \"ZodOptional\" || typeName === \"optional\") {\n const inner = def.innerType;\n if (inner) return wrapDateSchemas(inner).optional();\n }\n if (typeName === \"ZodNullable\" || typeName === \"nullable\") {\n const inner = def.innerType;\n if (inner) return wrapDateSchemas(inner).nullable();\n }\n if (typeName === \"ZodDefault\" || typeName === \"default\") {\n const inner = def.innerType;\n const dflt = def.defaultValue;\n if (inner) {\n const wrapped = wrapDateSchemas(inner);\n return typeof dflt === \"function\"\n ? wrapped.default(dflt())\n : wrapped.default(dflt);\n }\n }\n return schema;\n}\n\n/**\n * Pick only specified fields from a Zod schema, always excluding system-managed keys.\n *\n * - `fields` undefined or empty → all schema fields minus systemKeys\n * - `fields` with values → only those fields, minus systemKeys\n *\n * Security contract (issue #17): the returned schema is rebuilt from scratch\n * with `z.object(...)`, which **strips** any key not explicitly listed —\n * even when the user's root schema was declared `.passthrough()`. This\n * guarantees attacker-supplied keys (e.g. `__sync_version`, forged\n * timestamps, arbitrary metadata) can never reach Firestore via create /\n * update payloads. System keys are removed here too, so they cannot be\n * client-overridden.\n *\n * Note: a field explicitly declared as `z.any()` / `z.record(z.unknown())`\n * in the user schema is still accepted as-is by design — document such\n * free-form fields carefully, as their contents are persisted verbatim.\n */\nfunction pickSchemaFields(\n schema: z.ZodObject<any>,\n fields: string[] | undefined,\n systemKeys: string[] = [],\n): z.ZodObject<any> {\n const shape = schema.shape;\n const picked: Record<string, z.ZodType> = {};\n\n const source = fields && fields.length > 0 ? fields : Object.keys(shape);\n\n for (const field of source) {\n if (systemKeys.includes(field)) continue;\n const topLevel = field.split(\".\")[0];\n if (topLevel && shape[topLevel]) {\n picked[topLevel] = shape[topLevel]!;\n }\n }\n\n return z.object(picked);\n}\n\n/**\n * Validate data against schema and return parsed result or error.\n */\nfunction validateData(\n schema: z.ZodObject<any>,\n data: unknown,\n fields: string[] | undefined,\n partial = false,\n systemKeys: string[] = [],\n):\n | { success: true; data: Record<string, unknown> }\n | { success: false; error: string } {\n try {\n const targetSchema = pickSchemaFields(schema, fields, systemKeys);\n const partialSchema = partial ? targetSchema.partial() : targetSchema;\n const finalSchema =\n getDateHandling() === \"normalize\"\n ? (wrapDateSchemas(partialSchema) as z.ZodObject<any>)\n : partialSchema;\n const parsed = finalSchema.parse(data);\n return { success: true, data: parsed as Record<string, unknown> };\n } catch (err) {\n if (err instanceof z.ZodError) {\n const messages = err.issues.map(\n (e) => `${e.path.join(\".\")}: ${e.message}`,\n );\n return {\n success: false,\n error: `Validation failed: ${messages.join(\", \")}`,\n };\n }\n return { success: false, error: \"Validation failed\" };\n }\n}\n\n// ---------------------------------------------------------------------------\n// Filter parsing\n// ---------------------------------------------------------------------------\n\ntype WhereOp =\n | \"==\"\n | \"!=\"\n | \"<\"\n | \"<=\"\n | \">\"\n | \">=\"\n | \"in\"\n | \"not-in\"\n | \"array-contains\"\n | \"array-contains-any\";\n\ninterface ParsedFilter {\n field: string;\n op: WhereOp;\n value: unknown;\n}\n\n/**\n * Parse query params into filter conditions.\n * Supports:\n * - field=value → field == value\n * - field__op=value → field op value (e.g., status__ne=draft → status != draft)\n * - field__in=a,b,c → field in [a, b, c]\n */\nfunction parseFilters(\n query: Record<string, string | string[] | undefined>,\n filterableFields: string[] | undefined,\n): ParsedFilter[] {\n const filters: ParsedFilter[] = [];\n const allowedFields = filterableFields ? new Set(filterableFields) : null;\n\n const opMap: Record<string, WhereOp> = {\n eq: \"==\",\n ne: \"!=\",\n lt: \"<\",\n lte: \"<=\",\n gt: \">\",\n gte: \">=\",\n in: \"in\",\n nin: \"not-in\",\n contains: \"array-contains\",\n containsAny: \"array-contains-any\",\n };\n\n for (const [key, rawVal] of Object.entries(query)) {\n if (rawVal === undefined) continue;\n\n // Skip pagination/meta params\n if (\n [\"cursor\", \"limit\", \"pageSize\", \"orderBy\", \"orderDir\", \"select\"].includes(\n key,\n )\n )\n continue;\n\n const val = Array.isArray(rawVal) ? rawVal[0] : rawVal;\n if (val === undefined || val === \"\") continue;\n\n // Parse field__op format\n const match = key.match(/^(\\w+)__(\\w+)$/);\n let field: string;\n let op: WhereOp = \"==\";\n\n if (match && match[1] && match[2]) {\n field = match[1];\n const opKey = match[2];\n if (opMap[opKey]) {\n op = opMap[opKey];\n } else {\n continue; // Unknown operator, skip\n }\n } else if (!match) {\n field = key;\n } else {\n continue; // Invalid match\n }\n\n // Check if field is filterable\n if (allowedFields && !allowedFields.has(field)) continue;\n\n // Parse value\n let parsedVal: unknown = val;\n\n // Handle \"in\" and \"not-in\" operators (comma-separated)\n if (op === \"in\" || op === \"not-in\" || op === \"array-contains-any\") {\n parsedVal = val.split(\",\").map((v) => parseValue(v.trim()));\n } else {\n parsedVal = parseValue(val);\n }\n\n filters.push({ field, op, value: parsedVal });\n }\n\n return filters;\n}\n\n/**\n * Parse a string value into appropriate type.\n */\nfunction parseValue(val: string): unknown {\n // Boolean\n if (val === \"true\") return true;\n if (val === \"false\") return false;\n if (val === \"null\" || val === \"__null__\") return null;\n\n // Number\n const num = Number(val);\n if (!isNaN(num) && val !== \"\") return num;\n\n // String\n return val;\n}\n\n// ---------------------------------------------------------------------------\n// Cursor serialization helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Serialize a Firestore DocumentSnapshot to a JSON-safe cursor object.\n */\nfunction serializeCursor(\n snapshot: import(\"firebase-admin/firestore\").DocumentSnapshot | undefined,\n): Record<string, unknown> | null {\n if (!snapshot) return null;\n return {\n docId: snapshot.id,\n docPath: snapshot.ref?.path ?? undefined,\n };\n}\n\n/**\n * Deserialize a cursor object back to a DocumentSnapshot.\n * Fetches the document from Firestore to get the actual snapshot.\n * Supports root collections and subcollections/collection groups via full docPath.\n */\nasync function deserializeCursor(\n entry: CrudRepoEntry,\n cursor: unknown,\n): Promise<import(\"firebase-admin/firestore\").DocumentSnapshot | undefined> {\n if (!cursor) return undefined;\n\n let cursorObj: Record<string, unknown> | undefined;\n if (typeof cursor === \"string\") {\n try {\n cursorObj = JSON.parse(cursor);\n } catch {\n cursorObj = cursor.includes(\"/\")\n ? { docPath: cursor }\n : { docId: cursor };\n }\n } else if (typeof cursor === \"object\") {\n cursorObj = cursor as Record<string, unknown>;\n }\n\n if (!cursorObj) return undefined;\n\n const docPath =\n typeof cursorObj.docPath === \"string\" ? cursorObj.docPath : undefined;\n const docId =\n typeof cursorObj.docId === \"string\" ? cursorObj.docId : undefined;\n\n try {\n const colRef = entry.repo.ref as any;\n const firestore = colRef?.firestore;\n\n // 1. If docPath is available and firestore instance exists, get doc directly by full path\n if (docPath && firestore && typeof firestore.doc === \"function\") {\n const snapshot = await firestore.doc(docPath).get();\n if (snapshot.exists) return snapshot;\n }\n\n // 2. If docId is a full path (e.g. \"users/u1/comments/c1\"), get doc by full path\n if (docId && docId.includes(\"/\") && firestore && typeof firestore.doc === \"function\") {\n const snapshot = await firestore.doc(docId).get();\n if (snapshot.exists) return snapshot;\n }\n\n // 3. Root collection fallback (colRef.doc exists for CollectionReference)\n if (docId && typeof colRef.doc === \"function\") {\n const snapshot = await colRef.doc(docId).get();\n if (snapshot.exists) return snapshot;\n }\n\n return undefined;\n } catch {\n return undefined;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Handlers factory\n// ---------------------------------------------------------------------------\n\nexport function createCrudHandlers(\n registry: CrudRepoRegistry,\n basePath: string,\n verbose: boolean,\n) {\n // ── Authorization helpers ───────────────────────────────────────────────\n /**\n * Default-deny gate: when the server has `auth` configured, reject any\n * operation without an explicit rule. When `auth` is absent, rules are\n * ignored entirely (open API).\n */\n async function assertRule<TCtx>(\n c: any,\n entry: CrudRepoEntry,\n op: keyof NonNullable<CrudRepoEntry[\"rules\"]>,\n ctx: TCtx,\n ): Promise<boolean> {\n if (!entry.rules) return true;\n const rule = entry.rules?.[op] as\n | ((c: TCtx) => boolean | Promise<boolean>)\n | undefined;\n if (!rule) {\n sendError(c, `Operation \"${op}\" is not allowed for this repository`, 403);\n return false;\n }\n try {\n const ok = await rule(ctx);\n if (!ok) {\n return sendError(c, \"Forbidden\", 403);\n return false;\n }\n return true;\n } catch (err) {\n const message =\n verbose && err instanceof Error ? err.message : \"Forbidden\";\n return sendError(c, message, 403);\n return false;\n }\n }\n\n /** Apply `rules.filter` to every doc in a list; returns the filtered slice. */\n async function applyRowFilter<T extends Record<string, unknown>>(\n entry: CrudRepoEntry,\n user: any,\n params: Record<string, string>,\n docs: T[],\n ): Promise<T[]> {\n if (!entry.rules) return docs;\n const filter = entry.rules?.filter as\n | ((c: {\n user: any;\n doc: T;\n params: Record<string, string>;\n }) => boolean | Promise<boolean>)\n | undefined;\n if (!filter) return docs;\n const out: T[] = [];\n for (const doc of docs) {\n try {\n if (await filter({ user, doc, params })) out.push(doc);\n } catch {\n // exclude on error (fail closed)\n }\n }\n return out;\n }\n\n /** Pull the authenticated user from the request (may be undefined when auth is off). */\n function userOf(c: any): any {\n return c.get(\"user\") ?? c.get(\"docsUser\") ?? null;\n }\n\n // ── Helper to get repo entry ────────────────────────────────────────────\n function getRepoEntry(\n repoName: string | undefined,\n c: any,\n ): CrudRepoEntry | null {\n if (!repoName) {\n const parts = c.req.path.split(\"/\");\n for (const part of parts) {\n if (registry[part]) {\n repoName = part;\n break;\n }\n }\n }\n if (!repoName || !registry[repoName]) {\n return null;\n }\n return registry[repoName] ?? null;\n }\n\n /**\n * Extract Firestore document path args from a document's stored path.\n * e.g. \"posts/abc/comments/xyz\" → [\"abc\", \"xyz\"] (the doc-ID segments).\n */\n function extractPathArgs(\n doc: Record<string, unknown>,\n pathKey?: string,\n ): string[] | undefined {\n if (!pathKey) return undefined;\n const fullPath = doc[pathKey];\n if (typeof fullPath !== \"string\" || !fullPath) return undefined;\n const segments = fullPath.split(\"/\").filter(Boolean);\n const args: string[] = [];\n for (let i = 1; i < segments.length; i += 2) {\n args.push(segments[i]!);\n }\n return args.length > 0 ? args : undefined;\n }\n\n /**\n * Fetch a single document by its documentKey, with fallback to query\n * for collection-group repos where direct documentRef may fail.\n */\n async function fetchDocById(\n entry: CrudRepoEntry,\n docId: string,\n ): Promise<Record<string, unknown> | null> {\n const getterName = `by${entry.documentKey.charAt(0).toUpperCase()}${entry.documentKey.slice(1)}`;\n const getter = (entry.repo.get as any)[getterName];\n\n if (typeof getter === \"function\") {\n try {\n const doc = (await getter(docId)) as Record<string, unknown> | null;\n if (doc) return doc;\n } catch {\n // Direct ref may fail for subcollections — fall through to query\n }\n }\n\n const results = await entry.repo.query.by({\n where: [[entry.documentKey, \"==\", docId]],\n limit: 1,\n });\n return (results[0] as Record<string, unknown>) ?? null;\n }\n\n // ── LIST: GET /:repoName ────────────────────────────────────────────────\n async function handleList(ctx: any): Promise<any> {\n const c = ctx.c;\n\n const params = c.req.param();\n const entry = getRepoEntry(params.repoName, c);\n if (!entry) return sendError(c, `Repository not found`, 404);\n\n const user = userOf(c);\n if (\n !(await assertRule(c, entry, \"list\", {\n user,\n query: c.req.query(),\n params,\n }))\n )\n return;\n\n // Captured for error handling (so the catch can build an index URL)\n let ctxFilters: { field: string; op: any; value: string }[] = [];\n let ctxSort: { field: string; dir: \"asc\" | \"desc\" } | undefined;\n\n try {\n const query = c.req.query();\n const pageSize = Math.min(\n Number(query.pageSize) || entry.pageSize,\n 100, // Max page size\n );\n const cursor = query.cursor as string | undefined;\n const direction =\n (query.direction as string)?.toLowerCase() === \"prev\" ? \"prev\" : \"next\";\n const orderBy = query.orderBy as string | undefined;\n const orderDir =\n (query.orderDir as string)?.toLowerCase() === \"desc\" ? \"desc\" : \"asc\";\n const selectStr = query.select as string | undefined;\n const select = selectStr\n ? selectStr.split(\",\").map((s) => s.trim())\n : undefined;\n\n // Parse includes (relation population)\n let includes:\n | (string | { relation: string; select?: string[] })[]\n | undefined;\n if (entry.allowedIncludes && query.includes) {\n const rawIncludes =\n typeof query.includes === \"string\"\n ? query.includes.split(\",\").map((s: string) => s.trim())\n : Array.isArray(query.includes)\n ? query.includes\n : [];\n includes = rawIncludes.filter(\n (inc: string) =>\n typeof inc === \"string\" && entry.allowedIncludes!.includes(inc),\n );\n if (includes?.length === 0) includes = undefined;\n }\n\n // Parse filters\n const filters = parseFilters(query, entry.filterableFields);\n ctxFilters = filters.map((f) => ({\n field: f.field,\n op: f.op,\n value: String(f.value ?? \"\"),\n }));\n if (orderBy) ctxSort = { field: orderBy, dir: orderDir };\n\n // Build query options\n const queryOptions: any = {\n pageSize,\n direction,\n };\n\n if (cursor) {\n try {\n const cursorObj =\n typeof cursor === \"string\" ? JSON.parse(cursor) : cursor;\n queryOptions.cursor = await deserializeCursor(entry, cursorObj);\n } catch {\n // Invalid cursor, ignore\n }\n }\n\n if (orderBy) {\n if (entry.orderableFields && !entry.orderableFields.includes(orderBy)) {\n return sendError(c, `Field not orderable: ${orderBy}`, 400);\n }\n queryOptions.orderBy = [{ field: orderBy, direction: orderDir }];\n }\n\n if (filters.length > 0) {\n queryOptions.where = [];\n for (const f of filters) {\n let finalValue = f.value;\n const fieldSchema = (entry.schema as any)?.shape?.[f.field];\n if (fieldSchema && typeof fieldSchema.safeParse === \"function\") {\n const parsed = fieldSchema.safeParse(f.value);\n if (parsed.success) {\n finalValue = parsed.data;\n } else if (Array.isArray(f.value)) {\n // If f.value is an array (e.g. for `__in` / `__nin` operators) and fieldSchema is for a single element,\n // try validating each element of the array individually.\n const parsedArray: unknown[] = [];\n let hasError = false;\n let errorMessage = \"\";\n for (const item of f.value) {\n const itemParsed = fieldSchema.safeParse(item);\n if (itemParsed.success) {\n parsedArray.push(itemParsed.data);\n } else {\n hasError = true;\n errorMessage = itemParsed.error.issues\n .map((e: any) => e.message)\n .join(\", \");\n break;\n }\n }\n if (hasError) {\n return sendError(\n c,\n `Invalid filter value for '${f.field}': ${errorMessage}`,\n 400,\n );\n }\n finalValue = parsedArray;\n } else {\n const messages = parsed.error.issues\n .map((e: any) => e.message)\n .join(\", \");\n return sendError(\n c,\n `Invalid filter value for '${f.field}': ${messages}`,\n 400,\n );\n }\n }\n queryOptions.where.push([f.field, f.op, finalValue]);\n }\n }\n\n if (select) {\n queryOptions.select = select as any;\n }\n\n if (includes) {\n queryOptions.include = includes as any;\n }\n\n // Execute query\n const result = await entry.repo.query.paginate(queryOptions);\n const filteredItems = await applyRowFilter(\n entry,\n userOf(c),\n params,\n result.data,\n );\n\n const responseData: ListResponseData = {\n items: filteredItems,\n hasNextPage: result.hasNextPage,\n hasPrevPage: result.hasPrevPage,\n nextCursor: serializeCursor(result.nextCursor),\n prevCursor: serializeCursor(result.prevCursor),\n };\n\n return sendSuccess(c, responseData, {\n pageSize,\n hasMore: result.hasNextPage,\n });\n } catch (err) {\n sendQueryError(\n c,\n err,\n {\n ref: entry.repo.ref,\n path: entry.path,\n isGroup: !!entry.isGroup,\n filters: ctxFilters,\n sort: ctxSort,\n },\n \"Failed to fetch documents\",\n verbose,\n );\n }\n }\n\n // ── QUERY: POST /:repoName/query ────────────────────────────────────────\n // Advanced query endpoint supporting OR conditions, array filters, etc.\n async function handleQuery(ctx: any): Promise<any> {\n const c = ctx.c;\n\n const params = c.req.param();\n const entry = getRepoEntry(params.repoName, c);\n if (!entry) return sendError(c, `Repository not found`, 404);\n\n const user = userOf(c);\n if (\n !(await assertRule(c, entry, \"list\", {\n user,\n query: ctx.input || {},\n params,\n }))\n )\n return;\n\n // Captured for error handling (so the catch can build an index URL)\n let ctxFilters: { field: string; op: any; value: string }[] = [];\n let ctxSort: { field: string; dir: \"asc\" | \"desc\" } | undefined;\n\n try {\n const body: QueryRequestBody = ctx.input || {};\n const pageSize = Math.min(body.pageSize || entry.pageSize, 100);\n const direction = body.direction === \"prev\" ? \"prev\" : \"next\";\n\n // Capture context for index URL fallback\n if (body.where) {\n ctxFilters = body.where.map((w) => ({\n field: String(w[0]),\n op: w[1] as any,\n value: String(w[2] ?? \"\"),\n }));\n }\n if (body.orderBy && body.orderBy[0]) {\n ctxSort = {\n field: body.orderBy[0].field,\n dir: body.orderBy[0].direction === \"desc\" ? \"desc\" : \"asc\",\n };\n }\n\n // Build query options\n const queryOptions: any = {\n pageSize,\n direction,\n };\n\n // Cursor\n if (body.cursor) {\n try {\n const cursorObj =\n typeof body.cursor === \"string\"\n ? JSON.parse(body.cursor)\n : body.cursor;\n queryOptions.cursor = await deserializeCursor(entry, cursorObj);\n } catch {\n // Invalid cursor, ignore\n }\n }\n\n // Includes (relation population)\n if (entry.allowedIncludes && body.includes && body.includes.length > 0) {\n const validIncludes = body.includes.filter((inc) => {\n if (typeof inc === \"string\") {\n return entry.allowedIncludes!.includes(inc);\n }\n if (\n typeof inc === \"object\" &&\n inc !== null &&\n \"relation\" in inc &&\n typeof inc.relation === \"string\"\n ) {\n return entry.allowedIncludes!.includes(inc.relation);\n }\n return false;\n });\n if (validIncludes.length > 0) {\n queryOptions.include = validIncludes as any;\n }\n }\n\n // Where conditions (AND)\n if (body.where && body.where.length > 0) {\n // Validate filterable fields if configured\n if (entry.filterableFields) {\n const allowed = new Set(entry.filterableFields);\n const invalid = body.where.filter((w) => !allowed.has(w[0]));\n if (invalid.length > 0) {\n sendError(\n c,\n `Fields not filterable: ${invalid.map((w) => w[0]).join(\", \")}`,\n 400,\n );\n return;\n }\n }\n queryOptions.where = body.where;\n }\n\n // OR where conditions (simple)\n if (body.orWhere && body.orWhere.length > 0) {\n if (entry.filterableFields) {\n const allowed = new Set(entry.filterableFields);\n const invalid = body.orWhere.filter((w) => !allowed.has(w[0]));\n if (invalid.length > 0) {\n sendError(\n c,\n `Fields not filterable: ${invalid.map((w) => w[0]).join(\", \")}`,\n 400,\n );\n return;\n }\n }\n queryOptions.orWhere = body.orWhere;\n }\n\n // OR where groups (advanced)\n if (body.orWhereGroups && body.orWhereGroups.length > 0) {\n if (entry.filterableFields) {\n const allowed = new Set(entry.filterableFields);\n for (const group of body.orWhereGroups) {\n const invalid = group.filter((w) => !allowed.has(w[0]));\n if (invalid.length > 0) {\n sendError(\n c,\n `Fields not filterable: ${invalid.map((w) => w[0]).join(\", \")}`,\n 400,\n );\n return;\n }\n }\n }\n queryOptions.orWhereGroups = body.orWhereGroups;\n }\n\n // Order by\n if (body.orderBy && body.orderBy.length > 0) {\n if (entry.orderableFields) {\n const allowed = new Set(entry.orderableFields);\n const invalid = body.orderBy.filter((o) => !allowed.has(o.field));\n if (invalid.length > 0) {\n sendError(\n c,\n `Fields not orderable: ${invalid.map((o) => o.field).join(\", \")}`,\n 400,\n );\n return;\n }\n }\n queryOptions.orderBy = body.orderBy;\n }\n\n // Select\n if (body.select && body.select.length > 0) {\n queryOptions.select = body.select;\n }\n\n // Execute query\n const result = await entry.repo.query.paginate(queryOptions);\n const filteredItems = await applyRowFilter(\n entry,\n userOf(c),\n params,\n result.data,\n );\n\n const responseData: ListResponseData = {\n items: filteredItems,\n hasNextPage: result.hasNextPage,\n hasPrevPage: result.hasPrevPage,\n nextCursor: serializeCursor(result.nextCursor),\n prevCursor: serializeCursor(result.prevCursor),\n };\n\n return sendSuccess(c, responseData, {\n pageSize,\n hasMore: result.hasNextPage,\n });\n } catch (err) {\n sendQueryError(\n c,\n err,\n {\n ref: entry.repo.ref,\n path: entry.path,\n isGroup: !!entry.isGroup,\n filters: ctxFilters,\n sort: ctxSort,\n },\n \"Failed to query documents\",\n verbose,\n );\n }\n }\n\n // ── GET: GET /:repoName/:id ─────────────────────────────────────────────\n async function handleGet(ctx: any): Promise<any> {\n const c = ctx.c;\n\n const params = c.req.param();\n const entry = getRepoEntry(params.repoName, c);\n if (!entry) return sendError(c, `Repository not found`, 404);\n\n const id = params.id;\n if (!id) {\n return sendError(c, \"Document ID required\", 400);\n }\n\n try {\n const doc = await fetchDocById(entry, id);\n\n if (!doc) {\n return sendError(c, \"Document not found\", 404);\n }\n\n const user = userOf(c);\n if (\n !(await assertRule(c, entry, \"get\", {\n user,\n doc: doc as any,\n params,\n }))\n )\n return;\n\n // Apply row-level filter (404 if rejected, to avoid existence leakage)\n if (entry.rules?.filter) {\n try {\n const ok = await entry.rules.filter({\n user,\n doc: doc as any,\n params,\n });\n if (!ok) {\n return sendError(c, \"Document not found\", 404);\n }\n } catch {\n return sendError(c, \"Document not found\", 404);\n }\n }\n\n return sendSuccess(c, doc);\n } catch (err) {\n sendQueryError(\n c,\n err,\n {\n ref: entry.repo.ref,\n path: entry.path,\n isGroup: !!entry.isGroup,\n filters: [{ field: entry.documentKey, op: \"==\", value: id }],\n },\n \"Failed to fetch document\",\n verbose,\n );\n }\n }\n\n // ── CREATE: POST /:repoName ─────────────────────────────────────────────\n async function handleCreate(ctx: any): Promise<any> {\n const c = ctx.c;\n\n const params = c.req.param();\n const entry = getRepoEntry(params.repoName, c);\n if (!entry) return sendError(c, `Repository not found`, 404);\n\n try {\n const body = ctx.input || {};\n\n const user = userOf(c);\n if (\n !(await assertRule(c, entry, \"create\", {\n user,\n body,\n params,\n }))\n )\n return;\n\n // Validate against schema\n const validation = validateData(\n entry.schema,\n body,\n entry.createFields,\n false,\n entry.systemKeys,\n );\n if (!validation.success) {\n return sendError(c, (validation as any).error, 400);\n }\n\n // Custom validation\n if (entry.validate) {\n const customError = await entry.validate(validation.data, \"create\");\n if (customError) {\n return sendError(c, customError, 400);\n }\n }\n\n // Create document\n let created: any;\n if (entry.isGroup && entry.parentKeys && entry.parentKeys.length > 0) {\n // Collection-group repos cannot use create(); use set() with parent path args.\n const data: Record<string, any> = { ...validation.data };\n // set() doesn't auto-set createdKey, so inject it here\n if (entry.createdKey) {\n data[entry.createdKey] = new Date();\n }\n const missingKeys = entry.parentKeys.filter((k) => !data[k]);\n if (missingKeys.length > 0) {\n sendError(\n c,\n `Missing parent key(s) for subcollection create: ${missingKeys.join(\", \")}`,\n 400,\n );\n return;\n }\n const parentIds = entry.parentKeys.map((k) => data[k] as string);\n const docId = data[entry.documentKey] || generateFirestoreId();\n created = await entry.repo.set(...parentIds, docId, data);\n } else {\n created = await entry.repo.create(validation.data as any);\n }\n\n return sendSuccess(c, created, undefined, 201);\n } catch (err) {\n const message =\n verbose && err instanceof Error\n ? err.message\n : \"Failed to create document\";\n return sendError(c, message, 500);\n }\n }\n\n // ── UPDATE: PUT/PATCH /:repoName/:id ────────────────────────────────────\n async function handleUpdate(ctx: any, partial: boolean): Promise<any> {\n const c = ctx.c;\n const params = c.req.param();\n const entry = getRepoEntry(params.repoName, c);\n if (!entry) return sendError(c, `Repository not found`, 404);\n\n const id = params.id;\n if (!id) {\n return sendError(c, \"Document ID required\", 400);\n }\n\n try {\n const body = ctx.input || {};\n\n // Fetch existing doc so the rule can authorize against current state\n const existingDoc = await fetchDocById(entry, id);\n if (!existingDoc) {\n return sendError(c, \"Document not found\", 404);\n }\n\n const user = userOf(c);\n if (\n !(await assertRule(c, entry, \"update\", {\n user,\n doc: existingDoc as any,\n body,\n params,\n }))\n )\n return;\n\n // Validate against schema\n const validation = validateData(\n entry.schema,\n body,\n entry.mutableFields,\n partial,\n entry.systemKeys,\n );\n if (!validation.success) {\n return sendError(c, (validation as any).error, 400);\n }\n\n // Custom validation\n if (entry.validate) {\n const customError = await entry.validate(validation.data, \"update\");\n if (customError) {\n return sendError(c, customError, 400);\n }\n }\n\n // Update document — derive path args for subcollections\n const pathArgs = extractPathArgs(existingDoc, entry.pathKey) ?? [id];\n const updated = await entry.repo.update(\n ...pathArgs,\n validation.data as any,\n );\n\n return sendSuccess(c, updated);\n } catch (err) {\n const message =\n verbose && err instanceof Error\n ? err.message\n : \"Failed to update document\";\n return sendError(c, message, 500);\n }\n }\n\n // ── DELETE: DELETE /:repoName/:id ───────────────────────────────────────\n async function handleDelete(ctx: any): Promise<any> {\n const c = ctx.c;\n\n const params = c.req.param();\n const entry = getRepoEntry(params.repoName, c);\n if (!entry) return sendError(c, `Repository not found`, 404);\n\n if (!entry.allowDelete) {\n return sendError(c, \"Delete not allowed for this repository\", 403);\n }\n\n const id = params.id;\n if (!id) {\n return sendError(c, \"Document ID required\", 400);\n }\n\n try {\n // Fetch first to authorize against current state and get path args\n const doc = await fetchDocById(entry, id);\n if (!doc) {\n return sendError(c, \"Document not found\", 404);\n }\n\n const user = userOf(c);\n if (\n !(await assertRule(c, entry, \"delete\", {\n user,\n doc: doc as any,\n params,\n }))\n )\n return;\n\n const pathArgs = extractPathArgs(doc, entry.pathKey) ?? [id];\n await entry.repo.delete(...pathArgs);\n return sendSuccess(c, { deleted: true });\n } catch (err) {\n const message =\n verbose && err instanceof Error\n ? err.message\n : \"Failed to delete document\";\n return sendError(c, message, 500);\n }\n }\n\n // ── OPTIONS: for CORS preflight ─────────────────────────────────────────\n function handleOptions(ctx: any): any {\n const c = ctx.c;\n return c.text(\"\", 204, {\n \"Access-Control-Allow-Methods\": \"GET, POST, PUT, PATCH, DELETE, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"Content-Type, Authorization\",\n \"Access-Control-Max-Age\": \"86400\",\n });\n }\n\n // ── BATCH: POST /:repoName/batch ─────────────────────────────────────────\n async function handleBatch(ctx: any) {\n const c = ctx.c;\n const params = c.req.param();\n const entry = getRepoEntry(params.repoName, c);\n if (!entry) return sendError(c, `Repository not found`, 404);\n\n try {\n const body = ctx.input || {};\n if (!Array.isArray(body.operations)) {\n return sendError(c, \"operations array is required\", 400);\n }\n\n const user = userOf(c);\n\n const batch = entry.repo.batch.create();\n const results = [];\n\n for (const op of body.operations) {\n if (!op.type || ![\"create\", \"update\", \"delete\"].includes(op.type)) {\n return sendError(c, \"Invalid operation type\", 400);\n }\n\n if (op.type === \"create\") {\n if (\n !(await assertRule(c, entry, \"create\", {\n user,\n body: op.data,\n params,\n }))\n )\n return;\n const validation = validateData(\n entry.schema,\n op.data,\n entry.createFields,\n false,\n entry.systemKeys,\n );\n if (!validation.success)\n return sendError(c, (validation as any).error, 400);\n\n let docId = op.data[entry.documentKey] || generateFirestoreId();\n const data = { ...validation.data };\n if (entry.createdKey) data[entry.createdKey] = new Date();\n\n if (entry.isGroup && entry.parentKeys) {\n const parentIds = entry.parentKeys.map(\n (k: string) => data[k] as string,\n );\n batch.set(...parentIds, docId, data);\n } else {\n batch.set(docId, data);\n }\n results.push({ op: \"create\", id: docId });\n } else if (op.type === \"update\") {\n if (!op.id) return sendError(c, \"id required for update\", 400);\n\n const existingDoc = await fetchDocById(entry, op.id);\n if (!existingDoc)\n return sendError(c, `Document ${op.id} not found`, 404);\n\n if (\n !(await assertRule(c, entry, \"update\", {\n user,\n doc: existingDoc as any,\n body: op.data,\n params,\n }))\n )\n return;\n\n const validation = validateData(\n entry.schema,\n op.data,\n entry.mutableFields,\n true,\n entry.systemKeys,\n );\n if (!validation.success)\n return sendError(c, (validation as any).error, 400);\n\n const pathArgs = extractPathArgs(existingDoc, entry.pathKey) ?? [\n op.id,\n ];\n batch.update(...pathArgs, validation.data);\n results.push({ op: \"update\", id: op.id });\n } else if (op.type === \"delete\") {\n if (!entry.allowDelete)\n return sendError(c, \"Delete not allowed\", 403);\n if (!op.id) return sendError(c, \"id required for delete\", 400);\n\n const doc = await fetchDocById(entry, op.id);\n if (!doc) return sendError(c, `Document ${op.id} not found`, 404);\n if (\n !(await assertRule(c, entry, \"delete\", {\n user,\n doc: doc as any,\n params,\n }))\n )\n return;\n\n const pathArgs = extractPathArgs(doc, entry.pathKey) ?? [op.id];\n batch.delete(...pathArgs);\n results.push({ op: \"delete\", id: op.id });\n }\n }\n\n await batch.commit();\n return sendSuccess(c, { results });\n } catch (err) {\n const message =\n verbose && err instanceof Error\n ? err.message\n : \"Batch operation failed\";\n return sendError(c, message, 500);\n }\n }\n\n return {\n handleList,\n handleQuery,\n handleGet,\n handleCreate,\n handleUpdate,\n handleDelete,\n handleBatch,\n handleOptions,\n };\n}\n","/**\n * OpenAPI 3.1 specification generator for the CRUD server.\n *\n * Introspects each `CrudRepoEntry` and uses Zod 4's native `z.toJSONSchema()`\n * to produce a fully typed OpenAPI document ready for Scalar UI or codegen.\n *\n * @module servers/crud/openapi\n */\n\nimport { z } from \"zod\";\nimport { getOpenApiMetadata } from \"@asteasolutions/zod-to-openapi\";\nimport type { CrudRepoEntry, CrudRepoRegistry, OpenAPISpecOptions } from \"./types\";\n\nexport type { OpenAPISpecOptions };\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Minimal subset of an OpenAPI 3.1 document we produce. */\nexport interface OpenAPIDocument {\n openapi: \"3.1.0\";\n info: OpenAPIInfo;\n servers?: { url: string; description?: string }[];\n paths: Record<string, Record<string, OpenAPIOperation>>;\n components: {\n schemas: Record<string, Record<string, unknown>>;\n securitySchemes?: Record<string, Record<string, unknown>>;\n };\n security?: Record<string, string[]>[];\n tags?: { name: string; description?: string }[];\n}\n\nexport interface OpenAPIInfo {\n title: string;\n version: string;\n description?: string;\n}\n\ninterface OpenAPIOperation {\n operationId: string;\n summary: string;\n tags: string[];\n parameters?: Record<string, unknown>[];\n requestBody?: Record<string, unknown>;\n responses: Record<string, Record<string, unknown>>;\n security?: Record<string, string[]>[];\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Convert a Zod schema to a JSON Schema object suitable for OpenAPI 3.1.\n *\n * Uses `unrepresentable: \"any\"` so that types Zod can't natively serialize\n * (e.g. `z.date()`, `z.bigint()`, custom classes — common with Firestore\n * Timestamps stored as `Date`) don't throw and collapse the whole schema to\n * a bare `{ type: \"object\" }`. We additionally override a few well-known\n * cases to a sensible OpenAPI representation.\n */\nfunction zodToJsonSchema(schema: z.ZodType): Record<string, unknown> {\n try {\n return z.toJSONSchema(schema, {\n target: \"openapi-3.1\",\n unrepresentable: \"any\",\n override: (ctx) => {\n const metadata = getOpenApiMetadata(ctx.zodSchema as unknown as z.ZodTypeAny);\n if (metadata) {\n Object.assign(ctx.jsonSchema, metadata);\n }\n\n const def: any = (ctx.zodSchema as any)?._zod?.def;\n if (!def) return;\n if (def.type === \"date\" && !(ctx.jsonSchema as any).type) {\n (ctx.jsonSchema as any).type = \"string\";\n (ctx.jsonSchema as any).format = \"date-time\";\n } else if (def.type === \"bigint\" && !(ctx.jsonSchema as any).type) {\n (ctx.jsonSchema as any).type = \"string\";\n (ctx.jsonSchema as any).format = \"int64\";\n }\n },\n }) as Record<string, unknown>;\n } catch (err) {\n if (typeof console !== \"undefined\" && console.warn) {\n console.warn(\n \"[generateOpenAPISpec] Failed to convert Zod schema to JSON Schema; falling back to {type:object}.\",\n err,\n );\n }\n return { type: \"object\" };\n }\n}\n\n/** Wraps a JSON Schema in a `#/components/schemas/<name>` $ref. */\nfunction schemaRef(name: string): Record<string, unknown> {\n return { $ref: `#/components/schemas/${name}` };\n}\n\n/** Standard error response schema. */\nfunction errorResponse(description: string): Record<string, unknown> {\n return {\n description,\n content: {\n \"application/json\": {\n schema: schemaRef(\"ErrorResponse\"),\n },\n },\n };\n}\n\n/** Standard success response wrapping data. */\nfunction successResponse(\n description: string,\n dataSchema: Record<string, unknown>,\n): Record<string, unknown> {\n return {\n description,\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n success: { type: \"boolean\", enum: [true] },\n data: dataSchema,\n },\n required: [\"success\", \"data\"],\n },\n },\n },\n };\n}\n\n/** Build list response with pagination metadata. */\nfunction listResponse(\n itemSchema: Record<string, unknown>,\n): Record<string, unknown> {\n return {\n description: \"Paginated list of documents\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n success: { type: \"boolean\", enum: [true] },\n data: {\n type: \"object\",\n properties: {\n items: { type: \"array\", items: itemSchema },\n nextCursor: {\n oneOf: [{ type: \"object\" }, { type: \"null\" }],\n },\n prevCursor: {\n oneOf: [{ type: \"object\" }, { type: \"null\" }],\n },\n hasNextPage: { type: \"boolean\" },\n hasPrevPage: { type: \"boolean\" },\n },\n required: [\"items\", \"hasNextPage\", \"hasPrevPage\"],\n },\n meta: {\n type: \"object\",\n properties: {\n pageSize: { type: \"integer\" },\n hasMore: { type: \"boolean\" },\n cursor: {\n oneOf: [{ type: \"string\" }, { type: \"null\" }],\n },\n },\n },\n },\n required: [\"success\", \"data\"],\n },\n },\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Pagination / filter query parameters (shared across list endpoints)\n// ---------------------------------------------------------------------------\n\nfunction paginationParams(entry: CrudRepoEntry): Record<string, unknown>[] {\n return [\n {\n name: \"pageSize\",\n in: \"query\",\n schema: { type: \"integer\", default: entry.pageSize, maximum: 100 },\n description: \"Number of items per page\",\n },\n {\n name: \"cursor\",\n in: \"query\",\n schema: { type: \"string\" },\n description: \"Base64 pagination cursor\",\n },\n {\n name: \"orderBy\",\n in: \"query\",\n schema: { type: \"string\" },\n description: \"Field name to order by\",\n },\n {\n name: \"orderDir\",\n in: \"query\",\n schema: { type: \"string\", enum: [\"asc\", \"desc\"] },\n description: \"Order direction\",\n },\n {\n name: \"select\",\n in: \"query\",\n schema: { type: \"string\" },\n description: \"Comma-separated list of fields to return\",\n },\n ];\n}\n\nfunction filterParams(entry: CrudRepoEntry): Record<string, unknown>[] {\n const fields = entry.filterableFields ?? Object.keys(entry.schema.shape);\n const ops = [\n \"eq\",\n \"ne\",\n \"lt\",\n \"lte\",\n \"gt\",\n \"gte\",\n \"in\",\n \"nin\",\n \"contains\",\n \"containsAny\",\n ];\n\n const opDescriptions: Record<string, string> = {\n eq: \"equals. Use 'null' or '__null__' to match null values\",\n ne: \"not equals. Use 'null' or '__null__' to match non-null values\",\n lt: \"less than\",\n lte: \"less than or equal\",\n gt: \"greater than\",\n gte: \"greater than or equal\",\n in: \"in list (comma-separated values). Supports 'null' and '__null__' (e.g. val1,val2,__null__)\",\n nin: \"not in list (comma-separated values). Supports 'null' and '__null__'\",\n contains: \"array-contains\",\n containsAny: \"array-contains-any (comma-separated values). Supports 'null' and '__null__'\",\n };\n\n const params: Record<string, unknown>[] = [];\n for (const field of fields) {\n // Direct equality filter: ?field=value\n params.push({\n name: field,\n in: \"query\",\n schema: { type: \"string\" },\n description: `Filter by ${field} (equality). Use 'null' or '__null__' for null values`,\n });\n // Operator filters: ?field__op=value\n for (const op of ops) {\n const descDetail = opDescriptions[op] ? ` (${opDescriptions[op]})` : \"\";\n params.push({\n name: `${field}__${op}`,\n in: \"query\",\n schema: { type: \"string\" },\n description: `Filter ${field} with operator ${op}${descDetail}`,\n });\n }\n }\n return params;\n}\n\n// ---------------------------------------------------------------------------\n// Query body schema (POST /query)\n// ---------------------------------------------------------------------------\n\nfunction queryBodySchema(): Record<string, unknown> {\n return {\n type: \"object\",\n properties: {\n where: {\n type: \"array\",\n items: {\n type: \"array\",\n items: {},\n minItems: 3,\n maxItems: 3,\n },\n description: \"AND conditions: [field, operator, value][]\",\n },\n orWhere: {\n type: \"array\",\n items: {\n type: \"array\",\n items: {},\n minItems: 3,\n maxItems: 3,\n },\n description: \"Simple OR conditions (each independently OR'd)\",\n },\n orWhereGroups: {\n type: \"array\",\n items: {\n type: \"array\",\n items: {\n type: \"array\",\n items: {},\n minItems: 3,\n maxItems: 3,\n },\n },\n description: \"Advanced OR groups (AND within, OR across groups)\",\n },\n orderBy: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n field: { type: \"string\" },\n direction: { type: \"string\", enum: [\"asc\", \"desc\"] },\n },\n required: [\"field\"],\n },\n },\n select: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"Fields to select (projection)\",\n },\n pageSize: {\n type: \"integer\",\n maximum: 100,\n description: \"Number of items per page\",\n },\n cursor: {\n oneOf: [{ type: \"string\" }, { type: \"object\" }],\n description: \"Pagination cursor\",\n },\n direction: {\n type: \"string\",\n enum: [\"next\", \"prev\"],\n description: \"Pagination direction\",\n },\n includes: {\n type: \"array\",\n items: {\n oneOf: [\n { type: \"string\" },\n {\n type: \"object\",\n properties: {\n relation: { type: \"string\" },\n select: { type: \"array\", items: { type: \"string\" } },\n },\n required: [\"relation\"],\n },\n ],\n },\n description: \"Relations to include (populate)\",\n },\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Path generation per repo entry\n// ---------------------------------------------------------------------------\n\nfunction buildPathsForEntry(\n entry: CrudRepoEntry,\n base: string,\n modelSchemaName: string,\n createSchemaName: string | null,\n updateSchemaName: string | null,\n): Record<string, Record<string, OpenAPIOperation>> {\n const paths: Record<string, Record<string, OpenAPIOperation>> = {};\n const tag = entry.name;\n const collectionPath = `${base}/${entry.name}`;\n const documentPath = `${collectionPath}/{${entry.documentKey}}`;\n\n const idParam = {\n name: entry.documentKey,\n in: \"path\",\n required: true,\n schema: { type: \"string\" },\n description: `Unique document identifier`,\n };\n\n // ── GET /:repo → list ──────────────────────────────────────────────\n paths[collectionPath] = {\n get: {\n operationId: `list${capitalize(entry.name)}`,\n summary: `List ${entry.name} (paginated)`,\n tags: [tag],\n parameters: [...paginationParams(entry), ...filterParams(entry)],\n responses: {\n \"200\": listResponse(schemaRef(modelSchemaName)),\n \"500\": errorResponse(\"Internal server error\"),\n },\n },\n // ── POST /:repo → create ────────────────────────────────────────\n post: {\n operationId: `create${capitalize(entry.name)}`,\n summary: `Create a ${singularize(entry.name)}`,\n tags: [tag],\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: schemaRef(createSchemaName ?? modelSchemaName),\n },\n },\n },\n responses: {\n \"201\": successResponse(\"Document created\", schemaRef(modelSchemaName)),\n \"400\": errorResponse(\"Validation error\"),\n \"500\": errorResponse(\"Internal server error\"),\n },\n },\n };\n\n // ── POST /:repo/query → advanced query ────────────────────────────\n paths[`${collectionPath}/query`] = {\n post: {\n operationId: `query${capitalize(entry.name)}`,\n summary: `Query ${entry.name} with advanced filters`,\n tags: [tag],\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: schemaRef(\"QueryRequestBody\"),\n },\n },\n },\n responses: {\n \"200\": listResponse(schemaRef(modelSchemaName)),\n \"400\": errorResponse(\"Invalid query\"),\n \"500\": errorResponse(\"Internal server error\"),\n },\n },\n };\n\n // ── POST /:repo/batch → batch operations ─────────────────────────\n paths[`${collectionPath}/batch`] = {\n post: {\n operationId: `batch${capitalize(entry.name)}`,\n summary: `Execute batch operations on ${entry.name}`,\n tags: [tag],\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: schemaRef(`${modelSchemaName}BatchRequest`),\n },\n },\n },\n responses: {\n \"200\": successResponse(\"Batch operations completed\", {\n type: \"object\",\n properties: {\n results: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n op: { type: \"string\" },\n id: { type: \"string\" },\n },\n },\n },\n },\n }),\n \"400\": errorResponse(\"Validation error\"),\n \"403\": errorResponse(\"Forbidden\"),\n \"404\": errorResponse(\"Document not found\"),\n \"500\": errorResponse(\"Internal server error\"),\n },\n },\n };\n\n // ── Single-document paths ────────────────────────────────────────\n const docOps: Record<string, OpenAPIOperation> = {};\n\n // GET /:repo/:id\n docOps.get = {\n operationId: `get${capitalize(singularize(entry.name))}`,\n summary: `Get a single ${singularize(entry.name)}`,\n tags: [tag],\n parameters: [idParam],\n responses: {\n \"200\": successResponse(\"Document found\", schemaRef(modelSchemaName)),\n \"404\": errorResponse(\"Document not found\"),\n \"500\": errorResponse(\"Internal server error\"),\n },\n };\n\n // PUT /:repo/:id (full update)\n docOps.put = {\n operationId: `update${capitalize(singularize(entry.name))}`,\n summary: `Update a ${singularize(entry.name)} (full replace)`,\n tags: [tag],\n parameters: [idParam],\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: schemaRef(updateSchemaName ?? modelSchemaName),\n },\n },\n },\n responses: {\n \"200\": successResponse(\"Document updated\", schemaRef(modelSchemaName)),\n \"400\": errorResponse(\"Validation error\"),\n \"404\": errorResponse(\"Document not found\"),\n \"500\": errorResponse(\"Internal server error\"),\n },\n };\n\n // PATCH /:repo/:id (partial update)\n docOps.patch = {\n operationId: `patch${capitalize(singularize(entry.name))}`,\n summary: `Partially update a ${singularize(entry.name)}`,\n tags: [tag],\n parameters: [idParam],\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: {\n allOf: [schemaRef(updateSchemaName ?? modelSchemaName)],\n description: \"All fields are optional for partial updates\",\n },\n },\n },\n },\n responses: {\n \"200\": successResponse(\"Document patched\", schemaRef(modelSchemaName)),\n \"400\": errorResponse(\"Validation error\"),\n \"404\": errorResponse(\"Document not found\"),\n \"500\": errorResponse(\"Internal server error\"),\n },\n };\n\n // DELETE /:repo/:id (only if allowDelete)\n if (entry.allowDelete) {\n docOps.delete = {\n operationId: `delete${capitalize(singularize(entry.name))}`,\n summary: `Delete a ${singularize(entry.name)}`,\n tags: [tag],\n parameters: [idParam],\n responses: {\n \"200\": successResponse(\"Document deleted\", {\n type: \"object\",\n properties: { id: { type: \"string\" } },\n }),\n \"404\": errorResponse(\"Document not found\"),\n \"500\": errorResponse(\"Internal server error\"),\n },\n };\n }\n\n paths[documentPath] = docOps;\n\n return paths;\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Generate a full OpenAPI 3.1 specification from a `CrudRepoRegistry`.\n *\n * Uses Zod 4's native `z.toJSONSchema()` to convert each repo's schema\n * into a JSON Schema component, then assembles paths for the standard\n * CRUD endpoints.\n *\n * @example\n * ```ts\n * import { generateOpenAPISpec } from \"@lpdjs/firestore-repo-service/servers/crud\";\n *\n * const spec = generateOpenAPISpec(registry, \"/api\", {\n * title: \"My API\",\n * version: \"1.0.0\",\n * servers: [{ url: \"https://my-api.example.com\" }],\n * auth: \"bearer\",\n * });\n *\n * // Write to file\n * fs.writeFileSync(\"openapi.json\", JSON.stringify(spec, null, 2));\n * ```\n */\nexport function generateOpenAPISpec(\n registry: CrudRepoRegistry,\n basePath: string,\n options: OpenAPISpecOptions = {},\n): OpenAPIDocument {\n const {\n title = \"CRUD API\",\n version = \"1.0.0\",\n description,\n servers,\n auth = false,\n } = options;\n\n const base = basePath === \"/\" ? \"\" : basePath.replace(/\\/$/, \"\");\n\n // ── Components: schemas ───────────────────────────────────────────\n const schemas: Record<string, Record<string, unknown>> = {};\n const allPaths: Record<string, Record<string, OpenAPIOperation>> = {};\n const tags: { name: string; description?: string }[] = [];\n\n // Shared schemas\n schemas[\"ErrorResponse\"] = {\n type: \"object\",\n properties: {\n success: { type: \"boolean\", enum: [false] },\n error: { type: \"string\" },\n },\n required: [\"success\", \"error\"],\n };\n\n schemas[\"QueryRequestBody\"] = queryBodySchema();\n\n // Per-repo schemas & paths\n for (const [name, entry] of Object.entries(registry)) {\n const modelName = capitalize(singularize(name));\n const createName = `${modelName}Create`;\n const updateName = `${modelName}Update`;\n\n // Full model schema\n schemas[modelName] = zodToJsonSchema(entry.schema);\n\n // Helper: build a filtered shape (respects systemKeys + field list)\n const buildShape = (\n fieldList: string[] | undefined,\n ): Record<string, z.ZodType> => {\n const source =\n fieldList && fieldList.length > 0\n ? fieldList\n : Object.keys(entry.schema.shape);\n const shape: Record<string, z.ZodType> = {};\n for (const f of source) {\n const top = f.split(\".\")[0];\n if (top && entry.schema.shape[top] && !entry.systemKeys.includes(top)) {\n shape[top] = entry.schema.shape[top];\n }\n }\n return shape;\n };\n\n // Create schema\n let createSchemaName: string | null = null;\n const createShape = buildShape(entry.createFields);\n if (Object.keys(createShape).length > 0) {\n schemas[createName] = zodToJsonSchema(z.object(createShape));\n createSchemaName = createName;\n }\n\n // Update schema\n let updateSchemaName: string | null = null;\n const updateShape = buildShape(entry.mutableFields);\n if (Object.keys(updateShape).length > 0) {\n schemas[updateName] = zodToJsonSchema(z.object(updateShape));\n updateSchemaName = updateName;\n }\n\n // Batch schema\n schemas[`${modelName}BatchRequest`] = {\n type: \"object\",\n properties: {\n operations: {\n type: \"array\",\n items: {\n oneOf: [\n {\n type: \"object\",\n properties: {\n type: { type: \"string\", enum: [\"create\"] },\n data: schemaRef(createSchemaName ?? modelName),\n },\n required: [\"type\", \"data\"],\n },\n {\n type: \"object\",\n properties: {\n type: { type: \"string\", enum: [\"update\"] },\n id: { type: \"string\" },\n data: {\n allOf: [schemaRef(updateSchemaName ?? modelName)],\n description: \"Partial updates allowed\",\n },\n },\n required: [\"type\", \"id\", \"data\"],\n },\n ...(entry.allowDelete\n ? [\n {\n type: \"object\",\n properties: {\n type: { type: \"string\", enum: [\"delete\"] },\n id: { type: \"string\" },\n },\n required: [\"type\", \"id\"],\n },\n ]\n : []),\n ],\n },\n },\n },\n required: [\"operations\"],\n };\n\n // Build paths\n const entryPaths = buildPathsForEntry(\n entry,\n base,\n modelName,\n createSchemaName,\n updateSchemaName,\n );\n Object.assign(allPaths, entryPaths);\n\n // Tag\n tags.push({\n name,\n description: `Operations on ${name} (collection: ${entry.path})`,\n });\n }\n\n // ── Security ──────────────────────────────────────────────────────\n const securitySchemes: Record<string, Record<string, unknown>> = {};\n let security: Record<string, string[]>[] | undefined;\n\n if (auth === \"basic\") {\n securitySchemes[\"basicAuth\"] = {\n type: \"http\",\n scheme: \"basic\",\n };\n security = [{ basicAuth: [] }];\n } else if (auth === \"bearer\") {\n securitySchemes[\"bearerAuth\"] = {\n type: \"http\",\n scheme: \"bearer\",\n bearerFormat: \"JWT\",\n };\n security = [{ bearerAuth: [] }];\n }\n\n // ── Assemble ──────────────────────────────────────────────────────\n const doc: OpenAPIDocument = {\n openapi: \"3.1.0\",\n info: {\n title,\n version,\n ...(description ? { description } : {}),\n },\n ...(servers && servers.length > 0 ? { servers } : {}),\n paths: allPaths,\n components: {\n schemas,\n ...(Object.keys(securitySchemes).length > 0 ? { securitySchemes } : {}),\n },\n ...(security ? { security } : {}),\n tags,\n };\n\n return doc;\n}\n\n// ---------------------------------------------------------------------------\n// Utility\n// ---------------------------------------------------------------------------\n\nfunction capitalize(s: string): string {\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n\n/** Naive singularize: strip trailing 's' for display. */\nfunction singularize(s: string): string {\n if (s.endsWith(\"ies\")) return s.slice(0, -3) + \"y\";\n if (s.endsWith(\"ses\") || s.endsWith(\"xes\") || s.endsWith(\"zes\"))\n return s.slice(0, -2);\n if (s.endsWith(\"s\") && !s.endsWith(\"ss\")) return s.slice(0, -1);\n return s;\n}\n","/**\n * Public types for the Hono file-based API server.\n *\n * Designed to be:\n * - **fully typed** end-to-end (Zod input/output → handler payload type),\n * - **runtime-safe** via Zod parsing on every request,\n * - **bundle-friendly** for Firebase Cloud Functions v2 cold-start (codegen\n * emits static imports — no `fs`/`import()` at runtime).\n */\n\nimport type { z, ZodError } from \"zod\";\nimport type { Context, Env, MiddlewareHandler } from \"hono\";\nimport type { AnyServicesContainer } from \"./services\";\nimport type { DocsAuthExtension } from \"./docs-auth\";\n\nexport type HttpMethod = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\n\n/** Where the validated payload comes from. */\nexport type PayloadSource = \"json\" | \"query\" | \"form\" | \"param\";\n\n/**\n * Structured logger injected into every handler / interceptor / error-handler\n * context. Implement it, or extend the package's `BaseLogger` and override its\n * `write` hook to route to your sink (Firebase logger, pino, …).\n *\n * `error()` returns a correlation id so the same value can be both logged and\n * returned to the client.\n */\nexport interface Logger {\n info(message: string, meta?: unknown): void;\n warn(message: string, meta?: unknown): void;\n /** @returns a correlation id (e.g. to include in the HTTP error response). */\n error(error: unknown, meta?: unknown): string;\n debug(message: string, meta?: unknown): void;\n}\n\n/** Context passed to {@link ErrorHandler.handle}. */\nexport interface ErrorHandlerContext<\n TEnv extends Env = Env,\n TServices extends AnyServicesContainer = AnyServicesContainer,\n> {\n /** The thrown value (an `AppError`, a Zod {@link ValidationError}, …). */\n error: unknown;\n /** Hono request context — set status, read headers, build the response. */\n c: Context<TEnv>;\n /** Route metadata (read-only). */\n route: AnyRouteDef;\n /** Global DI services container. */\n services: TServices;\n /** Injected {@link Logger} when one was passed to the API, else `undefined`. */\n logger?: Logger;\n}\n\n/**\n * Cross-cutting error strategy — a class (or object) you pass to the API and\n * that the server injects everywhere **and** applies automatically.\n *\n * Implement {@link ErrorHandler.handle} to map any thrown value to an HTTP\n * `Response` (e.g. your `AppError` → status + localized body, plus structured\n * logging with a correlation id). Return `null` to decline the error and let\n * the built-in fallback (`ValidationError` envelope) / `onError` take over.\n *\n * Prefer extending the package's {@link BaseErrorHandler} (it already maps the\n * built-in errors) and overriding its `mapError` / `logError` hooks. Pass it\n * **per API** via `ApiConfig.errorHandler`, or once via the registry\n * (`{ services, errorHandler }`); it is then available in every handler /\n * interceptor context as `errorHandler` and auto-applied on any uncaught error.\n */\nexport interface ErrorHandler<\n TEnv extends Env = Env,\n TServices extends AnyServicesContainer = AnyServicesContainer,\n> {\n handle(\n ctx: ErrorHandlerContext<TEnv, TServices>,\n ): Response | null | Promise<Response | null>;\n}\n\n/** Handler signature — receives a single typed context object. */\nexport type RouteHandler<\n TIn,\n TOut,\n TEnv extends Env = Env,\n TServices extends AnyServicesContainer = AnyServicesContainer,\n> = (ctx: {\n /** Validated (and typed) request payload. `void` when no `input` schema is defined. */\n input: TIn;\n /** Raw Hono `Context` for headers, set status, redirect, etc. */\n c: Context<TEnv>;\n /**\n * Global DI services container — same instance shared by every handler.\n * Empty `ServicesContainer` when the server was started without a\n * `services` option.\n */\n services: TServices;\n /**\n * Injected {@link ErrorHandler} when one was passed to the API, else\n * `undefined`. Usually you just `throw` and let it apply automatically.\n */\n errorHandler?: ErrorHandler<TEnv, TServices>;\n /** Injected {@link Logger} when one was passed to the API, else `undefined`. */\n logger?: Logger;\n}) => Promise<TOut | Response> | TOut | Response;\n\n/**\n * One route declaration. Default-exported by every `routes.ts` file inside the\n * domain tree. Use {@link defineRoute} for full type inference.\n */\nexport interface RouteDef<\n TIn extends z.ZodTypeAny | undefined = z.ZodTypeAny | undefined,\n TOut extends z.ZodTypeAny | undefined = z.ZodTypeAny | undefined,\n TEnv extends Env = Env,\n> {\n /**\n * Logical API tag — routes sharing the same `api` are mounted on the same\n * `HonoServer` (typically one Cloud Function per `api`).\n *\n * To expose the **same logic** under several APIs with different\n * inputs/outputs, export multiple `defineRoute({...})` from the same file\n * (default + named exports are both picked up by the codegen).\n */\n api: string;\n\n /** HTTP method. */\n method: HttpMethod;\n\n /**\n * URL path appended to the server `basePath`. If omitted, the codegen will\n * derive it from the file location (e.g. `domains/activities/useCases/createCustom/routes.ts`\n * → `/activities/createCustom`).\n */\n path?: string;\n\n /**\n * Where the request payload comes from.\n * Default: `\"json\"` for body methods (POST/PUT/PATCH/DELETE), `\"query\"` for GET.\n */\n source?: PayloadSource;\n\n /** Zod schema validating the payload. Failures yield a 400 response. */\n input?: TIn;\n\n /**\n * Zod schema for the success response. Used to populate the OpenAPI spec\n * and (when `validateOutput` is enabled on the server) to assert the\n * runtime payload returned by the handler.\n */\n output?: TOut;\n\n /** Status code for the success response. Default: 200. */\n status?: number;\n\n /** Hono middlewares applied to this route only (after global middlewares). */\n middlewares?: MiddlewareHandler<TEnv>[];\n\n // ── OpenAPI metadata ─────────────────────────────────────────────────\n summary?: string;\n description?: string;\n tags?: string[];\n /** Mark the operation as deprecated in the generated spec. */\n deprecated?: boolean;\n /** Security requirements (operationId-level override). */\n security?: SecurityRequirement[];\n\n /** The request handler. */\n handler: RouteHandler<\n TIn extends z.ZodTypeAny ? z.infer<TIn> : void,\n TOut extends z.ZodTypeAny ? z.infer<TOut> : unknown,\n TEnv\n >;\n}\n\n/** Erased `RouteDef` used by registry/codegen — handler signature is opaque. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyRouteDef = RouteDef<any, any>;\n\n/**\n * What `routes.ts` can default-export:\n * - a single {@link RouteDef} (most common case),\n * - or an array of {@link RouteDef} (e.g. expose the same useCase on\n * multiple `api` tags or under multiple paths). `readonly` arrays are\n * accepted so that tuple-preserving helpers like {@link defineRoutes} (or a\n * plain `as const` array) can be default-exported directly.\n */\nexport type RouteModuleDefault = AnyRouteDef | readonly AnyRouteDef[];\n\n// ── useCase ⇆ routes type bridge ──────────────────────────────────────────\n// A useCase should never re-declare its input/output by hand. Instead it\n// derives them from the Zod schemas of the route(s) that drive it, so the two\n// can never drift apart. Pass `typeof import(\"./routes.js\").default` to the\n// helpers below.\n\n/**\n * Identity helper that **preserves the tuple type** of a `routes.ts` default\n * export. A plain array literal (`export default [a, b]`) collapses every\n * element to a single common type, which would lose each route's individual\n * schema. Wrapping the array with `defineRoutes([...])` keeps the per-route\n * types intact so {@link RouteInput} / {@link RouteOutput} can aggregate them\n * into a union.\n *\n * @example\n * export default defineRoutes([\n * defineRoute({ ... }),\n * defineRoute({ ... }),\n * ]);\n */\nexport function defineRoutes<const T extends readonly AnyRouteDef[]>(\n routes: T,\n): T {\n return routes;\n}\n\n/**\n * Normalizes a `routes.ts` default export — a single {@link RouteDef} or an\n * array of them — to a *union* of its individual route members.\n */\nexport type RoutesUnion<T> = T extends readonly (infer R)[] ? R : T;\n\ntype InferRouteInput<R> = R extends { input?: infer I }\n ? I extends z.ZodTypeAny\n ? z.infer<I>\n : void\n : void;\n\ntype InferRouteOutput<R> = R extends { output?: infer O }\n ? O extends z.ZodTypeAny\n ? z.infer<O>\n : unknown\n : unknown;\n\n/**\n * Union of validated request payloads across every route in a `routes.ts`\n * module. Use it to type a useCase input without duplicating the Zod schema:\n *\n * @example\n * type Routes = typeof import(\"./routes.js\").default;\n * export type CreatePostUseCaseInput = RouteInput<Routes>;\n */\nexport type RouteInput<T> = InferRouteInput<RoutesUnion<T>>;\n\n/**\n * Union of success-response payloads across every route in a `routes.ts`\n * module. Mirror of {@link RouteInput} for the useCase output type.\n */\nexport type RouteOutput<T> = InferRouteOutput<RoutesUnion<T>>;\n\n/**\n * Thrown by the server when the incoming request fails Zod validation.\n * Caught by the {@link RouteInterceptor} (if any) so users can shape the\n * response envelope however they like; otherwise yields a default 400.\n */\nexport class ValidationError extends Error {\n readonly statusCode = 400 as const;\n constructor(\n /** Original Zod error — `error.issues` to enumerate field-level problems. */\n readonly zodError: ZodError,\n /** Where the offending payload came from. */\n readonly source: PayloadSource,\n ) {\n super(\"Request validation failed\");\n this.name = \"ValidationError\";\n }\n}\n\n/**\n * Cross-cutting interceptor applied around every handler.\n * Use it for response envelopes, business-error → HTTP mapping, structured\n * logging, tracing spans, etc.\n *\n * Wrap `next()` in `try/catch` to intercept BOTH Zod {@link ValidationError}s\n * (thrown before the handler runs) AND business errors thrown by the handler.\n *\n * @example\n * ```ts\n * interceptor: async ({ next, route, c }) => {\n * try {\n * const data = await next();\n * return c.json({ success: true, data, error: null });\n * } catch (err) {\n * if (err instanceof ValidationError) {\n * return c.json({ success: false, error: \"validation\", issues: err.zodError.issues }, 400);\n * }\n * if (err instanceof DomainError) {\n * return c.json({ success: false, error: err.code }, err.statusCode);\n * }\n * throw err; // → falls back to onError or Hono's default 500\n * }\n * }\n * ```\n */\nexport type RouteInterceptor<\n TEnv extends Env = Env,\n TServices extends AnyServicesContainer = AnyServicesContainer,\n> = (ctx: {\n /**\n * Calls validation + handler and returns the raw value.\n * Throws {@link ValidationError} on Zod failure or any error thrown by the handler.\n */\n next: () => Promise<unknown>;\n /** Route metadata (read-only). */\n route: AnyRouteDef;\n /** Hono request context. */\n c: Context<TEnv>;\n /** Global DI services container. See {@link RouteHandler}. */\n services: TServices;\n /**\n * Injected {@link ErrorHandler} when one was passed to the API. Call\n * `errorHandler?.handle({ error, c, route, services })` in your `catch` to\n * reuse the shared mapping, or simply rethrow to let it apply automatically.\n */\n errorHandler?: ErrorHandler<TEnv, TServices>;\n /** Injected {@link Logger} when one was passed to the API, else `undefined`. */\n logger?: Logger;\n}) => Promise<Response | unknown> | Response | unknown;\n\n/**\n * Success-envelope schema declared alongside an interceptor so the generated\n * OpenAPI spec documents what the **wrapper actually returns** (not the raw\n * handler output).\n *\n * - a **static** Zod schema → same envelope for every route (e.g.\n * `z.object({ data: z.any(), intercepted: z.boolean() })`);\n * - a **factory** `(routeOutput) => schema` → wraps each route's own `output`,\n * so `data` is typed per endpoint in the docs.\n */\nexport type InterceptorOutput =\n | z.ZodTypeAny\n | ((routeOutput: z.ZodTypeAny | undefined) => z.ZodTypeAny);\n\n/** A single declared error response for the OpenAPI spec. */\nexport type InterceptorErrorResponse =\n | z.ZodTypeAny\n | { description?: string; schema?: z.ZodTypeAny };\n\n/**\n * Structured interceptor — pairs the cross-cutting {@link RouteInterceptor}\n * `handler` with the OpenAPI metadata describing what it returns, so the docs\n * reflect the real wrapped responses (success envelope + error shapes).\n *\n * @example\n * ```ts\n * interceptor: {\n * // factory: `data` reflects each route's own output schema\n * output: (routeOutput) =>\n * z.object({ data: routeOutput ?? z.unknown(), intercepted: z.boolean() }),\n * errors: {\n * 400: ValidationErrorSchema,\n * 500: { description: \"Internal\", schema: ErrorSchema },\n * },\n * handler: async ({ c, next }) => {\n * const data = await next();\n * return c.json({ data, intercepted: true });\n * },\n * }\n * ```\n */\nexport interface InterceptorConfig<\n TEnv extends Env = Env,\n TServices extends AnyServicesContainer = AnyServicesContainer,\n> {\n /** Success-envelope schema (static) or per-route factory. */\n output?: InterceptorOutput;\n /**\n * Error responses applied to **every** operation, keyed by HTTP status. Pass\n * a bare Zod schema or `{ description, schema }`.\n */\n errors?: Record<number, InterceptorErrorResponse>;\n /** The interceptor function. See {@link RouteInterceptor}. */\n handler: RouteInterceptor<TEnv, TServices>;\n}\n\n/**\n * Interceptor option accepted by the server / registry — either a bare\n * {@link RouteInterceptor} function (legacy) or a structured\n * {@link InterceptorConfig} carrying OpenAPI metadata.\n */\nexport type InterceptorOption<\n TEnv extends Env = Env,\n TServices extends AnyServicesContainer = AnyServicesContainer,\n> = RouteInterceptor<TEnv, TServices> | InterceptorConfig<TEnv, TServices>;\n\n/** OpenAPI document info (subset of the spec used by the helper). */\nexport interface OpenAPIInfo {\n title: string;\n version: string;\n description?: string;\n}\n\n// ── OpenAPI 3.1 Security Scheme Object ──────────────────────────────────────\n\n/** Fields shared by every security scheme. */\nexport interface SecuritySchemeBase {\n /** Human-readable description (CommonMark). */\n description?: string;\n}\n\n/** API key carried in a header, query param or cookie. */\nexport interface ApiKeySecurityScheme extends SecuritySchemeBase {\n type: \"apiKey\";\n /** Name of the header, query parameter or cookie. */\n name: string;\n /** Location of the API key. */\n in: \"query\" | \"header\" | \"cookie\";\n}\n\n/**\n * HTTP authentication (RFC 7235), e.g. `bearer` (Firebase ID tokens) or\n * `basic`.\n */\nexport interface HttpSecurityScheme extends SecuritySchemeBase {\n type: \"http\";\n /** Auth scheme name — `\"bearer\"`, `\"basic\"`, `\"digest\"`, … */\n // eslint-disable-next-line @typescript-eslint/ban-types\n scheme: \"bearer\" | \"basic\" | \"digest\" | (string & {});\n /** Hint for the bearer token format, e.g. `\"JWT\"` / `\"Firebase JWT\"`. */\n bearerFormat?: string;\n}\n\n/** Mutual TLS authentication. */\nexport interface MutualTlsSecurityScheme extends SecuritySchemeBase {\n type: \"mutualTLS\";\n}\n\n/** A single OAuth2 flow. */\nexport interface OAuthFlowObject {\n authorizationUrl?: string;\n tokenUrl?: string;\n refreshUrl?: string;\n /** Available scopes → description. */\n scopes: Record<string, string>;\n}\n\n/** The OAuth2 flows supported by an {@link OAuth2SecurityScheme}. */\nexport interface OAuthFlowsObject {\n implicit?: OAuthFlowObject;\n password?: OAuthFlowObject;\n clientCredentials?: OAuthFlowObject;\n authorizationCode?: OAuthFlowObject;\n}\n\n/** OAuth2 authentication. */\nexport interface OAuth2SecurityScheme extends SecuritySchemeBase {\n type: \"oauth2\";\n flows: OAuthFlowsObject;\n}\n\n/** OpenID Connect Discovery. */\nexport interface OpenIdConnectSecurityScheme extends SecuritySchemeBase {\n type: \"openIdConnect\";\n openIdConnectUrl: string;\n}\n\n/** OpenAPI 3.1 Security Scheme Object (discriminated on `type`). */\nexport type SecurityScheme =\n | ApiKeySecurityScheme\n | HttpSecurityScheme\n | MutualTlsSecurityScheme\n | OAuth2SecurityScheme\n | OpenIdConnectSecurityScheme;\n\n/**\n * A single Security Requirement Object: maps a scheme name (a key of\n * {@link OpenAPIConfig.securitySchemes}) to the list of required scopes\n * (empty `[]` for `http` / `apiKey`).\n */\nexport type SecurityRequirement = Record<string, string[]>;\n\n/** OpenAPI configuration on the server. */\nexport interface OpenAPIConfig {\n /** Path served by the JSON spec (e.g. `/openapi.json`). Default: `/openapi.json`. */\n path?: string;\n /** Path serving the documentation UI. Set to `false` to disable. Default: `/docs`. */\n docsPath?: string | false;\n /** OpenAPI document info. */\n info: OpenAPIInfo;\n /** Optional servers list for the spec. */\n servers?: { url: string; description?: string }[];\n /**\n * Reusable security schemes, keyed by name. The keys are referenced from\n * {@link OpenAPIConfig.security} / per-route `security`.\n *\n * @example\n * ```ts\n * securitySchemes: {\n * bearerAuth: { type: \"http\", scheme: \"bearer\", bearerFormat: \"Firebase JWT\" },\n * }\n * ```\n */\n securitySchemes?: Record<string, SecurityScheme>;\n /**\n * Default security requirement applied to every operation. Each entry maps a\n * scheme name (a key of {@link OpenAPIConfig.securitySchemes}) to its scopes.\n *\n * @example `security: [{ bearerAuth: [] }]`\n */\n security?: SecurityRequirement[];\n /**\n * Hono middleware(s) guarding **only** the docs UI and JSON spec endpoints\n * (not the API routes). Use a raw middleware for a custom flow, or the\n * built-in {@link firebaseBearerAuth} / {@link basicAuth} helpers.\n *\n * @example\n * ```ts\n * import { firebaseBearerAuth } from \"@lpdjs/firestore-repo-service/servers/hono\";\n * openapi: { info, docsAuth: firebaseBearerAuth({ getAuth }) }\n * ```\n *\n * For a full login form + session cookie (like the admin server), pass the\n * {@link DocsAuthExtension} returned by `firebaseDocsAuth({ ... })` instead.\n */\n docsAuth?: MiddlewareHandler | MiddlewareHandler[] | DocsAuthExtension;\n}\n\n/** Options consumed by the {@link HonoServer} constructor. */\nexport interface HonoServerOptions<TEnv extends Env = Env> {\n /**\n * API tag — only routes whose `api` matches this value are mounted.\n * If omitted, every route in the registry is mounted.\n */\n api?: string;\n\n /** Pre-resolved route registry (typically the codegen output). */\n routes: AnyRouteDef[];\n\n /** URL prefix mounted before every route path. Default: `\"\"`. */\n basePath?: string;\n\n /** Hono middlewares applied to every route (after the built-ins). */\n middlewares?: MiddlewareHandler<TEnv>[];\n\n /**\n * Alias for `middlewares` — global middlewares applied to every route.\n * If both are provided, `globalMiddlewares` is appended after `middlewares`.\n */\n globalMiddlewares?: MiddlewareHandler<TEnv>[];\n\n /**\n * If `true`, the server validates the value returned by every handler\n * against the route's `output` schema and rejects mismatches with a 500\n * response. Useful in dev / staging. Default: `false`.\n */\n validateOutput?: boolean;\n\n /** Enable verbose logging of mounted routes at startup. Default: `false`. */\n verbose?: boolean;\n\n /** OpenAPI configuration. Omit to disable. */\n openapi?: OpenAPIConfig;\n\n /** Custom 404 handler. */\n notFound?: (c: Context<TEnv>) => Response | Promise<Response>;\n\n /** Custom error handler. */\n onError?: (err: unknown, c: Context<TEnv>) => Response | Promise<Response>;\n\n /**\n * Cross-cutting interceptor wrapping every handler call.\n * Ideal for response envelopes, business-error mapping, tracing.\n *\n * Pass a bare {@link RouteInterceptor} function, or an\n * {@link InterceptorConfig} (`{ output?, errors?, handler }`) so the\n * generated OpenAPI spec documents the wrapped responses.\n */\n interceptor?: InterceptorOption<TEnv>;\n\n /**\n * Cross-cutting error strategy applied to every uncaught error and injected\n * into every handler / interceptor context. See {@link ErrorHandler}.\n *\n * Typically shared across APIs — pass it once to `createApiRegistry` via\n * `{ services, errorHandler }`; this per-API field overrides it.\n */\n errorHandler?: ErrorHandler<TEnv>;\n\n /**\n * Structured {@link Logger} injected into every handler / interceptor /\n * error-handler context. Extend the package's `BaseLogger` to route to your\n * sink. Typically shared via `createApiRegistry({ services, logger })`; this\n * per-API field overrides it.\n */\n logger?: Logger;\n\n /**\n * Global DI services container (see {@link createServices}).\n *\n * When provided:\n * - a middleware is installed automatically so the built-in `ctx`\n * service resolves to the current request via `AsyncLocalStorage`;\n * - `services` is passed into every handler and the interceptor.\n *\n * The same container instance should be shared across every API of your\n * project — declare it once and pass it to {@link createApiRegistry}.\n */\n services?: AnyServicesContainer;\n}\n","/**\n * Built-in error types thrown by the server pipeline and their default\n * HTTP mapping — shared by the request handler and {@link BaseErrorHandler}.\n */\n\nimport type { ZodError } from \"zod\";\nimport { ValidationError } from \"./types\";\n\n/** Thrown when the request body cannot be read / parsed → HTTP 400. */\nexport class BadRequestError extends Error {\n readonly statusCode = 400 as const;\n constructor(message: string) {\n super(message);\n this.name = \"BadRequestError\";\n }\n}\n\n/** Thrown when a handler's return value fails the `output` schema → HTTP 500. */\nexport class OutputValidationError extends Error {\n readonly statusCode = 500 as const;\n constructor(readonly zodError: ZodError) {\n super(\"Output validation failed\");\n this.name = \"OutputValidationError\";\n }\n}\n\n/** Flatten a `ZodError` into a compact `{ path, code, message }[]`. */\nexport function formatZodIssues(error: ZodError): unknown {\n return error.issues.map((i) => ({\n path: i.path.join(\".\"),\n code: i.code,\n message: i.message,\n }));\n}\n\n/**\n * Default JSON mapping for the package's own errors (`ValidationError`,\n * `BadRequestError`, `OutputValidationError`). Returns `null` for anything\n * else so the caller can decide (rethrow / custom handler).\n */\nexport function defaultErrorResponse(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n c: any,\n err: unknown,\n): Response | null {\n if (err instanceof ValidationError) {\n return c.json(\n {\n success: false,\n error: \"Validation failed\",\n issues: formatZodIssues(err.zodError),\n },\n 400,\n );\n }\n if (err instanceof BadRequestError) {\n return c.json(\n { success: false, error: \"Bad Request\", message: err.message },\n 400,\n );\n }\n if (err instanceof OutputValidationError) {\n return c.json(\n {\n success: false,\n error: \"Output validation failed\",\n issues: formatZodIssues(err.zodError),\n },\n 500,\n );\n }\n return null;\n}\n","/**\n * OpenAPI 3.1 spec generator from {@link RouteDef} entries.\n *\n * Uses `@asteasolutions/zod-to-openapi` directly so users keep importing the\n * vanilla `zod` package (no opinionated `z` re-export required).\n */\n\nimport {\n OpenAPIRegistry,\n OpenApiGeneratorV31,\n extendZodWithOpenApi,\n} from \"@asteasolutions/zod-to-openapi\";\nimport { z } from \"zod\";\nimport type {\n AnyRouteDef,\n HttpMethod,\n InterceptorConfig,\n InterceptorErrorResponse,\n OpenAPIConfig,\n PayloadSource,\n} from \"./types\";\n\n// Patches Zod prototype with `.openapi()` and enables schema → OpenAPI\n// conversion for vanilla zod schemas. Idempotent — safe to call multiple times.\nextendZodWithOpenApi(z);\n\nconst DEFAULT_RESPONSE_DESCRIPTION = \"Successful response\";\nconst DEFAULT_ERROR_DESCRIPTION = \"Error response\";\n\nfunction defaultSource(method: HttpMethod): PayloadSource {\n return method === \"get\" ? \"query\" : \"json\";\n}\n\n/**\n * Resolve the success-envelope schema for a route, honouring an interceptor's\n * static schema or per-route factory. Falls back to the raw `route.output`.\n */\nfunction resolveSuccessSchema(\n routeOutput: z.ZodTypeAny | undefined,\n interceptor: InterceptorConfig | undefined,\n): z.ZodTypeAny | undefined {\n const out = interceptor?.output;\n if (!out) return routeOutput;\n return typeof out === \"function\" ? out(routeOutput) : out;\n}\n\n/** Normalise a declared error response to `{ description, schema? }`. */\nfunction normalizeErrorResponse(\n entry: InterceptorErrorResponse,\n): { description: string; schema?: z.ZodTypeAny } {\n // A Zod schema exposes `safeParse`; a plain config object does not.\n if (typeof (entry as { safeParse?: unknown }).safeParse === \"function\") {\n return { description: DEFAULT_ERROR_DESCRIPTION, schema: entry as z.ZodTypeAny };\n }\n const cfg = entry as { description?: string; schema?: z.ZodTypeAny };\n return { description: cfg.description ?? DEFAULT_ERROR_DESCRIPTION, schema: cfg.schema };\n}\n\n/** Build the OpenAPI document from the mounted route registry. */\nexport function buildOpenApiDocument(\n routes: AnyRouteDef[],\n basePath: string,\n config: OpenAPIConfig,\n interceptor?: InterceptorConfig,\n): Record<string, unknown> {\n const registry = new OpenAPIRegistry();\n\n if (config.securitySchemes) {\n for (const [name, scheme] of Object.entries(config.securitySchemes)) {\n // The registry's runtime accepts any spec-shaped object; cast through\n // `unknown` to satisfy zod-to-openapi's stricter typings.\n registry.registerComponent(\n \"securitySchemes\",\n name,\n scheme as unknown as Parameters<\n typeof registry.registerComponent\n >[2],\n );\n }\n }\n\n for (const route of routes) {\n const method = route.method;\n const source = route.source ?? defaultSource(method);\n const fullPath = joinPath(basePath, route.path ?? \"/\");\n const status = route.status ?? 200;\n\n const requestBody = buildRequestBody(method, source, route.input);\n const requestQuery = buildQueryOrParam(source, route.input, \"query\");\n const requestParams = buildQueryOrParam(source, route.input, \"param\");\n const operationId = makeOperationId(method, fullPath);\n\n // Success response — wrapped by the interceptor envelope when declared.\n const successSchema = resolveSuccessSchema(route.output, interceptor);\n const responses: Record<string, unknown> = {\n [status]: successSchema\n ? {\n description: DEFAULT_RESPONSE_DESCRIPTION,\n content: { \"application/json\": { schema: successSchema } },\n }\n : { description: DEFAULT_RESPONSE_DESCRIPTION },\n };\n\n // Declared error responses (interceptor.errors) applied to every operation.\n if (interceptor?.errors) {\n for (const [code, entry] of Object.entries(interceptor.errors)) {\n const { description, schema } = normalizeErrorResponse(entry);\n responses[code] = schema\n ? { description, content: { \"application/json\": { schema } } }\n : { description };\n }\n }\n\n registry.registerPath({\n method,\n path: convertExpressPathToOpenApi(fullPath),\n operationId,\n summary: route.summary,\n description: route.description,\n tags: route.tags,\n deprecated: route.deprecated,\n security: route.security,\n // Cast: registerPath types narrow query/params to ZodObject — we accept\n // any ZodTypeAny at runtime and let users pass plain objects via z.object.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n request: {\n ...(requestQuery ? { query: requestQuery } : {}),\n ...(requestParams ? { params: requestParams } : {}),\n ...(requestBody ? { body: requestBody } : {}),\n } as any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n responses: responses as any,\n });\n }\n\n const generator = new OpenApiGeneratorV31(registry.definitions);\n const document = generator.generateDocument({\n openapi: \"3.1.0\",\n // OpenAPIInfo is structurally compatible; cast to satisfy the `x-*` index.\n info: config.info as Parameters<\n typeof generator.generateDocument\n >[0][\"info\"],\n servers: config.servers,\n security: config.security,\n });\n return document as unknown as Record<string, unknown>;\n}\n\nfunction buildRequestBody(\n method: HttpMethod,\n source: PayloadSource,\n schema: z.ZodTypeAny | undefined,\n): { content: Record<string, { schema: z.ZodTypeAny }> } | null {\n if (!schema) return null;\n if (method === \"get\") return null;\n if (source === \"json\") {\n return { content: { \"application/json\": { schema } } };\n }\n if (source === \"form\") {\n return {\n content: { \"application/x-www-form-urlencoded\": { schema } },\n };\n }\n return null;\n}\n\nfunction buildQueryOrParam(\n source: PayloadSource,\n schema: z.ZodTypeAny | undefined,\n target: \"query\" | \"param\",\n): z.ZodTypeAny | undefined {\n if (!schema) return undefined;\n if (target === \"query\" && source === \"query\") return schema;\n if (target === \"param\" && source === \"param\") return schema;\n return undefined;\n}\n\n/** Convert `:foo` style express params to `{foo}` OpenAPI placeholders. */\nfunction convertExpressPathToOpenApi(path: string): string {\n return path.replace(/:([A-Za-z0-9_]+)/g, \"{$1}\");\n}\n\nfunction joinPath(base: string, path: string): string {\n const left = base.endsWith(\"/\") ? base.slice(0, -1) : base;\n const right = path.startsWith(\"/\") ? path : `/${path}`;\n const merged = `${left}${right}`;\n return merged === \"\" ? \"/\" : merged;\n}\n\nfunction makeOperationId(method: HttpMethod, path: string): string {\n const cleaned = path\n .replace(/[{}]/g, \"\")\n .replace(/\\/+/g, \"_\")\n .replace(/[^A-Za-z0-9_]/g, \"\")\n .replace(/^_+|_+$/g, \"\");\n return `${method}_${cleaned || \"root\"}`;\n}\n\n/**\n * Render a self-contained Scalar API Reference HTML page that points to the\n * generated spec. Loaded from CDN — no build step required.\n */\nexport function renderDocsHtml(specUrl: string, title: string): string {\n const safeUrl = specUrl.replace(/\"/g, \"&quot;\");\n const safeTitle = title\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\");\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\" />\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\" />\n<title>${safeTitle}</title>\n</head>\n<body>\n<script id=\"api-reference\" data-url=\"${safeUrl}\"></script>\n<script src=\"https://cdn.jsdelivr.net/npm/@scalar/api-reference\"></script>\n</body>\n</html>`;\n}\n","/**\n * Hono-native auth guards for the OpenAPI docs / spec endpoints.\n *\n * These return plain Hono `MiddlewareHandler`s, so they slot into\n * `OpenAPIConfig.docsAuth` (which protects only `/docs` + `/openapi.json`,\n * never the API routes). For a fully custom flow, pass your own middleware\n * instead of these helpers.\n */\n\nimport type { MiddlewareHandler } from \"hono\";\nimport { renderLoginPage } from \"../auth/login-page\";\nimport { parseCookies } from \"../auth/session\";\nimport type {\n DecodedIdTokenLike,\n FirebaseAdminAuthLike,\n} from \"../auth/firebase-auth\";\n\n/** Decoded token shape — kept minimal to avoid a hard firebase-admin import. */\nexport interface DecodedBearerToken {\n uid: string;\n email?: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [claim: string]: any;\n}\n\n/** Minimal Firebase Admin Auth surface used by {@link firebaseBearerAuth}. */\nexport interface FirebaseBearerAuthLike {\n verifyIdToken(\n idToken: string,\n checkRevoked?: boolean,\n ): Promise<DecodedBearerToken>;\n}\n\n/** Options for {@link firebaseBearerAuth}. */\nexport interface FirebaseBearerAuthOptions {\n /**\n * Returns the Firebase Admin Auth instance, e.g. `() => getAuth()`. Called\n * lazily on each request so `initializeApp()` runs first.\n */\n getAuth: () => FirebaseBearerAuthLike;\n /**\n * Authorization policy. Return `false` (or throw) to reject the request,\n * any truthy value to allow. Defaults to allowing any verified token.\n */\n allow?: (token: DecodedBearerToken) => boolean | Promise<boolean>;\n /** Revoke check passed to `verifyIdToken`. Default: `false`. */\n checkRevoked?: boolean;\n /**\n * Context key under which the decoded token is stored (`c.set(key, token)`)\n * for downstream handlers. Default: `\"docsUser\"`.\n */\n contextKey?: string;\n}\n\n/**\n * Guard the docs / spec endpoints with a Firebase ID token (Bearer scheme).\n *\n * @example\n * ```ts\n * import { getAuth } from \"firebase-admin/auth\";\n * import { firebaseBearerAuth } from \"@lpdjs/firestore-repo-service/servers/hono\";\n *\n * openapi: {\n * info,\n * docsAuth: firebaseBearerAuth({\n * getAuth: () => getAuth(),\n * allow: (t) => t.admin === true,\n * }),\n * }\n * ```\n */\nexport function firebaseBearerAuth(\n options: FirebaseBearerAuthOptions,\n): MiddlewareHandler {\n const {\n getAuth,\n allow,\n checkRevoked = false,\n contextKey = \"docsUser\",\n } = options;\n\n return async (c, next) => {\n const header = c.req.header(\"authorization\") ?? c.req.header(\"Authorization\");\n const match = header?.match(/^Bearer\\s+(.+)$/i);\n if (!match) {\n return c.json({ error: \"Unauthorized\" }, 401, {\n \"WWW-Authenticate\": \"Bearer\",\n });\n }\n\n let decoded: DecodedBearerToken;\n try {\n decoded = await getAuth().verifyIdToken(match[1]!, checkRevoked);\n } catch {\n return c.json({ error: \"Unauthorized\" }, 401, {\n \"WWW-Authenticate\": \"Bearer\",\n });\n }\n\n if (allow) {\n let permitted = false;\n try {\n permitted = await allow(decoded);\n } catch {\n permitted = false;\n }\n if (!permitted) return c.json({ error: \"Forbidden\" }, 403);\n }\n\n c.set(contextKey, decoded);\n return next();\n };\n}\n\n/** Options for {@link basicAuth}. */\nexport interface BasicAuthOptions {\n username: string;\n password: string;\n /** Realm advertised in the `WWW-Authenticate` header. Default: `\"Docs\"`. */\n realm?: string;\n}\n\n/**\n * Guard the docs / spec endpoints with HTTP Basic Auth.\n *\n * @example\n * ```ts\n * openapi: { info, docsAuth: basicAuth({ username: \"admin\", password: \"secret\" }) }\n * ```\n */\nexport function basicAuth(options: BasicAuthOptions): MiddlewareHandler {\n const { username, password, realm = \"Docs\" } = options;\n const expected = `Basic ${btoa(`${username}:${password}`)}`;\n\n return async (c, next) => {\n const header =\n c.req.header(\"authorization\") ?? c.req.header(\"Authorization\") ?? \"\";\n if (!timingSafeEqual(header, expected)) {\n return c.text(\"Unauthorized\", 401, {\n \"WWW-Authenticate\": `Basic realm=\"${realm}\"`,\n });\n }\n return next();\n };\n}\n\n/** Constant-time string comparison to avoid leaking length/contents via timing. */\nfunction timingSafeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);\n return diff === 0;\n}\n\n// ===========================================================================\n// Firebase login-form auth (session cookie) — mirrors the admin server flow\n// ===========================================================================\n\n/** A bare auxiliary route name (relative to the docs directory). */\nexport interface DocsAuthRoute {\n method: \"GET\" | \"POST\";\n /** Bare path segment relative to the docs directory, e.g. `\"__login\"`. */\n name: string;\n handler: MiddlewareHandler;\n}\n\n/**\n * Richer `docsAuth` value (vs. a bare `MiddlewareHandler`): a guard middleware\n * **plus** auxiliary routes (login page, session exchange, logout) that the\n * {@link HonoServer} mounts next to the docs/spec endpoints. Mirrors the admin\n * server's `AuthExtension`. Produced by {@link firebaseDocsAuth}.\n */\nexport interface DocsAuthExtension {\n readonly __docsAuthExtension: true;\n /** Guard applied to the docs UI + JSON spec endpoints. */\n middleware: MiddlewareHandler;\n /** Auxiliary routes mounted (unguarded) in the docs directory. */\n routes: DocsAuthRoute[];\n /** Bare login route name, used to redirect unauthenticated browsers. */\n loginName: string;\n}\n\n/** Type guard distinguishing a {@link DocsAuthExtension} from a raw middleware. */\nexport function isDocsAuthExtension(value: unknown): value is DocsAuthExtension {\n return (\n typeof value === \"object\" &&\n value !== null &&\n (value as { __docsAuthExtension?: unknown }).__docsAuthExtension === true\n );\n}\n\n/** Options for {@link firebaseDocsAuth}. */\nexport interface FirebaseDocsAuthOptions {\n /**\n * Returns the Firebase Admin Auth instance, e.g. `() => getAuth()`. Called\n * lazily on each request so `initializeApp()` runs first. Must expose\n * `verifyIdToken`, `verifySessionCookie`, `createSessionCookie`,\n * `revokeRefreshTokens`.\n */\n getAuth: () => FirebaseAdminAuthLike;\n /** Firebase Web API key — required by the JS SDK on the login page. */\n apiKey: string;\n /** Firebase Auth domain (e.g. `my-project.firebaseapp.com`). */\n authDomain: string;\n /**\n * Transport mode. `\"cookie\"` (default) gates the docs behind the bundled\n * login form + a server-side session cookie. `\"both\"` additionally accepts a\n * `Bearer` ID token (handy to embed the docs in an authenticated iframe).\n */\n mode?: \"cookie\" | \"both\";\n /**\n * Authorization policy. Return `false` (or throw) to reject, any truthy value\n * to allow. Defaults to allowing any verified user. Receives the decoded\n * ID-token / session-cookie claims.\n */\n allow?: (token: DecodedIdTokenLike) => boolean | Promise<boolean>;\n /** Providers shown on the login page. Default: `[\"password\", \"google\"]`. */\n providers?: (\"password\" | \"google\")[];\n /** Login page title. Default: `\"Docs sign-in\"`. */\n title?: string;\n /** Session cookie name. Default: `\"__docs_session\"`. */\n cookieName?: string;\n /** Session cookie TTL in days. Default: `5` (Firebase max is 14). */\n sessionTtlDays?: number;\n /** Cookie `Secure` flag. Default: `true` (set `false` only for local HTTP). */\n secureCookie?: boolean;\n /** Cookie `SameSite`. Default: `\"Lax\"`. */\n sameSite?: \"Strict\" | \"Lax\" | \"None\";\n /**\n * Context key under which the decoded token is stored (`c.set(key, token)`)\n * for downstream handlers. Default: `\"docsUser\"`.\n */\n contextKey?: string;\n /**\n * Behaviour when authentication fails. `\"redirect\"` (default) sends browser\n * `GET`s to the login page; `\"401\"` always returns a JSON 401.\n */\n onUnauthenticated?: \"redirect\" | \"401\";\n /**\n * Firebase Auth emulator host (e.g. `127.0.0.1:9099`). When set, the login\n * page's client SDK targets the emulator via `connectAuthEmulator`, matching\n * the Admin SDK (which already routes to the emulator when\n * `FIREBASE_AUTH_EMULATOR_HOST` is set). Defaults to that env var; pass `\"\"`\n * to force it off.\n */\n authEmulatorHost?: string;\n}\n\nconst LOGIN_NAME = \"__login\";\nconst SESSION_NAME = \"__session\";\nconst LOGOUT_NAME = \"__logout\";\n\n/** Last path segment, e.g. `/v1/docs` → `docs`. Empty string for `/`. */\nfunction lastSegment(path: string): string {\n const segs = path.split(\"?\")[0]!.split(\"/\").filter(Boolean);\n return segs[segs.length - 1] ?? \"\";\n}\n\n/** Build a `Set-Cookie` header value (HttpOnly, path-scoped). */\nfunction buildSetCookie(\n name: string,\n value: string,\n opts: {\n maxAgeSeconds: number;\n secure: boolean;\n sameSite: \"Strict\" | \"Lax\" | \"None\";\n },\n): string {\n const segments = [\n `${name}=${value}`,\n \"Path=/\",\n `Max-Age=${opts.maxAgeSeconds}`,\n \"HttpOnly\",\n `SameSite=${opts.sameSite}`,\n ];\n if (opts.secure) segments.push(\"Secure\");\n return segments.join(\"; \");\n}\n\n/** Restrict a `next` target to a simple same-origin relative token. */\nfunction sanitizeNext(raw: string | undefined, fallback: string): string {\n if (!raw) return fallback;\n if (raw.startsWith(\"/\") || raw.includes(\"://\") || raw.includes(\"\\\\\")) {\n return fallback;\n }\n return raw;\n}\n\n/**\n * Guard the docs / spec endpoints with a Firebase **login form + session\n * cookie**, the same flow as the admin server — instead of forcing callers to\n * craft a `Bearer` token by hand.\n *\n * Returns a {@link DocsAuthExtension}: pass it straight to\n * `OpenAPIConfig.docsAuth`. The {@link HonoServer} mounts the bundled\n * `__login` / `__session` / `__logout` routes next to the docs and applies the\n * guard. Unauthenticated browsers are redirected to the login page; once signed\n * in, an HttpOnly session cookie keeps them authenticated.\n *\n * @example\n * ```ts\n * import { getAuth } from \"firebase-admin/auth\";\n * import { firebaseDocsAuth } from \"@lpdjs/firestore-repo-service/servers/hono\";\n *\n * openapi: {\n * info,\n * docsAuth: firebaseDocsAuth({\n * getAuth: () => getAuth(),\n * apiKey: process.env.FIREBASE_API_KEY!,\n * authDomain: process.env.FIREBASE_AUTH_DOMAIN!,\n * allow: (t) => t.admin === true, // optional policy\n * }),\n * }\n * ```\n */\nexport function firebaseDocsAuth(\n options: FirebaseDocsAuthOptions,\n): DocsAuthExtension {\n const {\n getAuth,\n apiKey,\n authDomain,\n mode = \"cookie\",\n allow,\n providers = [\"password\", \"google\"],\n title = \"Docs sign-in\",\n cookieName = \"__docs_session\",\n sessionTtlDays = 5,\n secureCookie = true,\n sameSite = \"Lax\",\n contextKey = \"docsUser\",\n onUnauthenticated = \"redirect\",\n authEmulatorHost = process.env[\"FIREBASE_AUTH_EMULATOR_HOST\"],\n } = options;\n\n async function passesAllow(token: DecodedIdTokenLike): Promise<boolean> {\n if (!allow) return true;\n try {\n return Boolean(await allow(token));\n } catch {\n return false;\n }\n }\n\n // ── Login page (GET __login) ──────────────────────────────────────────────\n const loginHandler: MiddlewareHandler = async (c) => {\n // Validate lazily (at request time) so importing this module during the\n // Firebase CLI analysis / emulator load doesn't throw before env vars are\n // injected — same approach as the admin `firebaseAuth`.\n if (!apiKey || !authDomain) {\n throw new Error(\n \"[firebaseDocsAuth] `apiKey` and `authDomain` are required for the login \" +\n \"page. Find both in the Firebase Console → Project Settings → General → \" +\n \"Web app config.\",\n );\n }\n const next = sanitizeNext(c.req.query(\"next\"), \"docs\");\n const error = c.req.query(\"error\") ?? null;\n const html = renderLoginPage({\n title,\n providers,\n apiKey,\n authDomain,\n // Relative to the login page URL (resolved client-side), so it works\n // behind any Cloud Functions / reverse-proxy prefix.\n sessionPath: SESSION_NAME,\n next,\n error,\n authEmulatorHost,\n });\n return c.html(html, 200, { \"Cache-Control\": \"no-store\" });\n };\n\n // ── Session exchange (POST __session) ─────────────────────────────────────\n const sessionHandler: MiddlewareHandler = async (c) => {\n let idToken = \"\";\n try {\n const body = (await c.req.json()) as { idToken?: unknown };\n idToken = typeof body.idToken === \"string\" ? body.idToken : \"\";\n } catch {\n idToken = \"\";\n }\n if (!idToken) {\n return c.json({ success: false, error: \"Missing idToken\" }, 400);\n }\n\n const expiresInMs = sessionTtlDays * 24 * 60 * 60 * 1000;\n try {\n const auth = getAuth();\n const decoded = await auth.verifyIdToken(idToken, true);\n if (!(await passesAllow(decoded))) {\n return c.json({ success: false, error: \"Forbidden\" }, 403);\n }\n // Reject stale sign-ins (Google guidance: require a recent auth, < 5 min).\n const authTimeRaw = (decoded as { auth_time?: number }).auth_time;\n const authTime =\n typeof authTimeRaw === \"number\" ? authTimeRaw * 1000 : Date.now();\n if (Date.now() - authTime > 5 * 60 * 1000) {\n return c.json(\n { success: false, error: \"Recent sign-in required\" },\n 401,\n );\n }\n const sessionCookie = await auth.createSessionCookie(idToken, {\n expiresIn: expiresInMs,\n });\n const cookie = buildSetCookie(\n cookieName,\n encodeURIComponent(sessionCookie),\n {\n maxAgeSeconds: Math.floor(expiresInMs / 1000),\n secure: secureCookie,\n sameSite,\n },\n );\n c.header(\"Set-Cookie\", cookie);\n return c.json({ success: true });\n } catch (err) {\n const message = err instanceof Error ? err.message : \"Invalid idToken\";\n return c.json({ success: false, error: message }, 401);\n }\n };\n\n // ── Logout (POST __logout) ────────────────────────────────────────────────\n const logoutHandler: MiddlewareHandler = async (c) => {\n const cookies = parseCookies(c.req.header(\"cookie\") ?? \"\");\n const session = cookies[cookieName];\n if (session) {\n try {\n const auth = getAuth();\n const decoded = await auth.verifySessionCookie(session, false);\n await auth.revokeRefreshTokens(decoded.uid);\n } catch {\n /* best-effort */\n }\n }\n c.header(\n \"Set-Cookie\",\n buildSetCookie(cookieName, \"\", {\n maxAgeSeconds: 0,\n secure: secureCookie,\n sameSite,\n }),\n );\n return c.json({ success: true });\n };\n\n // ── Guard middleware (docs + spec) ────────────────────────────────────────\n const middleware: MiddlewareHandler = async (c, next) => {\n const auth = getAuth();\n\n // mode \"both\": accept a Bearer ID token first (e.g. iframe embedding).\n if (mode === \"both\") {\n const header =\n c.req.header(\"authorization\") ?? c.req.header(\"Authorization\");\n const match = header?.match(/^Bearer\\s+(.+)$/i);\n if (match) {\n try {\n const decoded = await auth.verifyIdToken(match[1]!, false);\n if (await passesAllow(decoded)) {\n c.set(contextKey, decoded);\n return next();\n }\n } catch {\n /* fall through to cookie / unauthenticated */\n }\n }\n }\n\n // Session cookie.\n const cookies = parseCookies(c.req.header(\"cookie\") ?? \"\");\n const session = cookies[cookieName];\n if (session) {\n try {\n const decoded = await auth.verifySessionCookie(session, false);\n if (await passesAllow(decoded)) {\n c.set(contextKey, decoded);\n return next();\n }\n } catch {\n /* unauthenticated */\n }\n }\n\n // Unauthenticated.\n const accept = c.req.header(\"accept\") ?? \"\";\n const isBrowserGet =\n c.req.method === \"GET\" && accept.includes(\"text/html\");\n if (onUnauthenticated === \"redirect\" && isBrowserGet) {\n const target = encodeURIComponent(lastSegment(c.req.path) || \"docs\");\n // Relative to the requested page (login route is a sibling), so the\n // external prefix is preserved by the browser.\n return c.redirect(`${LOGIN_NAME}?next=${target}`, 302);\n }\n return c.json({ error: \"Unauthorized\" }, 401);\n };\n\n return {\n __docsAuthExtension: true,\n middleware,\n loginName: LOGIN_NAME,\n routes: [\n { method: \"GET\", name: LOGIN_NAME, handler: loginHandler },\n { method: \"POST\", name: SESSION_NAME, handler: sessionHandler },\n { method: \"POST\", name: LOGOUT_NAME, handler: logoutHandler },\n ],\n };\n}\n","/**\n * Global DI services container for the Hono server.\n *\n * Lets you declare all your singletons (repositories, SDK clients, useCases,\n * loggers…) **once**, then inject them anywhere — routes, interceptors,\n * cron jobs, Firestore triggers, tests.\n *\n * ## How it works\n *\n * - Each service is constructed **lazily** on first access and cached for\n * the process lifetime (perfect for Cloud Functions cold-start).\n * - Providers may be **classes** (auto-injected: `new Class(services)`)\n * or **factories** (`(services) => instance`). Mix both freely.\n * - Inter-service dependencies are inferred either by destructuring the\n * factory argument (`postRepo: ({ db }) => new PostRepo(db)`) or by\n * reading `this.services.*` inside a class.\n * - A built-in `ctx` service exposes the **current request's** Hono\n * `Context` via `AsyncLocalStorage`. UseCases access\n * `this.services.ctx.c.get(\"user\")` without any plumbing.\n * - Cycles are detected at first access with a clear error.\n *\n * @example\n * ```ts\n * // src/services.ts — infrastructure singletons only (no useCases here)\n * import { createServices } from \"@lpdjs/firestore-repo-service/servers/hono\";\n * import { PostRepo } from \"./domains/posts/PostRepo.js\";\n * import { Mailer } from \"./services/Mailer.js\";\n *\n * export const services = createServices({\n * postRepo: PostRepo, // class form (auto-injected)\n * mailer: ({ ctx }) => new Mailer(ctx), // factory form\n * });\n *\n * export type Services = typeof services;\n * ```\n *\n * @example\n * ```ts\n * // src/apis.ts\n * import { services } from \"./services.js\";\n * export const apis = createApiRegistry(\n * { v1: { basePath: \"/v1\", ... } },\n * { services },\n * );\n * ```\n *\n * @example\n * ```ts\n * // Inside a useCase — extends the UseCase base, owns its Zod schemas\n * import { z } from \"zod\";\n * import { UseCase } from \"@lpdjs/firestore-repo-service/servers/hono\";\n * import type { Services } from \"../../services.js\";\n *\n * const input = z.object({ title: z.string() });\n * const output = z.object({ id: z.string() });\n *\n * export class CreatePostUseCase extends UseCase<typeof input, typeof output, Services> {\n * static readonly input = input;\n * static readonly output = output;\n *\n * async execute(payload: z.infer<typeof input>): Promise<z.infer<typeof output>> {\n * const user = this.services.ctx.c.get(\"user\");\n * return this.services.postRepo.create({ ...payload, authorId: user.id });\n * }\n * }\n * ```\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { Context, Env, MiddlewareHandler } from \"hono\";\n\n// ---------------------------------------------------------------------------\n// Request-scoped context (AsyncLocalStorage backed)\n// ---------------------------------------------------------------------------\n\n/**\n * Per-request context exposed to every service / useCase.\n * The instance is a **stable singleton** but its `c` getter resolves to the\n * Hono `Context` of the currently-handled request via `AsyncLocalStorage`.\n *\n * Outside of a request (cron, manual scripts, tests), wrap your call in\n * {@link withRequestContext} to supply a context, otherwise accessing `c`\n * will throw.\n */\nexport interface RequestContext<TEnv extends Env = Env> {\n /** Hono `Context` of the currently-handled request. */\n readonly c: Context<TEnv>;\n /**\n * Same as `c` but returns `undefined` instead of throwing when called\n * outside a request scope. Useful for opportunistic logging.\n */\n readonly maybeC: Context<TEnv> | undefined;\n}\n\ninterface RequestStore {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n c: Context<any>;\n}\n\nconst als = new AsyncLocalStorage<RequestStore>();\n\nconst requestContextSingleton: RequestContext = Object.freeze({\n get c() {\n const store = als.getStore();\n if (!store) {\n throw new Error(\n \"[services] requestContext.c was accessed outside of a request. \" +\n \"Wrap non-HTTP code paths (cron, triggers, scripts, tests) in \" +\n \"`withRequestContext({ c }, () => ...)` to supply a Hono Context.\",\n );\n }\n return store.c;\n },\n get maybeC() {\n return als.getStore()?.c;\n },\n});\n\n/**\n * Hono middleware installed automatically by `HonoServer` when a `services`\n * container is provided. Populates the AsyncLocalStorage so the built-in\n * `ctx` service resolves to the current request.\n *\n * Exported for advanced cases (custom server / non-Hono adapter); you do not\n * need to call this manually in the standard flow.\n */\nexport function createRequestContextMiddleware(): MiddlewareHandler {\n return async (c, next) => {\n await als.run({ c }, async () => {\n await next();\n });\n };\n}\n\n/**\n * Run `fn` with a synthetic request context — required when invoking\n * services outside an HTTP handler (cron jobs, Firestore triggers, scripts,\n * unit tests). Inside `fn`, `services.ctx.c` resolves to the supplied `c`.\n *\n * @example\n * ```ts\n * // A cron that reuses a useCase\n * export const dailyTask = onSchedule(\"every 24 hours\", async () => {\n * await withRequestContext({ c: fakeContext() }, async () => {\n * await services.createPostUseCase.execute({ ... });\n * });\n * });\n * ```\n */\nexport function withRequestContext<T>(\n ctx: { c: Context },\n fn: () => Promise<T> | T,\n): Promise<T> {\n return als.run({ c: ctx.c }, async () => fn());\n}\n\n// ---------------------------------------------------------------------------\n// createServices\n// ---------------------------------------------------------------------------\n\n/**\n * Reserved service name — the built-in request context. User factories\n * cannot override it.\n */\nconst CTX_KEY = \"ctx\" as const;\n\n/**\n * Helper that derives the public services type from an output map.\n * Each entry in `TMap` is the instance type returned by its provider.\n * The built-in `ctx` is always present.\n */\nexport type ServicesOf<TMap> = { readonly ctx: RequestContext } & {\n readonly [K in keyof TMap]: TMap[K];\n};\n\n/**\n * A single provider entry — either a factory `(deps) => R` or a class\n * `new (deps) => R`. `deps` is the *complete* services proxy\n * (siblings + built-in `ctx`).\n */\nexport type ServiceProvider<TMap, R> =\n | ((deps: ServicesOf<TMap>) => R)\n | (new (deps: ServicesOf<TMap>) => R);\n\n/**\n * A provider map — each value is either a factory or a class constructor.\n */\nexport type ServiceProviderMap<TMap> = {\n [K in keyof TMap]: K extends typeof CTX_KEY\n ? never\n : ServiceProvider<TMap, TMap[K]>;\n};\n\n/**\n * Extract the instance/return type from a single provider value.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ProviderReturn<P> = P extends new (...args: any) => infer R\n ? R\n : // eslint-disable-next-line @typescript-eslint/no-explicit-any\n P extends (...args: any) => infer R\n ? R\n : never;\n\n/**\n * Compute the output service map from an inferred provider map.\n */\nexport type MapFromProviders<P> = {\n [K in keyof P]: ProviderReturn<P[K]>;\n};\n\n/**\n * Container returned by {@link createServices}. Behaves like a plain object\n * keyed by service name — accessing a key triggers lazy instantiation.\n * Use `type Services = typeof services` to derive the public type.\n */\nexport type ServicesContainer<TMap> = TMap;\n\n/**\n * Build a lazy singleton DI container.\n *\n * @param providers A map of service name → factory function **or** class\n * constructor. The single argument (factory deps / first\n * ctor param) receives a deps proxy typed as the full\n * services map (siblings + the built-in `ctx`).\n *\n * @example Factory form\n * ```ts\n * db: () => getFirestore(),\n * postRepo: ({ db }) => new PostRepo(db),\n * ```\n *\n * @example Class form (zero-boilerplate auto-injection)\n * ```ts\n * class RepositoryService {\n * constructor(private readonly services: Services) {}\n * get posts() { return this.services.db.posts; }\n * }\n *\n * createServices({\n * db: () => getFirestore(), // ← factory\n * repository: RepositoryService, // ← bare class (deps auto-injected)\n * });\n * ```\n */\nexport function createServices<\n P extends Record<\n string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ((deps: any) => unknown) | (new (deps: any) => unknown)\n >,\n>(providers: P): ServicesContainer<ServicesOf<MapFromProviders<P>>> {\n const cache = new Map<string, unknown>();\n const inProgress: string[] = [];\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const proxy = new Proxy({} as any, {\n get(_target, prop) {\n if (typeof prop !== \"string\") return undefined;\n if (prop === CTX_KEY) return requestContextSingleton;\n\n if (cache.has(prop)) return cache.get(prop);\n\n const provider = (providers as Record<string, unknown>)[prop];\n if (typeof provider !== \"function\") {\n throw new Error(\n `[services] unknown service \"${prop}\". Registered: ${\n [CTX_KEY, ...Object.keys(providers)].join(\", \")\n }`,\n );\n }\n\n if (inProgress.includes(prop)) {\n throw new Error(\n `[services] circular dependency detected: ${[\n ...inProgress,\n prop,\n ].join(\" → \")}`,\n );\n }\n\n inProgress.push(prop);\n try {\n const value = isClassConstructor(provider)\n ? new (provider as new (deps: unknown) => unknown)(proxy)\n : (provider as (deps: unknown) => unknown)(proxy);\n cache.set(prop, value);\n return value;\n } finally {\n inProgress.pop();\n }\n },\n has(_target, prop) {\n if (typeof prop !== \"string\") return false;\n return prop === CTX_KEY || prop in providers;\n },\n ownKeys() {\n return [CTX_KEY, ...Object.keys(providers)];\n },\n getOwnPropertyDescriptor(_t, prop) {\n if (typeof prop !== \"string\") return undefined;\n if (prop === CTX_KEY || prop in providers) {\n return { enumerable: true, configurable: true };\n }\n return undefined;\n },\n });\n\n return proxy as ServicesContainer<ServicesOf<MapFromProviders<P>>>;\n}\n\n/**\n * Detect whether a function value should be invoked with `new` (class\n * constructor) or called directly (plain factory). Relies on the `class`\n * keyword being preserved in `Function.prototype.toString`, which is the\n * case for TypeScript / esbuild output targeting modern JS (ES2015+).\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction isClassConstructor(fn: Function): boolean {\n return /^class[\\s{]/.test(Function.prototype.toString.call(fn));\n}\n\n/**\n * Opaque container type used by registry / server signatures that don't\n * need to know the concrete services map.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyServicesContainer = ServicesContainer<Record<string, any>>;\n","/**\n * `HonoServer` — high-performance, fully-typed file-based API server for\n * Firebase Cloud Functions v2 (`onRequest`).\n *\n * Designed to:\n * - rely on **prebuild codegen** (`hono:gen` CLI) for static imports → zero\n * runtime filesystem scan, optimal cold-start;\n * - expose handlers receiving a Zod-parsed payload typed end-to-end;\n * - generate the OpenAPI 3.1 spec automatically from the same Zod schemas;\n * - bridge Hono's Web Fetch API to Cloud Functions' Express-style\n * `(req, res)` via `@hono/node-server`'s request listener.\n */\n\nimport { Hono } from \"hono\";\nimport { getRequestListener } from \"@hono/node-server\";\nimport { z } from \"zod\";\nimport type { Env, MiddlewareHandler } from \"hono\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport type { HttpsOptions } from \"firebase-functions/v2/https\";\n\nimport type {\n AnyRouteDef,\n ErrorHandler,\n HonoServerOptions,\n HttpMethod,\n InterceptorConfig,\n InterceptorOption,\n Logger,\n PayloadSource,\n RouteInterceptor,\n} from \"./types\";\nimport {\n BadRequestError,\n defaultErrorResponse,\n OutputValidationError,\n} from \"./errors\";\nimport { ValidationError } from \"./types\";\nimport { buildOpenApiDocument, renderDocsHtml } from \"./openapi\";\nimport { isDocsAuthExtension } from \"./docs-auth\";\nimport {\n createRequestContextMiddleware,\n type AnyServicesContainer,\n} from \"./services\";\n\n/**\n * Minimal shape of `firebase-functions/v2/https` `onRequest` so the package\n * stays decoupled from a specific firebase-functions version. We import the\n * real type only when users pass `onRequest` to `toFunction(...)`.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype OnRequestFn = (...args: any[]) => any;\n\n/**\n * Sentinel passed to handlers / interceptors when the server is started\n * without a `services` container. Frozen so accidental writes throw.\n */\nconst EMPTY_SERVICES: AnyServicesContainer = Object.freeze(\n {},\n) as unknown as AnyServicesContainer;\n\nexport class HonoServer<TEnv extends Env = Env> {\n private readonly app: Hono<TEnv>;\n private readonly options: HonoServerOptions<TEnv>;\n private readonly mountedRoutes: AnyRouteDef[];\n private cachedSpec: Record<string, unknown> | null = null;\n\n constructor(options: HonoServerOptions<TEnv>) {\n this.options = options;\n this.app = new Hono<TEnv>();\n this.mountedRoutes = filterRoutes(options.routes, options.api);\n\n // Install the request-context middleware FIRST so the AsyncLocalStorage\n // is populated before any user middleware / handler runs.\n if (options.services) {\n this.app.use(\"*\", createRequestContextMiddleware());\n }\n\n const globalMws = [\n ...(options.middlewares ?? []),\n ...(options.globalMiddlewares ?? []),\n ];\n for (const mw of globalMws) this.app.use(\"*\", mw);\n\n this.mountRoutes();\n this.mountOpenApi();\n\n if (options.notFound) this.app.notFound(options.notFound);\n if (options.onError) this.app.onError(options.onError);\n }\n\n /** Underlying Hono instance — useful for advanced composition / tests. */\n get hono(): Hono<TEnv> {\n return this.app;\n }\n\n /** Raw `(req, res)` handler suitable for `onRequest()` / `http.createServer`. */\n get nodeHandler(): (req: IncomingMessage, res: ServerResponse) => void {\n return getRequestListener(this.app.fetch, {\n overrideGlobalObjects: false,\n });\n }\n\n /**\n * Wrap the server as a Cloud Functions v2 HTTP function.\n *\n * @param onRequest The `onRequest` factory imported from\n * `firebase-functions/v2/https` (or `firebase-functions/https`).\n * @param httpsOptions Options forwarded as the first argument to\n * `onRequest()` (region, memory, invoker, etc.).\n */\n toFunction(onRequest: OnRequestFn, httpsOptions?: HttpsOptions) {\n const handler = this.nodeHandler;\n if (httpsOptions) {\n return onRequest(httpsOptions, handler);\n }\n return onRequest(handler);\n }\n\n /** Generate (and cache) the OpenAPI 3.1 spec for the mounted routes. */\n buildOpenApiSpec(): Record<string, unknown> {\n if (this.cachedSpec) return this.cachedSpec;\n if (!this.options.openapi) {\n throw new Error(\"[HonoServer] openapi config not set\");\n }\n this.cachedSpec = buildOpenApiDocument(\n this.mountedRoutes,\n this.options.basePath ?? \"\",\n this.options.openapi,\n interceptorConfig(this.options.interceptor as InterceptorOption | undefined),\n );\n return this.cachedSpec;\n }\n\n // ── Internals ─────────────────────────────────────────────────────────\n\n private mountRoutes(): void {\n const basePath = this.options.basePath ?? \"\";\n const validateOutput = this.options.validateOutput ?? false;\n const verbose = this.options.verbose ?? false;\n\n for (const route of this.mountedRoutes) {\n if (!route.path) {\n throw new Error(\n `[HonoServer] route \"${route.method.toUpperCase()} (no path)\" — missing \\`path\\`. ` +\n \"Run the codegen so the path is derived from the file location, or set it explicitly.\",\n );\n }\n\n const fullPath = joinPath(basePath, route.path);\n const middlewares = route.middlewares ?? [];\n const source: PayloadSource =\n route.source ?? (route.method === \"get\" ? \"query\" : \"json\");\n\n const handler = makeRouteHandler(\n route,\n source,\n validateOutput,\n interceptorFn(this.options.interceptor as InterceptorOption | undefined),\n this.options.services,\n this.options.errorHandler as ErrorHandler | undefined,\n this.options.logger as Logger | undefined,\n );\n const httpMethod = route.method.toUpperCase() as\n | \"GET\"\n | \"POST\"\n | \"PUT\"\n | \"PATCH\"\n | \"DELETE\";\n // `app.on(method, path, handlers[])` accepts a variadic array of\n // handlers/middlewares — the typed `.get/.post/...` overloads don't\n // accept a spread of generic `MiddlewareHandler[]`.\n this.app.on(\n httpMethod,\n [fullPath],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...([...middlewares, handler] as any[]),\n );\n\n if (verbose) {\n // eslint-disable-next-line no-console\n console.log(\n `[HonoServer] ${route.method.toUpperCase().padEnd(6)} ${fullPath}`,\n );\n }\n }\n }\n\n private mountOpenApi(): void {\n const cfg = this.options.openapi;\n if (!cfg) return;\n const specPath = cfg.path ?? \"/openapi.json\";\n const docsPath = cfg.docsPath === undefined ? \"/docs\" : cfg.docsPath;\n const fullSpecPath = joinPath(this.options.basePath ?? \"\", specPath);\n const fullDocsPath =\n docsPath === false ? null : joinPath(this.options.basePath ?? \"\", docsPath);\n\n // Auth guards applied ONLY to the spec + docs endpoints (not API routes).\n // A DocsAuthExtension (e.g. firebaseDocsAuth) also contributes auxiliary\n // routes (login page / session / logout) mounted next to the docs.\n let guards: MiddlewareHandler[];\n if (isDocsAuthExtension(cfg.docsAuth)) {\n const ext = cfg.docsAuth;\n guards = [ext.middleware];\n // Mount the aux routes (unguarded) as siblings of the docs/spec page so\n // bare-name relative links/redirects stay correct behind any prefix.\n const authDir = dirOf(fullDocsPath ?? fullSpecPath);\n for (const route of ext.routes) {\n this.app.on(\n route.method,\n [joinPath(authDir, route.name)],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n route.handler as any,\n );\n }\n } else {\n guards = cfg.docsAuth\n ? Array.isArray(cfg.docsAuth)\n ? cfg.docsAuth\n : [cfg.docsAuth]\n : [];\n }\n\n this.app.on(\n \"GET\",\n [fullSpecPath],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...([...guards, (c: any) => c.json(this.buildOpenApiSpec())] as any[]),\n );\n\n if (fullDocsPath) {\n // Resolve the spec URL relative to the docs page so it works whether the\n // server is mounted at `/`, behind a Firebase Functions prefix\n // (`/<project>/<region>/<funcName>/...`), or behind any reverse proxy.\n const relativeSpecUrl = relativeUrlFromTo(fullDocsPath, fullSpecPath);\n this.app.on(\n \"GET\",\n [fullDocsPath],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...([\n ...guards,\n (c: any) => c.html(renderDocsHtml(relativeSpecUrl, cfg.info.title)),\n ] as any[]),\n );\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** Type guard distinguishing a structured interceptor from a bare function. */\nfunction isInterceptorConfig(\n i: InterceptorOption | undefined,\n): i is InterceptorConfig {\n return typeof i === \"object\" && i !== null && typeof i.handler === \"function\";\n}\n\n/** Extract the runtime interceptor function from either form. */\nfunction interceptorFn(\n i: InterceptorOption | undefined,\n): RouteInterceptor | undefined {\n if (!i) return undefined;\n return isInterceptorConfig(i) ? i.handler : i;\n}\n\n/** Extract the OpenAPI metadata (output/errors) from the structured form. */\nfunction interceptorConfig(\n i: InterceptorOption | undefined,\n): InterceptorConfig | undefined {\n return isInterceptorConfig(i) ? i : undefined;\n}\n\nfunction filterRoutes(\n routes: AnyRouteDef[],\n api: string | undefined,\n): AnyRouteDef[] {\n if (!api) return routes.slice();\n return routes.filter((r) =>\n Array.isArray(r.api) ? r.api.includes(api) : r.api === api,\n );\n}\n\nfunction joinPath(base: string, path: string): string {\n const left = base.endsWith(\"/\") ? base.slice(0, -1) : base;\n const right = path.startsWith(\"/\") ? path : `/${path}`;\n const merged = `${left}${right}`;\n return merged === \"\" ? \"/\" : merged;\n}\n\n/** Directory of an absolute pathname, e.g. `/v1/docs` → `/v1`, `/docs` → ``. */\nfunction dirOf(path: string): string {\n const idx = path.lastIndexOf(\"/\");\n return idx <= 0 ? \"\" : path.slice(0, idx);\n}\n\n/**\n * Compute a URL relative to `from` that points to `to`, both being absolute\n * pathnames (e.g. `/v1/docs` → `/v1/openapi.json` becomes `openapi.json`).\n * Lets the OpenAPI UI fetch the spec without knowing the upstream prefix\n * added by Firebase Functions / reverse proxies.\n */\nfunction relativeUrlFromTo(from: string, to: string): string {\n const fromSegs = from.split(\"/\").filter(Boolean);\n const toSegs = to.split(\"/\").filter(Boolean);\n // Drop the docs page filename so we resolve relative to its directory.\n fromSegs.pop();\n let common = 0;\n while (\n common < fromSegs.length &&\n common < toSegs.length &&\n fromSegs[common] === toSegs[common]\n ) {\n common++;\n }\n const ups = fromSegs.length - common;\n const rel = [\n ...Array(ups).fill(\"..\"),\n ...toSegs.slice(common),\n ].join(\"/\");\n return rel || \"./\";\n}\n\n/**\n * Build the actual Hono handler with input validation, output validation\n * (optional), and error normalisation.\n */\nfunction makeRouteHandler(\n route: AnyRouteDef,\n source: PayloadSource,\n validateOutput: boolean,\n interceptor: RouteInterceptor | undefined,\n services: AnyServicesContainer | undefined,\n errorHandler: ErrorHandler | undefined,\n logger: Logger | undefined,\n) {\n const inputSchema = route.input as z.ZodTypeAny | undefined;\n const outputSchema = route.output as z.ZodTypeAny | undefined;\n const status = route.status ?? 200;\n // Empty fallback so handlers/interceptors always see a `services` field\n // even when the server was started without a container.\n const servicesArg = (services ?? (EMPTY_SERVICES as AnyServicesContainer));\n\n return async (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n c: any,\n ): Promise<Response> => {\n // Apply the injected ErrorHandler, falling back to the built-in envelope.\n // Returns a Response when handled, or null to let the error propagate.\n const applyErrorHandler = async (err: unknown): Promise<Response | null> => {\n if (errorHandler) {\n const handled = await errorHandler.handle({\n error: err,\n c,\n route,\n services: servicesArg,\n logger,\n });\n if (handled) return handled;\n }\n return defaultErrorResponse(c, err);\n };\n\n // `next()` runs validation + handler. Any Zod failure throws\n // `ValidationError` so the interceptor (or default catcher) can shape it.\n const callNext = async (): Promise<unknown> => {\n let payload: unknown = undefined;\n\n // Always read payload if it's expected, even without an input schema.\n // E.g., generic handlers that manually validate the body.\n let raw: unknown;\n try {\n raw = await readPayload(c, source, route.method);\n } catch (err) {\n throw new BadRequestError(\n err instanceof Error ? err.message : String(err),\n );\n }\n\n if (inputSchema) {\n const parsed = inputSchema.safeParse(raw);\n if (!parsed.success) {\n throw new ValidationError(parsed.error, source);\n }\n payload = parsed.data;\n } else {\n payload = raw;\n }\n\n const result = await (route.handler as (ctx: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input: any;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n c: any;\n services: AnyServicesContainer;\n errorHandler: ErrorHandler | undefined;\n logger: Logger | undefined;\n }) => unknown)({\n input: payload,\n c,\n services: servicesArg,\n errorHandler,\n logger,\n });\n\n if (validateOutput && outputSchema && !(result instanceof Response)) {\n const checked = outputSchema.safeParse(result);\n if (!checked.success) {\n throw new OutputValidationError(checked.error);\n }\n return checked.data;\n }\n return result;\n };\n\n let result: unknown;\n if (interceptor) {\n // Interceptor owns the response shape — including validation errors.\n // If it rethrows, the injected ErrorHandler / default catcher applies.\n try {\n result = await interceptor({\n next: callNext,\n route,\n c,\n services: servicesArg,\n errorHandler,\n logger,\n });\n } catch (err) {\n const handled = await applyErrorHandler(err);\n if (handled) return handled;\n throw err;\n }\n } else {\n // Default behaviour — ErrorHandler first, then the built-in\n // ValidationError envelope, else bubble to onError / Hono.\n try {\n result = await callNext();\n } catch (err) {\n const handled = await applyErrorHandler(err);\n if (handled) return handled;\n throw err;\n }\n }\n\n if (result instanceof Response) return result;\n return c.json(result, status);\n };\n}\n\nasync function readPayload(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n c: any,\n source: PayloadSource,\n method: HttpMethod,\n): Promise<unknown> {\n switch (source) {\n case \"json\": {\n if (method === \"get\") return c.req.query();\n const text = await c.req.text();\n if (!text) return {};\n try {\n return JSON.parse(text);\n } catch (err) {\n throw new Error(\n `Invalid JSON body: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n case \"query\":\n return c.req.query();\n case \"form\": {\n const form = await c.req.parseBody();\n return form;\n }\n case \"param\":\n return c.req.param();\n default:\n return {};\n }\n}\n","/**\n * @module servers/crud\n *\n * Creates a REST API server for CRUD operations on Firestore repositories using HonoServer.\n */\nimport type { HttpsOptions } from \"firebase-functions/v2/https\";\nimport type { ConfiguredRepository } from \"../../repositories/types\";\nimport { createCrudHandlers } from \"./handlers\";\nimport { generateOpenAPISpec, type OpenAPIDocument } from \"./openapi\";\nimport type { CrudRepoEntry, CrudRepoRegistry, CrudServerOptions } from \"./types\";\nimport { HonoServer } from \"../hono/server\";\nimport type { AnyRouteDef } from \"../hono/types\";\nimport { getLinkBase } from \"../utils/link-base\";\n\n\nexport function createCrudServer<\n TRepos extends Record<string, ConfiguredRepository<any>>,\n>(\n options: CrudServerOptions<TRepos>,\n): ((req: any, res: any) => Promise<void>) & { spec: () => OpenAPIDocument; httpsOptions?: HttpsOptions } {\n const {\n basePath = \"/\",\n repos,\n parseBody = true,\n securityHeaders: securityHeadersOpt,\n verbose = false,\n httpsOptions,\n } = options;\n\n const base = basePath === \"/\" ? \"\" : basePath.replace(/\\/$/, \"\");\n\n const registry: CrudRepoRegistry = {};\n for (const [name, cfg] of Object.entries(repos)) {\n if (!cfg.repo) {\n throw new Error(`[createCrudServer] Repository \"${name}\" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);\n }\n\n const resolvedSchema = cfg.schema ?? (cfg.repo as any).schema ?? null;\n if (!resolvedSchema) {\n throw new Error(`[createCrudServer] Repository \"${name}\" has no Zod schema.`);\n }\n\n let filterableFields: string[] | undefined;\n let orderableFields: string[] | undefined;\n let mutableFields: string[] | undefined;\n let createFields: string[] | undefined;\n if (cfg.fieldsConfig) {\n const fc = cfg.fieldsConfig as Record<string, readonly string[]>;\n filterableFields = [];\n orderableFields = [];\n mutableFields = [];\n createFields = [];\n for (const [field, roles] of Object.entries(fc)) {\n for (const role of roles) {\n if (role === \"filterable\") filterableFields.push(field);\n else if (role === \"orderable\") orderableFields.push(field);\n else if (role === \"mutable\") mutableFields.push(field);\n else if (role === \"create\") createFields.push(field);\n }\n }\n if (orderableFields.length === 0) orderableFields = filterableFields;\n if (filterableFields.length === 0) filterableFields = undefined;\n if (orderableFields && orderableFields.length === 0) orderableFields = undefined;\n if (mutableFields.length === 0) mutableFields = undefined;\n if (createFields.length === 0) createFields = undefined;\n }\n\n const parentKeys = (() => {\n const pk = (cfg.repo as any)._parentKeys as string[] | undefined;\n return pk && pk.length > 0 ? pk : undefined;\n })();\n if (parentKeys && createFields) {\n for (const pk of parentKeys) {\n if (!createFields.includes(pk)) createFields.push(pk);\n }\n }\n\n const entry: CrudRepoEntry = {\n name,\n path: cfg.path,\n repo: cfg.repo,\n schema: resolvedSchema,\n systemKeys: (cfg.repo as any)._systemKeys ?? [cfg.documentKey ?? \"docId\"],\n documentKey: cfg.documentKey ?? \"docId\",\n pathKey: (cfg.repo as any)._pathKey ?? undefined,\n isGroup: !!(cfg.repo as any)._isGroup,\n parentKeys,\n createdKey: (cfg.repo as any)._createdKey ?? undefined,\n pageSize: cfg.pageSize ?? 25,\n filterableFields,\n orderableFields,\n mutableFields,\n createFields,\n allowDelete: cfg.allowDelete ?? false,\n allowedIncludes: cfg.allowedIncludes as string[] | undefined,\n validate: cfg.validate as CrudRepoEntry[\"validate\"],\n rules: cfg.rules,\n };\n\n registry[name] = entry;\n }\n\n const handlers = createCrudHandlers(registry, base, verbose);\n\n const openapi = options.openapi;\n const openapiOpts = openapi && typeof openapi === \"object\" ? openapi : {};\n let _specCache: OpenAPIDocument | null = null;\n function getSpec(): OpenAPIDocument {\n if (!_specCache) {\n _specCache = generateOpenAPISpec(registry, base, {\n ...openapiOpts,\n auth: openapiOpts.auth ?? false,\n });\n }\n return _specCache;\n }\n\n const routes: AnyRouteDef[] = [];\n\n for (const name of Object.keys(registry)) {\n routes.push({\n api: \"crud\",\n method: \"get\",\n path: `/${name}`,\n source: \"query\",\n handler: handlers.handleList,\n });\n routes.push({\n api: \"crud\",\n method: \"post\",\n path: `/${name}/query`,\n source: \"json\",\n handler: handlers.handleQuery,\n });\n routes.push({\n api: \"crud\",\n method: \"get\",\n path: `/${name}/:id`,\n source: \"query\",\n handler: handlers.handleGet,\n });\n routes.push({\n api: \"crud\",\n method: \"post\",\n path: `/${name}`,\n source: \"json\",\n handler: handlers.handleCreate,\n });\n routes.push({\n api: \"crud\",\n method: \"put\",\n path: `/${name}/:id`,\n source: \"json\",\n handler: (ctx) => handlers.handleUpdate(ctx, false),\n });\n routes.push({\n api: \"crud\",\n method: \"patch\",\n path: `/${name}/:id`,\n source: \"json\",\n handler: (ctx) => handlers.handleUpdate(ctx, true),\n });\n routes.push({\n api: \"crud\",\n method: \"delete\",\n path: `/${name}/:id`,\n source: \"query\",\n handler: handlers.handleDelete,\n });\n routes.push({\n api: \"crud\",\n method: \"post\",\n path: `/${name}/batch`,\n source: \"json\",\n handler: handlers.handleBatch,\n });\n }\n\n // Create the HonoServer\n const server = new HonoServer({\n ...options,\n openapi: openapi !== false ? {\n path: openapiOpts.path ?? \"/openapi.json\",\n docsPath: openapiOpts.docsPath ?? \"/docs\",\n info: { \n title: openapiOpts.title ?? \"CRUD API\", \n version: openapiOpts.version ?? \"1.0.0\" \n },\n docsAuth: openapiOpts.docsAuth as any,\n } : undefined,\n basePath,\n api: \"crud\",\n routes,\n middlewares: [\n async (c, next) => {\n if (c.req.method === \"OPTIONS\") {\n return c.text(\"\", 204 as any, {\n \"Access-Control-Allow-Methods\": \"GET, POST, PUT, PATCH, DELETE, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"Content-Type, Authorization\",\n \"Access-Control-Max-Age\": \"86400\",\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Credentials\": \"true\",\n });\n }\n c.header(\"Access-Control-Allow-Origin\", \"*\");\n c.header(\"Access-Control-Allow-Credentials\", \"true\");\n await next();\n return;\n },\n ...(options.middlewares || []),\n ],\n });\n\n if (openapi !== false) {\n server.buildOpenApiSpec = getSpec as any;\n }\n\n if (securityHeadersOpt !== false) {\n const { securityHeaders } = require(\"../utils/security-headers\");\n const base0 = securityHeadersOpt === undefined ? { csp: false as const } : securityHeadersOpt;\n server.hono.use(\"*\", async (c, next) => {\n const adapter = securityHeaders(base0);\n await new Promise<void>((resolve) => {\n const fakeReq = c.req.raw;\n const fakeRes = {\n setHeader: (k: string, v: string) => c.header(k, v),\n removeHeader: (k: string) => c.res.headers.delete(k),\n };\n adapter(fakeReq, fakeRes, () => resolve());\n });\n await next();\n });\n }\n\n const handler = server.nodeHandler as any;\n handler.spec = getSpec;\n if (httpsOptions) handler.httpsOptions = httpsOptions;\n\n return handler;\n}\n\nexport { generateOpenAPISpec } from \"./openapi\";\nexport type { OpenAPIDocument, OpenAPISpecOptions } from \"./openapi\";\nexport type {\n ApiResponse,\n CrudRepoConfig,\n CrudRepoEntry,\n CrudRepoRegistry,\n CrudServerOptions,\n FieldRole,\n ListResponseData,\n QueryRequestBody,\n RepoFieldPath,\n RepoRelationKeys,\n UserFieldPath,\n} from \"./types\";\n"]}
1
+ {"version":3,"sources":["../../../src/servers/utils/security-headers.ts","../../../src/shared/date-config.ts","../../../src/servers/admin/index-url.ts","../../../src/servers/crud/handlers.ts","../../../src/servers/crud/openapi.ts","../../../src/servers/hono/types.ts","../../../src/servers/hono/errors.ts","../../../src/servers/hono/openapi.ts","../../../src/servers/hono/docs-auth.ts","../../../src/servers/hono/services.ts","../../../src/servers/hono/server.ts","../../../src/servers/crud/index.ts"],"names":["security_headers_exports","__export","DEFAULT_HTML_CSP","securityHeaders","opts","csp","frameOptions","referrerPolicy","cacheControl","_req","res","next","ADMIN_CDN","GSTATIC","init_security_headers","__esmMin","currentMode","getDateHandling","isTimestampLike","v","coerceToDate","value","Timestamp","d","maybeNormalize","RANGE_OPS","ARRAY_OPS","toIndexOrder","dir","collectionIdFromPath","path","segments","buildIndexUrl","projectId","collectionId","isGroup","filters","sort","fields","seen","f","buildExemptionUrl","lastDir","buildCompositeUrl","databaseId","resource","payload","pbString","pbInt","pbMessage","encodeIndexField","urlDbId","encoded","toBase64","extractIndexUrl","message","pbVarint","n","out","pbTag","fieldNumber","wireType","bytes","bin","b64","field","extractProjectId","ref","r","candidates","c","isMissingIndexError","err","fe","toQueryError","ctx","isIndex","indexUrl","colId","sendJson","data","status","sendSuccess","meta","sendError","error","sendQueryError","fallbackMessage","verbose","qe","_idChars","generateFirestoreId","id","randomBytes","i","byte","wrapDateSchemas","schema","def","typeName","z","shape","wrapped","k","inner","dflt","pickSchemaFields","systemKeys","picked","source","topLevel","validateData","partial","targetSchema","partialSchema","e","parseFieldValue","entrySchema","val","fieldSchema","parsed","parsedArray","item","itemParsed","parseFilters","query","filterableFields","allowedFields","opMap","key","rawVal","match","op","opKey","parsedVal","parseValue","num","serializeCursor","snapshot","deserializeCursor","entry","cursor","cursorObj","docPath","docId","colRef","firestore","createCrudHandlers","registry","basePath","assertRule","rule","applyRowFilter","user","params","docs","filter","doc","userOf","getRepoEntry","repoName","parts","part","extractPathArgs","pathKey","fullPath","args","fetchDocById","getterName","getter","handleList","ctxFilters","ctxSort","pageSize","direction","orderBy","orderDir","selectStr","select","s","includes","inc","queryOptions","parsedRes","result","responseData","handleQuery","body","w","validIncludes","allowed","invalid","parsedWhere","parsedOrWhere","group","parsedOrWhereGroups","parsedGroup","o","handleGet","handleCreate","validation","customError","created","missingKeys","parentIds","handleUpdate","existingDoc","pathArgs","updated","handleDelete","handleOptions","handleBatch","batch","results","zodToJsonSchema","metadata","getOpenApiMetadata","schemaRef","name","errorResponse","description","successResponse","dataSchema","listResponse","itemSchema","unwrapZodType","zodType","cur","resolveFieldPathSchema","rawSub","extractLeafFields","zodSchema","prefix","depth","fieldPath","subUnwrapped","getFilterableLeafFields","zodTypeToJsonValueSchema","jsonSchema","paginationParams","leafFields","orderableFields","filterParams","ops","opDescriptions","valSchema","descDetail","isListOp","queryBodySchema","buildTypedQueryBodySchema","orderableFieldNames","leafFieldNames","whereTuples","unwrapped","elemSchema","whereItemSchema","buildPathsForEntry","base","modelSchemaName","createSchemaName","updateSchemaName","querySchemaName","paths","tag","collectionPath","documentPath","idParam","capitalize","singularize","docOps","generateOpenAPISpec","options","title","version","servers","auth","schemas","allPaths","tags","modelName","createName","updateName","queryName","buildShape","fieldList","top","createShape","updateShape","entryPaths","securitySchemes","security","ValidationError","zodError","BadRequestError","OutputValidationError","formatZodIssues","defaultErrorResponse","extendZodWithOpenApi","DEFAULT_RESPONSE_DESCRIPTION","DEFAULT_ERROR_DESCRIPTION","defaultSource","method","resolveSuccessSchema","routeOutput","interceptor","normalizeErrorResponse","cfg","buildOpenApiDocument","routes","config","OpenAPIRegistry","scheme","route","joinPath","requestBody","buildRequestBody","requestQuery","buildQueryOrParam","requestParams","operationId","makeOperationId","successSchema","responses","code","convertExpressPathToOpenApi","OpenApiGeneratorV31","target","left","right","merged","cleaned","renderDocsHtml","specUrl","safeUrl","isDocsAuthExtension","als","AsyncLocalStorage","createRequestContextMiddleware","EMPTY_SERVICES","HonoServer","Hono","filterRoutes","globalMws","mw","getRequestListener","onRequest","httpsOptions","handler","interceptorConfig","validateOutput","middlewares","makeRouteHandler","interceptorFn","httpMethod","specPath","docsPath","fullSpecPath","fullDocsPath","guards","ext","authDir","dirOf","relativeSpecUrl","relativeUrlFromTo","isInterceptorConfig","api","idx","from","to","fromSegs","toSegs","common","ups","services","errorHandler","logger","inputSchema","outputSchema","servicesArg","applyErrorHandler","handled","callNext","raw","readPayload","checked","text","createCrudServer","repos","parseBody","securityHeadersOpt","resolvedSchema","mutableFields","createFields","fc","roles","role","parentKeys","pk","handlers","openapi","openapiOpts","_specCache","getSpec","server","base0","adapter","resolve","fakeReq"],"mappings":"yyBAAA,IAAAA,EAAAA,CAAA,EAAA,CAAAC,EAAAA,CAAAD,EAAAA,CAAA,CAAA,gBAAA,CAAA,IAAAE,EAAAA,CAAA,eAAA,CAAA,IAAAC,EAAAA,CAAAA,CAAAA,CAsEO,SAASA,EAAAA,CAAgBC,CAAAA,CAA+B,EAAC,CAAG,CACjE,IAAMC,CAAAA,CAAMD,CAAAA,CAAK,GAAA,GAAQ,MAAA,CAAYF,EAAAA,CAAmBE,CAAAA,CAAK,GAAA,CACvDE,CAAAA,CAAeF,CAAAA,CAAK,YAAA,GAAiB,MAAA,CAAY,MAAA,CAASA,CAAAA,CAAK,aAC/DG,CAAAA,CACJH,CAAAA,CAAK,cAAA,GAAmB,MAAA,CAAY,aAAA,CAAgBA,CAAAA,CAAK,cAAA,CACrDI,CAAAA,CACJJ,CAAAA,CAAK,YAAA,GAAiB,MAAA,CAAY,mBAAA,CAAsBA,CAAAA,CAAK,YAAA,CAE/D,OAAO,MAAOK,CAAAA,CAAcC,CAAAA,CAAaC,CAAAA,GAA8B,CACjE,OAAOD,CAAAA,EAAK,SAAA,EAAc,UAAA,GAC5BA,CAAAA,CAAI,SAAA,CAAU,wBAAA,CAA0B,SAAS,CAAA,CAC7CJ,CAAAA,EAAcI,EAAI,SAAA,CAAU,iBAAA,CAAmBJ,CAAY,CAAA,CAC3DC,CAAAA,EAAgBG,CAAAA,CAAI,SAAA,CAAU,iBAAA,CAAmBH,CAAc,CAAA,CAC/DC,CAAAA,EAAcE,CAAAA,CAAI,SAAA,CAAU,eAAA,CAAiBF,CAAY,CAAA,CACzDH,CAAAA,EAAKK,CAAAA,CAAI,SAAA,CAAU,yBAAA,CAA2BL,CAAG,CAAA,CAAA,CAEvD,MAAMM,CAAAA,GACR,CACF,CAxFA,IAkBMC,EAAAA,CACAC,G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Q,CACd,SAAA,CAAW,CAAChT,CAAAA,CAAWpF,CAAAA,GAAcmD,EAAE,MAAA,CAAOiC,CAAAA,CAAGpF,CAAC,CAAA,CAClD,YAAA,CAAeoF,GAAcjC,CAAAA,CAAE,GAAA,CAAI,OAAA,CAAQ,MAAA,CAAOiC,CAAC,CACrD,EAC0B,IAAM+S,CAAAA,EAAS,EAC3C,CAAC,EACD,MAAM3Y,CAAAA,GACR,CAAC,EACH,CAEA,IAAMgV,CAAAA,CAAUwD,CAAAA,CAAO,WAAA,CACvB,OAAAxD,CAAAA,CAAQ,IAAA,CAAOuD,EACXxD,CAAAA,GAAcC,CAAAA,CAAQ,YAAA,CAAeD,CAAAA,CAAAA,CAElCC,CACT","file":"index.js","sourcesContent":["/**\n * Default security-headers middleware for the bundled HTTP servers.\n *\n * Addresses issues #12 (no security headers / clickjacking / cache leakage)\n * and #13 (no CSP bounding the CDN origins loaded by the admin & login pages).\n *\n * The middleware is framework-agnostic: it only touches `res.setHeader`\n * (present on Node's `ServerResponse` and the shims used by the admin/CRUD\n * routers) and always calls `next()`.\n */\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyReq = any;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyRes = any;\ntype Next = () => void | Promise<void>;\n\n/** CDN/script origins the bundled admin UI and login page load from. */\nconst ADMIN_CDN = \"https://cdn.jsdelivr.net\";\nconst GSTATIC = \"https://www.gstatic.com\";\n\n/**\n * Reasonable default Content-Security-Policy for the bundled **HTML** pages\n * (admin UI + login). Allows the specific CDN origins the pages need and\n * forbids framing entirely. `'unsafe-inline'`/`'unsafe-eval'` are required by\n * the Tailwind browser build and the small inline bootstrap scripts.\n */\nexport const DEFAULT_HTML_CSP = [\n \"default-src 'self'\",\n `script-src 'self' 'unsafe-inline' 'unsafe-eval' ${ADMIN_CDN} ${GSTATIC}`,\n `style-src 'self' 'unsafe-inline' ${ADMIN_CDN}`,\n `connect-src 'self' ${GSTATIC} https://*.googleapis.com https://*.firebaseio.com https://identitytoolkit.googleapis.com`,\n \"img-src 'self' data:\",\n \"font-src 'self' data:\",\n \"frame-ancestors 'none'\",\n \"base-uri 'self'\",\n \"form-action 'self'\",\n].join(\"; \");\n\nexport interface SecurityHeadersOptions {\n /**\n * Content-Security-Policy value. Pass a string to override, or `false` to\n * omit the header entirely. Defaults to {@link DEFAULT_HTML_CSP} for HTML\n * servers (admin/login) and is omitted for pure JSON APIs unless provided.\n */\n csp?: string | false;\n /**\n * `X-Frame-Options` value. Default `\"DENY\"`. Pass `false` to omit (e.g. when\n * the app must be embedded in a trusted iframe — prefer a CSP\n * `frame-ancestors` allowlist instead).\n */\n frameOptions?: string | false;\n /** `Referrer-Policy` value. Default `\"no-referrer\"`. */\n referrerPolicy?: string | false;\n /**\n * `Cache-Control` value. Default `\"private, no-store\"` to keep private data\n * out of shared proxy caches. Pass `false` to leave caching to handlers.\n */\n cacheControl?: string | false;\n}\n\n/**\n * Build a middleware that sets a baseline of security response headers.\n *\n * @example\n * ```ts\n * router.use(securityHeaders()); // HTML-safe defaults\n * router.use(securityHeaders({ csp: false })); // JSON API (no CSP)\n * ```\n */\nexport function securityHeaders(opts: SecurityHeadersOptions = {}) {\n const csp = opts.csp === undefined ? DEFAULT_HTML_CSP : opts.csp;\n const frameOptions = opts.frameOptions === undefined ? \"DENY\" : opts.frameOptions;\n const referrerPolicy =\n opts.referrerPolicy === undefined ? \"no-referrer\" : opts.referrerPolicy;\n const cacheControl =\n opts.cacheControl === undefined ? \"private, no-store\" : opts.cacheControl;\n\n return async (_req: AnyReq, res: AnyRes, next: Next): Promise<void> => {\n if (typeof res?.setHeader === \"function\") {\n res.setHeader(\"X-Content-Type-Options\", \"nosniff\");\n if (frameOptions) res.setHeader(\"X-Frame-Options\", frameOptions);\n if (referrerPolicy) res.setHeader(\"Referrer-Policy\", referrerPolicy);\n if (cacheControl) res.setHeader(\"Cache-Control\", cacheControl);\n if (csp) res.setHeader(\"Content-Security-Policy\", csp);\n }\n await next();\n };\n}\n","import { Timestamp } from \"firebase-admin/firestore\";\n\nexport type DateHandlingMode = \"preserve\" | \"normalize\";\n\nlet currentMode: DateHandlingMode = \"preserve\";\n\nexport function setDateHandling(mode: DateHandlingMode): void {\n currentMode = mode;\n}\n\nexport function getDateHandling(): DateHandlingMode {\n return currentMode;\n}\n\nfunction isTimestampLike(\n v: unknown,\n): v is { _seconds: number; _nanoseconds: number } {\n return (\n typeof v === \"object\" &&\n v !== null &&\n typeof (v as { _seconds?: unknown })._seconds === \"number\" &&\n typeof (v as { _nanoseconds?: unknown })._nanoseconds === \"number\"\n );\n}\n\nexport function coerceToDate(value: unknown): Date | null {\n if (value === null || value === undefined) return null;\n if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value;\n if (value instanceof Timestamp) return value.toDate();\n if (isTimestampLike(value)) {\n return new Date(\n value._seconds * 1000 + Math.floor(value._nanoseconds / 1e6),\n );\n }\n if (typeof value === \"string\") {\n const d = new Date(value);\n return Number.isNaN(d.getTime()) ? null : d;\n }\n if (typeof value === \"number\") {\n const d = new Date(value);\n return Number.isNaN(d.getTime()) ? null : d;\n }\n return null;\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n if (typeof v !== \"object\" || v === null) return false;\n const proto = Object.getPrototypeOf(v);\n return proto === Object.prototype || proto === null;\n}\n\nexport function normalizeTimestamps<T>(value: T): T {\n if (value instanceof Timestamp) return value.toDate() as unknown as T;\n if (Array.isArray(value)) {\n return value.map((v) => normalizeTimestamps(v)) as unknown as T;\n }\n if (isPlainObject(value)) {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) {\n out[k] = normalizeTimestamps(v);\n }\n return out as unknown as T;\n }\n return value;\n}\n\nexport function maybeNormalize<T>(value: T): T {\n return currentMode === \"normalize\" ? normalizeTimestamps(value) : value;\n}\n","/**\n * Generates a Firebase Console URL to create a composite index OR a\n * single-field index exemption.\n *\n * When Firestore throws FAILED_PRECONDITION (code 9) for missing indexes,\n * the error message sometimes includes a creation link (regular collections)\n * but often does NOT include it (collection groups). This utility builds the\n * link from the query context so the admin UI can always present it.\n *\n * Two URL shapes are produced depending on the query:\n *\n * - **Composite index** (≥ 2 indexed fields, or any COLLECTION-scope multi-field\n * query). Encoded as a JSON `create_composite=` parameter under\n * `/v1/r/project/{p}/firestore/indexes`.\n *\n * - **Single-field exemption** (exactly one indexed field on a COLLECTION_GROUP\n * query — Firestore disables single-field collection-group indexes by\n * default and requires an explicit exemption). Encoded as a base64\n * protobuf `create_exemption=` parameter under\n * `/project/{p}/firestore/databases/-default-/indexes/automatic`.\n */\n\nimport type {\n FilterState,\n QueryError,\n SortState,\n WhereOp,\n} from \"./components/types\";\n\n// ── Types ────────────────────────────────────────────────────────────────────\n\ninterface IndexField {\n fieldPath: string;\n order?: \"ASCENDING\" | \"DESCENDING\";\n arrayConfig?: \"CONTAINS\";\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────\n\nconst RANGE_OPS = new Set<WhereOp>([\"<\", \"<=\", \">\", \">=\", \"!=\"]);\nconst ARRAY_OPS = new Set<WhereOp>([\"array-contains\", \"array-contains-any\"]);\n\nfunction toIndexOrder(dir?: \"asc\" | \"desc\"): \"ASCENDING\" | \"DESCENDING\" {\n return dir === \"desc\" ? \"DESCENDING\" : \"ASCENDING\";\n}\n\n/**\n * Extract the collection ID (last path segment) from a Firestore path.\n * e.g. \"posts/{postId}/comments\" → \"comments\"\n */\nexport function collectionIdFromPath(path: string): string {\n const segments = path.split(\"/\").filter(Boolean);\n return segments[segments.length - 1] ?? path;\n}\n\n// ── Main ─────────────────────────────────────────────────────────────────────\n\n/**\n * Build a Firebase Console URL that pre-fills the composite-index creation form.\n *\n * @param projectId - GCP project ID (e.g. \"firestore-repo-services\")\n * @param collectionId - Firestore collection ID (e.g. \"posts\", \"comments\")\n * @param isGroup - Whether this is a collection group query\n * @param filters - Active filter states from the admin UI\n * @param sort - Active sort state (optional)\n * @returns - Full HTTPS URL to the Firebase Console index wizard\n */\nexport function buildIndexUrl(\n projectId: string,\n collectionId: string,\n isGroup: boolean,\n filters: FilterState[],\n sort?: SortState,\n): string {\n const fields: IndexField[] = [];\n const seen = new Set<string>();\n\n // 1. Equality filters first (order doesn't matter for equality)\n for (const f of filters) {\n if (f.op === \"==\" || f.op === \"in\" || f.op === \"not-in\") {\n if (seen.has(f.field)) continue;\n seen.add(f.field);\n fields.push({ fieldPath: f.field, order: \"ASCENDING\" });\n }\n }\n\n // 2. Array operators\n for (const f of filters) {\n if (ARRAY_OPS.has(f.op)) {\n if (seen.has(f.field)) continue;\n seen.add(f.field);\n fields.push({ fieldPath: f.field, arrayConfig: \"CONTAINS\" });\n }\n }\n\n // 3. Range / inequality filters\n for (const f of filters) {\n if (RANGE_OPS.has(f.op)) {\n if (seen.has(f.field)) continue;\n seen.add(f.field);\n // Use the sort direction if the range field matches the orderBy field\n const dir =\n sort?.field === f.field ? toIndexOrder(sort.dir) : \"ASCENDING\";\n fields.push({ fieldPath: f.field, order: dir });\n }\n }\n\n // 4. OrderBy fields not already covered by filters\n if (sort && !seen.has(sort.field)) {\n fields.push({ fieldPath: sort.field, order: toIndexOrder(sort.dir) });\n }\n\n // ── Single-field collection-group exemption ──────────────────────────────\n // Firestore disables single-field collection-group indexes by default; you\n // must create an explicit \"field exemption\". The Firebase Console wizard\n // for that uses a totally different URL (`create_exemption=`) with its own\n // protobuf shape — see buildExemptionUrl below.\n if (fields.length === 1 && isGroup) {\n return buildExemptionUrl(projectId, collectionId, fields[0]!);\n }\n\n // ── Composite index ──────────────────────────────────────────────────────\n // Firebase Console encodes composite indexes as a base64 protobuf payload\n // under `create_composite=`. Every composite index implicitly ends with\n // `__name__` as a tie-breaker, so we always append it (matches what the\n // Console itself produces).\n const lastDir =\n sort && fields.some((f) => f.fieldPath === sort.field)\n ? toIndexOrder(sort.dir)\n : \"ASCENDING\";\n fields.push({ fieldPath: \"__name__\", order: lastDir });\n\n return buildCompositeUrl(projectId, collectionId, isGroup, fields);\n}\n\n/**\n * Build a Firebase Console URL that pre-fills the composite index creation\n * form for either a regular collection or a collection-group query.\n *\n * The URL uses a base64-encoded protobuf payload (the same shape the Console\n * itself produces when you click \"Add index\" in the UI). Schema:\n *\n * message CompositeIndex {\n * string resource_path = 1; // projects/.../collectionGroups/{cg}/indexes/_\n * int32 query_scope = 2; // 1 = COLLECTION, 2 = COLLECTION_GROUP\n * repeated IndexField fields = 3;\n * }\n */\nexport function buildCompositeUrl(\n projectId: string,\n collectionId: string,\n isGroup: boolean,\n fields: IndexField[],\n databaseId: string = \"(default)\",\n): string {\n const resource = `projects/${projectId}/databases/${databaseId}/collectionGroups/${collectionId}/indexes/_`;\n\n const payload: number[] = [\n ...pbString(1, resource),\n ...pbInt(2, isGroup ? 2 : 1),\n ];\n for (const f of fields) {\n payload.push(...pbMessage(3, encodeIndexField(f)));\n }\n\n const urlDbId = databaseId === \"(default)\" ? \"-default-\" : databaseId;\n const encoded = encodeURIComponent(toBase64(payload));\n return `https://console.firebase.google.com/project/${projectId}/firestore/databases/${urlDbId}/indexes?create_composite=${encoded}`;\n}\n\n/**\n * Try to extract an index-creation URL from a Firestore error message.\n * Returns `undefined` if no URL is found.\n */\nexport function extractIndexUrl(message: string): string | undefined {\n const match = message.match(\n /https:\\/\\/console\\.firebase\\.google\\.com[^\\s)\"]*/,\n );\n return match?.[0];\n}\n\n// ── Single-field exemption URL (collection-group) ────────────────────────────\n\n/**\n * Minimal protobuf encoder for the field-exemption payload used by the\n * Firebase Console URL `?create_exemption=…`.\n *\n * Wire format (subset):\n * tag = (field_number << 3) | wire_type\n * wire types: 0 = varint, 2 = length-delimited\n *\n * Schema we encode (reverse-engineered from real Firebase Console URLs):\n * message FieldExemption {\n * string resource_path = 1; // projects/.../fields/{field}\n * int32 query_scope = 2; // 1 = COLLECTION, 2 = COLLECTION_GROUP\n * IndexConfig index = 3;\n * }\n * message IndexConfig {\n * string field_path = 1;\n * int32 order = 2; // 1 = ASCENDING, 2 = DESCENDING\n * int32 array_config = 3; // 1 = CONTAINS (mutually exclusive with order)\n * }\n */\nfunction pbVarint(n: number): number[] {\n const out: number[] = [];\n let v = n >>> 0;\n while (v >= 0x80) {\n out.push((v & 0x7f) | 0x80);\n v >>>= 7;\n }\n out.push(v & 0x7f);\n return out;\n}\n\nfunction pbTag(fieldNumber: number, wireType: 0 | 2): number {\n return (fieldNumber << 3) | wireType;\n}\n\nfunction pbString(fieldNumber: number, value: string): number[] {\n const bytes = Array.from(new TextEncoder().encode(value));\n return [pbTag(fieldNumber, 2), ...pbVarint(bytes.length), ...bytes];\n}\n\nfunction pbInt(fieldNumber: number, value: number): number[] {\n return [pbTag(fieldNumber, 0), ...pbVarint(value)];\n}\n\nfunction pbMessage(fieldNumber: number, payload: number[]): number[] {\n return [pbTag(fieldNumber, 2), ...pbVarint(payload.length), ...payload];\n}\n\n/** Encode an IndexField submessage: { field_path:1, order:2 OR array_config:3 } */\nfunction encodeIndexField(f: IndexField): number[] {\n const out: number[] = [...pbString(1, f.fieldPath)];\n if (f.arrayConfig === \"CONTAINS\") {\n out.push(...pbInt(3, 1));\n } else {\n out.push(...pbInt(2, f.order === \"DESCENDING\" ? 2 : 1));\n }\n return out;\n}\n\nfunction toBase64(bytes: number[]): string {\n // Standard base64 (no padding) — matches what Firebase Console produces.\n // Use Buffer when available (Node), otherwise fall back to btoa.\n const bin = String.fromCharCode(...bytes);\n let b64: string;\n if (typeof Buffer !== \"undefined\") {\n b64 = Buffer.from(bytes).toString(\"base64\");\n } else if (typeof btoa !== \"undefined\") {\n b64 = btoa(bin);\n } else {\n throw new Error(\"No base64 encoder available\");\n }\n return b64.replace(/=+$/, \"\");\n}\n\n/**\n * Build a Firebase Console URL that pre-fills the single-field index\n * exemption form for a collection-group query.\n */\nexport function buildExemptionUrl(\n projectId: string,\n collectionId: string,\n field: IndexField,\n databaseId: string = \"(default)\",\n): string {\n const resource = `projects/${projectId}/databases/${databaseId}/collectionGroups/${collectionId}/fields/${field.fieldPath}`;\n\n const payload: number[] = [\n ...pbString(1, resource),\n ...pbInt(2, 2), // COLLECTION_GROUP\n ...pbMessage(3, encodeIndexField(field)),\n ];\n\n // Database ID for the URL path: \"(default)\" → \"-default-\",\n // any other ID is used as-is (Firebase Console uses the bare ID).\n const urlDbId = databaseId === \"(default)\" ? \"-default-\" : databaseId;\n\n // create_exemption is base64 (URL-safe characters only — `+` and `/` are\n // valid in query string values per RFC, and Firebase accepts them, but we\n // URL-encode just to be safe).\n const encoded = encodeURIComponent(toBase64(payload));\n return `https://console.firebase.google.com/project/${projectId}/firestore/databases/${urlDbId}/indexes/automatic?create_exemption=${encoded}`;\n}\n\n// ── Project ID extraction ────────────────────────────────────────────────────\n\n/**\n * Robustly extract the GCP project ID from a Firestore reference.\n * Falls back through several known locations across firebase-admin versions\n * and finally to standard environment variables.\n */\nexport function extractProjectId(ref: unknown): string | undefined {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const r = ref as any;\n const candidates: unknown[] = [\n r?.firestore?.projectId,\n r?.firestore?.app?.options?.projectId,\n r?.firestore?._settings?.projectId,\n r?.firestore?.databaseId?.projectId,\n r?._firestore?.projectId,\n ];\n for (const c of candidates) {\n if (typeof c === \"string\" && c.length > 0) return c;\n }\n const env =\n process.env[\"GCLOUD_PROJECT\"] ||\n process.env[\"GOOGLE_CLOUD_PROJECT\"] ||\n process.env[\"FIREBASE_PROJECT_ID\"];\n return env || undefined;\n}\n\n// ── Centralized error → QueryError conversion ────────────────────────────────\n\n/**\n * Context required to build a fallback index URL when Firestore does not\n * include one in its error (typical for collection-group queries).\n */\nexport interface QueryErrorContext {\n /** Repository ref (CollectionReference / Query) used to extract project id */\n ref: unknown;\n /** Firestore collection path of the repo (e.g. \"posts/{postId}/comments\") */\n path: string;\n /** Whether the repo is a collection-group */\n isGroup: boolean;\n /** Active where filters at the time of the failed query */\n filters: FilterState[];\n /** Active orderBy state at the time of the failed query (if any) */\n sort?: SortState;\n}\n\n/**\n * Detect whether an unknown error thrown by Firestore is a missing-index\n * (`FAILED_PRECONDITION` / code 9) error.\n */\nexport function isMissingIndexError(err: unknown): boolean {\n const fe = err as { code?: number; message?: string } | null | undefined;\n if (!fe) return false;\n if (fe.code === 9) return true;\n return typeof fe.message === \"string\"\n ? fe.message.includes(\"requires an index\")\n : false;\n}\n\n/**\n * Convert a Firestore error into a typed `QueryError` with a guaranteed\n * `indexUrl` for missing-index cases (extracted from the message when\n * present, otherwise rebuilt from the query context — necessary for\n * collection-group queries where the SDK omits the link).\n *\n * Returns `null` when `err` is falsy.\n */\nexport function toQueryError(\n err: unknown,\n ctx: QueryErrorContext,\n): QueryError {\n const fe = (err ?? {}) as { code?: number; message?: string };\n const isIndex = isMissingIndexError(err);\n\n let indexUrl: string | undefined;\n if (isIndex) {\n indexUrl = fe.message ? extractIndexUrl(fe.message) : undefined;\n if (!indexUrl) {\n const projectId = extractProjectId(ctx.ref);\n if (projectId) {\n const colId = collectionIdFromPath(ctx.path);\n indexUrl = buildIndexUrl(\n projectId,\n colId,\n ctx.isGroup,\n ctx.filters,\n ctx.sort,\n );\n }\n }\n }\n\n return {\n type: isIndex ? \"index\" : \"error\",\n message: isIndex\n ? \"This query requires a composite index that does not exist yet.\"\n : (fe.message ?? \"Query failed\"),\n indexUrl,\n };\n}\n","/**\n * HTTP route handlers for the CRUD API server.\n *\n * Routes:\n * GET /:repoName → list documents (paginated)\n * GET /:repoName/:id → get single document\n * POST /:repoName → create document\n * PUT /:repoName/:id → update document (full)\n * PATCH /:repoName/:id → update document (partial)\n * DELETE /:repoName/:id → delete document\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { z } from \"zod\";\nimport {\n coerceToDate,\n getDateHandling,\n maybeNormalize,\n} from \"../../shared/date-config\";\nimport { toQueryError, type QueryErrorContext } from \"../admin/index-url\";\nimport type {\n ApiResponse,\n CrudRepoEntry,\n CrudRepoRegistry,\n ListResponseData,\n QueryRequestBody,\n} from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Response helpers\n// ---------------------------------------------------------------------------\n\nfunction sendJson<T>(c: any, data: ApiResponse<T>, status = 200) {\n const payload = maybeNormalize(data);\n return c.json(payload, status as any);\n}\n\nfunction sendSuccess<T>(\n c: any,\n data: T,\n meta?: ApiResponse[\"meta\"],\n status = 200,\n) {\n return sendJson(c, { success: true, data, meta }, status);\n}\n\nfunction sendError(c: any, error: string, status = 400) {\n return sendJson(c, { success: false, error }, status);\n}\n\n/**\n * Send a structured error response. When the underlying Firestore error is a\n * missing-index (`FAILED_PRECONDITION` / code 9), include `errorType: \"index\"`\n * and an `indexUrl` pointing to the Firebase Console index-creation wizard —\n * crucial for collection-group queries where the SDK omits the link.\n */\nfunction sendQueryError(\n c: any,\n err: unknown,\n ctx: QueryErrorContext,\n fallbackMessage: string,\n verbose: boolean,\n) {\n const qe = toQueryError(err, ctx);\n const isIndex = qe.type === \"index\";\n const status = isIndex ? 424 : 500;\n const message = isIndex\n ? qe.message\n : verbose && err instanceof Error\n ? err.message\n : fallbackMessage;\n const payload: ApiResponse = { success: false, error: message };\n if (isIndex) {\n payload.errorType = \"index\";\n if (qe.indexUrl) payload.indexUrl = qe.indexUrl;\n }\n return sendJson(c, payload, status);\n}\n\n// ---------------------------------------------------------------------------\n// ID generation\n// ---------------------------------------------------------------------------\n\nconst _idChars =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n\n/**\n * Generate a random 20-char alphanumeric ID matching Firestore's native format.\n *\n * Uses a CSPRNG (`crypto.randomBytes`) — not `Math.random()` — so generated\n * ids are unpredictable, matching Firestore's own `doc().id`. Rejection\n * sampling (dropping the biased tail `>= 62*4`) keeps the distribution uniform\n * across the 62-char alphabet.\n */\nfunction generateFirestoreId(): string {\n let id = \"\";\n while (id.length < 20) {\n const bytes = randomBytes(20);\n for (let i = 0; i < bytes.length && id.length < 20; i++) {\n const byte = bytes[i]!;\n if (byte >= _idChars.length * 4) continue; // drop biased tail (248..255)\n id += _idChars.charAt(byte % _idChars.length);\n }\n }\n return id;\n}\n\n// ---------------------------------------------------------------------------\n// Zod schema helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Recursively wrap z.date() with z.preprocess(coerceToDate) so that ISO strings,\n * Firestore Timestamps and {_seconds,_nanoseconds} payloads are accepted as input.\n * Only invoked when global date handling mode is \"normalize\".\n */\nfunction wrapDateSchemas(schema: z.ZodType): z.ZodType {\n const def = (schema as any)._def ?? (schema as any).def;\n if (!def) return schema;\n const typeName = def.typeName ?? def.type;\n\n if (typeName === \"ZodDate\" || typeName === \"date\") {\n return z.preprocess((v) => coerceToDate(v) ?? v, schema as z.ZodDate);\n }\n if (typeName === \"ZodObject\" || typeName === \"object\") {\n const shape = (schema as z.ZodObject<any>).shape;\n const wrapped: Record<string, z.ZodType> = {};\n for (const [k, v] of Object.entries(shape)) {\n wrapped[k] = wrapDateSchemas(v as z.ZodType);\n }\n return z.object(wrapped);\n }\n if (typeName === \"ZodArray\" || typeName === \"array\") {\n const inner = def.element ?? def.type;\n if (inner) return z.array(wrapDateSchemas(inner));\n }\n if (typeName === \"ZodOptional\" || typeName === \"optional\") {\n const inner = def.innerType;\n if (inner) return wrapDateSchemas(inner).optional();\n }\n if (typeName === \"ZodNullable\" || typeName === \"nullable\") {\n const inner = def.innerType;\n if (inner) return wrapDateSchemas(inner).nullable();\n }\n if (typeName === \"ZodDefault\" || typeName === \"default\") {\n const inner = def.innerType;\n const dflt = def.defaultValue;\n if (inner) {\n const wrapped = wrapDateSchemas(inner);\n return typeof dflt === \"function\"\n ? wrapped.default(dflt())\n : wrapped.default(dflt);\n }\n }\n return schema;\n}\n\n/**\n * Pick only specified fields from a Zod schema, always excluding system-managed keys.\n *\n * - `fields` undefined or empty → all schema fields minus systemKeys\n * - `fields` with values → only those fields, minus systemKeys\n *\n * Security contract (issue #17): the returned schema is rebuilt from scratch\n * with `z.object(...)`, which **strips** any key not explicitly listed —\n * even when the user's root schema was declared `.passthrough()`. This\n * guarantees attacker-supplied keys (e.g. `__sync_version`, forged\n * timestamps, arbitrary metadata) can never reach Firestore via create /\n * update payloads. System keys are removed here too, so they cannot be\n * client-overridden.\n *\n * Note: a field explicitly declared as `z.any()` / `z.record(z.unknown())`\n * in the user schema is still accepted as-is by design — document such\n * free-form fields carefully, as their contents are persisted verbatim.\n */\nfunction pickSchemaFields(\n schema: z.ZodObject<any>,\n fields: string[] | undefined,\n systemKeys: string[] = [],\n): z.ZodObject<any> {\n const shape = schema.shape;\n const picked: Record<string, z.ZodType> = {};\n\n const source = fields && fields.length > 0 ? fields : Object.keys(shape);\n\n for (const field of source) {\n if (systemKeys.includes(field)) continue;\n const topLevel = field.split(\".\")[0];\n if (topLevel && shape[topLevel]) {\n picked[topLevel] = shape[topLevel]!;\n }\n }\n\n return z.object(picked);\n}\n\n/**\n * Validate data against schema and return parsed result or error.\n */\nfunction validateData(\n schema: z.ZodObject<any>,\n data: unknown,\n fields: string[] | undefined,\n partial = false,\n systemKeys: string[] = [],\n):\n | { success: true; data: Record<string, unknown> }\n | { success: false; error: string } {\n try {\n const targetSchema = pickSchemaFields(schema, fields, systemKeys);\n const partialSchema = partial ? targetSchema.partial() : targetSchema;\n const finalSchema =\n getDateHandling() === \"normalize\"\n ? (wrapDateSchemas(partialSchema) as z.ZodObject<any>)\n : partialSchema;\n const parsed = finalSchema.parse(data);\n return { success: true, data: parsed as Record<string, unknown> };\n } catch (err) {\n if (err instanceof z.ZodError) {\n const messages = err.issues.map(\n (e) => `${e.path.join(\".\")}: ${e.message}`,\n );\n return {\n success: false,\n error: `Validation failed: ${messages.join(\", \")}`,\n };\n }\n return { success: false, error: \"Validation failed\" };\n }\n}\n\n// ---------------------------------------------------------------------------\n// Filter parsing\n// ---------------------------------------------------------------------------\n\ntype WhereOp =\n | \"==\"\n | \"!=\"\n | \"<\"\n | \"<=\"\n | \">\"\n | \">=\"\n | \"in\"\n | \"not-in\"\n | \"array-contains\"\n | \"array-contains-any\";\n\ninterface ParsedFilter {\n field: string;\n op: WhereOp;\n value: unknown;\n}\n\n/**\n * Safely parse a filter value using the entity's schema field definition (if present).\n * If safeParse succeeds, returns the parsed data.\n * If safeParse fails on a single value but value is an Array, attempts to safeParse each item.\n */\nfunction parseFieldValue(\n entrySchema: unknown,\n field: string,\n val: unknown,\n): { success: true; data: unknown } | { success: false; error: string } {\n const fieldSchema = (entrySchema as any)?.shape?.[field];\n if (!fieldSchema || typeof fieldSchema.safeParse !== \"function\") {\n return { success: true, data: val };\n }\n\n const parsed = fieldSchema.safeParse(val);\n if (parsed.success) {\n return { success: true, data: parsed.data };\n }\n\n if (Array.isArray(val)) {\n const parsedArray: unknown[] = [];\n for (const item of val) {\n const itemParsed = fieldSchema.safeParse(item);\n if (itemParsed.success) {\n parsedArray.push(itemParsed.data);\n } else {\n const errorMessage = itemParsed.error.issues\n .map((e: any) => e.message)\n .join(\", \");\n return { success: false, error: errorMessage };\n }\n }\n return { success: true, data: parsedArray };\n }\n\n const messages = parsed.error.issues\n .map((e: any) => e.message)\n .join(\", \");\n return { success: false, error: messages };\n}\n\n/**\n * Parse query params into filter conditions.\n * Supports:\n * - field=value → field == value\n * - field__op=value → field op value (e.g., status__ne=draft → status != draft)\n * - field__in=a,b,c → field in [a, b, c]\n */\nfunction parseFilters(\n query: Record<string, string | string[] | undefined>,\n filterableFields: string[] | undefined,\n): ParsedFilter[] {\n const filters: ParsedFilter[] = [];\n const allowedFields = filterableFields ? new Set(filterableFields) : null;\n\n const opMap: Record<string, WhereOp> = {\n eq: \"==\",\n ne: \"!=\",\n lt: \"<\",\n lte: \"<=\",\n gt: \">\",\n gte: \">=\",\n in: \"in\",\n nin: \"not-in\",\n contains: \"array-contains\",\n containsAny: \"array-contains-any\",\n };\n\n for (const [key, rawVal] of Object.entries(query)) {\n if (rawVal === undefined) continue;\n\n // Skip pagination/meta params\n if (\n [\"cursor\", \"limit\", \"pageSize\", \"orderBy\", \"orderDir\", \"select\"].includes(\n key,\n )\n )\n continue;\n\n const val = Array.isArray(rawVal) ? rawVal[0] : rawVal;\n if (val === undefined || val === \"\") continue;\n\n // Parse field__op format\n const match = key.match(/^(\\w+)__(\\w+)$/);\n let field: string;\n let op: WhereOp = \"==\";\n\n if (match && match[1] && match[2]) {\n field = match[1];\n const opKey = match[2];\n if (opMap[opKey]) {\n op = opMap[opKey];\n } else {\n continue; // Unknown operator, skip\n }\n } else if (!match) {\n field = key;\n } else {\n continue; // Invalid match\n }\n\n // Check if field is filterable\n if (allowedFields && !allowedFields.has(field)) continue;\n\n // Parse value\n let parsedVal: unknown = val;\n\n // Handle \"in\" and \"not-in\" operators (comma-separated)\n if (op === \"in\" || op === \"not-in\" || op === \"array-contains-any\") {\n parsedVal = val.split(\",\").map((v) => parseValue(v.trim()));\n } else {\n parsedVal = parseValue(val);\n }\n\n filters.push({ field, op, value: parsedVal });\n }\n\n return filters;\n}\n\n/**\n * Parse a string value into appropriate type.\n */\nfunction parseValue(val: string): unknown {\n // Boolean\n if (val === \"true\") return true;\n if (val === \"false\") return false;\n if (val === \"null\" || val === \"__null__\") return null;\n\n // Number\n const num = Number(val);\n if (!isNaN(num) && val !== \"\") return num;\n\n // String\n return val;\n}\n\n// ---------------------------------------------------------------------------\n// Cursor serialization helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Serialize a Firestore DocumentSnapshot to a JSON-safe cursor object.\n */\nfunction serializeCursor(\n snapshot: import(\"firebase-admin/firestore\").DocumentSnapshot | undefined,\n): Record<string, unknown> | null {\n if (!snapshot) return null;\n return {\n docId: snapshot.id,\n docPath: snapshot.ref?.path ?? undefined,\n };\n}\n\n/**\n * Deserialize a cursor object back to a DocumentSnapshot.\n * Fetches the document from Firestore to get the actual snapshot.\n * Supports root collections and subcollections/collection groups via full docPath.\n */\nasync function deserializeCursor(\n entry: CrudRepoEntry,\n cursor: unknown,\n): Promise<import(\"firebase-admin/firestore\").DocumentSnapshot | undefined> {\n if (!cursor) return undefined;\n\n let cursorObj: Record<string, unknown> | undefined;\n if (typeof cursor === \"string\") {\n try {\n cursorObj = JSON.parse(cursor);\n } catch {\n cursorObj = cursor.includes(\"/\")\n ? { docPath: cursor }\n : { docId: cursor };\n }\n } else if (typeof cursor === \"object\") {\n cursorObj = cursor as Record<string, unknown>;\n }\n\n if (!cursorObj) return undefined;\n\n const docPath =\n typeof cursorObj.docPath === \"string\" ? cursorObj.docPath : undefined;\n const docId =\n typeof cursorObj.docId === \"string\" ? cursorObj.docId : undefined;\n\n try {\n const colRef = entry.repo.ref as any;\n const firestore = colRef?.firestore;\n\n // 1. If docPath is available and firestore instance exists, get doc directly by full path\n if (docPath && firestore && typeof firestore.doc === \"function\") {\n const snapshot = await firestore.doc(docPath).get();\n if (snapshot.exists) return snapshot;\n }\n\n // 2. If docId is a full path (e.g. \"users/u1/comments/c1\"), get doc by full path\n if (docId && docId.includes(\"/\") && firestore && typeof firestore.doc === \"function\") {\n const snapshot = await firestore.doc(docId).get();\n if (snapshot.exists) return snapshot;\n }\n\n // 3. Root collection fallback (colRef.doc exists for CollectionReference)\n if (docId && typeof colRef.doc === \"function\") {\n const snapshot = await colRef.doc(docId).get();\n if (snapshot.exists) return snapshot;\n }\n\n return undefined;\n } catch {\n return undefined;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Handlers factory\n// ---------------------------------------------------------------------------\n\nexport function createCrudHandlers(\n registry: CrudRepoRegistry,\n basePath: string,\n verbose: boolean,\n) {\n // ── Authorization helpers ───────────────────────────────────────────────\n /**\n * Default-deny gate: when the server has `auth` configured, reject any\n * operation without an explicit rule. When `auth` is absent, rules are\n * ignored entirely (open API).\n */\n async function assertRule<TCtx>(\n c: any,\n entry: CrudRepoEntry,\n op: keyof NonNullable<CrudRepoEntry[\"rules\"]>,\n ctx: TCtx,\n ): Promise<boolean> {\n if (!entry.rules) return true;\n const rule = entry.rules?.[op] as\n | ((c: TCtx) => boolean | Promise<boolean>)\n | undefined;\n if (!rule) {\n sendError(c, `Operation \"${op}\" is not allowed for this repository`, 403);\n return false;\n }\n try {\n const ok = await rule(ctx);\n if (!ok) {\n return sendError(c, \"Forbidden\", 403);\n return false;\n }\n return true;\n } catch (err) {\n const message =\n verbose && err instanceof Error ? err.message : \"Forbidden\";\n return sendError(c, message, 403);\n return false;\n }\n }\n\n /** Apply `rules.filter` to every doc in a list; returns the filtered slice. */\n async function applyRowFilter<T extends Record<string, unknown>>(\n entry: CrudRepoEntry,\n user: any,\n params: Record<string, string>,\n docs: T[],\n ): Promise<T[]> {\n if (!entry.rules) return docs;\n const filter = entry.rules?.filter as\n | ((c: {\n user: any;\n doc: T;\n params: Record<string, string>;\n }) => boolean | Promise<boolean>)\n | undefined;\n if (!filter) return docs;\n const out: T[] = [];\n for (const doc of docs) {\n try {\n if (await filter({ user, doc, params })) out.push(doc);\n } catch {\n // exclude on error (fail closed)\n }\n }\n return out;\n }\n\n /** Pull the authenticated user from the request (may be undefined when auth is off). */\n function userOf(c: any): any {\n return c.get(\"user\") ?? c.get(\"docsUser\") ?? null;\n }\n\n // ── Helper to get repo entry ────────────────────────────────────────────\n function getRepoEntry(\n repoName: string | undefined,\n c: any,\n ): CrudRepoEntry | null {\n if (!repoName) {\n const parts = c.req.path.split(\"/\");\n for (const part of parts) {\n if (registry[part]) {\n repoName = part;\n break;\n }\n }\n }\n if (!repoName || !registry[repoName]) {\n return null;\n }\n return registry[repoName] ?? null;\n }\n\n /**\n * Extract Firestore document path args from a document's stored path.\n * e.g. \"posts/abc/comments/xyz\" → [\"abc\", \"xyz\"] (the doc-ID segments).\n */\n function extractPathArgs(\n doc: Record<string, unknown>,\n pathKey?: string,\n ): string[] | undefined {\n if (!pathKey) return undefined;\n const fullPath = doc[pathKey];\n if (typeof fullPath !== \"string\" || !fullPath) return undefined;\n const segments = fullPath.split(\"/\").filter(Boolean);\n const args: string[] = [];\n for (let i = 1; i < segments.length; i += 2) {\n args.push(segments[i]!);\n }\n return args.length > 0 ? args : undefined;\n }\n\n /**\n * Fetch a single document by its documentKey, with fallback to query\n * for collection-group repos where direct documentRef may fail.\n */\n async function fetchDocById(\n entry: CrudRepoEntry,\n docId: string,\n ): Promise<Record<string, unknown> | null> {\n const getterName = `by${entry.documentKey.charAt(0).toUpperCase()}${entry.documentKey.slice(1)}`;\n const getter = (entry.repo.get as any)[getterName];\n\n if (typeof getter === \"function\") {\n try {\n const doc = (await getter(docId)) as Record<string, unknown> | null;\n if (doc) return doc;\n } catch {\n // Direct ref may fail for subcollections — fall through to query\n }\n }\n\n const results = await entry.repo.query.by({\n where: [[entry.documentKey, \"==\", docId]],\n limit: 1,\n });\n return (results[0] as Record<string, unknown>) ?? null;\n }\n\n // ── LIST: GET /:repoName ────────────────────────────────────────────────\n async function handleList(ctx: any): Promise<any> {\n const c = ctx.c;\n\n const params = c.req.param();\n const entry = getRepoEntry(params.repoName, c);\n if (!entry) return sendError(c, `Repository not found`, 404);\n\n const user = userOf(c);\n if (\n !(await assertRule(c, entry, \"list\", {\n user,\n query: c.req.query(),\n params,\n }))\n )\n return;\n\n // Captured for error handling (so the catch can build an index URL)\n let ctxFilters: { field: string; op: any; value: string }[] = [];\n let ctxSort: { field: string; dir: \"asc\" | \"desc\" } | undefined;\n\n try {\n const query = c.req.query();\n const pageSize = Math.min(\n Number(query.pageSize) || entry.pageSize,\n 100, // Max page size\n );\n const cursor = query.cursor as string | undefined;\n const direction =\n (query.direction as string)?.toLowerCase() === \"prev\" ? \"prev\" : \"next\";\n const orderBy = query.orderBy as string | undefined;\n const orderDir =\n (query.orderDir as string)?.toLowerCase() === \"desc\" ? \"desc\" : \"asc\";\n const selectStr = query.select as string | undefined;\n const select = selectStr\n ? selectStr.split(\",\").map((s) => s.trim())\n : undefined;\n\n // Parse includes (relation population)\n let includes:\n | (string | { relation: string; select?: string[] })[]\n | undefined;\n if (entry.allowedIncludes && query.includes) {\n const rawIncludes =\n typeof query.includes === \"string\"\n ? query.includes.split(\",\").map((s: string) => s.trim())\n : Array.isArray(query.includes)\n ? query.includes\n : [];\n includes = rawIncludes.filter(\n (inc: string) =>\n typeof inc === \"string\" && entry.allowedIncludes!.includes(inc),\n );\n if (includes?.length === 0) includes = undefined;\n }\n\n // Parse filters\n const filters = parseFilters(query, entry.filterableFields);\n ctxFilters = filters.map((f) => ({\n field: f.field,\n op: f.op,\n value: String(f.value ?? \"\"),\n }));\n if (orderBy) ctxSort = { field: orderBy, dir: orderDir };\n\n // Build query options\n const queryOptions: any = {\n pageSize,\n direction,\n };\n\n if (cursor) {\n try {\n const cursorObj =\n typeof cursor === \"string\" ? JSON.parse(cursor) : cursor;\n queryOptions.cursor = await deserializeCursor(entry, cursorObj);\n } catch {\n // Invalid cursor, ignore\n }\n }\n\n if (orderBy) {\n if (entry.orderableFields && !entry.orderableFields.includes(orderBy)) {\n return sendError(c, `Field not orderable: ${orderBy}`, 400);\n }\n queryOptions.orderBy = [{ field: orderBy, direction: orderDir }];\n }\n\n if (filters.length > 0) {\n queryOptions.where = [];\n for (const f of filters) {\n const parsedRes = parseFieldValue(entry.schema, f.field, f.value);\n if (!parsedRes.success) {\n return sendError(\n c,\n `Invalid filter value for '${f.field}': ${parsedRes.error}`,\n 400,\n );\n }\n queryOptions.where.push([f.field, f.op, parsedRes.data]);\n }\n }\n\n if (select) {\n queryOptions.select = select as any;\n }\n\n if (includes) {\n queryOptions.include = includes as any;\n }\n\n // Execute query\n const result = await entry.repo.query.paginate(queryOptions);\n const filteredItems = await applyRowFilter(\n entry,\n userOf(c),\n params,\n result.data,\n );\n\n const responseData: ListResponseData = {\n items: filteredItems,\n hasNextPage: result.hasNextPage,\n hasPrevPage: result.hasPrevPage,\n nextCursor: serializeCursor(result.nextCursor),\n prevCursor: serializeCursor(result.prevCursor),\n };\n\n return sendSuccess(c, responseData, {\n pageSize,\n hasMore: result.hasNextPage,\n });\n } catch (err) {\n sendQueryError(\n c,\n err,\n {\n ref: entry.repo.ref,\n path: entry.path,\n isGroup: !!entry.isGroup,\n filters: ctxFilters,\n sort: ctxSort,\n },\n \"Failed to fetch documents\",\n verbose,\n );\n }\n }\n\n // ── QUERY: POST /:repoName/query ────────────────────────────────────────\n // Advanced query endpoint supporting OR conditions, array filters, etc.\n async function handleQuery(ctx: any): Promise<any> {\n const c = ctx.c;\n\n const params = c.req.param();\n const entry = getRepoEntry(params.repoName, c);\n if (!entry) return sendError(c, `Repository not found`, 404);\n\n const user = userOf(c);\n if (\n !(await assertRule(c, entry, \"list\", {\n user,\n query: ctx.input || {},\n params,\n }))\n )\n return;\n\n // Captured for error handling (so the catch can build an index URL)\n let ctxFilters: { field: string; op: any; value: string }[] = [];\n let ctxSort: { field: string; dir: \"asc\" | \"desc\" } | undefined;\n\n try {\n const body: QueryRequestBody = ctx.input || {};\n const pageSize = Math.min(body.pageSize || entry.pageSize, 100);\n const direction = body.direction === \"prev\" ? \"prev\" : \"next\";\n\n // Capture context for index URL fallback\n if (body.where) {\n ctxFilters = body.where.map((w) => ({\n field: String(w[0]),\n op: w[1] as any,\n value: String(w[2] ?? \"\"),\n }));\n }\n if (body.orderBy && body.orderBy[0]) {\n ctxSort = {\n field: body.orderBy[0].field,\n dir: body.orderBy[0].direction === \"desc\" ? \"desc\" : \"asc\",\n };\n }\n\n // Build query options\n const queryOptions: any = {\n pageSize,\n direction,\n };\n\n // Cursor\n if (body.cursor) {\n try {\n const cursorObj =\n typeof body.cursor === \"string\"\n ? JSON.parse(body.cursor)\n : body.cursor;\n queryOptions.cursor = await deserializeCursor(entry, cursorObj);\n } catch {\n // Invalid cursor, ignore\n }\n }\n\n // Includes (relation population)\n if (entry.allowedIncludes && body.includes && body.includes.length > 0) {\n const validIncludes = body.includes.filter((inc) => {\n if (typeof inc === \"string\") {\n return entry.allowedIncludes!.includes(inc);\n }\n if (\n typeof inc === \"object\" &&\n inc !== null &&\n \"relation\" in inc &&\n typeof inc.relation === \"string\"\n ) {\n return entry.allowedIncludes!.includes(inc.relation);\n }\n return false;\n });\n if (validIncludes.length > 0) {\n queryOptions.include = validIncludes as any;\n }\n }\n\n // Where conditions (AND)\n if (body.where && body.where.length > 0) {\n // Validate filterable fields if configured\n if (entry.filterableFields) {\n const allowed = new Set(entry.filterableFields);\n const invalid = body.where.filter((w) => !allowed.has(w[0]));\n if (invalid.length > 0) {\n sendError(\n c,\n `Fields not filterable: ${invalid.map((w) => w[0]).join(\", \")}`,\n 400,\n );\n return;\n }\n }\n const parsedWhere: [string, any, any][] = [];\n for (const w of body.where) {\n const parsedRes = parseFieldValue(entry.schema, w[0], w[2]);\n if (!parsedRes.success) {\n sendError(\n c,\n `Invalid filter value for '${w[0]}': ${parsedRes.error}`,\n 400,\n );\n return;\n }\n parsedWhere.push([w[0], w[1], parsedRes.data]);\n }\n queryOptions.where = parsedWhere;\n }\n\n // OR where conditions (simple)\n if (body.orWhere && body.orWhere.length > 0) {\n if (entry.filterableFields) {\n const allowed = new Set(entry.filterableFields);\n const invalid = body.orWhere.filter((w) => !allowed.has(w[0]));\n if (invalid.length > 0) {\n sendError(\n c,\n `Fields not filterable: ${invalid.map((w) => w[0]).join(\", \")}`,\n 400,\n );\n return;\n }\n }\n const parsedOrWhere: [string, any, any][] = [];\n for (const w of body.orWhere) {\n const parsedRes = parseFieldValue(entry.schema, w[0], w[2]);\n if (!parsedRes.success) {\n sendError(\n c,\n `Invalid filter value for '${w[0]}': ${parsedRes.error}`,\n 400,\n );\n return;\n }\n parsedOrWhere.push([w[0], w[1], parsedRes.data]);\n }\n queryOptions.orWhere = parsedOrWhere;\n }\n\n // OR where groups (advanced)\n if (body.orWhereGroups && body.orWhereGroups.length > 0) {\n if (entry.filterableFields) {\n const allowed = new Set(entry.filterableFields);\n for (const group of body.orWhereGroups) {\n const invalid = group.filter((w) => !allowed.has(w[0]));\n if (invalid.length > 0) {\n sendError(\n c,\n `Fields not filterable: ${invalid.map((w) => w[0]).join(\", \")}`,\n 400,\n );\n return;\n }\n }\n }\n const parsedOrWhereGroups: [string, any, any][][] = [];\n for (const group of body.orWhereGroups) {\n const parsedGroup: [string, any, any][] = [];\n for (const w of group) {\n const parsedRes = parseFieldValue(entry.schema, w[0], w[2]);\n if (!parsedRes.success) {\n sendError(\n c,\n `Invalid filter value for '${w[0]}': ${parsedRes.error}`,\n 400,\n );\n return;\n }\n parsedGroup.push([w[0], w[1], parsedRes.data]);\n }\n parsedOrWhereGroups.push(parsedGroup);\n }\n queryOptions.orWhereGroups = parsedOrWhereGroups;\n }\n\n // Order by\n if (body.orderBy && body.orderBy.length > 0) {\n if (entry.orderableFields) {\n const allowed = new Set(entry.orderableFields);\n const invalid = body.orderBy.filter((o) => !allowed.has(o.field));\n if (invalid.length > 0) {\n sendError(\n c,\n `Fields not orderable: ${invalid.map((o) => o.field).join(\", \")}`,\n 400,\n );\n return;\n }\n }\n queryOptions.orderBy = body.orderBy;\n }\n\n // Select\n if (body.select && body.select.length > 0) {\n queryOptions.select = body.select;\n }\n\n // Execute query\n const result = await entry.repo.query.paginate(queryOptions);\n const filteredItems = await applyRowFilter(\n entry,\n userOf(c),\n params,\n result.data,\n );\n\n const responseData: ListResponseData = {\n items: filteredItems,\n hasNextPage: result.hasNextPage,\n hasPrevPage: result.hasPrevPage,\n nextCursor: serializeCursor(result.nextCursor),\n prevCursor: serializeCursor(result.prevCursor),\n };\n\n return sendSuccess(c, responseData, {\n pageSize,\n hasMore: result.hasNextPage,\n });\n } catch (err) {\n sendQueryError(\n c,\n err,\n {\n ref: entry.repo.ref,\n path: entry.path,\n isGroup: !!entry.isGroup,\n filters: ctxFilters,\n sort: ctxSort,\n },\n \"Failed to query documents\",\n verbose,\n );\n }\n }\n\n // ── GET: GET /:repoName/:id ─────────────────────────────────────────────\n async function handleGet(ctx: any): Promise<any> {\n const c = ctx.c;\n\n const params = c.req.param();\n const entry = getRepoEntry(params.repoName, c);\n if (!entry) return sendError(c, `Repository not found`, 404);\n\n const id = params.id;\n if (!id) {\n return sendError(c, \"Document ID required\", 400);\n }\n\n try {\n const doc = await fetchDocById(entry, id);\n\n if (!doc) {\n return sendError(c, \"Document not found\", 404);\n }\n\n const user = userOf(c);\n if (\n !(await assertRule(c, entry, \"get\", {\n user,\n doc: doc as any,\n params,\n }))\n )\n return;\n\n // Apply row-level filter (404 if rejected, to avoid existence leakage)\n if (entry.rules?.filter) {\n try {\n const ok = await entry.rules.filter({\n user,\n doc: doc as any,\n params,\n });\n if (!ok) {\n return sendError(c, \"Document not found\", 404);\n }\n } catch {\n return sendError(c, \"Document not found\", 404);\n }\n }\n\n return sendSuccess(c, doc);\n } catch (err) {\n sendQueryError(\n c,\n err,\n {\n ref: entry.repo.ref,\n path: entry.path,\n isGroup: !!entry.isGroup,\n filters: [{ field: entry.documentKey, op: \"==\", value: id }],\n },\n \"Failed to fetch document\",\n verbose,\n );\n }\n }\n\n // ── CREATE: POST /:repoName ─────────────────────────────────────────────\n async function handleCreate(ctx: any): Promise<any> {\n const c = ctx.c;\n\n const params = c.req.param();\n const entry = getRepoEntry(params.repoName, c);\n if (!entry) return sendError(c, `Repository not found`, 404);\n\n try {\n const body = ctx.input || {};\n\n const user = userOf(c);\n if (\n !(await assertRule(c, entry, \"create\", {\n user,\n body,\n params,\n }))\n )\n return;\n\n // Validate against schema\n const validation = validateData(\n entry.schema,\n body,\n entry.createFields,\n false,\n entry.systemKeys,\n );\n if (!validation.success) {\n return sendError(c, (validation as any).error, 400);\n }\n\n // Custom validation\n if (entry.validate) {\n const customError = await entry.validate(validation.data, \"create\");\n if (customError) {\n return sendError(c, customError, 400);\n }\n }\n\n // Create document\n let created: any;\n if (entry.isGroup && entry.parentKeys && entry.parentKeys.length > 0) {\n // Collection-group repos cannot use create(); use set() with parent path args.\n const data: Record<string, any> = { ...validation.data };\n // set() doesn't auto-set createdKey, so inject it here\n if (entry.createdKey) {\n data[entry.createdKey] = new Date();\n }\n const missingKeys = entry.parentKeys.filter((k) => !data[k]);\n if (missingKeys.length > 0) {\n sendError(\n c,\n `Missing parent key(s) for subcollection create: ${missingKeys.join(\", \")}`,\n 400,\n );\n return;\n }\n const parentIds = entry.parentKeys.map((k) => data[k] as string);\n const docId = data[entry.documentKey] || generateFirestoreId();\n created = await entry.repo.set(...parentIds, docId, data);\n } else {\n created = await entry.repo.create(validation.data as any);\n }\n\n return sendSuccess(c, created, undefined, 201);\n } catch (err) {\n const message =\n verbose && err instanceof Error\n ? err.message\n : \"Failed to create document\";\n return sendError(c, message, 500);\n }\n }\n\n // ── UPDATE: PUT/PATCH /:repoName/:id ────────────────────────────────────\n async function handleUpdate(ctx: any, partial: boolean): Promise<any> {\n const c = ctx.c;\n const params = c.req.param();\n const entry = getRepoEntry(params.repoName, c);\n if (!entry) return sendError(c, `Repository not found`, 404);\n\n const id = params.id;\n if (!id) {\n return sendError(c, \"Document ID required\", 400);\n }\n\n try {\n const body = ctx.input || {};\n\n // Fetch existing doc so the rule can authorize against current state\n const existingDoc = await fetchDocById(entry, id);\n if (!existingDoc) {\n return sendError(c, \"Document not found\", 404);\n }\n\n const user = userOf(c);\n if (\n !(await assertRule(c, entry, \"update\", {\n user,\n doc: existingDoc as any,\n body,\n params,\n }))\n )\n return;\n\n // Validate against schema\n const validation = validateData(\n entry.schema,\n body,\n entry.mutableFields,\n partial,\n entry.systemKeys,\n );\n if (!validation.success) {\n return sendError(c, (validation as any).error, 400);\n }\n\n // Custom validation\n if (entry.validate) {\n const customError = await entry.validate(validation.data, \"update\");\n if (customError) {\n return sendError(c, customError, 400);\n }\n }\n\n // Update document — derive path args for subcollections\n const pathArgs = extractPathArgs(existingDoc, entry.pathKey) ?? [id];\n const updated = await entry.repo.update(\n ...pathArgs,\n validation.data as any,\n );\n\n return sendSuccess(c, updated);\n } catch (err) {\n const message =\n verbose && err instanceof Error\n ? err.message\n : \"Failed to update document\";\n return sendError(c, message, 500);\n }\n }\n\n // ── DELETE: DELETE /:repoName/:id ───────────────────────────────────────\n async function handleDelete(ctx: any): Promise<any> {\n const c = ctx.c;\n\n const params = c.req.param();\n const entry = getRepoEntry(params.repoName, c);\n if (!entry) return sendError(c, `Repository not found`, 404);\n\n if (!entry.allowDelete) {\n return sendError(c, \"Delete not allowed for this repository\", 403);\n }\n\n const id = params.id;\n if (!id) {\n return sendError(c, \"Document ID required\", 400);\n }\n\n try {\n // Fetch first to authorize against current state and get path args\n const doc = await fetchDocById(entry, id);\n if (!doc) {\n return sendError(c, \"Document not found\", 404);\n }\n\n const user = userOf(c);\n if (\n !(await assertRule(c, entry, \"delete\", {\n user,\n doc: doc as any,\n params,\n }))\n )\n return;\n\n const pathArgs = extractPathArgs(doc, entry.pathKey) ?? [id];\n await entry.repo.delete(...pathArgs);\n return sendSuccess(c, { deleted: true });\n } catch (err) {\n const message =\n verbose && err instanceof Error\n ? err.message\n : \"Failed to delete document\";\n return sendError(c, message, 500);\n }\n }\n\n // ── OPTIONS: for CORS preflight ─────────────────────────────────────────\n function handleOptions(ctx: any): any {\n const c = ctx.c;\n return c.text(\"\", 204, {\n \"Access-Control-Allow-Methods\": \"GET, POST, PUT, PATCH, DELETE, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"Content-Type, Authorization\",\n \"Access-Control-Max-Age\": \"86400\",\n });\n }\n\n // ── BATCH: POST /:repoName/batch ─────────────────────────────────────────\n async function handleBatch(ctx: any) {\n const c = ctx.c;\n const params = c.req.param();\n const entry = getRepoEntry(params.repoName, c);\n if (!entry) return sendError(c, `Repository not found`, 404);\n\n try {\n const body = ctx.input || {};\n if (!Array.isArray(body.operations)) {\n return sendError(c, \"operations array is required\", 400);\n }\n\n const user = userOf(c);\n\n const batch = entry.repo.batch.create();\n const results = [];\n\n for (const op of body.operations) {\n if (!op.type || ![\"create\", \"update\", \"delete\"].includes(op.type)) {\n return sendError(c, \"Invalid operation type\", 400);\n }\n\n if (op.type === \"create\") {\n if (\n !(await assertRule(c, entry, \"create\", {\n user,\n body: op.data,\n params,\n }))\n )\n return;\n const validation = validateData(\n entry.schema,\n op.data,\n entry.createFields,\n false,\n entry.systemKeys,\n );\n if (!validation.success)\n return sendError(c, (validation as any).error, 400);\n\n let docId = op.data[entry.documentKey] || generateFirestoreId();\n const data = { ...validation.data };\n if (entry.createdKey) data[entry.createdKey] = new Date();\n\n if (entry.isGroup && entry.parentKeys) {\n const parentIds = entry.parentKeys.map(\n (k: string) => data[k] as string,\n );\n batch.set(...parentIds, docId, data);\n } else {\n batch.set(docId, data);\n }\n results.push({ op: \"create\", id: docId });\n } else if (op.type === \"update\") {\n if (!op.id) return sendError(c, \"id required for update\", 400);\n\n const existingDoc = await fetchDocById(entry, op.id);\n if (!existingDoc)\n return sendError(c, `Document ${op.id} not found`, 404);\n\n if (\n !(await assertRule(c, entry, \"update\", {\n user,\n doc: existingDoc as any,\n body: op.data,\n params,\n }))\n )\n return;\n\n const validation = validateData(\n entry.schema,\n op.data,\n entry.mutableFields,\n true,\n entry.systemKeys,\n );\n if (!validation.success)\n return sendError(c, (validation as any).error, 400);\n\n const pathArgs = extractPathArgs(existingDoc, entry.pathKey) ?? [\n op.id,\n ];\n batch.update(...pathArgs, validation.data);\n results.push({ op: \"update\", id: op.id });\n } else if (op.type === \"delete\") {\n if (!entry.allowDelete)\n return sendError(c, \"Delete not allowed\", 403);\n if (!op.id) return sendError(c, \"id required for delete\", 400);\n\n const doc = await fetchDocById(entry, op.id);\n if (!doc) return sendError(c, `Document ${op.id} not found`, 404);\n if (\n !(await assertRule(c, entry, \"delete\", {\n user,\n doc: doc as any,\n params,\n }))\n )\n return;\n\n const pathArgs = extractPathArgs(doc, entry.pathKey) ?? [op.id];\n batch.delete(...pathArgs);\n results.push({ op: \"delete\", id: op.id });\n }\n }\n\n await batch.commit();\n return sendSuccess(c, { results });\n } catch (err) {\n const message =\n verbose && err instanceof Error\n ? err.message\n : \"Batch operation failed\";\n return sendError(c, message, 500);\n }\n }\n\n return {\n handleList,\n handleQuery,\n handleGet,\n handleCreate,\n handleUpdate,\n handleDelete,\n handleBatch,\n handleOptions,\n };\n}\n","/**\n * OpenAPI 3.1 specification generator for the CRUD server.\n *\n * Introspects each `CrudRepoEntry` and uses Zod 4's native `z.toJSONSchema()`\n * to produce a fully typed OpenAPI document ready for Scalar UI or codegen.\n *\n * @module servers/crud/openapi\n */\n\nimport { z } from \"zod\";\nimport { getOpenApiMetadata } from \"@asteasolutions/zod-to-openapi\";\nimport type { CrudRepoEntry, CrudRepoRegistry, OpenAPISpecOptions } from \"./types\";\n\nexport type { OpenAPISpecOptions };\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Minimal subset of an OpenAPI 3.1 document we produce. */\nexport interface OpenAPIDocument {\n openapi: \"3.1.0\";\n info: OpenAPIInfo;\n servers?: { url: string; description?: string }[];\n paths: Record<string, Record<string, OpenAPIOperation>>;\n components: {\n schemas: Record<string, Record<string, unknown>>;\n securitySchemes?: Record<string, Record<string, unknown>>;\n };\n security?: Record<string, string[]>[];\n tags?: { name: string; description?: string }[];\n}\n\nexport interface OpenAPIInfo {\n title: string;\n version: string;\n description?: string;\n}\n\ninterface OpenAPIOperation {\n operationId: string;\n summary: string;\n tags: string[];\n parameters?: Record<string, unknown>[];\n requestBody?: Record<string, unknown>;\n responses: Record<string, Record<string, unknown>>;\n security?: Record<string, string[]>[];\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Convert a Zod schema to a JSON Schema object suitable for OpenAPI 3.1.\n *\n * Uses `unrepresentable: \"any\"` so that types Zod can't natively serialize\n * (e.g. `z.date()`, `z.bigint()`, custom classes — common with Firestore\n * Timestamps stored as `Date`) don't throw and collapse the whole schema to\n * a bare `{ type: \"object\" }`. We additionally override a few well-known\n * cases to a sensible OpenAPI representation.\n */\nfunction zodToJsonSchema(schema: z.ZodType): Record<string, unknown> {\n try {\n return z.toJSONSchema(schema, {\n target: \"openapi-3.1\",\n unrepresentable: \"any\",\n override: (ctx) => {\n const metadata = getOpenApiMetadata(ctx.zodSchema as unknown as z.ZodTypeAny);\n if (metadata) {\n Object.assign(ctx.jsonSchema, metadata);\n }\n\n const def: any = (ctx.zodSchema as any)?._zod?.def;\n if (!def) return;\n if (def.type === \"date\" && !(ctx.jsonSchema as any).type) {\n (ctx.jsonSchema as any).type = \"string\";\n (ctx.jsonSchema as any).format = \"date-time\";\n } else if (def.type === \"bigint\" && !(ctx.jsonSchema as any).type) {\n (ctx.jsonSchema as any).type = \"string\";\n (ctx.jsonSchema as any).format = \"int64\";\n }\n },\n }) as Record<string, unknown>;\n } catch (err) {\n if (typeof console !== \"undefined\" && console.warn) {\n console.warn(\n \"[generateOpenAPISpec] Failed to convert Zod schema to JSON Schema; falling back to {type:object}.\",\n err,\n );\n }\n return { type: \"object\" };\n }\n}\n\n/** Wraps a JSON Schema in a `#/components/schemas/<name>` $ref. */\nfunction schemaRef(name: string): Record<string, unknown> {\n return { $ref: `#/components/schemas/${name}` };\n}\n\n/** Standard error response schema. */\nfunction errorResponse(description: string): Record<string, unknown> {\n return {\n description,\n content: {\n \"application/json\": {\n schema: schemaRef(\"ErrorResponse\"),\n },\n },\n };\n}\n\n/** Standard success response wrapping data. */\nfunction successResponse(\n description: string,\n dataSchema: Record<string, unknown>,\n): Record<string, unknown> {\n return {\n description,\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n success: { type: \"boolean\", enum: [true] },\n data: dataSchema,\n },\n required: [\"success\", \"data\"],\n },\n },\n },\n };\n}\n\n/** Build list response with pagination metadata. */\nfunction listResponse(\n itemSchema: Record<string, unknown>,\n): Record<string, unknown> {\n return {\n description: \"Paginated list of documents\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n success: { type: \"boolean\", enum: [true] },\n data: {\n type: \"object\",\n properties: {\n items: { type: \"array\", items: itemSchema },\n nextCursor: {\n oneOf: [{ type: \"object\" }, { type: \"null\" }],\n },\n prevCursor: {\n oneOf: [{ type: \"object\" }, { type: \"null\" }],\n },\n hasNextPage: { type: \"boolean\" },\n hasPrevPage: { type: \"boolean\" },\n },\n required: [\"items\", \"hasNextPage\", \"hasPrevPage\"],\n },\n meta: {\n type: \"object\",\n properties: {\n pageSize: { type: \"integer\" },\n hasMore: { type: \"boolean\" },\n cursor: {\n oneOf: [{ type: \"string\" }, { type: \"null\" }],\n },\n },\n },\n },\n required: [\"success\", \"data\"],\n },\n },\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Introspection & Zod-to-OpenAPI Type Resolution\n// ---------------------------------------------------------------------------\n\n/** Helper to unwrap Zod modifiers (optional, nullable, default, catch, effects, etc.) */\nfunction unwrapZodType(zodType: any): any {\n let cur = zodType;\n while (cur) {\n const def = cur._zod?.def ?? cur._def;\n if (!def) break;\n if (def.innerType) {\n cur = def.innerType;\n } else if (def.schema) {\n cur = def.schema;\n } else if (\n def.type === \"optional\" ||\n def.type === \"nullable\" ||\n def.type === \"default\" ||\n def.type === \"catch\" ||\n def.type === \"effects\"\n ) {\n cur = def.innerType ?? def.schema;\n } else {\n break;\n }\n }\n return cur;\n}\n\n/** Resolve a dot-notation path (e.g. \"address.city\") from a Zod schema */\nfunction resolveFieldPathSchema(entrySchema: any, path: string): any {\n const parts = path.split(\".\");\n let cur = unwrapZodType(entrySchema);\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n if (!part) continue;\n const shape: Record<string, any> | undefined = (cur as any)?.shape;\n if (!shape || !shape[part]) {\n return undefined;\n }\n const rawSub = shape[part];\n if (i === parts.length - 1) {\n return rawSub;\n }\n cur = unwrapZodType(rawSub);\n }\n return cur;\n}\n\n/** Recursively extract leaf fields and parent object fields from a Zod object schema */\nfunction extractLeafFields(\n zodSchema: any,\n prefix = \"\",\n depth = 0,\n): { path: string; zodSchema: any }[] {\n if (depth > 5) return [];\n const unwrapped = unwrapZodType(zodSchema);\n const shape = unwrapped?.shape;\n if (!shape) return [];\n\n const results: { path: string; zodSchema: any }[] = [];\n for (const [key, rawSub] of Object.entries(shape)) {\n const fieldPath = prefix ? `${prefix}.${key}` : key;\n const subUnwrapped = unwrapZodType(rawSub);\n if (subUnwrapped?.shape && typeof subUnwrapped.shape === \"object\") {\n results.push({ path: fieldPath, zodSchema: rawSub });\n results.push(...extractLeafFields(subUnwrapped, fieldPath, depth + 1));\n } else {\n results.push({ path: fieldPath, zodSchema: rawSub });\n }\n }\n return results;\n}\n\n/** Get all filterable leaf fields for a CrudRepoEntry */\nfunction getFilterableLeafFields(\n entry: CrudRepoEntry,\n): { path: string; zodSchema: any }[] {\n if (entry.filterableFields && entry.filterableFields.length > 0) {\n return entry.filterableFields.map((path) => ({\n path,\n zodSchema: resolveFieldPathSchema(entry.schema, path),\n }));\n }\n return extractLeafFields(entry.schema);\n}\n\n/** Convert a Zod field schema to an inline OpenAPI JSON Schema for its value */\nfunction zodTypeToJsonValueSchema(zodType: any): Record<string, unknown> {\n if (!zodType) return { type: \"string\" };\n const jsonSchema = zodToJsonSchema(zodType);\n delete jsonSchema[\"$schema\"];\n delete jsonSchema[\"title\"];\n return jsonSchema;\n}\n\n// ---------------------------------------------------------------------------\n// Pagination / filter query parameters (shared across list endpoints)\n// ---------------------------------------------------------------------------\n\nfunction paginationParams(entry: CrudRepoEntry): Record<string, unknown>[] {\n const leafFields = getFilterableLeafFields(entry);\n const orderableFields =\n entry.orderableFields ?? leafFields.map((f) => f.path);\n\n return [\n {\n name: \"pageSize\",\n in: \"query\",\n schema: { type: \"integer\", default: entry.pageSize, maximum: 100 },\n description: \"Number of items per page\",\n },\n {\n name: \"cursor\",\n in: \"query\",\n schema: { type: \"string\" },\n description: \"Base64 pagination cursor\",\n },\n {\n name: \"orderBy\",\n in: \"query\",\n schema: {\n type: \"string\",\n ...(orderableFields.length > 0 ? { enum: orderableFields } : {}),\n },\n description: \"Field name to order by\",\n },\n {\n name: \"orderDir\",\n in: \"query\",\n schema: { type: \"string\", enum: [\"asc\", \"desc\"] },\n description: \"Order direction\",\n },\n {\n name: \"select\",\n in: \"query\",\n schema: { type: \"string\" },\n description: `Comma-separated list of fields to return${\n leafFields.length > 0\n ? ` (${leafFields.map((f) => f.path).join(\", \")})`\n : \"\"\n }`,\n },\n ];\n}\n\nfunction filterParams(entry: CrudRepoEntry): Record<string, unknown>[] {\n const leafFields = getFilterableLeafFields(entry);\n const ops = [\n \"eq\",\n \"ne\",\n \"lt\",\n \"lte\",\n \"gt\",\n \"gte\",\n \"in\",\n \"nin\",\n \"contains\",\n \"containsAny\",\n ];\n\n const opDescriptions: Record<string, string> = {\n eq: \"equals. Use 'null' or '__null__' to match null values\",\n ne: \"not equals. Use 'null' or '__null__' to match non-null values\",\n lt: \"less than\",\n lte: \"less than or equal\",\n gt: \"greater than\",\n gte: \"greater than or equal\",\n in: \"in list (comma-separated values). Supports 'null' and '__null__' (e.g. val1,val2,__null__)\",\n nin: \"not in list (comma-separated values). Supports 'null' and '__null__'\",\n contains: \"array-contains\",\n containsAny: \"array-contains-any (comma-separated values). Supports 'null' and '__null__'\",\n };\n\n const params: Record<string, unknown>[] = [];\n for (const { path: field, zodSchema } of leafFields) {\n const valSchema = zodTypeToJsonValueSchema(zodSchema);\n\n // Direct equality filter: ?field=value\n params.push({\n name: field,\n in: \"query\",\n schema: valSchema,\n description: `Filter by ${field} (equality). Use 'null' or '__null__' for null values`,\n });\n // Operator filters: ?field__op=value\n for (const op of ops) {\n const descDetail = opDescriptions[op] ? ` (${opDescriptions[op]})` : \"\";\n const isListOp = op === \"in\" || op === \"nin\" || op === \"containsAny\";\n params.push({\n name: `${field}__${op}`,\n in: \"query\",\n schema: isListOp\n ? { type: \"string\", description: \"Comma-separated list of values\" }\n : valSchema,\n description: `Filter ${field} with operator ${op}${descDetail}`,\n });\n }\n }\n return params;\n}\n\n// ---------------------------------------------------------------------------\n// Query body schema (POST /query)\n// ---------------------------------------------------------------------------\n\nfunction queryBodySchema(): Record<string, unknown> {\n return {\n type: \"object\",\n properties: {\n where: {\n type: \"array\",\n items: {\n type: \"array\",\n items: {},\n minItems: 3,\n maxItems: 3,\n },\n description: \"AND conditions: [field, operator, value][]\",\n },\n orWhere: {\n type: \"array\",\n items: {\n type: \"array\",\n items: {},\n minItems: 3,\n maxItems: 3,\n },\n description: \"Simple OR conditions (each independently OR'd)\",\n },\n orWhereGroups: {\n type: \"array\",\n items: {\n type: \"array\",\n items: {\n type: \"array\",\n items: {},\n minItems: 3,\n maxItems: 3,\n },\n },\n description: \"Advanced OR groups (AND within, OR across groups)\",\n },\n orderBy: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n field: { type: \"string\" },\n direction: { type: \"string\", enum: [\"asc\", \"desc\"] },\n },\n required: [\"field\"],\n },\n },\n select: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"Fields to select (projection)\",\n },\n pageSize: {\n type: \"integer\",\n maximum: 100,\n description: \"Number of items per page\",\n },\n cursor: {\n oneOf: [{ type: \"string\" }, { type: \"object\" }],\n description: \"Pagination cursor\",\n },\n direction: {\n type: \"string\",\n enum: [\"next\", \"prev\"],\n description: \"Pagination direction\",\n },\n includes: {\n type: \"array\",\n items: {\n oneOf: [\n { type: \"string\" },\n {\n type: \"object\",\n properties: {\n relation: { type: \"string\" },\n select: { type: \"array\", items: { type: \"string\" } },\n },\n required: [\"relation\"],\n },\n ],\n },\n description: \"Relations to include (populate)\",\n },\n },\n };\n}\n\n/** Build a strongly-typed OpenAPI QueryRequestBody schema tailored to a CrudRepoEntry */\nfunction buildTypedQueryBodySchema(entry: CrudRepoEntry): Record<string, unknown> {\n const leafFields = getFilterableLeafFields(entry);\n const orderableFieldNames =\n entry.orderableFields ?? leafFields.map((f) => f.path);\n const leafFieldNames = leafFields.map((f) => f.path);\n\n if (leafFields.length === 0) {\n return queryBodySchema();\n }\n\n const whereTuples: Record<string, unknown>[] = [];\n\n for (const { path, zodSchema } of leafFields) {\n const valSchema = zodTypeToJsonValueSchema(zodSchema);\n const unwrapped = unwrapZodType(zodSchema);\n\n const isArrayType =\n (unwrapped as any)?._zod?.def?.type === \"array\" ||\n (unwrapped as any)?._def?.typeName === \"ZodArray\" ||\n (unwrapped as any)?._def?.type === \"array\";\n\n const elemSchema = isArrayType\n ? zodTypeToJsonValueSchema(\n (unwrapped as any)?._zod?.def?.element ??\n (unwrapped as any)?._def?.type ??\n (unwrapped as any)?._def?.element,\n )\n : valSchema;\n\n // Standard comparison operators (==, !=, <, <=, >, >=)\n whereTuples.push({\n type: \"array\",\n description: `Condition on '${path}'`,\n prefixItems: [\n { type: \"string\", enum: [path] },\n {\n type: \"string\",\n enum: [\"==\", \"!=\", \"<\", \"<=\", \">\", \">=\", \"eq\", \"ne\", \"lt\", \"lte\", \"gt\", \"gte\"],\n },\n valSchema,\n ],\n minItems: 3,\n maxItems: 3,\n });\n\n // List operators (in, not-in)\n whereTuples.push({\n type: \"array\",\n description: `List condition on '${path}' (in, not-in)`,\n prefixItems: [\n { type: \"string\", enum: [path] },\n { type: \"string\", enum: [\"in\", \"not-in\", \"nin\"] },\n { type: \"array\", items: valSchema },\n ],\n minItems: 3,\n maxItems: 3,\n });\n\n // Array contains operators\n whereTuples.push({\n type: \"array\",\n description: `Array contains condition on '${path}'`,\n prefixItems: [\n { type: \"string\", enum: [path] },\n { type: \"string\", enum: [\"array-contains\", \"contains\"] },\n elemSchema,\n ],\n minItems: 3,\n maxItems: 3,\n });\n\n whereTuples.push({\n type: \"array\",\n description: `Array contains-any condition on '${path}'`,\n prefixItems: [\n { type: \"string\", enum: [path] },\n { type: \"string\", enum: [\"array-contains-any\", \"containsAny\"] },\n { type: \"array\", items: elemSchema },\n ],\n minItems: 3,\n maxItems: 3,\n });\n }\n\n const whereItemSchema = {\n oneOf: whereTuples,\n };\n\n return {\n type: \"object\",\n properties: {\n where: {\n type: \"array\",\n items: whereItemSchema,\n description: \"AND conditions: [field, operator, value][]\",\n },\n orWhere: {\n type: \"array\",\n items: whereItemSchema,\n description: \"Simple OR conditions (each independently OR'd)\",\n },\n orWhereGroups: {\n type: \"array\",\n items: {\n type: \"array\",\n items: whereItemSchema,\n },\n description: \"Advanced OR groups (AND within, OR across groups)\",\n },\n orderBy: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n field: { type: \"string\", enum: orderableFieldNames },\n direction: { type: \"string\", enum: [\"asc\", \"desc\"] },\n },\n required: [\"field\"],\n },\n },\n select: {\n type: \"array\",\n items: { type: \"string\", enum: leafFieldNames },\n description: \"Fields to select (projection)\",\n },\n pageSize: {\n type: \"integer\",\n maximum: 100,\n description: \"Number of items per page\",\n },\n cursor: {\n oneOf: [{ type: \"string\" }, { type: \"object\" }],\n description: \"Pagination cursor\",\n },\n direction: {\n type: \"string\",\n enum: [\"next\", \"prev\"],\n description: \"Pagination direction\",\n },\n includes: {\n type: \"array\",\n items:\n entry.allowedIncludes && entry.allowedIncludes.length > 0\n ? {\n oneOf: [\n { type: \"string\", enum: entry.allowedIncludes },\n {\n type: \"object\",\n properties: {\n relation: { type: \"string\", enum: entry.allowedIncludes },\n select: { type: \"array\", items: { type: \"string\" } },\n },\n required: [\"relation\"],\n },\n ],\n }\n : {\n oneOf: [\n { type: \"string\" },\n {\n type: \"object\",\n properties: {\n relation: { type: \"string\" },\n select: { type: \"array\", items: { type: \"string\" } },\n },\n required: [\"relation\"],\n },\n ],\n },\n description: \"Relations to include (populate)\",\n },\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Path generation per repo entry\n// ---------------------------------------------------------------------------\n\nfunction buildPathsForEntry(\n entry: CrudRepoEntry,\n base: string,\n modelSchemaName: string,\n createSchemaName: string | null,\n updateSchemaName: string | null,\n querySchemaName: string = \"QueryRequestBody\",\n): Record<string, Record<string, OpenAPIOperation>> {\n const paths: Record<string, Record<string, OpenAPIOperation>> = {};\n const tag = entry.name;\n const collectionPath = `${base}/${entry.name}`;\n const documentPath = `${collectionPath}/{${entry.documentKey}}`;\n\n const idParam = {\n name: entry.documentKey,\n in: \"path\",\n required: true,\n schema: { type: \"string\" },\n description: `Unique document identifier`,\n };\n\n // ── GET /:repo → list ──────────────────────────────────────────────\n paths[collectionPath] = {\n get: {\n operationId: `list${capitalize(entry.name)}`,\n summary: `List ${entry.name} (paginated)`,\n tags: [tag],\n parameters: [...paginationParams(entry), ...filterParams(entry)],\n responses: {\n \"200\": listResponse(schemaRef(modelSchemaName)),\n \"500\": errorResponse(\"Internal server error\"),\n },\n },\n // ── POST /:repo → create ────────────────────────────────────────\n post: {\n operationId: `create${capitalize(entry.name)}`,\n summary: `Create a ${singularize(entry.name)}`,\n tags: [tag],\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: schemaRef(createSchemaName ?? modelSchemaName),\n },\n },\n },\n responses: {\n \"201\": successResponse(\"Document created\", schemaRef(modelSchemaName)),\n \"400\": errorResponse(\"Validation error\"),\n \"500\": errorResponse(\"Internal server error\"),\n },\n },\n };\n\n // ── POST /:repo/query → advanced query ────────────────────────────\n paths[`${collectionPath}/query`] = {\n post: {\n operationId: `query${capitalize(entry.name)}`,\n summary: `Query ${entry.name} with advanced filters`,\n tags: [tag],\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: schemaRef(querySchemaName),\n },\n },\n },\n responses: {\n \"200\": listResponse(schemaRef(modelSchemaName)),\n \"400\": errorResponse(\"Invalid query\"),\n \"500\": errorResponse(\"Internal server error\"),\n },\n },\n };\n\n // ── POST /:repo/batch → batch operations ─────────────────────────\n paths[`${collectionPath}/batch`] = {\n post: {\n operationId: `batch${capitalize(entry.name)}`,\n summary: `Execute batch operations on ${entry.name}`,\n tags: [tag],\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: schemaRef(`${modelSchemaName}BatchRequest`),\n },\n },\n },\n responses: {\n \"200\": successResponse(\"Batch operations completed\", {\n type: \"object\",\n properties: {\n results: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n op: { type: \"string\" },\n id: { type: \"string\" },\n },\n },\n },\n },\n }),\n \"400\": errorResponse(\"Validation error\"),\n \"403\": errorResponse(\"Forbidden\"),\n \"404\": errorResponse(\"Document not found\"),\n \"500\": errorResponse(\"Internal server error\"),\n },\n },\n };\n\n // ── Single-document paths ────────────────────────────────────────\n const docOps: Record<string, OpenAPIOperation> = {};\n\n // GET /:repo/:id\n docOps.get = {\n operationId: `get${capitalize(singularize(entry.name))}`,\n summary: `Get a single ${singularize(entry.name)}`,\n tags: [tag],\n parameters: [idParam],\n responses: {\n \"200\": successResponse(\"Document found\", schemaRef(modelSchemaName)),\n \"404\": errorResponse(\"Document not found\"),\n \"500\": errorResponse(\"Internal server error\"),\n },\n };\n\n // PUT /:repo/:id (full update)\n docOps.put = {\n operationId: `update${capitalize(singularize(entry.name))}`,\n summary: `Update a ${singularize(entry.name)} (full replace)`,\n tags: [tag],\n parameters: [idParam],\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: schemaRef(updateSchemaName ?? modelSchemaName),\n },\n },\n },\n responses: {\n \"200\": successResponse(\"Document updated\", schemaRef(modelSchemaName)),\n \"400\": errorResponse(\"Validation error\"),\n \"404\": errorResponse(\"Document not found\"),\n \"500\": errorResponse(\"Internal server error\"),\n },\n };\n\n // PATCH /:repo/:id (partial update)\n docOps.patch = {\n operationId: `patch${capitalize(singularize(entry.name))}`,\n summary: `Partially update a ${singularize(entry.name)}`,\n tags: [tag],\n parameters: [idParam],\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: {\n allOf: [schemaRef(updateSchemaName ?? modelSchemaName)],\n description: \"All fields are optional for partial updates\",\n },\n },\n },\n },\n responses: {\n \"200\": successResponse(\"Document patched\", schemaRef(modelSchemaName)),\n \"400\": errorResponse(\"Validation error\"),\n \"404\": errorResponse(\"Document not found\"),\n \"500\": errorResponse(\"Internal server error\"),\n },\n };\n\n // DELETE /:repo/:id (only if allowDelete)\n if (entry.allowDelete) {\n docOps.delete = {\n operationId: `delete${capitalize(singularize(entry.name))}`,\n summary: `Delete a ${singularize(entry.name)}`,\n tags: [tag],\n parameters: [idParam],\n responses: {\n \"200\": successResponse(\"Document deleted\", {\n type: \"object\",\n properties: { id: { type: \"string\" } },\n }),\n \"404\": errorResponse(\"Document not found\"),\n \"500\": errorResponse(\"Internal server error\"),\n },\n };\n }\n\n paths[documentPath] = docOps;\n\n return paths;\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Generate a full OpenAPI 3.1 specification from a `CrudRepoRegistry`.\n *\n * Uses Zod 4's native `z.toJSONSchema()` to convert each repo's schema\n * into a JSON Schema component, then assembles paths for the standard\n * CRUD endpoints.\n *\n * @example\n * ```ts\n * import { generateOpenAPISpec } from \"@lpdjs/firestore-repo-service/servers/crud\";\n *\n * const spec = generateOpenAPISpec(registry, \"/api\", {\n * title: \"My API\",\n * version: \"1.0.0\",\n * servers: [{ url: \"https://my-api.example.com\" }],\n * auth: \"bearer\",\n * });\n *\n * // Write to file\n * fs.writeFileSync(\"openapi.json\", JSON.stringify(spec, null, 2));\n * ```\n */\nexport function generateOpenAPISpec(\n registry: CrudRepoRegistry,\n basePath: string,\n options: OpenAPISpecOptions = {},\n): OpenAPIDocument {\n const {\n title = \"CRUD API\",\n version = \"1.0.0\",\n description,\n servers,\n auth = false,\n } = options;\n\n const base = basePath === \"/\" ? \"\" : basePath.replace(/\\/$/, \"\");\n\n // ── Components: schemas ───────────────────────────────────────────\n const schemas: Record<string, Record<string, unknown>> = {};\n const allPaths: Record<string, Record<string, OpenAPIOperation>> = {};\n const tags: { name: string; description?: string }[] = [];\n\n // Shared schemas\n schemas[\"ErrorResponse\"] = {\n type: \"object\",\n properties: {\n success: { type: \"boolean\", enum: [false] },\n error: { type: \"string\" },\n },\n required: [\"success\", \"error\"],\n };\n\n schemas[\"QueryRequestBody\"] = queryBodySchema();\n\n // Per-repo schemas & paths\n for (const [name, entry] of Object.entries(registry)) {\n const modelName = capitalize(singularize(name));\n const createName = `${modelName}Create`;\n const updateName = `${modelName}Update`;\n const queryName = `${modelName}QueryRequestBody`;\n\n // Full model schema\n schemas[modelName] = zodToJsonSchema(entry.schema);\n\n // Per-repository typed QueryRequestBody schema\n schemas[queryName] = buildTypedQueryBodySchema(entry);\n\n // Helper: build a filtered shape (respects systemKeys + field list)\n const buildShape = (\n fieldList: string[] | undefined,\n ): Record<string, z.ZodType> => {\n const source =\n fieldList && fieldList.length > 0\n ? fieldList\n : Object.keys(entry.schema.shape);\n const shape: Record<string, z.ZodType> = {};\n for (const f of source) {\n const top = f.split(\".\")[0];\n if (top && entry.schema.shape[top] && !entry.systemKeys.includes(top)) {\n shape[top] = entry.schema.shape[top];\n }\n }\n return shape;\n };\n\n // Create schema\n let createSchemaName: string | null = null;\n const createShape = buildShape(entry.createFields);\n if (Object.keys(createShape).length > 0) {\n schemas[createName] = zodToJsonSchema(z.object(createShape));\n createSchemaName = createName;\n }\n\n // Update schema\n let updateSchemaName: string | null = null;\n const updateShape = buildShape(entry.mutableFields);\n if (Object.keys(updateShape).length > 0) {\n schemas[updateName] = zodToJsonSchema(z.object(updateShape));\n updateSchemaName = updateName;\n }\n\n // Batch schema\n schemas[`${modelName}BatchRequest`] = {\n type: \"object\",\n properties: {\n operations: {\n type: \"array\",\n items: {\n oneOf: [\n {\n type: \"object\",\n properties: {\n type: { type: \"string\", enum: [\"create\"] },\n data: schemaRef(createSchemaName ?? modelName),\n },\n required: [\"type\", \"data\"],\n },\n {\n type: \"object\",\n properties: {\n type: { type: \"string\", enum: [\"update\"] },\n id: { type: \"string\" },\n data: {\n allOf: [schemaRef(updateSchemaName ?? modelName)],\n description: \"Partial updates allowed\",\n },\n },\n required: [\"type\", \"id\", \"data\"],\n },\n ...(entry.allowDelete\n ? [\n {\n type: \"object\",\n properties: {\n type: { type: \"string\", enum: [\"delete\"] },\n id: { type: \"string\" },\n },\n required: [\"type\", \"id\"],\n },\n ]\n : []),\n ],\n },\n },\n },\n required: [\"operations\"],\n };\n\n // Build paths\n const entryPaths = buildPathsForEntry(\n entry,\n base,\n modelName,\n createSchemaName,\n updateSchemaName,\n queryName,\n );\n Object.assign(allPaths, entryPaths);\n\n // Tag\n tags.push({\n name,\n description: `Operations on ${name} (collection: ${entry.path})`,\n });\n }\n\n\n // ── Security ──────────────────────────────────────────────────────\n const securitySchemes: Record<string, Record<string, unknown>> = {};\n let security: Record<string, string[]>[] | undefined;\n\n if (auth === \"basic\") {\n securitySchemes[\"basicAuth\"] = {\n type: \"http\",\n scheme: \"basic\",\n };\n security = [{ basicAuth: [] }];\n } else if (auth === \"bearer\") {\n securitySchemes[\"bearerAuth\"] = {\n type: \"http\",\n scheme: \"bearer\",\n bearerFormat: \"JWT\",\n };\n security = [{ bearerAuth: [] }];\n }\n\n // ── Assemble ──────────────────────────────────────────────────────\n const doc: OpenAPIDocument = {\n openapi: \"3.1.0\",\n info: {\n title,\n version,\n ...(description ? { description } : {}),\n },\n ...(servers && servers.length > 0 ? { servers } : {}),\n paths: allPaths,\n components: {\n schemas,\n ...(Object.keys(securitySchemes).length > 0 ? { securitySchemes } : {}),\n },\n ...(security ? { security } : {}),\n tags,\n };\n\n return doc;\n}\n\n// ---------------------------------------------------------------------------\n// Utility\n// ---------------------------------------------------------------------------\n\nfunction capitalize(s: string): string {\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n\n/** Naive singularize: strip trailing 's' for display. */\nfunction singularize(s: string): string {\n if (s.endsWith(\"ies\")) return s.slice(0, -3) + \"y\";\n if (s.endsWith(\"ses\") || s.endsWith(\"xes\") || s.endsWith(\"zes\"))\n return s.slice(0, -2);\n if (s.endsWith(\"s\") && !s.endsWith(\"ss\")) return s.slice(0, -1);\n return s;\n}\n","/**\n * Public types for the Hono file-based API server.\n *\n * Designed to be:\n * - **fully typed** end-to-end (Zod input/output → handler payload type),\n * - **runtime-safe** via Zod parsing on every request,\n * - **bundle-friendly** for Firebase Cloud Functions v2 cold-start (codegen\n * emits static imports — no `fs`/`import()` at runtime).\n */\n\nimport type { z, ZodError } from \"zod\";\nimport type { Context, Env, MiddlewareHandler } from \"hono\";\nimport type { AnyServicesContainer } from \"./services\";\nimport type { DocsAuthExtension } from \"./docs-auth\";\n\nexport type HttpMethod = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\n\n/** Where the validated payload comes from. */\nexport type PayloadSource = \"json\" | \"query\" | \"form\" | \"param\";\n\n/**\n * Structured logger injected into every handler / interceptor / error-handler\n * context. Implement it, or extend the package's `BaseLogger` and override its\n * `write` hook to route to your sink (Firebase logger, pino, …).\n *\n * `error()` returns a correlation id so the same value can be both logged and\n * returned to the client.\n */\nexport interface Logger {\n info(message: string, meta?: unknown): void;\n warn(message: string, meta?: unknown): void;\n /** @returns a correlation id (e.g. to include in the HTTP error response). */\n error(error: unknown, meta?: unknown): string;\n debug(message: string, meta?: unknown): void;\n}\n\n/** Context passed to {@link ErrorHandler.handle}. */\nexport interface ErrorHandlerContext<\n TEnv extends Env = Env,\n TServices extends AnyServicesContainer = AnyServicesContainer,\n> {\n /** The thrown value (an `AppError`, a Zod {@link ValidationError}, …). */\n error: unknown;\n /** Hono request context — set status, read headers, build the response. */\n c: Context<TEnv>;\n /** Route metadata (read-only). */\n route: AnyRouteDef;\n /** Global DI services container. */\n services: TServices;\n /** Injected {@link Logger} when one was passed to the API, else `undefined`. */\n logger?: Logger;\n}\n\n/**\n * Cross-cutting error strategy — a class (or object) you pass to the API and\n * that the server injects everywhere **and** applies automatically.\n *\n * Implement {@link ErrorHandler.handle} to map any thrown value to an HTTP\n * `Response` (e.g. your `AppError` → status + localized body, plus structured\n * logging with a correlation id). Return `null` to decline the error and let\n * the built-in fallback (`ValidationError` envelope) / `onError` take over.\n *\n * Prefer extending the package's {@link BaseErrorHandler} (it already maps the\n * built-in errors) and overriding its `mapError` / `logError` hooks. Pass it\n * **per API** via `ApiConfig.errorHandler`, or once via the registry\n * (`{ services, errorHandler }`); it is then available in every handler /\n * interceptor context as `errorHandler` and auto-applied on any uncaught error.\n */\nexport interface ErrorHandler<\n TEnv extends Env = Env,\n TServices extends AnyServicesContainer = AnyServicesContainer,\n> {\n handle(\n ctx: ErrorHandlerContext<TEnv, TServices>,\n ): Response | null | Promise<Response | null>;\n}\n\n/** Handler signature — receives a single typed context object. */\nexport type RouteHandler<\n TIn,\n TOut,\n TEnv extends Env = Env,\n TServices extends AnyServicesContainer = AnyServicesContainer,\n> = (ctx: {\n /** Validated (and typed) request payload. `void` when no `input` schema is defined. */\n input: TIn;\n /** Raw Hono `Context` for headers, set status, redirect, etc. */\n c: Context<TEnv>;\n /**\n * Global DI services container — same instance shared by every handler.\n * Empty `ServicesContainer` when the server was started without a\n * `services` option.\n */\n services: TServices;\n /**\n * Injected {@link ErrorHandler} when one was passed to the API, else\n * `undefined`. Usually you just `throw` and let it apply automatically.\n */\n errorHandler?: ErrorHandler<TEnv, TServices>;\n /** Injected {@link Logger} when one was passed to the API, else `undefined`. */\n logger?: Logger;\n}) => Promise<TOut | Response> | TOut | Response;\n\n/**\n * One route declaration. Default-exported by every `routes.ts` file inside the\n * domain tree. Use {@link defineRoute} for full type inference.\n */\nexport interface RouteDef<\n TIn extends z.ZodTypeAny | undefined = z.ZodTypeAny | undefined,\n TOut extends z.ZodTypeAny | undefined = z.ZodTypeAny | undefined,\n TEnv extends Env = Env,\n> {\n /**\n * Logical API tag — routes sharing the same `api` are mounted on the same\n * `HonoServer` (typically one Cloud Function per `api`).\n *\n * To expose the **same logic** under several APIs with different\n * inputs/outputs, export multiple `defineRoute({...})` from the same file\n * (default + named exports are both picked up by the codegen).\n */\n api: string;\n\n /** HTTP method. */\n method: HttpMethod;\n\n /**\n * URL path appended to the server `basePath`. If omitted, the codegen will\n * derive it from the file location (e.g. `domains/activities/useCases/createCustom/routes.ts`\n * → `/activities/createCustom`).\n */\n path?: string;\n\n /**\n * Where the request payload comes from.\n * Default: `\"json\"` for body methods (POST/PUT/PATCH/DELETE), `\"query\"` for GET.\n */\n source?: PayloadSource;\n\n /** Zod schema validating the payload. Failures yield a 400 response. */\n input?: TIn;\n\n /**\n * Zod schema for the success response. Used to populate the OpenAPI spec\n * and (when `validateOutput` is enabled on the server) to assert the\n * runtime payload returned by the handler.\n */\n output?: TOut;\n\n /** Status code for the success response. Default: 200. */\n status?: number;\n\n /** Hono middlewares applied to this route only (after global middlewares). */\n middlewares?: MiddlewareHandler<TEnv>[];\n\n // ── OpenAPI metadata ─────────────────────────────────────────────────\n summary?: string;\n description?: string;\n tags?: string[];\n /** Mark the operation as deprecated in the generated spec. */\n deprecated?: boolean;\n /** Security requirements (operationId-level override). */\n security?: SecurityRequirement[];\n\n /** The request handler. */\n handler: RouteHandler<\n TIn extends z.ZodTypeAny ? z.infer<TIn> : void,\n TOut extends z.ZodTypeAny ? z.infer<TOut> : unknown,\n TEnv\n >;\n}\n\n/** Erased `RouteDef` used by registry/codegen — handler signature is opaque. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyRouteDef = RouteDef<any, any>;\n\n/**\n * What `routes.ts` can default-export:\n * - a single {@link RouteDef} (most common case),\n * - or an array of {@link RouteDef} (e.g. expose the same useCase on\n * multiple `api` tags or under multiple paths). `readonly` arrays are\n * accepted so that tuple-preserving helpers like {@link defineRoutes} (or a\n * plain `as const` array) can be default-exported directly.\n */\nexport type RouteModuleDefault = AnyRouteDef | readonly AnyRouteDef[];\n\n// ── useCase ⇆ routes type bridge ──────────────────────────────────────────\n// A useCase should never re-declare its input/output by hand. Instead it\n// derives them from the Zod schemas of the route(s) that drive it, so the two\n// can never drift apart. Pass `typeof import(\"./routes.js\").default` to the\n// helpers below.\n\n/**\n * Identity helper that **preserves the tuple type** of a `routes.ts` default\n * export. A plain array literal (`export default [a, b]`) collapses every\n * element to a single common type, which would lose each route's individual\n * schema. Wrapping the array with `defineRoutes([...])` keeps the per-route\n * types intact so {@link RouteInput} / {@link RouteOutput} can aggregate them\n * into a union.\n *\n * @example\n * export default defineRoutes([\n * defineRoute({ ... }),\n * defineRoute({ ... }),\n * ]);\n */\nexport function defineRoutes<const T extends readonly AnyRouteDef[]>(\n routes: T,\n): T {\n return routes;\n}\n\n/**\n * Normalizes a `routes.ts` default export — a single {@link RouteDef} or an\n * array of them — to a *union* of its individual route members.\n */\nexport type RoutesUnion<T> = T extends readonly (infer R)[] ? R : T;\n\ntype InferRouteInput<R> = R extends { input?: infer I }\n ? I extends z.ZodTypeAny\n ? z.infer<I>\n : void\n : void;\n\ntype InferRouteOutput<R> = R extends { output?: infer O }\n ? O extends z.ZodTypeAny\n ? z.infer<O>\n : unknown\n : unknown;\n\n/**\n * Union of validated request payloads across every route in a `routes.ts`\n * module. Use it to type a useCase input without duplicating the Zod schema:\n *\n * @example\n * type Routes = typeof import(\"./routes.js\").default;\n * export type CreatePostUseCaseInput = RouteInput<Routes>;\n */\nexport type RouteInput<T> = InferRouteInput<RoutesUnion<T>>;\n\n/**\n * Union of success-response payloads across every route in a `routes.ts`\n * module. Mirror of {@link RouteInput} for the useCase output type.\n */\nexport type RouteOutput<T> = InferRouteOutput<RoutesUnion<T>>;\n\n/**\n * Thrown by the server when the incoming request fails Zod validation.\n * Caught by the {@link RouteInterceptor} (if any) so users can shape the\n * response envelope however they like; otherwise yields a default 400.\n */\nexport class ValidationError extends Error {\n readonly statusCode = 400 as const;\n constructor(\n /** Original Zod error — `error.issues` to enumerate field-level problems. */\n readonly zodError: ZodError,\n /** Where the offending payload came from. */\n readonly source: PayloadSource,\n ) {\n super(\"Request validation failed\");\n this.name = \"ValidationError\";\n }\n}\n\n/**\n * Cross-cutting interceptor applied around every handler.\n * Use it for response envelopes, business-error → HTTP mapping, structured\n * logging, tracing spans, etc.\n *\n * Wrap `next()` in `try/catch` to intercept BOTH Zod {@link ValidationError}s\n * (thrown before the handler runs) AND business errors thrown by the handler.\n *\n * @example\n * ```ts\n * interceptor: async ({ next, route, c }) => {\n * try {\n * const data = await next();\n * return c.json({ success: true, data, error: null });\n * } catch (err) {\n * if (err instanceof ValidationError) {\n * return c.json({ success: false, error: \"validation\", issues: err.zodError.issues }, 400);\n * }\n * if (err instanceof DomainError) {\n * return c.json({ success: false, error: err.code }, err.statusCode);\n * }\n * throw err; // → falls back to onError or Hono's default 500\n * }\n * }\n * ```\n */\nexport type RouteInterceptor<\n TEnv extends Env = Env,\n TServices extends AnyServicesContainer = AnyServicesContainer,\n> = (ctx: {\n /**\n * Calls validation + handler and returns the raw value.\n * Throws {@link ValidationError} on Zod failure or any error thrown by the handler.\n */\n next: () => Promise<unknown>;\n /** Route metadata (read-only). */\n route: AnyRouteDef;\n /** Hono request context. */\n c: Context<TEnv>;\n /** Global DI services container. See {@link RouteHandler}. */\n services: TServices;\n /**\n * Injected {@link ErrorHandler} when one was passed to the API. Call\n * `errorHandler?.handle({ error, c, route, services })` in your `catch` to\n * reuse the shared mapping, or simply rethrow to let it apply automatically.\n */\n errorHandler?: ErrorHandler<TEnv, TServices>;\n /** Injected {@link Logger} when one was passed to the API, else `undefined`. */\n logger?: Logger;\n}) => Promise<Response | unknown> | Response | unknown;\n\n/**\n * Success-envelope schema declared alongside an interceptor so the generated\n * OpenAPI spec documents what the **wrapper actually returns** (not the raw\n * handler output).\n *\n * - a **static** Zod schema → same envelope for every route (e.g.\n * `z.object({ data: z.any(), intercepted: z.boolean() })`);\n * - a **factory** `(routeOutput) => schema` → wraps each route's own `output`,\n * so `data` is typed per endpoint in the docs.\n */\nexport type InterceptorOutput =\n | z.ZodTypeAny\n | ((routeOutput: z.ZodTypeAny | undefined) => z.ZodTypeAny);\n\n/** A single declared error response for the OpenAPI spec. */\nexport type InterceptorErrorResponse =\n | z.ZodTypeAny\n | { description?: string; schema?: z.ZodTypeAny };\n\n/**\n * Structured interceptor — pairs the cross-cutting {@link RouteInterceptor}\n * `handler` with the OpenAPI metadata describing what it returns, so the docs\n * reflect the real wrapped responses (success envelope + error shapes).\n *\n * @example\n * ```ts\n * interceptor: {\n * // factory: `data` reflects each route's own output schema\n * output: (routeOutput) =>\n * z.object({ data: routeOutput ?? z.unknown(), intercepted: z.boolean() }),\n * errors: {\n * 400: ValidationErrorSchema,\n * 500: { description: \"Internal\", schema: ErrorSchema },\n * },\n * handler: async ({ c, next }) => {\n * const data = await next();\n * return c.json({ data, intercepted: true });\n * },\n * }\n * ```\n */\nexport interface InterceptorConfig<\n TEnv extends Env = Env,\n TServices extends AnyServicesContainer = AnyServicesContainer,\n> {\n /** Success-envelope schema (static) or per-route factory. */\n output?: InterceptorOutput;\n /**\n * Error responses applied to **every** operation, keyed by HTTP status. Pass\n * a bare Zod schema or `{ description, schema }`.\n */\n errors?: Record<number, InterceptorErrorResponse>;\n /** The interceptor function. See {@link RouteInterceptor}. */\n handler: RouteInterceptor<TEnv, TServices>;\n}\n\n/**\n * Interceptor option accepted by the server / registry — either a bare\n * {@link RouteInterceptor} function (legacy) or a structured\n * {@link InterceptorConfig} carrying OpenAPI metadata.\n */\nexport type InterceptorOption<\n TEnv extends Env = Env,\n TServices extends AnyServicesContainer = AnyServicesContainer,\n> = RouteInterceptor<TEnv, TServices> | InterceptorConfig<TEnv, TServices>;\n\n/** OpenAPI document info (subset of the spec used by the helper). */\nexport interface OpenAPIInfo {\n title: string;\n version: string;\n description?: string;\n}\n\n// ── OpenAPI 3.1 Security Scheme Object ──────────────────────────────────────\n\n/** Fields shared by every security scheme. */\nexport interface SecuritySchemeBase {\n /** Human-readable description (CommonMark). */\n description?: string;\n}\n\n/** API key carried in a header, query param or cookie. */\nexport interface ApiKeySecurityScheme extends SecuritySchemeBase {\n type: \"apiKey\";\n /** Name of the header, query parameter or cookie. */\n name: string;\n /** Location of the API key. */\n in: \"query\" | \"header\" | \"cookie\";\n}\n\n/**\n * HTTP authentication (RFC 7235), e.g. `bearer` (Firebase ID tokens) or\n * `basic`.\n */\nexport interface HttpSecurityScheme extends SecuritySchemeBase {\n type: \"http\";\n /** Auth scheme name — `\"bearer\"`, `\"basic\"`, `\"digest\"`, … */\n // eslint-disable-next-line @typescript-eslint/ban-types\n scheme: \"bearer\" | \"basic\" | \"digest\" | (string & {});\n /** Hint for the bearer token format, e.g. `\"JWT\"` / `\"Firebase JWT\"`. */\n bearerFormat?: string;\n}\n\n/** Mutual TLS authentication. */\nexport interface MutualTlsSecurityScheme extends SecuritySchemeBase {\n type: \"mutualTLS\";\n}\n\n/** A single OAuth2 flow. */\nexport interface OAuthFlowObject {\n authorizationUrl?: string;\n tokenUrl?: string;\n refreshUrl?: string;\n /** Available scopes → description. */\n scopes: Record<string, string>;\n}\n\n/** The OAuth2 flows supported by an {@link OAuth2SecurityScheme}. */\nexport interface OAuthFlowsObject {\n implicit?: OAuthFlowObject;\n password?: OAuthFlowObject;\n clientCredentials?: OAuthFlowObject;\n authorizationCode?: OAuthFlowObject;\n}\n\n/** OAuth2 authentication. */\nexport interface OAuth2SecurityScheme extends SecuritySchemeBase {\n type: \"oauth2\";\n flows: OAuthFlowsObject;\n}\n\n/** OpenID Connect Discovery. */\nexport interface OpenIdConnectSecurityScheme extends SecuritySchemeBase {\n type: \"openIdConnect\";\n openIdConnectUrl: string;\n}\n\n/** OpenAPI 3.1 Security Scheme Object (discriminated on `type`). */\nexport type SecurityScheme =\n | ApiKeySecurityScheme\n | HttpSecurityScheme\n | MutualTlsSecurityScheme\n | OAuth2SecurityScheme\n | OpenIdConnectSecurityScheme;\n\n/**\n * A single Security Requirement Object: maps a scheme name (a key of\n * {@link OpenAPIConfig.securitySchemes}) to the list of required scopes\n * (empty `[]` for `http` / `apiKey`).\n */\nexport type SecurityRequirement = Record<string, string[]>;\n\n/** OpenAPI configuration on the server. */\nexport interface OpenAPIConfig {\n /** Path served by the JSON spec (e.g. `/openapi.json`). Default: `/openapi.json`. */\n path?: string;\n /** Path serving the documentation UI. Set to `false` to disable. Default: `/docs`. */\n docsPath?: string | false;\n /** OpenAPI document info. */\n info: OpenAPIInfo;\n /** Optional servers list for the spec. */\n servers?: { url: string; description?: string }[];\n /**\n * Reusable security schemes, keyed by name. The keys are referenced from\n * {@link OpenAPIConfig.security} / per-route `security`.\n *\n * @example\n * ```ts\n * securitySchemes: {\n * bearerAuth: { type: \"http\", scheme: \"bearer\", bearerFormat: \"Firebase JWT\" },\n * }\n * ```\n */\n securitySchemes?: Record<string, SecurityScheme>;\n /**\n * Default security requirement applied to every operation. Each entry maps a\n * scheme name (a key of {@link OpenAPIConfig.securitySchemes}) to its scopes.\n *\n * @example `security: [{ bearerAuth: [] }]`\n */\n security?: SecurityRequirement[];\n /**\n * Hono middleware(s) guarding **only** the docs UI and JSON spec endpoints\n * (not the API routes). Use a raw middleware for a custom flow, or the\n * built-in {@link firebaseBearerAuth} / {@link basicAuth} helpers.\n *\n * @example\n * ```ts\n * import { firebaseBearerAuth } from \"@lpdjs/firestore-repo-service/servers/hono\";\n * openapi: { info, docsAuth: firebaseBearerAuth({ getAuth }) }\n * ```\n *\n * For a full login form + session cookie (like the admin server), pass the\n * {@link DocsAuthExtension} returned by `firebaseDocsAuth({ ... })` instead.\n */\n docsAuth?: MiddlewareHandler | MiddlewareHandler[] | DocsAuthExtension;\n}\n\n/** Options consumed by the {@link HonoServer} constructor. */\nexport interface HonoServerOptions<TEnv extends Env = Env> {\n /**\n * API tag — only routes whose `api` matches this value are mounted.\n * If omitted, every route in the registry is mounted.\n */\n api?: string;\n\n /** Pre-resolved route registry (typically the codegen output). */\n routes: AnyRouteDef[];\n\n /** URL prefix mounted before every route path. Default: `\"\"`. */\n basePath?: string;\n\n /** Hono middlewares applied to every route (after the built-ins). */\n middlewares?: MiddlewareHandler<TEnv>[];\n\n /**\n * Alias for `middlewares` — global middlewares applied to every route.\n * If both are provided, `globalMiddlewares` is appended after `middlewares`.\n */\n globalMiddlewares?: MiddlewareHandler<TEnv>[];\n\n /**\n * If `true`, the server validates the value returned by every handler\n * against the route's `output` schema and rejects mismatches with a 500\n * response. Useful in dev / staging. Default: `false`.\n */\n validateOutput?: boolean;\n\n /** Enable verbose logging of mounted routes at startup. Default: `false`. */\n verbose?: boolean;\n\n /** OpenAPI configuration. Omit to disable. */\n openapi?: OpenAPIConfig;\n\n /** Custom 404 handler. */\n notFound?: (c: Context<TEnv>) => Response | Promise<Response>;\n\n /** Custom error handler. */\n onError?: (err: unknown, c: Context<TEnv>) => Response | Promise<Response>;\n\n /**\n * Cross-cutting interceptor wrapping every handler call.\n * Ideal for response envelopes, business-error mapping, tracing.\n *\n * Pass a bare {@link RouteInterceptor} function, or an\n * {@link InterceptorConfig} (`{ output?, errors?, handler }`) so the\n * generated OpenAPI spec documents the wrapped responses.\n */\n interceptor?: InterceptorOption<TEnv>;\n\n /**\n * Cross-cutting error strategy applied to every uncaught error and injected\n * into every handler / interceptor context. See {@link ErrorHandler}.\n *\n * Typically shared across APIs — pass it once to `createApiRegistry` via\n * `{ services, errorHandler }`; this per-API field overrides it.\n */\n errorHandler?: ErrorHandler<TEnv>;\n\n /**\n * Structured {@link Logger} injected into every handler / interceptor /\n * error-handler context. Extend the package's `BaseLogger` to route to your\n * sink. Typically shared via `createApiRegistry({ services, logger })`; this\n * per-API field overrides it.\n */\n logger?: Logger;\n\n /**\n * Global DI services container (see {@link createServices}).\n *\n * When provided:\n * - a middleware is installed automatically so the built-in `ctx`\n * service resolves to the current request via `AsyncLocalStorage`;\n * - `services` is passed into every handler and the interceptor.\n *\n * The same container instance should be shared across every API of your\n * project — declare it once and pass it to {@link createApiRegistry}.\n */\n services?: AnyServicesContainer;\n}\n","/**\n * Built-in error types thrown by the server pipeline and their default\n * HTTP mapping — shared by the request handler and {@link BaseErrorHandler}.\n */\n\nimport type { ZodError } from \"zod\";\nimport { ValidationError } from \"./types\";\n\n/** Thrown when the request body cannot be read / parsed → HTTP 400. */\nexport class BadRequestError extends Error {\n readonly statusCode = 400 as const;\n constructor(message: string) {\n super(message);\n this.name = \"BadRequestError\";\n }\n}\n\n/** Thrown when a handler's return value fails the `output` schema → HTTP 500. */\nexport class OutputValidationError extends Error {\n readonly statusCode = 500 as const;\n constructor(readonly zodError: ZodError) {\n super(\"Output validation failed\");\n this.name = \"OutputValidationError\";\n }\n}\n\n/** Flatten a `ZodError` into a compact `{ path, code, message }[]`. */\nexport function formatZodIssues(error: ZodError): unknown {\n return error.issues.map((i) => ({\n path: i.path.join(\".\"),\n code: i.code,\n message: i.message,\n }));\n}\n\n/**\n * Default JSON mapping for the package's own errors (`ValidationError`,\n * `BadRequestError`, `OutputValidationError`). Returns `null` for anything\n * else so the caller can decide (rethrow / custom handler).\n */\nexport function defaultErrorResponse(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n c: any,\n err: unknown,\n): Response | null {\n if (err instanceof ValidationError) {\n return c.json(\n {\n success: false,\n error: \"Validation failed\",\n issues: formatZodIssues(err.zodError),\n },\n 400,\n );\n }\n if (err instanceof BadRequestError) {\n return c.json(\n { success: false, error: \"Bad Request\", message: err.message },\n 400,\n );\n }\n if (err instanceof OutputValidationError) {\n return c.json(\n {\n success: false,\n error: \"Output validation failed\",\n issues: formatZodIssues(err.zodError),\n },\n 500,\n );\n }\n return null;\n}\n","/**\n * OpenAPI 3.1 spec generator from {@link RouteDef} entries.\n *\n * Uses `@asteasolutions/zod-to-openapi` directly so users keep importing the\n * vanilla `zod` package (no opinionated `z` re-export required).\n */\n\nimport {\n OpenAPIRegistry,\n OpenApiGeneratorV31,\n extendZodWithOpenApi,\n} from \"@asteasolutions/zod-to-openapi\";\nimport { z } from \"zod\";\nimport type {\n AnyRouteDef,\n HttpMethod,\n InterceptorConfig,\n InterceptorErrorResponse,\n OpenAPIConfig,\n PayloadSource,\n} from \"./types\";\n\n// Patches Zod prototype with `.openapi()` and enables schema → OpenAPI\n// conversion for vanilla zod schemas. Idempotent — safe to call multiple times.\nextendZodWithOpenApi(z);\n\nconst DEFAULT_RESPONSE_DESCRIPTION = \"Successful response\";\nconst DEFAULT_ERROR_DESCRIPTION = \"Error response\";\n\nfunction defaultSource(method: HttpMethod): PayloadSource {\n return method === \"get\" ? \"query\" : \"json\";\n}\n\n/**\n * Resolve the success-envelope schema for a route, honouring an interceptor's\n * static schema or per-route factory. Falls back to the raw `route.output`.\n */\nfunction resolveSuccessSchema(\n routeOutput: z.ZodTypeAny | undefined,\n interceptor: InterceptorConfig | undefined,\n): z.ZodTypeAny | undefined {\n const out = interceptor?.output;\n if (!out) return routeOutput;\n return typeof out === \"function\" ? out(routeOutput) : out;\n}\n\n/** Normalise a declared error response to `{ description, schema? }`. */\nfunction normalizeErrorResponse(\n entry: InterceptorErrorResponse,\n): { description: string; schema?: z.ZodTypeAny } {\n // A Zod schema exposes `safeParse`; a plain config object does not.\n if (typeof (entry as { safeParse?: unknown }).safeParse === \"function\") {\n return { description: DEFAULT_ERROR_DESCRIPTION, schema: entry as z.ZodTypeAny };\n }\n const cfg = entry as { description?: string; schema?: z.ZodTypeAny };\n return { description: cfg.description ?? DEFAULT_ERROR_DESCRIPTION, schema: cfg.schema };\n}\n\n/** Build the OpenAPI document from the mounted route registry. */\nexport function buildOpenApiDocument(\n routes: AnyRouteDef[],\n basePath: string,\n config: OpenAPIConfig,\n interceptor?: InterceptorConfig,\n): Record<string, unknown> {\n const registry = new OpenAPIRegistry();\n\n if (config.securitySchemes) {\n for (const [name, scheme] of Object.entries(config.securitySchemes)) {\n // The registry's runtime accepts any spec-shaped object; cast through\n // `unknown` to satisfy zod-to-openapi's stricter typings.\n registry.registerComponent(\n \"securitySchemes\",\n name,\n scheme as unknown as Parameters<\n typeof registry.registerComponent\n >[2],\n );\n }\n }\n\n for (const route of routes) {\n const method = route.method;\n const source = route.source ?? defaultSource(method);\n const fullPath = joinPath(basePath, route.path ?? \"/\");\n const status = route.status ?? 200;\n\n const requestBody = buildRequestBody(method, source, route.input);\n const requestQuery = buildQueryOrParam(source, route.input, \"query\");\n const requestParams = buildQueryOrParam(source, route.input, \"param\");\n const operationId = makeOperationId(method, fullPath);\n\n // Success response — wrapped by the interceptor envelope when declared.\n const successSchema = resolveSuccessSchema(route.output, interceptor);\n const responses: Record<string, unknown> = {\n [status]: successSchema\n ? {\n description: DEFAULT_RESPONSE_DESCRIPTION,\n content: { \"application/json\": { schema: successSchema } },\n }\n : { description: DEFAULT_RESPONSE_DESCRIPTION },\n };\n\n // Declared error responses (interceptor.errors) applied to every operation.\n if (interceptor?.errors) {\n for (const [code, entry] of Object.entries(interceptor.errors)) {\n const { description, schema } = normalizeErrorResponse(entry);\n responses[code] = schema\n ? { description, content: { \"application/json\": { schema } } }\n : { description };\n }\n }\n\n registry.registerPath({\n method,\n path: convertExpressPathToOpenApi(fullPath),\n operationId,\n summary: route.summary,\n description: route.description,\n tags: route.tags,\n deprecated: route.deprecated,\n security: route.security,\n // Cast: registerPath types narrow query/params to ZodObject — we accept\n // any ZodTypeAny at runtime and let users pass plain objects via z.object.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n request: {\n ...(requestQuery ? { query: requestQuery } : {}),\n ...(requestParams ? { params: requestParams } : {}),\n ...(requestBody ? { body: requestBody } : {}),\n } as any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n responses: responses as any,\n });\n }\n\n const generator = new OpenApiGeneratorV31(registry.definitions);\n const document = generator.generateDocument({\n openapi: \"3.1.0\",\n // OpenAPIInfo is structurally compatible; cast to satisfy the `x-*` index.\n info: config.info as Parameters<\n typeof generator.generateDocument\n >[0][\"info\"],\n servers: config.servers,\n security: config.security,\n });\n return document as unknown as Record<string, unknown>;\n}\n\nfunction buildRequestBody(\n method: HttpMethod,\n source: PayloadSource,\n schema: z.ZodTypeAny | undefined,\n): { content: Record<string, { schema: z.ZodTypeAny }> } | null {\n if (!schema) return null;\n if (method === \"get\") return null;\n if (source === \"json\") {\n return { content: { \"application/json\": { schema } } };\n }\n if (source === \"form\") {\n return {\n content: { \"application/x-www-form-urlencoded\": { schema } },\n };\n }\n return null;\n}\n\nfunction buildQueryOrParam(\n source: PayloadSource,\n schema: z.ZodTypeAny | undefined,\n target: \"query\" | \"param\",\n): z.ZodTypeAny | undefined {\n if (!schema) return undefined;\n if (target === \"query\" && source === \"query\") return schema;\n if (target === \"param\" && source === \"param\") return schema;\n return undefined;\n}\n\n/** Convert `:foo` style express params to `{foo}` OpenAPI placeholders. */\nfunction convertExpressPathToOpenApi(path: string): string {\n return path.replace(/:([A-Za-z0-9_]+)/g, \"{$1}\");\n}\n\nfunction joinPath(base: string, path: string): string {\n const left = base.endsWith(\"/\") ? base.slice(0, -1) : base;\n const right = path.startsWith(\"/\") ? path : `/${path}`;\n const merged = `${left}${right}`;\n return merged === \"\" ? \"/\" : merged;\n}\n\nfunction makeOperationId(method: HttpMethod, path: string): string {\n const cleaned = path\n .replace(/[{}]/g, \"\")\n .replace(/\\/+/g, \"_\")\n .replace(/[^A-Za-z0-9_]/g, \"\")\n .replace(/^_+|_+$/g, \"\");\n return `${method}_${cleaned || \"root\"}`;\n}\n\n/**\n * Render a self-contained Scalar API Reference HTML page that points to the\n * generated spec. Loaded from CDN — no build step required.\n */\nexport function renderDocsHtml(specUrl: string, title: string): string {\n const safeUrl = specUrl.replace(/\"/g, \"&quot;\");\n const safeTitle = title\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\");\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\" />\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\" />\n<title>${safeTitle}</title>\n</head>\n<body>\n<script id=\"api-reference\" data-url=\"${safeUrl}\"></script>\n<script src=\"https://cdn.jsdelivr.net/npm/@scalar/api-reference\"></script>\n</body>\n</html>`;\n}\n","/**\n * Hono-native auth guards for the OpenAPI docs / spec endpoints.\n *\n * These return plain Hono `MiddlewareHandler`s, so they slot into\n * `OpenAPIConfig.docsAuth` (which protects only `/docs` + `/openapi.json`,\n * never the API routes). For a fully custom flow, pass your own middleware\n * instead of these helpers.\n */\n\nimport type { MiddlewareHandler } from \"hono\";\nimport { renderLoginPage } from \"../auth/login-page\";\nimport { parseCookies } from \"../auth/session\";\nimport type {\n DecodedIdTokenLike,\n FirebaseAdminAuthLike,\n} from \"../auth/firebase-auth\";\n\n/** Decoded token shape — kept minimal to avoid a hard firebase-admin import. */\nexport interface DecodedBearerToken {\n uid: string;\n email?: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [claim: string]: any;\n}\n\n/** Minimal Firebase Admin Auth surface used by {@link firebaseBearerAuth}. */\nexport interface FirebaseBearerAuthLike {\n verifyIdToken(\n idToken: string,\n checkRevoked?: boolean,\n ): Promise<DecodedBearerToken>;\n}\n\n/** Options for {@link firebaseBearerAuth}. */\nexport interface FirebaseBearerAuthOptions {\n /**\n * Returns the Firebase Admin Auth instance, e.g. `() => getAuth()`. Called\n * lazily on each request so `initializeApp()` runs first.\n */\n getAuth: () => FirebaseBearerAuthLike;\n /**\n * Authorization policy. Return `false` (or throw) to reject the request,\n * any truthy value to allow. Defaults to allowing any verified token.\n */\n allow?: (token: DecodedBearerToken) => boolean | Promise<boolean>;\n /** Revoke check passed to `verifyIdToken`. Default: `false`. */\n checkRevoked?: boolean;\n /**\n * Context key under which the decoded token is stored (`c.set(key, token)`)\n * for downstream handlers. Default: `\"docsUser\"`.\n */\n contextKey?: string;\n}\n\n/**\n * Guard the docs / spec endpoints with a Firebase ID token (Bearer scheme).\n *\n * @example\n * ```ts\n * import { getAuth } from \"firebase-admin/auth\";\n * import { firebaseBearerAuth } from \"@lpdjs/firestore-repo-service/servers/hono\";\n *\n * openapi: {\n * info,\n * docsAuth: firebaseBearerAuth({\n * getAuth: () => getAuth(),\n * allow: (t) => t.admin === true,\n * }),\n * }\n * ```\n */\nexport function firebaseBearerAuth(\n options: FirebaseBearerAuthOptions,\n): MiddlewareHandler {\n const {\n getAuth,\n allow,\n checkRevoked = false,\n contextKey = \"docsUser\",\n } = options;\n\n return async (c, next) => {\n const header = c.req.header(\"authorization\") ?? c.req.header(\"Authorization\");\n const match = header?.match(/^Bearer\\s+(.+)$/i);\n if (!match) {\n return c.json({ error: \"Unauthorized\" }, 401, {\n \"WWW-Authenticate\": \"Bearer\",\n });\n }\n\n let decoded: DecodedBearerToken;\n try {\n decoded = await getAuth().verifyIdToken(match[1]!, checkRevoked);\n } catch {\n return c.json({ error: \"Unauthorized\" }, 401, {\n \"WWW-Authenticate\": \"Bearer\",\n });\n }\n\n if (allow) {\n let permitted = false;\n try {\n permitted = await allow(decoded);\n } catch {\n permitted = false;\n }\n if (!permitted) return c.json({ error: \"Forbidden\" }, 403);\n }\n\n c.set(contextKey, decoded);\n return next();\n };\n}\n\n/** Options for {@link basicAuth}. */\nexport interface BasicAuthOptions {\n username: string;\n password: string;\n /** Realm advertised in the `WWW-Authenticate` header. Default: `\"Docs\"`. */\n realm?: string;\n}\n\n/**\n * Guard the docs / spec endpoints with HTTP Basic Auth.\n *\n * @example\n * ```ts\n * openapi: { info, docsAuth: basicAuth({ username: \"admin\", password: \"secret\" }) }\n * ```\n */\nexport function basicAuth(options: BasicAuthOptions): MiddlewareHandler {\n const { username, password, realm = \"Docs\" } = options;\n const expected = `Basic ${btoa(`${username}:${password}`)}`;\n\n return async (c, next) => {\n const header =\n c.req.header(\"authorization\") ?? c.req.header(\"Authorization\") ?? \"\";\n if (!timingSafeEqual(header, expected)) {\n return c.text(\"Unauthorized\", 401, {\n \"WWW-Authenticate\": `Basic realm=\"${realm}\"`,\n });\n }\n return next();\n };\n}\n\n/** Constant-time string comparison to avoid leaking length/contents via timing. */\nfunction timingSafeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);\n return diff === 0;\n}\n\n// ===========================================================================\n// Firebase login-form auth (session cookie) — mirrors the admin server flow\n// ===========================================================================\n\n/** A bare auxiliary route name (relative to the docs directory). */\nexport interface DocsAuthRoute {\n method: \"GET\" | \"POST\";\n /** Bare path segment relative to the docs directory, e.g. `\"__login\"`. */\n name: string;\n handler: MiddlewareHandler;\n}\n\n/**\n * Richer `docsAuth` value (vs. a bare `MiddlewareHandler`): a guard middleware\n * **plus** auxiliary routes (login page, session exchange, logout) that the\n * {@link HonoServer} mounts next to the docs/spec endpoints. Mirrors the admin\n * server's `AuthExtension`. Produced by {@link firebaseDocsAuth}.\n */\nexport interface DocsAuthExtension {\n readonly __docsAuthExtension: true;\n /** Guard applied to the docs UI + JSON spec endpoints. */\n middleware: MiddlewareHandler;\n /** Auxiliary routes mounted (unguarded) in the docs directory. */\n routes: DocsAuthRoute[];\n /** Bare login route name, used to redirect unauthenticated browsers. */\n loginName: string;\n}\n\n/** Type guard distinguishing a {@link DocsAuthExtension} from a raw middleware. */\nexport function isDocsAuthExtension(value: unknown): value is DocsAuthExtension {\n return (\n typeof value === \"object\" &&\n value !== null &&\n (value as { __docsAuthExtension?: unknown }).__docsAuthExtension === true\n );\n}\n\n/** Options for {@link firebaseDocsAuth}. */\nexport interface FirebaseDocsAuthOptions {\n /**\n * Returns the Firebase Admin Auth instance, e.g. `() => getAuth()`. Called\n * lazily on each request so `initializeApp()` runs first. Must expose\n * `verifyIdToken`, `verifySessionCookie`, `createSessionCookie`,\n * `revokeRefreshTokens`.\n */\n getAuth: () => FirebaseAdminAuthLike;\n /** Firebase Web API key — required by the JS SDK on the login page. */\n apiKey: string;\n /** Firebase Auth domain (e.g. `my-project.firebaseapp.com`). */\n authDomain: string;\n /**\n * Transport mode. `\"cookie\"` (default) gates the docs behind the bundled\n * login form + a server-side session cookie. `\"both\"` additionally accepts a\n * `Bearer` ID token (handy to embed the docs in an authenticated iframe).\n */\n mode?: \"cookie\" | \"both\";\n /**\n * Authorization policy. Return `false` (or throw) to reject, any truthy value\n * to allow. Defaults to allowing any verified user. Receives the decoded\n * ID-token / session-cookie claims.\n */\n allow?: (token: DecodedIdTokenLike) => boolean | Promise<boolean>;\n /** Providers shown on the login page. Default: `[\"password\", \"google\"]`. */\n providers?: (\"password\" | \"google\")[];\n /** Login page title. Default: `\"Docs sign-in\"`. */\n title?: string;\n /** Session cookie name. Default: `\"__docs_session\"`. */\n cookieName?: string;\n /** Session cookie TTL in days. Default: `5` (Firebase max is 14). */\n sessionTtlDays?: number;\n /** Cookie `Secure` flag. Default: `true` (set `false` only for local HTTP). */\n secureCookie?: boolean;\n /** Cookie `SameSite`. Default: `\"Lax\"`. */\n sameSite?: \"Strict\" | \"Lax\" | \"None\";\n /**\n * Context key under which the decoded token is stored (`c.set(key, token)`)\n * for downstream handlers. Default: `\"docsUser\"`.\n */\n contextKey?: string;\n /**\n * Behaviour when authentication fails. `\"redirect\"` (default) sends browser\n * `GET`s to the login page; `\"401\"` always returns a JSON 401.\n */\n onUnauthenticated?: \"redirect\" | \"401\";\n /**\n * Firebase Auth emulator host (e.g. `127.0.0.1:9099`). When set, the login\n * page's client SDK targets the emulator via `connectAuthEmulator`, matching\n * the Admin SDK (which already routes to the emulator when\n * `FIREBASE_AUTH_EMULATOR_HOST` is set). Defaults to that env var; pass `\"\"`\n * to force it off.\n */\n authEmulatorHost?: string;\n}\n\nconst LOGIN_NAME = \"__login\";\nconst SESSION_NAME = \"__session\";\nconst LOGOUT_NAME = \"__logout\";\n\n/** Last path segment, e.g. `/v1/docs` → `docs`. Empty string for `/`. */\nfunction lastSegment(path: string): string {\n const segs = path.split(\"?\")[0]!.split(\"/\").filter(Boolean);\n return segs[segs.length - 1] ?? \"\";\n}\n\n/** Build a `Set-Cookie` header value (HttpOnly, path-scoped). */\nfunction buildSetCookie(\n name: string,\n value: string,\n opts: {\n maxAgeSeconds: number;\n secure: boolean;\n sameSite: \"Strict\" | \"Lax\" | \"None\";\n },\n): string {\n const segments = [\n `${name}=${value}`,\n \"Path=/\",\n `Max-Age=${opts.maxAgeSeconds}`,\n \"HttpOnly\",\n `SameSite=${opts.sameSite}`,\n ];\n if (opts.secure) segments.push(\"Secure\");\n return segments.join(\"; \");\n}\n\n/** Restrict a `next` target to a simple same-origin relative token. */\nfunction sanitizeNext(raw: string | undefined, fallback: string): string {\n if (!raw) return fallback;\n if (raw.startsWith(\"/\") || raw.includes(\"://\") || raw.includes(\"\\\\\")) {\n return fallback;\n }\n return raw;\n}\n\n/**\n * Guard the docs / spec endpoints with a Firebase **login form + session\n * cookie**, the same flow as the admin server — instead of forcing callers to\n * craft a `Bearer` token by hand.\n *\n * Returns a {@link DocsAuthExtension}: pass it straight to\n * `OpenAPIConfig.docsAuth`. The {@link HonoServer} mounts the bundled\n * `__login` / `__session` / `__logout` routes next to the docs and applies the\n * guard. Unauthenticated browsers are redirected to the login page; once signed\n * in, an HttpOnly session cookie keeps them authenticated.\n *\n * @example\n * ```ts\n * import { getAuth } from \"firebase-admin/auth\";\n * import { firebaseDocsAuth } from \"@lpdjs/firestore-repo-service/servers/hono\";\n *\n * openapi: {\n * info,\n * docsAuth: firebaseDocsAuth({\n * getAuth: () => getAuth(),\n * apiKey: process.env.FIREBASE_API_KEY!,\n * authDomain: process.env.FIREBASE_AUTH_DOMAIN!,\n * allow: (t) => t.admin === true, // optional policy\n * }),\n * }\n * ```\n */\nexport function firebaseDocsAuth(\n options: FirebaseDocsAuthOptions,\n): DocsAuthExtension {\n const {\n getAuth,\n apiKey,\n authDomain,\n mode = \"cookie\",\n allow,\n providers = [\"password\", \"google\"],\n title = \"Docs sign-in\",\n cookieName = \"__docs_session\",\n sessionTtlDays = 5,\n secureCookie = true,\n sameSite = \"Lax\",\n contextKey = \"docsUser\",\n onUnauthenticated = \"redirect\",\n authEmulatorHost = process.env[\"FIREBASE_AUTH_EMULATOR_HOST\"],\n } = options;\n\n async function passesAllow(token: DecodedIdTokenLike): Promise<boolean> {\n if (!allow) return true;\n try {\n return Boolean(await allow(token));\n } catch {\n return false;\n }\n }\n\n // ── Login page (GET __login) ──────────────────────────────────────────────\n const loginHandler: MiddlewareHandler = async (c) => {\n // Validate lazily (at request time) so importing this module during the\n // Firebase CLI analysis / emulator load doesn't throw before env vars are\n // injected — same approach as the admin `firebaseAuth`.\n if (!apiKey || !authDomain) {\n throw new Error(\n \"[firebaseDocsAuth] `apiKey` and `authDomain` are required for the login \" +\n \"page. Find both in the Firebase Console → Project Settings → General → \" +\n \"Web app config.\",\n );\n }\n const next = sanitizeNext(c.req.query(\"next\"), \"docs\");\n const error = c.req.query(\"error\") ?? null;\n const html = renderLoginPage({\n title,\n providers,\n apiKey,\n authDomain,\n // Relative to the login page URL (resolved client-side), so it works\n // behind any Cloud Functions / reverse-proxy prefix.\n sessionPath: SESSION_NAME,\n next,\n error,\n authEmulatorHost,\n });\n return c.html(html, 200, { \"Cache-Control\": \"no-store\" });\n };\n\n // ── Session exchange (POST __session) ─────────────────────────────────────\n const sessionHandler: MiddlewareHandler = async (c) => {\n let idToken = \"\";\n try {\n const body = (await c.req.json()) as { idToken?: unknown };\n idToken = typeof body.idToken === \"string\" ? body.idToken : \"\";\n } catch {\n idToken = \"\";\n }\n if (!idToken) {\n return c.json({ success: false, error: \"Missing idToken\" }, 400);\n }\n\n const expiresInMs = sessionTtlDays * 24 * 60 * 60 * 1000;\n try {\n const auth = getAuth();\n const decoded = await auth.verifyIdToken(idToken, true);\n if (!(await passesAllow(decoded))) {\n return c.json({ success: false, error: \"Forbidden\" }, 403);\n }\n // Reject stale sign-ins (Google guidance: require a recent auth, < 5 min).\n const authTimeRaw = (decoded as { auth_time?: number }).auth_time;\n const authTime =\n typeof authTimeRaw === \"number\" ? authTimeRaw * 1000 : Date.now();\n if (Date.now() - authTime > 5 * 60 * 1000) {\n return c.json(\n { success: false, error: \"Recent sign-in required\" },\n 401,\n );\n }\n const sessionCookie = await auth.createSessionCookie(idToken, {\n expiresIn: expiresInMs,\n });\n const cookie = buildSetCookie(\n cookieName,\n encodeURIComponent(sessionCookie),\n {\n maxAgeSeconds: Math.floor(expiresInMs / 1000),\n secure: secureCookie,\n sameSite,\n },\n );\n c.header(\"Set-Cookie\", cookie);\n return c.json({ success: true });\n } catch (err) {\n const message = err instanceof Error ? err.message : \"Invalid idToken\";\n return c.json({ success: false, error: message }, 401);\n }\n };\n\n // ── Logout (POST __logout) ────────────────────────────────────────────────\n const logoutHandler: MiddlewareHandler = async (c) => {\n const cookies = parseCookies(c.req.header(\"cookie\") ?? \"\");\n const session = cookies[cookieName];\n if (session) {\n try {\n const auth = getAuth();\n const decoded = await auth.verifySessionCookie(session, false);\n await auth.revokeRefreshTokens(decoded.uid);\n } catch {\n /* best-effort */\n }\n }\n c.header(\n \"Set-Cookie\",\n buildSetCookie(cookieName, \"\", {\n maxAgeSeconds: 0,\n secure: secureCookie,\n sameSite,\n }),\n );\n return c.json({ success: true });\n };\n\n // ── Guard middleware (docs + spec) ────────────────────────────────────────\n const middleware: MiddlewareHandler = async (c, next) => {\n const auth = getAuth();\n\n // mode \"both\": accept a Bearer ID token first (e.g. iframe embedding).\n if (mode === \"both\") {\n const header =\n c.req.header(\"authorization\") ?? c.req.header(\"Authorization\");\n const match = header?.match(/^Bearer\\s+(.+)$/i);\n if (match) {\n try {\n const decoded = await auth.verifyIdToken(match[1]!, false);\n if (await passesAllow(decoded)) {\n c.set(contextKey, decoded);\n return next();\n }\n } catch {\n /* fall through to cookie / unauthenticated */\n }\n }\n }\n\n // Session cookie.\n const cookies = parseCookies(c.req.header(\"cookie\") ?? \"\");\n const session = cookies[cookieName];\n if (session) {\n try {\n const decoded = await auth.verifySessionCookie(session, false);\n if (await passesAllow(decoded)) {\n c.set(contextKey, decoded);\n return next();\n }\n } catch {\n /* unauthenticated */\n }\n }\n\n // Unauthenticated.\n const accept = c.req.header(\"accept\") ?? \"\";\n const isBrowserGet =\n c.req.method === \"GET\" && accept.includes(\"text/html\");\n if (onUnauthenticated === \"redirect\" && isBrowserGet) {\n const target = encodeURIComponent(lastSegment(c.req.path) || \"docs\");\n // Relative to the requested page (login route is a sibling), so the\n // external prefix is preserved by the browser.\n return c.redirect(`${LOGIN_NAME}?next=${target}`, 302);\n }\n return c.json({ error: \"Unauthorized\" }, 401);\n };\n\n return {\n __docsAuthExtension: true,\n middleware,\n loginName: LOGIN_NAME,\n routes: [\n { method: \"GET\", name: LOGIN_NAME, handler: loginHandler },\n { method: \"POST\", name: SESSION_NAME, handler: sessionHandler },\n { method: \"POST\", name: LOGOUT_NAME, handler: logoutHandler },\n ],\n };\n}\n","/**\n * Global DI services container for the Hono server.\n *\n * Lets you declare all your singletons (repositories, SDK clients, useCases,\n * loggers…) **once**, then inject them anywhere — routes, interceptors,\n * cron jobs, Firestore triggers, tests.\n *\n * ## How it works\n *\n * - Each service is constructed **lazily** on first access and cached for\n * the process lifetime (perfect for Cloud Functions cold-start).\n * - Providers may be **classes** (auto-injected: `new Class(services)`)\n * or **factories** (`(services) => instance`). Mix both freely.\n * - Inter-service dependencies are inferred either by destructuring the\n * factory argument (`postRepo: ({ db }) => new PostRepo(db)`) or by\n * reading `this.services.*` inside a class.\n * - A built-in `ctx` service exposes the **current request's** Hono\n * `Context` via `AsyncLocalStorage`. UseCases access\n * `this.services.ctx.c.get(\"user\")` without any plumbing.\n * - Cycles are detected at first access with a clear error.\n *\n * @example\n * ```ts\n * // src/services.ts — infrastructure singletons only (no useCases here)\n * import { createServices } from \"@lpdjs/firestore-repo-service/servers/hono\";\n * import { PostRepo } from \"./domains/posts/PostRepo.js\";\n * import { Mailer } from \"./services/Mailer.js\";\n *\n * export const services = createServices({\n * postRepo: PostRepo, // class form (auto-injected)\n * mailer: ({ ctx }) => new Mailer(ctx), // factory form\n * });\n *\n * export type Services = typeof services;\n * ```\n *\n * @example\n * ```ts\n * // src/apis.ts\n * import { services } from \"./services.js\";\n * export const apis = createApiRegistry(\n * { v1: { basePath: \"/v1\", ... } },\n * { services },\n * );\n * ```\n *\n * @example\n * ```ts\n * // Inside a useCase — extends the UseCase base, owns its Zod schemas\n * import { z } from \"zod\";\n * import { UseCase } from \"@lpdjs/firestore-repo-service/servers/hono\";\n * import type { Services } from \"../../services.js\";\n *\n * const input = z.object({ title: z.string() });\n * const output = z.object({ id: z.string() });\n *\n * export class CreatePostUseCase extends UseCase<typeof input, typeof output, Services> {\n * static readonly input = input;\n * static readonly output = output;\n *\n * async execute(payload: z.infer<typeof input>): Promise<z.infer<typeof output>> {\n * const user = this.services.ctx.c.get(\"user\");\n * return this.services.postRepo.create({ ...payload, authorId: user.id });\n * }\n * }\n * ```\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { Context, Env, MiddlewareHandler } from \"hono\";\n\n// ---------------------------------------------------------------------------\n// Request-scoped context (AsyncLocalStorage backed)\n// ---------------------------------------------------------------------------\n\n/**\n * Per-request context exposed to every service / useCase.\n * The instance is a **stable singleton** but its `c` getter resolves to the\n * Hono `Context` of the currently-handled request via `AsyncLocalStorage`.\n *\n * Outside of a request (cron, manual scripts, tests), wrap your call in\n * {@link withRequestContext} to supply a context, otherwise accessing `c`\n * will throw.\n */\nexport interface RequestContext<TEnv extends Env = Env> {\n /** Hono `Context` of the currently-handled request. */\n readonly c: Context<TEnv>;\n /**\n * Same as `c` but returns `undefined` instead of throwing when called\n * outside a request scope. Useful for opportunistic logging.\n */\n readonly maybeC: Context<TEnv> | undefined;\n}\n\ninterface RequestStore {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n c: Context<any>;\n}\n\nconst als = new AsyncLocalStorage<RequestStore>();\n\nconst requestContextSingleton: RequestContext = Object.freeze({\n get c() {\n const store = als.getStore();\n if (!store) {\n throw new Error(\n \"[services] requestContext.c was accessed outside of a request. \" +\n \"Wrap non-HTTP code paths (cron, triggers, scripts, tests) in \" +\n \"`withRequestContext({ c }, () => ...)` to supply a Hono Context.\",\n );\n }\n return store.c;\n },\n get maybeC() {\n return als.getStore()?.c;\n },\n});\n\n/**\n * Hono middleware installed automatically by `HonoServer` when a `services`\n * container is provided. Populates the AsyncLocalStorage so the built-in\n * `ctx` service resolves to the current request.\n *\n * Exported for advanced cases (custom server / non-Hono adapter); you do not\n * need to call this manually in the standard flow.\n */\nexport function createRequestContextMiddleware(): MiddlewareHandler {\n return async (c, next) => {\n await als.run({ c }, async () => {\n await next();\n });\n };\n}\n\n/**\n * Run `fn` with a synthetic request context — required when invoking\n * services outside an HTTP handler (cron jobs, Firestore triggers, scripts,\n * unit tests). Inside `fn`, `services.ctx.c` resolves to the supplied `c`.\n *\n * @example\n * ```ts\n * // A cron that reuses a useCase\n * export const dailyTask = onSchedule(\"every 24 hours\", async () => {\n * await withRequestContext({ c: fakeContext() }, async () => {\n * await services.createPostUseCase.execute({ ... });\n * });\n * });\n * ```\n */\nexport function withRequestContext<T>(\n ctx: { c: Context },\n fn: () => Promise<T> | T,\n): Promise<T> {\n return als.run({ c: ctx.c }, async () => fn());\n}\n\n// ---------------------------------------------------------------------------\n// createServices\n// ---------------------------------------------------------------------------\n\n/**\n * Reserved service name — the built-in request context. User factories\n * cannot override it.\n */\nconst CTX_KEY = \"ctx\" as const;\n\n/**\n * Helper that derives the public services type from an output map.\n * Each entry in `TMap` is the instance type returned by its provider.\n * The built-in `ctx` is always present.\n */\nexport type ServicesOf<TMap> = { readonly ctx: RequestContext } & {\n readonly [K in keyof TMap]: TMap[K];\n};\n\n/**\n * A single provider entry — either a factory `(deps) => R` or a class\n * `new (deps) => R`. `deps` is the *complete* services proxy\n * (siblings + built-in `ctx`).\n */\nexport type ServiceProvider<TMap, R> =\n | ((deps: ServicesOf<TMap>) => R)\n | (new (deps: ServicesOf<TMap>) => R);\n\n/**\n * A provider map — each value is either a factory or a class constructor.\n */\nexport type ServiceProviderMap<TMap> = {\n [K in keyof TMap]: K extends typeof CTX_KEY\n ? never\n : ServiceProvider<TMap, TMap[K]>;\n};\n\n/**\n * Extract the instance/return type from a single provider value.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ProviderReturn<P> = P extends new (...args: any) => infer R\n ? R\n : // eslint-disable-next-line @typescript-eslint/no-explicit-any\n P extends (...args: any) => infer R\n ? R\n : never;\n\n/**\n * Compute the output service map from an inferred provider map.\n */\nexport type MapFromProviders<P> = {\n [K in keyof P]: ProviderReturn<P[K]>;\n};\n\n/**\n * Container returned by {@link createServices}. Behaves like a plain object\n * keyed by service name — accessing a key triggers lazy instantiation.\n * Use `type Services = typeof services` to derive the public type.\n */\nexport type ServicesContainer<TMap> = TMap;\n\n/**\n * Build a lazy singleton DI container.\n *\n * @param providers A map of service name → factory function **or** class\n * constructor. The single argument (factory deps / first\n * ctor param) receives a deps proxy typed as the full\n * services map (siblings + the built-in `ctx`).\n *\n * @example Factory form\n * ```ts\n * db: () => getFirestore(),\n * postRepo: ({ db }) => new PostRepo(db),\n * ```\n *\n * @example Class form (zero-boilerplate auto-injection)\n * ```ts\n * class RepositoryService {\n * constructor(private readonly services: Services) {}\n * get posts() { return this.services.db.posts; }\n * }\n *\n * createServices({\n * db: () => getFirestore(), // ← factory\n * repository: RepositoryService, // ← bare class (deps auto-injected)\n * });\n * ```\n */\nexport function createServices<\n P extends Record<\n string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ((deps: any) => unknown) | (new (deps: any) => unknown)\n >,\n>(providers: P): ServicesContainer<ServicesOf<MapFromProviders<P>>> {\n const cache = new Map<string, unknown>();\n const inProgress: string[] = [];\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const proxy = new Proxy({} as any, {\n get(_target, prop) {\n if (typeof prop !== \"string\") return undefined;\n if (prop === CTX_KEY) return requestContextSingleton;\n\n if (cache.has(prop)) return cache.get(prop);\n\n const provider = (providers as Record<string, unknown>)[prop];\n if (typeof provider !== \"function\") {\n throw new Error(\n `[services] unknown service \"${prop}\". Registered: ${\n [CTX_KEY, ...Object.keys(providers)].join(\", \")\n }`,\n );\n }\n\n if (inProgress.includes(prop)) {\n throw new Error(\n `[services] circular dependency detected: ${[\n ...inProgress,\n prop,\n ].join(\" → \")}`,\n );\n }\n\n inProgress.push(prop);\n try {\n const value = isClassConstructor(provider)\n ? new (provider as new (deps: unknown) => unknown)(proxy)\n : (provider as (deps: unknown) => unknown)(proxy);\n cache.set(prop, value);\n return value;\n } finally {\n inProgress.pop();\n }\n },\n has(_target, prop) {\n if (typeof prop !== \"string\") return false;\n return prop === CTX_KEY || prop in providers;\n },\n ownKeys() {\n return [CTX_KEY, ...Object.keys(providers)];\n },\n getOwnPropertyDescriptor(_t, prop) {\n if (typeof prop !== \"string\") return undefined;\n if (prop === CTX_KEY || prop in providers) {\n return { enumerable: true, configurable: true };\n }\n return undefined;\n },\n });\n\n return proxy as ServicesContainer<ServicesOf<MapFromProviders<P>>>;\n}\n\n/**\n * Detect whether a function value should be invoked with `new` (class\n * constructor) or called directly (plain factory). Relies on the `class`\n * keyword being preserved in `Function.prototype.toString`, which is the\n * case for TypeScript / esbuild output targeting modern JS (ES2015+).\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction isClassConstructor(fn: Function): boolean {\n return /^class[\\s{]/.test(Function.prototype.toString.call(fn));\n}\n\n/**\n * Opaque container type used by registry / server signatures that don't\n * need to know the concrete services map.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyServicesContainer = ServicesContainer<Record<string, any>>;\n","/**\n * `HonoServer` — high-performance, fully-typed file-based API server for\n * Firebase Cloud Functions v2 (`onRequest`).\n *\n * Designed to:\n * - rely on **prebuild codegen** (`hono:gen` CLI) for static imports → zero\n * runtime filesystem scan, optimal cold-start;\n * - expose handlers receiving a Zod-parsed payload typed end-to-end;\n * - generate the OpenAPI 3.1 spec automatically from the same Zod schemas;\n * - bridge Hono's Web Fetch API to Cloud Functions' Express-style\n * `(req, res)` via `@hono/node-server`'s request listener.\n */\n\nimport { Hono } from \"hono\";\nimport { getRequestListener } from \"@hono/node-server\";\nimport { z } from \"zod\";\nimport type { Env, MiddlewareHandler } from \"hono\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport type { HttpsOptions } from \"firebase-functions/v2/https\";\n\nimport type {\n AnyRouteDef,\n ErrorHandler,\n HonoServerOptions,\n HttpMethod,\n InterceptorConfig,\n InterceptorOption,\n Logger,\n PayloadSource,\n RouteInterceptor,\n} from \"./types\";\nimport {\n BadRequestError,\n defaultErrorResponse,\n OutputValidationError,\n} from \"./errors\";\nimport { ValidationError } from \"./types\";\nimport { buildOpenApiDocument, renderDocsHtml } from \"./openapi\";\nimport { isDocsAuthExtension } from \"./docs-auth\";\nimport {\n createRequestContextMiddleware,\n type AnyServicesContainer,\n} from \"./services\";\n\n/**\n * Minimal shape of `firebase-functions/v2/https` `onRequest` so the package\n * stays decoupled from a specific firebase-functions version. We import the\n * real type only when users pass `onRequest` to `toFunction(...)`.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype OnRequestFn = (...args: any[]) => any;\n\n/**\n * Sentinel passed to handlers / interceptors when the server is started\n * without a `services` container. Frozen so accidental writes throw.\n */\nconst EMPTY_SERVICES: AnyServicesContainer = Object.freeze(\n {},\n) as unknown as AnyServicesContainer;\n\nexport class HonoServer<TEnv extends Env = Env> {\n private readonly app: Hono<TEnv>;\n private readonly options: HonoServerOptions<TEnv>;\n private readonly mountedRoutes: AnyRouteDef[];\n private cachedSpec: Record<string, unknown> | null = null;\n\n constructor(options: HonoServerOptions<TEnv>) {\n this.options = options;\n this.app = new Hono<TEnv>();\n this.mountedRoutes = filterRoutes(options.routes, options.api);\n\n // Install the request-context middleware FIRST so the AsyncLocalStorage\n // is populated before any user middleware / handler runs.\n if (options.services) {\n this.app.use(\"*\", createRequestContextMiddleware());\n }\n\n const globalMws = [\n ...(options.middlewares ?? []),\n ...(options.globalMiddlewares ?? []),\n ];\n for (const mw of globalMws) this.app.use(\"*\", mw);\n\n this.mountRoutes();\n this.mountOpenApi();\n\n if (options.notFound) this.app.notFound(options.notFound);\n if (options.onError) this.app.onError(options.onError);\n }\n\n /** Underlying Hono instance — useful for advanced composition / tests. */\n get hono(): Hono<TEnv> {\n return this.app;\n }\n\n /** Raw `(req, res)` handler suitable for `onRequest()` / `http.createServer`. */\n get nodeHandler(): (req: IncomingMessage, res: ServerResponse) => void {\n return getRequestListener(this.app.fetch, {\n overrideGlobalObjects: false,\n });\n }\n\n /**\n * Wrap the server as a Cloud Functions v2 HTTP function.\n *\n * @param onRequest The `onRequest` factory imported from\n * `firebase-functions/v2/https` (or `firebase-functions/https`).\n * @param httpsOptions Options forwarded as the first argument to\n * `onRequest()` (region, memory, invoker, etc.).\n */\n toFunction(onRequest: OnRequestFn, httpsOptions?: HttpsOptions) {\n const handler = this.nodeHandler;\n if (httpsOptions) {\n return onRequest(httpsOptions, handler);\n }\n return onRequest(handler);\n }\n\n /** Generate (and cache) the OpenAPI 3.1 spec for the mounted routes. */\n buildOpenApiSpec(): Record<string, unknown> {\n if (this.cachedSpec) return this.cachedSpec;\n if (!this.options.openapi) {\n throw new Error(\"[HonoServer] openapi config not set\");\n }\n this.cachedSpec = buildOpenApiDocument(\n this.mountedRoutes,\n this.options.basePath ?? \"\",\n this.options.openapi,\n interceptorConfig(this.options.interceptor as InterceptorOption | undefined),\n );\n return this.cachedSpec;\n }\n\n // ── Internals ─────────────────────────────────────────────────────────\n\n private mountRoutes(): void {\n const basePath = this.options.basePath ?? \"\";\n const validateOutput = this.options.validateOutput ?? false;\n const verbose = this.options.verbose ?? false;\n\n for (const route of this.mountedRoutes) {\n if (!route.path) {\n throw new Error(\n `[HonoServer] route \"${route.method.toUpperCase()} (no path)\" — missing \\`path\\`. ` +\n \"Run the codegen so the path is derived from the file location, or set it explicitly.\",\n );\n }\n\n const fullPath = joinPath(basePath, route.path);\n const middlewares = route.middlewares ?? [];\n const source: PayloadSource =\n route.source ?? (route.method === \"get\" ? \"query\" : \"json\");\n\n const handler = makeRouteHandler(\n route,\n source,\n validateOutput,\n interceptorFn(this.options.interceptor as InterceptorOption | undefined),\n this.options.services,\n this.options.errorHandler as ErrorHandler | undefined,\n this.options.logger as Logger | undefined,\n );\n const httpMethod = route.method.toUpperCase() as\n | \"GET\"\n | \"POST\"\n | \"PUT\"\n | \"PATCH\"\n | \"DELETE\";\n // `app.on(method, path, handlers[])` accepts a variadic array of\n // handlers/middlewares — the typed `.get/.post/...` overloads don't\n // accept a spread of generic `MiddlewareHandler[]`.\n this.app.on(\n httpMethod,\n [fullPath],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...([...middlewares, handler] as any[]),\n );\n\n if (verbose) {\n // eslint-disable-next-line no-console\n console.log(\n `[HonoServer] ${route.method.toUpperCase().padEnd(6)} ${fullPath}`,\n );\n }\n }\n }\n\n private mountOpenApi(): void {\n const cfg = this.options.openapi;\n if (!cfg) return;\n const specPath = cfg.path ?? \"/openapi.json\";\n const docsPath = cfg.docsPath === undefined ? \"/docs\" : cfg.docsPath;\n const fullSpecPath = joinPath(this.options.basePath ?? \"\", specPath);\n const fullDocsPath =\n docsPath === false ? null : joinPath(this.options.basePath ?? \"\", docsPath);\n\n // Auth guards applied ONLY to the spec + docs endpoints (not API routes).\n // A DocsAuthExtension (e.g. firebaseDocsAuth) also contributes auxiliary\n // routes (login page / session / logout) mounted next to the docs.\n let guards: MiddlewareHandler[];\n if (isDocsAuthExtension(cfg.docsAuth)) {\n const ext = cfg.docsAuth;\n guards = [ext.middleware];\n // Mount the aux routes (unguarded) as siblings of the docs/spec page so\n // bare-name relative links/redirects stay correct behind any prefix.\n const authDir = dirOf(fullDocsPath ?? fullSpecPath);\n for (const route of ext.routes) {\n this.app.on(\n route.method,\n [joinPath(authDir, route.name)],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n route.handler as any,\n );\n }\n } else {\n guards = cfg.docsAuth\n ? Array.isArray(cfg.docsAuth)\n ? cfg.docsAuth\n : [cfg.docsAuth]\n : [];\n }\n\n this.app.on(\n \"GET\",\n [fullSpecPath],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...([...guards, (c: any) => c.json(this.buildOpenApiSpec())] as any[]),\n );\n\n if (fullDocsPath) {\n // Resolve the spec URL relative to the docs page so it works whether the\n // server is mounted at `/`, behind a Firebase Functions prefix\n // (`/<project>/<region>/<funcName>/...`), or behind any reverse proxy.\n const relativeSpecUrl = relativeUrlFromTo(fullDocsPath, fullSpecPath);\n this.app.on(\n \"GET\",\n [fullDocsPath],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...([\n ...guards,\n (c: any) => c.html(renderDocsHtml(relativeSpecUrl, cfg.info.title)),\n ] as any[]),\n );\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** Type guard distinguishing a structured interceptor from a bare function. */\nfunction isInterceptorConfig(\n i: InterceptorOption | undefined,\n): i is InterceptorConfig {\n return typeof i === \"object\" && i !== null && typeof i.handler === \"function\";\n}\n\n/** Extract the runtime interceptor function from either form. */\nfunction interceptorFn(\n i: InterceptorOption | undefined,\n): RouteInterceptor | undefined {\n if (!i) return undefined;\n return isInterceptorConfig(i) ? i.handler : i;\n}\n\n/** Extract the OpenAPI metadata (output/errors) from the structured form. */\nfunction interceptorConfig(\n i: InterceptorOption | undefined,\n): InterceptorConfig | undefined {\n return isInterceptorConfig(i) ? i : undefined;\n}\n\nfunction filterRoutes(\n routes: AnyRouteDef[],\n api: string | undefined,\n): AnyRouteDef[] {\n if (!api) return routes.slice();\n return routes.filter((r) =>\n Array.isArray(r.api) ? r.api.includes(api) : r.api === api,\n );\n}\n\nfunction joinPath(base: string, path: string): string {\n const left = base.endsWith(\"/\") ? base.slice(0, -1) : base;\n const right = path.startsWith(\"/\") ? path : `/${path}`;\n const merged = `${left}${right}`;\n return merged === \"\" ? \"/\" : merged;\n}\n\n/** Directory of an absolute pathname, e.g. `/v1/docs` → `/v1`, `/docs` → ``. */\nfunction dirOf(path: string): string {\n const idx = path.lastIndexOf(\"/\");\n return idx <= 0 ? \"\" : path.slice(0, idx);\n}\n\n/**\n * Compute a URL relative to `from` that points to `to`, both being absolute\n * pathnames (e.g. `/v1/docs` → `/v1/openapi.json` becomes `openapi.json`).\n * Lets the OpenAPI UI fetch the spec without knowing the upstream prefix\n * added by Firebase Functions / reverse proxies.\n */\nfunction relativeUrlFromTo(from: string, to: string): string {\n const fromSegs = from.split(\"/\").filter(Boolean);\n const toSegs = to.split(\"/\").filter(Boolean);\n // Drop the docs page filename so we resolve relative to its directory.\n fromSegs.pop();\n let common = 0;\n while (\n common < fromSegs.length &&\n common < toSegs.length &&\n fromSegs[common] === toSegs[common]\n ) {\n common++;\n }\n const ups = fromSegs.length - common;\n const rel = [\n ...Array(ups).fill(\"..\"),\n ...toSegs.slice(common),\n ].join(\"/\");\n return rel || \"./\";\n}\n\n/**\n * Build the actual Hono handler with input validation, output validation\n * (optional), and error normalisation.\n */\nfunction makeRouteHandler(\n route: AnyRouteDef,\n source: PayloadSource,\n validateOutput: boolean,\n interceptor: RouteInterceptor | undefined,\n services: AnyServicesContainer | undefined,\n errorHandler: ErrorHandler | undefined,\n logger: Logger | undefined,\n) {\n const inputSchema = route.input as z.ZodTypeAny | undefined;\n const outputSchema = route.output as z.ZodTypeAny | undefined;\n const status = route.status ?? 200;\n // Empty fallback so handlers/interceptors always see a `services` field\n // even when the server was started without a container.\n const servicesArg = (services ?? (EMPTY_SERVICES as AnyServicesContainer));\n\n return async (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n c: any,\n ): Promise<Response> => {\n // Apply the injected ErrorHandler, falling back to the built-in envelope.\n // Returns a Response when handled, or null to let the error propagate.\n const applyErrorHandler = async (err: unknown): Promise<Response | null> => {\n if (errorHandler) {\n const handled = await errorHandler.handle({\n error: err,\n c,\n route,\n services: servicesArg,\n logger,\n });\n if (handled) return handled;\n }\n return defaultErrorResponse(c, err);\n };\n\n // `next()` runs validation + handler. Any Zod failure throws\n // `ValidationError` so the interceptor (or default catcher) can shape it.\n const callNext = async (): Promise<unknown> => {\n let payload: unknown = undefined;\n\n // Always read payload if it's expected, even without an input schema.\n // E.g., generic handlers that manually validate the body.\n let raw: unknown;\n try {\n raw = await readPayload(c, source, route.method);\n } catch (err) {\n throw new BadRequestError(\n err instanceof Error ? err.message : String(err),\n );\n }\n\n if (inputSchema) {\n const parsed = inputSchema.safeParse(raw);\n if (!parsed.success) {\n throw new ValidationError(parsed.error, source);\n }\n payload = parsed.data;\n } else {\n payload = raw;\n }\n\n const result = await (route.handler as (ctx: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input: any;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n c: any;\n services: AnyServicesContainer;\n errorHandler: ErrorHandler | undefined;\n logger: Logger | undefined;\n }) => unknown)({\n input: payload,\n c,\n services: servicesArg,\n errorHandler,\n logger,\n });\n\n if (validateOutput && outputSchema && !(result instanceof Response)) {\n const checked = outputSchema.safeParse(result);\n if (!checked.success) {\n throw new OutputValidationError(checked.error);\n }\n return checked.data;\n }\n return result;\n };\n\n let result: unknown;\n if (interceptor) {\n // Interceptor owns the response shape — including validation errors.\n // If it rethrows, the injected ErrorHandler / default catcher applies.\n try {\n result = await interceptor({\n next: callNext,\n route,\n c,\n services: servicesArg,\n errorHandler,\n logger,\n });\n } catch (err) {\n const handled = await applyErrorHandler(err);\n if (handled) return handled;\n throw err;\n }\n } else {\n // Default behaviour — ErrorHandler first, then the built-in\n // ValidationError envelope, else bubble to onError / Hono.\n try {\n result = await callNext();\n } catch (err) {\n const handled = await applyErrorHandler(err);\n if (handled) return handled;\n throw err;\n }\n }\n\n if (result instanceof Response) return result;\n return c.json(result, status);\n };\n}\n\nasync function readPayload(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n c: any,\n source: PayloadSource,\n method: HttpMethod,\n): Promise<unknown> {\n switch (source) {\n case \"json\": {\n if (method === \"get\") return c.req.query();\n const text = await c.req.text();\n if (!text) return {};\n try {\n return JSON.parse(text);\n } catch (err) {\n throw new Error(\n `Invalid JSON body: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n case \"query\":\n return c.req.query();\n case \"form\": {\n const form = await c.req.parseBody();\n return form;\n }\n case \"param\":\n return c.req.param();\n default:\n return {};\n }\n}\n","/**\n * @module servers/crud\n *\n * Creates a REST API server for CRUD operations on Firestore repositories using HonoServer.\n */\nimport type { HttpsOptions } from \"firebase-functions/v2/https\";\nimport type { ConfiguredRepository } from \"../../repositories/types\";\nimport { createCrudHandlers } from \"./handlers\";\nimport { generateOpenAPISpec, type OpenAPIDocument } from \"./openapi\";\nimport type { CrudRepoEntry, CrudRepoRegistry, CrudServerOptions } from \"./types\";\nimport { HonoServer } from \"../hono/server\";\nimport type { AnyRouteDef } from \"../hono/types\";\nimport { getLinkBase } from \"../utils/link-base\";\n\n\nexport function createCrudServer<\n TRepos extends Record<string, ConfiguredRepository<any>>,\n>(\n options: CrudServerOptions<TRepos>,\n): ((req: any, res: any) => Promise<void>) & { spec: () => OpenAPIDocument; httpsOptions?: HttpsOptions } {\n const {\n basePath = \"/\",\n repos,\n parseBody = true,\n securityHeaders: securityHeadersOpt,\n verbose = false,\n httpsOptions,\n } = options;\n\n const base = basePath === \"/\" ? \"\" : basePath.replace(/\\/$/, \"\");\n\n const registry: CrudRepoRegistry = {};\n for (const [name, cfg] of Object.entries(repos)) {\n if (!cfg.repo) {\n throw new Error(`[createCrudServer] Repository \"${name}\" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);\n }\n\n const resolvedSchema = cfg.schema ?? (cfg.repo as any).schema ?? null;\n if (!resolvedSchema) {\n throw new Error(`[createCrudServer] Repository \"${name}\" has no Zod schema.`);\n }\n\n let filterableFields: string[] | undefined;\n let orderableFields: string[] | undefined;\n let mutableFields: string[] | undefined;\n let createFields: string[] | undefined;\n if (cfg.fieldsConfig) {\n const fc = cfg.fieldsConfig as Record<string, readonly string[]>;\n filterableFields = [];\n orderableFields = [];\n mutableFields = [];\n createFields = [];\n for (const [field, roles] of Object.entries(fc)) {\n for (const role of roles) {\n if (role === \"filterable\") filterableFields.push(field);\n else if (role === \"orderable\") orderableFields.push(field);\n else if (role === \"mutable\") mutableFields.push(field);\n else if (role === \"create\") createFields.push(field);\n }\n }\n if (orderableFields.length === 0) orderableFields = filterableFields;\n if (filterableFields.length === 0) filterableFields = undefined;\n if (orderableFields && orderableFields.length === 0) orderableFields = undefined;\n if (mutableFields.length === 0) mutableFields = undefined;\n if (createFields.length === 0) createFields = undefined;\n }\n\n const parentKeys = (() => {\n const pk = (cfg.repo as any)._parentKeys as string[] | undefined;\n return pk && pk.length > 0 ? pk : undefined;\n })();\n if (parentKeys && createFields) {\n for (const pk of parentKeys) {\n if (!createFields.includes(pk)) createFields.push(pk);\n }\n }\n\n const entry: CrudRepoEntry = {\n name,\n path: cfg.path,\n repo: cfg.repo,\n schema: resolvedSchema,\n systemKeys: (cfg.repo as any)._systemKeys ?? [cfg.documentKey ?? \"docId\"],\n documentKey: cfg.documentKey ?? \"docId\",\n pathKey: (cfg.repo as any)._pathKey ?? undefined,\n isGroup: !!(cfg.repo as any)._isGroup,\n parentKeys,\n createdKey: (cfg.repo as any)._createdKey ?? undefined,\n pageSize: cfg.pageSize ?? 25,\n filterableFields,\n orderableFields,\n mutableFields,\n createFields,\n allowDelete: cfg.allowDelete ?? false,\n allowedIncludes: cfg.allowedIncludes as string[] | undefined,\n validate: cfg.validate as CrudRepoEntry[\"validate\"],\n rules: cfg.rules,\n };\n\n registry[name] = entry;\n }\n\n const handlers = createCrudHandlers(registry, base, verbose);\n\n const openapi = options.openapi;\n const openapiOpts = openapi && typeof openapi === \"object\" ? openapi : {};\n let _specCache: OpenAPIDocument | null = null;\n function getSpec(): OpenAPIDocument {\n if (!_specCache) {\n _specCache = generateOpenAPISpec(registry, base, {\n ...openapiOpts,\n auth: openapiOpts.auth ?? false,\n });\n }\n return _specCache;\n }\n\n const routes: AnyRouteDef[] = [];\n\n for (const name of Object.keys(registry)) {\n routes.push({\n api: \"crud\",\n method: \"get\",\n path: `/${name}`,\n source: \"query\",\n handler: handlers.handleList,\n });\n routes.push({\n api: \"crud\",\n method: \"post\",\n path: `/${name}/query`,\n source: \"json\",\n handler: handlers.handleQuery,\n });\n routes.push({\n api: \"crud\",\n method: \"get\",\n path: `/${name}/:id`,\n source: \"query\",\n handler: handlers.handleGet,\n });\n routes.push({\n api: \"crud\",\n method: \"post\",\n path: `/${name}`,\n source: \"json\",\n handler: handlers.handleCreate,\n });\n routes.push({\n api: \"crud\",\n method: \"put\",\n path: `/${name}/:id`,\n source: \"json\",\n handler: (ctx) => handlers.handleUpdate(ctx, false),\n });\n routes.push({\n api: \"crud\",\n method: \"patch\",\n path: `/${name}/:id`,\n source: \"json\",\n handler: (ctx) => handlers.handleUpdate(ctx, true),\n });\n routes.push({\n api: \"crud\",\n method: \"delete\",\n path: `/${name}/:id`,\n source: \"query\",\n handler: handlers.handleDelete,\n });\n routes.push({\n api: \"crud\",\n method: \"post\",\n path: `/${name}/batch`,\n source: \"json\",\n handler: handlers.handleBatch,\n });\n }\n\n // Create the HonoServer\n const server = new HonoServer({\n ...options,\n openapi: openapi !== false ? {\n path: openapiOpts.path ?? \"/openapi.json\",\n docsPath: openapiOpts.docsPath ?? \"/docs\",\n info: { \n title: openapiOpts.title ?? \"CRUD API\", \n version: openapiOpts.version ?? \"1.0.0\" \n },\n docsAuth: openapiOpts.docsAuth as any,\n } : undefined,\n basePath,\n api: \"crud\",\n routes,\n middlewares: [\n async (c, next) => {\n if (c.req.method === \"OPTIONS\") {\n return c.text(\"\", 204 as any, {\n \"Access-Control-Allow-Methods\": \"GET, POST, PUT, PATCH, DELETE, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"Content-Type, Authorization\",\n \"Access-Control-Max-Age\": \"86400\",\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Credentials\": \"true\",\n });\n }\n c.header(\"Access-Control-Allow-Origin\", \"*\");\n c.header(\"Access-Control-Allow-Credentials\", \"true\");\n await next();\n return;\n },\n ...(options.middlewares || []),\n ],\n });\n\n if (openapi !== false) {\n server.buildOpenApiSpec = getSpec as any;\n }\n\n if (securityHeadersOpt !== false) {\n const { securityHeaders } = require(\"../utils/security-headers\");\n const base0 = securityHeadersOpt === undefined ? { csp: false as const } : securityHeadersOpt;\n server.hono.use(\"*\", async (c, next) => {\n const adapter = securityHeaders(base0);\n await new Promise<void>((resolve) => {\n const fakeReq = c.req.raw;\n const fakeRes = {\n setHeader: (k: string, v: string) => c.header(k, v),\n removeHeader: (k: string) => c.res.headers.delete(k),\n };\n adapter(fakeReq, fakeRes, () => resolve());\n });\n await next();\n });\n }\n\n const handler = server.nodeHandler as any;\n handler.spec = getSpec;\n if (httpsOptions) handler.httpsOptions = httpsOptions;\n\n return handler;\n}\n\nexport { generateOpenAPISpec } from \"./openapi\";\nexport type { OpenAPIDocument, OpenAPISpecOptions } from \"./openapi\";\nexport type {\n ApiResponse,\n CrudRepoConfig,\n CrudRepoEntry,\n CrudRepoRegistry,\n CrudServerOptions,\n FieldRole,\n ListResponseData,\n QueryRequestBody,\n RepoFieldPath,\n RepoRelationKeys,\n UserFieldPath,\n} from \"./types\";\n"]}