@lpdjs/firestore-repo-service 2.6.32 → 2.6.34

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.
Files changed (40) hide show
  1. package/README.md +14 -373
  2. package/dist/{create-servers-nXXPnlJt.d.ts → create-servers-DDHHOqOW.d.ts} +3 -3
  3. package/dist/{create-servers-BoJrRNI2.d.cts → create-servers-DmQNkgM_.d.cts} +3 -3
  4. package/dist/{index-DZnXSClM.d.cts → index-bkOZzCvS.d.cts} +1 -1
  5. package/dist/{index-BE-Iuye5.d.ts → index-qSs2G4CW.d.ts} +1 -1
  6. package/dist/index.cjs +94 -94
  7. package/dist/index.cjs.map +1 -1
  8. package/dist/index.d.cts +7 -5
  9. package/dist/index.d.ts +7 -5
  10. package/dist/index.js +94 -94
  11. package/dist/index.js.map +1 -1
  12. package/dist/llms-full.txt +43 -21
  13. package/dist/llms.txt +1 -1
  14. package/dist/{openapi-BHW1HViI.d.cts → openapi-B_2O8iJW.d.cts} +1 -1
  15. package/dist/{openapi-BupSdudk.d.ts → openapi-DBi6hg2V.d.ts} +1 -1
  16. package/dist/servers/admin/index.d.cts +4 -2
  17. package/dist/servers/admin/index.d.ts +4 -2
  18. package/dist/servers/crud/index.cjs +7 -7
  19. package/dist/servers/crud/index.cjs.map +1 -1
  20. package/dist/servers/crud/index.d.cts +7 -171
  21. package/dist/servers/crud/index.d.ts +7 -171
  22. package/dist/servers/crud/index.js +7 -7
  23. package/dist/servers/crud/index.js.map +1 -1
  24. package/dist/servers/hono/index.d.cts +5 -858
  25. package/dist/servers/hono/index.d.ts +5 -858
  26. package/dist/servers/index.cjs +98 -98
  27. package/dist/servers/index.cjs.map +1 -1
  28. package/dist/servers/index.d.cts +7 -5
  29. package/dist/servers/index.d.ts +7 -5
  30. package/dist/servers/index.js +98 -98
  31. package/dist/servers/index.js.map +1 -1
  32. package/dist/sync/index.cjs +7 -7
  33. package/dist/sync/index.cjs.map +1 -1
  34. package/dist/sync/index.js +7 -7
  35. package/dist/sync/index.js.map +1 -1
  36. package/dist/types-B4dMmfet.d.cts +860 -0
  37. package/dist/{types-CpkQQn4b.d.cts → types-BRS75oO7.d.cts} +10 -38
  38. package/dist/{types-BcT92G9B.d.ts → types-DnycnK_G.d.ts} +10 -38
  39. package/dist/types-DyKJJ9UQ.d.ts +860 -0
  40. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/servers/admin/router.ts","../../../src/servers/utils/link-base.ts","../../../src/servers/auth/firebase-auth.ts","../../../src/shared/date-config.ts","../../../src/servers/admin/index-url.ts","../../../src/servers/crud/handlers.ts","../../../src/servers/crud/openapi.ts","../../../src/servers/utils/security-headers.ts","../../../src/servers/crud/index.ts"],"names":["compilePath","path","paramNames","src","c","_match","name","extractPath","req","raw","idx","MiniRouter","_req","res","err","middleware","handler","method","pattern","matchedRoute","params","route","m","i","enrichedReq","finalHandler","index","next","mw","getLinkBase","staticBasePath","region","base","project","resolvedRegion","target","service","host","isAuthExtension","value","currentMode","getDateHandling","isTimestampLike","v","coerceToDate","Timestamp","d","maybeNormalize","RANGE_OPS","ARRAY_OPS","toIndexOrder","dir","collectionIdFromPath","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","isMissingIndexError","fe","toQueryError","ctx","isIndex","indexUrl","colId","sendJson","data","status","sendSuccess","meta","sendError","error","sendQueryError","fallbackMessage","verbose","qe","_idChars","generateFirestoreId","id","randomBytes","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","docId","colRef","createCrudHandlers","registry","basePath","authEnabled","assertRule","rule","applyRowFilter","user","docs","filter","doc","userOf","getRepoEntry","repoName","extractPathArgs","pathKey","fullPath","args","fetchDocById","getterName","getter","handleList","ctxFilters","ctxSort","pageSize","direction","orderBy","orderDir","selectStr","select","s","includes","inc","queryOptions","cursorObj","result","responseData","handleQuery","body","w","validIncludes","allowed","invalid","group","o","handleGet","handleCreate","validation","customError","created","missingKeys","parentIds","handleUpdate","existingDoc","pathArgs","updated","handleDelete","handleOptions","zodToJsonSchema","schemaRef","errorResponse","description","successResponse","dataSchema","listResponse","itemSchema","paginationParams","filterParams","ops","queryBodySchema","buildPathsForEntry","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","ADMIN_CDN","GSTATIC","DEFAULT_HTML_CSP","securityHeaders","opts","csp","frameOptions","referrerPolicy","cacheControl","scalarDocsHtml","specUrl","readRawBody","createCrudServer","repos","parseBody","securityHeadersOpt","extraMiddleware","httpsOptions","cfg","resolvedSchema","orderableFields","mutableFields","createFields","fc","roles","role","parentKeys","pk","handlers","openapi","openapiOpts","_specCache","getSpec","authType","router","base0","_res","mountPath","realm","expected","specPath","docsPath","spec","html"],"mappings":"2GAqHA,SAASA,GAAYC,CAAAA,CAAyD,CAC5E,IAAMC,CAAAA,CAAuB,GACvBC,CAAAA,CAAMF,CAAAA,CACT,OAAA,CAAQ,qBAAA,CAAwBG,GAAOA,CAAAA,GAAM,GAAA,CAAMA,EAAI,CAAA,EAAA,EAAKA,CAAC,EAAG,CAAA,CAChE,OAAA,CAAQ,4BAAA,CAA8B,CAACC,EAAQC,CAAAA,IAC9CJ,CAAAA,CAAW,KAAKI,CAAI,CAAA,CACb,UACR,CAAA,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CACAc,IACF,CAAC,EAGDyQ,CAAAA,CAAO,GAAA,CAAI,GAAGpQ,CAAI,CAAA,UAAA,CAAA,CAAc8P,EAAS,UAAU,CAAA,CAGnDM,EAAO,IAAA,CAAK,CAAA,EAAGpQ,CAAI,CAAA,gBAAA,CAAA,CAAoB8P,CAAAA,CAAS,WAAW,CAAA,CAG3DM,CAAAA,CAAO,IAAI,CAAA,EAAGpQ,CAAI,iBAAkB8P,CAAAA,CAAS,SAAS,EAGtDM,CAAAA,CAAO,IAAA,CAAK,GAAGpQ,CAAI,CAAA,UAAA,CAAA,CAAc8P,EAAS,YAAY,CAAA,CAGtDM,EAAO,GAAA,CAAI,CAAA,EAAGpQ,CAAI,CAAA,cAAA,CAAA,CAAkB,CAACxB,EAAUK,CAAAA,GAC7CiR,CAAAA,CAAS,aAAatR,CAAAA,CAAKK,CAAAA,CAAK,KAAK,CACvC,CAAA,CAGAuR,EAAO,KAAA,CAAM,CAAA,EAAGpQ,CAAI,CAAA,cAAA,CAAA,CAAkB,CAACxB,EAAUK,CAAAA,GAC/CiR,CAAAA,CAAS,aAAatR,CAAAA,CAAKK,CAAAA,CAAK,IAAI,CACtC,CAAA,CAGAuR,EAAO,MAAA,CAAO,CAAA,EAAGpQ,CAAI,CAAA,cAAA,CAAA,CAAkB8P,CAAAA,CAAS,YAAY,CAAA,CAG5D,IAAM9Q,EAAU,MACdR,CAAAA,CACAK,IACkB,CAClB,MAAMuR,EAAO,MAAA,CAAO5R,CAAAA,CAAYK,CAAU,EAC5C,CAAA,CAGA,OAACG,CAAAA,CAAgB,IAAA,CAAOkR,EACpBf,CAAAA,GAAenQ,CAAAA,CAAgB,YAAA,CAAemQ,CAAAA,CAAAA,CAE3CnQ,CAMT","file":"index.cjs","sourcesContent":["/**\n * Minimal zero-dependency HTTP router for Firebase Functions.\n * Compatible with any Express-like (req, res) handler.\n *\n * Supports:\n * - Named path parameters (e.g. \"/repos/:name/:id\")\n * - GET, POST, DELETE methods\n * - Global middleware (before each route)\n * - 404 / error fallbacks\n *\n * @example\n * ```typescript\n * import { MiniRouter } from \"@lpdjs/firestore-repo-service/servers/admin\";\n *\n * // Create router\n * const router = new MiniRouter();\n *\n * // Add global middleware (executed before every route)\n * router.use(async (req, res, next) => {\n * console.log(`${req.method} ${req.url}`);\n * await next();\n * });\n *\n * // Auth middleware\n * router.use((req, res, next) => {\n * if (!req.headers?.authorization) {\n * res.status(401).send(\"Unauthorized\");\n * return;\n * }\n * next();\n * });\n *\n * // Define routes with path parameters\n * router.get(\"/users\", async (req, res) => {\n * res.json({ users: await getAllUsers() });\n * });\n *\n * router.get(\"/users/:id\", async (req, res) => {\n * const user = await getUser(req.params.id); // Access path params\n * if (!user) {\n * res.status(404).send(\"User not found\");\n * return;\n * }\n * res.json(user);\n * });\n *\n * router.post(\"/users\", async (req, res) => {\n * const user = await createUser(req.body);\n * res.status(201).json(user);\n * });\n *\n * router.delete(\"/users/:id\", async (req, res) => {\n * await deleteUser(req.params.id);\n * res.status(204).end();\n * });\n *\n * // Custom 404 handler\n * router.onNotFound((req, res) => {\n * res.status(404).json({ error: \"Route not found\", path: req.url });\n * });\n *\n * // Custom error handler\n * router.onError((err, req, res) => {\n * console.error(\"Error:\", err);\n * res.status(500).json({ error: \"Internal server error\" });\n * });\n *\n * // Use with Firebase Functions\n * export const api = onRequest(async (req, res) => {\n * await router.handle(req, res);\n * });\n * ```\n */\n\nexport type AnyReq = {\n method?: string;\n url?: string;\n /** Express originalUrl — preserved before any router stripping, contains the full path including the Firebase Functions prefix */\n originalUrl?: string;\n path?: string;\n headers?: Record<string, string | string[] | undefined>;\n body?: unknown;\n query?: Record<string, string | string[] | undefined>;\n};\n\nexport type AnyRes = {\n status: (code: number) => AnyRes;\n set: (key: string, value: string) => AnyRes;\n send: (body: string) => void;\n json: (body: unknown) => void;\n end: () => void;\n};\n\nexport type RouteParams = Record<string, string>;\n\nexport type RouteHandler = (\n req: AnyReq & { params: RouteParams },\n res: AnyRes,\n) => void | Promise<void>;\n\nexport type Middleware = (\n req: AnyReq & { params: RouteParams },\n res: AnyRes,\n next: () => void | Promise<void>,\n) => void | Promise<void>;\n\n// ---------------------------------------------------------------------------\n// Route matching\n// ---------------------------------------------------------------------------\n\ninterface CompiledRoute {\n method: string;\n pattern: RegExp;\n paramNames: string[];\n handler: RouteHandler;\n}\n\nfunction compilePath(path: string): { pattern: RegExp; paramNames: string[] } {\n const paramNames: string[] = [];\n const src = path\n .replace(/[.*+?^${}()|[\\]\\\\]/g, (c) => (c === \":\" ? c : `\\\\${c}`))\n .replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, (_match, name: string) => {\n paramNames.push(name);\n return \"([^/]+)\";\n });\n\n return { pattern: new RegExp(`^${src}$`), paramNames };\n}\n\nfunction extractPath(req: AnyReq): string {\n const raw = req.path ?? req.url ?? \"/\";\n const idx = raw.indexOf(\"?\");\n return idx === -1 ? raw : raw.slice(0, idx);\n}\n\n// ---------------------------------------------------------------------------\n// Router class\n// ---------------------------------------------------------------------------\n\nexport class MiniRouter {\n private routes: CompiledRoute[] = [];\n private middlewares: Middleware[] = [];\n private notFoundHandler: RouteHandler = (_req, res) => {\n res.status(404).send(\"Not Found\");\n };\n private errorHandler: (err: unknown, req: AnyReq, res: AnyRes) => void = (\n err,\n _req,\n res,\n ) => {\n console.error(\"[MiniRouter]\", err);\n res.status(500).send(\"Internal Server Error\");\n };\n\n // ── Route registration ────────────────────────────────────────────────────\n\n use(middleware: Middleware): this {\n this.middlewares.push(middleware);\n return this;\n }\n\n get(path: string, handler: RouteHandler): this {\n return this.addRoute(\"GET\", path, handler);\n }\n\n post(path: string, handler: RouteHandler): this {\n return this.addRoute(\"POST\", path, handler);\n }\n\n put(path: string, handler: RouteHandler): this {\n return this.addRoute(\"PUT\", path, handler);\n }\n\n patch(path: string, handler: RouteHandler): this {\n return this.addRoute(\"PATCH\", path, handler);\n }\n\n delete(path: string, handler: RouteHandler): this {\n return this.addRoute(\"DELETE\", path, handler);\n }\n\n onNotFound(handler: RouteHandler): this {\n this.notFoundHandler = handler;\n return this;\n }\n\n onError(handler: (err: unknown, req: AnyReq, res: AnyRes) => void): this {\n this.errorHandler = handler;\n return this;\n }\n\n private addRoute(method: string, path: string, handler: RouteHandler): this {\n const { pattern, paramNames } = compilePath(path);\n this.routes.push({\n method: method.toUpperCase(),\n pattern,\n paramNames,\n handler,\n });\n return this;\n }\n\n // ── Dispatch ──────────────────────────────────────────────────────────────\n\n async handle(req: AnyReq, res: AnyRes): Promise<void> {\n const method = (req.method ?? \"GET\").toUpperCase();\n const path = extractPath(req);\n\n // Find matching route\n let matchedRoute: CompiledRoute | null = null;\n let params: RouteParams = {};\n\n for (const route of this.routes) {\n if (route.method !== method) continue;\n const m = path.match(route.pattern);\n if (m) {\n matchedRoute = route;\n params = {};\n route.paramNames.forEach((name, i) => {\n params[name] = decodeURIComponent(m[i + 1] ?? \"\");\n });\n break;\n }\n }\n\n const enrichedReq = Object.assign(req, { params });\n\n // Run middleware chain → then handler\n const handler = matchedRoute ? matchedRoute.handler : this.notFoundHandler;\n\n try {\n await this.runMiddlewareChain(enrichedReq, res, handler);\n } catch (err) {\n this.errorHandler(err, req, res);\n }\n }\n\n private async runMiddlewareChain(\n req: AnyReq & { params: RouteParams },\n res: AnyRes,\n finalHandler: RouteHandler,\n ): Promise<void> {\n let index = 0;\n\n const next = async (): Promise<void> => {\n if (index < this.middlewares.length) {\n const mw = this.middlewares[index++]!;\n await mw(req, res, next);\n } else {\n await finalHandler(req, res);\n }\n };\n\n await next();\n }\n}\n","/**\n * Compute the URL prefix used to build absolute paths from inside a\n * Firebase HTTPS function. Handles three deployment shapes uniformly:\n *\n * 1. **Firebase emulator** (`FUNCTIONS_EMULATOR=true`) — exposes functions at\n * `http://localhost:5001/{project}/{region}/{functionTarget}/...`. The\n * handler receives `req.url` *without* this prefix, so we rebuild it from\n * `GCLOUD_PROJECT`, `FUNCTION_REGION`, `FUNCTION_TARGET`.\n *\n * 2. **Cloud Functions v2 default URL** (`*.cloudfunctions.net/{name}`) —\n * Cloud Run terminates routing at the service name, so links must include\n * the `K_SERVICE` prefix. Detected via the `host` header containing\n * `cloudfunctions.net`.\n *\n * 3. **Custom domain / Hosting rewrite** — the proxy strips the prefix\n * before reaching the handler, so links are relative to the configured\n * `staticBasePath`.\n *\n * @param req The incoming request (needs `headers.host` / `hostname`).\n * @param staticBasePath The user-configured base path (e.g. `\"/api\"`).\n * @param region Explicit deployment region (e.g. `\"europe-west1\"`).\n * Used **only** in the emulator branch to build the\n * `/{project}/{region}/{target}` prefix; when omitted it\n * falls back to `FUNCTION_REGION` then `\"us-central1\"`.\n * Pass it (e.g. from `httpsOptions.region`) whenever the\n * function is deployed outside `us-central1`, since the\n * emulator does not reliably expose the region via env.\n * @returns A path prefix (no trailing slash) suitable for prepending to\n * `req.url` to build a same-function absolute URL.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getLinkBase(\n req: any,\n staticBasePath: string,\n region?: string,\n): string {\n const base = staticBasePath === \"/\" ? \"\" : staticBasePath.replace(/\\/$/, \"\");\n\n if (process.env[\"FUNCTIONS_EMULATOR\"] === \"true\") {\n const project =\n process.env[\"GCLOUD_PROJECT\"] ??\n process.env[\"GOOGLE_CLOUD_PROJECT\"] ??\n \"demo-project\";\n const resolvedRegion =\n region ?? process.env[\"FUNCTION_REGION\"] ?? \"us-central1\";\n // FUNCTION_TARGET uses dots (e.g. \"sync.functions.adminsync\") but the\n // emulator URL uses hyphens (\"sync-functions-adminsync\").\n const target = (process.env[\"FUNCTION_TARGET\"] ?? \"\").replace(/\\./g, \"-\");\n return `/${project}/${resolvedRegion}/${target}${base}`;\n }\n\n // Cloud Functions v2: K_SERVICE = function name = URL path prefix.\n // Only add it when accessed via cloudfunctions.net (not custom domains).\n // Cloud Run (Gen 2) lowercases service names, but K_SERVICE may still\n // carry the original mixed-case export name — normalise to lowercase\n // so that generated links match the canonical URL.\n const service = process.env[\"K_SERVICE\"];\n const host: string =\n req?.hostname ?? req?.headers?.[\"host\"] ?? \"\";\n if (service && typeof host === \"string\" && host.includes(\"cloudfunctions.net\")) {\n return `/${service.toLowerCase()}${base}`;\n }\n\n return base;\n}\n\n/**\n * Normalise the `region` field of a Firebase `HttpsOptions` (which may be a\n * single region, an array, a CEL `Expression`, or a `ResetValue`) into a single\n * concrete region string for {@link getLinkBase}. Returns `undefined` for\n * anything that is not a plain string at config time.\n */\nexport function resolveRegion(region: unknown): string | undefined {\n if (typeof region === \"string\") return region;\n if (Array.isArray(region)) {\n const first = region[0];\n return typeof first === \"string\" ? first : undefined;\n }\n return undefined;\n}\n","/**\n * Firebase Auth helper for the admin & CRUD servers.\n *\n * Returns an {@link AuthExtension} ready to plug into `servers.admin()` or\n * `servers.crud()`. Supports two transport modes:\n *\n * - **`cookie`** — session cookie pattern (default for admin UIs). Mounts\n * `/__login`, `/__session`, `/__logout` routes; the page lets the user sign\n * in client-side with the Firebase JS SDK and exchanges the resulting ID\n * token for an HttpOnly session cookie via Firebase Admin SDK.\n * - **`bearer`** — verifies `Authorization: Bearer <idToken>` on every request\n * (default for REST APIs). No login routes mounted.\n * - **`both`** — accept either cookie or bearer.\n *\n * The helper is **agnostic** about authorization: pass an `allow` callback\n * returning whatever role/context shape you need. The result is exposed as\n * `req.user.context` to downstream middlewares and route handlers.\n *\n * @example Admin (cookie + role trio)\n * ```ts\n * import { firebaseAuth } from \"@lpdjs/firestore-repo-service/servers/auth\";\n * import { getAuth } from \"firebase-admin/auth\";\n *\n * servers.admin({\n * auth: firebaseAuth({\n * getAuth,\n * mode: \"cookie\",\n * apiKey: process.env.FIREBASE_WEB_API_KEY!,\n * authDomain: process.env.FIREBASE_AUTH_DOMAIN!,\n * allow: ({ email, claims }) => {\n * if (claims.superAdmin) return { role: \"superAdmin\" };\n * if (email?.endsWith(\"@solarpush.io\")) return { role: \"admin\" };\n * if (email) return { role: \"viewer\" };\n * return null;\n * },\n * }),\n * repos: { ... },\n * });\n * ```\n *\n * @example CRUD (bearer + business rules per repo)\n * ```ts\n * servers.crud({\n * auth: firebaseAuth({ getAuth, mode: \"bearer\", allow: (u) => u }),\n * repos: {\n * comments: {\n * repo: repos.comments,\n * rules: {\n * list: () => true,\n * get: ({ user, doc }) => doc.public || doc.authorId === user.uid,\n * create: ({ user }) => !!user.uid,\n * update: ({ user, doc }) => user.uid === doc.authorId,\n * delete: ({ user, doc }) => user.claims.role === \"moderator\",\n * },\n * },\n * },\n * });\n * ```\n */\n\nimport type { AnyReq, Middleware, RouteHandler } from \"../admin/router\";\nimport { getLinkBase } from \"../utils/link-base\";\nimport { renderLoginPage } from \"./login-page\";\nimport {\n createLogoutHandler,\n createSessionHandler,\n parseCookies,\n SESSION_COOKIE_DEFAULT,\n} from \"./session\";\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal Firebase Admin Auth surface needed by this helper.\n * Avoids a hard import of `firebase-admin/auth` so the package stays\n * decoupled from a specific firebase-admin version.\n */\nexport interface FirebaseAdminAuthLike {\n verifyIdToken(\n idToken: string,\n checkRevoked?: boolean,\n ): Promise<DecodedIdTokenLike>;\n verifySessionCookie(\n sessionCookie: string,\n checkRevoked?: boolean,\n ): Promise<DecodedIdTokenLike>;\n createSessionCookie(\n idToken: string,\n sessionCookieOptions: { expiresIn: number },\n ): Promise<string>;\n revokeRefreshTokens(uid: string): Promise<void>;\n}\n\nexport interface DecodedIdTokenLike {\n uid: string;\n email?: string;\n email_verified?: boolean;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [claim: string]: any;\n}\n\n/** Identity attached to every authenticated request as `req.user`. */\nexport interface AuthUser<TContext = unknown> {\n uid: string;\n email: string | null;\n emailVerified: boolean;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n claims: Record<string, any>;\n /** Result of the user-supplied `allow()` callback. */\n context: TContext;\n}\n\n/** A route descriptor mounted by `firebaseAuth` before the protected chain. */\nexport interface AuthRoute {\n method: \"GET\" | \"POST\";\n path: string;\n handler: RouteHandler;\n}\n\n/**\n * Returned by {@link firebaseAuth}. Servers detect this shape (vs.\n * `BasicAuthConfig` / raw `Middleware`) and mount the routes before pushing\n * the middleware onto the chain.\n */\nexport interface AuthExtension {\n readonly __authExtension: true;\n middleware: Middleware;\n /** Auxiliary routes (login page, session, logout). Empty in pure bearer mode. */\n routes: AuthRoute[];\n /** Path used to redirect unauthenticated browser requests. */\n loginPath: string;\n}\n\nexport type FirebaseAuthMode = \"cookie\" | \"bearer\" | \"both\";\n\n/** Provider configuration for the bundled login page. */\nexport interface FirebaseAuthLoginPageConfig {\n /** Page title. Default: \"Admin sign-in\". */\n title?: string;\n /**\n * Providers shown on the login page.\n * Default: `[\"password\", \"google\"]`.\n */\n providers?: (\"password\" | \"google\")[];\n}\n\nexport interface FirebaseAuthConfig<TContext = unknown> {\n /** Lazy getter for the Firebase Admin Auth instance. */\n getAuth: () => FirebaseAdminAuthLike;\n\n /** Transport mode. Default: `\"cookie\"`. */\n mode?: FirebaseAuthMode;\n\n /**\n * Authorization callback. Receives the verified token claims and returns:\n * - a context object → request is allowed, exposed as `req.user.context`,\n * - `null` → request is rejected (401 / redirect to login).\n *\n * If omitted, the default policy allows any authenticated user with\n * `context = null`.\n */\n allow?: (\n user: Omit<AuthUser, \"context\">,\n ) => TContext | null | Promise<TContext | null>;\n\n // ── Cookie mode options ────────────────────────────────────────────────\n /**\n * Whether to mount the bundled `/__login`, `/__session`, `/__logout`\n * routes. Default: `true` for `cookie`/`both`, `false` for `bearer`.\n */\n loginPage?: boolean | FirebaseAuthLoginPageConfig;\n\n /**\n * Firebase Web API key required by the JS SDK on the login page.\n * Mandatory when `loginPage` is enabled. Find it in your Firebase Console\n * under Project Settings → General → Web app config.\n */\n apiKey?: string;\n\n /**\n * Firebase Auth domain (e.g. `my-project.firebaseapp.com`).\n * Mandatory when `loginPage` is enabled.\n */\n authDomain?: string;\n\n /** Cookie name. Default: `__admin_session`. */\n cookieName?: string;\n\n /** Session cookie TTL in days. Default: `5` (Firebase max is 14). */\n sessionTtlDays?: number;\n\n /**\n * Cookie `Secure` flag. Default: `true`. Set to `false` only for local\n * development over HTTP.\n */\n secureCookie?: boolean;\n\n /** Cookie `SameSite`. Default: `\"Lax\"`. */\n sameSite?: \"Strict\" | \"Lax\" | \"None\";\n\n /**\n * Deployment region (e.g. `\"europe-west1\"`). Used to build the login page's\n * same-function URLs **under the Firebase emulator**, which does not reliably\n * expose the region via env — without it the emulator prefix falls back to\n * `us-central1`, so the session POST 404s when deployed elsewhere. Has no\n * effect in production (the prefix is derived from the request there). When\n * created via `servers.admin/crud()` this defaults to `httpsOptions.region`.\n */\n region?: string;\n\n /**\n * Firebase Auth emulator host (e.g. `127.0.0.1:9099`). When set, the login\n * page's client SDK is pointed at the emulator via `connectAuthEmulator`,\n * matching the Admin SDK (which already targets the emulator when\n * `FIREBASE_AUTH_EMULATOR_HOST` is set). Defaults to that env var, so local\n * `firebase emulators:start` runs work out of the box; pass `\"\"` to force it\n * off.\n */\n authEmulatorHost?: string;\n\n /**\n * Enable the built-in CSRF defense: state-changing requests\n * (`POST`/`PUT`/`PATCH`/`DELETE`) authenticated by **session cookie** must\n * carry an `Origin`/`Referer` header matching the request host. Bearer\n * requests are exempt (a browser never auto-attaches an `Authorization`\n * header, so they are not CSRF-able).\n *\n * **Defaults to `true` only when `sameSite: \"None\"`** (and not in `bearer`\n * mode). With the default `Lax`/`Strict` cookie the browser already blocks\n * the session cookie on cross-site mutations, so the check is unnecessary\n * and is left off to avoid false positives behind proxies whose `Host`\n * differs from the public origin (e.g. Cloud Functions v2 / Cloud Run).\n * Set to `true` to force the check on regardless of `sameSite`, or `false`\n * to disable it even with `sameSite: \"None\"` (only if you implement your\n * own CSRF protection upstream).\n */\n csrfProtection?: boolean;\n\n /**\n * Behaviour when authentication fails or `allow()` returns `null`.\n * - `\"redirect\"` (default in cookie mode) → 302 to the login page,\n * - `\"401\"` (default in bearer mode) → JSON 401 response.\n */\n onUnauthenticated?: \"redirect\" | \"401\";\n\n /**\n * Routes that should bypass the auth middleware (matched against the path\n * after the basePath stripping). The auxiliary login routes are always\n * public regardless of this option.\n */\n publicPaths?: (string | RegExp)[];\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction defaultLoginPage(mode: FirebaseAuthMode): boolean {\n return mode === \"cookie\" || mode === \"both\";\n}\n\nfunction defaultUnauth(mode: FirebaseAuthMode): \"redirect\" | \"401\" {\n return mode === \"bearer\" ? \"401\" : \"redirect\";\n}\n\nfunction pathOf(req: AnyReq): string {\n const raw = req.path ?? req.url ?? \"/\";\n const idx = raw.indexOf(\"?\");\n return idx === -1 ? raw : raw.slice(0, idx);\n}\n\nfunction queryAction(req: AnyReq): string | null {\n const q = (req as { query?: Record<string, unknown> }).query;\n if (q && typeof q.__action === \"string\") return q.__action;\n // Fallback: parse from URL when query parsing isn't done by the runtime.\n const url = req.url ?? \"\";\n const idx = url.indexOf(\"?\");\n if (idx === -1) return null;\n const params = new URLSearchParams(url.slice(idx + 1));\n return params.get(\"__action\");\n}\n\nfunction methodOf(req: AnyReq): string {\n return String(req.method ?? \"GET\").toUpperCase();\n}\n\n/**\n * Strip a redirect / `next` target down to a safe **same-origin path**.\n *\n * Rejects protocol-relative (`//evil.com`), backslash-escaped (`/\\evil.com`)\n * and absolute (`https://…`) targets that would let an attacker turn the\n * post-login redirect into an open redirect / phishing vector (issue #07).\n * Anything suspicious collapses to `\"/\"`.\n */\nfunction sanitizeNextPath(next: string): string {\n if (typeof next !== \"string\" || next.length === 0) return \"/\";\n if (!next.startsWith(\"/\")) return \"/\";\n if (next.startsWith(\"//\") || next.startsWith(\"/\\\\\")) return \"/\";\n if (next.includes(\"://\")) return \"/\";\n return next;\n}\n\nfunction headerOf(req: AnyReq, name: string): string | undefined {\n const raw = req.headers?.[name];\n if (Array.isArray(raw)) return raw[0];\n return typeof raw === \"string\" ? raw : undefined;\n}\n\nconst CSRF_SAFE_METHODS = new Set([\"GET\", \"HEAD\", \"OPTIONS\"]);\n\n/**\n * Same-origin check used as a CSRF defense for state-changing requests.\n * Compares the request `Origin` (or `Referer`) host against the request host.\n * Returns `true` only when they match. A missing/invalid Origin fails closed.\n */\nfunction isSameOriginRequest(req: AnyReq): boolean {\n const originHeader = headerOf(req, \"origin\") ?? headerOf(req, \"referer\");\n if (!originHeader) return false;\n const host = headerOf(req, \"x-forwarded-host\") ?? headerOf(req, \"host\");\n if (!host) return false;\n try {\n return new URL(originHeader).host === host;\n } catch {\n return false;\n }\n}\n\nfunction isPublic(\n path: string,\n patterns: (string | RegExp)[] | undefined,\n): boolean {\n if (!patterns || patterns.length === 0) return false;\n for (const p of patterns) {\n if (typeof p === \"string\") {\n if (path === p || path.startsWith(p + \"/\")) return true;\n } else if (p.test(path)) {\n return true;\n }\n }\n return false;\n}\n\nfunction wantsHtml(req: AnyReq): boolean {\n const accept = String(req.headers?.accept ?? \"\");\n // Strict: only real browser navigations advertise `text/html`. Treating\n // `*/*` or a missing Accept header as HTML caused curl, healthchecks and\n // server-to-server fetches to receive a 200 login page instead of a clear\n // 401 (issue #16).\n return accept.includes(\"text/html\");\n}\n\nfunction extractBearer(req: AnyReq): string | null {\n const raw = req.headers?.authorization;\n const header = Array.isArray(raw) ? raw[0] : raw;\n if (!header) return null;\n const m = /^Bearer\\s+(.+)$/i.exec(header);\n return m ? m[1]!.trim() : null;\n}\n\nfunction rejectUnauthenticated(\n req: AnyReq,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n res: any,\n policy: \"redirect\" | \"401\",\n loginPath: string,\n): void {\n if (policy === \"redirect\" && wantsHtml(req)) {\n const target = encodeURIComponent(req.url ?? \"/\");\n res\n .status(302)\n .set(\"Location\", `${loginPath}?next=${target}`)\n .set(\"Cache-Control\", \"no-store\")\n .end();\n return;\n }\n res\n .status(401)\n .set(\"Content-Type\", \"application/json; charset=utf-8\")\n .send(JSON.stringify({ success: false, error: \"Unauthorized\" }));\n}\n\n// ---------------------------------------------------------------------------\n// Public factory\n// ---------------------------------------------------------------------------\n\n/**\n * Build a Firebase Auth extension for use with `servers.admin()` or\n * `servers.crud()`. See module-level docs for the full design and examples.\n */\nexport function firebaseAuth<TContext = unknown>(\n config: FirebaseAuthConfig<TContext>,\n): AuthExtension {\n const mode: FirebaseAuthMode = config.mode ?? \"cookie\";\n const cookieName = config.cookieName ?? SESSION_COOKIE_DEFAULT;\n const ttlDays = config.sessionTtlDays ?? 5;\n const secure = config.secureCookie ?? true;\n const sameSite = config.sameSite ?? \"Lax\";\n // The Origin/Referer (CSRF) check is only needed when `SameSite=None`:\n // with the default `Lax` (or `Strict`) the browser already refuses to send\n // the session cookie on cross-site state-changing requests, so a cross-site\n // POST/PUT/DELETE is unauthenticated and harmless. Enforcing the Origin\n // check unconditionally also breaks legitimate same-origin requests on\n // platforms where the container's `Host` differs from the public origin\n // (e.g. Cloud Functions v2 / Cloud Run, where `Host` is the internal\n // `*.run.app` host while `Origin` is the `*.cloudfunctions.net` domain).\n // Can be forced on/off explicitly via `csrfProtection`.\n const csrfProtection =\n config.csrfProtection ?? (mode !== \"bearer\" && sameSite === \"None\");\n if (mode !== \"bearer\" && sameSite === \"None\") {\n console.warn(\n \"[firebaseAuth] `sameSite: \\\"None\\\"` disables the browser's built-in \" +\n \"SameSite CSRF protection. \" +\n (csrfProtection\n ? \"The same-origin (Origin/Referer) check is active as the primary \" +\n \"defense — ensure state-changing requests are sent same-origin or \" +\n \"carry a bearer token.\"\n : \"`csrfProtection` is disabled — your endpoints are CSRF-exposed.\"),\n );\n }\n const onUnauth = config.onUnauthenticated ?? defaultUnauth(mode);\n const loginEnabled =\n config.loginPage === undefined\n ? defaultLoginPage(mode)\n : config.loginPage !== false;\n\n const loginPath = \"/__login\";\n const sessionPath = \"/__session\";\n const logoutPath = \"/__logout\";\n\n // ── Auxiliary handlers (kept in `routes` for hosting deployments\n // where users can mount them at known paths, AND invoked in-band by the\n // middleware on `?__action=session|logout` so vanilla Cloud Functions\n // — where there is no separate URL prefix per route — work too). ──────\n const sessionHandler = createSessionHandler({\n getAuth: config.getAuth,\n cookieName,\n ttlDays,\n secure,\n sameSite,\n });\n const logoutHandler = createLogoutHandler({\n getAuth: config.getAuth,\n cookieName,\n secure,\n sameSite,\n });\n\n function renderInlineLogin(\n req: AnyReq,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n res: any,\n error: string | null = null,\n status = 200,\n ): void {\n // Validate lazily (at request time) so module loading during Firebase CLI\n // analysis doesn't throw before env vars are injected.\n if (!config.apiKey || !config.authDomain) {\n throw new Error(\n \"[firebaseAuth] `apiKey` and `authDomain` are required when `loginPage` is enabled. \" +\n \"Find both in the Firebase Console under Project Settings → General → Web app config.\",\n );\n }\n const pageCfg: FirebaseAuthLoginPageConfig =\n typeof config.loginPage === \"object\" ? config.loginPage : {};\n // Build a same-function absolute URL: the function's external prefix\n // (Cloud Functions name, emulator project/region/target, or \"\" for\n // custom domains) + the in-router request path. The browser otherwise\n // resolves form actions relative to the public URL, which doesn't\n // include the function name on Cloud Functions.\n const prefix = getLinkBase(req, \"/\", config.region);\n const inner = req.url ?? \"/\";\n // Sanitize to a same-origin path so a crafted request URL (e.g.\n // `//evil.com/...` on a custom domain where the prefix is empty) cannot\n // turn the post-login redirect or the form action into an open redirect\n // (issue #07).\n const fullPath = sanitizeNextPath(\n `${prefix}${inner.startsWith(\"/\") ? inner : `/${inner}`}`,\n );\n const sep = fullPath.includes(\"?\") ? \"&\" : \"?\";\n const sessionAction = `${fullPath}${sep}__action=session`;\n const html = renderLoginPage({\n title: pageCfg.title ?? \"Admin sign-in\",\n providers: pageCfg.providers ?? [\"password\", \"google\"],\n apiKey: config.apiKey!,\n authDomain: config.authDomain!,\n sessionPath: sessionAction,\n next: fullPath,\n error,\n authEmulatorHost:\n config.authEmulatorHost ?? process.env[\"FIREBASE_AUTH_EMULATOR_HOST\"],\n });\n res\n .status(status)\n .set(\"Content-Type\", \"text/html; charset=utf-8\")\n .set(\"Cache-Control\", \"no-store\")\n .send(html);\n }\n\n // ── Auxiliary routes ─────────────────────────────────────────────────────\n const routes: AuthRoute[] = [];\n if (loginEnabled) {\n routes.push({\n method: \"GET\",\n path: loginPath,\n handler: (req, res) => {\n const error = (req.query?.error as string | undefined) ?? null;\n renderInlineLogin(req, res, error);\n },\n });\n routes.push({\n method: \"POST\",\n path: sessionPath,\n handler: sessionHandler,\n });\n routes.push({\n method: \"POST\",\n path: logoutPath,\n handler: logoutHandler,\n });\n }\n\n const publicPaths: (string | RegExp)[] = [\n ...(config.publicPaths ?? []),\n loginPath,\n sessionPath,\n logoutPath,\n ];\n\n // ── Middleware ───────────────────────────────────────────────────────────\n const middleware: Middleware = async (req, res, next) => {\n const path = pathOf(req);\n const method = methodOf(req);\n\n // 0. CSRF defense for cookie sessions (only active when `SameSite=None`,\n // or when `csrfProtection` is explicitly forced on — see config). With\n // the default Lax/Strict cookie the browser already blocks the session\n // cookie on cross-site state-changing requests, so this is skipped to\n // avoid breaking legitimate same-origin requests behind proxies. When\n // active it runs FIRST so it also protects the in-band\n // `?__action=logout|session` shortcut below (issues #05, #06).\n if (\n csrfProtection &&\n mode !== \"bearer\" &&\n !CSRF_SAFE_METHODS.has(method) &&\n !extractBearer(req) &&\n !isSameOriginRequest(req)\n ) {\n res\n .status(403)\n .set(\"Content-Type\", \"application/json; charset=utf-8\")\n .send(\n JSON.stringify({\n success: false,\n error: \"Origin check failed (possible CSRF)\",\n }),\n );\n return;\n }\n\n // 1. In-band action endpoints. The bundled login page posts the session\n // exchange (and logout) to the CURRENT url with `?__action=session`\n // (resp. `logout`) rather than to the mounted `/__session` route,\n // because on vanilla Cloud Functions the helper cannot reliably know\n // the function's public URL prefix to address a separate route. These\n // actions are inherently public (login/logout need no prior auth) and\n // are protected against cross-site abuse by the same-origin guard\n // above (issue #06).\n if (loginEnabled && method === \"POST\") {\n const action = queryAction(req);\n if (action === \"session\") {\n await sessionHandler(req, res);\n return;\n }\n if (action === \"logout\") {\n await logoutHandler(req, res);\n return;\n }\n }\n\n // 2. Public paths (mounted login routes, user-supplied allowlist).\n if (isPublic(path, publicPaths)) {\n await next();\n return;\n }\n\n let decoded: DecodedIdTokenLike | null = null;\n try {\n const auth = config.getAuth();\n\n // Try bearer first when allowed (cheaper, no cookie parsing).\n if (mode === \"bearer\" || mode === \"both\") {\n const token = extractBearer(req);\n if (token) {\n decoded = await auth.verifyIdToken(token, true);\n }\n }\n\n // Fall back to cookie when allowed.\n if (!decoded && (mode === \"cookie\" || mode === \"both\")) {\n const cookieHeader = req.headers?.cookie;\n const raw = Array.isArray(cookieHeader)\n ? cookieHeader.join(\"; \")\n : cookieHeader;\n const cookies = parseCookies(typeof raw === \"string\" ? raw : \"\");\n const session = cookies[cookieName];\n if (session) {\n decoded = await auth.verifySessionCookie(session, true);\n }\n }\n } catch {\n decoded = null;\n }\n\n if (!decoded) {\n rejectUnauthenticated(req, res);\n return;\n }\n\n const baseUser: Omit<AuthUser, \"context\"> = {\n uid: decoded.uid,\n email: typeof decoded.email === \"string\" ? decoded.email : null,\n emailVerified: !!decoded.email_verified,\n claims: decoded as Record<string, unknown>,\n };\n\n let context: TContext | null;\n try {\n context = config.allow\n ? await config.allow(baseUser)\n : (null as TContext | null);\n } catch {\n context = null;\n }\n\n if (config.allow && context === null) {\n rejectUnauthenticated(req, res);\n return;\n }\n\n (req as AnyReq & { user?: AuthUser<TContext> }).user = {\n ...baseUser,\n context: context as TContext,\n };\n\n await next();\n };\n\n /**\n * Reject according to the configured policy:\n * - cookie/both + GET HTML browser request → render the login page inline\n * on the SAME URL with a `401` status (works on Cloud Functions where\n * there's no separate `/__login` route reachable from the public URL).\n * A 401 keeps the response HTTP-compliant for monitoring/healthchecks\n * while browsers still render the page (issue #16).\n * - bearer mode or non-HTML clients → JSON 401.\n */\n function rejectUnauthenticated(\n req: AnyReq,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n res: any,\n ): void {\n if (\n onUnauth === \"redirect\" &&\n loginEnabled &&\n methodOf(req) === \"GET\" &&\n wantsHtml(req)\n ) {\n renderInlineLogin(req, res, null, 401);\n return;\n }\n res\n .status(401)\n .set(\"Content-Type\", \"application/json; charset=utf-8\")\n .send(JSON.stringify({ success: false, error: \"Unauthorized\" }));\n }\n\n return {\n __authExtension: true,\n middleware,\n routes,\n loginPath,\n };\n}\n\n/**\n * Type guard: detect an {@link AuthExtension} (vs. legacy\n * `BasicAuthConfig` / `Middleware`).\n */\nexport function isAuthExtension(value: unknown): value is AuthExtension {\n return (\n !!value &&\n typeof value === \"object\" &&\n (value as { __authExtension?: unknown }).__authExtension === true\n );\n}\n\n/**\n * Helper for explicitly opening a CRUD operation when the server has\n * `auth` defined (bypasses the default-deny policy).\n *\n * @example\n * ```ts\n * rules: { list: allowAll, get: allowAll }\n * ```\n */\nexport const allowAll = (): true => true;\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 {\n isMissingIndexError,\n toQueryError,\n type QueryErrorContext,\n} 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>(res: any, data: ApiResponse<T>, status = 200): void {\n const payload = maybeNormalize(data);\n res\n .status(status)\n .set(\"Content-Type\", \"application/json; charset=utf-8\")\n .send(JSON.stringify(payload));\n}\n\nfunction sendSuccess<T>(\n res: any,\n data: T,\n meta?: ApiResponse[\"meta\"],\n status = 200,\n): void {\n sendJson(res, { success: true, data, meta }, status);\n}\n\nfunction sendError(res: any, error: string, status = 400): void {\n sendJson(res, { 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 res: any,\n err: unknown,\n ctx: QueryErrorContext,\n fallbackMessage: string,\n verbose: boolean,\n): void {\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 sendJson(res, 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\") 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 { docId: snapshot.id };\n}\n\n/**\n * Deserialize a cursor object back to a DocumentSnapshot.\n * Fetches the document from Firestore to get the actual snapshot.\n */\nasync function deserializeCursor(\n entry: CrudRepoEntry,\n cursor: unknown,\n): Promise<import(\"firebase-admin/firestore\").DocumentSnapshot | undefined> {\n if (!cursor || typeof cursor !== \"object\") return undefined;\n const docId = (cursor as Record<string, unknown>).docId;\n if (typeof docId !== \"string\") return undefined;\n\n try {\n // Get the collection reference from the repo\n const colRef = entry.repo\n .ref as import(\"firebase-admin/firestore\").CollectionReference;\n if (typeof colRef.doc !== \"function\") return undefined;\n const snapshot = await colRef.doc(docId).get();\n return snapshot.exists ? snapshot : 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 authEnabled: boolean = false,\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 res: any,\n entry: CrudRepoEntry,\n op: \"list\" | \"get\" | \"create\" | \"update\" | \"delete\",\n ctx: TCtx,\n ): Promise<boolean> {\n if (!authEnabled) return true;\n const rule = entry.rules?.[op] as\n | ((c: TCtx) => boolean | Promise<boolean>)\n | undefined;\n if (!rule) {\n sendError(\n res,\n `Operation \"${op}\" is not allowed for this repository`,\n 403,\n );\n return false;\n }\n try {\n const ok = await rule(ctx);\n if (!ok) {\n sendError(res, \"Forbidden\", 403);\n return false;\n }\n return true;\n } catch (err) {\n const message =\n verbose && err instanceof Error ? err.message : \"Forbidden\";\n sendError(res, 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 (!authEnabled) return docs;\n const filter = entry.rules?.filter as\n | ((c: { user: any; doc: T; params: Record<string, string> }) =>\n | boolean\n | 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(req: any): any {\n return req?.user ?? null;\n }\n\n // ── Helper to get repo entry ────────────────────────────────────────────\n function getRepoEntry(\n repoName: string | undefined,\n res: any,\n ): CrudRepoEntry | null {\n if (!repoName || !registry[repoName]) {\n sendError(res, `Repository \"${repoName}\" not found`, 404);\n return null;\n }\n return registry[repoName];\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(req: any, res: any): Promise<void> {\n const params = req.params || {};\n const entry = getRepoEntry(params.repoName, res);\n if (!entry) return;\n\n const user = userOf(req);\n if (\n !(await assertRule(res, entry, \"list\", {\n user,\n query: 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 = 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 sendError(res, `Field not orderable: ${orderBy}`, 400);\n return;\n }\n queryOptions.orderBy = [{ field: orderBy, direction: orderDir }];\n }\n\n if (filters.length > 0) {\n queryOptions.where = filters.map((f) => [f.field, f.op, f.value]);\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(req),\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 sendSuccess(res, responseData, {\n pageSize,\n hasMore: result.hasNextPage,\n });\n } catch (err) {\n sendQueryError(\n res,\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(req: any, res: any): Promise<void> {\n const params = req.params || {};\n const entry = getRepoEntry(params.repoName, res);\n if (!entry) return;\n\n const user = userOf(req);\n if (\n !(await assertRule(res, entry, \"list\", {\n user,\n query: req.body ?? {},\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 = req.body ?? {};\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 res,\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 res,\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 res,\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 res,\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(req),\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 sendSuccess(res, responseData, {\n pageSize,\n hasMore: result.hasNextPage,\n });\n } catch (err) {\n sendQueryError(\n res,\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(req: any, res: any): Promise<void> {\n const params = req.params || {};\n const entry = getRepoEntry(params.repoName, res);\n if (!entry) return;\n\n const id = params.id;\n if (!id) {\n sendError(res, \"Document ID required\", 400);\n return;\n }\n\n try {\n const doc = await fetchDocById(entry, id);\n\n if (!doc) {\n sendError(res, \"Document not found\", 404);\n return;\n }\n\n const user = userOf(req);\n if (\n !(await assertRule(res, 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 (authEnabled && 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 sendError(res, \"Document not found\", 404);\n return;\n }\n } catch {\n sendError(res, \"Document not found\", 404);\n return;\n }\n }\n\n sendSuccess(res, doc);\n } catch (err) {\n sendQueryError(\n res,\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(req: any, res: any): Promise<void> {\n const params = req.params || {};\n const entry = getRepoEntry(params.repoName, res);\n if (!entry) return;\n\n try {\n const body = req.body ?? {};\n\n const user = userOf(req);\n if (\n !(await assertRule(res, 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 sendError(res, validation.error, 400);\n return;\n }\n\n // Custom validation\n if (entry.validate) {\n const customError = await entry.validate(validation.data, \"create\");\n if (customError) {\n sendError(res, customError, 400);\n return;\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 res,\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 =\n 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 sendSuccess(res, created, undefined, 201);\n } catch (err) {\n const message =\n verbose && err instanceof Error\n ? err.message\n : \"Failed to create document\";\n sendError(res, message, 500);\n }\n }\n\n // ── UPDATE: PUT/PATCH /:repoName/:id ────────────────────────────────────\n async function handleUpdate(\n req: any,\n res: any,\n partial: boolean,\n ): Promise<void> {\n const params = req.params || {};\n const entry = getRepoEntry(params.repoName, res);\n if (!entry) return;\n\n const id = params.id;\n if (!id) {\n sendError(res, \"Document ID required\", 400);\n return;\n }\n\n try {\n const body = req.body ?? {};\n\n // Fetch existing doc so the rule can authorize against current state\n const existingDoc = await fetchDocById(entry, id);\n if (!existingDoc) {\n sendError(res, \"Document not found\", 404);\n return;\n }\n\n const user = userOf(req);\n if (\n !(await assertRule(res, 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 sendError(res, validation.error, 400);\n return;\n }\n\n // Custom validation\n if (entry.validate) {\n const customError = await entry.validate(validation.data, \"update\");\n if (customError) {\n sendError(res, customError, 400);\n return;\n }\n }\n\n // Update document — derive path args for subcollections\n const pathArgs =\n extractPathArgs(existingDoc, entry.pathKey) ?? [id];\n const updated = await entry.repo.update(\n ...pathArgs,\n validation.data as any,\n );\n\n sendSuccess(res, updated);\n } catch (err) {\n const message =\n verbose && err instanceof Error\n ? err.message\n : \"Failed to update document\";\n sendError(res, message, 500);\n }\n }\n\n // ── DELETE: DELETE /:repoName/:id ───────────────────────────────────────\n async function handleDelete(req: any, res: any): Promise<void> {\n const params = req.params || {};\n const entry = getRepoEntry(params.repoName, res);\n if (!entry) return;\n\n if (!entry.allowDelete) {\n sendError(res, \"Delete not allowed for this repository\", 403);\n return;\n }\n\n const id = params.id;\n if (!id) {\n sendError(res, \"Document ID required\", 400);\n return;\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 sendError(res, \"Document not found\", 404);\n return;\n }\n\n const user = userOf(req);\n if (\n !(await assertRule(res, 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 sendSuccess(res, { deleted: true });\n } catch (err) {\n const message =\n verbose && err instanceof Error\n ? err.message\n : \"Failed to delete document\";\n sendError(res, message, 500);\n }\n }\n\n // ── OPTIONS: for CORS preflight ─────────────────────────────────────────\n function handleOptions(req: any, res: any): void {\n res\n .status(204)\n .set(\n \"Access-Control-Allow-Methods\",\n \"GET, POST, PUT, PATCH, DELETE, OPTIONS\",\n )\n .set(\"Access-Control-Allow-Headers\", \"Content-Type, Authorization\")\n .set(\"Access-Control-Max-Age\", \"86400\")\n .send(\"\");\n }\n\n return {\n handleList,\n handleQuery,\n handleGet,\n handleCreate,\n handleUpdate,\n handleDelete,\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 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 def: any = (ctx.zodSchema as any)?._zod?.def;\n if (!def) return;\n if (def.type === \"date\") {\n (ctx.jsonSchema as any).type = \"string\";\n (ctx.jsonSchema as any).format = \"date-time\";\n } else if (def.type === \"bigint\") {\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 = [\"eq\", \"ne\", \"lt\", \"lte\", \"gt\", \"gte\", \"in\", \"nin\", \"contains\"];\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)`,\n });\n // Operator filters: ?field__op=value\n for (const op of ops) {\n params.push({\n name: `${field}__${op}`,\n in: \"query\",\n schema: { type: \"string\" },\n description: `Filter ${field} with operator ${op}`,\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 // ── 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 // 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 * 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","/**\n * @module servers/crud\n *\n * Creates a REST API server for CRUD operations on Firestore repositories.\n *\n * Features:\n * - RESTful endpoints for List, Get, Create, Update, Delete\n * - Request validation using Zod schemas\n * - Cursor-based pagination\n * - Query filtering with operators (eq, ne, lt, gt, in, etc.)\n * - Field selection\n * - CORS support\n * - Configurable auth (Basic Auth or custom middleware)\n *\n * @example\n * ```ts\n * import * as functions from \"firebase-functions\";\n * import { z } from \"zod\";\n * import { createCrudServer } from \"@lpdjs/firestore-repo-service/servers/crud\";\n *\n * const postSchema = z.object({\n * title: z.string().min(1),\n * content: z.string(),\n * status: z.enum([\"draft\", \"published\"]),\n * authorId: z.string(),\n * });\n *\n * export const api = functions.https.onRequest(\n * createCrudServer({\n * basePath: \"/api\",\n * repos: {\n * posts: {\n * repo: repos.posts,\n * schema: postSchema,\n * path: \"posts\",\n * fieldsConfig: {\n * status: [\"filterable\"],\n * authorId: [\"filterable\"],\n * },\n * allowDelete: true,\n * },\n * },\n * })\n * );\n * ```\n *\n * ## API Endpoints\n *\n * | Method | Path | Description |\n * |--------|-------------------|--------------------------|\n * | GET | /:repo | List documents (paginated) |\n * | GET | /:repo/:id | Get single document |\n * | POST | /:repo | Create document |\n * | PUT | /:repo/:id | Update document (full) |\n * | PATCH | /:repo/:id | Update document (partial)|\n * | DELETE | /:repo/:id | Delete document |\n *\n * ## Query Parameters (GET list)\n *\n * | Param | Description |\n * |------------|------------------------------------------|\n * | pageSize | Number of items per page (max 100) |\n * | cursor | Base64 pagination cursor |\n * | orderBy | Field to order by |\n * | orderDir | Order direction (asc/desc) |\n * | select | Comma-separated fields to return |\n * | field | Filter by field (field=value) |\n * | field__op | Filter with operator (field__gt=10) |\n *\n * ## Filter Operators\n *\n * | Suffix | Firestore Op | Example |\n * |-------------|-------------------|-----------------------|\n * | (none) | == | status=active |\n * | __eq | == | status__eq=active |\n * | __ne | != | status__ne=draft |\n * | __lt | < | age__lt=18 |\n * | __lte | <= | age__lte=18 |\n * | __gt | > | age__gt=18 |\n * | __gte | >= | age__gte=18 |\n * | __in | in | status__in=a,b,c |\n * | __nin | not-in | status__nin=x,y |\n * | __contains | array-contains | tags__contains=news |\n */\n\nimport { MiniRouter } from \"../admin/router\";\nimport { isAuthExtension } from \"../auth\";\nimport type { HttpsOptions } from \"firebase-functions/v2/https\";\nimport type { HttpRequest, HttpResponse } from \"../http-types\";\nimport type { ConfiguredRepository } from \"../../repositories/types\";\nimport { createCrudHandlers } from \"./handlers\";\nimport { generateOpenAPISpec, type OpenAPIDocument } from \"./openapi\";\nimport type {\n CrudRepoEntry,\n CrudRepoRegistry,\n CrudServerOptions,\n} from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Scalar API docs HTML template\n// ---------------------------------------------------------------------------\n\n/** Returns a self-contained HTML page using Scalar to render the spec. */\nfunction scalarDocsHtml(title: string, specUrl: string): string {\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>${title}</title>\n</head>\n<body>\n <script id=\"api-reference\" data-url=\"${specUrl}\"></script>\n <script src=\"https://cdn.jsdelivr.net/npm/@scalar/api-reference\"></script>\n</body>\n</html>`;\n}\n\nimport { getLinkBase } from \"../utils/link-base\";\nimport { securityHeaders } from \"../utils/security-headers\";\n\n// ---------------------------------------------------------------------------\n// Body parser\n// ---------------------------------------------------------------------------\n\n/** Eagerly reads the raw request body as a string */\nasync function readRawBody(req: HttpRequest): Promise<string> {\n if (typeof (req as any).rawBody === \"string\")\n return (req as any).rawBody as string;\n if (Buffer.isBuffer((req as any).rawBody))\n return ((req as any).rawBody as Buffer).toString(\"utf8\");\n return \"\";\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Creates an Express-compatible request handler for a REST CRUD API.\n *\n * @template TRepos - Shape of the repos map (inferred automatically)\n * @param options - CRUD server configuration\n * @returns Express-compatible request handler for Firebase Functions\n *\n * @example\n * ```typescript\n * // Basic CRUD server\n * import { onRequest } from \"firebase-functions/https\";\n * import { createCrudServer } from \"@lpdjs/firestore-repo-service/servers/crud\";\n *\n * export const api = onRequest(\n * createCrudServer({\n * basePath: \"/api\",\n * repos: {\n * users: {\n * repo: repos.users,\n * path: \"users\",\n * fieldsConfig: {\n * name: [\"create\", \"mutable\"],\n * email: [\"create\", \"mutable\", \"filterable\"],\n * isActive: [\"filterable\"],\n * },\n * allowDelete: false,\n * },\n * posts: {\n * repo: repos.posts,\n * path: \"posts\",\n * fieldsConfig: {\n * status: [\"filterable\"],\n * userId: [\"filterable\"],\n * },\n * allowDelete: true,\n * },\n * },\n * })\n * );\n *\n * // With authentication\n * export const api = onRequest(\n * createCrudServer({\n * basePath: \"/api\",\n * auth: {\n * type: \"basic\",\n * username: \"api\",\n * password: process.env.API_PASSWORD!,\n * },\n * repos: { ... },\n * })\n * );\n *\n * // With custom auth middleware\n * export const api = onRequest(\n * createCrudServer({\n * auth: async (req, res, next) => {\n * const token = req.headers?.authorization?.replace(\"Bearer \", \"\");\n * if (!token || !(await verifyToken(token))) {\n * res.status(401).json({ success: false, error: \"Unauthorized\" });\n * return;\n * }\n * next();\n * },\n * repos: { ... },\n * })\n * );\n *\n * // With custom validation\n * export const api = onRequest(\n * createCrudServer({\n * repos: {\n * posts: {\n * repo: repos.posts,\n * path: \"posts\",\n * validate: async (data, operation) => {\n * if (operation === \"create\" && !data.title) {\n * return \"Title is required\";\n * }\n * return undefined;\n * },\n * },\n * },\n * })\n * );\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 auth,\n middleware: extraMiddleware = [],\n verbose = false,\n httpsOptions,\n } = options;\n\n // Normalise basePath: no trailing slash\n const base = basePath === \"/\" ? \"\" : basePath.replace(/\\/$/, \"\");\n\n // Build the registry\n const registry: CrudRepoRegistry = {};\n for (const [name, cfg] of Object.entries(repos)) {\n // Schema resolution: explicit cfg.schema > embedded in repo (createRepositoryConfig(schema))\n const resolvedSchema = cfg.schema ?? (cfg.repo as any).schema ?? null;\n if (!resolvedSchema) {\n throw new Error(\n `[createCrudServer] Repository \"${name}\" has no Zod schema. ` +\n `Either use createRepositoryConfig(schema)(config) or pass schema: explicitly.`,\n );\n }\n\n // Resolve fieldsConfig → separate arrays for runtime\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 // Fail-closed sort whitelist: when no field is explicitly \"orderable\",\n // reuse the filterable set so existing configs keep working but fields\n // that are neither filterable nor orderable cannot be sorted on (#03).\n if (orderableFields.length === 0) orderableFields = filterableFields;\n if (filterableFields.length === 0) filterableFields = undefined;\n if (orderableFields && orderableFields.length === 0)\n orderableFields = undefined;\n if (mutableFields.length === 0) mutableFields = undefined;\n if (createFields.length === 0) createFields = undefined;\n }\n\n // For collection-group repos, ensure parentKeys are included in createFields\n // so the validation accepts them in the request body.\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 authEnabled = !!auth;\n const handlers = createCrudHandlers(registry, base, verbose, authEnabled);\n\n // ── OpenAPI spec (cached) ─────────────────────────────────────────────\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 const authType = !auth\n ? false\n : isAuthExtension(auth) || typeof auth === \"function\"\n ? (\"bearer\" as const)\n : (\"basic\" as const);\n _specCache = generateOpenAPISpec(registry, base, {\n ...openapiOpts,\n auth: openapiOpts.auth ?? authType,\n });\n }\n return _specCache;\n }\n\n // ── Router ─────────────────────────────────────────────────────────────\n const router = new MiniRouter();\n\n // ── Security headers (runs first). CSP defaults off for the JSON API so the\n // bundled Scalar docs UI keeps loading; callers can opt in via options.\n if (securityHeadersOpt !== false) {\n const base0 =\n securityHeadersOpt === undefined ? { csp: false as const } : securityHeadersOpt;\n router.use(securityHeaders(base0));\n }\n\n // ── CORS middleware ─────────────────────────────────────────────────────\n router.use((req, res, next) => {\n res.set(\"Access-Control-Allow-Origin\", \"*\");\n res.set(\"Access-Control-Allow-Credentials\", \"true\");\n next();\n });\n\n // ── 1. Body-parsing middleware ──────────────────────────────────────────\n if (parseBody) {\n router.use(async (req, _res, next) => {\n const r = req as unknown as HttpRequest;\n const contentType = String(r.headers?.[\"content-type\"] ?? \"\");\n if (contentType.includes(\"application/json\")) {\n if (typeof r.body === \"string\") {\n try {\n (req as any).body = JSON.parse(r.body);\n } catch {\n /* keep as string */\n }\n } else if (Buffer.isBuffer((req as any).rawBody)) {\n try {\n const raw = await readRawBody(r);\n (req as any).body = JSON.parse(raw);\n } catch {\n /* keep as is */\n }\n }\n }\n await next();\n });\n }\n\n // ── 2. Auth middleware ──────────────────────────────────────────────────\n if (auth) {\n if (isAuthExtension(auth)) {\n // Mount login/session/logout routes BEFORE the protected chain.\n for (const route of auth.routes) {\n const mountPath = `${base}${route.path}`;\n if (route.method === \"GET\") router.get(mountPath, route.handler);\n else router.post(mountPath, route.handler);\n }\n router.use(auth.middleware);\n } else if (typeof auth === \"function\") {\n // Custom middleware\n router.use(auth);\n } else {\n // HTTP Basic Auth\n const realm = auth.realm ?? \"API\";\n const expected =\n \"Basic \" +\n Buffer.from(`${auth.username}:${auth.password}`).toString(\"base64\");\n router.use((req, res, next) => {\n const authorization = (req as any).headers?.[\"authorization\"] ?? \"\";\n if (authorization !== expected) {\n res\n .status(401)\n .set(\"WWW-Authenticate\", `Basic realm=\"${realm}\"`)\n .set(\"Content-Type\", \"application/json\")\n .send(JSON.stringify({ success: false, error: \"Unauthorized\" }));\n return;\n }\n next();\n });\n }\n }\n\n // ── 3. Extra user middleware ────────────────────────────────────────────\n for (const mw of extraMiddleware) {\n router.use(mw);\n }\n\n // ── 4. Routes ─────────────────────────────────────────────────────────────\n\n // ── OpenAPI spec & docs endpoints (before auth so they're public) ────\n if (openapi !== false) {\n const specPath = `${base}/__spec.json`;\n const docsPath = `${base}/__docs`;\n\n router.get(specPath, (_req: any, res: any) => {\n const spec = getSpec();\n res\n .status(200)\n .set(\"Content-Type\", \"application/json; charset=utf-8\")\n .send(JSON.stringify(spec, null, 2));\n });\n\n router.get(docsPath, (req: any, res: any) => {\n // Rebuild spec URL with the correct prefix for the current context\n // (emulator, Cloud Functions URL, or custom domain).\n const specUrl = getLinkBase(req, base) + \"/__spec.json\";\n const html = scalarDocsHtml(openapiOpts.title ?? \"CRUD API\", specUrl);\n res\n .status(200)\n .set(\"Content-Type\", \"text/html; charset=utf-8\")\n .send(html);\n });\n }\n\n // OPTIONS for CORS preflight\n router.use((req, res, next) => {\n if (req.method === \"OPTIONS\") {\n handlers.handleOptions(req, res);\n return;\n }\n next();\n });\n\n // List: GET /:repoName\n router.get(`${base}/:repoName`, handlers.handleList);\n\n // Query: POST /:repoName/query (advanced filtering with body)\n router.post(`${base}/:repoName/query`, handlers.handleQuery);\n\n // Get: GET /:repoName/:id\n router.get(`${base}/:repoName/:id`, handlers.handleGet);\n\n // Create: POST /:repoName\n router.post(`${base}/:repoName`, handlers.handleCreate);\n\n // Update (full): PUT /:repoName/:id\n router.put(`${base}/:repoName/:id`, (req: any, res: any) =>\n handlers.handleUpdate(req, res, false),\n );\n\n // Update (partial): PATCH /:repoName/:id\n router.patch(`${base}/:repoName/:id`, (req: any, res: any) =>\n handlers.handleUpdate(req, res, true),\n );\n\n // Delete: DELETE /:repoName/:id\n router.delete(`${base}/:repoName/:id`, handlers.handleDelete);\n\n // ── Request handler ─────────────────────────────────────────────────────\n const handler = async (\n req: HttpRequest,\n res: HttpResponse,\n ): Promise<void> => {\n await router.handle(req as any, res as any);\n };\n\n // Attach spec getter so users can call server.spec() programmatically\n (handler as any).spec = getSpec;\n if (httpsOptions) (handler as any).httpsOptions = httpsOptions;\n\n return handler as ((req: any, res: any) => Promise<void>) & {\n /** Return the generated OpenAPI 3.1 document. */\n spec: () => OpenAPIDocument;\n /** Options to forward to `onRequest()` from firebase-functions. */\n httpsOptions?: HttpsOptions;\n };\n}\n\n// Re-exports for convenience\nexport { generateOpenAPISpec } from \"./openapi\";\nexport type { OpenAPIDocument, OpenAPISpecOptions } from \"./openapi\";\nexport type {\n ApiResponse,\n BasicAuthConfig,\n CrudRepoConfig,\n CrudRepoEntry,\n CrudRepoRegistry,\n CrudServerOptions,\n FieldRole,\n ListResponseData,\n Middleware,\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","parseFilters","query","filterableFields","allowedFields","opMap","key","rawVal","val","match","op","opKey","parsedVal","parseValue","num","serializeCursor","snapshot","deserializeCursor","entry","cursor","docId","colRef","createCrudHandlers","registry","basePath","assertRule","rule","applyRowFilter","user","params","docs","filter","doc","userOf","getRepoEntry","repoName","extractPathArgs","pathKey","fullPath","args","fetchDocById","getterName","getter","handleList","ctxFilters","ctxSort","pageSize","direction","orderBy","orderDir","selectStr","select","s","includes","inc","queryOptions","cursorObj","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","schemaRef","name","errorResponse","description","successResponse","dataSchema","listResponse","itemSchema","paginationParams","filterParams","ops","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","parsed","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":"qtBAAA,IAAAA,EAAAA,CAAA,GAAAC,EAAAA,CAAAD,EAAAA,CAAA,sBAAAE,EAAAA,CAAA,eAAA,CAAA,IAAAC,KAsEO,SAASA,EAAAA,CAAgBC,EAA+B,EAAC,CAAG,CACjE,IAAMC,CAAAA,CAAMD,EAAK,GAAA,GAAQ,MAAA,CAAYF,GAAmBE,CAAAA,CAAK,GAAA,CACvDE,EAAeF,CAAAA,CAAK,YAAA,GAAiB,OAAY,MAAA,CAASA,CAAAA,CAAK,aAC/DG,CAAAA,CACJH,CAAAA,CAAK,iBAAmB,MAAA,CAAY,aAAA,CAAgBA,EAAK,cAAA,CACrDI,CAAAA,CACJJ,EAAK,YAAA,GAAiB,MAAA,CAAY,oBAAs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E,MAAA,CAAO,kCAAA,CAAoC,MAAM,CAAA,CACnD,MAAMA,CAAAA,GAER,EACA,GAAIsN,CAAAA,CAAQ,aAAe,EAC7B,CACF,CAAC,CAAA,CAMD,GAJIiI,IAAY,KAAA,GACdI,CAAAA,CAAO,iBAAmBD,CAAAA,CAAAA,CAGxBd,CAAAA,GAAuB,MAAO,CAChC,GAAM,CAAE,eAAA,CAAApV,CAAgB,CAAA,eAClBoW,CAAAA,CAAQhB,CAAAA,GAAuB,OAAY,CAAE,GAAA,CAAK,KAAe,CAAA,CAAIA,CAAAA,CAC3Ee,CAAAA,CAAO,IAAA,CAAK,GAAA,CAAI,GAAA,CAAK,MAAOhS,CAAAA,CAAG3D,CAAAA,GAAS,CACtC,IAAM6V,CAAAA,CAAUrW,EAAgBoW,CAAK,CAAA,CACrC,MAAM,IAAI,OAAA,CAAeE,CAAAA,EAAY,CACnC,IAAMC,CAAAA,CAAUpS,EAAE,GAAA,CAAI,GAAA,CAKtBkS,EAAQE,CAAAA,CAJQ,CACd,SAAA,CAAW,CAACnQ,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,IAAMkQ,CAAAA,EAAS,EAC3C,CAAC,EACD,MAAM9V,CAAAA,GACR,CAAC,EACH,CAEA,IAAMiS,CAAAA,CAAU0D,CAAAA,CAAO,WAAA,CACvB,OAAA1D,CAAAA,CAAQ,IAAA,CAAOyD,EACX1D,CAAAA,GAAcC,CAAAA,CAAQ,YAAA,CAAeD,CAAAA,CAAAA,CAElCC,CACT","file":"index.cjs","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 {\n isMissingIndexError,\n toQueryError,\n type QueryErrorContext,\n} 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>(c: any, data: T, meta?: ApiResponse[\"meta\"], status = 200) {\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(c: any, err: unknown, ctx: QueryErrorContext, fallbackMessage: string, verbose: boolean) {\n const qe = toQueryError(err, ctx);\n const isIndex = qe.type === \"index\";\n const status = isIndex ? 424 : 500;\n const message = isIndex ? qe.message : verbose && err instanceof Error ? err.message : 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\") 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 { docId: snapshot.id };\n}\n\n/**\n * Deserialize a cursor object back to a DocumentSnapshot.\n * Fetches the document from Firestore to get the actual snapshot.\n */\nasync function deserializeCursor(\n entry: CrudRepoEntry,\n cursor: unknown,\n): Promise<import(\"firebase-admin/firestore\").DocumentSnapshot | undefined> {\n if (!cursor || typeof cursor !== \"object\") return undefined;\n const docId = (cursor as Record<string, unknown>).docId;\n if (typeof docId !== \"string\") return undefined;\n\n try {\n // Get the collection reference from the repo\n const colRef = entry.repo\n .ref as import(\"firebase-admin/firestore\").CollectionReference;\n if (typeof colRef.doc !== \"function\") return undefined;\n const snapshot = await colRef.doc(docId).get();\n return snapshot.exists ? snapshot : 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>(c: any, entry: CrudRepoEntry, op: keyof NonNullable<CrudRepoEntry[\"rules\"]>, ctx: TCtx): 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(\n c,\n `Operation \"${op}\" is not allowed for this repository`,\n 403,\n );\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: { user: any; doc: T; params: Record<string, string> }) =>\n | boolean\n | 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 || !registry[repoName]) {\n return sendError(c, `Repository \"${repoName}\" not found`, 404);\n return null;\n }\n return registry[repoName];\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;\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 = filters.map((f) => [f.field, f.op, f.value]);\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;\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;\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;\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 =\n 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;\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 =\n 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;\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;\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 (!(await assertRule(c, entry, \"create\", { user, body: op.data, params }))) return;\n const validation = validateData(entry.schema, op.data, entry.createFields, false, entry.systemKeys);\n if (!validation.success) 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((k: string) => data[k] as string);\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) return sendError(c, `Document ${op.id} not found`, 404);\n \n if (!(await assertRule(c, entry, \"update\", { user, doc: existingDoc as any, body: op.data, params }))) return;\n \n const validation = validateData(entry.schema, op.data, entry.mutableFields, true, entry.systemKeys);\n if (!validation.success) return sendError(c, (validation as any).error, 400);\n \n const pathArgs = extractPathArgs(existingDoc, entry.pathKey) ?? [op.id];\n batch.update(...pathArgs, validation.data);\n results.push({ op: 'update', id: op.id });\n } else if (op.type === 'delete') {\n if (!entry.allowDelete) 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 (!(await assertRule(c, entry, \"delete\", { user, doc: doc as any, params }))) 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 = verbose && err instanceof Error ? err.message : \"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","/**\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 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 def: any = (ctx.zodSchema as any)?._zod?.def;\n if (!def) return;\n if (def.type === \"date\") {\n (ctx.jsonSchema as any).type = \"string\";\n (ctx.jsonSchema as any).format = \"date-time\";\n } else if (def.type === \"bigint\") {\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 = [\"eq\", \"ne\", \"lt\", \"lte\", \"gt\", \"gte\", \"in\", \"nin\", \"contains\"];\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)`,\n });\n // Operator filters: ?field__op=value\n for (const op of ops) {\n params.push({\n name: `${field}__${op}`,\n in: \"query\",\n schema: { type: \"string\" },\n description: `Filter ${field} with operator ${op}`,\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 // ── 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 // 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 if (inputSchema) {\n let raw: unknown;\n try {\n raw = await readPayload(c, source, route.method);\n } catch (err) {\n // Body parse failure → wrap as a generic Error so the interceptor\n // can decide. Use a 400-shaped Error subclass.\n throw new BadRequestError(\n err instanceof Error ? err.message : String(err),\n );\n }\n const parsed = inputSchema.safeParse(raw);\n if (!parsed.success) {\n throw new ValidationError(parsed.error, source);\n }\n payload = parsed.data;\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 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"]}