@lpdjs/firestore-repo-service 3.0.20 → 3.0.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/servers/utils/security-headers.ts","../../../src/shared/actor-context.ts","../../../src/history/types.ts","../../../src/history/inject.ts","../../../src/shared/date-config.ts","../../../src/shared/path-template.ts","../../../src/shared/zod-compat.ts","../../../src/servers/admin/index-url.ts","../../../src/history/diff.ts","../../../src/servers/crud/rules.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/mutations.ts","../../../src/servers/crud/effects.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","DEFAULT_HISTORY_REASON_HEADER","DEFAULT_HISTORY_COMMENT_HEADER","ACTOR_RESOLVER_HEADERS_SYMBOL","ALS_SYMBOL","g","actorStorage","AsyncLocalStorage","readFieldPath","obj","path","cur","part","pickFirstString","paths","p","val","readHeader","c","name","headerFn","createActorResolver","config","contextKeys","userIdFields","userEmailFields","reasonHeader","commentHeader","displayReasonHeader","displayCommentHeader","extrasFn","resolver","user","getFn","key","candidate","reason","comment","extras","getActorResolverHeaders","option","meta","normalizeActorResolver","createActorContextMiddleware","normalized","DEFAULT_HISTORY_SHADOW_KEY","resolveShadowConfig","shadowOpt","customFields","currentMode","getDateHandling","isTimestampLike","v","coerceToDate","value","Timestamp","d","maybeNormalize","ID_CHARS","generateFirestoreId","id","bytes","randomBytes","i","byte","extractSegmentParam","segment","parsePathTemplate","rawPath","documentKey","isGroup","segments","s","seg","isEvenSegments","collectionSegments","collectionId","collectionPath","parentKeys","documentPathTemplate","extractPathArgsFromDoc","doc","options","pathKey","fullPath","pathSegments","tplSegments","extracted","expectedCount","oddSegments","docIdVal","parentVals","allPresent","pk","getArrayElementType","schema","RANGE_OPS","ARRAY_OPS","toIndexOrder","dir","collectionIdFromPath","buildIndexUrl","projectId","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","bin","b64","field","extractProjectId","ref","r","candidates","isMissingIndexError","err","fe","toQueryError","ctx","isIndex","indexUrl","colId","valuesEqual","a","b","ka","kb","k","computeDeepDiff","before","changesInput","beforeObj","changes","after","oldVal","createRules","rules","applyRules","diff","rulesMap","rule","createBeforeRules","MAX_CRUD_PAGE_SIZE","parseCrudPageSize","raw","defaultPageSize","num","sendJson","data","status","sendSuccess","sendError","error","sendQueryError","fallbackMessage","verbose","onIndexError","qe","cbErr","wrapDateSchemas","def","typeName","z","shape","wrapped","inner","dflt","pickSchemaFields","systemKeys","picked","source","topLevel","unwrapZodType","zodType","resolveFieldPathSchema","entrySchema","parts","rawSub","makeDeepPartial","newShape","nextInner","nextOptions","opt","validateData","partial","dataObj","resultData","normalEntries","fieldSchema","effectiveFieldSchema","parsedValue","targetSchema","partialSchema","parsedNormal","e","OP_MAP","normalizeWhereOp","op","isValidOp","parseFieldValue","normalizedOp","unwrapped","elemSchema","parsed","parsedArray","item","itemParsed","parseFilters","query","filterableFields","allowedFields","rawVal","lastDoubleUnderscore","fieldCandidate","opKey","parsedVal","parseValue","serializeCursor","snapshot","deserializeCursor","entry","cursor","cursorObj","docPath","docId","colRef","firestore","pickDefinedChanges","defined","count","createCrudHandlers","registry","basePath","onHookError","reportHookError","logger","errCtx","handled","assertRule","applyRowFilter","params","docs","filter","userOf","getRepoEntry","repoName","extractPathArgs","fetchDocById","getterName","getter","handleList","ruleCheck","ctxFilters","ctxSort","pageSizeRes","pageSize","direction","orderBy","orderDir","selectStr","select","withTotalParam","withTotal","includes","inc","queryOptions","parsedRes","result","responseData","handleQuery","body","w","validIncludes","allowed","invalid","parsedWhere","parsedOrWhere","group","parsedOrWhereGroups","parsedGroup","o","handleGet","getRuleCheck","handleCreate","createRuleCheck","validation","customError","created","explicitPathArgs","missingKeys","parentIds","finalDoc","rawCreatedId","createdId","pathArgs","extraChanges","definedChanges","hookErr","handleUpdate","existingDoc","updateRuleCheck","preHookDiff","finalBody","finalDiff","updated","handleDelete","deleteRuleCheck","handleOptions","handleBatch","batch","results","hasHooks","createdItems","updatedItems","deletedItems","createdDoc","hasAnyOp","zodToJsonSchema","metadata","getOpenApiMetadata","schemaRef","errorResponse","description","successResponse","dataSchema","listResponse","itemSchema","copyMetadata","target","extractLeafFields","zodSchema","prefix","depth","fieldPath","subUnwrapped","getFilterableLeafFields","zodTypeToJsonValueSchema","jsonSchema","queryBodySchema","buildTypedQueryBodySchema","leafFields","orderableFieldNames","leafFieldNames","whereTuples","valSchema","whereItemSchema","resolveEntryHistoryFlags","historyConfig","shadow","buildHistoryHeaderParams","historyHeadersOpt","flags","seenLower","extra","spec","buildPathsForEntry","base","modelSchemaName","createSchemaName","updateSchemaName","patchSchemaName","querySchemaName","historyHeaderParams","tag","documentPath","idParam","capitalize","singularize","docOps","generateOpenAPISpec","title","version","servers","auth","schemas","allPaths","tags","modelName","createName","updateName","patchName","queryName","buildShape","fieldList","top","createShape","schemaShape","createJsonSchema","reqSet","updateShape","updateZodObj","createOpName","updateOpName","deleteOpName","entryPaths","securitySchemes","security","ValidationError","zodError","BadRequestError","OutputValidationError","formatZodIssues","defaultErrorResponse","extendZodWithOpenApi","DEFAULT_RESPONSE_DESCRIPTION","DEFAULT_ERROR_DESCRIPTION","ensureCustomSchemasHaveOpenApiType","visited","stripRedundantTypeWithComposition","node","record","defaultSource","method","resolveSuccessSchema","routeOutput","interceptor","normalizeErrorResponse","cfg","buildOpenApiDocument","routes","OpenAPIRegistry","scheme","route","joinPath","requestBody","buildRequestBody","requestQuery","buildQueryOrParam","requestParams","operationId","makeOperationId","successSchema","responses","code","convertExpressPathToOpenApi","document","OpenApiGeneratorV31","left","right","merged","cleaned","renderDocsHtml","specUrl","safeUrl","isDocsAuthExtension","als","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","inputSchema","outputSchema","servicesArg","applyErrorHandler","callNext","readPayload","checked","text","createMutations","mutations","runEntries","entries","applyMutations","mutationsMap","operation","createBeforeUpdateMutations","createBeforeCreateMutations","createEffects","effects","runEffectList","context","changesNeeded","isCalled","patch","applyEffects","effectsMap","createAfterUpdateEffects","buildContext","createCrudServer","repos","parseBody","securityHeadersOpt","resolvedSchema","orderableFields","mutableFields","createFields","fc","roles","role","baseSystemKeys","historyIdentityKeys","activeShadow","historyHeaders","indexesErrorCb","handlers","openapi","openapiOpts","resolvedActorHeaders","effectiveOpenApiHistoryHeaders","corsAllowHeaders","h","addHeader","trimmed","_specCache","getSpec","server","base0","adapter","resolve","fakeReq"],"mappings":"sVAAA,IAAA,EAAA,CAAA,MAAA,CAAA,cAAA,CAAA,IAAA,EAAA,CAAA,MAAA,CAAA,wBAAA,CAAA,IAAA,EAAA,CAAA,MAAA,CAAA,mBAAA,CAAA,IAAA,EAAA,CAAA,MAAA,CAAA,SAAA,CAAA,cAAA,CAAA,IAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,IAAA,CAAA,GAAA,CAAA,CAAA,MAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,OAAA,CAAA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C3C,CAAC,EACD,MAAMxjB,CAAAA,GACR,CAAC,EACH,CAEA,IAAMke,CAAAA,CAAUmF,EAAO,WAAA,CACvB,OAAAnF,CAAAA,CAAQ,IAAA,CAAOkF,CAAAA,CACXnF,CAAAA,GAAcC,CAAAA,CAAQ,YAAA,CAAeD,GAElCC,CACT","file":"index.js","sourcesContent":["/**\n * Default security-headers middleware for the bundled HTTP servers.\n *\n * Addresses issues #12 (no security headers / clickjacking / cache leakage)\n * and #13 (no CSP bounding the CDN origins loaded by the admin & login pages).\n *\n * The middleware is framework-agnostic: it only touches `res.setHeader`\n * (present on Node's `ServerResponse` and the shims used by the admin/CRUD\n * routers) and always calls `next()`.\n */\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyReq = any;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyRes = any;\ntype Next = () => void | Promise<void>;\n\n/** CDN/script origins the bundled admin UI and login page load from. */\nconst ADMIN_CDN = \"https://cdn.jsdelivr.net\";\nconst GSTATIC = \"https://www.gstatic.com\";\n\n/**\n * Reasonable default Content-Security-Policy for the bundled **HTML** pages\n * (admin UI + login). Allows the specific CDN origins the pages need and\n * forbids framing entirely. `'unsafe-inline'`/`'unsafe-eval'` are required by\n * the Tailwind browser build and the small inline bootstrap scripts.\n */\nexport const DEFAULT_HTML_CSP = [\n \"default-src 'self'\",\n `script-src 'self' 'unsafe-inline' 'unsafe-eval' ${ADMIN_CDN} ${GSTATIC}`,\n `style-src 'self' 'unsafe-inline' ${ADMIN_CDN}`,\n `connect-src 'self' ${GSTATIC} https://*.googleapis.com https://*.firebaseio.com https://identitytoolkit.googleapis.com`,\n \"img-src 'self' data:\",\n \"font-src 'self' data:\",\n \"frame-ancestors 'none'\",\n \"base-uri 'self'\",\n \"form-action 'self'\",\n].join(\"; \");\n\nexport interface SecurityHeadersOptions {\n /**\n * Content-Security-Policy value. Pass a string to override, or `false` to\n * omit the header entirely. Defaults to {@link DEFAULT_HTML_CSP} for HTML\n * servers (admin/login) and is omitted for pure JSON APIs unless provided.\n */\n csp?: string | false;\n /**\n * `X-Frame-Options` value. Default `\"DENY\"`. Pass `false` to omit (e.g. when\n * the app must be embedded in a trusted iframe — prefer a CSP\n * `frame-ancestors` allowlist instead).\n */\n frameOptions?: string | false;\n /** `Referrer-Policy` value. Default `\"no-referrer\"`. */\n referrerPolicy?: string | false;\n /**\n * `Cache-Control` value. Default `\"private, no-store\"` to keep private data\n * out of shared proxy caches. Pass `false` to leave caching to handlers.\n */\n cacheControl?: string | false;\n}\n\n/**\n * Build a middleware that sets a baseline of security response headers.\n *\n * @example\n * ```ts\n * router.use(securityHeaders()); // HTML-safe defaults\n * router.use(securityHeaders({ csp: false })); // JSON API (no CSP)\n * ```\n */\nexport function securityHeaders(opts: SecurityHeadersOptions = {}) {\n const csp = opts.csp === undefined ? DEFAULT_HTML_CSP : opts.csp;\n const frameOptions = opts.frameOptions === undefined ? \"DENY\" : opts.frameOptions;\n const referrerPolicy =\n opts.referrerPolicy === undefined ? \"no-referrer\" : opts.referrerPolicy;\n const cacheControl =\n opts.cacheControl === undefined ? \"private, no-store\" : opts.cacheControl;\n\n return async (_req: AnyReq, res: AnyRes, next: Next): Promise<void> => {\n if (typeof res?.setHeader === \"function\") {\n res.setHeader(\"X-Content-Type-Options\", \"nosniff\");\n if (frameOptions) res.setHeader(\"X-Frame-Options\", frameOptions);\n if (referrerPolicy) res.setHeader(\"Referrer-Policy\", referrerPolicy);\n if (cacheControl) res.setHeader(\"Cache-Control\", cacheControl);\n if (csp) res.setHeader(\"Content-Security-Policy\", csp);\n }\n await next();\n };\n}\n","/**\n * Request-scoped & programmatic actor context backed by `AsyncLocalStorage`.\n *\n * Uses a `globalThis[Symbol.for(...)]` singleton so separate tsup bundles\n * (`dist/index`, `dist/servers/hono`, `dist/servers/crud`, `dist/history`,\n * `dist/servers/index`) always share the exact same `AsyncLocalStorage`\n * instance.\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { Context, MiddlewareHandler } from \"hono\";\n\n/** Actor & audit metadata captured for history writes. */\nexport interface HistoryActor {\n userId?: string | null;\n userEmail?: string | null;\n reason?: string | null;\n comment?: string | null;\n extras?: Record<string, unknown>;\n}\n\n/** Function resolving the current actor lazily from a Hono `Context`. */\nexport type ActorResolver = (c: Context) => HistoryActor | null | undefined;\n\n/**\n * Declarative configuration for {@link createActorResolver} so projects can\n * customize context keys, nested user property paths, and request headers\n * without writing a full resolver from scratch.\n */\nexport interface ActorResolverFieldConfig {\n /**\n * Hono context keys inspected in order via `c.get(key)`.\n * Default: `[\"user\", \"docsUser\"]`.\n */\n contextKeys?: string[];\n /**\n * Property paths on the user object checked in order for `userId`.\n * Supports dot-notation (e.g. `\"baseUser.id\"`).\n * Default: `[\"uid\", \"id\", \"sub\"]`.\n */\n userIdFields?: string[];\n /**\n * Property paths on the user object checked in order for `userEmail`.\n * Supports dot-notation (e.g. `\"baseUser.email\"`).\n * Default: `[\"email\"]`.\n */\n userEmailFields?: string[];\n /**\n * HTTP header name for change reason, or `false` to disable header lookup.\n * Default: `\"x-history-reason\"`.\n */\n reasonHeader?: string | false;\n /**\n * HTTP header name for change comment, or `false` to disable header lookup.\n * Default: `\"x-history-comment\"`.\n */\n commentHeader?: string | false;\n /**\n * Optional extractor to populate `actor.extras` from `(c, user)`.\n */\n extras?: (\n c: Context,\n user: Record<string, unknown> | null,\n ) => Record<string, unknown> | undefined;\n}\n\n/**\n * Accepted by `HonoServerOptions.actorResolver`, `ApiRegistryOptions.actorResolver`,\n * `CrudServerOptions.actorResolver`, and `CreateServersDeps.actorResolver`:\n * either a custom resolver function or a declarative field-mapping config.\n */\nexport type ActorResolverOption = ActorResolver | ActorResolverFieldConfig;\n\n/** Canonical default HTTP header name for change reason. */\nexport const DEFAULT_HISTORY_REASON_HEADER = \"X-History-Reason\";\n\n/** Canonical default HTTP header name for change comment. */\nexport const DEFAULT_HISTORY_COMMENT_HEADER = \"X-History-Comment\";\n\n/** Resolved history audit header names exposed by an `actorResolver`. */\nexport interface ResolvedHistoryHeaderNames {\n reasonHeader: string | false;\n commentHeader: string | false;\n}\n\nconst ACTOR_RESOLVER_HEADERS_SYMBOL = Symbol.for(\n \"@lpdjs/firestore-repo-service:actorResolverHeaders\",\n);\n\ninterface ActorStore {\n c?: Context;\n resolver?: ActorResolver;\n override?: Partial<HistoryActor>;\n}\n\nconst ALS_SYMBOL = Symbol.for(\"@lpdjs/firestore-repo-service:actorContext\");\nconst g = globalThis as Record<\n symbol,\n AsyncLocalStorage<ActorStore> | undefined\n>;\nconst actorStorage = (g[ALS_SYMBOL] ??= new AsyncLocalStorage<ActorStore>());\n\n/** Safely traverse a dot-notation path (e.g. `\"baseUser.email\"`) on an object. */\nfunction readFieldPath(\n obj: Record<string, unknown>,\n path: string,\n): unknown {\n if (!path.includes(\".\")) return obj[path];\n let cur: unknown = obj;\n for (const part of path.split(\".\")) {\n if (!cur || typeof cur !== \"object\") return undefined;\n cur = (cur as Record<string, unknown>)[part];\n }\n return cur;\n}\n\n/** Pick the first non-empty string/number value across candidate paths. */\nfunction pickFirstString(\n obj: Record<string, unknown>,\n paths: string[],\n): string | null {\n for (const p of paths) {\n const val = readFieldPath(obj, p);\n if (typeof val === \"string\" && val.length > 0) return val;\n if (typeof val === \"number\") return String(val);\n }\n return null;\n}\n\n/** Read an HTTP header safely from a Hono `Context` (tolerates minimal mocks). */\nfunction readHeader(c: Context, name: string | false): string | undefined {\n if (name === false) return undefined;\n const headerFn = (c as any)?.req?.header;\n if (typeof headerFn !== \"function\") return undefined;\n const val = headerFn.call((c as any).req, name);\n return typeof val === \"string\" && val.length > 0 ? val : undefined;\n}\n\n/**\n * Build an {@link ActorResolver} from a declarative field/header configuration.\n *\n * @example\n * ```ts\n * const actorResolver = createActorResolver({\n * contextKeys: [\"authUser\", \"user\"],\n * userIdFields: [\"docId\", \"uid\"],\n * userEmailFields: [\"baseUser.email\", \"email\"],\n * reasonHeader: \"x-audit-reason\",\n * });\n * ```\n */\nexport function createActorResolver(\n config: ActorResolverFieldConfig = {},\n): ActorResolver {\n const contextKeys = config.contextKeys ?? [\"user\", \"docsUser\"];\n const userIdFields = config.userIdFields ?? [\"uid\", \"id\", \"sub\"];\n const userEmailFields = config.userEmailFields ?? [\"email\"];\n const reasonHeader =\n config.reasonHeader === undefined ? \"x-history-reason\" : config.reasonHeader;\n const commentHeader =\n config.commentHeader === undefined\n ? \"x-history-comment\"\n : config.commentHeader;\n const displayReasonHeader: string | false =\n config.reasonHeader === undefined\n ? DEFAULT_HISTORY_REASON_HEADER\n : config.reasonHeader;\n const displayCommentHeader: string | false =\n config.commentHeader === undefined\n ? DEFAULT_HISTORY_COMMENT_HEADER\n : config.commentHeader;\n const extrasFn = config.extras;\n\n const resolver: ActorResolver = (c: Context): HistoryActor | null => {\n let user: Record<string, unknown> | null = null;\n const getFn = (c as any)?.get;\n if (typeof getFn === \"function\") {\n for (const key of contextKeys) {\n const candidate = getFn.call(c, key);\n if (candidate && typeof candidate === \"object\") {\n user = candidate as Record<string, unknown>;\n break;\n }\n }\n }\n\n const reason = readHeader(c, reasonHeader);\n const comment = readHeader(c, commentHeader);\n const extras = extrasFn ? extrasFn(c, user) : undefined;\n\n if (!user) {\n if (reason === undefined && comment === undefined && !extras) {\n return null;\n }\n return {\n ...(reason !== undefined ? { reason } : {}),\n ...(comment !== undefined ? { comment } : {}),\n ...(extras ? { extras } : {}),\n };\n }\n\n return {\n userId: pickFirstString(user, userIdFields),\n userEmail: pickFirstString(user, userEmailFields),\n ...(reason !== undefined ? { reason } : {}),\n ...(comment !== undefined ? { comment } : {}),\n ...(extras ? { extras } : {}),\n };\n };\n\n Object.defineProperty(resolver, ACTOR_RESOLVER_HEADERS_SYMBOL, {\n value: {\n reasonHeader: displayReasonHeader,\n commentHeader: displayCommentHeader,\n } satisfies ResolvedHistoryHeaderNames,\n enumerable: false,\n configurable: false,\n });\n\n return resolver;\n}\n\n/**\n * Inspect an {@link ActorResolverOption} (declarative config object, resolver\n * created via {@link createActorResolver}, custom function, or `undefined`)\n * and return the effective history audit header names for OpenAPI / CORS.\n */\nexport function getActorResolverHeaders(\n option?: ActorResolverOption,\n): ResolvedHistoryHeaderNames {\n if (!option) {\n return {\n reasonHeader: DEFAULT_HISTORY_REASON_HEADER,\n commentHeader: DEFAULT_HISTORY_COMMENT_HEADER,\n };\n }\n if (typeof option === \"function\") {\n const meta = (option as any)[ACTOR_RESOLVER_HEADERS_SYMBOL] as\n | ResolvedHistoryHeaderNames\n | undefined;\n if (meta) return { ...meta };\n return {\n reasonHeader: DEFAULT_HISTORY_REASON_HEADER,\n commentHeader: DEFAULT_HISTORY_COMMENT_HEADER,\n };\n }\n return {\n reasonHeader:\n option.reasonHeader === undefined\n ? DEFAULT_HISTORY_REASON_HEADER\n : option.reasonHeader,\n commentHeader:\n option.commentHeader === undefined\n ? DEFAULT_HISTORY_COMMENT_HEADER\n : option.commentHeader,\n };\n}\n\n/**\n * Default actor resolver compatible with Firebase JWT / `firebaseBearerAuth` /\n * custom auth middlewares setting `c.get(\"user\")` or `c.get(\"docsUser\")`.\n */\nexport const defaultActorResolver: ActorResolver = createActorResolver();\n\n/** Normalize either a function resolver or a declarative config object. */\nexport function normalizeActorResolver(\n option?: ActorResolverOption,\n): ActorResolver | undefined {\n if (!option) return undefined;\n return typeof option === \"function\" ? option : createActorResolver(option);\n}\n\n/**\n * Hono middleware mounted automatically at the top of `HonoServer`.\n * Stores `{ c, resolver }` in `AsyncLocalStorage` so downstream repository\n * writes resolve the authenticated user lazily after auth middlewares run.\n */\nexport function createActorContextMiddleware(\n resolver?: ActorResolverOption,\n): MiddlewareHandler {\n const normalized = normalizeActorResolver(resolver);\n return async (c, next) => {\n await actorStorage.run({ c, resolver: normalized }, async () => {\n await next();\n });\n };\n}\n\n/**\n * Resolve the active {@link HistoryActor} for the current async execution\n * context, or `null` when outside any scope or when no actor is available.\n */\nexport function getCurrentActor(): HistoryActor | null {\n const store = actorStorage.getStore();\n if (!store) return null;\n\n let fromReq: HistoryActor | null | undefined = null;\n if (store.c) {\n try {\n fromReq = (store.resolver ?? defaultActorResolver)(store.c);\n } catch {\n fromReq = null;\n }\n }\n\n if (!fromReq && !store.override) return null;\n\n const merged: HistoryActor = { ...(fromReq ?? {}) };\n if (store.override) {\n if (store.override.userId !== undefined) {\n merged.userId = store.override.userId;\n }\n if (store.override.userEmail !== undefined) {\n merged.userEmail = store.override.userEmail;\n }\n if (store.override.reason !== undefined) {\n merged.reason = store.override.reason;\n }\n if (store.override.comment !== undefined) {\n merged.comment = store.override.comment;\n }\n if (store.override.extras !== undefined) {\n merged.extras = {\n ...(fromReq?.extras ?? {}),\n ...store.override.extras,\n };\n }\n }\n\n return merged;\n}\n\n/**\n * Execute `fn` within an isolated actor scope — ideal for crons, Pub/Sub\n * workers, scripts, and unit tests.\n *\n * @example\n * ```ts\n * await withActor({ userId: \"cron:invoicing\", reason: \"monthly-run\" }, async () => {\n * await repos.invoices.create(payload);\n * });\n * ```\n */\nexport function withActor<T>(actor: HistoryActor, fn: () => T): T {\n return actorStorage.run({ override: { ...actor } }, fn);\n}\n\n/**\n * Enrich or override actor metadata (`reason`, `comment`, `extras`, …) for the\n * current active request / `withActor` scope without touching repository calls.\n *\n * Safe no-op returning `false` when called outside any active ALS scope.\n */\nexport function setRequestActorMeta(meta: Partial<HistoryActor>): boolean {\n const store = actorStorage.getStore();\n if (!store) return false;\n\n const prev = store.override ?? {};\n const nextOverride: Partial<HistoryActor> = { ...prev, ...meta };\n if (prev.extras || meta.extras) {\n nextOverride.extras = {\n ...(prev.extras ?? {}),\n ...(meta.extras ?? {}),\n };\n }\n store.override = nextOverride;\n return true;\n}\n","/**\n * Types and interfaces for the history (change-log) module.\n *\n * The package writes history entries in **schema v2** (1 Firestore document\n * per `update`/`create`/`delete` event, with a `changes` map keyed by field\n * name). It reads both v1 (legacy: 1 doc per modified field) and v2 by\n * normalising them into a unified {@link HistoryEntry} shape.\n */\n\nimport type { Timestamp } from \"firebase-admin/firestore\";\nimport type {\n DocumentOptions,\n onDocumentWritten,\n} from \"firebase-functions/v2/firestore\";\n\n/**\n * Cloud Functions v2 options forwarded to `onDocumentWritten()` for history triggers.\n * The `document` field is omitted because the library sets it itself from the collection path.\n */\nexport type TriggerOptions = Omit<DocumentOptions, \"document\">;\nexport type HistoryTriggerOptions = TriggerOptions;\n\n/* ------------------------------------------------------------------------- */\n/* Public unified shape */\n/* ------------------------------------------------------------------------- */\n\nexport type HistoryOperation = \"create\" | \"update\" | \"delete\" | \"custom\";\n\n/**\n * Structured payload attached to `operation: \"custom\"` history entries\n * (business actions independent of model fields, e.g. manual invoice creation,\n * PDF export, email sent, etc.).\n */\nexport interface HistoryCustomData {\n /** Human-readable title (e.g. `\"Création de la facture\"`). */\n title: string;\n /** Optional human-readable description (e.g. `\"Facture #F-2026-042 créée manuellement\"`). */\n description?: string;\n /** Optional business action key for filtering/grouping/icons (e.g. `\"invoice_create_manually\"`). */\n key?: string;\n /** Optional front-end visibility flag (default: `true`). */\n display?: boolean;\n /** Optional arbitrary structured business payload (e.g. `{ invoiceId, amount }`). */\n data?: Record<string, unknown>;\n}\n\n/** Input payload accepted by `repo.history.recordCustom(...)`. */\nexport interface HistoryCustomInput extends HistoryCustomData {\n /**\n * Optional metadata overrides (`reason`, `comment`, `extras`, `userId`,\n * `userEmail`). Automatically merged on top of the active ALS actor.\n */\n meta?: HistoryMeta;\n}\n\n/**\n * Detected JS/Firestore type of a value as stored in a history entry.\n * Matches the values returned by {@link valueType}.\n */\nexport type HistoryValueType =\n | \"string\"\n | \"number\"\n | \"boolean\"\n | \"timestamp\"\n | \"date\"\n | \"array\"\n | \"object\"\n | \"null\"\n | \"undefined\";\n\n/** A single field change inside a history entry. */\nexport interface HistoryFieldChange {\n oldValue: unknown;\n newValue: unknown;\n type: { old: HistoryValueType; new: HistoryValueType };\n}\n\n/** Captured metadata for a history entry. */\nexport interface HistoryMeta {\n userId?: string | null;\n userEmail?: string | null;\n reason?: string | null;\n comment?: string | null;\n /** Free-form extra fields copied from the source document. */\n extras?: Record<string, unknown>;\n}\n\n/**\n * Unified history entry returned by `repo.history.list(...)`.\n * Both v1 and v2 documents are normalised into this shape.\n */\nexport interface HistoryEntry<T = Record<string, unknown>> {\n /** Stable id of the underlying Firestore history document (the v1+v2 storage doc). */\n historyDocId: string;\n /** Id of the entity this entry belongs to. */\n historyToObjectId: string;\n /** When the change was recorded. */\n historySetAt: Timestamp;\n /** Source schema version. v1 = legacy (1 doc/field), v2 = current (1 doc/update). */\n schemaVersion: 1 | 2;\n /** v2 only — v1 is always normalised to \"update\". */\n operation: HistoryOperation;\n /** Captured author / context information. */\n meta: HistoryMeta;\n /** Present on `operation: \"custom\"` entries (business actions independent of model fields). */\n custom?: HistoryCustomData;\n /** Per-field changes. Keys are field names of T. */\n changes: { [K in keyof T & string]?: HistoryFieldChange } & {\n [field: string]: HistoryFieldChange;\n };\n}\n\n/* ------------------------------------------------------------------------- */\n/* Storage-level shapes (what is actually written / read in Firestore) */\n/* ------------------------------------------------------------------------- */\n\n/** v2 document layout. */\nexport interface V2HistoryDoc {\n schemaVersion: 2;\n historyDocId: string;\n historyToObjectId: string;\n historySetAt: Timestamp;\n operation: HistoryOperation;\n meta: HistoryMeta;\n /** Present on `operation: \"custom\"` entries. */\n custom?: HistoryCustomData;\n changes: Record<string, HistoryFieldChange>;\n /** Optional TTL marker (Firestore deletes the doc after this date). */\n expiresAt?: Timestamp;\n /** Set when the doc had to be truncated to fit the 1 MiB limit. */\n _truncated?: boolean;\n}\n\n/** v1 document layout (legacy — read-only support). */\nexport interface V1HistoryDoc {\n // schemaVersion is absent in v1.\n schemaVersion?: undefined;\n historyDocId: string;\n historyToObjectId: string;\n historyUserId?: string;\n historyUserEmail?: string;\n historySetAt: Timestamp;\n field: string;\n changes: { oldValue: unknown; newValue: unknown };\n types?: { oldValue: string; newValue: string };\n // Extra freeform metadata seen in legacy code.\n historyDetails?: Record<string, unknown> | null;\n extraHistoryDetails?: {\n comment?: string;\n reason?: string;\n toKey?: string;\n force?: boolean;\n } | null;\n extraContentKeys?: Record<string, unknown> | null;\n objectType?: string;\n}\n\n/* ------------------------------------------------------------------------- */\n/* Configuration */\n/* ------------------------------------------------------------------------- */\n\n/** Default top-level shadow field name stored on Firestore documents for auto-injected history metadata. */\nexport const DEFAULT_HISTORY_SHADOW_KEY = \"_historyMeta\";\n\n/**\n * Customize (or disable via `false`) the sub-field names stored inside the\n * shadow metadata object on Firestore documents.\n */\nexport interface HistoryShadowFieldsConfig {\n /** Key inside the shadow object for author userId, or `false` to omit. Default: `\"userId\"`. */\n userId?: string | false;\n /** Key inside the shadow object for author userEmail, or `false` to omit. Default: `\"userEmail\"`. */\n userEmail?: string | false;\n /** Key inside the shadow object for change reason, or `false` to omit. Default: `\"reason\"`. */\n reason?: string | false;\n /** Key inside the shadow object for change comment, or `false` to omit. Default: `\"comment\"`. */\n comment?: string | false;\n /** Key inside the shadow object for extras map, or `false` to omit. Default: `\"extras\"`. */\n extras?: string | false;\n}\n\n/**\n * Configuration for the internal shadow field used to transport actor metadata\n * to Firestore `onDocumentWritten` triggers without modifying Zod schemas.\n */\nexport interface HistoryShadowConfig {\n /**\n * Top-level field name stored on the Firestore document (not required in the\n * Zod schema, automatically excluded from diffs and sync, and stripped on read).\n * Default: `\"_historyMeta\"`.\n */\n key?: string;\n /**\n * Customize or disable individual sub-field names inside the shadow object.\n * Default: `{ userId: \"userId\", userEmail: \"userEmail\", reason: \"reason\", comment: \"comment\", extras: \"extras\" }`.\n */\n fields?: HistoryShadowFieldsConfig;\n}\n\n/**\n * Fallback author values written when no actor is active in `AsyncLocalStorage`\n * (crons, scripts, admin UI, public routes).\n */\nexport interface HistoryFallbackActor {\n userId?: string | null;\n userEmail?: string | null;\n}\n\n/**\n * Per-repo history configuration. Attached on the repository config under\n * the `history` key. All meta sub-keys must reference fields that exist on\n * the model (compile-time enforced by {@link HistoryConfigForModel}).\n */\nexport interface HistoryConfigBase {\n /** Master switch — when false/absent, no triggers are generated and no `repo.history` API is exposed. */\n enabled: boolean;\n /** Subcollection name used to store history docs. Default: \"history\". */\n subcollection?: string;\n /**\n * Automatically inject actor metadata from `AsyncLocalStorage` into the\n * shadow field on repository writes (`create`, `set`, `update`, `batch`,\n * `transaction`, `bulk`). Default: `true` when `enabled: true`.\n */\n autoInjectMeta?: boolean;\n /**\n * Shadow field configuration (zero Zod schema changes).\n *\n * - Omitted or `true` (when `meta` is absent): uses `\"_historyMeta\"` with default sub-fields.\n * - `string`: shorthand for `{ key: \"<customKey>\" }`.\n * - `HistoryShadowConfig`: customize both `key` and nested `fields`.\n * - `false`: disable shadow metadata injection/reading.\n */\n shadow?: boolean | string | HistoryShadowConfig;\n /**\n * Fallback actor written when no actor is active in `AsyncLocalStorage` so\n * previous author metadata never leaks onto subsequent writes.\n * Default: `{ userId: null, userEmail: null }`.\n */\n fallbackActor?: HistoryFallbackActor;\n /**\n * Optional Firestore TTL configuration. When set, every written history doc\n * gets an `expiresAt` Timestamp at `now + days`. You still need to enable\n * the TTL policy on the `expiresAt` field via gcloud / console.\n */\n ttl?: { days: number };\n /**\n * Cloud Functions v2 options forwarded to `onDocumentWritten()` for this\n * repository's history trigger (e.g. `region`, `vpcConnector`, `memory`, etc.).\n */\n triggerOptions?: HistoryTriggerOptions;\n}\n\n/**\n * Strongly-typed history config bound to a model `T`.\n *\n * - `meta.*` keys must be keyof T (or string for `extras` entries).\n * - `include` / `exclude` accept keyof T.\n */\nexport interface HistoryConfigForModel<T> extends HistoryConfigBase {\n meta?: {\n /** Field on T that holds the author user id. */\n userId?: keyof T & string;\n /** Field on T that holds the author email. */\n userEmail?: keyof T & string;\n /** Field on T that holds an optional change reason. */\n reason?: keyof T & string;\n /** Field on T that holds an optional change comment. */\n comment?: keyof T & string;\n /** Free-form extra field names copied verbatim into `meta.extras`. */\n extras?: (keyof T & string)[];\n };\n /** When set, only these top-level fields are diffed. */\n include?: (keyof T & string)[];\n /** Always excluded from the diff (in addition to meta + system keys). */\n exclude?: (keyof T & string)[];\n /**\n * Optional async hook to enrich/mutate an entry before it's written.\n * Return `null` to drop the entry entirely.\n */\n onBeforeWrite?: (\n entry: V2HistoryDoc,\n ctx: { repoName: string; docId: string; before: T | null; after: T | null },\n ) => V2HistoryDoc | null | Promise<V2HistoryDoc | null>;\n}\n\n/* ------------------------------------------------------------------------- */\n/* Read API options */\n/* ------------------------------------------------------------------------- */\n\nexport interface HistoryListOptions<T = unknown> {\n /** Max number of normalised entries to return. Default: 50. */\n limit?: number;\n /** Cursor for pagination (use `historySetAt` of the last received entry). */\n cursor?: Timestamp;\n /** Sort direction on `historySetAt`. Default: \"desc\". */\n direction?: \"asc\" | \"desc\";\n /** Restrict to entries that touch any of these fields (post-filter). */\n fields?: (keyof T & string)[];\n /** Restrict to entries with these operations (v2 only — v1 is always \"update\"). */\n operations?: HistoryOperation[];\n}\n\nexport interface HistoryRawListOptions {\n limit?: number;\n cursor?: Timestamp;\n direction?: \"asc\" | \"desc\";\n}\n\n/* ------------------------------------------------------------------------- */\n/* Trigger factory configuration */\n/* ------------------------------------------------------------------------- */\n\n/**\n * Firestore trigger constructors injected by the consumer.\n * Mirrors the DI pattern used by `createSyncTriggers`.\n */\nexport interface HistoryFirestoreTriggersDep {\n // Either onDocumentWritten alone is enough; we keep the more granular ones\n // available so the worker can stay efficient.\n onDocumentWritten: typeof onDocumentWritten;\n}\n\n/** Per-repo override at the `createHistoryTriggers` call site. */\nexport interface HistoryTriggerRepoOverride {\n /**\n * Explicit Firestore document path pattern. Required for collection-group\n * repositories whose path cannot be auto-detected.\n * @example \"residences/{residenceId}/workshops/{docId}\"\n */\n triggerPath?: string;\n /**\n * Cloud Functions v2 options forwarded to `onDocumentWritten()` for this\n * repository's history trigger. Overrides global `triggerOptions`.\n */\n triggerOptions?: HistoryTriggerOptions;\n}\n\nexport interface HistoryTriggersConfig<M = Record<string, any>> {\n deps: HistoryFirestoreTriggersDep;\n /** Defaults applied to every repo unless overridden. */\n defaults?: { ttl?: { days: number } };\n /**\n * Cloud Functions v2 options forwarded to `onDocumentWritten()` for every\n * history trigger handler. Use to configure `region`, `vpcConnector`,\n * `memory`, `cpu`, `timeoutSeconds`, `maxInstances`, `secrets`, etc.\n */\n triggerOptions?: HistoryTriggerOptions;\n /** Per-repo overrides keyed by repo name in the mapping. */\n repos?: Partial<Record<keyof M & string, HistoryTriggerRepoOverride>>;\n}\n","/**\n * Shadow metadata injection, resolution, and read-stripping helpers for the\n * history module.\n *\n * Writes actor metadata from the cross-bundle `AsyncLocalStorage` context into\n * a configurable shadow object (default `_historyMeta`) on Firestore documents\n * without requiring any changes to model Zod schemas.\n */\n\nimport { getCurrentActor } from \"../shared/actor-context\";\nimport {\n DEFAULT_HISTORY_SHADOW_KEY,\n type HistoryConfigForModel,\n} from \"./types\";\n\nexport interface ResolvedShadowFields {\n userId: string | false;\n userEmail: string | false;\n reason: string | false;\n comment: string | false;\n extras: string | false;\n}\n\nexport interface ResolvedShadowConfig {\n key: string;\n fields: ResolvedShadowFields;\n}\n\n/**\n * Resolve the effective shadow storage configuration for a repository's\n * `history` config, or `null` when shadow storage is inactive.\n *\n * Shadow storage is active whenever `history.enabled` is `true`, `shadow` is\n * not `false`, and either `meta` is omitted or `shadow` is explicitly provided.\n */\nexport function resolveShadowConfig(\n config: HistoryConfigForModel<any> | undefined | null,\n): ResolvedShadowConfig | null {\n if (!config?.enabled) return null;\n if (config.shadow === false) return null;\n if (config.meta && config.shadow === undefined) return null;\n\n const shadowOpt = config.shadow;\n const key =\n typeof shadowOpt === \"string\" && shadowOpt.trim().length > 0\n ? shadowOpt.trim()\n : typeof shadowOpt === \"object\" &&\n shadowOpt !== null &&\n typeof shadowOpt.key === \"string\" &&\n shadowOpt.key.trim().length > 0\n ? shadowOpt.key.trim()\n : DEFAULT_HISTORY_SHADOW_KEY;\n\n const customFields =\n typeof shadowOpt === \"object\" && shadowOpt !== null\n ? shadowOpt.fields\n : undefined;\n\n return {\n key,\n fields: {\n userId: customFields?.userId ?? \"userId\",\n userEmail: customFields?.userEmail ?? \"userEmail\",\n reason: customFields?.reason ?? \"reason\",\n comment: customFields?.comment ?? \"comment\",\n extras: customFields?.extras ?? \"extras\",\n },\n };\n}\n\n/**\n * Return the active shadow key for a repository's history config, or `null`\n * when shadow storage is inactive.\n */\nexport function getHistoryShadowKey(\n config: HistoryConfigForModel<any> | undefined | null,\n): string | null {\n return resolveShadowConfig(config)?.key ?? null;\n}\n\n/**\n * Return the reserved identity/shadow keys that must be stripped from incoming\n * CRUD payloads (anti-spoofing) and omitted from Create/Update OpenAPI schemas.\n */\nexport function getHistoryIdentityKeys(\n config: HistoryConfigForModel<any> | undefined | null,\n): string[] {\n const shadow = resolveShadowConfig(config);\n return shadow ? [shadow.key] : [];\n}\n\n/**\n * Strip the internal shadow field from a document returned by repository\n * read/write methods (`get`, `query`, `paginate`, `create`, `set`, `update`,\n * `transaction.get`). Zero-overhead no-op when `shadowKey` is `null` or absent.\n */\nexport function stripHistoryShadowField<T>(\n value: T,\n shadowKey: string | null | undefined,\n): T {\n if (!shadowKey || !value || typeof value !== \"object\" || Array.isArray(value)) {\n return value;\n }\n const rec = value as Record<string, unknown>;\n if (!(shadowKey in rec)) return value;\n\n const { [shadowKey]: _dropped, ...rest } = rec;\n return rest as T;\n}\n\n/**\n * Inject the current ALS actor metadata into the configurable shadow field on\n * a Firestore write payload (`create`, `set`, `update`, `batch`, `transaction`,\n * `bulk`).\n *\n * Always writes explicit `null` for absent `reason`, `comment`, `extras`, and\n * applies `fallbackActor` when no actor is active so previous write metadata\n * never leaks — including across Firestore `set(..., { merge: true })`.\n */\nexport function injectHistoryMeta(\n payload: Record<string, unknown>,\n historyConfig: HistoryConfigForModel<any> | undefined,\n): void {\n if (!historyConfig?.enabled || historyConfig.autoInjectMeta === false) return;\n\n const shadow = resolveShadowConfig(historyConfig);\n if (!shadow) return;\n\n const actor = getCurrentActor();\n const fallback = historyConfig.fallbackActor ?? {};\n const userId =\n actor?.userId !== undefined ? actor.userId : (fallback.userId ?? null);\n const userEmail =\n actor?.userEmail !== undefined\n ? actor.userEmail\n : (fallback.userEmail ?? null);\n const reason = actor?.reason ?? null;\n const comment = actor?.comment ?? null;\n const extras =\n actor?.extras && Object.keys(actor.extras).length > 0 ? actor.extras : null;\n\n const shadowObj: Record<string, unknown> = {};\n const { fields } = shadow;\n if (fields.userId !== false) shadowObj[fields.userId] = userId;\n if (fields.userEmail !== false) shadowObj[fields.userEmail] = userEmail;\n if (fields.reason !== false) shadowObj[fields.reason] = reason;\n if (fields.comment !== false) shadowObj[fields.comment] = comment;\n if (fields.extras !== false) shadowObj[fields.extras] = extras;\n\n payload[shadow.key] = shadowObj;\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","import { randomBytes } from \"node:crypto\";\nimport type { DocumentReference, Firestore } from \"firebase-admin/firestore\";\n\nconst ID_CHARS =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n\n/**\n * Generate a random 20-char alphanumeric ID matching Firestore's native format.\n *\n * Uses a CSPRNG (`crypto.randomBytes`) with rejection sampling (dropping the\n * biased tail `>= 62*4`) to keep the distribution uniform across the 62-char\n * alphabet.\n */\nexport function 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 >= ID_CHARS.length * 4) continue; // drop biased tail (248..255)\n id += ID_CHARS.charAt(byte % ID_CHARS.length);\n }\n }\n return id;\n}\n\n/** Extract parameter name from a `{param}` segment, or `null` if static. */\nfunction extractSegmentParam(segment: string): string | null {\n const match = segment.match(/^\\{([^}]+)\\}$/);\n return match?.[1]?.trim() || null;\n}\n\n/**\n * Parsed metadata from a repository `path` configuration string.\n */\nexport interface ParsedPathTemplate {\n /** Raw path string as configured on the repository */\n rawPath: string;\n /**\n * Target Firestore collection ID (last collection segment, e.g. `\"prev_events\"`\n * from `\"prevention/prev_rules/prev_workshops/{workshopId}/prev_events\"`).\n * Used for `db.collectionGroup(collectionId)`.\n */\n collectionId: string;\n /**\n * Collection path (without trailing document segment). Used for `db.collection(...)`\n * on non-group repositories (`isGroup: false`).\n */\n collectionPath: string;\n /**\n * Ordered list of dynamic `{param}` parent keys extracted from the path\n * (excluding fixed transit segments like `\"prev_rules\"` and the trailing\n * `documentKey`).\n */\n parentKeys: string[];\n /**\n * Full Firestore document path pattern including trailing `/{documentKey}`\n * (e.g. `\"prevention/prev_rules/prev_workshops/{workshopId}/prev_events/{docId}\"`),\n * or `null` when `isGroup: true` and `rawPath` is a bare single-segment\n * collection name without a path template.\n */\n documentPathTemplate: string | null;\n /** `true` when `rawPath` contains `/` or `{...}` template placeholders */\n hasTemplate: boolean;\n}\n\n/**\n * Parse a repository `path` into collection ID, ordered dynamic parent keys,\n * and full document path template.\n *\n * Supports:\n * - Bare collection names: `\"users\"`, `\"res_events\"`\n * - Odd-segment collection templates: `\"residences/{residenceId}/res_events\"`,\n * `\"prevention/prev_rules/prev_workshops/{workshopId}/prev_events\"`\n * - Even-segment document templates: `\"residences/{residenceId}/res_events/{docId}\"`\n */\nexport function parsePathTemplate(\n rawPath: string,\n documentKey = \"docId\",\n isGroup = false,\n): ParsedPathTemplate {\n if (typeof rawPath !== \"string\" || !rawPath.trim()) {\n return {\n rawPath: rawPath ?? \"\",\n collectionId: \"\",\n collectionPath: \"\",\n parentKeys: [],\n documentPathTemplate: null,\n hasTemplate: false,\n };\n }\n\n const segments = rawPath\n .split(\"/\")\n .map((s) => s.trim())\n .filter(Boolean);\n\n if (segments.length === 0) {\n return {\n rawPath,\n collectionId: rawPath,\n collectionPath: rawPath,\n parentKeys: [],\n documentPathTemplate: null,\n hasTemplate: false,\n };\n }\n\n if (segments.length === 1) {\n const seg = segments[0]!;\n return {\n rawPath,\n collectionId: seg,\n collectionPath: seg,\n parentKeys: [],\n documentPathTemplate: isGroup ? null : `${seg}/{${documentKey}}`,\n hasTemplate: rawPath.includes(\"{\") && rawPath.includes(\"}\"),\n };\n }\n\n // Multi-segment path:\n // - Even number of segments (col/doc/col/{docId}) -> last segment is the document ID placeholder\n // - Odd number of segments (col/doc/col) -> last segment is the target collection\n const isEvenSegments = segments.length % 2 === 0;\n const collectionSegments = isEvenSegments ? segments.slice(0, -1) : segments;\n const collectionId = collectionSegments[collectionSegments.length - 1]!;\n const collectionPath = collectionSegments.join(\"/\");\n\n // Parent segments are all segments before the target collection segment\n const parentSegments = collectionSegments.slice(0, -1);\n const parentKeys = parentSegments\n .map(extractSegmentParam)\n .filter((p): p is string => p !== null);\n\n const documentPathTemplate = isEvenSegments\n ? segments.join(\"/\")\n : `${collectionPath}/{${documentKey}}`;\n\n return {\n rawPath,\n collectionId,\n collectionPath,\n parentKeys,\n documentPathTemplate,\n hasTemplate: true,\n };\n}\n\n/**\n * Build a Firestore `DocumentReference` from a `documentPathTemplate`\n * (e.g. `\"prevention/prev_rules/prev_workshops/{workshopId}/prev_events/{docId}\"`)\n * and positional dynamic arguments (`[workshopId, docId]`).\n *\n * Static transit segments (like `\"prev_rules\"`) are preserved automatically.\n */\nexport function buildDocumentRefFromTemplate(\n db: Firestore,\n documentPathTemplate: string,\n args: unknown[],\n): DocumentReference {\n const segments = documentPathTemplate\n .split(\"/\")\n .map((s) => s.trim())\n .filter(Boolean);\n\n let argIndex = 0;\n const resolvedSegments: string[] = [];\n\n for (const seg of segments) {\n const paramName = extractSegmentParam(seg);\n if (paramName !== null) {\n const val = args[argIndex++];\n if (typeof val !== \"string\" || val.trim() === \"\") {\n throw new Error(\n `Missing or empty path parameter \"${paramName}\" when resolving document reference for \"${documentPathTemplate}\".`,\n );\n }\n resolvedSegments.push(val);\n } else {\n resolvedSegments.push(seg);\n }\n }\n\n const anyDb = db as any;\n\n // Try walking db.collection(seg0).doc(seg1).collection(seg2).doc(seg3)...\n // so mocks that spy on .collection().doc() work identically to hand-written refCb.\n if (typeof anyDb?.collection === \"function\" && resolvedSegments.length >= 2) {\n let cur: any = anyDb;\n let walked = true;\n for (let i = 0; i < resolvedSegments.length; i += 2) {\n const colName = resolvedSegments[i]!;\n const docId = resolvedSegments[i + 1]!;\n if (typeof cur?.collection !== \"function\") {\n walked = false;\n break;\n }\n const colRef = cur.collection(colName);\n if (typeof colRef?.doc !== \"function\") {\n walked = false;\n break;\n }\n cur = colRef.doc(docId);\n }\n if (walked && cur && cur !== anyDb) {\n return cur as DocumentReference;\n }\n }\n\n // Fallback: db.doc(fullPath)\n const fullPath = resolvedSegments.join(\"/\");\n if (typeof anyDb?.doc === \"function\") {\n return anyDb.doc(fullPath) as DocumentReference;\n }\n\n // Last-resort fallback for minimal single-collection test mocks\n if (typeof anyDb?.collection === \"function\" && resolvedSegments.length >= 2) {\n const colPath = resolvedSegments.slice(0, -1).join(\"/\");\n const docId = resolvedSegments[resolvedSegments.length - 1]!;\n const colRef = anyDb.collection(colPath);\n if (typeof colRef?.doc === \"function\") {\n return colRef.doc(docId) as DocumentReference;\n }\n return colRef as DocumentReference;\n }\n\n throw new Error(\n `Cannot resolve DocumentReference for \"${fullPath}\": Firestore instance does not expose .collection() or .doc().`,\n );\n}\n\nexport interface ExtractPathArgsOptions {\n pathKey?: string | null;\n documentKey?: string | null;\n parentKeys?: string[];\n documentPathTemplate?: string | null;\n isGroup?: boolean;\n}\n\n/**\n * Extract the dynamic document reference arguments from a stored document.\n *\n * Unlike naive odd-segment splitting, this helper skips fixed transit document\n * segments (such as `\"prev_rules\"` in `\"prevention/prev_rules/prev_workshops/w1/prev_events/e1\"`)\n * by matching against `documentPathTemplate` or `parentKeys`.\n */\nexport function extractPathArgsFromDoc(\n doc: Record<string, unknown> | null | undefined,\n options: ExtractPathArgsOptions = {},\n): string[] | undefined {\n if (!doc || typeof doc !== \"object\") return undefined;\n\n const {\n pathKey,\n documentKey = \"docId\",\n parentKeys,\n documentPathTemplate,\n isGroup,\n } = options;\n\n const fullPath =\n pathKey && typeof doc[pathKey] === \"string\" && doc[pathKey]\n ? (doc[pathKey] as string)\n : undefined;\n\n // 1. If we have both fullPath and a matching documentPathTemplate, extract only `{param}` positions\n if (fullPath && documentPathTemplate) {\n const pathSegments = fullPath.split(\"/\").filter(Boolean);\n const tplSegments = documentPathTemplate.split(\"/\").filter(Boolean);\n if (pathSegments.length === tplSegments.length) {\n const extracted: string[] = [];\n for (let i = 0; i < tplSegments.length; i++) {\n if (extractSegmentParam(tplSegments[i]!) !== null) {\n extracted.push(pathSegments[i]!);\n }\n }\n if (extracted.length > 0) {\n return extracted;\n }\n }\n }\n\n // 2. If parentKeys are known and non-empty\n if (parentKeys && parentKeys.length > 0) {\n const expectedCount = parentKeys.length + 1;\n\n if (fullPath) {\n const segments = fullPath.split(\"/\").filter(Boolean);\n const oddSegments: string[] = [];\n for (let i = 1; i < segments.length; i += 2) {\n oddSegments.push(segments[i]!);\n }\n if (oddSegments.length >= expectedCount) {\n return oddSegments.slice(oddSegments.length - expectedCount);\n }\n }\n\n // Fallback: extract parentKeys + documentKey directly from document fields\n const docIdVal = documentKey ? doc[documentKey] : undefined;\n if (typeof docIdVal === \"string\" && docIdVal.trim() !== \"\") {\n const parentVals: string[] = [];\n let allPresent = true;\n for (const pk of parentKeys) {\n const v = doc[pk];\n if (typeof v === \"string\" && v.trim() !== \"\") {\n parentVals.push(v);\n } else {\n allPresent = false;\n break;\n }\n }\n if (allPresent) {\n return [...parentVals, docIdVal];\n }\n }\n }\n\n // 3. Fallback when fullPath is present\n if (fullPath) {\n const segments = fullPath.split(\"/\").filter(Boolean);\n const oddSegments: string[] = [];\n for (let i = 1; i < segments.length; i += 2) {\n oddSegments.push(segments[i]!);\n }\n if (oddSegments.length > 0) {\n // For non-group repos without parentKeys (e.g. under a fixed transit doc), only the last docId is dynamic\n if (!isGroup && (!parentKeys || parentKeys.length === 0)) {\n return [oddSegments[oddSegments.length - 1]!];\n }\n return oddSegments;\n }\n }\n\n return undefined;\n}\n","/**\n * Zod introspection utilities — compatible with Zod 4.\n *\n * Centralizes all internal `_zod.def` accesses so the rest of the codebase\n * never touches Zod internals directly. If a future Zod version changes\n * the internal layout, only this file needs updating.\n */\n\nimport type { z } from \"zod\";\n\n// ---------------------------------------------------------------------------\n// Type-name resolution\n// ---------------------------------------------------------------------------\n\n/**\n * Canonical Zod type names used in the codebase.\n * These match the **Zod 3** naming convention (e.g. \"ZodString\") that the\n * form-gen / admin handlers already rely on, so we don't need to rewrite\n * every `case \"ZodString\":` branch.\n */\ntype ZodTypeName =\n | \"ZodString\"\n | \"ZodNumber\"\n | \"ZodBigInt\"\n | \"ZodBoolean\"\n | \"ZodDate\"\n | \"ZodEnum\"\n | \"ZodNativeEnum\"\n | \"ZodLiteral\"\n | \"ZodObject\"\n | \"ZodArray\"\n | \"ZodOptional\"\n | \"ZodNullable\"\n | \"ZodDefault\"\n | \"ZodCoerce\"\n | \"ZodUnion\"\n | \"ZodUndefined\"\n | \"ZodUnknown\"\n | \"ZodAny\"\n | \"ZodRecord\"\n | string;\n\n/**\n * Map from Zod 4 `_zod.def.type` (lowercase) → Zod 3 `_def.typeName` format.\n * Any key not in this map is capitalised as `Zod${Capitalised}`.\n */\nconst TYPE_MAP: Record<string, ZodTypeName> = {\n string: \"ZodString\",\n number: \"ZodNumber\",\n bigint: \"ZodBigInt\",\n boolean: \"ZodBoolean\",\n date: \"ZodDate\",\n enum: \"ZodEnum\",\n nativeEnum: \"ZodNativeEnum\",\n literal: \"ZodLiteral\",\n object: \"ZodObject\",\n array: \"ZodArray\",\n optional: \"ZodOptional\",\n nullable: \"ZodNullable\",\n default: \"ZodDefault\",\n coerce: \"ZodCoerce\",\n union: \"ZodUnion\",\n undefined: \"ZodUndefined\",\n unknown: \"ZodUnknown\",\n any: \"ZodAny\",\n record: \"ZodRecord\",\n};\n\n/**\n * Get the canonical type name of a Zod schema.\n *\n * Works with both Zod 3 (`_def.typeName`) and Zod 4 (`_zod.def.type`).\n * Returns names in Zod-3 style (\"ZodString\", \"ZodObject\" …) for\n * backward-compatible switch/case usage.\n */\nexport function getTypeName(schema: z.ZodType): ZodTypeName {\n const s = schema as any;\n\n // Zod 4 path\n const v4Type: string | undefined = s._zod?.def?.type;\n if (v4Type)\n return (\n TYPE_MAP[v4Type] ??\n `Zod${v4Type.charAt(0).toUpperCase()}${v4Type.slice(1)}`\n );\n\n // Zod 3 fallback\n const v3Type: string | undefined = s._def?.typeName;\n if (v3Type) return v3Type;\n\n return \"\";\n}\n\n// ---------------------------------------------------------------------------\n// Unwrapping wrappers (Optional / Nullable / Default)\n// ---------------------------------------------------------------------------\n\n/**\n * Get the inner schema from a wrapper type (Optional / Nullable / Default).\n */\nexport function getInnerType(schema: z.ZodType): z.ZodType | undefined {\n const s = schema as any;\n\n // Zod 4: _zod.def.innerType\n if (s._zod?.def?.innerType) return s._zod.def.innerType;\n\n // Zod 3 compat: _def.innerType\n if (s._def?.innerType) return s._def.innerType;\n\n return undefined;\n}\n\n/**\n * Get the **source** schema of an effect / transform / pipe wrapper, i.e. the\n * schema describing what the user actually provides:\n * - Zod 3 `ZodEffects` (`.transform()` / `.refine()` / `.preprocess()`) →\n * `_def.schema`;\n * - Zod 4 `ZodPipe` (the shape `.transform()` compiles to) → the `in` side.\n *\n * Lets form/field introspection see through `z.string().transform(...)` (which\n * should still render as a text input) instead of falling back to a JSON\n * textarea. Returns `undefined` when the schema is not an effect/pipe.\n */\nexport function getEffectInnerType(schema: z.ZodType): z.ZodType | undefined {\n const s = schema as any;\n\n // Zod 4: pipe — prefer the input side (what the user types).\n const pipeIn = s._zod?.def?.in;\n if (pipeIn) return pipeIn as z.ZodType;\n\n // Zod 3: ZodEffects wraps the base schema under `_def.schema`.\n if (s._def?.schema) return s._def.schema as z.ZodType;\n\n return undefined;\n}\n\n/**\n * Get the **element schema** from a `ZodArray`.\n * Returns `undefined` for non-array schemas.\n */\nexport function getArrayElementType(\n schema: z.ZodType,\n): z.ZodType | undefined {\n const s = schema as any;\n\n // Zod 4: _zod.def.element\n if (s._zod?.def?.element) return s._zod.def.element;\n\n // Zod 3: _def.type (ZodArray stores element schema in _def.type)\n if (s._def?.type) return s._def.type;\n\n return undefined;\n}\n\n/**\n * Returns the list of **required** (non-optional) top-level keys of a ZodObject.\n * A key is required when its schema is NOT wrapped in ZodOptional.\n * ZodNullable / ZodDefault fields are still considered required — they must be present.\n */\nexport function getRequiredSchemaKeys(schema: z.ZodObject<any>): string[] {\n const required: string[] = [];\n for (const [key, fieldSchema] of Object.entries(schema.shape)) {\n const typeName = getTypeName(fieldSchema as z.ZodType);\n if (typeName !== \"ZodOptional\") {\n required.push(key);\n }\n }\n return required;\n}\n\n/**\n * Get the default value for a ZodDefault schema.\n * In Zod 3 this was `_def.defaultValue()` (function). In Zod 4 it's a direct value.\n */\nexport function getDefaultValue(schema: z.ZodType): unknown {\n const s = schema as any;\n\n // Zod 4\n if (s._zod?.def?.defaultValue !== undefined) return s._zod.def.defaultValue;\n\n // Zod 3 compat\n const v = s._def?.defaultValue;\n if (typeof v === \"function\") return v();\n return v;\n}\n\n// ---------------------------------------------------------------------------\n// Object shape\n// ---------------------------------------------------------------------------\n\n/**\n * Get the shape of a ZodObject schema (Record<string, ZodType>).\n * Handles both Zod 3 (`_def.shape()` function) and Zod 4 (`.shape` property).\n */\nexport function getShape(schema: z.ZodType): Record<string, z.ZodType> {\n const s = schema as any;\n\n // Direct `.shape` property (Zod 3 & 4 for ZodObject instances)\n if (s.shape && typeof s.shape === \"object\") return s.shape;\n\n // Zod 4: _zod.def.shape\n if (s._zod?.def?.shape && typeof s._zod.def.shape === \"object\")\n return s._zod.def.shape;\n\n // Zod 3 fallback: _def.shape() or _def.shape\n if (s._def?.shape) {\n return typeof s._def.shape === \"function\" ? s._def.shape() : s._def.shape;\n }\n\n return {};\n}\n\n// ---------------------------------------------------------------------------\n// Enum / Literal values\n// ---------------------------------------------------------------------------\n\n/**\n * Get the values of a ZodEnum schema as a string[].\n */\nexport function getEnumValues(schema: z.ZodType): string[] {\n const s = schema as any;\n\n // Zod 4: `.options` or `_zod.def.entries`\n if (Array.isArray(s.options)) return s.options;\n if (s._zod?.def?.entries)\n return Object.values(s._zod.def.entries) as string[];\n\n // Zod 3: `_def.values`\n if (Array.isArray(s._def?.values)) return s._def.values;\n\n return [];\n}\n\n/**\n * Get the value object of a ZodNativeEnum schema.\n */\nexport function getNativeEnumValues(\n schema: z.ZodType,\n): Record<string, unknown> {\n const s = schema as any;\n\n // Zod 4: `_zod.def.entries` or `.enum`\n if (s._zod?.def?.entries) return s._zod.def.entries;\n if (s.enum && typeof s.enum === \"object\") return s.enum;\n\n // Zod 3: `_def.values`\n if (s._def?.values && typeof s._def.values === \"object\") return s._def.values;\n\n return {};\n}\n\n/**\n * Get the value of a ZodLiteral schema.\n */\nexport function getLiteralValue(schema: z.ZodType): unknown {\n const s = schema as any;\n\n // Zod 4: `_zod.def.values[0]`\n if (Array.isArray(s._zod?.def?.values)) return s._zod.def.values[0];\n\n // Zod 3: `_def.value`\n return s._def?.value;\n}\n\n/**\n * Get the member schemas of a ZodUnion (or ZodDiscriminatedUnion).\n * Works with both Zod 3 (`_def.options`) and Zod 4 (`.options` /\n * `_zod.def.options`). Returns an empty array when none can be resolved.\n */\nexport function getUnionOptions(schema: z.ZodType): z.ZodType[] {\n const s = schema as any;\n\n // Zod 4\n if (Array.isArray(s.options)) return s.options as z.ZodType[];\n if (Array.isArray(s._zod?.def?.options))\n return s._zod.def.options as z.ZodType[];\n\n // Zod 3\n if (Array.isArray(s._def?.options)) return s._def.options as z.ZodType[];\n\n return [];\n}\n\n// ---------------------------------------------------------------------------\n// String checks\n// ---------------------------------------------------------------------------\n\n/**\n * Get relevant \"check kinds\" from a ZodString schema.\n * Returns an array of kind strings: \"email\", \"url\", etc.\n */\nexport function getStringChecks(schema: z.ZodType): string[] {\n const s = schema as any;\n const kinds: string[] = [];\n\n // Zod 4: checks with `.format` field\n const v4Checks: any[] | undefined = s._zod?.def?.checks;\n if (Array.isArray(v4Checks)) {\n for (const c of v4Checks) {\n if (c.format) kinds.push(c.format);\n }\n if (kinds.length > 0) return kinds;\n }\n\n // Zod 3: _def.checks with `.kind` field\n const v3Checks: any[] | undefined = s._def?.checks;\n if (Array.isArray(v3Checks)) {\n for (const c of v3Checks) {\n if (c.kind) kinds.push(c.kind);\n }\n }\n\n return kinds;\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 { parsePathTemplate } from \"../../shared/path-template\";\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 collection segment) from a Firestore path.\n * e.g. \"posts/{postId}/comments\" → \"comments\"\n * e.g. \"posts/{postId}/comments/{docId}\" → \"comments\"\n */\nexport function collectionIdFromPath(path: string): string {\n return parsePathTemplate(path).collectionId || 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 * Diff helper for the history module.\n *\n * Computes a top-level shallow diff between two snapshots of the same\n * document. Returns an empty changes object when nothing relevant changed.\n *\n * Meta fields, system keys (docId / pathKey / createdKey / updatedKey) and\n * any field listed in `exclude` are filtered out. When `include` is set, only\n * the listed fields are considered.\n */\n\nimport { Timestamp } from \"firebase-admin/firestore\";\nimport type {\n HistoryFieldChange,\n HistoryValueType,\n} from \"./types\";\n\nexport interface DiffOptions {\n include?: string[];\n exclude?: string[];\n /** Field names that hold meta info (auto-excluded from diff). */\n metaFields?: string[];\n /** System keys auto-excluded (docId, pathKey, createdKey, updatedKey). */\n systemKeys?: string[];\n}\n\nexport function valueType(v: unknown): HistoryValueType {\n if (v === null) return \"null\";\n if (v === undefined) return \"undefined\";\n if (v instanceof Timestamp) return \"timestamp\";\n if (v instanceof Date) return \"date\";\n if (Array.isArray(v)) return \"array\";\n const t = typeof v;\n if (t === \"string\" || t === \"number\" || t === \"boolean\") return t;\n return \"object\";\n}\n\n/**\n * Structural equality good enough for change detection.\n *\n * Order-insensitive for object keys (Firestore does not guarantee key order\n * after partial updates / re-fetch, so `JSON.stringify` comparison produced\n * phantom diffs). Cycle-safe via a `seen` map, and never throws — see #14.\n */\nexport function valuesEqual(\n a: unknown,\n b: unknown,\n seen: WeakMap<object, unknown> = new WeakMap(),\n): boolean {\n if (a === b) return true;\n if (a === null || b === null || a === undefined || b === undefined) {\n return a === b;\n }\n\n if (a instanceof Timestamp && b instanceof Timestamp) {\n return a.isEqual(b);\n }\n if (a instanceof Date && b instanceof Date) {\n return a.getTime() === b.getTime();\n }\n\n if (Array.isArray(a) || Array.isArray(b)) {\n if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) {\n return false;\n }\n if (seen.get(a) === b) return true;\n seen.set(a, b);\n for (let i = 0; i < a.length; i++) {\n if (!valuesEqual(a[i], b[i], seen)) return false;\n }\n return true;\n }\n\n if (typeof a === \"object\" && typeof b === \"object\") {\n // A plain object is never equal to a special boxed value (one is a\n // Date/Timestamp, the other a plain object).\n if (\n a instanceof Date ||\n b instanceof Date ||\n a instanceof Timestamp ||\n b instanceof Timestamp\n ) {\n return false;\n }\n if (seen.get(a) === b) return true;\n seen.set(a, b);\n const ka = Object.keys(a as Record<string, unknown>);\n const kb = Object.keys(b as Record<string, unknown>);\n if (ka.length !== kb.length) return false;\n for (const k of ka) {\n if (!Object.prototype.hasOwnProperty.call(b, k)) return false;\n if (\n !valuesEqual(\n (a as Record<string, unknown>)[k],\n (b as Record<string, unknown>)[k],\n seen,\n )\n ) {\n return false;\n }\n }\n return true;\n }\n\n return false;\n}\n\n/**\n * Compute a flat top-level diff. Nested objects are compared as a whole — they\n * appear in the diff if changed but are NOT decomposed key by key.\n */\nexport function computeDiff<T extends Record<string, unknown>>(\n before: T | null | undefined,\n after: T | null | undefined,\n opts: DiffOptions = {},\n): Record<string, HistoryFieldChange> {\n const excludeSet = new Set<string>([\n ...(opts.exclude ?? []),\n ...(opts.metaFields ?? []),\n ...(opts.systemKeys ?? []),\n ]);\n const includeSet = opts.include ? new Set<string>(opts.include) : null;\n\n const beforeObj = (before ?? {}) as Record<string, unknown>;\n const afterObj = (after ?? {}) as Record<string, unknown>;\n\n const keys = new Set<string>([\n ...Object.keys(beforeObj),\n ...Object.keys(afterObj),\n ]);\n\n const changes: Record<string, HistoryFieldChange> = {};\n for (const key of keys) {\n if (excludeSet.has(key)) continue;\n if (includeSet && !includeSet.has(key)) continue;\n\n const oldValue = beforeObj[key];\n const newValue = afterObj[key];\n if (valuesEqual(oldValue, newValue)) continue;\n\n changes[key] = {\n oldValue: oldValue === undefined ? null : oldValue,\n newValue: newValue === undefined ? null : newValue,\n type: { old: valueType(oldValue), new: valueType(newValue) },\n };\n }\n\n return changes;\n}\n","/**\n * @module servers/crud/rules\n *\n * Rules and diff engine for CRUD authorization and field-level before rules.\n */\nimport { valuesEqual } from \"../../history/diff\";\nimport type { AuthUser } from \"../auth\";\nimport type {\n CrudUpdateRuleContext,\n DeepDiffReturn,\n Rule,\n RulesMap,\n} from \"./types\";\n\n/**\n * Computes a typed diff between the existing document (`before`) and the incoming partial changes (`changesInput`).\n * Only fields whose values have actually changed (via structural equality) are included in `changes`.\n */\nexport function computeDeepDiff<T extends Record<string, unknown>>(\n before: T,\n changesInput: Partial<T>,\n): DeepDiffReturn<T> {\n const beforeObj = before || ({} as T);\n const changes: Partial<T> = {};\n const after: T = { ...beforeObj };\n\n for (const [key, val] of Object.entries(changesInput || {})) {\n const oldVal = (beforeObj as any)[key];\n if (!valuesEqual(oldVal, val)) {\n (changes as any)[key] = val;\n (after as any)[key] = val;\n }\n }\n\n return {\n before: beforeObj,\n after,\n changes,\n };\n}\n\n/**\n * Helper to define field-by-field before-rules with strong typing.\n */\nexport function createRules<T>(\n rules: RulesMap<T>,\n): RulesMap<T> {\n return rules;\n}\n\n/**\n * Executes a map of field rules against a computed diff.\n * Evaluates rules only for the keys that changed in `diff.changes`.\n * Returns `{ allowed: true }` if all rules pass, or `{ allowed: false, reason: rule.description }` on the first failure.\n */\nexport async function applyRules<T>(\n diff: DeepDiffReturn<T>,\n rulesMap: RulesMap<T>,\n user?: AuthUser,\n): Promise<{ allowed: boolean; reason?: string }> {\n const changes = diff.changes || {};\n for (const key of Object.keys(changes) as (keyof T)[]) {\n const rules = rulesMap[key];\n if (rules && rules.length > 0) {\n for (const rule of rules) {\n const res = await rule.rule({\n diff,\n key,\n user,\n authenticatedUser: user,\n });\n if (res === false) {\n return { allowed: false, reason: rule.description };\n }\n }\n }\n }\n return { allowed: true };\n}\n\n/**\n * Wraps a rules map into a standard `rules.update` handler for `createCrudServer`.\n */\nexport function createBeforeRules<T>(\n rulesMap: RulesMap<T>,\n): (ctx: CrudUpdateRuleContext<T>) => Promise<{ allowed: boolean; reason?: string }> {\n return async (ctx: CrudUpdateRuleContext<T>) => {\n return applyRules(ctx.diff, rulesMap, ctx.user);\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 { z } from \"zod\";\nimport {\n coerceToDate,\n getDateHandling,\n maybeNormalize,\n} from \"../../shared/date-config\";\nimport {\n extractPathArgsFromDoc,\n generateFirestoreId,\n} from \"../../shared/path-template\";\nimport { getArrayElementType } from \"../../shared/zod-compat\";\nimport { toQueryError, type QueryErrorContext } from \"../admin/index-url\";\nimport { computeDeepDiff } from \"./rules\";\nimport type {\n ApiResponse,\n CrudHookErrorCallback,\n CrudHookErrorContext,\n CrudRepoEntry,\n CrudRepoRegistry,\n DeepDiffReturn,\n IndexErrorCallback,\n ListResponseData,\n QueryRequestBody,\n RuleResult,\n} from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Pagination validation\n// ---------------------------------------------------------------------------\n\nconst MAX_CRUD_PAGE_SIZE = 1000;\n\nfunction parseCrudPageSize(\n raw: unknown,\n defaultPageSize: number,\n): { success: true; value: number } | { success: false; error: string } {\n if (raw === undefined) {\n return {\n success: true,\n value: Math.min(Math.max(1, defaultPageSize), MAX_CRUD_PAGE_SIZE),\n };\n }\n const num =\n typeof raw === \"number\"\n ? raw\n : typeof raw === \"string\" && raw.trim() !== \"\"\n ? Number(raw)\n : NaN;\n if (!Number.isInteger(num) || num <= 0 || num > MAX_CRUD_PAGE_SIZE) {\n return {\n success: false,\n error: `Invalid pageSize: must be an integer between 1 and ${MAX_CRUD_PAGE_SIZE}`,\n };\n }\n return { success: true, value: num };\n}\n\n// ---------------------------------------------------------------------------\n// Response helpers\n// ---------------------------------------------------------------------------\n\nfunction sendJson<T>(c: any, data: ApiResponse<T>, status = 200) {\n const payload = maybeNormalize(data);\n return c.json(payload, status as any);\n}\n\nfunction sendSuccess<T>(\n c: any,\n data: T,\n meta?: ApiResponse[\"meta\"],\n status = 200,\n) {\n return sendJson(c, { success: true, data, meta }, status);\n}\n\nfunction sendError(c: any, error: string, status = 400) {\n return sendJson(c, { success: false, error }, status);\n}\n\n/**\n * Send a structured error response. When the underlying Firestore error is a\n * missing-index (`FAILED_PRECONDITION` / code 9), include `errorType: \"index\"`\n * and an `indexUrl` pointing to the Firebase Console index-creation wizard —\n * crucial for collection-group queries where the SDK omits the link.\n */\nasync function sendQueryError(\n c: any,\n err: unknown,\n ctx: QueryErrorContext & { repoName?: string },\n fallbackMessage: string,\n verbose: boolean,\n onIndexError?: IndexErrorCallback,\n) {\n const qe = toQueryError(err, ctx);\n const isIndex = qe.type === \"index\";\n const status = isIndex ? 424 : 500;\n const message = isIndex\n ? qe.message\n : verbose && err instanceof Error\n ? err.message\n : fallbackMessage;\n const payload: ApiResponse = { success: false, error: message };\n if (isIndex) {\n payload.errorType = \"index\";\n if (qe.indexUrl) {\n payload.indexUrl = qe.indexUrl;\n if (onIndexError) {\n try {\n const res = onIndexError({\n indexUrl: qe.indexUrl,\n repoName: ctx.repoName ?? \"\",\n path: ctx.path,\n isGroup: ctx.isGroup,\n filters: ctx.filters,\n sort: ctx.sort,\n error: err,\n c,\n });\n if (res instanceof Promise) {\n await res;\n }\n } catch (cbErr) {\n if (verbose) {\n // eslint-disable-next-line no-console\n console.error(\"[crudServer] Error in indexesError callback:\", cbErr);\n }\n }\n }\n }\n }\n return sendJson(c, payload, status);\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/** Helper to unwrap Zod modifiers (optional, nullable, default, catch, effects, etc.) */\nfunction unwrapZodType(zodType: any): any {\n let cur = zodType;\n while (cur) {\n const def = cur._zod?.def ?? cur._def;\n if (!def) break;\n if (def.innerType) {\n cur = def.innerType;\n } else if (def.schema) {\n cur = def.schema;\n } else if (\n def.type === \"optional\" ||\n def.type === \"nullable\" ||\n def.type === \"default\" ||\n def.type === \"catch\" ||\n def.type === \"effects\"\n ) {\n cur = def.innerType ?? def.schema;\n } else {\n break;\n }\n }\n return cur;\n}\n\n/** Resolve a dot-notation path (e.g. \"address.city\") from a Zod schema */\nfunction resolveFieldPathSchema(entrySchema: any, path: string): any {\n const parts = path.split(\".\");\n let cur = unwrapZodType(entrySchema);\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n if (!part) continue;\n const shape: Record<string, any> | undefined = (cur as any)?.shape;\n if (!shape || !shape[part]) {\n return undefined;\n }\n const rawSub = shape[part];\n if (i === parts.length - 1) {\n return rawSub;\n }\n cur = unwrapZodType(rawSub);\n }\n return cur;\n}\n\n/** Recursively make Zod objects deep-partial for PATCH updates */\nfunction makeDeepPartial(s: z.ZodType): z.ZodType {\n const def = (s as any)?._zod?.def ?? (s as any)?._def;\n const typeName = def?.typeName ?? def?.type;\n\n if (typeName === \"ZodObject\" || typeName === \"object\") {\n const shape = (s as z.ZodObject<any>).shape;\n const newShape: Record<string, z.ZodType> = {};\n for (const [k, v] of Object.entries(shape)) {\n newShape[k] = makeDeepPartial(v as z.ZodType);\n }\n return z.object(newShape).partial();\n }\n\n if (typeName === \"ZodOptional\" || typeName === \"optional\") {\n const inner = def.innerType as z.ZodType | undefined;\n if (!inner) return s;\n const nextInner = makeDeepPartial(inner);\n return nextInner === inner ? s : nextInner.optional();\n }\n\n if (typeName === \"ZodNullable\" || typeName === \"nullable\") {\n const inner = def.innerType as z.ZodType | undefined;\n if (!inner) return s;\n const nextInner = makeDeepPartial(inner);\n return nextInner === inner ? s : nextInner.nullable();\n }\n\n if (typeName === \"ZodDefault\" || typeName === \"default\") {\n const inner = def.innerType as z.ZodType | undefined;\n if (!inner) return s;\n return makeDeepPartial(inner).optional();\n }\n\n if (typeName === \"ZodUnion\" || typeName === \"union\") {\n const options = def.options as z.ZodType[] | undefined;\n if (!options || options.length < 2) return s;\n const nextOptions = options.map((opt) => makeDeepPartial(opt));\n const changed = nextOptions.some((opt, i) => opt !== options[i]);\n return changed ? z.union(nextOptions as any) : s;\n }\n\n return s;\n}\n\n/**\n * Validate data against schema and return parsed result or error.\n * Supports dot-notation keys (e.g. \"address.city\") and deep partial nested objects.\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 if (typeof data !== \"object\" || data === null || Array.isArray(data)) {\n return { success: false, error: \"Data payload must be an object\" };\n }\n\n try {\n const dataObj = data as Record<string, unknown>;\n const resultData: Record<string, unknown> = {};\n const normalEntries: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(dataObj)) {\n if (key.includes(\".\")) {\n // Dot notation key (e.g. \"address.city\")\n const topLevel = key.split(\".\")[0]!;\n if (systemKeys.includes(key) || systemKeys.includes(topLevel)) {\n continue;\n }\n if (fields && fields.length > 0) {\n if (!fields.includes(key) && !fields.includes(topLevel)) {\n return {\n success: false,\n error: `Field '${key}' is not allowed for this operation`,\n };\n }\n }\n const fieldSchema = resolveFieldPathSchema(schema, key);\n if (!fieldSchema) {\n return {\n success: false,\n error: `Field '${key}' does not exist in schema`,\n };\n }\n const effectiveFieldSchema = partial\n ? makeDeepPartial(fieldSchema)\n : fieldSchema;\n const wrappedSchema =\n getDateHandling() === \"normalize\"\n ? wrapDateSchemas(effectiveFieldSchema)\n : effectiveFieldSchema;\n const parsedValue = wrappedSchema.parse(value);\n resultData[key] = parsedValue;\n } else {\n normalEntries[key] = value;\n }\n }\n\n if (\n Object.keys(normalEntries).length > 0 ||\n Object.keys(resultData).length === 0\n ) {\n const targetSchema = pickSchemaFields(schema, fields, systemKeys);\n const partialSchema = partial\n ? (makeDeepPartial(targetSchema) as z.ZodObject<any>)\n : targetSchema;\n const finalSchema =\n getDateHandling() === \"normalize\"\n ? (wrapDateSchemas(partialSchema) as z.ZodObject<any>)\n : partialSchema;\n const parsedNormal = finalSchema.parse(normalEntries);\n Object.assign(resultData, parsedNormal);\n }\n\n return { success: true, data: resultData };\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\nexport type WhereOp =\n | \"==\"\n | \"!=\"\n | \"<\"\n | \"<=\"\n | \">\"\n | \">=\"\n | \"in\"\n | \"not-in\"\n | \"array-contains\"\n | \"array-contains-any\";\n\nconst OP_MAP: Record<string, WhereOp> = {\n eq: \"==\",\n \"==\": \"==\",\n ne: \"!=\",\n \"!=\": \"!=\",\n lt: \"<\",\n \"<\": \"<\",\n lte: \"<=\",\n \"<=\": \"<=\",\n gt: \">\",\n \">\": \">\",\n gte: \">=\",\n \">=\": \">=\",\n in: \"in\",\n nin: \"not-in\",\n \"not-in\": \"not-in\",\n not_in: \"not-in\",\n contains: \"array-contains\",\n \"array-contains\": \"array-contains\",\n array_contains: \"array-contains\",\n arrayContains: \"array-contains\",\n containsAny: \"array-contains-any\",\n \"array-contains-any\": \"array-contains-any\",\n array_contains_any: \"array-contains-any\",\n arrayContainsAny: \"array-contains-any\",\n};\n\n/**\n * Normalize any operator string (e.g. contains, array-contains, eq, nin) to a canonical WhereOp.\n */\nexport function normalizeWhereOp(op: string): WhereOp {\n return OP_MAP[op] ?? (op as WhereOp);\n}\n\nfunction isValidOp(op: string): boolean {\n return op in OP_MAP;\n}\n\ninterface ParsedFilter {\n field: string;\n op: WhereOp;\n value: unknown;\n}\n\n/**\n * Safely parse a filter value using the entity's schema field definition (if present).\n * If safeParse succeeds, returns the parsed data.\n * If safeParse fails on a single value but value is an Array, attempts to safeParse each item.\n */\nexport function parseFieldValue(\n entrySchema: unknown,\n field: string,\n val: unknown,\n op?: WhereOp | string,\n): { success: true; data: unknown } | { success: false; error: string } {\n const fieldSchema = resolveFieldPathSchema(entrySchema, field);\n if (!fieldSchema || typeof fieldSchema.safeParse !== \"function\") {\n return { success: true, data: val };\n }\n\n const normalizedOp = op ? normalizeWhereOp(op) : undefined;\n const unwrapped = unwrapZodType(fieldSchema);\n const elemSchema = getArrayElementType(unwrapped);\n\n // If the operator is array-contains, validate against the element schema\n if (normalizedOp === \"array-contains\") {\n const targetSchema = elemSchema ?? fieldSchema;\n if (typeof targetSchema.safeParse === \"function\") {\n const parsed = targetSchema.safeParse(val);\n if (parsed.success) {\n return { success: true, data: parsed.data };\n }\n const messages = parsed.error.issues\n .map((e: any) => e.message)\n .join(\", \");\n return { success: false, error: messages };\n }\n return { success: true, data: val };\n }\n\n // If the operator is array-contains-any, validate each element\n if (normalizedOp === \"array-contains-any\") {\n if (!Array.isArray(val)) {\n return {\n success: false,\n error: \"Expected array value for array-contains-any\",\n };\n }\n const targetSchema = elemSchema ?? fieldSchema;\n const parsedArray: unknown[] = [];\n for (const item of val) {\n if (typeof targetSchema.safeParse === \"function\") {\n const itemParsed = targetSchema.safeParse(item);\n if (itemParsed.success) {\n parsedArray.push(itemParsed.data);\n } else {\n const errorMessage = itemParsed.error.issues\n .map((e: any) => e.message)\n .join(\", \");\n return { success: false, error: errorMessage };\n }\n } else {\n parsedArray.push(item);\n }\n }\n return { success: true, data: parsedArray };\n }\n\n // Standard safeParse for the field\n const parsed = fieldSchema.safeParse(val);\n if (parsed.success) {\n return { success: true, data: parsed.data };\n }\n\n // If safeParse failed and val is an Array (e.g. for in / not-in on scalar field),\n // try parsing each item with targetSchema\n if (Array.isArray(val)) {\n const targetSchema = elemSchema ?? fieldSchema;\n const parsedArray: unknown[] = [];\n for (const item of val) {\n if (typeof targetSchema.safeParse === \"function\") {\n const itemParsed = targetSchema.safeParse(item);\n if (itemParsed.success) {\n parsedArray.push(itemParsed.data);\n } else {\n const errorMessage = itemParsed.error.issues\n .map((e: any) => e.message)\n .join(\", \");\n return { success: false, error: errorMessage };\n }\n } else {\n parsedArray.push(item);\n }\n }\n return { success: true, data: parsedArray };\n }\n\n const messages = parsed.error.issues\n .map((e: any) => e.message)\n .join(\", \");\n return { success: false, error: messages };\n}\n\n/**\n * Parse query params into filter conditions.\n * Supports:\n * - field=value → field == value\n * - field__op=value → field op value (e.g., status__ne=draft → status != draft)\n * - field__in=a,b,c → field in [a, b, c]\n */\nexport function 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 for (const [key, rawVal] of Object.entries(query)) {\n if (rawVal === undefined) continue;\n\n // Skip pagination/meta params\n if (\n [\n \"cursor\",\n \"direction\",\n \"limit\",\n \"pageSize\",\n \"orderBy\",\n \"orderDir\",\n \"select\",\n \"includes\",\n \"withTotal\",\n ].includes(key)\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 lastDoubleUnderscore = key.lastIndexOf(\"__\");\n let field: string;\n let op: WhereOp = \"==\";\n\n if (lastDoubleUnderscore !== -1) {\n const fieldCandidate = key.slice(0, lastDoubleUnderscore);\n const opKey = key.slice(lastDoubleUnderscore + 2);\n if (isValidOp(opKey)) {\n field = fieldCandidate;\n op = normalizeWhereOp(opKey);\n } else {\n field = key;\n op = \"==\";\n }\n } else {\n field = key;\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\", \"not-in\", and \"array-contains-any\" operators (comma-separated)\n if (op === \"in\" || op === \"not-in\" || op === \"array-contains-any\") {\n parsedVal = val.split(\",\").map((v) => parseValue(v.trim()));\n } else {\n parsedVal = parseValue(val);\n }\n\n filters.push({ field, op, value: parsedVal });\n }\n\n return filters;\n}\n\n/**\n * Parse a string value into appropriate type.\n */\nfunction parseValue(val: string): unknown {\n // Boolean\n if (val === \"true\") return true;\n if (val === \"false\") return false;\n if (val === \"null\" || val === \"__null__\") return null;\n\n // Number\n const num = Number(val);\n if (!isNaN(num) && val !== \"\") return num;\n\n // String\n return val;\n}\n\n// ---------------------------------------------------------------------------\n// Cursor serialization helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Serialize a Firestore DocumentSnapshot to a JSON-safe cursor object.\n */\nfunction serializeCursor(\n snapshot: import(\"firebase-admin/firestore\").DocumentSnapshot | undefined,\n): Record<string, unknown> | null {\n if (!snapshot) return null;\n return {\n docId: snapshot.id,\n docPath: snapshot.ref?.path ?? undefined,\n };\n}\n\n/**\n * Deserialize a cursor object back to a DocumentSnapshot.\n * Fetches the document from Firestore to get the actual snapshot.\n * Supports root collections and subcollections/collection groups via full docPath.\n */\nasync function deserializeCursor(\n entry: CrudRepoEntry,\n cursor: unknown,\n): Promise<import(\"firebase-admin/firestore\").DocumentSnapshot | undefined> {\n if (!cursor) return undefined;\n\n let cursorObj: Record<string, unknown> | undefined;\n if (typeof cursor === \"string\") {\n try {\n cursorObj = JSON.parse(cursor);\n } catch {\n cursorObj = cursor.includes(\"/\")\n ? { docPath: cursor }\n : { docId: cursor };\n }\n } else if (typeof cursor === \"object\") {\n cursorObj = cursor as Record<string, unknown>;\n }\n\n if (!cursorObj) return undefined;\n\n const docPath =\n typeof cursorObj.docPath === \"string\" ? cursorObj.docPath : undefined;\n const docId =\n typeof cursorObj.docId === \"string\" ? cursorObj.docId : undefined;\n\n try {\n const colRef = entry.repo.ref as any;\n const firestore = colRef?.firestore;\n\n // 1. If docPath is available and firestore instance exists, get doc directly by full path\n if (docPath && firestore && typeof firestore.doc === \"function\") {\n const snapshot = await firestore.doc(docPath).get();\n if (snapshot.exists) return snapshot;\n }\n\n // 2. If docId is a full path (e.g. \"users/u1/comments/c1\"), get doc by full path\n if (docId && docId.includes(\"/\") && firestore && typeof firestore.doc === \"function\") {\n const snapshot = await firestore.doc(docId).get();\n if (snapshot.exists) return snapshot;\n }\n\n // 3. Root collection fallback (colRef.doc exists for CollectionReference)\n if (docId && typeof colRef.doc === \"function\") {\n const snapshot = await colRef.doc(docId).get();\n if (snapshot.exists) return snapshot;\n }\n\n return undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Extract a non-empty plain object of defined fields from a hook's optional\n * `changesNeeded` return value (`Partial<T>`). Returns `null` when empty or\n * not a plain object, and strips `undefined` entries so Firestore `.update()`\n * does not fail on undefined values.\n */\nfunction pickDefinedChanges(value: unknown): Record<string, unknown> | null {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return null;\n }\n const defined: Record<string, unknown> = {};\n let count = 0;\n for (const [k, v] of Object.entries(value)) {\n if (v !== undefined) {\n defined[k] = v;\n count++;\n }\n }\n return count > 0 ? defined : null;\n}\n\n// ---------------------------------------------------------------------------\n// Handlers factory\n// ---------------------------------------------------------------------------\n\nexport function createCrudHandlers(\n registry: CrudRepoRegistry,\n basePath: string,\n verbose: boolean,\n onIndexError?: IndexErrorCallback,\n onHookError?: CrudHookErrorCallback,\n) {\n /**\n * Report an error thrown by a post-write hook (or its follow-up `changesNeeded`\n * update) without turning a committed write into a misleading HTTP 500.\n */\n async function reportHookError(\n entry: CrudRepoEntry,\n logger: any,\n errCtx: Omit<CrudHookErrorContext, \"error\">,\n error: unknown,\n ): Promise<void> {\n let handled = false;\n if (entry.hooks?.onAfterError) {\n handled = true;\n try {\n const res = entry.hooks.onAfterError(error, errCtx.hook);\n if (res instanceof Promise) {\n await res;\n }\n } catch (cbErr) {\n // eslint-disable-next-line no-console\n console.error(\"[crudServer] Error in hooks.onAfterError callback:\", cbErr);\n }\n }\n if (onHookError) {\n handled = true;\n try {\n const res = onHookError({ ...errCtx, error });\n if (res instanceof Promise) {\n await res;\n }\n } catch (cbErr) {\n // eslint-disable-next-line no-console\n console.error(\"[crudServer] Error in onHookError callback:\", cbErr);\n }\n }\n if (handled) return;\n if (logger && typeof logger.error === \"function\") {\n logger.error(error, {\n hook: errCtx.hook,\n repoName: errCtx.repoName,\n path: errCtx.path,\n ...(errCtx.id !== undefined ? { id: errCtx.id } : {}),\n ...(errCtx.pathArgs !== undefined\n ? { pathArgs: errCtx.pathArgs }\n : {}),\n });\n return;\n }\n // eslint-disable-next-line no-console\n console.error(\n `[crudServer] Hook \"${errCtx.hook}\" failed on repo \"${errCtx.repoName}\":`,\n {\n hook: errCtx.hook,\n repoName: errCtx.repoName,\n path: errCtx.path,\n ...(errCtx.id !== undefined ? { id: errCtx.id } : {}),\n ...(errCtx.pathArgs !== undefined\n ? { pathArgs: errCtx.pathArgs }\n : {}),\n error,\n },\n );\n }\n // ── Authorization helpers ───────────────────────────────────────────────\n /**\n * Default-deny gate: when the server has `auth` configured, reject any\n * operation without an explicit rule. When `auth` is absent, rules are\n * ignored entirely (open API).\n */\n async function assertRule<TCtx>(\n c: any,\n entry: CrudRepoEntry,\n op: keyof NonNullable<CrudRepoEntry[\"rules\"]>,\n ctx: TCtx,\n ): Promise<{ allowed: boolean; errorResponse?: any }> {\n if (!entry.rules) return { allowed: true };\n const rule = entry.rules?.[op] as\n | ((c: TCtx) => RuleResult | Promise<RuleResult>)\n | undefined;\n if (!rule) {\n return {\n allowed: false,\n errorResponse: sendError(\n c,\n `Operation \"${op}\" is not allowed for this repository`,\n 403,\n ),\n };\n }\n try {\n const res = await rule(ctx);\n if (res === false) {\n return {\n allowed: false,\n errorResponse: sendError(c, \"Forbidden\", 403),\n };\n }\n if (typeof res === \"string\") {\n return {\n allowed: false,\n errorResponse: sendError(c, res, 403),\n };\n }\n if (typeof res === \"object\" && res !== null && !res.allowed) {\n return {\n allowed: false,\n errorResponse: sendError(c, res.reason || \"Forbidden\", 403),\n };\n }\n return { allowed: true };\n } catch (err) {\n const message =\n verbose && err instanceof Error ? err.message : \"Forbidden\";\n return {\n allowed: false,\n errorResponse: sendError(c, message, 403),\n };\n }\n }\n\n /** Apply `rules.filter` to every doc in a list; returns the filtered slice. */\n async function applyRowFilter<T extends Record<string, unknown>>(\n entry: CrudRepoEntry,\n user: any,\n params: Record<string, string>,\n docs: T[],\n ): Promise<T[]> {\n if (!entry.rules) return docs;\n const filter = entry.rules?.filter as\n | ((c: {\n user: any;\n doc: T;\n params: Record<string, string>;\n }) => boolean | Promise<boolean>)\n | undefined;\n if (!filter) return docs;\n const out: T[] = [];\n for (const doc of docs) {\n try {\n if (await filter({ user, doc, params })) out.push(doc);\n } catch {\n // exclude on error (fail closed)\n }\n }\n return out;\n }\n\n /** Pull the authenticated user from the request (may be undefined when auth is off). */\n function userOf(c: any): any {\n return c.get(\"user\") ?? c.get(\"docsUser\") ?? null;\n }\n\n // ── Helper to get repo entry ────────────────────────────────────────────\n function getRepoEntry(\n repoName: string | undefined,\n c: any,\n ): CrudRepoEntry | null {\n if (!repoName) {\n const parts = c.req.path.split(\"/\");\n for (const part of parts) {\n if (registry[part]) {\n repoName = part;\n break;\n }\n }\n }\n if (!repoName || !registry[repoName]) {\n return null;\n }\n return registry[repoName] ?? null;\n }\n\n /**\n * Extract Firestore document path args from a document's stored path.\n * e.g. \"posts/abc/comments/xyz\" → [\"abc\", \"xyz\"] (the doc-ID segments).\n */\n function extractPathArgs(\n doc: Record<string, unknown>,\n entry: CrudRepoEntry,\n ): string[] | undefined {\n return extractPathArgsFromDoc(doc, {\n pathKey: entry.pathKey,\n documentKey: entry.documentKey,\n parentKeys: entry.parentKeys,\n documentPathTemplate: entry.documentPathTemplate,\n isGroup: entry.isGroup,\n });\n }\n\n /**\n * Fetch a single document by its documentKey, with fallback to query\n * for collection-group repos where direct documentRef may fail.\n */\n async function fetchDocById(\n entry: CrudRepoEntry,\n docId: string,\n ): Promise<Record<string, unknown> | null> {\n const getterName = `by${entry.documentKey.charAt(0).toUpperCase()}${entry.documentKey.slice(1)}`;\n const getter = (entry.repo.get as any)[getterName];\n\n if (typeof getter === \"function\") {\n try {\n const doc = (await getter(docId)) as Record<string, unknown> | null;\n if (doc) return doc;\n } catch {\n // Direct ref may fail for subcollections — fall through to query\n }\n }\n\n const results = await entry.repo.query.by({\n where: [[entry.documentKey, \"==\", docId]],\n limit: 1,\n });\n return (results[0] as Record<string, unknown>) ?? null;\n }\n\n // ── LIST: GET /:repoName ────────────────────────────────────────────────\n async function handleList(ctx: any): Promise<any> {\n const c = ctx.c;\n\n const params = c.req.param();\n const entry = getRepoEntry(params.repoName, c);\n if (!entry) return sendError(c, `Repository not found`, 404);\n\n const user = userOf(c);\n const ruleCheck = await assertRule(c, entry, \"list\", {\n user,\n query: c.req.query(),\n params,\n });\n if (!ruleCheck.allowed) return ruleCheck.errorResponse;\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 pageSizeRes = parseCrudPageSize(query.pageSize, entry.pageSize);\n if (!pageSizeRes.success) {\n return sendError(c, pageSizeRes.error, 400);\n }\n const pageSize = pageSizeRes.value;\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 const withTotalParam = query.withTotal;\n const withTotal =\n withTotalParam === \"true\" ||\n withTotalParam === \"1\" ||\n withTotalParam === true;\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 ...(withTotal ? { withTotal: true } : {}),\n };\n\n if (cursor) {\n try {\n const cursorObj =\n typeof cursor === \"string\" ? JSON.parse(cursor) : cursor;\n queryOptions.cursor = await deserializeCursor(entry, cursorObj);\n } catch {\n // Invalid cursor, ignore\n }\n }\n\n if (orderBy) {\n if (entry.orderableFields && !entry.orderableFields.includes(orderBy)) {\n return sendError(c, `Field not orderable: ${orderBy}`, 400);\n }\n queryOptions.orderBy = [{ field: orderBy, direction: orderDir }];\n }\n\n if (filters.length > 0) {\n queryOptions.where = [];\n for (const f of filters) {\n const parsedRes = parseFieldValue(entry.schema, f.field, f.value, f.op);\n if (!parsedRes.success) {\n return sendError(\n c,\n `Invalid filter value for '${f.field}': ${parsedRes.error}`,\n 400,\n );\n }\n queryOptions.where.push([f.field, f.op, parsedRes.data]);\n }\n }\n\n if (select) {\n queryOptions.select = select as any;\n }\n\n if (includes) {\n queryOptions.include = includes as any;\n }\n\n // Execute query\n const result = await entry.repo.query.paginate(queryOptions);\n const filteredItems = await applyRowFilter(\n entry,\n userOf(c),\n params,\n result.data,\n );\n\n const responseData: ListResponseData = {\n items: filteredItems,\n hasNextPage: result.hasNextPage,\n hasPrevPage: result.hasPrevPage,\n nextCursor: serializeCursor(result.nextCursor),\n prevCursor: serializeCursor(result.prevCursor),\n ...(result.totalCount !== undefined\n ? {\n totalCount: result.totalCount,\n totalCountIsExact: result.totalCountIsExact,\n }\n : {}),\n };\n\n return sendSuccess(c, responseData, {\n pageSize,\n hasMore: result.hasNextPage,\n ...(result.totalCount !== undefined\n ? {\n totalCount: result.totalCount,\n totalCountIsExact: result.totalCountIsExact,\n }\n : {}),\n });\n } catch (err) {\n return await sendQueryError(\n c,\n err,\n {\n repoName: params.repoName || entry.name,\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 onIndexError,\n );\n }\n }\n\n // ── QUERY: POST /:repoName/query ────────────────────────────────────────\n // Advanced query endpoint supporting OR conditions, array filters, etc.\n async function handleQuery(ctx: any): Promise<any> {\n const c = ctx.c;\n\n const params = c.req.param();\n const entry = getRepoEntry(params.repoName, c);\n if (!entry) return sendError(c, `Repository not found`, 404);\n\n const user = userOf(c);\n const ruleCheck = await assertRule(c, entry, \"list\", {\n user,\n query: ctx.input || {},\n params,\n });\n if (!ruleCheck.allowed) return ruleCheck.errorResponse;\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 pageSizeRes = parseCrudPageSize(body.pageSize, entry.pageSize);\n if (!pageSizeRes.success) {\n return sendError(c, pageSizeRes.error, 400);\n }\n const pageSize = pageSizeRes.value;\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 const withTotal =\n body.withTotal === true || String(body.withTotal) === \"true\";\n\n // Build query options\n const queryOptions: any = {\n pageSize,\n direction,\n ...(withTotal ? { withTotal: true } : {}),\n };\n\n // Cursor\n if (body.cursor) {\n try {\n const cursorObj =\n typeof body.cursor === \"string\"\n ? JSON.parse(body.cursor)\n : body.cursor;\n queryOptions.cursor = await deserializeCursor(entry, cursorObj);\n } catch {\n // Invalid cursor, ignore\n }\n }\n\n // Includes (relation population)\n if (entry.allowedIncludes && body.includes && body.includes.length > 0) {\n const validIncludes = body.includes.filter((inc) => {\n if (typeof inc === \"string\") {\n return entry.allowedIncludes!.includes(inc);\n }\n if (\n typeof inc === \"object\" &&\n inc !== null &&\n \"relation\" in inc &&\n typeof inc.relation === \"string\"\n ) {\n return entry.allowedIncludes!.includes(inc.relation);\n }\n return false;\n });\n if (validIncludes.length > 0) {\n queryOptions.include = validIncludes as any;\n }\n }\n\n // Where conditions (AND)\n if (body.where && body.where.length > 0) {\n // Validate filterable fields if configured\n if (entry.filterableFields) {\n const allowed = new Set(entry.filterableFields);\n const invalid = body.where.filter((w) => !allowed.has(w[0]));\n if (invalid.length > 0) {\n sendError(\n c,\n `Fields not filterable: ${invalid.map((w) => w[0]).join(\", \")}`,\n 400,\n );\n return;\n }\n }\n const parsedWhere: [string, any, any][] = [];\n for (const w of body.where) {\n const normalizedOp = normalizeWhereOp(w[1]);\n const parsedRes = parseFieldValue(entry.schema, w[0], w[2], normalizedOp);\n if (!parsedRes.success) {\n sendError(\n c,\n `Invalid filter value for '${w[0]}': ${parsedRes.error}`,\n 400,\n );\n return;\n }\n parsedWhere.push([w[0], normalizedOp, parsedRes.data]);\n }\n queryOptions.where = parsedWhere;\n }\n\n // OR where conditions (simple)\n if (body.orWhere && body.orWhere.length > 0) {\n if (entry.filterableFields) {\n const allowed = new Set(entry.filterableFields);\n const invalid = body.orWhere.filter((w) => !allowed.has(w[0]));\n if (invalid.length > 0) {\n sendError(\n c,\n `Fields not filterable: ${invalid.map((w) => w[0]).join(\", \")}`,\n 400,\n );\n return;\n }\n }\n const parsedOrWhere: [string, any, any][] = [];\n for (const w of body.orWhere) {\n const normalizedOp = normalizeWhereOp(w[1]);\n const parsedRes = parseFieldValue(entry.schema, w[0], w[2], normalizedOp);\n if (!parsedRes.success) {\n sendError(\n c,\n `Invalid filter value for '${w[0]}': ${parsedRes.error}`,\n 400,\n );\n return;\n }\n parsedOrWhere.push([w[0], normalizedOp, parsedRes.data]);\n }\n queryOptions.orWhere = parsedOrWhere;\n }\n\n // OR where groups (advanced)\n if (body.orWhereGroups && body.orWhereGroups.length > 0) {\n if (entry.filterableFields) {\n const allowed = new Set(entry.filterableFields);\n for (const group of body.orWhereGroups) {\n const invalid = group.filter((w) => !allowed.has(w[0]));\n if (invalid.length > 0) {\n sendError(\n c,\n `Fields not filterable: ${invalid.map((w) => w[0]).join(\", \")}`,\n 400,\n );\n return;\n }\n }\n }\n const parsedOrWhereGroups: [string, any, any][][] = [];\n for (const group of body.orWhereGroups) {\n const parsedGroup: [string, any, any][] = [];\n for (const w of group) {\n const normalizedOp = normalizeWhereOp(w[1]);\n const parsedRes = parseFieldValue(entry.schema, w[0], w[2], normalizedOp);\n if (!parsedRes.success) {\n sendError(\n c,\n `Invalid filter value for '${w[0]}': ${parsedRes.error}`,\n 400,\n );\n return;\n }\n parsedGroup.push([w[0], normalizedOp, parsedRes.data]);\n }\n parsedOrWhereGroups.push(parsedGroup);\n }\n queryOptions.orWhereGroups = parsedOrWhereGroups;\n }\n\n // Order by\n if (body.orderBy && body.orderBy.length > 0) {\n if (entry.orderableFields) {\n const allowed = new Set(entry.orderableFields);\n const invalid = body.orderBy.filter((o) => !allowed.has(o.field));\n if (invalid.length > 0) {\n sendError(\n c,\n `Fields not orderable: ${invalid.map((o) => o.field).join(\", \")}`,\n 400,\n );\n return;\n }\n }\n queryOptions.orderBy = body.orderBy;\n }\n\n // Select\n if (body.select && body.select.length > 0) {\n queryOptions.select = body.select;\n }\n\n // Execute query\n const result = await entry.repo.query.paginate(queryOptions);\n const filteredItems = await applyRowFilter(\n entry,\n userOf(c),\n params,\n result.data,\n );\n\n const responseData: ListResponseData = {\n items: filteredItems,\n hasNextPage: result.hasNextPage,\n hasPrevPage: result.hasPrevPage,\n nextCursor: serializeCursor(result.nextCursor),\n prevCursor: serializeCursor(result.prevCursor),\n ...(result.totalCount !== undefined\n ? {\n totalCount: result.totalCount,\n totalCountIsExact: result.totalCountIsExact,\n }\n : {}),\n };\n\n return sendSuccess(c, responseData, {\n pageSize,\n hasMore: result.hasNextPage,\n ...(result.totalCount !== undefined\n ? {\n totalCount: result.totalCount,\n totalCountIsExact: result.totalCountIsExact,\n }\n : {}),\n });\n } catch (err) {\n return await sendQueryError(\n c,\n err,\n {\n repoName: params.repoName || entry.name,\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 onIndexError,\n );\n }\n }\n\n // ── GET: GET /:repoName/:id ─────────────────────────────────────────────\n async function handleGet(ctx: any): Promise<any> {\n const c = ctx.c;\n\n const params = c.req.param();\n const entry = getRepoEntry(params.repoName, c);\n if (!entry) return sendError(c, `Repository not found`, 404);\n\n const id = params.id;\n if (!id) {\n return sendError(c, \"Document ID required\", 400);\n }\n\n try {\n const doc = await fetchDocById(entry, id);\n\n if (!doc) {\n return sendError(c, \"Document not found\", 404);\n }\n\n const user = userOf(c);\n const getRuleCheck = await assertRule(c, entry, \"get\", {\n user,\n doc: doc as any,\n params,\n });\n if (!getRuleCheck.allowed) return getRuleCheck.errorResponse;\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 return await sendQueryError(\n c,\n err,\n {\n repoName: params.repoName || entry.name,\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 onIndexError,\n );\n }\n }\n\n // ── CREATE: POST /:repoName ─────────────────────────────────────────────\n async function handleCreate(ctx: any): Promise<any> {\n const c = ctx.c;\n\n const params = c.req.param();\n const entry = getRepoEntry(params.repoName, c);\n if (!entry) return sendError(c, `Repository not found`, 404);\n\n try {\n const body = ctx.input || {};\n\n const user = userOf(c);\n const createRuleCheck = await assertRule(c, entry, \"create\", {\n user,\n body,\n params,\n });\n if (!createRuleCheck.allowed) return createRuleCheck.errorResponse;\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 // Pre-write mutations hook (mutates validation.data by reference)\n if (entry.hooks?.beforeCreate) {\n await entry.hooks.beforeCreate({\n user,\n body: validation.data as any,\n params,\n c,\n });\n }\n\n // Create document\n let created: any;\n let explicitPathArgs: string[] | undefined;\n if (entry.isGroup && entry.parentKeys && entry.parentKeys.length > 0) {\n const data: Record<string, any> = { ...validation.data };\n const missingKeys = entry.parentKeys.filter(\n (k) =>\n data[k] === undefined ||\n data[k] === null ||\n (typeof data[k] === \"string\" && data[k].trim() === \"\"),\n );\n if (missingKeys.length > 0) {\n return sendError(\n c,\n `Missing parent key(s) for subcollection create: ${missingKeys.join(\", \")}`,\n 400,\n );\n }\n if (typeof entry.repo.create === \"function\") {\n created = await entry.repo.create(data as any);\n } else {\n const parentIds = entry.parentKeys.map((k) => String(data[k]));\n const docId = data[entry.documentKey] || generateFirestoreId();\n explicitPathArgs = [...parentIds, docId];\n created = await entry.repo.set(...parentIds, docId, data);\n }\n } else {\n created = await entry.repo.create(validation.data as any);\n }\n\n let finalDoc = created;\n if (entry.hooks?.afterCreate) {\n const rawCreatedId =\n created?.[entry.documentKey] ??\n explicitPathArgs?.[explicitPathArgs.length - 1] ??\n \"\";\n const createdId = String(rawCreatedId);\n const pathArgs =\n explicitPathArgs ??\n extractPathArgs(created, entry) ??\n extractPathArgs(\n {\n ...validation.data,\n ...(createdId ? { [entry.documentKey]: createdId } : {}),\n },\n entry,\n ) ??\n (createdId ? [createdId] : []);\n\n try {\n const extraChanges = await entry.hooks.afterCreate({\n user,\n doc: created,\n id: createdId,\n pathArgs,\n params,\n c,\n });\n const definedChanges = pickDefinedChanges(extraChanges);\n if (definedChanges && pathArgs.length > 0) {\n finalDoc = await entry.repo.update(\n ...pathArgs,\n definedChanges as any,\n );\n }\n } catch (hookErr) {\n await reportHookError(\n entry,\n ctx.logger,\n {\n hook: \"afterCreate\",\n repoName: entry.name,\n path: entry.path,\n id: createdId,\n pathArgs,\n user,\n c,\n },\n hookErr,\n );\n }\n }\n\n return sendSuccess(c, finalDoc, undefined, 201);\n } catch (err) {\n const message =\n verbose && err instanceof Error\n ? err.message\n : \"Failed to create document\";\n return sendError(c, message, 500);\n }\n }\n\n // ── UPDATE: PUT/PATCH /:repoName/:id ────────────────────────────────────\n async function handleUpdate(ctx: any, partial: boolean): Promise<any> {\n const c = ctx.c;\n const params = c.req.param();\n const entry = getRepoEntry(params.repoName, c);\n if (!entry) return sendError(c, `Repository not found`, 404);\n\n const id = params.id;\n if (!id) {\n return sendError(c, \"Document ID required\", 400);\n }\n\n try {\n const body = ctx.input || {};\n\n // Fetch existing doc so the rule can authorize against current state\n const existingDoc = await fetchDocById(entry, id);\n if (!existingDoc) {\n return sendError(c, \"Document not found\", 404);\n }\n\n // 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 // Compute diff between existing doc and sanitized changes\n const diff = computeDeepDiff(existingDoc as any, validation.data);\n\n const user = userOf(c);\n const updateRuleCheck = await assertRule(c, entry, \"update\", {\n user,\n doc: existingDoc as any,\n body: validation.data,\n diff,\n params,\n });\n if (!updateRuleCheck.allowed) return updateRuleCheck.errorResponse;\n\n // Pre-write mutations hook (mutates validation.data by reference)\n if (entry.hooks?.beforeUpdate) {\n const preHookDiff = entry.rules?.update\n ? computeDeepDiff(existingDoc as any, validation.data)\n : diff;\n await entry.hooks.beforeUpdate({\n user,\n doc: existingDoc as any,\n body: validation.data as any,\n diff: preHookDiff,\n params,\n c,\n });\n }\n\n // Recompute diff AFTER rules.update & hooks.beforeUpdate so preWrite mutations are included\n const finalBody = { ...validation.data };\n const finalDiff = entry.hooks?.afterUpdate\n ? computeDeepDiff(existingDoc as any, finalBody)\n : diff;\n\n // Update document — derive path args for subcollections\n const pathArgs = extractPathArgs(existingDoc, entry) ?? [id];\n const updated = await entry.repo.update(\n ...pathArgs,\n validation.data as any,\n );\n\n let finalDoc = updated;\n if (entry.hooks?.afterUpdate) {\n try {\n const extraChanges = await entry.hooks.afterUpdate({\n user,\n before: existingDoc as any,\n after: updated as any,\n body: finalBody as any,\n diff: finalDiff,\n id,\n pathArgs,\n params,\n c,\n });\n const definedChanges = pickDefinedChanges(extraChanges);\n if (definedChanges) {\n finalDoc = await entry.repo.update(\n ...pathArgs,\n definedChanges as any,\n );\n }\n } catch (hookErr) {\n await reportHookError(\n entry,\n ctx.logger,\n {\n hook: \"afterUpdate\",\n repoName: entry.name,\n path: entry.path,\n id,\n pathArgs,\n user,\n c,\n },\n hookErr,\n );\n }\n }\n\n return sendSuccess(c, finalDoc);\n } catch (err) {\n const message =\n verbose && err instanceof Error\n ? err.message\n : \"Failed to update document\";\n return sendError(c, message, 500);\n }\n }\n\n // ── DELETE: DELETE /:repoName/:id ───────────────────────────────────────\n async function handleDelete(ctx: any): Promise<any> {\n const c = ctx.c;\n\n const params = c.req.param();\n const entry = getRepoEntry(params.repoName, c);\n if (!entry) return sendError(c, `Repository not found`, 404);\n\n if (!entry.allowDelete) {\n return sendError(c, \"Delete not allowed for this repository\", 403);\n }\n\n const id = params.id;\n if (!id) {\n return sendError(c, \"Document ID required\", 400);\n }\n\n try {\n // Fetch first to authorize against current state and get path args\n const doc = await fetchDocById(entry, id);\n if (!doc) {\n return sendError(c, \"Document not found\", 404);\n }\n\n const user = userOf(c);\n const deleteRuleCheck = await assertRule(c, entry, \"delete\", {\n user,\n doc: doc as any,\n params,\n });\n if (!deleteRuleCheck.allowed) return deleteRuleCheck.errorResponse;\n\n const pathArgs = extractPathArgs(doc, entry) ?? [id];\n await entry.repo.delete(...pathArgs);\n\n if (entry.hooks?.afterDelete) {\n try {\n await entry.hooks.afterDelete({\n user,\n doc: doc as any,\n id,\n pathArgs,\n params,\n c,\n });\n } catch (hookErr) {\n await reportHookError(\n entry,\n ctx.logger,\n {\n hook: \"afterDelete\",\n repoName: entry.name,\n path: entry.path,\n id,\n pathArgs,\n user,\n c,\n },\n hookErr,\n );\n }\n }\n\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\":\n \"Content-Type, Authorization, X-History-Reason, X-History-Comment\",\n \"Access-Control-Max-Age\": \"86400\",\n });\n }\n\n // ── BATCH: POST /:repoName/batch ─────────────────────────────────────────\n async function handleBatch(ctx: any) {\n const c = ctx.c;\n const params = c.req.param();\n const entry = getRepoEntry(params.repoName, c);\n if (!entry) return sendError(c, `Repository not found`, 404);\n\n try {\n const body = ctx.input || {};\n if (!Array.isArray(body.operations)) {\n return sendError(c, \"operations array is required\", 400);\n }\n\n const user = userOf(c);\n\n const batch = entry.repo.batch.create();\n const results = [];\n const hasHooks = !!entry.hooks;\n const createdItems: Array<{ id: string; pathArgs: string[]; doc: any }> =\n [];\n const updatedItems: Array<{\n id: string;\n pathArgs: string[];\n before: any;\n after: any;\n body: any;\n diff: DeepDiffReturn<any>;\n }> = [];\n const deletedItems: Array<{ id: string; pathArgs: string[]; doc: any }> =\n [];\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 const createRuleCheck = await assertRule(c, entry, \"create\", {\n user,\n body: op.data,\n params,\n });\n if (!createRuleCheck.allowed) return createRuleCheck.errorResponse;\n\n const validation = validateData(\n entry.schema,\n op.data,\n entry.createFields,\n false,\n entry.systemKeys,\n );\n if (!validation.success)\n return sendError(c, (validation as any).error, 400);\n\n if (entry.hooks?.beforeCreate) {\n await entry.hooks.beforeCreate({\n user,\n body: validation.data as any,\n params,\n c,\n });\n }\n\n let docId =\n op.data[entry.documentKey] ||\n (validation.data[entry.documentKey] as string | undefined) ||\n generateFirestoreId();\n const data = { ...validation.data };\n if (entry.createdKey && data[entry.createdKey] === undefined) {\n data[entry.createdKey] = new Date();\n }\n\n let pathArgs: string[];\n if (entry.isGroup && entry.parentKeys) {\n const parentIds = entry.parentKeys.map(\n (k: string) => String(data[k]),\n );\n pathArgs = [...parentIds, docId];\n batch.set(...parentIds, docId, data);\n } else {\n pathArgs = [docId];\n batch.set(docId, data);\n }\n results.push({ op: \"create\", id: docId });\n\n if (hasHooks) {\n const createdDoc: Record<string, unknown> = {\n ...data,\n [entry.documentKey]: docId,\n };\n if (\n entry.pathKey &&\n typeof (entry.repo as any).documentRef === \"function\"\n ) {\n try {\n const ref = (entry.repo as any).documentRef(...pathArgs);\n if (ref?.path) createdDoc[entry.pathKey] = ref.path;\n } catch {\n // Ignore in minimal mocks\n }\n }\n createdItems.push({ id: docId, pathArgs, doc: createdDoc });\n }\n } else if (op.type === \"update\") {\n if (!op.id) return sendError(c, \"id required for update\", 400);\n\n const existingDoc = await fetchDocById(entry, op.id);\n if (!existingDoc)\n return sendError(c, `Document ${op.id} not found`, 404);\n\n const validation = validateData(\n entry.schema,\n op.data,\n entry.mutableFields,\n true,\n entry.systemKeys,\n );\n if (!validation.success)\n return sendError(c, (validation as any).error, 400);\n\n 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 const diff = computeDeepDiff(existingDoc as any, validation.data);\n\n const updateRuleCheck = await assertRule(c, entry, \"update\", {\n user,\n doc: existingDoc as any,\n body: validation.data,\n diff,\n params,\n });\n if (!updateRuleCheck.allowed) return updateRuleCheck.errorResponse;\n\n if (entry.hooks?.beforeUpdate) {\n const preHookDiff = entry.rules?.update\n ? computeDeepDiff(existingDoc as any, validation.data)\n : diff;\n await entry.hooks.beforeUpdate({\n user,\n doc: existingDoc as any,\n body: validation.data as any,\n diff: preHookDiff,\n params,\n c,\n });\n }\n\n // Recompute diff AFTER rules.update & hooks.beforeUpdate so preWrite mutations are included\n const finalBody = { ...validation.data };\n const finalDiff = hasHooks\n ? computeDeepDiff(existingDoc as any, finalBody)\n : diff;\n\n const pathArgs = extractPathArgs(existingDoc, entry) ?? [\n op.id,\n ];\n batch.update(...pathArgs, validation.data);\n results.push({ op: \"update\", id: op.id });\n\n if (hasHooks) {\n updatedItems.push({\n id: op.id,\n pathArgs,\n before: existingDoc,\n after: finalDiff.after,\n body: finalBody,\n diff: finalDiff,\n });\n }\n } else if (op.type === \"delete\") {\n if (!entry.allowDelete)\n return sendError(c, \"Delete not allowed\", 403);\n if (!op.id) return sendError(c, \"id required for delete\", 400);\n\n const doc = await fetchDocById(entry, op.id);\n if (!doc) return sendError(c, `Document ${op.id} not found`, 404);\n const deleteRuleCheck = await assertRule(c, entry, \"delete\", {\n user,\n doc: doc as any,\n params,\n });\n if (!deleteRuleCheck.allowed) return deleteRuleCheck.errorResponse;\n\n const pathArgs = extractPathArgs(doc, entry) ?? [op.id];\n batch.delete(...pathArgs);\n results.push({ op: \"delete\", id: op.id });\n\n if (hasHooks) {\n deletedItems.push({ id: op.id, pathArgs, doc });\n }\n }\n }\n\n await batch.commit();\n\n const hasAnyOp =\n createdItems.length > 0 ||\n updatedItems.length > 0 ||\n deletedItems.length > 0;\n\n if (entry.hooks && hasAnyOp) {\n if (entry.hooks.afterBatch) {\n try {\n await entry.hooks.afterBatch({\n user,\n created: createdItems,\n updated: updatedItems,\n deleted: deletedItems,\n params,\n c,\n });\n } catch (hookErr) {\n await reportHookError(\n entry,\n ctx.logger,\n {\n hook: \"afterBatch\",\n repoName: entry.name,\n path: entry.path,\n user,\n c,\n },\n hookErr,\n );\n }\n } else {\n if (entry.hooks.afterCreate) {\n for (const item of createdItems) {\n try {\n const extraChanges = await entry.hooks.afterCreate({\n user,\n doc: item.doc,\n id: item.id,\n pathArgs: item.pathArgs,\n params,\n c,\n });\n const definedChanges = pickDefinedChanges(extraChanges);\n if (definedChanges && item.pathArgs.length > 0) {\n await entry.repo.update(\n ...item.pathArgs,\n definedChanges as any,\n );\n }\n } catch (hookErr) {\n await reportHookError(\n entry,\n ctx.logger,\n {\n hook: \"afterCreate\",\n repoName: entry.name,\n path: entry.path,\n id: item.id,\n pathArgs: item.pathArgs,\n user,\n c,\n },\n hookErr,\n );\n }\n }\n }\n if (entry.hooks.afterUpdate) {\n for (const item of updatedItems) {\n try {\n const extraChanges = await entry.hooks.afterUpdate({\n user,\n before: item.before,\n after: item.after,\n body: item.body,\n diff: item.diff,\n id: item.id,\n pathArgs: item.pathArgs,\n params,\n c,\n });\n const definedChanges = pickDefinedChanges(extraChanges);\n if (definedChanges && item.pathArgs.length > 0) {\n await entry.repo.update(\n ...item.pathArgs,\n definedChanges as any,\n );\n }\n } catch (hookErr) {\n await reportHookError(\n entry,\n ctx.logger,\n {\n hook: \"afterUpdate\",\n repoName: entry.name,\n path: entry.path,\n id: item.id,\n pathArgs: item.pathArgs,\n user,\n c,\n },\n hookErr,\n );\n }\n }\n }\n if (entry.hooks.afterDelete) {\n for (const item of deletedItems) {\n try {\n await entry.hooks.afterDelete({\n user,\n doc: item.doc,\n id: item.id,\n pathArgs: item.pathArgs,\n params,\n c,\n });\n } catch (hookErr) {\n await reportHookError(\n entry,\n ctx.logger,\n {\n hook: \"afterDelete\",\n repoName: entry.name,\n path: entry.path,\n id: item.id,\n pathArgs: item.pathArgs,\n user,\n c,\n },\n hookErr,\n );\n }\n }\n }\n }\n }\n\n return sendSuccess(c, { results });\n } catch (err) {\n const message =\n verbose && err instanceof Error\n ? err.message\n : \"Batch operation failed\";\n return sendError(c, message, 500);\n }\n }\n\n return {\n handleList,\n handleQuery,\n handleGet,\n handleCreate,\n handleUpdate,\n handleDelete,\n handleBatch,\n handleOptions,\n };\n}\n","/**\n * OpenAPI 3.1 specification generator for the CRUD server.\n *\n * Introspects each `CrudRepoEntry` and uses Zod 4's native `z.toJSONSchema()`\n * to produce a fully typed OpenAPI document ready for Scalar UI or codegen.\n *\n * @module servers/crud/openapi\n */\n\nimport { z } from \"zod\";\nimport { getOpenApiMetadata } from \"@asteasolutions/zod-to-openapi\";\nimport { resolveShadowConfig } from \"../../history/inject\";\nimport {\n DEFAULT_HISTORY_COMMENT_HEADER,\n DEFAULT_HISTORY_REASON_HEADER,\n} from \"../../shared/actor-context\";\nimport type {\n CrudRepoEntry,\n CrudRepoRegistry,\n OpenAPIHistoryHeadersConfig,\n OpenAPISpecOptions,\n} from \"./types\";\n\nexport type { OpenAPISpecOptions };\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Minimal subset of an OpenAPI 3.1 document we produce. */\nexport interface OpenAPIDocument {\n openapi: \"3.1.0\";\n info: OpenAPIInfo;\n servers?: { url: string; description?: string }[];\n paths: Record<string, Record<string, OpenAPIOperation>>;\n components: {\n schemas: Record<string, Record<string, unknown>>;\n securitySchemes?: Record<string, Record<string, unknown>>;\n };\n security?: Record<string, string[]>[];\n tags?: { name: string; description?: string }[];\n}\n\nexport interface OpenAPIInfo {\n title: string;\n version: string;\n description?: string;\n}\n\ninterface OpenAPIOperation {\n operationId: string;\n summary: string;\n tags: string[];\n parameters?: Record<string, unknown>[];\n requestBody?: Record<string, unknown>;\n responses: Record<string, Record<string, unknown>>;\n security?: Record<string, string[]>[];\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Convert a Zod schema to a JSON Schema object suitable for OpenAPI 3.1.\n *\n * Uses `unrepresentable: \"any\"` so that types Zod can't natively serialize\n * (e.g. `z.date()`, `z.bigint()`, custom classes — common with Firestore\n * Timestamps stored as `Date`) don't throw and collapse the whole schema to\n * a bare `{ type: \"object\" }`. We additionally override a few well-known\n * cases to a sensible OpenAPI representation.\n */\nfunction zodToJsonSchema(schema: z.ZodType): Record<string, unknown> {\n try {\n return z.toJSONSchema(schema, {\n target: \"openapi-3.1\",\n unrepresentable: \"any\",\n override: (ctx) => {\n const metadata = getOpenApiMetadata(ctx.zodSchema as unknown as z.ZodTypeAny);\n if (metadata) {\n Object.assign(ctx.jsonSchema, metadata);\n if (ctx.jsonSchema.anyOf || ctx.jsonSchema.oneOf) {\n delete (ctx.jsonSchema as any).type;\n }\n }\n\n const def: any = (ctx.zodSchema as any)?._zod?.def;\n if (!def) return;\n if (def.type === \"date\" && !(ctx.jsonSchema as any).type && !ctx.jsonSchema.anyOf) {\n (ctx.jsonSchema as any).type = \"string\";\n (ctx.jsonSchema as any).format = \"date-time\";\n } else if (def.type === \"bigint\" && !(ctx.jsonSchema as any).type && !ctx.jsonSchema.anyOf) {\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 totalCount: {\n type: \"integer\",\n description:\n \"Total count of matching documents (when requested with withTotal=true)\",\n },\n totalCountIsExact: {\n type: \"boolean\",\n description:\n \"Whether totalCount is exact (true) or estimated due to OR conditions (false)\",\n },\n },\n required: [\"items\", \"hasNextPage\", \"hasPrevPage\"],\n },\n meta: {\n type: \"object\",\n properties: {\n pageSize: { type: \"integer\" },\n hasMore: { type: \"boolean\" },\n totalCount: { type: \"integer\" },\n totalCountIsExact: { type: \"boolean\" },\n cursor: {\n oneOf: [{ type: \"string\" }, { type: \"null\" }],\n },\n },\n },\n },\n required: [\"success\", \"data\"],\n },\n },\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Introspection & Zod-to-OpenAPI Type Resolution\n// ---------------------------------------------------------------------------\n\n/** Helper to unwrap Zod modifiers (optional, nullable, default, catch, effects, etc.) */\nfunction unwrapZodType(zodType: any): any {\n let cur = zodType;\n while (cur) {\n const def = cur._zod?.def ?? cur._def;\n if (!def) break;\n if (def.innerType) {\n cur = def.innerType;\n } else if (def.schema) {\n cur = def.schema;\n } else if (\n def.type === \"optional\" ||\n def.type === \"nullable\" ||\n def.type === \"default\" ||\n def.type === \"catch\" ||\n def.type === \"effects\"\n ) {\n cur = def.innerType ?? def.schema;\n } else {\n break;\n }\n }\n return cur;\n}\n\n/** Resolve a dot-notation path (e.g. \"address.city\") from a Zod schema */\nfunction resolveFieldPathSchema(entrySchema: any, path: string): any {\n const parts = path.split(\".\");\n let cur = unwrapZodType(entrySchema);\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n if (!part) continue;\n const shape: Record<string, any> | undefined = (cur as any)?.shape;\n if (!shape || !shape[part]) {\n return undefined;\n }\n const rawSub = shape[part];\n if (i === parts.length - 1) {\n return rawSub;\n }\n cur = unwrapZodType(rawSub);\n }\n return cur;\n}\n\n/** Recursively make Zod objects deep-partial for PATCH updates while preserving nullable/metadata */\nfunction makeDeepPartial(s: z.ZodType): z.ZodType {\n const def = (s as any)?._zod?.def ?? (s as any)?._def;\n const typeName = def?.typeName ?? def?.type;\n\n const copyMetadata = (target: z.ZodType): z.ZodType => {\n const metadata = getOpenApiMetadata(s as unknown as z.ZodTypeAny);\n if (metadata && typeof (target as any).openapi === \"function\") {\n return (target as any).openapi(metadata);\n }\n return target;\n };\n\n if (typeName === \"ZodObject\" || typeName === \"object\") {\n const shape = (s as z.ZodObject<any>).shape;\n const newShape: Record<string, z.ZodType> = {};\n for (const [k, v] of Object.entries(shape)) {\n newShape[k] = makeDeepPartial(v as z.ZodType);\n }\n return copyMetadata(z.object(newShape).partial());\n }\n\n if (typeName === \"ZodOptional\" || typeName === \"optional\") {\n const inner = def.innerType as z.ZodType | undefined;\n if (!inner) return s;\n const nextInner = makeDeepPartial(inner);\n return nextInner === inner ? s : copyMetadata(nextInner.optional());\n }\n\n if (typeName === \"ZodNullable\" || typeName === \"nullable\") {\n const inner = def.innerType as z.ZodType | undefined;\n if (!inner) return s;\n const nextInner = makeDeepPartial(inner);\n return nextInner === inner ? s : copyMetadata(nextInner.nullable());\n }\n\n if (typeName === \"ZodDefault\" || typeName === \"default\") {\n const inner = def.innerType as z.ZodType | undefined;\n if (!inner) return s;\n return copyMetadata(makeDeepPartial(inner).optional());\n }\n\n if (typeName === \"ZodUnion\" || typeName === \"union\") {\n const options = def.options as z.ZodType[] | undefined;\n if (!options || options.length < 2) return s;\n const nextOptions = options.map((opt) => makeDeepPartial(opt));\n const changed = nextOptions.some((opt, i) => opt !== options[i]);\n return changed ? copyMetadata(z.union(nextOptions as any)) : s;\n }\n\n return s;\n}\n\n/** Recursively extract leaf fields and parent object fields from a Zod object schema */\nfunction extractLeafFields(\n zodSchema: any,\n prefix = \"\",\n depth = 0,\n): { path: string; zodSchema: any }[] {\n if (depth > 5) return [];\n const unwrapped = unwrapZodType(zodSchema);\n const shape = unwrapped?.shape;\n if (!shape) return [];\n\n const results: { path: string; zodSchema: any }[] = [];\n for (const [key, rawSub] of Object.entries(shape)) {\n const fieldPath = prefix ? `${prefix}.${key}` : key;\n const subUnwrapped = unwrapZodType(rawSub);\n if (subUnwrapped?.shape && typeof subUnwrapped.shape === \"object\") {\n results.push({ path: fieldPath, zodSchema: rawSub });\n results.push(...extractLeafFields(subUnwrapped, fieldPath, depth + 1));\n } else {\n results.push({ path: fieldPath, zodSchema: rawSub });\n }\n }\n return results;\n}\n\n/** Get all filterable leaf fields for a CrudRepoEntry */\nfunction getFilterableLeafFields(\n entry: CrudRepoEntry,\n): { path: string; zodSchema: any }[] {\n if (entry.filterableFields && entry.filterableFields.length > 0) {\n return entry.filterableFields.map((path) => ({\n path,\n zodSchema: resolveFieldPathSchema(entry.schema, path),\n }));\n }\n return extractLeafFields(entry.schema);\n}\n\n/** Convert a Zod field schema to an inline OpenAPI JSON Schema for its value */\nfunction zodTypeToJsonValueSchema(zodType: any): Record<string, unknown> {\n if (!zodType) return { type: \"string\" };\n const jsonSchema = zodToJsonSchema(zodType);\n delete jsonSchema[\"$schema\"];\n delete jsonSchema[\"title\"];\n return jsonSchema;\n}\n\n// ---------------------------------------------------------------------------\n// Pagination / filter query parameters (shared across list endpoints)\n// ---------------------------------------------------------------------------\n\nfunction paginationParams(entry: CrudRepoEntry): Record<string, unknown>[] {\n const leafFields = getFilterableLeafFields(entry);\n const orderableFields =\n entry.orderableFields ?? leafFields.map((f) => f.path);\n\n return [\n {\n name: \"pageSize\",\n in: \"query\",\n schema: {\n type: \"integer\",\n default: entry.pageSize,\n minimum: 1,\n maximum: 1000,\n },\n description: \"Number of items per page\",\n },\n {\n name: \"cursor\",\n in: \"query\",\n schema: { type: \"string\" },\n description: \"Base64 pagination cursor\",\n },\n {\n name: \"orderBy\",\n in: \"query\",\n schema: {\n type: \"string\",\n ...(orderableFields.length > 0 ? { enum: orderableFields } : {}),\n },\n description: \"Field name to order by\",\n },\n {\n name: \"orderDir\",\n in: \"query\",\n schema: { type: \"string\", enum: [\"asc\", \"desc\"] },\n description: \"Order direction\",\n },\n {\n name: \"select\",\n in: \"query\",\n schema: { type: \"string\" },\n description: `Comma-separated list of fields to return${\n leafFields.length > 0\n ? ` (${leafFields.map((f) => f.path).join(\", \")})`\n : \"\"\n }`,\n },\n {\n name: \"withTotal\",\n in: \"query\",\n schema: { type: \"boolean\" },\n description:\n \"Include total document count (totalCount and totalCountIsExact) in response\",\n },\n ];\n}\n\nfunction filterParams(entry: CrudRepoEntry): Record<string, unknown>[] {\n const leafFields = getFilterableLeafFields(entry);\n const ops = [\n \"eq\",\n \"ne\",\n \"lt\",\n \"lte\",\n \"gt\",\n \"gte\",\n \"in\",\n \"nin\",\n \"contains\",\n \"containsAny\",\n ];\n\n const opDescriptions: Record<string, string> = {\n eq: \"equals. Use 'null' or '__null__' to match null values\",\n ne: \"not equals. Use 'null' or '__null__' to match non-null values\",\n lt: \"less than\",\n lte: \"less than or equal\",\n gt: \"greater than\",\n gte: \"greater than or equal\",\n in: \"in list (comma-separated values). Supports 'null' and '__null__' (e.g. val1,val2,__null__)\",\n nin: \"not in list (comma-separated values). Supports 'null' and '__null__'\",\n contains: \"array-contains\",\n containsAny: \"array-contains-any (comma-separated values). Supports 'null' and '__null__'\",\n };\n\n const params: Record<string, unknown>[] = [];\n for (const { path: field, zodSchema } of leafFields) {\n const valSchema = zodTypeToJsonValueSchema(zodSchema);\n const unwrapped = unwrapZodType(zodSchema);\n\n const isArrayType =\n (unwrapped as any)?._zod?.def?.type === \"array\" ||\n (unwrapped as any)?._def?.typeName === \"ZodArray\" ||\n (unwrapped as any)?._def?.type === \"array\";\n\n const elemSchema = isArrayType\n ? zodTypeToJsonValueSchema(\n (unwrapped as any)?._zod?.def?.element ??\n (unwrapped as any)?._def?.type ??\n (unwrapped as any)?._def?.element,\n )\n : valSchema;\n\n // Direct equality filter: ?field=value\n params.push({\n name: field,\n in: \"query\",\n schema: valSchema,\n description: `Filter by ${field} (equality). Use 'null' or '__null__' for null values`,\n });\n // Operator filters: ?field__op=value\n for (const op of ops) {\n const descDetail = opDescriptions[op] ? ` (${opDescriptions[op]})` : \"\";\n const isListOp = op === \"in\" || op === \"nin\" || op === \"containsAny\";\n const isElemOp = op === \"contains\";\n params.push({\n name: `${field}__${op}`,\n in: \"query\",\n schema: isListOp\n ? { type: \"string\", description: \"Comma-separated list of values\" }\n : isElemOp\n ? elemSchema\n : valSchema,\n description: `Filter ${field} with operator ${op}${descDetail}`,\n });\n }\n }\n return params;\n}\n\n// ---------------------------------------------------------------------------\n// Query body schema (POST /query)\n// ---------------------------------------------------------------------------\n\nfunction queryBodySchema(): Record<string, unknown> {\n return {\n type: \"object\",\n properties: {\n where: {\n type: \"array\",\n items: {\n type: \"array\",\n items: {},\n minItems: 3,\n maxItems: 3,\n },\n description: \"AND conditions: [field, operator, value][]\",\n },\n orWhere: {\n type: \"array\",\n items: {\n type: \"array\",\n items: {},\n minItems: 3,\n maxItems: 3,\n },\n description: \"Simple OR conditions (each independently OR'd)\",\n },\n orWhereGroups: {\n type: \"array\",\n items: {\n type: \"array\",\n items: {\n type: \"array\",\n items: {},\n minItems: 3,\n maxItems: 3,\n },\n },\n description: \"Advanced OR groups (AND within, OR across groups)\",\n },\n orderBy: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n field: { type: \"string\" },\n direction: { type: \"string\", enum: [\"asc\", \"desc\"] },\n },\n required: [\"field\"],\n },\n },\n select: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"Fields to select (projection)\",\n },\n pageSize: {\n type: \"integer\",\n minimum: 1,\n maximum: 1000,\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 withTotal: {\n type: \"boolean\",\n description:\n \"Include total document count (totalCount and totalCountIsExact) in response\",\n },\n },\n };\n}\n\n/** Build a strongly-typed OpenAPI QueryRequestBody schema tailored to a CrudRepoEntry */\nfunction buildTypedQueryBodySchema(entry: CrudRepoEntry): Record<string, unknown> {\n const leafFields = getFilterableLeafFields(entry);\n const orderableFieldNames =\n entry.orderableFields ?? leafFields.map((f) => f.path);\n const leafFieldNames = leafFields.map((f) => f.path);\n\n if (leafFields.length === 0) {\n return queryBodySchema();\n }\n\n const whereTuples: Record<string, unknown>[] = [];\n\n for (const { path, zodSchema } of leafFields) {\n const valSchema = zodTypeToJsonValueSchema(zodSchema);\n const unwrapped = unwrapZodType(zodSchema);\n\n const isArrayType =\n (unwrapped as any)?._zod?.def?.type === \"array\" ||\n (unwrapped as any)?._def?.typeName === \"ZodArray\" ||\n (unwrapped as any)?._def?.type === \"array\";\n\n const elemSchema = isArrayType\n ? zodTypeToJsonValueSchema(\n (unwrapped as any)?._zod?.def?.element ??\n (unwrapped as any)?._def?.type ??\n (unwrapped as any)?._def?.element,\n )\n : valSchema;\n\n // Standard comparison operators (==, !=, <, <=, >, >=)\n whereTuples.push({\n type: \"array\",\n description: `Condition on '${path}'`,\n prefixItems: [\n { type: \"string\", enum: [path] },\n {\n type: \"string\",\n enum: [\"==\", \"!=\", \"<\", \"<=\", \">\", \">=\", \"eq\", \"ne\", \"lt\", \"lte\", \"gt\", \"gte\"],\n },\n valSchema,\n ],\n minItems: 3,\n maxItems: 3,\n });\n\n // List operators (in, not-in)\n whereTuples.push({\n type: \"array\",\n description: `List condition on '${path}' (in, not-in)`,\n prefixItems: [\n { type: \"string\", enum: [path] },\n { type: \"string\", enum: [\"in\", \"not-in\", \"nin\"] },\n { type: \"array\", items: valSchema },\n ],\n minItems: 3,\n maxItems: 3,\n });\n\n // Array contains operators\n whereTuples.push({\n type: \"array\",\n description: `Array contains condition on '${path}'`,\n prefixItems: [\n { type: \"string\", enum: [path] },\n { type: \"string\", enum: [\"array-contains\", \"contains\"] },\n elemSchema,\n ],\n minItems: 3,\n maxItems: 3,\n });\n\n whereTuples.push({\n type: \"array\",\n description: `Array contains-any condition on '${path}'`,\n prefixItems: [\n { type: \"string\", enum: [path] },\n { type: \"string\", enum: [\"array-contains-any\", \"containsAny\"] },\n { type: \"array\", items: elemSchema },\n ],\n minItems: 3,\n maxItems: 3,\n });\n }\n\n const whereItemSchema = {\n oneOf: whereTuples,\n };\n\n return {\n type: \"object\",\n properties: {\n where: {\n type: \"array\",\n items: whereItemSchema,\n description: \"AND conditions: [field, operator, value][]\",\n },\n orWhere: {\n type: \"array\",\n items: whereItemSchema,\n description: \"Simple OR conditions (each independently OR'd)\",\n },\n orWhereGroups: {\n type: \"array\",\n items: {\n type: \"array\",\n items: whereItemSchema,\n },\n description: \"Advanced OR groups (AND within, OR across groups)\",\n },\n orderBy: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n field: { type: \"string\", enum: orderableFieldNames },\n direction: { type: \"string\", enum: [\"asc\", \"desc\"] },\n },\n required: [\"field\"],\n },\n },\n select: {\n type: \"array\",\n items: { type: \"string\", enum: leafFieldNames },\n description: \"Fields to select (projection)\",\n },\n pageSize: {\n type: \"integer\",\n minimum: 1,\n maximum: 1000,\n description: \"Number of items per page\",\n },\n cursor: {\n oneOf: [{ type: \"string\" }, { type: \"object\" }],\n description: \"Pagination cursor\",\n },\n direction: {\n type: \"string\",\n enum: [\"next\", \"prev\"],\n description: \"Pagination direction\",\n },\n includes: {\n type: \"array\",\n items:\n entry.allowedIncludes && entry.allowedIncludes.length > 0\n ? {\n oneOf: [\n { type: \"string\", enum: entry.allowedIncludes },\n {\n type: \"object\",\n properties: {\n relation: { type: \"string\", enum: entry.allowedIncludes },\n select: { type: \"array\", items: { type: \"string\" } },\n },\n required: [\"relation\"],\n },\n ],\n }\n : {\n oneOf: [\n { type: \"string\" },\n {\n type: \"object\",\n properties: {\n relation: { type: \"string\" },\n select: { type: \"array\", items: { type: \"string\" } },\n },\n required: [\"relation\"],\n },\n ],\n },\n description: \"Relations to include (populate)\",\n },\n withTotal: {\n type: \"boolean\",\n description:\n \"Include total document count (totalCount and totalCountIsExact) in response\",\n },\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// History audit header parameters (auto-detected per repo)\n// ---------------------------------------------------------------------------\n\nfunction resolveEntryHistoryFlags(\n entry: CrudRepoEntry,\n): { reason: boolean; comment: boolean } | null {\n if (entry.historyHeaders) {\n return entry.historyHeaders;\n }\n const historyConfig = (entry.repo as any)?._historyConfig;\n if (!historyConfig?.enabled || historyConfig.autoInjectMeta === false) {\n return null;\n }\n const shadow = resolveShadowConfig(historyConfig);\n if (!shadow) return null;\n return {\n reason: shadow.fields.reason !== false,\n comment: shadow.fields.comment !== false,\n };\n}\n\nfunction buildHistoryHeaderParams(\n entry: CrudRepoEntry,\n historyHeadersOpt: false | OpenAPIHistoryHeadersConfig | undefined,\n): Record<string, unknown>[] {\n if (historyHeadersOpt === false) return [];\n const flags = resolveEntryHistoryFlags(entry);\n if (!flags) return [];\n\n const reasonHeader =\n historyHeadersOpt?.reasonHeader === undefined\n ? DEFAULT_HISTORY_REASON_HEADER\n : historyHeadersOpt.reasonHeader;\n const commentHeader =\n historyHeadersOpt?.commentHeader === undefined\n ? DEFAULT_HISTORY_COMMENT_HEADER\n : historyHeadersOpt.commentHeader;\n\n const params: Record<string, unknown>[] = [];\n const seenLower = new Set<string>();\n\n if (flags.reason && typeof reasonHeader === \"string\" && reasonHeader.trim()) {\n const name = reasonHeader.trim();\n seenLower.add(name.toLowerCase());\n params.push({\n name,\n in: \"header\",\n required: false,\n schema: { type: \"string\" },\n description: \"Optional reason recorded in the document's change history\",\n });\n }\n\n if (flags.comment && typeof commentHeader === \"string\" && commentHeader.trim()) {\n const name = commentHeader.trim();\n if (!seenLower.has(name.toLowerCase())) {\n seenLower.add(name.toLowerCase());\n params.push({\n name,\n in: \"header\",\n required: false,\n schema: { type: \"string\" },\n description: \"Optional comment recorded in the document's change history\",\n });\n }\n }\n\n if (historyHeadersOpt?.extraHeaders?.length) {\n for (const extra of historyHeadersOpt.extraHeaders) {\n const spec = typeof extra === \"string\" ? { name: extra } : extra;\n const name = spec?.name?.trim();\n if (!name || seenLower.has(name.toLowerCase())) continue;\n seenLower.add(name.toLowerCase());\n params.push({\n name,\n in: \"header\",\n required: spec.required ?? false,\n schema: spec.schema ?? { type: \"string\" },\n ...(spec.description ? { description: spec.description } : {}),\n });\n }\n }\n\n return params;\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 patchSchemaName: string | null = null,\n querySchemaName: string = \"QueryRequestBody\",\n historyHeaderParams: Record<string, unknown>[] = [],\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 // ── POST /:repo → create ────────────────────────────────────────\n paths[collectionPath] = {\n post: {\n operationId: `create${capitalize(entry.name)}`,\n summary: `Create a ${singularize(entry.name)}`,\n tags: [tag],\n ...(historyHeaderParams.length > 0\n ? { parameters: [...historyHeaderParams] }\n : {}),\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 \"403\": errorResponse(\"Forbidden\"),\n \"500\": errorResponse(\"Internal server error\"),\n },\n },\n };\n\n // ── POST /:repo/query → advanced query ────────────────────────────\n paths[`${collectionPath}/query`] = {\n post: {\n operationId: `query${capitalize(entry.name)}`,\n summary: `Query ${entry.name} with advanced filters`,\n tags: [tag],\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: schemaRef(querySchemaName),\n },\n },\n },\n responses: {\n \"200\": listResponse(schemaRef(modelSchemaName)),\n \"400\": errorResponse(\"Invalid query\"),\n \"403\": errorResponse(\"Forbidden\"),\n \"424\": errorResponse(\"Missing composite index (includes indexUrl in response)\"),\n \"500\": errorResponse(\"Internal server error\"),\n },\n },\n };\n\n // ── POST /:repo/batch → batch operations ─────────────────────────\n paths[`${collectionPath}/batch`] = {\n post: {\n operationId: `batch${capitalize(entry.name)}`,\n summary: `Execute batch operations on ${entry.name}`,\n tags: [tag],\n ...(historyHeaderParams.length > 0\n ? { parameters: [...historyHeaderParams] }\n : {}),\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: schemaRef(`${modelSchemaName}BatchRequest`),\n },\n },\n },\n responses: {\n \"200\": successResponse(\"Batch operations completed\", {\n type: \"object\",\n properties: {\n results: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n op: { type: \"string\" },\n id: { type: \"string\" },\n },\n },\n },\n },\n }),\n \"400\": errorResponse(\"Validation error\"),\n \"403\": errorResponse(\"Forbidden\"),\n \"404\": errorResponse(\"Document not found\"),\n \"500\": errorResponse(\"Internal server error\"),\n },\n },\n };\n\n // ── Single-document paths ────────────────────────────────────────\n const docOps: Record<string, OpenAPIOperation> = {};\n\n // GET /:repo/:id\n docOps.get = {\n operationId: `get${capitalize(singularize(entry.name))}`,\n summary: `Get a single ${singularize(entry.name)}`,\n tags: [tag],\n parameters: [idParam],\n responses: {\n \"200\": successResponse(\"Document found\", schemaRef(modelSchemaName)),\n \"400\": errorResponse(\"Document ID required\"),\n \"403\": errorResponse(\"Forbidden\"),\n \"404\": errorResponse(\"Document not found\"),\n \"424\": errorResponse(\"Missing composite index (includes indexUrl in response)\"),\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, ...historyHeaderParams],\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 \"403\": errorResponse(\"Forbidden\"),\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, ...historyHeaderParams],\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: schemaRef(patchSchemaName ?? updateSchemaName ?? modelSchemaName),\n },\n },\n },\n responses: {\n \"200\": successResponse(\"Document patched\", schemaRef(modelSchemaName)),\n \"400\": errorResponse(\"Validation error\"),\n \"403\": errorResponse(\"Forbidden\"),\n \"404\": errorResponse(\"Document not found\"),\n \"500\": errorResponse(\"Internal server error\"),\n },\n };\n\n // 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 \"400\": errorResponse(\"Document ID required\"),\n \"403\": errorResponse(\"Forbidden\"),\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\", description: \"Human-readable error description\" },\n errorType: {\n type: \"string\",\n enum: [\"index\"],\n description: \"Error category discriminator. Set to 'index' when a Firestore composite index is missing.\",\n },\n indexUrl: {\n type: \"string\",\n format: \"uri\",\n description: \"Direct Firebase Console URL to create the required composite index (when errorType is 'index').\",\n },\n },\n required: [\"success\", \"error\"],\n };\n\n schemas[\"QueryRequestBody\"] = queryBodySchema();\n\n // Per-repo schemas & paths\n for (const [name, entry] of Object.entries(registry)) {\n const modelName = capitalize(singularize(name));\n const createName = `${modelName}Create`;\n const updateName = `${modelName}Update`;\n const patchName = `${modelName}Patch`;\n const queryName = `${modelName}QueryRequestBody`;\n\n // Full model schema\n schemas[modelName] = zodToJsonSchema(entry.schema);\n\n // Per-repository typed QueryRequestBody schema\n schemas[queryName] = buildTypedQueryBodySchema(entry);\n\n // Helper: build a filtered shape (respects systemKeys + field list)\n const buildShape = (\n fieldList: string[] | undefined,\n ): Record<string, z.ZodType> => {\n const shape: Record<string, z.ZodType> = {};\n const leafFields = extractLeafFields(entry.schema);\n\n for (const { path: fieldPath, zodSchema: fieldSchema } of leafFields) {\n const top = fieldPath.split(\".\")[0]!;\n if (\n entry.systemKeys.includes(top) ||\n entry.systemKeys.includes(fieldPath)\n ) {\n continue;\n }\n if (fieldList && fieldList.length > 0) {\n if (!fieldList.includes(fieldPath) && !fieldList.includes(top)) {\n continue;\n }\n }\n if (fieldPath.includes(\".\")) {\n shape[fieldPath] = fieldSchema.optional();\n } else {\n shape[fieldPath] = fieldSchema;\n }\n }\n return shape;\n };\n\n // Create schema\n let createSchemaName: string | null = null;\n const createShape = buildShape(entry.createFields);\n if (entry.isGroup && entry.parentKeys && entry.parentKeys.length > 0) {\n const schemaShape = (entry.schema as any)?.shape ?? {};\n for (const pk of entry.parentKeys) {\n if (!createShape[pk] && schemaShape[pk]) {\n createShape[pk] = schemaShape[pk];\n }\n }\n }\n if (Object.keys(createShape).length > 0) {\n const createJsonSchema = zodToJsonSchema(z.object(createShape));\n if (entry.isGroup && entry.parentKeys && entry.parentKeys.length > 0) {\n const reqSet = new Set<string>(\n Array.isArray(createJsonSchema.required)\n ? createJsonSchema.required\n : [],\n );\n for (const pk of entry.parentKeys) {\n if ((createJsonSchema.properties as Record<string, unknown> | undefined)?.[pk]) {\n reqSet.add(pk);\n }\n }\n if (reqSet.size > 0) {\n createJsonSchema.required = Array.from(reqSet);\n }\n }\n schemas[createName] = createJsonSchema;\n createSchemaName = createName;\n }\n\n // Update & Patch schemas\n let updateSchemaName: string | null = null;\n let patchSchemaName: string | null = null;\n const updateShape = buildShape(entry.mutableFields);\n if (Object.keys(updateShape).length > 0) {\n const updateZodObj = z.object(updateShape);\n schemas[updateName] = zodToJsonSchema(updateZodObj);\n updateSchemaName = updateName;\n schemas[patchName] = zodToJsonSchema(makeDeepPartial(updateZodObj));\n patchSchemaName = patchName;\n } else {\n schemas[patchName] = zodToJsonSchema(makeDeepPartial(entry.schema));\n patchSchemaName = patchName;\n }\n\n // Batch schema\n const createOpName = `${modelName}BatchCreateOperation`;\n const updateOpName = `${modelName}BatchUpdateOperation`;\n const deleteOpName = `${modelName}BatchDeleteOperation`;\n\n schemas[createOpName] = {\n type: \"object\",\n title: `${modelName} Create Operation`,\n properties: {\n type: { type: \"string\", enum: [\"create\"], const: \"create\" },\n data: schemaRef(createSchemaName ?? modelName),\n },\n required: [\"type\", \"data\"],\n };\n\n schemas[updateOpName] = {\n type: \"object\",\n title: `${modelName} Update Operation`,\n properties: {\n type: { type: \"string\", enum: [\"update\"], const: \"update\" },\n id: { type: \"string\" },\n data: schemaRef(patchSchemaName ?? updateSchemaName ?? modelName),\n },\n required: [\"type\", \"id\", \"data\"],\n };\n\n if (entry.allowDelete) {\n schemas[deleteOpName] = {\n type: \"object\",\n title: `${modelName} Delete Operation`,\n properties: {\n type: { type: \"string\", enum: [\"delete\"], const: \"delete\" },\n id: { type: \"string\" },\n },\n required: [\"type\", \"id\"],\n };\n }\n\n schemas[`${modelName}BatchRequest`] = {\n type: \"object\",\n properties: {\n operations: {\n type: \"array\",\n items: {\n oneOf: [\n schemaRef(createOpName),\n schemaRef(updateOpName),\n ...(entry.allowDelete ? [schemaRef(deleteOpName)] : []),\n ],\n discriminator: {\n propertyName: \"type\",\n },\n },\n },\n },\n required: [\"operations\"],\n };\n\n // Build paths\n const historyHeaderParams = buildHistoryHeaderParams(\n entry,\n options.historyHeaders,\n );\n const entryPaths = buildPathsForEntry(\n entry,\n base,\n modelName,\n createSchemaName,\n updateSchemaName,\n patchSchemaName,\n queryName,\n historyHeaderParams,\n );\n Object.assign(allPaths, entryPaths);\n\n // Tag\n tags.push({\n name,\n description: `Operations on ${name} (collection: ${entry.path})`,\n });\n }\n\n\n // ── Security ──────────────────────────────────────────────────────\n const securitySchemes: Record<string, Record<string, unknown>> = {};\n let security: Record<string, string[]>[] | undefined;\n\n if (auth === \"basic\") {\n securitySchemes[\"basicAuth\"] = {\n type: \"http\",\n scheme: \"basic\",\n };\n security = [{ basicAuth: [] }];\n } else if (auth === \"bearer\") {\n securitySchemes[\"bearerAuth\"] = {\n type: \"http\",\n scheme: \"bearer\",\n bearerFormat: \"JWT\",\n };\n security = [{ bearerAuth: [] }];\n }\n\n // ── Assemble ──────────────────────────────────────────────────────\n const doc: OpenAPIDocument = {\n openapi: \"3.1.0\",\n info: {\n title,\n version,\n ...(description ? { description } : {}),\n },\n ...(servers && servers.length > 0 ? { servers } : {}),\n paths: allPaths,\n components: {\n schemas,\n ...(Object.keys(securitySchemes).length > 0 ? { securitySchemes } : {}),\n },\n ...(security ? { security } : {}),\n tags,\n };\n\n return doc;\n}\n\n// ---------------------------------------------------------------------------\n// Utility\n// ---------------------------------------------------------------------------\n\nfunction capitalize(s: string): string {\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n\n/** Naive singularize: strip trailing 's' for display. */\nfunction singularize(s: string): string {\n if (s.endsWith(\"ies\")) return s.slice(0, -3) + \"y\";\n if (s.endsWith(\"ses\") || s.endsWith(\"xes\") || s.endsWith(\"zes\"))\n return s.slice(0, -2);\n if (s.endsWith(\"s\") && !s.endsWith(\"ss\")) return s.slice(0, -1);\n return s;\n}\n","/**\n * Public types for the Hono file-based API server.\n *\n * Designed to be:\n * - **fully typed** end-to-end (Zod input/output → handler payload type),\n * - **runtime-safe** via Zod parsing on every request,\n * - **bundle-friendly** for Firebase Cloud Functions v2 cold-start (codegen\n * emits static imports — no `fs`/`import()` at runtime).\n */\n\nimport type { z, ZodError } from \"zod\";\nimport type { Context, Env, MiddlewareHandler } from \"hono\";\nimport type { AnyServicesContainer } from \"./services\";\nimport type { DocsAuthExtension } from \"./docs-auth\";\nimport type { ActorResolverOption } from \"../../shared/actor-context\";\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 * Optional resolver (function or declarative field config) used to extract\n * the authenticated actor from the Hono `Context` for automatic history\n * shadow metadata injection. Defaults to {@link defaultActorResolver}\n * (`c.get(\"user\") ?? c.get(\"docsUser\")`).\n */\n actorResolver?: ActorResolverOption;\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 getOpenApiMetadata,\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\n/**\n * Recursively walks a Zod schema graph and ensures any `z.custom()` / `z.instanceof()`\n * node (`def.type === \"custom\"`) has a `type` entry in its metadata.\n * Without this, `@asteasolutions/zod-to-openapi` throws `UnknownZodTypeError` when a\n * custom schema (e.g. Firestore `Timestamp` or `GeoPoint`) either lacks `.openapi(...)`\n * or only specifies `{ anyOf: [...] }` / `{ oneOf: [...] }` without a top-level `type`.\n */\nfunction ensureCustomSchemasHaveOpenApiType(\n schema: unknown,\n visited = new Set<unknown>(),\n): void {\n if (!schema || typeof schema !== \"object\" || visited.has(schema)) return;\n visited.add(schema);\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const s = schema as any;\n const def = s._zod?.def ?? s.def;\n if (!def) return;\n\n if (def.type === \"custom\") {\n const meta = getOpenApiMetadata(s) as Record<string, unknown> | undefined;\n if (!meta?.type) {\n z.globalRegistry.add(s, { ...(meta ?? {}), type: \"object\" });\n }\n return;\n }\n\n if (def.innerType) ensureCustomSchemasHaveOpenApiType(def.innerType, visited);\n if (def.element) ensureCustomSchemasHaveOpenApiType(def.element, visited);\n if (def.valueType) ensureCustomSchemasHaveOpenApiType(def.valueType, visited);\n if (def.keyType) ensureCustomSchemasHaveOpenApiType(def.keyType, visited);\n if (def.left) ensureCustomSchemasHaveOpenApiType(def.left, visited);\n if (def.right) ensureCustomSchemasHaveOpenApiType(def.right, visited);\n if (def.in) ensureCustomSchemasHaveOpenApiType(def.in, visited);\n if (def.out) ensureCustomSchemasHaveOpenApiType(def.out, visited);\n if (typeof def.getter === \"function\") {\n try {\n ensureCustomSchemasHaveOpenApiType(def.getter(), visited);\n } catch {\n // ignore lazy evaluation errors\n }\n }\n if (Array.isArray(def.options)) {\n for (const opt of def.options) ensureCustomSchemasHaveOpenApiType(opt, visited);\n }\n if (Array.isArray(def.items)) {\n for (const item of def.items) ensureCustomSchemasHaveOpenApiType(item, visited);\n }\n const shape = typeof def.shape === \"function\" ? def.shape() : def.shape;\n if (shape && typeof shape === \"object\") {\n for (const val of Object.values(shape)) {\n ensureCustomSchemasHaveOpenApiType(val, visited);\n }\n }\n}\n\n/**\n * Recursively strips top-level `type` on schema nodes that also define `anyOf` or `oneOf`\n * (preventing OpenAPI 3.1 generator conflicts when a fallback `type: \"object\"` was injected).\n */\nfunction stripRedundantTypeWithComposition(node: unknown): void {\n if (!node || typeof node !== \"object\") return;\n if (Array.isArray(node)) {\n for (const item of node) stripRedundantTypeWithComposition(item);\n return;\n }\n const record = node as Record<string, unknown>;\n if ((Array.isArray(record.anyOf) || Array.isArray(record.oneOf)) && \"type\" in record) {\n delete record.type;\n }\n for (const val of Object.values(record)) {\n stripRedundantTypeWithComposition(val);\n }\n}\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 if (route.input) ensureCustomSchemasHaveOpenApiType(route.input);\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 if (successSchema) ensureCustomSchemasHaveOpenApiType(successSchema);\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 if (schema) ensureCustomSchemasHaveOpenApiType(schema);\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 stripRedundantTypeWithComposition(document);\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 { createActorContextMiddleware } from \"../../shared/actor-context\";\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 actor-context middleware VERY FIRST so AsyncLocalStorage\n // captures the Hono Context before any auth/user middleware runs; actor\n // resolution runs lazily at Firestore write time after auth populates c.get(\"user\").\n this.app.use(\"*\", createActorContextMiddleware(options.actorResolver));\n\n // Install the request-context middleware so the built-in `ctx` service\n // resolves to the current request before any user middleware / handler runs.\n if (options.services) {\n this.app.use(\"*\", createRequestContextMiddleware());\n }\n\n const globalMws = [\n ...(options.middlewares ?? []),\n ...(options.globalMiddlewares ?? []),\n ];\n for (const mw of globalMws) this.app.use(\"*\", mw);\n\n this.mountRoutes();\n this.mountOpenApi();\n\n if (options.notFound) this.app.notFound(options.notFound);\n if (options.onError) this.app.onError(options.onError);\n }\n\n /** Underlying Hono instance — useful for advanced composition / tests. */\n get hono(): Hono<TEnv> {\n return this.app;\n }\n\n /** Raw `(req, res)` handler suitable for `onRequest()` / `http.createServer`. */\n get nodeHandler(): (req: IncomingMessage, res: ServerResponse) => void {\n return getRequestListener(this.app.fetch, {\n overrideGlobalObjects: false,\n });\n }\n\n /**\n * Wrap the server as a Cloud Functions v2 HTTP function.\n *\n * @param onRequest The `onRequest` factory imported from\n * `firebase-functions/v2/https` (or `firebase-functions/https`).\n * @param httpsOptions Options forwarded as the first argument to\n * `onRequest()` (region, memory, invoker, etc.).\n */\n toFunction(onRequest: OnRequestFn, httpsOptions?: HttpsOptions) {\n const handler = this.nodeHandler;\n if (httpsOptions) {\n return onRequest(httpsOptions, handler);\n }\n return onRequest(handler);\n }\n\n /** Generate (and cache) the OpenAPI 3.1 spec for the mounted routes. */\n buildOpenApiSpec(): Record<string, unknown> {\n if (this.cachedSpec) return this.cachedSpec;\n if (!this.options.openapi) {\n throw new Error(\"[HonoServer] openapi config not set\");\n }\n this.cachedSpec = buildOpenApiDocument(\n this.mountedRoutes,\n this.options.basePath ?? \"\",\n this.options.openapi,\n interceptorConfig(this.options.interceptor as InterceptorOption | undefined),\n );\n return this.cachedSpec;\n }\n\n // ── Internals ─────────────────────────────────────────────────────────\n\n private mountRoutes(): void {\n const basePath = this.options.basePath ?? \"\";\n const validateOutput = this.options.validateOutput ?? false;\n const verbose = this.options.verbose ?? false;\n\n for (const route of this.mountedRoutes) {\n if (!route.path) {\n throw new Error(\n `[HonoServer] route \"${route.method.toUpperCase()} (no path)\" — missing \\`path\\`. ` +\n \"Run the codegen so the path is derived from the file location, or set it explicitly.\",\n );\n }\n\n const fullPath = joinPath(basePath, route.path);\n const middlewares = route.middlewares ?? [];\n const source: PayloadSource =\n route.source ?? (route.method === \"get\" ? \"query\" : \"json\");\n\n const handler = makeRouteHandler(\n route,\n source,\n validateOutput,\n interceptorFn(this.options.interceptor as InterceptorOption | undefined),\n this.options.services,\n this.options.errorHandler as ErrorHandler | undefined,\n this.options.logger as Logger | undefined,\n );\n const httpMethod = route.method.toUpperCase() as\n | \"GET\"\n | \"POST\"\n | \"PUT\"\n | \"PATCH\"\n | \"DELETE\";\n // `app.on(method, path, handlers[])` accepts a variadic array of\n // handlers/middlewares — the typed `.get/.post/...` overloads don't\n // accept a spread of generic `MiddlewareHandler[]`.\n this.app.on(\n httpMethod,\n [fullPath],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...([...middlewares, handler] as any[]),\n );\n\n if (verbose) {\n // eslint-disable-next-line no-console\n console.log(\n `[HonoServer] ${route.method.toUpperCase().padEnd(6)} ${fullPath}`,\n );\n }\n }\n }\n\n private mountOpenApi(): void {\n const cfg = this.options.openapi;\n if (!cfg) return;\n const specPath = cfg.path ?? \"/openapi.json\";\n const docsPath = cfg.docsPath === undefined ? \"/docs\" : cfg.docsPath;\n const fullSpecPath = joinPath(this.options.basePath ?? \"\", specPath);\n const fullDocsPath =\n docsPath === false ? null : joinPath(this.options.basePath ?? \"\", docsPath);\n\n // Auth guards applied ONLY to the spec + docs endpoints (not API routes).\n // A DocsAuthExtension (e.g. firebaseDocsAuth) also contributes auxiliary\n // routes (login page / session / logout) mounted next to the docs.\n let guards: MiddlewareHandler[];\n if (isDocsAuthExtension(cfg.docsAuth)) {\n const ext = cfg.docsAuth;\n guards = [ext.middleware];\n // Mount the aux routes (unguarded) as siblings of the docs/spec page so\n // bare-name relative links/redirects stay correct behind any prefix.\n const authDir = dirOf(fullDocsPath ?? fullSpecPath);\n for (const route of ext.routes) {\n this.app.on(\n route.method,\n [joinPath(authDir, route.name)],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n route.handler as any,\n );\n }\n } else {\n guards = cfg.docsAuth\n ? Array.isArray(cfg.docsAuth)\n ? cfg.docsAuth\n : [cfg.docsAuth]\n : [];\n }\n\n this.app.on(\n \"GET\",\n [fullSpecPath],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...([...guards, (c: any) => c.json(this.buildOpenApiSpec())] as any[]),\n );\n\n if (fullDocsPath) {\n // Resolve the spec URL relative to the docs page so it works whether the\n // server is mounted at `/`, behind a Firebase Functions prefix\n // (`/<project>/<region>/<funcName>/...`), or behind any reverse proxy.\n const relativeSpecUrl = relativeUrlFromTo(fullDocsPath, fullSpecPath);\n this.app.on(\n \"GET\",\n [fullDocsPath],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...([\n ...guards,\n (c: any) => c.html(renderDocsHtml(relativeSpecUrl, cfg.info.title)),\n ] as any[]),\n );\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** Type guard distinguishing a structured interceptor from a bare function. */\nfunction isInterceptorConfig(\n i: InterceptorOption | undefined,\n): i is InterceptorConfig {\n return typeof i === \"object\" && i !== null && typeof i.handler === \"function\";\n}\n\n/** Extract the runtime interceptor function from either form. */\nfunction interceptorFn(\n i: InterceptorOption | undefined,\n): RouteInterceptor | undefined {\n if (!i) return undefined;\n return isInterceptorConfig(i) ? i.handler : i;\n}\n\n/** Extract the OpenAPI metadata (output/errors) from the structured form. */\nfunction interceptorConfig(\n i: InterceptorOption | undefined,\n): InterceptorConfig | undefined {\n return isInterceptorConfig(i) ? i : undefined;\n}\n\nfunction filterRoutes(\n routes: AnyRouteDef[],\n api: string | undefined,\n): AnyRouteDef[] {\n if (!api) return routes.slice();\n return routes.filter((r) =>\n Array.isArray(r.api) ? r.api.includes(api) : r.api === api,\n );\n}\n\nfunction joinPath(base: string, path: string): string {\n const left = base.endsWith(\"/\") ? base.slice(0, -1) : base;\n const right = path.startsWith(\"/\") ? path : `/${path}`;\n const merged = `${left}${right}`;\n return merged === \"\" ? \"/\" : merged;\n}\n\n/** Directory of an absolute pathname, e.g. `/v1/docs` → `/v1`, `/docs` → ``. */\nfunction dirOf(path: string): string {\n const idx = path.lastIndexOf(\"/\");\n return idx <= 0 ? \"\" : path.slice(0, idx);\n}\n\n/**\n * Compute a URL relative to `from` that points to `to`, both being absolute\n * pathnames (e.g. `/v1/docs` → `/v1/openapi.json` becomes `openapi.json`).\n * Lets the OpenAPI UI fetch the spec without knowing the upstream prefix\n * added by Firebase Functions / reverse proxies.\n */\nfunction relativeUrlFromTo(from: string, to: string): string {\n const fromSegs = from.split(\"/\").filter(Boolean);\n const toSegs = to.split(\"/\").filter(Boolean);\n // Drop the docs page filename so we resolve relative to its directory.\n fromSegs.pop();\n let common = 0;\n while (\n common < fromSegs.length &&\n common < toSegs.length &&\n fromSegs[common] === toSegs[common]\n ) {\n common++;\n }\n const ups = fromSegs.length - common;\n const rel = [\n ...Array(ups).fill(\"..\"),\n ...toSegs.slice(common),\n ].join(\"/\");\n return rel || \"./\";\n}\n\n/**\n * Build the actual Hono handler with input validation, output validation\n * (optional), and error normalisation.\n */\nfunction makeRouteHandler(\n route: AnyRouteDef,\n source: PayloadSource,\n validateOutput: boolean,\n interceptor: RouteInterceptor | undefined,\n services: AnyServicesContainer | undefined,\n errorHandler: ErrorHandler | undefined,\n logger: Logger | undefined,\n) {\n const inputSchema = route.input as z.ZodTypeAny | undefined;\n const outputSchema = route.output as z.ZodTypeAny | undefined;\n const status = route.status ?? 200;\n // Empty fallback so handlers/interceptors always see a `services` field\n // even when the server was started without a container.\n const servicesArg = (services ?? (EMPTY_SERVICES as AnyServicesContainer));\n\n return async (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n c: any,\n ): Promise<Response> => {\n // Apply the injected ErrorHandler, falling back to the built-in envelope.\n // Returns a Response when handled, or null to let the error propagate.\n const applyErrorHandler = async (err: unknown): Promise<Response | null> => {\n if (errorHandler) {\n const handled = await errorHandler.handle({\n error: err,\n c,\n route,\n services: servicesArg,\n logger,\n });\n if (handled) return handled;\n }\n return defaultErrorResponse(c, err);\n };\n\n // `next()` runs validation + handler. Any Zod failure throws\n // `ValidationError` so the interceptor (or default catcher) can shape it.\n const callNext = async (): Promise<unknown> => {\n let payload: unknown = undefined;\n\n // Always read payload if it's expected, even without an input schema.\n // E.g., generic handlers that manually validate the body.\n let raw: unknown;\n try {\n raw = await readPayload(c, source, route.method);\n } catch (err) {\n throw new BadRequestError(\n err instanceof Error ? err.message : String(err),\n );\n }\n\n if (inputSchema) {\n const parsed = inputSchema.safeParse(raw);\n if (!parsed.success) {\n throw new ValidationError(parsed.error, source);\n }\n payload = parsed.data;\n } else {\n payload = raw;\n }\n\n const result = await (route.handler as (ctx: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input: any;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n c: any;\n services: AnyServicesContainer;\n errorHandler: ErrorHandler | undefined;\n logger: Logger | undefined;\n }) => unknown)({\n input: payload,\n c,\n services: servicesArg,\n errorHandler,\n logger,\n });\n\n if (validateOutput && outputSchema && !(result instanceof Response)) {\n const checked = outputSchema.safeParse(result);\n if (!checked.success) {\n throw new OutputValidationError(checked.error);\n }\n return checked.data;\n }\n return result;\n };\n\n let result: unknown;\n if (interceptor) {\n // Interceptor owns the response shape — including validation errors.\n // If it rethrows, the injected ErrorHandler / default catcher applies.\n try {\n result = await interceptor({\n next: callNext,\n route,\n c,\n services: servicesArg,\n errorHandler,\n logger,\n });\n } catch (err) {\n const handled = await applyErrorHandler(err);\n if (handled) return handled;\n throw err;\n }\n } else {\n // Default behaviour — ErrorHandler first, then the built-in\n // ValidationError envelope, else bubble to onError / Hono.\n try {\n result = await callNext();\n } catch (err) {\n const handled = await applyErrorHandler(err);\n if (handled) return handled;\n throw err;\n }\n }\n\n if (result instanceof Response) return result;\n return c.json(result, status);\n };\n}\n\nasync function readPayload(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n c: any,\n source: PayloadSource,\n method: HttpMethod,\n): Promise<unknown> {\n switch (source) {\n case \"json\": {\n if (method === \"get\") return c.req.query();\n const text = await c.req.text();\n if (!text) return {};\n try {\n return JSON.parse(text);\n } catch (err) {\n throw new Error(\n `Invalid JSON body: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n case \"query\":\n return c.req.query();\n case \"form\": {\n const form = await c.req.parseBody();\n return form;\n }\n case \"param\":\n return c.req.param();\n default:\n return {};\n }\n}\n","/**\n * @module servers/crud/mutations\n *\n * Pre-write mutation engine for CRUD payload normalization and server-derived\n * field injection before persisting to Firestore.\n */\n\nimport type { AuthUser } from \"../auth\";\nimport { computeDeepDiff } from \"./rules\";\nimport type {\n CrudBeforeCreateContext,\n CrudBeforeUpdateContext,\n CrudWriteOperation,\n DeepDiffReturn,\n MutationsMap,\n PreWriteMutation,\n} from \"./types\";\n\n/**\n * Helper to define field-by-field (and wildcard `\"*\"`) pre-write mutations\n * with strong typing.\n */\nexport function createMutations<T>(\n mutations: MutationsMap<T>,\n): MutationsMap<T> {\n return mutations;\n}\n\nasync function runEntries<T>(\n entries: PreWriteMutation<T>[] | undefined,\n ctx: {\n body: Partial<T>;\n doc: T | null;\n diff: DeepDiffReturn<T>;\n key: keyof T | \"*\";\n operation: CrudWriteOperation;\n user?: AuthUser;\n },\n): Promise<void> {\n if (!entries?.length) return;\n for (const entry of entries) {\n if (typeof entry === \"function\") {\n await entry(ctx);\n } else if (entry && typeof entry.mutation === \"function\") {\n if (entry.operations && !entry.operations.includes(ctx.operation)) {\n continue;\n }\n await entry.mutation(ctx);\n }\n }\n}\n\n/**\n * Executes a map of pre-write mutations against `body` / `diff`:\n * 1. Runs per-field mutations for each key present in `diff.changes`.\n * 2. Runs wildcard `\"*\"` mutations unconditionally after per-field mutations.\n */\nexport async function applyMutations<T>(\n body: Partial<T>,\n doc: T | null,\n diff: DeepDiffReturn<T>,\n mutationsMap: MutationsMap<T>,\n user?: AuthUser,\n operation: CrudWriteOperation = doc ? \"update\" : \"create\",\n): Promise<void> {\n for (const key of Object.keys(diff.changes) as (keyof T)[]) {\n await runEntries(mutationsMap[key], {\n body,\n doc,\n diff,\n key,\n operation,\n user,\n });\n }\n await runEntries(mutationsMap[\"*\"], {\n body,\n doc,\n diff,\n key: \"*\",\n operation,\n user,\n });\n}\n\n/**\n * Wraps a {@link MutationsMap} into a `hooks.beforeUpdate` handler\n * (analogous to `createBeforeRules`).\n */\nexport function createBeforeUpdateMutations<T>(\n mutationsMap: MutationsMap<T>,\n): (ctx: CrudBeforeUpdateContext<T>) => Promise<void> {\n return async (ctx: CrudBeforeUpdateContext<T>): Promise<void> => {\n await applyMutations(\n ctx.body,\n ctx.doc,\n ctx.diff,\n mutationsMap,\n ctx.user,\n \"update\",\n );\n };\n}\n\n/**\n * Wraps a {@link MutationsMap} into a `hooks.beforeCreate` handler\n * (analogous to `createBeforeRules`).\n */\nexport function createBeforeCreateMutations<T>(\n mutationsMap: MutationsMap<T>,\n): (ctx: CrudBeforeCreateContext<T>) => Promise<void> {\n return async (ctx: CrudBeforeCreateContext<T>): Promise<void> => {\n const diff = computeDeepDiff(\n {} as Record<string, unknown>,\n ctx.body as Record<string, unknown>,\n ) as DeepDiffReturn<T>;\n await applyMutations(\n ctx.body,\n null,\n diff,\n mutationsMap,\n ctx.user,\n \"create\",\n );\n };\n}\n","/**\n * @module servers/crud/effects\n *\n * Reactive post-write effects engine aligned with `rules.ts` / `mutations.ts`.\n * Evaluates field-level and wildcard `\"*\"` effect rules against a recomputed diff,\n * captures per-rule errors without aborting sibling effects, and aggregates\n * optional follow-up document patches (`changesNeeded`).\n */\n\nimport type { AuthUser } from \"../auth\";\nimport type {\n ApplyEffectsResult,\n CrudAfterUpdateContext,\n CrudEffectOperation,\n DeepDiffReturn,\n EffectExecutionResult,\n EffectsMap,\n RuleEffect,\n} from \"./types\";\n\n/**\n * Helper to define field-by-field (and wildcard `\"*\"`) post-write effects\n * with strong typing.\n */\nexport function createEffects<T, TContext>(\n effects: EffectsMap<T, TContext>,\n): EffectsMap<T, TContext> {\n return effects;\n}\n\nasync function runEffectList<T, TContext>(\n rules: RuleEffect<T, TContext>[] | undefined,\n key: keyof T | \"*\",\n diff: DeepDiffReturn<T>,\n context: TContext,\n results: EffectExecutionResult[],\n changesNeeded: Partial<T>,\n user?: AuthUser,\n operation?: CrudEffectOperation,\n): Promise<Partial<T>> {\n if (!rules?.length) return changesNeeded;\n let merged = changesNeeded;\n\n for (const rule of rules) {\n let err: unknown = null;\n let isCalled = false;\n try {\n isCalled = Boolean(await rule.rule({ diff, key, user, operation }));\n if (isCalled) {\n const patch = await rule.handler(context);\n if (patch) merged = { ...merged, ...patch };\n }\n } catch (error) {\n err = error;\n }\n results.push({\n key: String(key),\n description: rule.description,\n isCalled,\n error: err,\n });\n }\n return merged;\n}\n\n/**\n * Executes a map of reactive effects against a computed `diff`:\n * 1. Runs per-field effects for every key in `diff.changes`.\n * 2. Runs wildcard `\"*\"` effects after per-field effects.\n *\n * Each effect is isolated in a `try/catch` so one failure never prevents\n * remaining effects from executing. Any `Partial<T>` patches returned by\n * handlers are merged into `changesNeeded`.\n */\nexport async function applyEffects<T, TContext>(\n diff: DeepDiffReturn<T>,\n effectsMap: EffectsMap<T, TContext>,\n context: TContext,\n user?: AuthUser,\n operation: CrudEffectOperation = \"update\",\n): Promise<ApplyEffectsResult<T>> {\n const results: EffectExecutionResult[] = [];\n let changesNeeded = {} as Partial<T>;\n\n for (const key of Object.keys(diff.changes) as (keyof T)[]) {\n changesNeeded = await runEffectList(\n effectsMap[key],\n key,\n diff,\n context,\n results,\n changesNeeded,\n user,\n operation,\n );\n }\n\n changesNeeded = await runEffectList(\n effectsMap[\"*\"],\n \"*\",\n diff,\n context,\n results,\n changesNeeded,\n user,\n operation,\n );\n\n return {\n results,\n changesNeeded,\n hasErrors: results.some((r) => r.error !== null),\n };\n}\n\n/**\n * Wraps an {@link EffectsMap} into a `hooks.afterUpdate` handler\n * (analogous to `createBeforeRules`).\n */\nexport function createAfterUpdateEffects<T, TContext>(\n effectsMap: EffectsMap<T, TContext>,\n buildContext: (ctx: CrudAfterUpdateContext<T>) => TContext,\n options?: {\n onRuleError?: (\n result: EffectExecutionResult,\n ctx: CrudAfterUpdateContext<T>,\n ) => void | Promise<void>;\n },\n): (ctx: CrudAfterUpdateContext<T>) => Promise<void | Partial<T>> {\n return async (\n ctx: CrudAfterUpdateContext<T>,\n ): Promise<void | Partial<T>> => {\n const context = buildContext(ctx);\n const { results, changesNeeded } = await applyEffects(\n ctx.diff,\n effectsMap,\n context,\n ctx.user,\n \"update\",\n );\n\n if (options?.onRuleError) {\n for (const r of results) {\n if (r.error) {\n await options.onRuleError(r, ctx);\n }\n }\n }\n\n return Object.keys(changesNeeded).length > 0 ? changesNeeded : undefined;\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 { resolveShadowConfig } from \"../../history/inject\";\nimport type { ConfiguredRepository } from \"../../repositories/types\";\nimport { getActorResolverHeaders } from \"../../shared/actor-context\";\nimport { createCrudHandlers } from \"./handlers\";\nimport { generateOpenAPISpec, type OpenAPIDocument } from \"./openapi\";\nimport type {\n CrudRepoEntry,\n CrudRepoRegistry,\n CrudServerOptions,\n OpenAPIHistoryHeadersConfig,\n} from \"./types\";\nimport { HonoServer } from \"../hono/server\";\nimport type { AnyRouteDef } from \"../hono/types\";\nimport { getLinkBase } from \"../utils/link-base\";\n\n\nexport function createCrudServer<\n TRepos extends Record<string, ConfiguredRepository<any>>,\n>(\n options: CrudServerOptions<TRepos>,\n): ((req: any, res: any) => Promise<void>) & { spec: () => OpenAPIDocument; httpsOptions?: HttpsOptions } {\n const {\n basePath = \"/\",\n repos,\n parseBody = true,\n securityHeaders: securityHeadersOpt,\n verbose = false,\n httpsOptions,\n } = options;\n\n const base = basePath === \"/\" ? \"\" : basePath.replace(/\\/$/, \"\");\n\n const registry: CrudRepoRegistry = {};\n for (const [name, cfg] of Object.entries(repos)) {\n if (!cfg.repo) {\n throw new Error(`[createCrudServer] Repository \"${name}\" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);\n }\n\n const resolvedSchema = cfg.schema ?? (cfg.repo as any).schema ?? null;\n if (!resolvedSchema) {\n throw new Error(`[createCrudServer] Repository \"${name}\" has no Zod schema.`);\n }\n\n let filterableFields: string[] | undefined;\n let orderableFields: string[] | undefined;\n let mutableFields: string[] | undefined;\n let createFields: string[] | undefined;\n if (cfg.fieldsConfig) {\n const fc = cfg.fieldsConfig as Record<string, readonly string[]>;\n filterableFields = [];\n orderableFields = [];\n mutableFields = [];\n createFields = [];\n for (const [field, roles] of Object.entries(fc)) {\n for (const role of roles) {\n if (role === \"filterable\") filterableFields.push(field);\n else if (role === \"orderable\") orderableFields.push(field);\n else if (role === \"mutable\") mutableFields.push(field);\n else if (role === \"create\") createFields.push(field);\n }\n }\n if (orderableFields.length === 0) orderableFields = filterableFields;\n if (filterableFields.length === 0) filterableFields = undefined;\n if (orderableFields && orderableFields.length === 0) orderableFields = undefined;\n if (mutableFields.length === 0) mutableFields = undefined;\n if (createFields.length === 0) createFields = undefined;\n }\n\n const parentKeys = (() => {\n const pk = (cfg.repo as any)._parentKeys as string[] | undefined;\n return pk && pk.length > 0 ? pk : undefined;\n })();\n if (parentKeys && createFields) {\n for (const pk of parentKeys) {\n if (!createFields.includes(pk)) createFields.push(pk);\n }\n }\n\n const baseSystemKeys: string[] = (cfg.repo as any)._systemKeys ?? [\n cfg.documentKey ?? \"docId\",\n ];\n const historyIdentityKeys: string[] =\n (cfg.repo as any)._historyIdentityKeys ?? [];\n const systemKeys = Array.from(\n new Set([...baseSystemKeys, ...historyIdentityKeys]),\n );\n\n const historyConfig = (cfg.repo as any)._historyConfig;\n const activeShadow =\n historyConfig?.enabled && historyConfig.autoInjectMeta !== false\n ? resolveShadowConfig(historyConfig)\n : null;\n const historyHeaders = activeShadow\n ? {\n reason: activeShadow.fields.reason !== false,\n comment: activeShadow.fields.comment !== false,\n }\n : undefined;\n\n const entry: CrudRepoEntry = {\n name,\n path: cfg.path,\n repo: cfg.repo,\n schema: resolvedSchema,\n systemKeys,\n documentKey: cfg.documentKey ?? \"docId\",\n pathKey: (cfg.repo as any)._pathKey ?? undefined,\n isGroup: !!(cfg.repo as any)._isGroup,\n parentKeys,\n documentPathTemplate:\n (cfg.repo as any)._documentPathTemplate ?? undefined,\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 hooks: cfg.hooks,\n ...(historyHeaders ? { historyHeaders } : {}),\n };\n\n registry[name] = entry;\n }\n\n const indexesErrorCb = options.indexesError ?? options.onIndexError;\n const handlers = createCrudHandlers(\n registry,\n base,\n verbose,\n indexesErrorCb,\n options.onHookError,\n );\n\n const openapi = options.openapi;\n const openapiOpts = openapi && typeof openapi === \"object\" ? openapi : {};\n const resolvedActorHeaders = getActorResolverHeaders(options.actorResolver);\n const effectiveOpenApiHistoryHeaders: false | OpenAPIHistoryHeadersConfig =\n openapiOpts.historyHeaders === false\n ? false\n : {\n reasonHeader:\n openapiOpts.historyHeaders?.reasonHeader !== undefined\n ? openapiOpts.historyHeaders.reasonHeader\n : resolvedActorHeaders.reasonHeader,\n commentHeader:\n openapiOpts.historyHeaders?.commentHeader !== undefined\n ? openapiOpts.historyHeaders.commentHeader\n : resolvedActorHeaders.commentHeader,\n ...(openapiOpts.historyHeaders?.extraHeaders\n ? { extraHeaders: openapiOpts.historyHeaders.extraHeaders }\n : {}),\n };\n\n // Build CORS Access-Control-Allow-Headers dynamically so custom actorResolver\n // header names & declared extraHeaders work seamlessly from browsers / Scalar UI.\n const corsAllowHeaders = (() => {\n const out: string[] = [\"Content-Type\", \"Authorization\"];\n const seen = new Set(out.map((h) => h.toLowerCase()));\n const addHeader = (h: string | false | undefined) => {\n if (typeof h !== \"string\") return;\n const trimmed = h.trim();\n if (!trimmed || seen.has(trimmed.toLowerCase())) return;\n seen.add(trimmed.toLowerCase());\n out.push(trimmed);\n };\n addHeader(resolvedActorHeaders.reasonHeader);\n addHeader(resolvedActorHeaders.commentHeader);\n if (\n openapiOpts.historyHeaders &&\n typeof openapiOpts.historyHeaders === \"object\"\n ) {\n addHeader(openapiOpts.historyHeaders.reasonHeader);\n addHeader(openapiOpts.historyHeaders.commentHeader);\n if (openapiOpts.historyHeaders.extraHeaders) {\n for (const extra of openapiOpts.historyHeaders.extraHeaders) {\n addHeader(typeof extra === \"string\" ? extra : extra?.name);\n }\n }\n }\n return out.join(\", \");\n })();\n\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 historyHeaders: effectiveOpenApiHistoryHeaders,\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: \"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\": corsAllowHeaders,\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 {\n applyRules,\n computeDeepDiff,\n createBeforeRules,\n createRules,\n} from \"./rules\";\nexport {\n applyMutations,\n createBeforeCreateMutations,\n createBeforeUpdateMutations,\n createMutations,\n} from \"./mutations\";\nexport {\n applyEffects,\n createAfterUpdateEffects,\n createEffects,\n} from \"./effects\";\nexport type {\n AnyCrudHooks,\n ApiResponse,\n ApplyEffectsResult,\n CrudAfterBatchContext,\n CrudAfterBatchCreatedItem,\n CrudAfterBatchDeletedItem,\n CrudAfterBatchUpdatedItem,\n CrudAfterCreateContext,\n CrudAfterDeleteContext,\n CrudAfterUpdateContext,\n CrudBeforeCreateContext,\n CrudBeforeUpdateContext,\n CrudEffectOperation,\n CrudHookErrorCallback,\n CrudHookErrorContext,\n CrudHookName,\n CrudHooks,\n CrudRepoConfig,\n CrudRepoEntry,\n CrudRepoRegistry,\n CrudRules,\n CrudServerOptions,\n CrudUpdateRuleContext,\n CrudWriteOperation,\n DeepDiffReturn,\n EffectExecutionResult,\n EffectPredicateArgs,\n EffectsMap,\n FieldRole,\n IndexErrorCallback,\n IndexErrorContext,\n ListResponseData,\n MutationContext,\n MutationRule,\n MutationsMap,\n OpenAPIHeaderParamSpec,\n OpenAPIHistoryHeadersConfig,\n PreWriteMutation,\n PreWriteMutationFn,\n QueryRequestBody,\n RepoFieldPath,\n RepoRelationKeys,\n Rule,\n RuleEffect,\n RuleResult,\n RulesMap,\n UserFieldPath,\n} from \"./types\";\n"]}
1
+ {"version":3,"sources":["../../../src/servers/utils/security-headers.ts","../../../src/shared/actor-context.ts","../../../src/history/types.ts","../../../src/history/inject.ts","../../../src/shared/date-config.ts","../../../src/shared/path-template.ts","../../../src/shared/zod-compat.ts","../../../src/servers/admin/index-url.ts","../../../src/history/diff.ts","../../../src/servers/crud/rules.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/mutations.ts","../../../src/servers/crud/effects.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","DEFAULT_HISTORY_REASON_HEADER","DEFAULT_HISTORY_COMMENT_HEADER","ACTOR_RESOLVER_HEADERS_SYMBOL","ALS_SYMBOL","g","actorStorage","AsyncLocalStorage","readFieldPath","obj","path","cur","part","pickFirstString","paths","p","val","readHeader","c","name","headerFn","createActorResolver","config","contextKeys","userIdFields","userEmailFields","reasonHeader","commentHeader","displayReasonHeader","displayCommentHeader","extrasFn","resolver","user","getFn","key","candidate","reason","comment","extras","getActorResolverHeaders","option","meta","normalizeActorResolver","createActorContextMiddleware","normalized","DEFAULT_HISTORY_SHADOW_KEY","resolveShadowConfig","shadowOpt","customFields","currentMode","getDateHandling","isTimestampLike","v","coerceToDate","value","Timestamp","d","maybeNormalize","ID_CHARS","generateFirestoreId","id","bytes","randomBytes","i","byte","extractSegmentParam","segment","parsePathTemplate","rawPath","documentKey","isGroup","segments","s","seg","isEvenSegments","collectionSegments","collectionId","collectionPath","parentKeys","documentPathTemplate","extractPathArgsFromDoc","doc","options","pathKey","fullPath","pathSegments","tplSegments","extracted","expectedCount","oddSegments","docIdVal","parentVals","allPresent","pk","getArrayElementType","schema","RANGE_OPS","ARRAY_OPS","toIndexOrder","dir","collectionIdFromPath","buildIndexUrl","projectId","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","bin","b64","field","extractProjectId","ref","r","candidates","isMissingIndexError","err","fe","toQueryError","ctx","isIndex","indexUrl","colId","valuesEqual","a","b","ka","kb","k","computeDeepDiff","before","changesInput","beforeObj","changes","after","oldVal","createRules","rules","applyRules","diff","rulesMap","rule","createBeforeRules","MAX_CRUD_PAGE_SIZE","parseCrudPageSize","raw","defaultPageSize","num","sendJson","data","status","sendSuccess","sendError","error","sendQueryError","fallbackMessage","verbose","onIndexError","qe","cbErr","wrapDateSchemas","def","typeName","z","shape","wrapped","inner","dflt","pickSchemaFields","systemKeys","picked","source","topLevel","unwrapZodType","zodType","resolveFieldPathSchema","entrySchema","parts","rawSub","makeDeepPartial","newShape","nextInner","nextOptions","opt","validateData","partial","dataObj","resultData","normalEntries","fieldSchema","effectiveFieldSchema","parsedValue","targetSchema","partialSchema","parsedNormal","e","OP_MAP","normalizeWhereOp","op","isValidOp","parseFieldValue","normalizedOp","unwrapped","elemSchema","parsed","parsedArray","item","itemParsed","parseFilters","query","filterableFields","allowedFields","rawVal","lastDoubleUnderscore","fieldCandidate","opKey","parsedVal","parseValue","serializeCursor","snapshot","deserializeCursor","entry","cursor","cursorObj","docPath","docId","colRef","firestore","pickDefinedChanges","defined","count","createCrudHandlers","registry","basePath","onHookError","reportHookError","logger","errCtx","handled","assertRule","applyRowFilter","params","docs","filter","userOf","getRepoEntry","repoName","extractPathArgs","fetchDocById","getterName","getter","handleList","ruleCheck","ctxFilters","ctxSort","pageSizeRes","pageSize","direction","orderBy","orderDir","selectStr","select","withTotalParam","withTotal","includes","inc","queryOptions","parsedRes","result","responseData","handleQuery","body","w","validIncludes","allowed","invalid","parsedWhere","parsedOrWhere","group","parsedOrWhereGroups","parsedGroup","o","handleGet","getRuleCheck","handleCreate","createRuleCheck","validation","customError","created","explicitPathArgs","missingKeys","parentIds","finalDoc","rawCreatedId","createdId","pathArgs","extraChanges","definedChanges","hookErr","handleUpdate","existingDoc","updateRuleCheck","preHookDiff","finalBody","finalDiff","updated","handleDelete","deleteRuleCheck","handleOptions","handleBatch","batch","results","hasHooks","createdItems","updatedItems","deletedItems","createdDoc","hasAnyOp","zodToJsonSchema","metadata","getOpenApiMetadata","schemaRef","errorResponse","description","successResponse","dataSchema","listResponse","itemSchema","copyMetadata","target","extractLeafFields","zodSchema","prefix","depth","fieldPath","subUnwrapped","getFilterableLeafFields","zodTypeToJsonValueSchema","jsonSchema","queryBodySchema","buildTypedQueryBodySchema","leafFields","orderableFieldNames","leafFieldNames","whereTuples","valSchema","whereItemSchema","resolveEntryHistoryFlags","historyConfig","shadow","buildHistoryHeaderParams","historyHeadersOpt","flags","seenLower","extra","spec","buildPathsForEntry","base","modelSchemaName","createSchemaName","updateSchemaName","patchSchemaName","querySchemaName","historyHeaderParams","tag","documentPath","idParam","capitalize","singularize","docOps","generateOpenAPISpec","title","version","servers","auth","schemas","allPaths","tags","modelName","createName","updateName","patchName","queryName","buildShape","fieldList","top","createShape","schemaShape","createJsonSchema","reqSet","updateShape","updateZodObj","createOpName","updateOpName","deleteOpName","entryPaths","securitySchemes","security","ValidationError","zodError","BadRequestError","OutputValidationError","formatZodIssues","defaultErrorResponse","extendZodWithOpenApi","DEFAULT_RESPONSE_DESCRIPTION","DEFAULT_ERROR_DESCRIPTION","ensureCustomSchemasHaveOpenApiType","visited","stripRedundantTypeWithComposition","node","record","defaultSource","method","resolveSuccessSchema","routeOutput","interceptor","normalizeErrorResponse","cfg","buildOpenApiDocument","routes","OpenAPIRegistry","scheme","route","joinPath","requestBody","buildRequestBody","requestQuery","buildQueryOrParam","requestParams","operationId","makeOperationId","successSchema","responses","code","convertExpressPathToOpenApi","document","OpenApiGeneratorV31","left","right","merged","cleaned","renderDocsHtml","specUrl","safeUrl","isDocsAuthExtension","als","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","inputSchema","outputSchema","servicesArg","applyErrorHandler","callNext","readPayload","checked","text","createMutations","mutations","runEntries","entries","applyMutations","mutationsMap","operation","createBeforeUpdateMutations","createBeforeCreateMutations","createEffects","effects","runEffectList","context","changesNeeded","isCalled","patch","applyEffects","effectsMap","createAfterUpdateEffects","buildContext","createCrudServer","repos","parseBody","securityHeadersOpt","resolvedSchema","orderableFields","mutableFields","createFields","fc","roles","role","baseSystemKeys","historyIdentityKeys","activeShadow","historyHeaders","indexesErrorCb","handlers","openapi","openapiOpts","resolvedActorHeaders","effectiveOpenApiHistoryHeaders","corsAllowHeaders","h","addHeader","trimmed","_specCache","getSpec","server","base0","adapter","resolve","fakeReq"],"mappings":"sVAAA,IAAA,EAAA,CAAA,MAAA,CAAA,cAAA,CAAA,IAAA,EAAA,CAAA,MAAA,CAAA,wBAAA,CAAA,IAAA,EAAA,CAAA,MAAA,CAAA,mBAAA,CAAA,IAAA,EAAA,CAA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AclC,CAAAA,CAAE,OAAOmI,CAAAA,CAAGjG,CAAC,CAAA,CAClD,YAAA,CAAeiG,CAAAA,EAAcnI,CAAAA,CAAE,GAAA,CAAI,OAAA,CAAQ,OAAOmI,CAAC,CACrD,CAAA,CAC0B,IAAM+Z,CAAAA,EAAS,EAC3C,CAAC,EACD,MAAMxjB,CAAAA,GACR,CAAC,EACH,CAEA,IAAMke,CAAAA,CAAUmF,EAAO,WAAA,CACvB,OAAAnF,CAAAA,CAAQ,IAAA,CAAOkF,CAAAA,CACXnF,CAAAA,GAAcC,CAAAA,CAAQ,YAAA,CAAeD,GAElCC,CACT","file":"index.js","sourcesContent":["/**\n * Default security-headers middleware for the bundled HTTP servers.\n *\n * Addresses issues #12 (no security headers / clickjacking / cache leakage)\n * and #13 (no CSP bounding the CDN origins loaded by the admin & login pages).\n *\n * The middleware is framework-agnostic: it only touches `res.setHeader`\n * (present on Node's `ServerResponse` and the shims used by the admin/CRUD\n * routers) and always calls `next()`.\n */\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyReq = any;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyRes = any;\ntype Next = () => void | Promise<void>;\n\n/** CDN/script origins the bundled admin UI and login page load from. */\nconst ADMIN_CDN = \"https://cdn.jsdelivr.net\";\nconst GSTATIC = \"https://www.gstatic.com\";\n\n/**\n * Reasonable default Content-Security-Policy for the bundled **HTML** pages\n * (admin UI + login). Allows the specific CDN origins the pages need and\n * forbids framing entirely. `'unsafe-inline'`/`'unsafe-eval'` are required by\n * the Tailwind browser build and the small inline bootstrap scripts.\n */\nexport const DEFAULT_HTML_CSP = [\n \"default-src 'self'\",\n `script-src 'self' 'unsafe-inline' 'unsafe-eval' ${ADMIN_CDN} ${GSTATIC}`,\n `style-src 'self' 'unsafe-inline' ${ADMIN_CDN}`,\n `connect-src 'self' ${GSTATIC} https://*.googleapis.com https://*.firebaseio.com https://identitytoolkit.googleapis.com`,\n \"img-src 'self' data:\",\n \"font-src 'self' data:\",\n \"frame-ancestors 'none'\",\n \"base-uri 'self'\",\n \"form-action 'self'\",\n].join(\"; \");\n\nexport interface SecurityHeadersOptions {\n /**\n * Content-Security-Policy value. Pass a string to override, or `false` to\n * omit the header entirely. Defaults to {@link DEFAULT_HTML_CSP} for HTML\n * servers (admin/login) and is omitted for pure JSON APIs unless provided.\n */\n csp?: string | false;\n /**\n * `X-Frame-Options` value. Default `\"DENY\"`. Pass `false` to omit (e.g. when\n * the app must be embedded in a trusted iframe — prefer a CSP\n * `frame-ancestors` allowlist instead).\n */\n frameOptions?: string | false;\n /** `Referrer-Policy` value. Default `\"no-referrer\"`. */\n referrerPolicy?: string | false;\n /**\n * `Cache-Control` value. Default `\"private, no-store\"` to keep private data\n * out of shared proxy caches. Pass `false` to leave caching to handlers.\n */\n cacheControl?: string | false;\n}\n\n/**\n * Build a middleware that sets a baseline of security response headers.\n *\n * @example\n * ```ts\n * router.use(securityHeaders()); // HTML-safe defaults\n * router.use(securityHeaders({ csp: false })); // JSON API (no CSP)\n * ```\n */\nexport function securityHeaders(opts: SecurityHeadersOptions = {}) {\n const csp = opts.csp === undefined ? DEFAULT_HTML_CSP : opts.csp;\n const frameOptions = opts.frameOptions === undefined ? \"DENY\" : opts.frameOptions;\n const referrerPolicy =\n opts.referrerPolicy === undefined ? \"no-referrer\" : opts.referrerPolicy;\n const cacheControl =\n opts.cacheControl === undefined ? \"private, no-store\" : opts.cacheControl;\n\n return async (_req: AnyReq, res: AnyRes, next: Next): Promise<void> => {\n if (typeof res?.setHeader === \"function\") {\n res.setHeader(\"X-Content-Type-Options\", \"nosniff\");\n if (frameOptions) res.setHeader(\"X-Frame-Options\", frameOptions);\n if (referrerPolicy) res.setHeader(\"Referrer-Policy\", referrerPolicy);\n if (cacheControl) res.setHeader(\"Cache-Control\", cacheControl);\n if (csp) res.setHeader(\"Content-Security-Policy\", csp);\n }\n await next();\n };\n}\n","/**\n * Request-scoped & programmatic actor context backed by `AsyncLocalStorage`.\n *\n * Uses a `globalThis[Symbol.for(...)]` singleton so separate tsup bundles\n * (`dist/index`, `dist/servers/hono`, `dist/servers/crud`, `dist/history`,\n * `dist/servers/index`) always share the exact same `AsyncLocalStorage`\n * instance.\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { Context, MiddlewareHandler } from \"hono\";\n\n/** Actor & audit metadata captured for history writes. */\nexport interface HistoryActor {\n userId?: string | null;\n userEmail?: string | null;\n reason?: string | null;\n comment?: string | null;\n extras?: Record<string, unknown>;\n}\n\n/** Function resolving the current actor lazily from a Hono `Context`. */\nexport type ActorResolver = (c: Context) => HistoryActor | null | undefined;\n\n/**\n * Declarative configuration for {@link createActorResolver} so projects can\n * customize context keys, nested user property paths, and request headers\n * without writing a full resolver from scratch.\n */\nexport interface ActorResolverFieldConfig {\n /**\n * Hono context keys inspected in order via `c.get(key)`.\n * Default: `[\"user\", \"docsUser\"]`.\n */\n contextKeys?: string[];\n /**\n * Property paths on the user object checked in order for `userId`.\n * Supports dot-notation (e.g. `\"baseUser.id\"`).\n * Default: `[\"uid\", \"id\", \"sub\"]`.\n */\n userIdFields?: string[];\n /**\n * Property paths on the user object checked in order for `userEmail`.\n * Supports dot-notation (e.g. `\"baseUser.email\"`).\n * Default: `[\"email\"]`.\n */\n userEmailFields?: string[];\n /**\n * HTTP header name for change reason, or `false` to disable header lookup.\n * Default: `\"x-history-reason\"`.\n */\n reasonHeader?: string | false;\n /**\n * HTTP header name for change comment, or `false` to disable header lookup.\n * Default: `\"x-history-comment\"`.\n */\n commentHeader?: string | false;\n /**\n * Optional extractor to populate `actor.extras` from `(c, user)`.\n */\n extras?: (\n c: Context,\n user: Record<string, unknown> | null,\n ) => Record<string, unknown> | undefined;\n}\n\n/**\n * Accepted by `HonoServerOptions.actorResolver`, `ApiRegistryOptions.actorResolver`,\n * `CrudServerOptions.actorResolver`, and `CreateServersDeps.actorResolver`:\n * either a custom resolver function or a declarative field-mapping config.\n */\nexport type ActorResolverOption = ActorResolver | ActorResolverFieldConfig;\n\n/** Canonical default HTTP header name for change reason. */\nexport const DEFAULT_HISTORY_REASON_HEADER = \"X-History-Reason\";\n\n/** Canonical default HTTP header name for change comment. */\nexport const DEFAULT_HISTORY_COMMENT_HEADER = \"X-History-Comment\";\n\n/** Resolved history audit header names exposed by an `actorResolver`. */\nexport interface ResolvedHistoryHeaderNames {\n reasonHeader: string | false;\n commentHeader: string | false;\n}\n\nconst ACTOR_RESOLVER_HEADERS_SYMBOL = Symbol.for(\n \"@lpdjs/firestore-repo-service:actorResolverHeaders\",\n);\n\ninterface ActorStore {\n c?: Context;\n resolver?: ActorResolver;\n override?: Partial<HistoryActor>;\n}\n\nconst ALS_SYMBOL = Symbol.for(\"@lpdjs/firestore-repo-service:actorContext\");\nconst g = globalThis as Record<\n symbol,\n AsyncLocalStorage<ActorStore> | undefined\n>;\nconst actorStorage = (g[ALS_SYMBOL] ??= new AsyncLocalStorage<ActorStore>());\n\n/** Safely traverse a dot-notation path (e.g. `\"baseUser.email\"`) on an object. */\nfunction readFieldPath(\n obj: Record<string, unknown>,\n path: string,\n): unknown {\n if (!path.includes(\".\")) return obj[path];\n let cur: unknown = obj;\n for (const part of path.split(\".\")) {\n if (!cur || typeof cur !== \"object\") return undefined;\n cur = (cur as Record<string, unknown>)[part];\n }\n return cur;\n}\n\n/** Pick the first non-empty string/number value across candidate paths. */\nfunction pickFirstString(\n obj: Record<string, unknown>,\n paths: string[],\n): string | null {\n for (const p of paths) {\n const val = readFieldPath(obj, p);\n if (typeof val === \"string\" && val.length > 0) return val;\n if (typeof val === \"number\") return String(val);\n }\n return null;\n}\n\n/** Read an HTTP header safely from a Hono `Context` (tolerates minimal mocks). */\nfunction readHeader(c: Context, name: string | false): string | undefined {\n if (name === false) return undefined;\n const headerFn = (c as any)?.req?.header;\n if (typeof headerFn !== \"function\") return undefined;\n const val = headerFn.call((c as any).req, name);\n return typeof val === \"string\" && val.length > 0 ? val : undefined;\n}\n\n/**\n * Build an {@link ActorResolver} from a declarative field/header configuration.\n *\n * @example\n * ```ts\n * const actorResolver = createActorResolver({\n * contextKeys: [\"authUser\", \"user\"],\n * userIdFields: [\"docId\", \"uid\"],\n * userEmailFields: [\"baseUser.email\", \"email\"],\n * reasonHeader: \"x-audit-reason\",\n * });\n * ```\n */\nexport function createActorResolver(\n config: ActorResolverFieldConfig = {},\n): ActorResolver {\n const contextKeys = config.contextKeys ?? [\"user\", \"docsUser\"];\n const userIdFields = config.userIdFields ?? [\"uid\", \"id\", \"sub\"];\n const userEmailFields = config.userEmailFields ?? [\"email\"];\n const reasonHeader =\n config.reasonHeader === undefined ? \"x-history-reason\" : config.reasonHeader;\n const commentHeader =\n config.commentHeader === undefined\n ? \"x-history-comment\"\n : config.commentHeader;\n const displayReasonHeader: string | false =\n config.reasonHeader === undefined\n ? DEFAULT_HISTORY_REASON_HEADER\n : config.reasonHeader;\n const displayCommentHeader: string | false =\n config.commentHeader === undefined\n ? DEFAULT_HISTORY_COMMENT_HEADER\n : config.commentHeader;\n const extrasFn = config.extras;\n\n const resolver: ActorResolver = (c: Context): HistoryActor | null => {\n let user: Record<string, unknown> | null = null;\n const getFn = (c as any)?.get;\n if (typeof getFn === \"function\") {\n for (const key of contextKeys) {\n const candidate = getFn.call(c, key);\n if (candidate && typeof candidate === \"object\") {\n user = candidate as Record<string, unknown>;\n break;\n }\n }\n }\n\n const reason = readHeader(c, reasonHeader);\n const comment = readHeader(c, commentHeader);\n const extras = extrasFn ? extrasFn(c, user) : undefined;\n\n if (!user) {\n if (reason === undefined && comment === undefined && !extras) {\n return null;\n }\n return {\n ...(reason !== undefined ? { reason } : {}),\n ...(comment !== undefined ? { comment } : {}),\n ...(extras ? { extras } : {}),\n };\n }\n\n return {\n userId: pickFirstString(user, userIdFields),\n userEmail: pickFirstString(user, userEmailFields),\n ...(reason !== undefined ? { reason } : {}),\n ...(comment !== undefined ? { comment } : {}),\n ...(extras ? { extras } : {}),\n };\n };\n\n Object.defineProperty(resolver, ACTOR_RESOLVER_HEADERS_SYMBOL, {\n value: {\n reasonHeader: displayReasonHeader,\n commentHeader: displayCommentHeader,\n } satisfies ResolvedHistoryHeaderNames,\n enumerable: false,\n configurable: false,\n });\n\n return resolver;\n}\n\n/**\n * Inspect an {@link ActorResolverOption} (declarative config object, resolver\n * created via {@link createActorResolver}, custom function, or `undefined`)\n * and return the effective history audit header names for OpenAPI / CORS.\n */\nexport function getActorResolverHeaders(\n option?: ActorResolverOption,\n): ResolvedHistoryHeaderNames {\n if (!option) {\n return {\n reasonHeader: DEFAULT_HISTORY_REASON_HEADER,\n commentHeader: DEFAULT_HISTORY_COMMENT_HEADER,\n };\n }\n if (typeof option === \"function\") {\n const meta = (option as any)[ACTOR_RESOLVER_HEADERS_SYMBOL] as\n | ResolvedHistoryHeaderNames\n | undefined;\n if (meta) return { ...meta };\n return {\n reasonHeader: DEFAULT_HISTORY_REASON_HEADER,\n commentHeader: DEFAULT_HISTORY_COMMENT_HEADER,\n };\n }\n return {\n reasonHeader:\n option.reasonHeader === undefined\n ? DEFAULT_HISTORY_REASON_HEADER\n : option.reasonHeader,\n commentHeader:\n option.commentHeader === undefined\n ? DEFAULT_HISTORY_COMMENT_HEADER\n : option.commentHeader,\n };\n}\n\n/**\n * Default actor resolver compatible with Firebase JWT / `firebaseBearerAuth` /\n * custom auth middlewares setting `c.get(\"user\")` or `c.get(\"docsUser\")`.\n */\nexport const defaultActorResolver: ActorResolver = createActorResolver();\n\n/** Normalize either a function resolver or a declarative config object. */\nexport function normalizeActorResolver(\n option?: ActorResolverOption,\n): ActorResolver | undefined {\n if (!option) return undefined;\n return typeof option === \"function\" ? option : createActorResolver(option);\n}\n\n/**\n * Hono middleware mounted automatically at the top of `HonoServer`.\n * Stores `{ c, resolver }` in `AsyncLocalStorage` so downstream repository\n * writes resolve the authenticated user lazily after auth middlewares run.\n */\nexport function createActorContextMiddleware(\n resolver?: ActorResolverOption,\n): MiddlewareHandler {\n const normalized = normalizeActorResolver(resolver);\n return async (c, next) => {\n await actorStorage.run({ c, resolver: normalized }, async () => {\n await next();\n });\n };\n}\n\n/**\n * Resolve the active {@link HistoryActor} for the current async execution\n * context, or `null` when outside any scope or when no actor is available.\n */\nexport function getCurrentActor(): HistoryActor | null {\n const store = actorStorage.getStore();\n if (!store) return null;\n\n let fromReq: HistoryActor | null | undefined = null;\n if (store.c) {\n try {\n fromReq = (store.resolver ?? defaultActorResolver)(store.c);\n } catch {\n fromReq = null;\n }\n }\n\n if (!fromReq && !store.override) return null;\n\n const merged: HistoryActor = { ...(fromReq ?? {}) };\n if (store.override) {\n if (store.override.userId !== undefined) {\n merged.userId = store.override.userId;\n }\n if (store.override.userEmail !== undefined) {\n merged.userEmail = store.override.userEmail;\n }\n if (store.override.reason !== undefined) {\n merged.reason = store.override.reason;\n }\n if (store.override.comment !== undefined) {\n merged.comment = store.override.comment;\n }\n if (store.override.extras !== undefined) {\n merged.extras = {\n ...(fromReq?.extras ?? {}),\n ...store.override.extras,\n };\n }\n }\n\n return merged;\n}\n\n/**\n * Execute `fn` within an isolated actor scope — ideal for crons, Pub/Sub\n * workers, scripts, and unit tests.\n *\n * @example\n * ```ts\n * await withActor({ userId: \"cron:invoicing\", reason: \"monthly-run\" }, async () => {\n * await repos.invoices.create(payload);\n * });\n * ```\n */\nexport function withActor<T>(actor: HistoryActor, fn: () => T): T {\n return actorStorage.run({ override: { ...actor } }, fn);\n}\n\n/**\n * Enrich or override actor metadata (`reason`, `comment`, `extras`, …) for the\n * current active request / `withActor` scope without touching repository calls.\n *\n * Safe no-op returning `false` when called outside any active ALS scope.\n */\nexport function setRequestActorMeta(meta: Partial<HistoryActor>): boolean {\n const store = actorStorage.getStore();\n if (!store) return false;\n\n const prev = store.override ?? {};\n const nextOverride: Partial<HistoryActor> = { ...prev, ...meta };\n if (prev.extras || meta.extras) {\n nextOverride.extras = {\n ...(prev.extras ?? {}),\n ...(meta.extras ?? {}),\n };\n }\n store.override = nextOverride;\n return true;\n}\n","/**\n * Types and interfaces for the history (change-log) module.\n *\n * The package writes history entries in **schema v2** (1 Firestore document\n * per `update`/`create`/`delete` event, with a `changes` map keyed by field\n * name). It reads both v1 (legacy: 1 doc per modified field) and v2 by\n * normalising them into a unified {@link HistoryEntry} shape.\n */\n\nimport type { Timestamp } from \"firebase-admin/firestore\";\nimport type {\n DocumentOptions,\n onDocumentWritten,\n} from \"firebase-functions/v2/firestore\";\n\n/**\n * Cloud Functions v2 options forwarded to `onDocumentWritten()` for history triggers.\n * The `document` field is omitted because the library sets it itself from the collection path.\n */\nexport type TriggerOptions = Omit<DocumentOptions, \"document\">;\nexport type HistoryTriggerOptions = TriggerOptions;\n\n/* ------------------------------------------------------------------------- */\n/* Public unified shape */\n/* ------------------------------------------------------------------------- */\n\nexport type HistoryOperation = \"create\" | \"update\" | \"delete\" | \"custom\";\n\n/**\n * Structured payload attached to `operation: \"custom\"` history entries\n * (business actions independent of model fields, e.g. manual invoice creation,\n * PDF export, email sent, etc.).\n */\nexport interface HistoryCustomData {\n /** Human-readable title (e.g. `\"Création de la facture\"`). */\n title: string;\n /** Optional human-readable description (e.g. `\"Facture #F-2026-042 créée manuellement\"`). */\n description?: string;\n /** Optional business action key for filtering/grouping/icons (e.g. `\"invoice_create_manually\"`). */\n key?: string;\n /** Optional front-end visibility flag (default: `true`). */\n display?: boolean;\n /** Optional arbitrary structured business payload (e.g. `{ invoiceId, amount }`). */\n data?: Record<string, unknown>;\n}\n\n/** Input payload accepted by `repo.history.recordCustom(...)`. */\nexport interface HistoryCustomInput extends HistoryCustomData {\n /**\n * Optional metadata overrides (`reason`, `comment`, `extras`, `userId`,\n * `userEmail`). Automatically merged on top of the active ALS actor.\n */\n meta?: HistoryMeta;\n}\n\n/**\n * Detected JS/Firestore type of a value as stored in a history entry.\n * Matches the values returned by {@link valueType}.\n */\nexport type HistoryValueType =\n | \"string\"\n | \"number\"\n | \"boolean\"\n | \"timestamp\"\n | \"date\"\n | \"array\"\n | \"object\"\n | \"null\"\n | \"undefined\";\n\n/** A single field change inside a history entry. */\nexport interface HistoryFieldChange {\n oldValue: unknown;\n newValue: unknown;\n type: { old: HistoryValueType; new: HistoryValueType };\n}\n\n/** Captured metadata for a history entry. */\nexport interface HistoryMeta {\n userId?: string | null;\n userEmail?: string | null;\n reason?: string | null;\n comment?: string | null;\n /** Free-form extra fields copied from the source document. */\n extras?: Record<string, unknown>;\n}\n\n/**\n * Unified history entry returned by `repo.history.list(...)`.\n * Both v1 and v2 documents are normalised into this shape.\n */\nexport interface HistoryEntry<T = Record<string, unknown>> {\n /** Stable id of the underlying Firestore history document (the v1+v2 storage doc). */\n historyDocId: string;\n /** Id of the entity this entry belongs to. */\n historyToObjectId: string;\n /** When the change was recorded. */\n historySetAt: Timestamp;\n /** Source schema version. v1 = legacy (1 doc/field), v2 = current (1 doc/update). */\n schemaVersion: 1 | 2;\n /** v2 only — v1 is always normalised to \"update\". */\n operation: HistoryOperation;\n /** Captured author / context information. */\n meta: HistoryMeta;\n /** Present on `operation: \"custom\"` entries (business actions independent of model fields). */\n custom?: HistoryCustomData;\n /** Per-field changes. Keys are field names of T. */\n changes: { [K in keyof T & string]?: HistoryFieldChange } & {\n [field: string]: HistoryFieldChange;\n };\n}\n\n/* ------------------------------------------------------------------------- */\n/* Storage-level shapes (what is actually written / read in Firestore) */\n/* ------------------------------------------------------------------------- */\n\n/** v2 document layout. */\nexport interface V2HistoryDoc {\n schemaVersion: 2;\n historyDocId: string;\n historyToObjectId: string;\n historySetAt: Timestamp;\n operation: HistoryOperation;\n meta: HistoryMeta;\n /** Present on `operation: \"custom\"` entries. */\n custom?: HistoryCustomData;\n changes: Record<string, HistoryFieldChange>;\n /** Optional TTL marker (Firestore deletes the doc after this date). */\n expiresAt?: Timestamp;\n /** Set when the doc had to be truncated to fit the 1 MiB limit. */\n _truncated?: boolean;\n}\n\n/** v1 document layout (legacy — read-only support). */\nexport interface V1HistoryDoc {\n // schemaVersion is absent in v1.\n schemaVersion?: undefined;\n historyDocId: string;\n historyToObjectId: string;\n historyUserId?: string;\n historyUserEmail?: string;\n historySetAt: Timestamp;\n field: string;\n changes: { oldValue: unknown; newValue: unknown };\n types?: { oldValue: string; newValue: string };\n // Extra freeform metadata seen in legacy code.\n historyDetails?: Record<string, unknown> | null;\n extraHistoryDetails?: {\n comment?: string;\n reason?: string;\n toKey?: string;\n force?: boolean;\n } | null;\n extraContentKeys?: Record<string, unknown> | null;\n objectType?: string;\n}\n\n/* ------------------------------------------------------------------------- */\n/* Configuration */\n/* ------------------------------------------------------------------------- */\n\n/** Default top-level shadow field name stored on Firestore documents for auto-injected history metadata. */\nexport const DEFAULT_HISTORY_SHADOW_KEY = \"_historyMeta\";\n\n/**\n * Customize (or disable via `false`) the sub-field names stored inside the\n * shadow metadata object on Firestore documents.\n */\nexport interface HistoryShadowFieldsConfig {\n /** Key inside the shadow object for author userId, or `false` to omit. Default: `\"userId\"`. */\n userId?: string | false;\n /** Key inside the shadow object for author userEmail, or `false` to omit. Default: `\"userEmail\"`. */\n userEmail?: string | false;\n /** Key inside the shadow object for change reason, or `false` to omit. Default: `\"reason\"`. */\n reason?: string | false;\n /** Key inside the shadow object for change comment, or `false` to omit. Default: `\"comment\"`. */\n comment?: string | false;\n /** Key inside the shadow object for extras map, or `false` to omit. Default: `\"extras\"`. */\n extras?: string | false;\n}\n\n/**\n * Configuration for the internal shadow field used to transport actor metadata\n * to Firestore `onDocumentWritten` triggers without modifying Zod schemas.\n */\nexport interface HistoryShadowConfig {\n /**\n * Top-level field name stored on the Firestore document (not required in the\n * Zod schema, automatically excluded from diffs and sync, and stripped on read).\n * Default: `\"_historyMeta\"`.\n */\n key?: string;\n /**\n * Customize or disable individual sub-field names inside the shadow object.\n * Default: `{ userId: \"userId\", userEmail: \"userEmail\", reason: \"reason\", comment: \"comment\", extras: \"extras\" }`.\n */\n fields?: HistoryShadowFieldsConfig;\n}\n\n/**\n * Fallback author values written when no actor is active in `AsyncLocalStorage`\n * (crons, scripts, admin UI, public routes).\n */\nexport interface HistoryFallbackActor {\n userId?: string | null;\n userEmail?: string | null;\n}\n\n/**\n * Per-repo history configuration. Attached on the repository config under\n * the `history` key. All meta sub-keys must reference fields that exist on\n * the model (compile-time enforced by {@link HistoryConfigForModel}).\n */\nexport interface HistoryConfigBase {\n /** Master switch — when false/absent, no triggers are generated and no `repo.history` API is exposed. */\n enabled: boolean;\n /** Subcollection name used to store history docs. Default: \"history\". */\n subcollection?: string;\n /**\n * Automatically inject actor metadata from `AsyncLocalStorage` into the\n * shadow field on repository writes (`create`, `set`, `update`, `batch`,\n * `transaction`, `bulk`). Default: `true` when `enabled: true`.\n */\n autoInjectMeta?: boolean;\n /**\n * Shadow field configuration (zero Zod schema changes).\n *\n * - Omitted or `true` (when `meta` is absent): uses `\"_historyMeta\"` with default sub-fields.\n * - `string`: shorthand for `{ key: \"<customKey>\" }`.\n * - `HistoryShadowConfig`: customize both `key` and nested `fields`.\n * - `false`: disable shadow metadata injection/reading.\n */\n shadow?: boolean | string | HistoryShadowConfig;\n /**\n * Fallback actor written when no actor is active in `AsyncLocalStorage` so\n * previous author metadata never leaks onto subsequent writes.\n * Default: `{ userId: null, userEmail: null }`.\n */\n fallbackActor?: HistoryFallbackActor;\n /**\n * Optional Firestore TTL configuration. When set, every written history doc\n * gets an `expiresAt` Timestamp at `now + days`. You still need to enable\n * the TTL policy on the `expiresAt` field via gcloud / console.\n */\n ttl?: { days: number };\n /**\n * Cloud Functions v2 options forwarded to `onDocumentWritten()` for this\n * repository's history trigger (e.g. `region`, `vpcConnector`, `memory`, etc.).\n */\n triggerOptions?: HistoryTriggerOptions;\n}\n\n/**\n * Strongly-typed history config bound to a model `T`.\n *\n * - `meta.*` keys must be keyof T (or string for `extras` entries).\n * - `include` / `exclude` accept keyof T.\n */\nexport interface HistoryConfigForModel<T> extends HistoryConfigBase {\n meta?: {\n /** Field on T that holds the author user id. */\n userId?: keyof T & string;\n /** Field on T that holds the author email. */\n userEmail?: keyof T & string;\n /** Field on T that holds an optional change reason. */\n reason?: keyof T & string;\n /** Field on T that holds an optional change comment. */\n comment?: keyof T & string;\n /** Free-form extra field names copied verbatim into `meta.extras`. */\n extras?: (keyof T & string)[];\n };\n /** When set, only these top-level fields are diffed. */\n include?: (keyof T & string)[];\n /** Always excluded from the diff (in addition to meta + system keys). */\n exclude?: (keyof T & string)[];\n /**\n * Optional async hook to enrich/mutate an entry before it's written.\n * Return `null` to drop the entry entirely.\n */\n onBeforeWrite?: (\n entry: V2HistoryDoc,\n ctx: { repoName: string; docId: string; before: T | null; after: T | null },\n ) => V2HistoryDoc | null | Promise<V2HistoryDoc | null>;\n}\n\n/* ------------------------------------------------------------------------- */\n/* Read API options */\n/* ------------------------------------------------------------------------- */\n\nexport interface HistoryListOptions<T = unknown> {\n /** Max number of normalised entries to return. Default: 50. */\n limit?: number;\n /** Cursor for pagination (use `historySetAt` of the last received entry). */\n cursor?: Timestamp;\n /** Sort direction on `historySetAt`. Default: \"desc\". */\n direction?: \"asc\" | \"desc\";\n /** Restrict to entries that touch any of these fields (post-filter). */\n fields?: (keyof T & string)[];\n /** Restrict to entries with these operations (v2 only — v1 is always \"update\"). */\n operations?: HistoryOperation[];\n}\n\nexport interface HistoryRawListOptions {\n limit?: number;\n cursor?: Timestamp;\n direction?: \"asc\" | \"desc\";\n}\n\n/* ------------------------------------------------------------------------- */\n/* Trigger factory configuration */\n/* ------------------------------------------------------------------------- */\n\n/**\n * Firestore trigger constructors injected by the consumer.\n * Mirrors the DI pattern used by `createSyncTriggers`.\n */\nexport interface HistoryFirestoreTriggersDep {\n // Either onDocumentWritten alone is enough; we keep the more granular ones\n // available so the worker can stay efficient.\n onDocumentWritten: typeof onDocumentWritten;\n}\n\n/** Per-repo override at the `createHistoryTriggers` call site. */\nexport interface HistoryTriggerRepoOverride {\n /**\n * Explicit Firestore document path pattern. Required for collection-group\n * repositories whose path cannot be auto-detected.\n * @example \"residences/{residenceId}/workshops/{docId}\"\n */\n triggerPath?: string;\n /**\n * Cloud Functions v2 options forwarded to `onDocumentWritten()` for this\n * repository's history trigger. Overrides global `triggerOptions`.\n */\n triggerOptions?: HistoryTriggerOptions;\n}\n\nexport interface HistoryTriggersConfig<M = Record<string, any>> {\n deps: HistoryFirestoreTriggersDep;\n /** Defaults applied to every repo unless overridden. */\n defaults?: { ttl?: { days: number } };\n /**\n * Cloud Functions v2 options forwarded to `onDocumentWritten()` for every\n * history trigger handler. Use to configure `region`, `vpcConnector`,\n * `memory`, `cpu`, `timeoutSeconds`, `maxInstances`, `secrets`, etc.\n */\n triggerOptions?: HistoryTriggerOptions;\n /** Per-repo overrides keyed by repo name in the mapping. */\n repos?: Partial<Record<keyof M & string, HistoryTriggerRepoOverride>>;\n}\n","/**\n * Shadow metadata injection, resolution, and read-stripping helpers for the\n * history module.\n *\n * Writes actor metadata from the cross-bundle `AsyncLocalStorage` context into\n * a configurable shadow object (default `_historyMeta`) on Firestore documents\n * without requiring any changes to model Zod schemas.\n */\n\nimport { getCurrentActor } from \"../shared/actor-context\";\nimport {\n DEFAULT_HISTORY_SHADOW_KEY,\n type HistoryConfigForModel,\n} from \"./types\";\n\nexport interface ResolvedShadowFields {\n userId: string | false;\n userEmail: string | false;\n reason: string | false;\n comment: string | false;\n extras: string | false;\n}\n\nexport interface ResolvedShadowConfig {\n key: string;\n fields: ResolvedShadowFields;\n}\n\n/**\n * Resolve the effective shadow storage configuration for a repository's\n * `history` config, or `null` when shadow storage is inactive.\n *\n * Shadow storage is active whenever `history.enabled` is `true`, `shadow` is\n * not `false`, and either `meta` is omitted or `shadow` is explicitly provided.\n */\nexport function resolveShadowConfig(\n config: HistoryConfigForModel<any> | undefined | null,\n): ResolvedShadowConfig | null {\n if (!config?.enabled) return null;\n if (config.shadow === false) return null;\n if (config.meta && config.shadow === undefined) return null;\n\n const shadowOpt = config.shadow;\n const key =\n typeof shadowOpt === \"string\" && shadowOpt.trim().length > 0\n ? shadowOpt.trim()\n : typeof shadowOpt === \"object\" &&\n shadowOpt !== null &&\n typeof shadowOpt.key === \"string\" &&\n shadowOpt.key.trim().length > 0\n ? shadowOpt.key.trim()\n : DEFAULT_HISTORY_SHADOW_KEY;\n\n const customFields =\n typeof shadowOpt === \"object\" && shadowOpt !== null\n ? shadowOpt.fields\n : undefined;\n\n return {\n key,\n fields: {\n userId: customFields?.userId ?? \"userId\",\n userEmail: customFields?.userEmail ?? \"userEmail\",\n reason: customFields?.reason ?? \"reason\",\n comment: customFields?.comment ?? \"comment\",\n extras: customFields?.extras ?? \"extras\",\n },\n };\n}\n\n/**\n * Return the active shadow key for a repository's history config, or `null`\n * when shadow storage is inactive.\n */\nexport function getHistoryShadowKey(\n config: HistoryConfigForModel<any> | undefined | null,\n): string | null {\n return resolveShadowConfig(config)?.key ?? null;\n}\n\n/**\n * Return the reserved identity/shadow keys that must be stripped from incoming\n * CRUD payloads (anti-spoofing) and omitted from Create/Update OpenAPI schemas.\n */\nexport function getHistoryIdentityKeys(\n config: HistoryConfigForModel<any> | undefined | null,\n): string[] {\n const shadow = resolveShadowConfig(config);\n return shadow ? [shadow.key] : [];\n}\n\n/**\n * Strip the internal shadow field from a document returned by repository\n * read/write methods (`get`, `query`, `paginate`, `create`, `set`, `update`,\n * `transaction.get`). Zero-overhead no-op when `shadowKey` is `null` or absent.\n */\nexport function stripHistoryShadowField<T>(\n value: T,\n shadowKey: string | null | undefined,\n): T {\n if (!shadowKey || !value || typeof value !== \"object\" || Array.isArray(value)) {\n return value;\n }\n const rec = value as Record<string, unknown>;\n if (!(shadowKey in rec)) return value;\n\n const { [shadowKey]: _dropped, ...rest } = rec;\n return rest as T;\n}\n\n/**\n * Inject the current ALS actor metadata into the configurable shadow field on\n * a Firestore write payload (`create`, `set`, `update`, `batch`, `transaction`,\n * `bulk`).\n *\n * Always writes explicit `null` for absent `reason`, `comment`, `extras`, and\n * applies `fallbackActor` when no actor is active so previous write metadata\n * never leaks — including across Firestore `set(..., { merge: true })`.\n */\nexport function injectHistoryMeta(\n payload: Record<string, unknown>,\n historyConfig: HistoryConfigForModel<any> | undefined,\n): void {\n if (!historyConfig?.enabled || historyConfig.autoInjectMeta === false) return;\n\n const shadow = resolveShadowConfig(historyConfig);\n if (!shadow) return;\n\n const actor = getCurrentActor();\n const fallback = historyConfig.fallbackActor ?? {};\n const userId =\n actor?.userId !== undefined ? actor.userId : (fallback.userId ?? null);\n const userEmail =\n actor?.userEmail !== undefined\n ? actor.userEmail\n : (fallback.userEmail ?? null);\n const reason = actor?.reason ?? null;\n const comment = actor?.comment ?? null;\n const extras =\n actor?.extras && Object.keys(actor.extras).length > 0 ? actor.extras : null;\n\n const shadowObj: Record<string, unknown> = {};\n const { fields } = shadow;\n if (fields.userId !== false) shadowObj[fields.userId] = userId;\n if (fields.userEmail !== false) shadowObj[fields.userEmail] = userEmail;\n if (fields.reason !== false) shadowObj[fields.reason] = reason;\n if (fields.comment !== false) shadowObj[fields.comment] = comment;\n if (fields.extras !== false) shadowObj[fields.extras] = extras;\n\n payload[shadow.key] = shadowObj;\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","import { randomBytes } from \"node:crypto\";\nimport type { DocumentReference, Firestore } from \"firebase-admin/firestore\";\n\nconst ID_CHARS =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n\n/**\n * Generate a random 20-char alphanumeric ID matching Firestore's native format.\n *\n * Uses a CSPRNG (`crypto.randomBytes`) with rejection sampling (dropping the\n * biased tail `>= 62*4`) to keep the distribution uniform across the 62-char\n * alphabet.\n */\nexport function 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 >= ID_CHARS.length * 4) continue; // drop biased tail (248..255)\n id += ID_CHARS.charAt(byte % ID_CHARS.length);\n }\n }\n return id;\n}\n\n/** Extract parameter name from a `{param}` segment, or `null` if static. */\nfunction extractSegmentParam(segment: string): string | null {\n const match = segment.match(/^\\{([^}]+)\\}$/);\n return match?.[1]?.trim() || null;\n}\n\n/**\n * Parsed metadata from a repository `path` configuration string.\n */\nexport interface ParsedPathTemplate {\n /** Raw path string as configured on the repository */\n rawPath: string;\n /**\n * Target Firestore collection ID (last collection segment, e.g. `\"prev_events\"`\n * from `\"prevention/prev_rules/prev_workshops/{workshopId}/prev_events\"`).\n * Used for `db.collectionGroup(collectionId)`.\n */\n collectionId: string;\n /**\n * Collection path (without trailing document segment). Used for `db.collection(...)`\n * on non-group repositories (`isGroup: false`).\n */\n collectionPath: string;\n /**\n * Ordered list of dynamic `{param}` parent keys extracted from the path\n * (excluding fixed transit segments like `\"prev_rules\"` and the trailing\n * `documentKey`).\n */\n parentKeys: string[];\n /**\n * Full Firestore document path pattern including trailing `/{documentKey}`\n * (e.g. `\"prevention/prev_rules/prev_workshops/{workshopId}/prev_events/{docId}\"`),\n * or `null` when `isGroup: true` and `rawPath` is a bare single-segment\n * collection name without a path template.\n */\n documentPathTemplate: string | null;\n /** `true` when `rawPath` contains `/` or `{...}` template placeholders */\n hasTemplate: boolean;\n}\n\n/**\n * Parse a repository `path` into collection ID, ordered dynamic parent keys,\n * and full document path template.\n *\n * Supports:\n * - Bare collection names: `\"users\"`, `\"res_events\"`\n * - Odd-segment collection templates: `\"residences/{residenceId}/res_events\"`,\n * `\"prevention/prev_rules/prev_workshops/{workshopId}/prev_events\"`\n * - Even-segment document templates: `\"residences/{residenceId}/res_events/{docId}\"`\n */\nexport function parsePathTemplate(\n rawPath: string,\n documentKey = \"docId\",\n isGroup = false,\n): ParsedPathTemplate {\n if (typeof rawPath !== \"string\" || !rawPath.trim()) {\n return {\n rawPath: rawPath ?? \"\",\n collectionId: \"\",\n collectionPath: \"\",\n parentKeys: [],\n documentPathTemplate: null,\n hasTemplate: false,\n };\n }\n\n const segments = rawPath\n .split(\"/\")\n .map((s) => s.trim())\n .filter(Boolean);\n\n if (segments.length === 0) {\n return {\n rawPath,\n collectionId: rawPath,\n collectionPath: rawPath,\n parentKeys: [],\n documentPathTemplate: null,\n hasTemplate: false,\n };\n }\n\n if (segments.length === 1) {\n const seg = segments[0]!;\n return {\n rawPath,\n collectionId: seg,\n collectionPath: seg,\n parentKeys: [],\n documentPathTemplate: isGroup ? null : `${seg}/{${documentKey}}`,\n hasTemplate: rawPath.includes(\"{\") && rawPath.includes(\"}\"),\n };\n }\n\n // Multi-segment path:\n // - Even number of segments (col/doc/col/{docId}) -> last segment is the document ID placeholder\n // - Odd number of segments (col/doc/col) -> last segment is the target collection\n const isEvenSegments = segments.length % 2 === 0;\n const collectionSegments = isEvenSegments ? segments.slice(0, -1) : segments;\n const collectionId = collectionSegments[collectionSegments.length - 1]!;\n const collectionPath = collectionSegments.join(\"/\");\n\n // Parent segments are all segments before the target collection segment\n const parentSegments = collectionSegments.slice(0, -1);\n const parentKeys = parentSegments\n .map(extractSegmentParam)\n .filter((p): p is string => p !== null);\n\n const documentPathTemplate = isEvenSegments\n ? segments.join(\"/\")\n : `${collectionPath}/{${documentKey}}`;\n\n return {\n rawPath,\n collectionId,\n collectionPath,\n parentKeys,\n documentPathTemplate,\n hasTemplate: true,\n };\n}\n\n/**\n * Build a Firestore `DocumentReference` from a `documentPathTemplate`\n * (e.g. `\"prevention/prev_rules/prev_workshops/{workshopId}/prev_events/{docId}\"`)\n * and positional dynamic arguments (`[workshopId, docId]`).\n *\n * Static transit segments (like `\"prev_rules\"`) are preserved automatically.\n */\nexport function buildDocumentRefFromTemplate(\n db: Firestore,\n documentPathTemplate: string,\n args: unknown[],\n): DocumentReference {\n const segments = documentPathTemplate\n .split(\"/\")\n .map((s) => s.trim())\n .filter(Boolean);\n\n let argIndex = 0;\n const resolvedSegments: string[] = [];\n\n for (const seg of segments) {\n const paramName = extractSegmentParam(seg);\n if (paramName !== null) {\n const val = args[argIndex++];\n if (typeof val !== \"string\" || val.trim() === \"\") {\n throw new Error(\n `Missing or empty path parameter \"${paramName}\" when resolving document reference for \"${documentPathTemplate}\".`,\n );\n }\n resolvedSegments.push(val);\n } else {\n resolvedSegments.push(seg);\n }\n }\n\n const anyDb = db as any;\n\n // Try walking db.collection(seg0).doc(seg1).collection(seg2).doc(seg3)...\n // so mocks that spy on .collection().doc() work identically to hand-written refCb.\n if (typeof anyDb?.collection === \"function\" && resolvedSegments.length >= 2) {\n let cur: any = anyDb;\n let walked = true;\n for (let i = 0; i < resolvedSegments.length; i += 2) {\n const colName = resolvedSegments[i]!;\n const docId = resolvedSegments[i + 1]!;\n if (typeof cur?.collection !== \"function\") {\n walked = false;\n break;\n }\n const colRef = cur.collection(colName);\n if (typeof colRef?.doc !== \"function\") {\n walked = false;\n break;\n }\n cur = colRef.doc(docId);\n }\n if (walked && cur && cur !== anyDb) {\n return cur as DocumentReference;\n }\n }\n\n // Fallback: db.doc(fullPath)\n const fullPath = resolvedSegments.join(\"/\");\n if (typeof anyDb?.doc === \"function\") {\n return anyDb.doc(fullPath) as DocumentReference;\n }\n\n // Last-resort fallback for minimal single-collection test mocks\n if (typeof anyDb?.collection === \"function\" && resolvedSegments.length >= 2) {\n const colPath = resolvedSegments.slice(0, -1).join(\"/\");\n const docId = resolvedSegments[resolvedSegments.length - 1]!;\n const colRef = anyDb.collection(colPath);\n if (typeof colRef?.doc === \"function\") {\n return colRef.doc(docId) as DocumentReference;\n }\n return colRef as DocumentReference;\n }\n\n throw new Error(\n `Cannot resolve DocumentReference for \"${fullPath}\": Firestore instance does not expose .collection() or .doc().`,\n );\n}\n\nexport interface ExtractPathArgsOptions {\n pathKey?: string | null;\n documentKey?: string | null;\n parentKeys?: string[];\n documentPathTemplate?: string | null;\n isGroup?: boolean;\n}\n\n/**\n * Extract the dynamic document reference arguments from a stored document.\n *\n * Unlike naive odd-segment splitting, this helper skips fixed transit document\n * segments (such as `\"prev_rules\"` in `\"prevention/prev_rules/prev_workshops/w1/prev_events/e1\"`)\n * by matching against `documentPathTemplate` or `parentKeys`.\n */\nexport function extractPathArgsFromDoc(\n doc: Record<string, unknown> | null | undefined,\n options: ExtractPathArgsOptions = {},\n): string[] | undefined {\n if (!doc || typeof doc !== \"object\") return undefined;\n\n const {\n pathKey,\n documentKey = \"docId\",\n parentKeys,\n documentPathTemplate,\n isGroup,\n } = options;\n\n const fullPath =\n pathKey && typeof doc[pathKey] === \"string\" && doc[pathKey]\n ? (doc[pathKey] as string)\n : undefined;\n\n // 1. If we have both fullPath and a matching documentPathTemplate, extract only `{param}` positions\n if (fullPath && documentPathTemplate) {\n const pathSegments = fullPath.split(\"/\").filter(Boolean);\n const tplSegments = documentPathTemplate.split(\"/\").filter(Boolean);\n if (pathSegments.length === tplSegments.length) {\n const extracted: string[] = [];\n for (let i = 0; i < tplSegments.length; i++) {\n if (extractSegmentParam(tplSegments[i]!) !== null) {\n extracted.push(pathSegments[i]!);\n }\n }\n if (extracted.length > 0) {\n return extracted;\n }\n }\n }\n\n // 2. If parentKeys are known and non-empty\n if (parentKeys && parentKeys.length > 0) {\n const expectedCount = parentKeys.length + 1;\n\n if (fullPath) {\n const segments = fullPath.split(\"/\").filter(Boolean);\n const oddSegments: string[] = [];\n for (let i = 1; i < segments.length; i += 2) {\n oddSegments.push(segments[i]!);\n }\n if (oddSegments.length >= expectedCount) {\n return oddSegments.slice(oddSegments.length - expectedCount);\n }\n }\n\n // Fallback: extract parentKeys + documentKey directly from document fields\n const docIdVal = documentKey ? doc[documentKey] : undefined;\n if (typeof docIdVal === \"string\" && docIdVal.trim() !== \"\") {\n const parentVals: string[] = [];\n let allPresent = true;\n for (const pk of parentKeys) {\n const v = doc[pk];\n if (typeof v === \"string\" && v.trim() !== \"\") {\n parentVals.push(v);\n } else {\n allPresent = false;\n break;\n }\n }\n if (allPresent) {\n return [...parentVals, docIdVal];\n }\n }\n }\n\n // 3. Fallback when fullPath is present\n if (fullPath) {\n const segments = fullPath.split(\"/\").filter(Boolean);\n const oddSegments: string[] = [];\n for (let i = 1; i < segments.length; i += 2) {\n oddSegments.push(segments[i]!);\n }\n if (oddSegments.length > 0) {\n // For non-group repos without parentKeys (e.g. under a fixed transit doc), only the last docId is dynamic\n if (!isGroup && (!parentKeys || parentKeys.length === 0)) {\n return [oddSegments[oddSegments.length - 1]!];\n }\n return oddSegments;\n }\n }\n\n return undefined;\n}\n","/**\n * Zod introspection utilities — compatible with Zod 4.\n *\n * Centralizes all internal `_zod.def` accesses so the rest of the codebase\n * never touches Zod internals directly. If a future Zod version changes\n * the internal layout, only this file needs updating.\n */\n\nimport type { z } from \"zod\";\n\n// ---------------------------------------------------------------------------\n// Type-name resolution\n// ---------------------------------------------------------------------------\n\n/**\n * Canonical Zod type names used in the codebase.\n * These match the **Zod 3** naming convention (e.g. \"ZodString\") that the\n * form-gen / admin handlers already rely on, so we don't need to rewrite\n * every `case \"ZodString\":` branch.\n */\ntype ZodTypeName =\n | \"ZodString\"\n | \"ZodNumber\"\n | \"ZodBigInt\"\n | \"ZodBoolean\"\n | \"ZodDate\"\n | \"ZodEnum\"\n | \"ZodNativeEnum\"\n | \"ZodLiteral\"\n | \"ZodObject\"\n | \"ZodArray\"\n | \"ZodOptional\"\n | \"ZodNullable\"\n | \"ZodDefault\"\n | \"ZodCoerce\"\n | \"ZodUnion\"\n | \"ZodUndefined\"\n | \"ZodUnknown\"\n | \"ZodAny\"\n | \"ZodRecord\"\n | string;\n\n/**\n * Map from Zod 4 `_zod.def.type` (lowercase) → Zod 3 `_def.typeName` format.\n * Any key not in this map is capitalised as `Zod${Capitalised}`.\n */\nconst TYPE_MAP: Record<string, ZodTypeName> = {\n string: \"ZodString\",\n number: \"ZodNumber\",\n bigint: \"ZodBigInt\",\n boolean: \"ZodBoolean\",\n date: \"ZodDate\",\n enum: \"ZodEnum\",\n nativeEnum: \"ZodNativeEnum\",\n literal: \"ZodLiteral\",\n object: \"ZodObject\",\n array: \"ZodArray\",\n optional: \"ZodOptional\",\n nullable: \"ZodNullable\",\n default: \"ZodDefault\",\n coerce: \"ZodCoerce\",\n union: \"ZodUnion\",\n undefined: \"ZodUndefined\",\n unknown: \"ZodUnknown\",\n any: \"ZodAny\",\n record: \"ZodRecord\",\n};\n\n/**\n * Get the canonical type name of a Zod schema.\n *\n * Works with both Zod 3 (`_def.typeName`) and Zod 4 (`_zod.def.type`).\n * Returns names in Zod-3 style (\"ZodString\", \"ZodObject\" …) for\n * backward-compatible switch/case usage.\n */\nexport function getTypeName(schema: z.ZodType): ZodTypeName {\n const s = schema as any;\n\n // Zod 4 path\n const v4Type: string | undefined = s._zod?.def?.type;\n if (v4Type)\n return (\n TYPE_MAP[v4Type] ??\n `Zod${v4Type.charAt(0).toUpperCase()}${v4Type.slice(1)}`\n );\n\n // Zod 3 fallback\n const v3Type: string | undefined = s._def?.typeName;\n if (v3Type) return v3Type;\n\n return \"\";\n}\n\n// ---------------------------------------------------------------------------\n// Unwrapping wrappers (Optional / Nullable / Default)\n// ---------------------------------------------------------------------------\n\n/**\n * Get the inner schema from a wrapper type (Optional / Nullable / Default).\n */\nexport function getInnerType(schema: z.ZodType): z.ZodType | undefined {\n const s = schema as any;\n\n // Zod 4: _zod.def.innerType\n if (s._zod?.def?.innerType) return s._zod.def.innerType;\n\n // Zod 3 compat: _def.innerType\n if (s._def?.innerType) return s._def.innerType;\n\n return undefined;\n}\n\n/**\n * Get the **source** schema of an effect / transform / pipe wrapper, i.e. the\n * schema describing what the user actually provides:\n * - Zod 3 `ZodEffects` (`.transform()` / `.refine()` / `.preprocess()`) →\n * `_def.schema`;\n * - Zod 4 `ZodPipe` (the shape `.transform()` compiles to) → the `in` side.\n *\n * Lets form/field introspection see through `z.string().transform(...)` (which\n * should still render as a text input) instead of falling back to a JSON\n * textarea. Returns `undefined` when the schema is not an effect/pipe.\n */\nexport function getEffectInnerType(schema: z.ZodType): z.ZodType | undefined {\n const s = schema as any;\n\n // Zod 4: pipe — prefer the input side (what the user types).\n const pipeIn = s._zod?.def?.in;\n if (pipeIn) return pipeIn as z.ZodType;\n\n // Zod 3: ZodEffects wraps the base schema under `_def.schema`.\n if (s._def?.schema) return s._def.schema as z.ZodType;\n\n return undefined;\n}\n\n/**\n * Get the **element schema** from a `ZodArray`.\n * Returns `undefined` for non-array schemas.\n */\nexport function getArrayElementType(\n schema: z.ZodType,\n): z.ZodType | undefined {\n const s = schema as any;\n\n // Zod 4: _zod.def.element\n if (s._zod?.def?.element) return s._zod.def.element;\n\n // Zod 3: _def.type (ZodArray stores element schema in _def.type)\n if (s._def?.type) return s._def.type;\n\n return undefined;\n}\n\n/**\n * Returns the list of **required** (non-optional) top-level keys of a ZodObject.\n * A key is required when its schema is NOT wrapped in ZodOptional.\n * ZodNullable / ZodDefault fields are still considered required — they must be present.\n */\nexport function getRequiredSchemaKeys(schema: z.ZodObject<any>): string[] {\n const required: string[] = [];\n for (const [key, fieldSchema] of Object.entries(schema.shape)) {\n const typeName = getTypeName(fieldSchema as z.ZodType);\n if (typeName !== \"ZodOptional\") {\n required.push(key);\n }\n }\n return required;\n}\n\n/**\n * Get the default value for a ZodDefault schema.\n * In Zod 3 this was `_def.defaultValue()` (function). In Zod 4 it's a direct value.\n */\nexport function getDefaultValue(schema: z.ZodType): unknown {\n const s = schema as any;\n\n // Zod 4\n if (s._zod?.def?.defaultValue !== undefined) return s._zod.def.defaultValue;\n\n // Zod 3 compat\n const v = s._def?.defaultValue;\n if (typeof v === \"function\") return v();\n return v;\n}\n\n// ---------------------------------------------------------------------------\n// Object shape\n// ---------------------------------------------------------------------------\n\n/**\n * Get the shape of a ZodObject schema (Record<string, ZodType>).\n * Handles both Zod 3 (`_def.shape()` function) and Zod 4 (`.shape` property).\n */\nexport function getShape(schema: z.ZodType): Record<string, z.ZodType> {\n const s = schema as any;\n\n // Direct `.shape` property (Zod 3 & 4 for ZodObject instances)\n if (s.shape && typeof s.shape === \"object\") return s.shape;\n\n // Zod 4: _zod.def.shape\n if (s._zod?.def?.shape && typeof s._zod.def.shape === \"object\")\n return s._zod.def.shape;\n\n // Zod 3 fallback: _def.shape() or _def.shape\n if (s._def?.shape) {\n return typeof s._def.shape === \"function\" ? s._def.shape() : s._def.shape;\n }\n\n return {};\n}\n\n// ---------------------------------------------------------------------------\n// Enum / Literal values\n// ---------------------------------------------------------------------------\n\n/**\n * Get the values of a ZodEnum schema as a string[].\n */\nexport function getEnumValues(schema: z.ZodType): string[] {\n const s = schema as any;\n\n // Zod 4: `.options` or `_zod.def.entries`\n if (Array.isArray(s.options)) return s.options;\n if (s._zod?.def?.entries)\n return Object.values(s._zod.def.entries) as string[];\n\n // Zod 3: `_def.values`\n if (Array.isArray(s._def?.values)) return s._def.values;\n\n return [];\n}\n\n/**\n * Get the value object of a ZodNativeEnum schema.\n */\nexport function getNativeEnumValues(\n schema: z.ZodType,\n): Record<string, unknown> {\n const s = schema as any;\n\n // Zod 4: `_zod.def.entries` or `.enum`\n if (s._zod?.def?.entries) return s._zod.def.entries;\n if (s.enum && typeof s.enum === \"object\") return s.enum;\n\n // Zod 3: `_def.values`\n if (s._def?.values && typeof s._def.values === \"object\") return s._def.values;\n\n return {};\n}\n\n/**\n * Get the value of a ZodLiteral schema.\n */\nexport function getLiteralValue(schema: z.ZodType): unknown {\n const s = schema as any;\n\n // Zod 4: `_zod.def.values[0]`\n if (Array.isArray(s._zod?.def?.values)) return s._zod.def.values[0];\n\n // Zod 3: `_def.value`\n return s._def?.value;\n}\n\n/**\n * Get the member schemas of a ZodUnion (or ZodDiscriminatedUnion).\n * Works with both Zod 3 (`_def.options`) and Zod 4 (`.options` /\n * `_zod.def.options`). Returns an empty array when none can be resolved.\n */\nexport function getUnionOptions(schema: z.ZodType): z.ZodType[] {\n const s = schema as any;\n\n // Zod 4\n if (Array.isArray(s.options)) return s.options as z.ZodType[];\n if (Array.isArray(s._zod?.def?.options))\n return s._zod.def.options as z.ZodType[];\n\n // Zod 3\n if (Array.isArray(s._def?.options)) return s._def.options as z.ZodType[];\n\n return [];\n}\n\n// ---------------------------------------------------------------------------\n// String checks\n// ---------------------------------------------------------------------------\n\n/**\n * Get relevant \"check kinds\" from a ZodString schema.\n * Returns an array of kind strings: \"email\", \"url\", etc.\n */\nexport function getStringChecks(schema: z.ZodType): string[] {\n const s = schema as any;\n const kinds: string[] = [];\n\n // Zod 4: checks with `.format` field\n const v4Checks: any[] | undefined = s._zod?.def?.checks;\n if (Array.isArray(v4Checks)) {\n for (const c of v4Checks) {\n if (c.format) kinds.push(c.format);\n }\n if (kinds.length > 0) return kinds;\n }\n\n // Zod 3: _def.checks with `.kind` field\n const v3Checks: any[] | undefined = s._def?.checks;\n if (Array.isArray(v3Checks)) {\n for (const c of v3Checks) {\n if (c.kind) kinds.push(c.kind);\n }\n }\n\n return kinds;\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 { parsePathTemplate } from \"../../shared/path-template\";\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 collection segment) from a Firestore path.\n * e.g. \"posts/{postId}/comments\" → \"comments\"\n * e.g. \"posts/{postId}/comments/{docId}\" → \"comments\"\n */\nexport function collectionIdFromPath(path: string): string {\n return parsePathTemplate(path).collectionId || 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 * Diff helper for the history module.\n *\n * Computes a top-level shallow diff between two snapshots of the same\n * document. Returns an empty changes object when nothing relevant changed.\n *\n * Meta fields, system keys (docId / pathKey / createdKey / updatedKey) and\n * any field listed in `exclude` are filtered out. When `include` is set, only\n * the listed fields are considered.\n */\n\nimport { Timestamp } from \"firebase-admin/firestore\";\nimport type {\n HistoryFieldChange,\n HistoryValueType,\n} from \"./types\";\n\nexport interface DiffOptions {\n include?: string[];\n exclude?: string[];\n /** Field names that hold meta info (auto-excluded from diff). */\n metaFields?: string[];\n /** System keys auto-excluded (docId, pathKey, createdKey, updatedKey). */\n systemKeys?: string[];\n}\n\nexport function valueType(v: unknown): HistoryValueType {\n if (v === null) return \"null\";\n if (v === undefined) return \"undefined\";\n if (v instanceof Timestamp) return \"timestamp\";\n if (v instanceof Date) return \"date\";\n if (Array.isArray(v)) return \"array\";\n const t = typeof v;\n if (t === \"string\" || t === \"number\" || t === \"boolean\") return t;\n return \"object\";\n}\n\n/**\n * Structural equality good enough for change detection.\n *\n * Order-insensitive for object keys (Firestore does not guarantee key order\n * after partial updates / re-fetch, so `JSON.stringify` comparison produced\n * phantom diffs). Cycle-safe via a `seen` map, and never throws — see #14.\n */\nexport function valuesEqual(\n a: unknown,\n b: unknown,\n seen: WeakMap<object, unknown> = new WeakMap(),\n): boolean {\n if (a === b) return true;\n if (a === null || b === null || a === undefined || b === undefined) {\n return a === b;\n }\n\n if (a instanceof Timestamp && b instanceof Timestamp) {\n return a.isEqual(b);\n }\n if (a instanceof Date && b instanceof Date) {\n return a.getTime() === b.getTime();\n }\n\n if (Array.isArray(a) || Array.isArray(b)) {\n if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) {\n return false;\n }\n if (seen.get(a) === b) return true;\n seen.set(a, b);\n for (let i = 0; i < a.length; i++) {\n if (!valuesEqual(a[i], b[i], seen)) return false;\n }\n return true;\n }\n\n if (typeof a === \"object\" && typeof b === \"object\") {\n // A plain object is never equal to a special boxed value (one is a\n // Date/Timestamp, the other a plain object).\n if (\n a instanceof Date ||\n b instanceof Date ||\n a instanceof Timestamp ||\n b instanceof Timestamp\n ) {\n return false;\n }\n if (seen.get(a) === b) return true;\n seen.set(a, b);\n const ka = Object.keys(a as Record<string, unknown>);\n const kb = Object.keys(b as Record<string, unknown>);\n if (ka.length !== kb.length) return false;\n for (const k of ka) {\n if (!Object.prototype.hasOwnProperty.call(b, k)) return false;\n if (\n !valuesEqual(\n (a as Record<string, unknown>)[k],\n (b as Record<string, unknown>)[k],\n seen,\n )\n ) {\n return false;\n }\n }\n return true;\n }\n\n return false;\n}\n\n/**\n * Compute a flat top-level diff. Nested objects are compared as a whole — they\n * appear in the diff if changed but are NOT decomposed key by key.\n */\nexport function computeDiff<T extends Record<string, unknown>>(\n before: T | null | undefined,\n after: T | null | undefined,\n opts: DiffOptions = {},\n): Record<string, HistoryFieldChange> {\n const excludeSet = new Set<string>([\n ...(opts.exclude ?? []),\n ...(opts.metaFields ?? []),\n ...(opts.systemKeys ?? []),\n ]);\n const includeSet = opts.include ? new Set<string>(opts.include) : null;\n\n const beforeObj = (before ?? {}) as Record<string, unknown>;\n const afterObj = (after ?? {}) as Record<string, unknown>;\n\n const keys = new Set<string>([\n ...Object.keys(beforeObj),\n ...Object.keys(afterObj),\n ]);\n\n const changes: Record<string, HistoryFieldChange> = {};\n for (const key of keys) {\n if (excludeSet.has(key)) continue;\n if (includeSet && !includeSet.has(key)) continue;\n\n const oldValue = beforeObj[key];\n const newValue = afterObj[key];\n if (valuesEqual(oldValue, newValue)) continue;\n\n changes[key] = {\n oldValue: oldValue === undefined ? null : oldValue,\n newValue: newValue === undefined ? null : newValue,\n type: { old: valueType(oldValue), new: valueType(newValue) },\n };\n }\n\n return changes;\n}\n","/**\n * @module servers/crud/rules\n *\n * Rules and diff engine for CRUD authorization and field-level before rules.\n */\nimport { valuesEqual } from \"../../history/diff\";\nimport type { AuthUser } from \"../auth\";\nimport type {\n CrudUpdateRuleContext,\n DeepDiffReturn,\n Rule,\n RulesMap,\n} from \"./types\";\n\n/**\n * Computes a typed diff between the existing document (`before`) and the incoming partial changes (`changesInput`).\n * Only fields whose values have actually changed (via structural equality) are included in `changes`.\n */\nexport function computeDeepDiff<T extends Record<string, unknown>>(\n before: T,\n changesInput: Partial<T>,\n): DeepDiffReturn<T> {\n const beforeObj = before || ({} as T);\n const changes: Partial<T> = {};\n const after: T = { ...beforeObj };\n\n for (const [key, val] of Object.entries(changesInput || {})) {\n const oldVal = (beforeObj as any)[key];\n if (!valuesEqual(oldVal, val)) {\n (changes as any)[key] = val;\n (after as any)[key] = val;\n }\n }\n\n return {\n before: beforeObj,\n after,\n changes,\n };\n}\n\n/**\n * Helper to define field-by-field before-rules with strong typing.\n */\nexport function createRules<T>(\n rules: RulesMap<T>,\n): RulesMap<T> {\n return rules;\n}\n\n/**\n * Executes a map of field rules against a computed diff.\n * Evaluates rules only for the keys that changed in `diff.changes`.\n * Returns `{ allowed: true }` if all rules pass, or `{ allowed: false, reason: rule.description }` on the first failure.\n */\nexport async function applyRules<T>(\n diff: DeepDiffReturn<T>,\n rulesMap: RulesMap<T>,\n user?: AuthUser,\n): Promise<{ allowed: boolean; reason?: string }> {\n const changes = diff.changes || {};\n for (const key of Object.keys(changes) as (keyof T)[]) {\n const rules = rulesMap[key];\n if (rules && rules.length > 0) {\n for (const rule of rules) {\n const res = await rule.rule({\n diff,\n key,\n user,\n authenticatedUser: user,\n });\n if (res === false) {\n return { allowed: false, reason: rule.description };\n }\n }\n }\n }\n return { allowed: true };\n}\n\n/**\n * Wraps a rules map into a standard `rules.update` handler for `createCrudServer`.\n */\nexport function createBeforeRules<T>(\n rulesMap: RulesMap<T>,\n): (ctx: CrudUpdateRuleContext<T>) => Promise<{ allowed: boolean; reason?: string }> {\n return async (ctx: CrudUpdateRuleContext<T>) => {\n return applyRules(ctx.diff, rulesMap, ctx.user);\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 { z } from \"zod\";\nimport {\n coerceToDate,\n getDateHandling,\n maybeNormalize,\n} from \"../../shared/date-config\";\nimport {\n extractPathArgsFromDoc,\n generateFirestoreId,\n} from \"../../shared/path-template\";\nimport { getArrayElementType } from \"../../shared/zod-compat\";\nimport { toQueryError, type QueryErrorContext } from \"../admin/index-url\";\nimport { computeDeepDiff } from \"./rules\";\nimport type {\n ApiResponse,\n CrudHookErrorCallback,\n CrudHookErrorContext,\n CrudRepoEntry,\n CrudRepoRegistry,\n DeepDiffReturn,\n IndexErrorCallback,\n ListResponseData,\n QueryRequestBody,\n RuleResult,\n} from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Pagination validation\n// ---------------------------------------------------------------------------\n\nconst MAX_CRUD_PAGE_SIZE = 1000;\n\nfunction parseCrudPageSize(\n raw: unknown,\n defaultPageSize: number,\n): { success: true; value: number } | { success: false; error: string } {\n if (raw === undefined) {\n return {\n success: true,\n value: Math.min(Math.max(1, defaultPageSize), MAX_CRUD_PAGE_SIZE),\n };\n }\n const num =\n typeof raw === \"number\"\n ? raw\n : typeof raw === \"string\" && raw.trim() !== \"\"\n ? Number(raw)\n : NaN;\n if (!Number.isInteger(num) || num <= 0 || num > MAX_CRUD_PAGE_SIZE) {\n return {\n success: false,\n error: `Invalid pageSize: must be an integer between 1 and ${MAX_CRUD_PAGE_SIZE}`,\n };\n }\n return { success: true, value: num };\n}\n\n// ---------------------------------------------------------------------------\n// Response helpers\n// ---------------------------------------------------------------------------\n\nfunction sendJson<T>(c: any, data: ApiResponse<T>, status = 200) {\n const payload = maybeNormalize(data);\n return c.json(payload, status as any);\n}\n\nfunction sendSuccess<T>(\n c: any,\n data: T,\n meta?: ApiResponse[\"meta\"],\n status = 200,\n) {\n return sendJson(c, { success: true, data, meta }, status);\n}\n\nfunction sendError(c: any, error: string, status = 400) {\n return sendJson(c, { success: false, error }, status);\n}\n\n/**\n * Send a structured error response. When the underlying Firestore error is a\n * missing-index (`FAILED_PRECONDITION` / code 9), include `errorType: \"index\"`\n * and an `indexUrl` pointing to the Firebase Console index-creation wizard —\n * crucial for collection-group queries where the SDK omits the link.\n */\nasync function sendQueryError(\n c: any,\n err: unknown,\n ctx: QueryErrorContext & { repoName?: string },\n fallbackMessage: string,\n verbose: boolean,\n onIndexError?: IndexErrorCallback,\n) {\n const qe = toQueryError(err, ctx);\n const isIndex = qe.type === \"index\";\n const status = isIndex ? 424 : 500;\n const message = isIndex\n ? qe.message\n : verbose && err instanceof Error\n ? err.message\n : fallbackMessage;\n const payload: ApiResponse = { success: false, error: message };\n if (isIndex) {\n payload.errorType = \"index\";\n if (qe.indexUrl) {\n payload.indexUrl = qe.indexUrl;\n if (onIndexError) {\n try {\n const res = onIndexError({\n indexUrl: qe.indexUrl,\n repoName: ctx.repoName ?? \"\",\n path: ctx.path,\n isGroup: ctx.isGroup,\n filters: ctx.filters,\n sort: ctx.sort,\n error: err,\n c,\n });\n if (res instanceof Promise) {\n await res;\n }\n } catch (cbErr) {\n if (verbose) {\n // eslint-disable-next-line no-console\n console.error(\"[crudServer] Error in indexesError callback:\", cbErr);\n }\n }\n }\n }\n }\n return sendJson(c, payload, status);\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/** Helper to unwrap Zod modifiers (optional, nullable, default, catch, effects, etc.) */\nfunction unwrapZodType(zodType: any): any {\n let cur = zodType;\n while (cur) {\n const def = cur._zod?.def ?? cur._def;\n if (!def) break;\n if (def.innerType) {\n cur = def.innerType;\n } else if (def.schema) {\n cur = def.schema;\n } else if (\n def.type === \"optional\" ||\n def.type === \"nullable\" ||\n def.type === \"default\" ||\n def.type === \"catch\" ||\n def.type === \"effects\"\n ) {\n cur = def.innerType ?? def.schema;\n } else {\n break;\n }\n }\n return cur;\n}\n\n/** Resolve a dot-notation path (e.g. \"address.city\") from a Zod schema */\nfunction resolveFieldPathSchema(entrySchema: any, path: string): any {\n const parts = path.split(\".\");\n let cur = unwrapZodType(entrySchema);\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n if (!part) continue;\n const shape: Record<string, any> | undefined = (cur as any)?.shape;\n if (!shape || !shape[part]) {\n return undefined;\n }\n const rawSub = shape[part];\n if (i === parts.length - 1) {\n return rawSub;\n }\n cur = unwrapZodType(rawSub);\n }\n return cur;\n}\n\n/** Recursively make Zod objects deep-partial for PATCH updates */\nfunction makeDeepPartial(s: z.ZodType): z.ZodType {\n const def = (s as any)?._zod?.def ?? (s as any)?._def;\n const typeName = def?.typeName ?? def?.type;\n\n if (typeName === \"ZodObject\" || typeName === \"object\") {\n const shape = (s as z.ZodObject<any>).shape;\n const newShape: Record<string, z.ZodType> = {};\n for (const [k, v] of Object.entries(shape)) {\n newShape[k] = makeDeepPartial(v as z.ZodType);\n }\n return z.object(newShape).partial();\n }\n\n if (typeName === \"ZodOptional\" || typeName === \"optional\") {\n const inner = def.innerType as z.ZodType | undefined;\n if (!inner) return s;\n const nextInner = makeDeepPartial(inner);\n return nextInner === inner ? s : nextInner.optional();\n }\n\n if (typeName === \"ZodNullable\" || typeName === \"nullable\") {\n const inner = def.innerType as z.ZodType | undefined;\n if (!inner) return s;\n const nextInner = makeDeepPartial(inner);\n return nextInner === inner ? s : nextInner.nullable();\n }\n\n if (typeName === \"ZodDefault\" || typeName === \"default\") {\n const inner = def.innerType as z.ZodType | undefined;\n if (!inner) return s;\n return makeDeepPartial(inner).optional();\n }\n\n if (typeName === \"ZodUnion\" || typeName === \"union\") {\n const options = def.options as z.ZodType[] | undefined;\n if (!options || options.length < 2) return s;\n const nextOptions = options.map((opt) => makeDeepPartial(opt));\n const changed = nextOptions.some((opt, i) => opt !== options[i]);\n return changed ? z.union(nextOptions as any) : s;\n }\n\n return s;\n}\n\n/**\n * Validate data against schema and return parsed result or error.\n * Supports dot-notation keys (e.g. \"address.city\") and deep partial nested objects.\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 if (typeof data !== \"object\" || data === null || Array.isArray(data)) {\n return { success: false, error: \"Data payload must be an object\" };\n }\n\n try {\n const dataObj = data as Record<string, unknown>;\n const resultData: Record<string, unknown> = {};\n const normalEntries: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(dataObj)) {\n if (key.includes(\".\")) {\n // Dot notation key (e.g. \"address.city\")\n const topLevel = key.split(\".\")[0]!;\n if (systemKeys.includes(key) || systemKeys.includes(topLevel)) {\n continue;\n }\n if (fields && fields.length > 0) {\n if (!fields.includes(key) && !fields.includes(topLevel)) {\n return {\n success: false,\n error: `Field '${key}' is not allowed for this operation`,\n };\n }\n }\n const fieldSchema = resolveFieldPathSchema(schema, key);\n if (!fieldSchema) {\n return {\n success: false,\n error: `Field '${key}' does not exist in schema`,\n };\n }\n const effectiveFieldSchema = partial\n ? makeDeepPartial(fieldSchema)\n : fieldSchema;\n const wrappedSchema =\n getDateHandling() === \"normalize\"\n ? wrapDateSchemas(effectiveFieldSchema)\n : effectiveFieldSchema;\n const parsedValue = wrappedSchema.parse(value);\n resultData[key] = parsedValue;\n } else {\n normalEntries[key] = value;\n }\n }\n\n if (\n Object.keys(normalEntries).length > 0 ||\n Object.keys(resultData).length === 0\n ) {\n const targetSchema = pickSchemaFields(schema, fields, systemKeys);\n const partialSchema = partial\n ? (makeDeepPartial(targetSchema) as z.ZodObject<any>)\n : targetSchema;\n const finalSchema =\n getDateHandling() === \"normalize\"\n ? (wrapDateSchemas(partialSchema) as z.ZodObject<any>)\n : partialSchema;\n const parsedNormal = finalSchema.parse(normalEntries);\n Object.assign(resultData, parsedNormal);\n }\n\n return { success: true, data: resultData };\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\nexport type WhereOp =\n | \"==\"\n | \"!=\"\n | \"<\"\n | \"<=\"\n | \">\"\n | \">=\"\n | \"in\"\n | \"not-in\"\n | \"array-contains\"\n | \"array-contains-any\";\n\nconst OP_MAP: Record<string, WhereOp> = {\n eq: \"==\",\n \"==\": \"==\",\n ne: \"!=\",\n \"!=\": \"!=\",\n lt: \"<\",\n \"<\": \"<\",\n lte: \"<=\",\n \"<=\": \"<=\",\n gt: \">\",\n \">\": \">\",\n gte: \">=\",\n \">=\": \">=\",\n in: \"in\",\n nin: \"not-in\",\n \"not-in\": \"not-in\",\n not_in: \"not-in\",\n contains: \"array-contains\",\n \"array-contains\": \"array-contains\",\n array_contains: \"array-contains\",\n arrayContains: \"array-contains\",\n containsAny: \"array-contains-any\",\n \"array-contains-any\": \"array-contains-any\",\n array_contains_any: \"array-contains-any\",\n arrayContainsAny: \"array-contains-any\",\n};\n\n/**\n * Normalize any operator string (e.g. contains, array-contains, eq, nin) to a canonical WhereOp.\n */\nexport function normalizeWhereOp(op: string): WhereOp {\n return OP_MAP[op] ?? (op as WhereOp);\n}\n\nfunction isValidOp(op: string): boolean {\n return op in OP_MAP;\n}\n\ninterface ParsedFilter {\n field: string;\n op: WhereOp;\n value: unknown;\n}\n\n/**\n * Safely parse a filter value using the entity's schema field definition (if present).\n * If safeParse succeeds, returns the parsed data.\n * If safeParse fails on a single value but value is an Array, attempts to safeParse each item.\n */\nexport function parseFieldValue(\n entrySchema: unknown,\n field: string,\n val: unknown,\n op?: WhereOp | string,\n): { success: true; data: unknown } | { success: false; error: string } {\n const fieldSchema = resolveFieldPathSchema(entrySchema, field);\n if (!fieldSchema || typeof fieldSchema.safeParse !== \"function\") {\n return { success: true, data: val };\n }\n\n const normalizedOp = op ? normalizeWhereOp(op) : undefined;\n const unwrapped = unwrapZodType(fieldSchema);\n const elemSchema = getArrayElementType(unwrapped);\n\n // If the operator is array-contains, validate against the element schema\n if (normalizedOp === \"array-contains\") {\n const targetSchema = elemSchema ?? fieldSchema;\n if (typeof targetSchema.safeParse === \"function\") {\n const parsed = targetSchema.safeParse(val);\n if (parsed.success) {\n return { success: true, data: parsed.data };\n }\n const messages = parsed.error.issues\n .map((e: any) => e.message)\n .join(\", \");\n return { success: false, error: messages };\n }\n return { success: true, data: val };\n }\n\n // If the operator is array-contains-any, validate each element\n if (normalizedOp === \"array-contains-any\") {\n if (!Array.isArray(val)) {\n return {\n success: false,\n error: \"Expected array value for array-contains-any\",\n };\n }\n const targetSchema = elemSchema ?? fieldSchema;\n const parsedArray: unknown[] = [];\n for (const item of val) {\n if (typeof targetSchema.safeParse === \"function\") {\n const itemParsed = targetSchema.safeParse(item);\n if (itemParsed.success) {\n parsedArray.push(itemParsed.data);\n } else {\n const errorMessage = itemParsed.error.issues\n .map((e: any) => e.message)\n .join(\", \");\n return { success: false, error: errorMessage };\n }\n } else {\n parsedArray.push(item);\n }\n }\n return { success: true, data: parsedArray };\n }\n\n // Standard safeParse for the field\n const parsed = fieldSchema.safeParse(val);\n if (parsed.success) {\n return { success: true, data: parsed.data };\n }\n\n // If safeParse failed and val is an Array (e.g. for in / not-in on scalar field),\n // try parsing each item with targetSchema\n if (Array.isArray(val)) {\n const targetSchema = elemSchema ?? fieldSchema;\n const parsedArray: unknown[] = [];\n for (const item of val) {\n if (typeof targetSchema.safeParse === \"function\") {\n const itemParsed = targetSchema.safeParse(item);\n if (itemParsed.success) {\n parsedArray.push(itemParsed.data);\n } else {\n const errorMessage = itemParsed.error.issues\n .map((e: any) => e.message)\n .join(\", \");\n return { success: false, error: errorMessage };\n }\n } else {\n parsedArray.push(item);\n }\n }\n return { success: true, data: parsedArray };\n }\n\n const messages = parsed.error.issues\n .map((e: any) => e.message)\n .join(\", \");\n return { success: false, error: messages };\n}\n\n/**\n * Parse query params into filter conditions.\n * Supports:\n * - field=value → field == value\n * - field__op=value → field op value (e.g., status__ne=draft → status != draft)\n * - field__in=a,b,c → field in [a, b, c]\n */\nexport function 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 for (const [key, rawVal] of Object.entries(query)) {\n if (rawVal === undefined) continue;\n\n // Skip pagination/meta params\n if (\n [\n \"cursor\",\n \"direction\",\n \"limit\",\n \"pageSize\",\n \"orderBy\",\n \"orderDir\",\n \"select\",\n \"includes\",\n \"withTotal\",\n ].includes(key)\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 lastDoubleUnderscore = key.lastIndexOf(\"__\");\n let field: string;\n let op: WhereOp = \"==\";\n\n if (lastDoubleUnderscore !== -1) {\n const fieldCandidate = key.slice(0, lastDoubleUnderscore);\n const opKey = key.slice(lastDoubleUnderscore + 2);\n if (isValidOp(opKey)) {\n field = fieldCandidate;\n op = normalizeWhereOp(opKey);\n } else {\n field = key;\n op = \"==\";\n }\n } else {\n field = key;\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\", \"not-in\", and \"array-contains-any\" operators (comma-separated)\n if (op === \"in\" || op === \"not-in\" || op === \"array-contains-any\") {\n parsedVal = val.split(\",\").map((v) => parseValue(v.trim()));\n } else {\n parsedVal = parseValue(val);\n }\n\n filters.push({ field, op, value: parsedVal });\n }\n\n return filters;\n}\n\n/**\n * Parse a string value into appropriate type.\n */\nfunction parseValue(val: string): unknown {\n // Boolean\n if (val === \"true\") return true;\n if (val === \"false\") return false;\n if (val === \"null\" || val === \"__null__\") return null;\n\n // Number\n const num = Number(val);\n if (!isNaN(num) && val !== \"\") return num;\n\n // String\n return val;\n}\n\n// ---------------------------------------------------------------------------\n// Cursor serialization helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Serialize a Firestore DocumentSnapshot to a JSON-safe cursor object.\n */\nfunction serializeCursor(\n snapshot: import(\"firebase-admin/firestore\").DocumentSnapshot | undefined,\n): Record<string, unknown> | null {\n if (!snapshot) return null;\n return {\n docId: snapshot.id,\n docPath: snapshot.ref?.path ?? undefined,\n };\n}\n\n/**\n * Deserialize a cursor object back to a DocumentSnapshot.\n * Fetches the document from Firestore to get the actual snapshot.\n * Supports root collections and subcollections/collection groups via full docPath.\n */\nasync function deserializeCursor(\n entry: CrudRepoEntry,\n cursor: unknown,\n): Promise<import(\"firebase-admin/firestore\").DocumentSnapshot | undefined> {\n if (!cursor) return undefined;\n\n let cursorObj: Record<string, unknown> | undefined;\n if (typeof cursor === \"string\") {\n try {\n cursorObj = JSON.parse(cursor);\n } catch {\n cursorObj = cursor.includes(\"/\")\n ? { docPath: cursor }\n : { docId: cursor };\n }\n } else if (typeof cursor === \"object\") {\n cursorObj = cursor as Record<string, unknown>;\n }\n\n if (!cursorObj) return undefined;\n\n const docPath =\n typeof cursorObj.docPath === \"string\" ? cursorObj.docPath : undefined;\n const docId =\n typeof cursorObj.docId === \"string\" ? cursorObj.docId : undefined;\n\n try {\n const colRef = entry.repo.ref as any;\n const firestore = colRef?.firestore;\n\n // 1. If docPath is available and firestore instance exists, get doc directly by full path\n if (docPath && firestore && typeof firestore.doc === \"function\") {\n const snapshot = await firestore.doc(docPath).get();\n if (snapshot.exists) return snapshot;\n }\n\n // 2. If docId is a full path (e.g. \"users/u1/comments/c1\"), get doc by full path\n if (docId && docId.includes(\"/\") && firestore && typeof firestore.doc === \"function\") {\n const snapshot = await firestore.doc(docId).get();\n if (snapshot.exists) return snapshot;\n }\n\n // 3. Root collection fallback (colRef.doc exists for CollectionReference)\n if (docId && typeof colRef.doc === \"function\") {\n const snapshot = await colRef.doc(docId).get();\n if (snapshot.exists) return snapshot;\n }\n\n return undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Extract a non-empty plain object of defined fields from a hook's optional\n * `changesNeeded` return value (`Partial<T>`). Returns `null` when empty or\n * not a plain object, and strips `undefined` entries so Firestore `.update()`\n * does not fail on undefined values.\n */\nfunction pickDefinedChanges(value: unknown): Record<string, unknown> | null {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return null;\n }\n const defined: Record<string, unknown> = {};\n let count = 0;\n for (const [k, v] of Object.entries(value)) {\n if (v !== undefined) {\n defined[k] = v;\n count++;\n }\n }\n return count > 0 ? defined : null;\n}\n\n// ---------------------------------------------------------------------------\n// Handlers factory\n// ---------------------------------------------------------------------------\n\nexport function createCrudHandlers(\n registry: CrudRepoRegistry,\n basePath: string,\n verbose: boolean,\n onIndexError?: IndexErrorCallback,\n onHookError?: CrudHookErrorCallback,\n) {\n /**\n * Report an error thrown by a post-write hook (or its follow-up `changesNeeded`\n * update) without turning a committed write into a misleading HTTP 500.\n */\n async function reportHookError(\n entry: CrudRepoEntry,\n logger: any,\n errCtx: Omit<CrudHookErrorContext, \"error\">,\n error: unknown,\n ): Promise<void> {\n let handled = false;\n if (entry.hooks?.onAfterError) {\n handled = true;\n try {\n const res = entry.hooks.onAfterError(error, errCtx.hook);\n if (res instanceof Promise) {\n await res;\n }\n } catch (cbErr) {\n // eslint-disable-next-line no-console\n console.error(\"[crudServer] Error in hooks.onAfterError callback:\", cbErr);\n }\n }\n if (onHookError) {\n handled = true;\n try {\n const res = onHookError({ ...errCtx, error });\n if (res instanceof Promise) {\n await res;\n }\n } catch (cbErr) {\n // eslint-disable-next-line no-console\n console.error(\"[crudServer] Error in onHookError callback:\", cbErr);\n }\n }\n if (handled) return;\n if (logger && typeof logger.error === \"function\") {\n logger.error(error, {\n hook: errCtx.hook,\n repoName: errCtx.repoName,\n path: errCtx.path,\n ...(errCtx.id !== undefined ? { id: errCtx.id } : {}),\n ...(errCtx.pathArgs !== undefined\n ? { pathArgs: errCtx.pathArgs }\n : {}),\n });\n return;\n }\n // eslint-disable-next-line no-console\n console.error(\n `[crudServer] Hook \"${errCtx.hook}\" failed on repo \"${errCtx.repoName}\":`,\n {\n hook: errCtx.hook,\n repoName: errCtx.repoName,\n path: errCtx.path,\n ...(errCtx.id !== undefined ? { id: errCtx.id } : {}),\n ...(errCtx.pathArgs !== undefined\n ? { pathArgs: errCtx.pathArgs }\n : {}),\n error,\n },\n );\n }\n // ── Authorization helpers ───────────────────────────────────────────────\n /**\n * Default-deny gate: when the server has `auth` configured, reject any\n * operation without an explicit rule. When `auth` is absent, rules are\n * ignored entirely (open API).\n */\n async function assertRule<TCtx>(\n c: any,\n entry: CrudRepoEntry,\n op: keyof NonNullable<CrudRepoEntry[\"rules\"]>,\n ctx: TCtx,\n ): Promise<{ allowed: boolean; errorResponse?: any }> {\n if (!entry.rules) return { allowed: true };\n const rule = entry.rules?.[op] as\n | ((c: TCtx) => RuleResult | Promise<RuleResult>)\n | undefined;\n if (!rule) {\n return {\n allowed: false,\n errorResponse: sendError(\n c,\n `Operation \"${op}\" is not allowed for this repository`,\n 403,\n ),\n };\n }\n try {\n const res = await rule(ctx);\n if (res === false) {\n return {\n allowed: false,\n errorResponse: sendError(c, \"Forbidden\", 403),\n };\n }\n if (typeof res === \"string\") {\n return {\n allowed: false,\n errorResponse: sendError(c, res, 403),\n };\n }\n if (typeof res === \"object\" && res !== null && !res.allowed) {\n return {\n allowed: false,\n errorResponse: sendError(c, res.reason || \"Forbidden\", 403),\n };\n }\n return { allowed: true };\n } catch (err) {\n const message =\n verbose && err instanceof Error ? err.message : \"Forbidden\";\n return {\n allowed: false,\n errorResponse: sendError(c, message, 403),\n };\n }\n }\n\n /** Apply `rules.filter` to every doc in a list; returns the filtered slice. */\n async function applyRowFilter<T extends Record<string, unknown>>(\n entry: CrudRepoEntry,\n user: any,\n params: Record<string, string>,\n docs: T[],\n ): Promise<T[]> {\n if (!entry.rules) return docs;\n const filter = entry.rules?.filter as\n | ((c: {\n user: any;\n doc: T;\n params: Record<string, string>;\n }) => boolean | Promise<boolean>)\n | undefined;\n if (!filter) return docs;\n const out: T[] = [];\n for (const doc of docs) {\n try {\n if (await filter({ user, doc, params })) out.push(doc);\n } catch {\n // exclude on error (fail closed)\n }\n }\n return out;\n }\n\n /** Pull the authenticated user from the request (may be undefined when auth is off). */\n function userOf(c: any): any {\n return c.get(\"user\") ?? c.get(\"docsUser\") ?? null;\n }\n\n // ── Helper to get repo entry ────────────────────────────────────────────\n function getRepoEntry(\n repoName: string | undefined,\n c: any,\n ): CrudRepoEntry | null {\n if (!repoName) {\n const parts = c.req.path.split(\"/\");\n for (const part of parts) {\n if (registry[part]) {\n repoName = part;\n break;\n }\n }\n }\n if (!repoName || !registry[repoName]) {\n return null;\n }\n return registry[repoName] ?? null;\n }\n\n /**\n * Extract Firestore document path args from a document's stored path.\n * e.g. \"posts/abc/comments/xyz\" → [\"abc\", \"xyz\"] (the doc-ID segments).\n */\n function extractPathArgs(\n doc: Record<string, unknown>,\n entry: CrudRepoEntry,\n ): string[] | undefined {\n return extractPathArgsFromDoc(doc, {\n pathKey: entry.pathKey,\n documentKey: entry.documentKey,\n parentKeys: entry.parentKeys,\n documentPathTemplate: entry.documentPathTemplate,\n isGroup: entry.isGroup,\n });\n }\n\n /**\n * Fetch a single document by its documentKey, with fallback to query\n * for collection-group repos where direct documentRef may fail.\n */\n async function fetchDocById(\n entry: CrudRepoEntry,\n docId: string,\n ): Promise<Record<string, unknown> | null> {\n const getterName = `by${entry.documentKey.charAt(0).toUpperCase()}${entry.documentKey.slice(1)}`;\n const getter = (entry.repo.get as any)[getterName];\n\n if (typeof getter === \"function\") {\n try {\n const doc = (await getter(docId)) as Record<string, unknown> | null;\n if (doc) return doc;\n } catch {\n // Direct ref may fail for subcollections — fall through to query\n }\n }\n\n const results = await entry.repo.query.by({\n where: [[entry.documentKey, \"==\", docId]],\n limit: 1,\n });\n return (results[0] as Record<string, unknown>) ?? null;\n }\n\n // ── LIST: GET /:repoName ────────────────────────────────────────────────\n async function handleList(ctx: any): Promise<any> {\n const c = ctx.c;\n\n const params = c.req.param();\n const entry = getRepoEntry(params.repoName, c);\n if (!entry) return sendError(c, `Repository not found`, 404);\n\n const user = userOf(c);\n const ruleCheck = await assertRule(c, entry, \"list\", {\n user,\n query: c.req.query(),\n params,\n });\n if (!ruleCheck.allowed) return ruleCheck.errorResponse;\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 pageSizeRes = parseCrudPageSize(query.pageSize, entry.pageSize);\n if (!pageSizeRes.success) {\n return sendError(c, pageSizeRes.error, 400);\n }\n const pageSize = pageSizeRes.value;\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 const withTotalParam = query.withTotal;\n const withTotal =\n withTotalParam === \"true\" ||\n withTotalParam === \"1\" ||\n withTotalParam === true;\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 ...(withTotal ? { withTotal: true } : {}),\n };\n\n if (cursor) {\n try {\n const cursorObj =\n typeof cursor === \"string\" ? JSON.parse(cursor) : cursor;\n queryOptions.cursor = await deserializeCursor(entry, cursorObj);\n } catch {\n // Invalid cursor, ignore\n }\n }\n\n if (orderBy) {\n if (entry.orderableFields && !entry.orderableFields.includes(orderBy)) {\n return sendError(c, `Field not orderable: ${orderBy}`, 400);\n }\n queryOptions.orderBy = [{ field: orderBy, direction: orderDir }];\n }\n\n if (filters.length > 0) {\n queryOptions.where = [];\n for (const f of filters) {\n const parsedRes = parseFieldValue(entry.schema, f.field, f.value, f.op);\n if (!parsedRes.success) {\n return sendError(\n c,\n `Invalid filter value for '${f.field}': ${parsedRes.error}`,\n 400,\n );\n }\n queryOptions.where.push([f.field, f.op, parsedRes.data]);\n }\n }\n\n if (select) {\n queryOptions.select = select as any;\n }\n\n if (includes) {\n queryOptions.include = includes as any;\n }\n\n // Execute query\n const result = await entry.repo.query.paginate(queryOptions);\n const filteredItems = await applyRowFilter(\n entry,\n userOf(c),\n params,\n result.data,\n );\n\n const responseData: ListResponseData = {\n items: filteredItems,\n hasNextPage: result.hasNextPage,\n hasPrevPage: result.hasPrevPage,\n nextCursor: serializeCursor(result.nextCursor),\n prevCursor: serializeCursor(result.prevCursor),\n ...(result.totalCount !== undefined\n ? {\n totalCount: result.totalCount,\n totalCountIsExact: result.totalCountIsExact,\n }\n : {}),\n };\n\n return sendSuccess(c, responseData, {\n pageSize,\n hasMore: result.hasNextPage,\n ...(result.totalCount !== undefined\n ? {\n totalCount: result.totalCount,\n totalCountIsExact: result.totalCountIsExact,\n }\n : {}),\n });\n } catch (err) {\n return await sendQueryError(\n c,\n err,\n {\n repoName: params.repoName || entry.name,\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 onIndexError,\n );\n }\n }\n\n // ── QUERY: POST /:repoName/query ────────────────────────────────────────\n // Advanced query endpoint supporting OR conditions, array filters, etc.\n async function handleQuery(ctx: any): Promise<any> {\n const c = ctx.c;\n\n const params = c.req.param();\n const entry = getRepoEntry(params.repoName, c);\n if (!entry) return sendError(c, `Repository not found`, 404);\n\n const user = userOf(c);\n const ruleCheck = await assertRule(c, entry, \"list\", {\n user,\n query: ctx.input || {},\n params,\n });\n if (!ruleCheck.allowed) return ruleCheck.errorResponse;\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 pageSizeRes = parseCrudPageSize(body.pageSize, entry.pageSize);\n if (!pageSizeRes.success) {\n return sendError(c, pageSizeRes.error, 400);\n }\n const pageSize = pageSizeRes.value;\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 const withTotal =\n body.withTotal === true || String(body.withTotal) === \"true\";\n\n // Build query options\n const queryOptions: any = {\n pageSize,\n direction,\n ...(withTotal ? { withTotal: true } : {}),\n };\n\n // Cursor\n if (body.cursor) {\n try {\n const cursorObj =\n typeof body.cursor === \"string\"\n ? JSON.parse(body.cursor)\n : body.cursor;\n queryOptions.cursor = await deserializeCursor(entry, cursorObj);\n } catch {\n // Invalid cursor, ignore\n }\n }\n\n // Includes (relation population)\n if (entry.allowedIncludes && body.includes && body.includes.length > 0) {\n const validIncludes = body.includes.filter((inc) => {\n if (typeof inc === \"string\") {\n return entry.allowedIncludes!.includes(inc);\n }\n if (\n typeof inc === \"object\" &&\n inc !== null &&\n \"relation\" in inc &&\n typeof inc.relation === \"string\"\n ) {\n return entry.allowedIncludes!.includes(inc.relation);\n }\n return false;\n });\n if (validIncludes.length > 0) {\n queryOptions.include = validIncludes as any;\n }\n }\n\n // Where conditions (AND)\n if (body.where && body.where.length > 0) {\n // Validate filterable fields if configured\n if (entry.filterableFields) {\n const allowed = new Set(entry.filterableFields);\n const invalid = body.where.filter((w) => !allowed.has(w[0]));\n if (invalid.length > 0) {\n sendError(\n c,\n `Fields not filterable: ${invalid.map((w) => w[0]).join(\", \")}`,\n 400,\n );\n return;\n }\n }\n const parsedWhere: [string, any, any][] = [];\n for (const w of body.where) {\n const normalizedOp = normalizeWhereOp(w[1]);\n const parsedRes = parseFieldValue(entry.schema, w[0], w[2], normalizedOp);\n if (!parsedRes.success) {\n sendError(\n c,\n `Invalid filter value for '${w[0]}': ${parsedRes.error}`,\n 400,\n );\n return;\n }\n parsedWhere.push([w[0], normalizedOp, parsedRes.data]);\n }\n queryOptions.where = parsedWhere;\n }\n\n // OR where conditions (simple)\n if (body.orWhere && body.orWhere.length > 0) {\n if (entry.filterableFields) {\n const allowed = new Set(entry.filterableFields);\n const invalid = body.orWhere.filter((w) => !allowed.has(w[0]));\n if (invalid.length > 0) {\n sendError(\n c,\n `Fields not filterable: ${invalid.map((w) => w[0]).join(\", \")}`,\n 400,\n );\n return;\n }\n }\n const parsedOrWhere: [string, any, any][] = [];\n for (const w of body.orWhere) {\n const normalizedOp = normalizeWhereOp(w[1]);\n const parsedRes = parseFieldValue(entry.schema, w[0], w[2], normalizedOp);\n if (!parsedRes.success) {\n sendError(\n c,\n `Invalid filter value for '${w[0]}': ${parsedRes.error}`,\n 400,\n );\n return;\n }\n parsedOrWhere.push([w[0], normalizedOp, parsedRes.data]);\n }\n queryOptions.orWhere = parsedOrWhere;\n }\n\n // OR where groups (advanced)\n if (body.orWhereGroups && body.orWhereGroups.length > 0) {\n if (entry.filterableFields) {\n const allowed = new Set(entry.filterableFields);\n for (const group of body.orWhereGroups) {\n const invalid = group.filter((w) => !allowed.has(w[0]));\n if (invalid.length > 0) {\n sendError(\n c,\n `Fields not filterable: ${invalid.map((w) => w[0]).join(\", \")}`,\n 400,\n );\n return;\n }\n }\n }\n const parsedOrWhereGroups: [string, any, any][][] = [];\n for (const group of body.orWhereGroups) {\n const parsedGroup: [string, any, any][] = [];\n for (const w of group) {\n const normalizedOp = normalizeWhereOp(w[1]);\n const parsedRes = parseFieldValue(entry.schema, w[0], w[2], normalizedOp);\n if (!parsedRes.success) {\n sendError(\n c,\n `Invalid filter value for '${w[0]}': ${parsedRes.error}`,\n 400,\n );\n return;\n }\n parsedGroup.push([w[0], normalizedOp, parsedRes.data]);\n }\n parsedOrWhereGroups.push(parsedGroup);\n }\n queryOptions.orWhereGroups = parsedOrWhereGroups;\n }\n\n // Order by\n if (body.orderBy && body.orderBy.length > 0) {\n if (entry.orderableFields) {\n const allowed = new Set(entry.orderableFields);\n const invalid = body.orderBy.filter((o) => !allowed.has(o.field));\n if (invalid.length > 0) {\n sendError(\n c,\n `Fields not orderable: ${invalid.map((o) => o.field).join(\", \")}`,\n 400,\n );\n return;\n }\n }\n queryOptions.orderBy = body.orderBy;\n }\n\n // Select\n if (body.select && body.select.length > 0) {\n queryOptions.select = body.select;\n }\n\n // Execute query\n const result = await entry.repo.query.paginate(queryOptions);\n const filteredItems = await applyRowFilter(\n entry,\n userOf(c),\n params,\n result.data,\n );\n\n const responseData: ListResponseData = {\n items: filteredItems,\n hasNextPage: result.hasNextPage,\n hasPrevPage: result.hasPrevPage,\n nextCursor: serializeCursor(result.nextCursor),\n prevCursor: serializeCursor(result.prevCursor),\n ...(result.totalCount !== undefined\n ? {\n totalCount: result.totalCount,\n totalCountIsExact: result.totalCountIsExact,\n }\n : {}),\n };\n\n return sendSuccess(c, responseData, {\n pageSize,\n hasMore: result.hasNextPage,\n ...(result.totalCount !== undefined\n ? {\n totalCount: result.totalCount,\n totalCountIsExact: result.totalCountIsExact,\n }\n : {}),\n });\n } catch (err) {\n return await sendQueryError(\n c,\n err,\n {\n repoName: params.repoName || entry.name,\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 onIndexError,\n );\n }\n }\n\n // ── GET: GET /:repoName/:id ─────────────────────────────────────────────\n async function handleGet(ctx: any): Promise<any> {\n const c = ctx.c;\n\n const params = c.req.param();\n const entry = getRepoEntry(params.repoName, c);\n if (!entry) return sendError(c, `Repository not found`, 404);\n\n const id = params.id;\n if (!id) {\n return sendError(c, \"Document ID required\", 400);\n }\n\n try {\n const doc = await fetchDocById(entry, id);\n\n if (!doc) {\n return sendError(c, \"Document not found\", 404);\n }\n\n const user = userOf(c);\n const getRuleCheck = await assertRule(c, entry, \"get\", {\n user,\n doc: doc as any,\n params,\n });\n if (!getRuleCheck.allowed) return getRuleCheck.errorResponse;\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 return await sendQueryError(\n c,\n err,\n {\n repoName: params.repoName || entry.name,\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 onIndexError,\n );\n }\n }\n\n // ── CREATE: POST /:repoName ─────────────────────────────────────────────\n async function handleCreate(ctx: any): Promise<any> {\n const c = ctx.c;\n\n const params = c.req.param();\n const entry = getRepoEntry(params.repoName, c);\n if (!entry) return sendError(c, `Repository not found`, 404);\n\n try {\n const body = ctx.input || {};\n\n const user = userOf(c);\n const createRuleCheck = await assertRule(c, entry, \"create\", {\n user,\n body,\n params,\n });\n if (!createRuleCheck.allowed) return createRuleCheck.errorResponse;\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 // Pre-write mutations hook (mutates validation.data by reference)\n if (entry.hooks?.beforeCreate) {\n await entry.hooks.beforeCreate({\n user,\n body: validation.data as any,\n params,\n c,\n });\n }\n\n // Create document\n let created: any;\n let explicitPathArgs: string[] | undefined;\n if (entry.isGroup && entry.parentKeys && entry.parentKeys.length > 0) {\n const data: Record<string, any> = { ...validation.data };\n const missingKeys = entry.parentKeys.filter(\n (k) =>\n data[k] === undefined ||\n data[k] === null ||\n (typeof data[k] === \"string\" && data[k].trim() === \"\"),\n );\n if (missingKeys.length > 0) {\n return sendError(\n c,\n `Missing parent key(s) for subcollection create: ${missingKeys.join(\", \")}`,\n 400,\n );\n }\n if (typeof entry.repo.create === \"function\") {\n created = await entry.repo.create(data as any);\n } else {\n const parentIds = entry.parentKeys.map((k) => String(data[k]));\n const docId = data[entry.documentKey] || generateFirestoreId();\n explicitPathArgs = [...parentIds, docId];\n created = await entry.repo.set(...parentIds, docId, data);\n }\n } else {\n created = await entry.repo.create(validation.data as any);\n }\n\n let finalDoc = created;\n if (entry.hooks?.afterCreate) {\n const rawCreatedId =\n created?.[entry.documentKey] ??\n explicitPathArgs?.[explicitPathArgs.length - 1] ??\n \"\";\n const createdId = String(rawCreatedId);\n const pathArgs =\n explicitPathArgs ??\n extractPathArgs(created, entry) ??\n extractPathArgs(\n {\n ...validation.data,\n ...(createdId ? { [entry.documentKey]: createdId } : {}),\n },\n entry,\n ) ??\n (createdId ? [createdId] : []);\n\n try {\n const extraChanges = await entry.hooks.afterCreate({\n user,\n doc: created,\n id: createdId,\n pathArgs,\n params,\n c,\n });\n const definedChanges = pickDefinedChanges(extraChanges);\n if (definedChanges && pathArgs.length > 0) {\n finalDoc = await entry.repo.update(\n ...pathArgs,\n definedChanges as any,\n );\n }\n } catch (hookErr) {\n await reportHookError(\n entry,\n ctx.logger,\n {\n hook: \"afterCreate\",\n repoName: entry.name,\n path: entry.path,\n id: createdId,\n pathArgs,\n user,\n c,\n },\n hookErr,\n );\n }\n }\n\n return sendSuccess(c, finalDoc, undefined, 201);\n } catch (err) {\n const message =\n verbose && err instanceof Error\n ? err.message\n : \"Failed to create document\";\n return sendError(c, message, 500);\n }\n }\n\n // ── UPDATE: PUT/PATCH /:repoName/:id ────────────────────────────────────\n async function handleUpdate(ctx: any, partial: boolean): Promise<any> {\n const c = ctx.c;\n const params = c.req.param();\n const entry = getRepoEntry(params.repoName, c);\n if (!entry) return sendError(c, `Repository not found`, 404);\n\n const id = params.id;\n if (!id) {\n return sendError(c, \"Document ID required\", 400);\n }\n\n try {\n const body = ctx.input || {};\n\n // Fetch existing doc so the rule can authorize against current state\n const existingDoc = await fetchDocById(entry, id);\n if (!existingDoc) {\n return sendError(c, \"Document not found\", 404);\n }\n\n // 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 // Compute diff between existing doc and sanitized changes\n const diff = computeDeepDiff(existingDoc as any, validation.data);\n\n const user = userOf(c);\n const updateRuleCheck = await assertRule(c, entry, \"update\", {\n user,\n doc: existingDoc as any,\n body: validation.data,\n diff,\n params,\n });\n if (!updateRuleCheck.allowed) return updateRuleCheck.errorResponse;\n\n // Pre-write mutations hook (mutates validation.data by reference)\n if (entry.hooks?.beforeUpdate) {\n const preHookDiff = entry.rules?.update\n ? computeDeepDiff(existingDoc as any, validation.data)\n : diff;\n await entry.hooks.beforeUpdate({\n user,\n doc: existingDoc as any,\n body: validation.data as any,\n diff: preHookDiff,\n params,\n c,\n });\n }\n\n // Recompute diff AFTER rules.update & hooks.beforeUpdate so preWrite mutations are included\n const finalBody = { ...validation.data };\n const finalDiff = entry.hooks?.afterUpdate\n ? computeDeepDiff(existingDoc as any, finalBody)\n : diff;\n\n // Update document — derive path args for subcollections\n const pathArgs = extractPathArgs(existingDoc, entry) ?? [id];\n const updated = await entry.repo.update(\n ...pathArgs,\n validation.data as any,\n );\n\n let finalDoc = updated;\n if (entry.hooks?.afterUpdate) {\n try {\n const extraChanges = await entry.hooks.afterUpdate({\n user,\n before: existingDoc as any,\n after: updated as any,\n body: finalBody as any,\n diff: finalDiff,\n id,\n pathArgs,\n params,\n c,\n });\n const definedChanges = pickDefinedChanges(extraChanges);\n if (definedChanges) {\n finalDoc = await entry.repo.update(\n ...pathArgs,\n definedChanges as any,\n );\n }\n } catch (hookErr) {\n await reportHookError(\n entry,\n ctx.logger,\n {\n hook: \"afterUpdate\",\n repoName: entry.name,\n path: entry.path,\n id,\n pathArgs,\n user,\n c,\n },\n hookErr,\n );\n }\n }\n\n return sendSuccess(c, finalDoc);\n } catch (err) {\n const message =\n verbose && err instanceof Error\n ? err.message\n : \"Failed to update document\";\n return sendError(c, message, 500);\n }\n }\n\n // ── DELETE: DELETE /:repoName/:id ───────────────────────────────────────\n async function handleDelete(ctx: any): Promise<any> {\n const c = ctx.c;\n\n const params = c.req.param();\n const entry = getRepoEntry(params.repoName, c);\n if (!entry) return sendError(c, `Repository not found`, 404);\n\n if (!entry.allowDelete) {\n return sendError(c, \"Delete not allowed for this repository\", 403);\n }\n\n const id = params.id;\n if (!id) {\n return sendError(c, \"Document ID required\", 400);\n }\n\n try {\n // Fetch first to authorize against current state and get path args\n const doc = await fetchDocById(entry, id);\n if (!doc) {\n return sendError(c, \"Document not found\", 404);\n }\n\n const user = userOf(c);\n const deleteRuleCheck = await assertRule(c, entry, \"delete\", {\n user,\n doc: doc as any,\n params,\n });\n if (!deleteRuleCheck.allowed) return deleteRuleCheck.errorResponse;\n\n const pathArgs = extractPathArgs(doc, entry) ?? [id];\n await entry.repo.delete(...pathArgs);\n\n if (entry.hooks?.afterDelete) {\n try {\n await entry.hooks.afterDelete({\n user,\n doc: doc as any,\n id,\n pathArgs,\n params,\n c,\n });\n } catch (hookErr) {\n await reportHookError(\n entry,\n ctx.logger,\n {\n hook: \"afterDelete\",\n repoName: entry.name,\n path: entry.path,\n id,\n pathArgs,\n user,\n c,\n },\n hookErr,\n );\n }\n }\n\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\":\n \"Content-Type, Authorization, X-History-Reason, X-History-Comment\",\n \"Access-Control-Max-Age\": \"86400\",\n });\n }\n\n // ── BATCH: POST /:repoName/batch ─────────────────────────────────────────\n async function handleBatch(ctx: any) {\n const c = ctx.c;\n const params = c.req.param();\n const entry = getRepoEntry(params.repoName, c);\n if (!entry) return sendError(c, `Repository not found`, 404);\n\n try {\n const body = ctx.input || {};\n if (!Array.isArray(body.operations)) {\n return sendError(c, \"operations array is required\", 400);\n }\n\n const user = userOf(c);\n\n const batch = entry.repo.batch.create();\n const results = [];\n const hasHooks = !!entry.hooks;\n const createdItems: Array<{ id: string; pathArgs: string[]; doc: any }> =\n [];\n const updatedItems: Array<{\n id: string;\n pathArgs: string[];\n before: any;\n after: any;\n body: any;\n diff: DeepDiffReturn<any>;\n }> = [];\n const deletedItems: Array<{ id: string; pathArgs: string[]; doc: any }> =\n [];\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 const createRuleCheck = await assertRule(c, entry, \"create\", {\n user,\n body: op.data,\n params,\n });\n if (!createRuleCheck.allowed) return createRuleCheck.errorResponse;\n\n const validation = validateData(\n entry.schema,\n op.data,\n entry.createFields,\n false,\n entry.systemKeys,\n );\n if (!validation.success)\n return sendError(c, (validation as any).error, 400);\n\n if (entry.hooks?.beforeCreate) {\n await entry.hooks.beforeCreate({\n user,\n body: validation.data as any,\n params,\n c,\n });\n }\n\n let docId =\n op.data[entry.documentKey] ||\n (validation.data[entry.documentKey] as string | undefined) ||\n generateFirestoreId();\n const data = { ...validation.data };\n if (entry.createdKey && data[entry.createdKey] === undefined) {\n data[entry.createdKey] = new Date();\n }\n\n let pathArgs: string[];\n if (entry.isGroup && entry.parentKeys) {\n const parentIds = entry.parentKeys.map(\n (k: string) => String(data[k]),\n );\n pathArgs = [...parentIds, docId];\n batch.set(...parentIds, docId, data);\n } else {\n pathArgs = [docId];\n batch.set(docId, data);\n }\n results.push({ op: \"create\", id: docId });\n\n if (hasHooks) {\n const createdDoc: Record<string, unknown> = {\n ...data,\n [entry.documentKey]: docId,\n };\n if (\n entry.pathKey &&\n typeof (entry.repo as any).documentRef === \"function\"\n ) {\n try {\n const ref = (entry.repo as any).documentRef(...pathArgs);\n if (ref?.path) createdDoc[entry.pathKey] = ref.path;\n } catch {\n // Ignore in minimal mocks\n }\n }\n createdItems.push({ id: docId, pathArgs, doc: createdDoc });\n }\n } else if (op.type === \"update\") {\n if (!op.id) return sendError(c, \"id required for update\", 400);\n\n const existingDoc = await fetchDocById(entry, op.id);\n if (!existingDoc)\n return sendError(c, `Document ${op.id} not found`, 404);\n\n const validation = validateData(\n entry.schema,\n op.data,\n entry.mutableFields,\n true,\n entry.systemKeys,\n );\n if (!validation.success)\n return sendError(c, (validation as any).error, 400);\n\n 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 const diff = computeDeepDiff(existingDoc as any, validation.data);\n\n const updateRuleCheck = await assertRule(c, entry, \"update\", {\n user,\n doc: existingDoc as any,\n body: validation.data,\n diff,\n params,\n });\n if (!updateRuleCheck.allowed) return updateRuleCheck.errorResponse;\n\n if (entry.hooks?.beforeUpdate) {\n const preHookDiff = entry.rules?.update\n ? computeDeepDiff(existingDoc as any, validation.data)\n : diff;\n await entry.hooks.beforeUpdate({\n user,\n doc: existingDoc as any,\n body: validation.data as any,\n diff: preHookDiff,\n params,\n c,\n });\n }\n\n // Recompute diff AFTER rules.update & hooks.beforeUpdate so preWrite mutations are included\n const finalBody = { ...validation.data };\n const finalDiff = hasHooks\n ? computeDeepDiff(existingDoc as any, finalBody)\n : diff;\n\n const pathArgs = extractPathArgs(existingDoc, entry) ?? [\n op.id,\n ];\n batch.update(...pathArgs, validation.data);\n results.push({ op: \"update\", id: op.id });\n\n if (hasHooks) {\n updatedItems.push({\n id: op.id,\n pathArgs,\n before: existingDoc,\n after: finalDiff.after,\n body: finalBody,\n diff: finalDiff,\n });\n }\n } else if (op.type === \"delete\") {\n if (!entry.allowDelete)\n return sendError(c, \"Delete not allowed\", 403);\n if (!op.id) return sendError(c, \"id required for delete\", 400);\n\n const doc = await fetchDocById(entry, op.id);\n if (!doc) return sendError(c, `Document ${op.id} not found`, 404);\n const deleteRuleCheck = await assertRule(c, entry, \"delete\", {\n user,\n doc: doc as any,\n params,\n });\n if (!deleteRuleCheck.allowed) return deleteRuleCheck.errorResponse;\n\n const pathArgs = extractPathArgs(doc, entry) ?? [op.id];\n batch.delete(...pathArgs);\n results.push({ op: \"delete\", id: op.id });\n\n if (hasHooks) {\n deletedItems.push({ id: op.id, pathArgs, doc });\n }\n }\n }\n\n await batch.commit();\n\n const hasAnyOp =\n createdItems.length > 0 ||\n updatedItems.length > 0 ||\n deletedItems.length > 0;\n\n if (entry.hooks && hasAnyOp) {\n if (entry.hooks.afterBatch) {\n try {\n await entry.hooks.afterBatch({\n user,\n created: createdItems,\n updated: updatedItems,\n deleted: deletedItems,\n params,\n c,\n });\n } catch (hookErr) {\n await reportHookError(\n entry,\n ctx.logger,\n {\n hook: \"afterBatch\",\n repoName: entry.name,\n path: entry.path,\n user,\n c,\n },\n hookErr,\n );\n }\n } else {\n if (entry.hooks.afterCreate) {\n for (const item of createdItems) {\n try {\n const extraChanges = await entry.hooks.afterCreate({\n user,\n doc: item.doc,\n id: item.id,\n pathArgs: item.pathArgs,\n params,\n c,\n });\n const definedChanges = pickDefinedChanges(extraChanges);\n if (definedChanges && item.pathArgs.length > 0) {\n await entry.repo.update(\n ...item.pathArgs,\n definedChanges as any,\n );\n }\n } catch (hookErr) {\n await reportHookError(\n entry,\n ctx.logger,\n {\n hook: \"afterCreate\",\n repoName: entry.name,\n path: entry.path,\n id: item.id,\n pathArgs: item.pathArgs,\n user,\n c,\n },\n hookErr,\n );\n }\n }\n }\n if (entry.hooks.afterUpdate) {\n for (const item of updatedItems) {\n try {\n const extraChanges = await entry.hooks.afterUpdate({\n user,\n before: item.before,\n after: item.after,\n body: item.body,\n diff: item.diff,\n id: item.id,\n pathArgs: item.pathArgs,\n params,\n c,\n });\n const definedChanges = pickDefinedChanges(extraChanges);\n if (definedChanges && item.pathArgs.length > 0) {\n await entry.repo.update(\n ...item.pathArgs,\n definedChanges as any,\n );\n }\n } catch (hookErr) {\n await reportHookError(\n entry,\n ctx.logger,\n {\n hook: \"afterUpdate\",\n repoName: entry.name,\n path: entry.path,\n id: item.id,\n pathArgs: item.pathArgs,\n user,\n c,\n },\n hookErr,\n );\n }\n }\n }\n if (entry.hooks.afterDelete) {\n for (const item of deletedItems) {\n try {\n await entry.hooks.afterDelete({\n user,\n doc: item.doc,\n id: item.id,\n pathArgs: item.pathArgs,\n params,\n c,\n });\n } catch (hookErr) {\n await reportHookError(\n entry,\n ctx.logger,\n {\n hook: \"afterDelete\",\n repoName: entry.name,\n path: entry.path,\n id: item.id,\n pathArgs: item.pathArgs,\n user,\n c,\n },\n hookErr,\n );\n }\n }\n }\n }\n }\n\n return sendSuccess(c, { results });\n } catch (err) {\n const message =\n verbose && err instanceof Error\n ? err.message\n : \"Batch operation failed\";\n return sendError(c, message, 500);\n }\n }\n\n return {\n handleList,\n handleQuery,\n handleGet,\n handleCreate,\n handleUpdate,\n handleDelete,\n handleBatch,\n handleOptions,\n };\n}\n","/**\n * OpenAPI 3.1 specification generator for the CRUD server.\n *\n * Introspects each `CrudRepoEntry` and uses Zod 4's native `z.toJSONSchema()`\n * to produce a fully typed OpenAPI document ready for Scalar UI or codegen.\n *\n * @module servers/crud/openapi\n */\n\nimport { z } from \"zod\";\nimport { getOpenApiMetadata } from \"@asteasolutions/zod-to-openapi\";\nimport { resolveShadowConfig } from \"../../history/inject\";\nimport {\n DEFAULT_HISTORY_COMMENT_HEADER,\n DEFAULT_HISTORY_REASON_HEADER,\n} from \"../../shared/actor-context\";\nimport type {\n CrudRepoEntry,\n CrudRepoRegistry,\n OpenAPIHistoryHeadersConfig,\n OpenAPISpecOptions,\n} from \"./types\";\n\nexport type { OpenAPISpecOptions };\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Minimal subset of an OpenAPI 3.1 document we produce. */\nexport interface OpenAPIDocument {\n openapi: \"3.1.0\";\n info: OpenAPIInfo;\n servers?: { url: string; description?: string }[];\n paths: Record<string, Record<string, OpenAPIOperation>>;\n components: {\n schemas: Record<string, Record<string, unknown>>;\n securitySchemes?: Record<string, Record<string, unknown>>;\n };\n security?: Record<string, string[]>[];\n tags?: { name: string; description?: string }[];\n}\n\nexport interface OpenAPIInfo {\n title: string;\n version: string;\n description?: string;\n}\n\ninterface OpenAPIOperation {\n operationId: string;\n summary: string;\n tags: string[];\n parameters?: Record<string, unknown>[];\n requestBody?: Record<string, unknown>;\n responses: Record<string, Record<string, unknown>>;\n security?: Record<string, string[]>[];\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Convert a Zod schema to a JSON Schema object suitable for OpenAPI 3.1.\n *\n * Uses `unrepresentable: \"any\"` so that types Zod can't natively serialize\n * (e.g. `z.date()`, `z.bigint()`, custom classes — common with Firestore\n * Timestamps stored as `Date`) don't throw and collapse the whole schema to\n * a bare `{ type: \"object\" }`. We additionally override a few well-known\n * cases to a sensible OpenAPI representation.\n */\nfunction zodToJsonSchema(schema: z.ZodType): Record<string, unknown> {\n try {\n return z.toJSONSchema(schema, {\n target: \"openapi-3.1\",\n unrepresentable: \"any\",\n override: (ctx) => {\n const metadata = getOpenApiMetadata(ctx.zodSchema as unknown as z.ZodTypeAny);\n if (metadata) {\n Object.assign(ctx.jsonSchema, metadata);\n if (ctx.jsonSchema.anyOf || ctx.jsonSchema.oneOf) {\n delete (ctx.jsonSchema as any).type;\n }\n }\n\n const def: any = (ctx.zodSchema as any)?._zod?.def;\n if (!def) return;\n if (def.type === \"date\" && !(ctx.jsonSchema as any).type && !ctx.jsonSchema.anyOf) {\n (ctx.jsonSchema as any).type = \"string\";\n (ctx.jsonSchema as any).format = \"date-time\";\n } else if (def.type === \"bigint\" && !(ctx.jsonSchema as any).type && !ctx.jsonSchema.anyOf) {\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 totalCount: {\n type: \"integer\",\n description:\n \"Total count of matching documents (when requested with withTotal=true)\",\n },\n totalCountIsExact: {\n type: \"boolean\",\n description:\n \"Whether totalCount is exact (true) or estimated via parallel branch-sum fallback (false)\",\n },\n },\n required: [\"items\", \"hasNextPage\", \"hasPrevPage\"],\n },\n meta: {\n type: \"object\",\n properties: {\n pageSize: { type: \"integer\" },\n hasMore: { type: \"boolean\" },\n totalCount: { type: \"integer\" },\n totalCountIsExact: { type: \"boolean\" },\n cursor: {\n oneOf: [{ type: \"string\" }, { type: \"null\" }],\n },\n },\n },\n },\n required: [\"success\", \"data\"],\n },\n },\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Introspection & Zod-to-OpenAPI Type Resolution\n// ---------------------------------------------------------------------------\n\n/** Helper to unwrap Zod modifiers (optional, nullable, default, catch, effects, etc.) */\nfunction unwrapZodType(zodType: any): any {\n let cur = zodType;\n while (cur) {\n const def = cur._zod?.def ?? cur._def;\n if (!def) break;\n if (def.innerType) {\n cur = def.innerType;\n } else if (def.schema) {\n cur = def.schema;\n } else if (\n def.type === \"optional\" ||\n def.type === \"nullable\" ||\n def.type === \"default\" ||\n def.type === \"catch\" ||\n def.type === \"effects\"\n ) {\n cur = def.innerType ?? def.schema;\n } else {\n break;\n }\n }\n return cur;\n}\n\n/** Resolve a dot-notation path (e.g. \"address.city\") from a Zod schema */\nfunction resolveFieldPathSchema(entrySchema: any, path: string): any {\n const parts = path.split(\".\");\n let cur = unwrapZodType(entrySchema);\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n if (!part) continue;\n const shape: Record<string, any> | undefined = (cur as any)?.shape;\n if (!shape || !shape[part]) {\n return undefined;\n }\n const rawSub = shape[part];\n if (i === parts.length - 1) {\n return rawSub;\n }\n cur = unwrapZodType(rawSub);\n }\n return cur;\n}\n\n/** Recursively make Zod objects deep-partial for PATCH updates while preserving nullable/metadata */\nfunction makeDeepPartial(s: z.ZodType): z.ZodType {\n const def = (s as any)?._zod?.def ?? (s as any)?._def;\n const typeName = def?.typeName ?? def?.type;\n\n const copyMetadata = (target: z.ZodType): z.ZodType => {\n const metadata = getOpenApiMetadata(s as unknown as z.ZodTypeAny);\n if (metadata && typeof (target as any).openapi === \"function\") {\n return (target as any).openapi(metadata);\n }\n return target;\n };\n\n if (typeName === \"ZodObject\" || typeName === \"object\") {\n const shape = (s as z.ZodObject<any>).shape;\n const newShape: Record<string, z.ZodType> = {};\n for (const [k, v] of Object.entries(shape)) {\n newShape[k] = makeDeepPartial(v as z.ZodType);\n }\n return copyMetadata(z.object(newShape).partial());\n }\n\n if (typeName === \"ZodOptional\" || typeName === \"optional\") {\n const inner = def.innerType as z.ZodType | undefined;\n if (!inner) return s;\n const nextInner = makeDeepPartial(inner);\n return nextInner === inner ? s : copyMetadata(nextInner.optional());\n }\n\n if (typeName === \"ZodNullable\" || typeName === \"nullable\") {\n const inner = def.innerType as z.ZodType | undefined;\n if (!inner) return s;\n const nextInner = makeDeepPartial(inner);\n return nextInner === inner ? s : copyMetadata(nextInner.nullable());\n }\n\n if (typeName === \"ZodDefault\" || typeName === \"default\") {\n const inner = def.innerType as z.ZodType | undefined;\n if (!inner) return s;\n return copyMetadata(makeDeepPartial(inner).optional());\n }\n\n if (typeName === \"ZodUnion\" || typeName === \"union\") {\n const options = def.options as z.ZodType[] | undefined;\n if (!options || options.length < 2) return s;\n const nextOptions = options.map((opt) => makeDeepPartial(opt));\n const changed = nextOptions.some((opt, i) => opt !== options[i]);\n return changed ? copyMetadata(z.union(nextOptions as any)) : s;\n }\n\n return s;\n}\n\n/** Recursively extract leaf fields and parent object fields from a Zod object schema */\nfunction extractLeafFields(\n zodSchema: any,\n prefix = \"\",\n depth = 0,\n): { path: string; zodSchema: any }[] {\n if (depth > 5) return [];\n const unwrapped = unwrapZodType(zodSchema);\n const shape = unwrapped?.shape;\n if (!shape) return [];\n\n const results: { path: string; zodSchema: any }[] = [];\n for (const [key, rawSub] of Object.entries(shape)) {\n const fieldPath = prefix ? `${prefix}.${key}` : key;\n const subUnwrapped = unwrapZodType(rawSub);\n if (subUnwrapped?.shape && typeof subUnwrapped.shape === \"object\") {\n results.push({ path: fieldPath, zodSchema: rawSub });\n results.push(...extractLeafFields(subUnwrapped, fieldPath, depth + 1));\n } else {\n results.push({ path: fieldPath, zodSchema: rawSub });\n }\n }\n return results;\n}\n\n/** Get all filterable leaf fields for a CrudRepoEntry */\nfunction getFilterableLeafFields(\n entry: CrudRepoEntry,\n): { path: string; zodSchema: any }[] {\n if (entry.filterableFields && entry.filterableFields.length > 0) {\n return entry.filterableFields.map((path) => ({\n path,\n zodSchema: resolveFieldPathSchema(entry.schema, path),\n }));\n }\n return extractLeafFields(entry.schema);\n}\n\n/** Convert a Zod field schema to an inline OpenAPI JSON Schema for its value */\nfunction zodTypeToJsonValueSchema(zodType: any): Record<string, unknown> {\n if (!zodType) return { type: \"string\" };\n const jsonSchema = zodToJsonSchema(zodType);\n delete jsonSchema[\"$schema\"];\n delete jsonSchema[\"title\"];\n return jsonSchema;\n}\n\n// ---------------------------------------------------------------------------\n// Pagination / filter query parameters (shared across list endpoints)\n// ---------------------------------------------------------------------------\n\nfunction paginationParams(entry: CrudRepoEntry): Record<string, unknown>[] {\n const leafFields = getFilterableLeafFields(entry);\n const orderableFields =\n entry.orderableFields ?? leafFields.map((f) => f.path);\n\n return [\n {\n name: \"pageSize\",\n in: \"query\",\n schema: {\n type: \"integer\",\n default: entry.pageSize,\n minimum: 1,\n maximum: 1000,\n },\n description: \"Number of items per page\",\n },\n {\n name: \"cursor\",\n in: \"query\",\n schema: { type: \"string\" },\n description: \"Base64 pagination cursor\",\n },\n {\n name: \"orderBy\",\n in: \"query\",\n schema: {\n type: \"string\",\n ...(orderableFields.length > 0 ? { enum: orderableFields } : {}),\n },\n description: \"Field name to order by\",\n },\n {\n name: \"orderDir\",\n in: \"query\",\n schema: { type: \"string\", enum: [\"asc\", \"desc\"] },\n description: \"Order direction\",\n },\n {\n name: \"select\",\n in: \"query\",\n schema: { type: \"string\" },\n description: `Comma-separated list of fields to return${\n leafFields.length > 0\n ? ` (${leafFields.map((f) => f.path).join(\", \")})`\n : \"\"\n }`,\n },\n {\n name: \"withTotal\",\n in: \"query\",\n schema: { type: \"boolean\" },\n description:\n \"Include total document count (totalCount and totalCountIsExact) in response\",\n },\n ];\n}\n\nfunction filterParams(entry: CrudRepoEntry): Record<string, unknown>[] {\n const leafFields = getFilterableLeafFields(entry);\n const ops = [\n \"eq\",\n \"ne\",\n \"lt\",\n \"lte\",\n \"gt\",\n \"gte\",\n \"in\",\n \"nin\",\n \"contains\",\n \"containsAny\",\n ];\n\n const opDescriptions: Record<string, string> = {\n eq: \"equals. Use 'null' or '__null__' to match null values\",\n ne: \"not equals. Use 'null' or '__null__' to match non-null values\",\n lt: \"less than\",\n lte: \"less than or equal\",\n gt: \"greater than\",\n gte: \"greater than or equal\",\n in: \"in list (comma-separated values). Supports 'null' and '__null__' (e.g. val1,val2,__null__)\",\n nin: \"not in list (comma-separated values). Supports 'null' and '__null__'\",\n contains: \"array-contains\",\n containsAny: \"array-contains-any (comma-separated values). Supports 'null' and '__null__'\",\n };\n\n const params: Record<string, unknown>[] = [];\n for (const { path: field, zodSchema } of leafFields) {\n const valSchema = zodTypeToJsonValueSchema(zodSchema);\n const unwrapped = unwrapZodType(zodSchema);\n\n const isArrayType =\n (unwrapped as any)?._zod?.def?.type === \"array\" ||\n (unwrapped as any)?._def?.typeName === \"ZodArray\" ||\n (unwrapped as any)?._def?.type === \"array\";\n\n const elemSchema = isArrayType\n ? zodTypeToJsonValueSchema(\n (unwrapped as any)?._zod?.def?.element ??\n (unwrapped as any)?._def?.type ??\n (unwrapped as any)?._def?.element,\n )\n : valSchema;\n\n // Direct equality filter: ?field=value\n params.push({\n name: field,\n in: \"query\",\n schema: valSchema,\n description: `Filter by ${field} (equality). Use 'null' or '__null__' for null values`,\n });\n // Operator filters: ?field__op=value\n for (const op of ops) {\n const descDetail = opDescriptions[op] ? ` (${opDescriptions[op]})` : \"\";\n const isListOp = op === \"in\" || op === \"nin\" || op === \"containsAny\";\n const isElemOp = op === \"contains\";\n params.push({\n name: `${field}__${op}`,\n in: \"query\",\n schema: isListOp\n ? { type: \"string\", description: \"Comma-separated list of values\" }\n : isElemOp\n ? elemSchema\n : valSchema,\n description: `Filter ${field} with operator ${op}${descDetail}`,\n });\n }\n }\n return params;\n}\n\n// ---------------------------------------------------------------------------\n// Query body schema (POST /query)\n// ---------------------------------------------------------------------------\n\nfunction queryBodySchema(): Record<string, unknown> {\n return {\n type: \"object\",\n properties: {\n where: {\n type: \"array\",\n items: {\n type: \"array\",\n items: {},\n minItems: 3,\n maxItems: 3,\n },\n description: \"AND conditions: [field, operator, value][]\",\n },\n orWhere: {\n type: \"array\",\n items: {\n type: \"array\",\n items: {},\n minItems: 3,\n maxItems: 3,\n },\n description: \"Simple OR conditions (each independently OR'd)\",\n },\n orWhereGroups: {\n type: \"array\",\n items: {\n type: \"array\",\n items: {\n type: \"array\",\n items: {},\n minItems: 3,\n maxItems: 3,\n },\n },\n description: \"Advanced OR groups (AND within, OR across groups)\",\n },\n orderBy: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n field: { type: \"string\" },\n direction: { type: \"string\", enum: [\"asc\", \"desc\"] },\n },\n required: [\"field\"],\n },\n },\n select: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"Fields to select (projection)\",\n },\n pageSize: {\n type: \"integer\",\n minimum: 1,\n maximum: 1000,\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 withTotal: {\n type: \"boolean\",\n description:\n \"Include total document count (totalCount and totalCountIsExact) in response\",\n },\n },\n };\n}\n\n/** Build a strongly-typed OpenAPI QueryRequestBody schema tailored to a CrudRepoEntry */\nfunction buildTypedQueryBodySchema(entry: CrudRepoEntry): Record<string, unknown> {\n const leafFields = getFilterableLeafFields(entry);\n const orderableFieldNames =\n entry.orderableFields ?? leafFields.map((f) => f.path);\n const leafFieldNames = leafFields.map((f) => f.path);\n\n if (leafFields.length === 0) {\n return queryBodySchema();\n }\n\n const whereTuples: Record<string, unknown>[] = [];\n\n for (const { path, zodSchema } of leafFields) {\n const valSchema = zodTypeToJsonValueSchema(zodSchema);\n const unwrapped = unwrapZodType(zodSchema);\n\n const isArrayType =\n (unwrapped as any)?._zod?.def?.type === \"array\" ||\n (unwrapped as any)?._def?.typeName === \"ZodArray\" ||\n (unwrapped as any)?._def?.type === \"array\";\n\n const elemSchema = isArrayType\n ? zodTypeToJsonValueSchema(\n (unwrapped as any)?._zod?.def?.element ??\n (unwrapped as any)?._def?.type ??\n (unwrapped as any)?._def?.element,\n )\n : valSchema;\n\n // Standard comparison operators (==, !=, <, <=, >, >=)\n whereTuples.push({\n type: \"array\",\n description: `Condition on '${path}'`,\n prefixItems: [\n { type: \"string\", enum: [path] },\n {\n type: \"string\",\n enum: [\"==\", \"!=\", \"<\", \"<=\", \">\", \">=\", \"eq\", \"ne\", \"lt\", \"lte\", \"gt\", \"gte\"],\n },\n valSchema,\n ],\n minItems: 3,\n maxItems: 3,\n });\n\n // List operators (in, not-in)\n whereTuples.push({\n type: \"array\",\n description: `List condition on '${path}' (in, not-in)`,\n prefixItems: [\n { type: \"string\", enum: [path] },\n { type: \"string\", enum: [\"in\", \"not-in\", \"nin\"] },\n { type: \"array\", items: valSchema },\n ],\n minItems: 3,\n maxItems: 3,\n });\n\n // Array contains operators\n whereTuples.push({\n type: \"array\",\n description: `Array contains condition on '${path}'`,\n prefixItems: [\n { type: \"string\", enum: [path] },\n { type: \"string\", enum: [\"array-contains\", \"contains\"] },\n elemSchema,\n ],\n minItems: 3,\n maxItems: 3,\n });\n\n whereTuples.push({\n type: \"array\",\n description: `Array contains-any condition on '${path}'`,\n prefixItems: [\n { type: \"string\", enum: [path] },\n { type: \"string\", enum: [\"array-contains-any\", \"containsAny\"] },\n { type: \"array\", items: elemSchema },\n ],\n minItems: 3,\n maxItems: 3,\n });\n }\n\n const whereItemSchema = {\n oneOf: whereTuples,\n };\n\n return {\n type: \"object\",\n properties: {\n where: {\n type: \"array\",\n items: whereItemSchema,\n description: \"AND conditions: [field, operator, value][]\",\n },\n orWhere: {\n type: \"array\",\n items: whereItemSchema,\n description: \"Simple OR conditions (each independently OR'd)\",\n },\n orWhereGroups: {\n type: \"array\",\n items: {\n type: \"array\",\n items: whereItemSchema,\n },\n description: \"Advanced OR groups (AND within, OR across groups)\",\n },\n orderBy: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n field: { type: \"string\", enum: orderableFieldNames },\n direction: { type: \"string\", enum: [\"asc\", \"desc\"] },\n },\n required: [\"field\"],\n },\n },\n select: {\n type: \"array\",\n items: { type: \"string\", enum: leafFieldNames },\n description: \"Fields to select (projection)\",\n },\n pageSize: {\n type: \"integer\",\n minimum: 1,\n maximum: 1000,\n description: \"Number of items per page\",\n },\n cursor: {\n oneOf: [{ type: \"string\" }, { type: \"object\" }],\n description: \"Pagination cursor\",\n },\n direction: {\n type: \"string\",\n enum: [\"next\", \"prev\"],\n description: \"Pagination direction\",\n },\n includes: {\n type: \"array\",\n items:\n entry.allowedIncludes && entry.allowedIncludes.length > 0\n ? {\n oneOf: [\n { type: \"string\", enum: entry.allowedIncludes },\n {\n type: \"object\",\n properties: {\n relation: { type: \"string\", enum: entry.allowedIncludes },\n select: { type: \"array\", items: { type: \"string\" } },\n },\n required: [\"relation\"],\n },\n ],\n }\n : {\n oneOf: [\n { type: \"string\" },\n {\n type: \"object\",\n properties: {\n relation: { type: \"string\" },\n select: { type: \"array\", items: { type: \"string\" } },\n },\n required: [\"relation\"],\n },\n ],\n },\n description: \"Relations to include (populate)\",\n },\n withTotal: {\n type: \"boolean\",\n description:\n \"Include total document count (totalCount and totalCountIsExact) in response\",\n },\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// History audit header parameters (auto-detected per repo)\n// ---------------------------------------------------------------------------\n\nfunction resolveEntryHistoryFlags(\n entry: CrudRepoEntry,\n): { reason: boolean; comment: boolean } | null {\n if (entry.historyHeaders) {\n return entry.historyHeaders;\n }\n const historyConfig = (entry.repo as any)?._historyConfig;\n if (!historyConfig?.enabled || historyConfig.autoInjectMeta === false) {\n return null;\n }\n const shadow = resolveShadowConfig(historyConfig);\n if (!shadow) return null;\n return {\n reason: shadow.fields.reason !== false,\n comment: shadow.fields.comment !== false,\n };\n}\n\nfunction buildHistoryHeaderParams(\n entry: CrudRepoEntry,\n historyHeadersOpt: false | OpenAPIHistoryHeadersConfig | undefined,\n): Record<string, unknown>[] {\n if (historyHeadersOpt === false) return [];\n const flags = resolveEntryHistoryFlags(entry);\n if (!flags) return [];\n\n const reasonHeader =\n historyHeadersOpt?.reasonHeader === undefined\n ? DEFAULT_HISTORY_REASON_HEADER\n : historyHeadersOpt.reasonHeader;\n const commentHeader =\n historyHeadersOpt?.commentHeader === undefined\n ? DEFAULT_HISTORY_COMMENT_HEADER\n : historyHeadersOpt.commentHeader;\n\n const params: Record<string, unknown>[] = [];\n const seenLower = new Set<string>();\n\n if (flags.reason && typeof reasonHeader === \"string\" && reasonHeader.trim()) {\n const name = reasonHeader.trim();\n seenLower.add(name.toLowerCase());\n params.push({\n name,\n in: \"header\",\n required: false,\n schema: { type: \"string\" },\n description: \"Optional reason recorded in the document's change history\",\n });\n }\n\n if (flags.comment && typeof commentHeader === \"string\" && commentHeader.trim()) {\n const name = commentHeader.trim();\n if (!seenLower.has(name.toLowerCase())) {\n seenLower.add(name.toLowerCase());\n params.push({\n name,\n in: \"header\",\n required: false,\n schema: { type: \"string\" },\n description: \"Optional comment recorded in the document's change history\",\n });\n }\n }\n\n if (historyHeadersOpt?.extraHeaders?.length) {\n for (const extra of historyHeadersOpt.extraHeaders) {\n const spec = typeof extra === \"string\" ? { name: extra } : extra;\n const name = spec?.name?.trim();\n if (!name || seenLower.has(name.toLowerCase())) continue;\n seenLower.add(name.toLowerCase());\n params.push({\n name,\n in: \"header\",\n required: spec.required ?? false,\n schema: spec.schema ?? { type: \"string\" },\n ...(spec.description ? { description: spec.description } : {}),\n });\n }\n }\n\n return params;\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 patchSchemaName: string | null = null,\n querySchemaName: string = \"QueryRequestBody\",\n historyHeaderParams: Record<string, unknown>[] = [],\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 // ── POST /:repo → create ────────────────────────────────────────\n paths[collectionPath] = {\n post: {\n operationId: `create${capitalize(entry.name)}`,\n summary: `Create a ${singularize(entry.name)}`,\n tags: [tag],\n ...(historyHeaderParams.length > 0\n ? { parameters: [...historyHeaderParams] }\n : {}),\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 \"403\": errorResponse(\"Forbidden\"),\n \"500\": errorResponse(\"Internal server error\"),\n },\n },\n };\n\n // ── POST /:repo/query → advanced query ────────────────────────────\n paths[`${collectionPath}/query`] = {\n post: {\n operationId: `query${capitalize(entry.name)}`,\n summary: `Query ${entry.name} with advanced filters`,\n tags: [tag],\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: schemaRef(querySchemaName),\n },\n },\n },\n responses: {\n \"200\": listResponse(schemaRef(modelSchemaName)),\n \"400\": errorResponse(\"Invalid query\"),\n \"403\": errorResponse(\"Forbidden\"),\n \"424\": errorResponse(\"Missing composite index (includes indexUrl in response)\"),\n \"500\": errorResponse(\"Internal server error\"),\n },\n },\n };\n\n // ── POST /:repo/batch → batch operations ─────────────────────────\n paths[`${collectionPath}/batch`] = {\n post: {\n operationId: `batch${capitalize(entry.name)}`,\n summary: `Execute batch operations on ${entry.name}`,\n tags: [tag],\n ...(historyHeaderParams.length > 0\n ? { parameters: [...historyHeaderParams] }\n : {}),\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: schemaRef(`${modelSchemaName}BatchRequest`),\n },\n },\n },\n responses: {\n \"200\": successResponse(\"Batch operations completed\", {\n type: \"object\",\n properties: {\n results: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n op: { type: \"string\" },\n id: { type: \"string\" },\n },\n },\n },\n },\n }),\n \"400\": errorResponse(\"Validation error\"),\n \"403\": errorResponse(\"Forbidden\"),\n \"404\": errorResponse(\"Document not found\"),\n \"500\": errorResponse(\"Internal server error\"),\n },\n },\n };\n\n // ── Single-document paths ────────────────────────────────────────\n const docOps: Record<string, OpenAPIOperation> = {};\n\n // GET /:repo/:id\n docOps.get = {\n operationId: `get${capitalize(singularize(entry.name))}`,\n summary: `Get a single ${singularize(entry.name)}`,\n tags: [tag],\n parameters: [idParam],\n responses: {\n \"200\": successResponse(\"Document found\", schemaRef(modelSchemaName)),\n \"400\": errorResponse(\"Document ID required\"),\n \"403\": errorResponse(\"Forbidden\"),\n \"404\": errorResponse(\"Document not found\"),\n \"424\": errorResponse(\"Missing composite index (includes indexUrl in response)\"),\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, ...historyHeaderParams],\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 \"403\": errorResponse(\"Forbidden\"),\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, ...historyHeaderParams],\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: schemaRef(patchSchemaName ?? updateSchemaName ?? modelSchemaName),\n },\n },\n },\n responses: {\n \"200\": successResponse(\"Document patched\", schemaRef(modelSchemaName)),\n \"400\": errorResponse(\"Validation error\"),\n \"403\": errorResponse(\"Forbidden\"),\n \"404\": errorResponse(\"Document not found\"),\n \"500\": errorResponse(\"Internal server error\"),\n },\n };\n\n // 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 \"400\": errorResponse(\"Document ID required\"),\n \"403\": errorResponse(\"Forbidden\"),\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\", description: \"Human-readable error description\" },\n errorType: {\n type: \"string\",\n enum: [\"index\"],\n description: \"Error category discriminator. Set to 'index' when a Firestore composite index is missing.\",\n },\n indexUrl: {\n type: \"string\",\n format: \"uri\",\n description: \"Direct Firebase Console URL to create the required composite index (when errorType is 'index').\",\n },\n },\n required: [\"success\", \"error\"],\n };\n\n schemas[\"QueryRequestBody\"] = queryBodySchema();\n\n // Per-repo schemas & paths\n for (const [name, entry] of Object.entries(registry)) {\n const modelName = capitalize(singularize(name));\n const createName = `${modelName}Create`;\n const updateName = `${modelName}Update`;\n const patchName = `${modelName}Patch`;\n const queryName = `${modelName}QueryRequestBody`;\n\n // Full model schema\n schemas[modelName] = zodToJsonSchema(entry.schema);\n\n // Per-repository typed QueryRequestBody schema\n schemas[queryName] = buildTypedQueryBodySchema(entry);\n\n // Helper: build a filtered shape (respects systemKeys + field list)\n const buildShape = (\n fieldList: string[] | undefined,\n ): Record<string, z.ZodType> => {\n const shape: Record<string, z.ZodType> = {};\n const leafFields = extractLeafFields(entry.schema);\n\n for (const { path: fieldPath, zodSchema: fieldSchema } of leafFields) {\n const top = fieldPath.split(\".\")[0]!;\n if (\n entry.systemKeys.includes(top) ||\n entry.systemKeys.includes(fieldPath)\n ) {\n continue;\n }\n if (fieldList && fieldList.length > 0) {\n if (!fieldList.includes(fieldPath) && !fieldList.includes(top)) {\n continue;\n }\n }\n if (fieldPath.includes(\".\")) {\n shape[fieldPath] = fieldSchema.optional();\n } else {\n shape[fieldPath] = fieldSchema;\n }\n }\n return shape;\n };\n\n // Create schema\n let createSchemaName: string | null = null;\n const createShape = buildShape(entry.createFields);\n if (entry.isGroup && entry.parentKeys && entry.parentKeys.length > 0) {\n const schemaShape = (entry.schema as any)?.shape ?? {};\n for (const pk of entry.parentKeys) {\n if (!createShape[pk] && schemaShape[pk]) {\n createShape[pk] = schemaShape[pk];\n }\n }\n }\n if (Object.keys(createShape).length > 0) {\n const createJsonSchema = zodToJsonSchema(z.object(createShape));\n if (entry.isGroup && entry.parentKeys && entry.parentKeys.length > 0) {\n const reqSet = new Set<string>(\n Array.isArray(createJsonSchema.required)\n ? createJsonSchema.required\n : [],\n );\n for (const pk of entry.parentKeys) {\n if ((createJsonSchema.properties as Record<string, unknown> | undefined)?.[pk]) {\n reqSet.add(pk);\n }\n }\n if (reqSet.size > 0) {\n createJsonSchema.required = Array.from(reqSet);\n }\n }\n schemas[createName] = createJsonSchema;\n createSchemaName = createName;\n }\n\n // Update & Patch schemas\n let updateSchemaName: string | null = null;\n let patchSchemaName: string | null = null;\n const updateShape = buildShape(entry.mutableFields);\n if (Object.keys(updateShape).length > 0) {\n const updateZodObj = z.object(updateShape);\n schemas[updateName] = zodToJsonSchema(updateZodObj);\n updateSchemaName = updateName;\n schemas[patchName] = zodToJsonSchema(makeDeepPartial(updateZodObj));\n patchSchemaName = patchName;\n } else {\n schemas[patchName] = zodToJsonSchema(makeDeepPartial(entry.schema));\n patchSchemaName = patchName;\n }\n\n // Batch schema\n const createOpName = `${modelName}BatchCreateOperation`;\n const updateOpName = `${modelName}BatchUpdateOperation`;\n const deleteOpName = `${modelName}BatchDeleteOperation`;\n\n schemas[createOpName] = {\n type: \"object\",\n title: `${modelName} Create Operation`,\n properties: {\n type: { type: \"string\", enum: [\"create\"], const: \"create\" },\n data: schemaRef(createSchemaName ?? modelName),\n },\n required: [\"type\", \"data\"],\n };\n\n schemas[updateOpName] = {\n type: \"object\",\n title: `${modelName} Update Operation`,\n properties: {\n type: { type: \"string\", enum: [\"update\"], const: \"update\" },\n id: { type: \"string\" },\n data: schemaRef(patchSchemaName ?? updateSchemaName ?? modelName),\n },\n required: [\"type\", \"id\", \"data\"],\n };\n\n if (entry.allowDelete) {\n schemas[deleteOpName] = {\n type: \"object\",\n title: `${modelName} Delete Operation`,\n properties: {\n type: { type: \"string\", enum: [\"delete\"], const: \"delete\" },\n id: { type: \"string\" },\n },\n required: [\"type\", \"id\"],\n };\n }\n\n schemas[`${modelName}BatchRequest`] = {\n type: \"object\",\n properties: {\n operations: {\n type: \"array\",\n items: {\n oneOf: [\n schemaRef(createOpName),\n schemaRef(updateOpName),\n ...(entry.allowDelete ? [schemaRef(deleteOpName)] : []),\n ],\n discriminator: {\n propertyName: \"type\",\n },\n },\n },\n },\n required: [\"operations\"],\n };\n\n // Build paths\n const historyHeaderParams = buildHistoryHeaderParams(\n entry,\n options.historyHeaders,\n );\n const entryPaths = buildPathsForEntry(\n entry,\n base,\n modelName,\n createSchemaName,\n updateSchemaName,\n patchSchemaName,\n queryName,\n historyHeaderParams,\n );\n Object.assign(allPaths, entryPaths);\n\n // Tag\n tags.push({\n name,\n description: `Operations on ${name} (collection: ${entry.path})`,\n });\n }\n\n\n // ── Security ──────────────────────────────────────────────────────\n const securitySchemes: Record<string, Record<string, unknown>> = {};\n let security: Record<string, string[]>[] | undefined;\n\n if (auth === \"basic\") {\n securitySchemes[\"basicAuth\"] = {\n type: \"http\",\n scheme: \"basic\",\n };\n security = [{ basicAuth: [] }];\n } else if (auth === \"bearer\") {\n securitySchemes[\"bearerAuth\"] = {\n type: \"http\",\n scheme: \"bearer\",\n bearerFormat: \"JWT\",\n };\n security = [{ bearerAuth: [] }];\n }\n\n // ── Assemble ──────────────────────────────────────────────────────\n const doc: OpenAPIDocument = {\n openapi: \"3.1.0\",\n info: {\n title,\n version,\n ...(description ? { description } : {}),\n },\n ...(servers && servers.length > 0 ? { servers } : {}),\n paths: allPaths,\n components: {\n schemas,\n ...(Object.keys(securitySchemes).length > 0 ? { securitySchemes } : {}),\n },\n ...(security ? { security } : {}),\n tags,\n };\n\n return doc;\n}\n\n// ---------------------------------------------------------------------------\n// Utility\n// ---------------------------------------------------------------------------\n\nfunction capitalize(s: string): string {\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n\n/** Naive singularize: strip trailing 's' for display. */\nfunction singularize(s: string): string {\n if (s.endsWith(\"ies\")) return s.slice(0, -3) + \"y\";\n if (s.endsWith(\"ses\") || s.endsWith(\"xes\") || s.endsWith(\"zes\"))\n return s.slice(0, -2);\n if (s.endsWith(\"s\") && !s.endsWith(\"ss\")) return s.slice(0, -1);\n return s;\n}\n","/**\n * Public types for the Hono file-based API server.\n *\n * Designed to be:\n * - **fully typed** end-to-end (Zod input/output → handler payload type),\n * - **runtime-safe** via Zod parsing on every request,\n * - **bundle-friendly** for Firebase Cloud Functions v2 cold-start (codegen\n * emits static imports — no `fs`/`import()` at runtime).\n */\n\nimport type { z, ZodError } from \"zod\";\nimport type { Context, Env, MiddlewareHandler } from \"hono\";\nimport type { AnyServicesContainer } from \"./services\";\nimport type { DocsAuthExtension } from \"./docs-auth\";\nimport type { ActorResolverOption } from \"../../shared/actor-context\";\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 * Optional resolver (function or declarative field config) used to extract\n * the authenticated actor from the Hono `Context` for automatic history\n * shadow metadata injection. Defaults to {@link defaultActorResolver}\n * (`c.get(\"user\") ?? c.get(\"docsUser\")`).\n */\n actorResolver?: ActorResolverOption;\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 getOpenApiMetadata,\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\n/**\n * Recursively walks a Zod schema graph and ensures any `z.custom()` / `z.instanceof()`\n * node (`def.type === \"custom\"`) has a `type` entry in its metadata.\n * Without this, `@asteasolutions/zod-to-openapi` throws `UnknownZodTypeError` when a\n * custom schema (e.g. Firestore `Timestamp` or `GeoPoint`) either lacks `.openapi(...)`\n * or only specifies `{ anyOf: [...] }` / `{ oneOf: [...] }` without a top-level `type`.\n */\nfunction ensureCustomSchemasHaveOpenApiType(\n schema: unknown,\n visited = new Set<unknown>(),\n): void {\n if (!schema || typeof schema !== \"object\" || visited.has(schema)) return;\n visited.add(schema);\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const s = schema as any;\n const def = s._zod?.def ?? s.def;\n if (!def) return;\n\n if (def.type === \"custom\") {\n const meta = getOpenApiMetadata(s) as Record<string, unknown> | undefined;\n if (!meta?.type) {\n z.globalRegistry.add(s, { ...(meta ?? {}), type: \"object\" });\n }\n return;\n }\n\n if (def.innerType) ensureCustomSchemasHaveOpenApiType(def.innerType, visited);\n if (def.element) ensureCustomSchemasHaveOpenApiType(def.element, visited);\n if (def.valueType) ensureCustomSchemasHaveOpenApiType(def.valueType, visited);\n if (def.keyType) ensureCustomSchemasHaveOpenApiType(def.keyType, visited);\n if (def.left) ensureCustomSchemasHaveOpenApiType(def.left, visited);\n if (def.right) ensureCustomSchemasHaveOpenApiType(def.right, visited);\n if (def.in) ensureCustomSchemasHaveOpenApiType(def.in, visited);\n if (def.out) ensureCustomSchemasHaveOpenApiType(def.out, visited);\n if (typeof def.getter === \"function\") {\n try {\n ensureCustomSchemasHaveOpenApiType(def.getter(), visited);\n } catch {\n // ignore lazy evaluation errors\n }\n }\n if (Array.isArray(def.options)) {\n for (const opt of def.options) ensureCustomSchemasHaveOpenApiType(opt, visited);\n }\n if (Array.isArray(def.items)) {\n for (const item of def.items) ensureCustomSchemasHaveOpenApiType(item, visited);\n }\n const shape = typeof def.shape === \"function\" ? def.shape() : def.shape;\n if (shape && typeof shape === \"object\") {\n for (const val of Object.values(shape)) {\n ensureCustomSchemasHaveOpenApiType(val, visited);\n }\n }\n}\n\n/**\n * Recursively strips top-level `type` on schema nodes that also define `anyOf` or `oneOf`\n * (preventing OpenAPI 3.1 generator conflicts when a fallback `type: \"object\"` was injected).\n */\nfunction stripRedundantTypeWithComposition(node: unknown): void {\n if (!node || typeof node !== \"object\") return;\n if (Array.isArray(node)) {\n for (const item of node) stripRedundantTypeWithComposition(item);\n return;\n }\n const record = node as Record<string, unknown>;\n if ((Array.isArray(record.anyOf) || Array.isArray(record.oneOf)) && \"type\" in record) {\n delete record.type;\n }\n for (const val of Object.values(record)) {\n stripRedundantTypeWithComposition(val);\n }\n}\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 if (route.input) ensureCustomSchemasHaveOpenApiType(route.input);\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 if (successSchema) ensureCustomSchemasHaveOpenApiType(successSchema);\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 if (schema) ensureCustomSchemasHaveOpenApiType(schema);\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 stripRedundantTypeWithComposition(document);\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 { createActorContextMiddleware } from \"../../shared/actor-context\";\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 actor-context middleware VERY FIRST so AsyncLocalStorage\n // captures the Hono Context before any auth/user middleware runs; actor\n // resolution runs lazily at Firestore write time after auth populates c.get(\"user\").\n this.app.use(\"*\", createActorContextMiddleware(options.actorResolver));\n\n // Install the request-context middleware so the built-in `ctx` service\n // resolves to the current request before any user middleware / handler runs.\n if (options.services) {\n this.app.use(\"*\", createRequestContextMiddleware());\n }\n\n const globalMws = [\n ...(options.middlewares ?? []),\n ...(options.globalMiddlewares ?? []),\n ];\n for (const mw of globalMws) this.app.use(\"*\", mw);\n\n this.mountRoutes();\n this.mountOpenApi();\n\n if (options.notFound) this.app.notFound(options.notFound);\n if (options.onError) this.app.onError(options.onError);\n }\n\n /** Underlying Hono instance — useful for advanced composition / tests. */\n get hono(): Hono<TEnv> {\n return this.app;\n }\n\n /** Raw `(req, res)` handler suitable for `onRequest()` / `http.createServer`. */\n get nodeHandler(): (req: IncomingMessage, res: ServerResponse) => void {\n return getRequestListener(this.app.fetch, {\n overrideGlobalObjects: false,\n });\n }\n\n /**\n * Wrap the server as a Cloud Functions v2 HTTP function.\n *\n * @param onRequest The `onRequest` factory imported from\n * `firebase-functions/v2/https` (or `firebase-functions/https`).\n * @param httpsOptions Options forwarded as the first argument to\n * `onRequest()` (region, memory, invoker, etc.).\n */\n toFunction(onRequest: OnRequestFn, httpsOptions?: HttpsOptions) {\n const handler = this.nodeHandler;\n if (httpsOptions) {\n return onRequest(httpsOptions, handler);\n }\n return onRequest(handler);\n }\n\n /** Generate (and cache) the OpenAPI 3.1 spec for the mounted routes. */\n buildOpenApiSpec(): Record<string, unknown> {\n if (this.cachedSpec) return this.cachedSpec;\n if (!this.options.openapi) {\n throw new Error(\"[HonoServer] openapi config not set\");\n }\n this.cachedSpec = buildOpenApiDocument(\n this.mountedRoutes,\n this.options.basePath ?? \"\",\n this.options.openapi,\n interceptorConfig(this.options.interceptor as InterceptorOption | undefined),\n );\n return this.cachedSpec;\n }\n\n // ── Internals ─────────────────────────────────────────────────────────\n\n private mountRoutes(): void {\n const basePath = this.options.basePath ?? \"\";\n const validateOutput = this.options.validateOutput ?? false;\n const verbose = this.options.verbose ?? false;\n\n for (const route of this.mountedRoutes) {\n if (!route.path) {\n throw new Error(\n `[HonoServer] route \"${route.method.toUpperCase()} (no path)\" — missing \\`path\\`. ` +\n \"Run the codegen so the path is derived from the file location, or set it explicitly.\",\n );\n }\n\n const fullPath = joinPath(basePath, route.path);\n const middlewares = route.middlewares ?? [];\n const source: PayloadSource =\n route.source ?? (route.method === \"get\" ? \"query\" : \"json\");\n\n const handler = makeRouteHandler(\n route,\n source,\n validateOutput,\n interceptorFn(this.options.interceptor as InterceptorOption | undefined),\n this.options.services,\n this.options.errorHandler as ErrorHandler | undefined,\n this.options.logger as Logger | undefined,\n );\n const httpMethod = route.method.toUpperCase() as\n | \"GET\"\n | \"POST\"\n | \"PUT\"\n | \"PATCH\"\n | \"DELETE\";\n // `app.on(method, path, handlers[])` accepts a variadic array of\n // handlers/middlewares — the typed `.get/.post/...` overloads don't\n // accept a spread of generic `MiddlewareHandler[]`.\n this.app.on(\n httpMethod,\n [fullPath],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...([...middlewares, handler] as any[]),\n );\n\n if (verbose) {\n // eslint-disable-next-line no-console\n console.log(\n `[HonoServer] ${route.method.toUpperCase().padEnd(6)} ${fullPath}`,\n );\n }\n }\n }\n\n private mountOpenApi(): void {\n const cfg = this.options.openapi;\n if (!cfg) return;\n const specPath = cfg.path ?? \"/openapi.json\";\n const docsPath = cfg.docsPath === undefined ? \"/docs\" : cfg.docsPath;\n const fullSpecPath = joinPath(this.options.basePath ?? \"\", specPath);\n const fullDocsPath =\n docsPath === false ? null : joinPath(this.options.basePath ?? \"\", docsPath);\n\n // Auth guards applied ONLY to the spec + docs endpoints (not API routes).\n // A DocsAuthExtension (e.g. firebaseDocsAuth) also contributes auxiliary\n // routes (login page / session / logout) mounted next to the docs.\n let guards: MiddlewareHandler[];\n if (isDocsAuthExtension(cfg.docsAuth)) {\n const ext = cfg.docsAuth;\n guards = [ext.middleware];\n // Mount the aux routes (unguarded) as siblings of the docs/spec page so\n // bare-name relative links/redirects stay correct behind any prefix.\n const authDir = dirOf(fullDocsPath ?? fullSpecPath);\n for (const route of ext.routes) {\n this.app.on(\n route.method,\n [joinPath(authDir, route.name)],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n route.handler as any,\n );\n }\n } else {\n guards = cfg.docsAuth\n ? Array.isArray(cfg.docsAuth)\n ? cfg.docsAuth\n : [cfg.docsAuth]\n : [];\n }\n\n this.app.on(\n \"GET\",\n [fullSpecPath],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...([...guards, (c: any) => c.json(this.buildOpenApiSpec())] as any[]),\n );\n\n if (fullDocsPath) {\n // Resolve the spec URL relative to the docs page so it works whether the\n // server is mounted at `/`, behind a Firebase Functions prefix\n // (`/<project>/<region>/<funcName>/...`), or behind any reverse proxy.\n const relativeSpecUrl = relativeUrlFromTo(fullDocsPath, fullSpecPath);\n this.app.on(\n \"GET\",\n [fullDocsPath],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...([\n ...guards,\n (c: any) => c.html(renderDocsHtml(relativeSpecUrl, cfg.info.title)),\n ] as any[]),\n );\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** Type guard distinguishing a structured interceptor from a bare function. */\nfunction isInterceptorConfig(\n i: InterceptorOption | undefined,\n): i is InterceptorConfig {\n return typeof i === \"object\" && i !== null && typeof i.handler === \"function\";\n}\n\n/** Extract the runtime interceptor function from either form. */\nfunction interceptorFn(\n i: InterceptorOption | undefined,\n): RouteInterceptor | undefined {\n if (!i) return undefined;\n return isInterceptorConfig(i) ? i.handler : i;\n}\n\n/** Extract the OpenAPI metadata (output/errors) from the structured form. */\nfunction interceptorConfig(\n i: InterceptorOption | undefined,\n): InterceptorConfig | undefined {\n return isInterceptorConfig(i) ? i : undefined;\n}\n\nfunction filterRoutes(\n routes: AnyRouteDef[],\n api: string | undefined,\n): AnyRouteDef[] {\n if (!api) return routes.slice();\n return routes.filter((r) =>\n Array.isArray(r.api) ? r.api.includes(api) : r.api === api,\n );\n}\n\nfunction joinPath(base: string, path: string): string {\n const left = base.endsWith(\"/\") ? base.slice(0, -1) : base;\n const right = path.startsWith(\"/\") ? path : `/${path}`;\n const merged = `${left}${right}`;\n return merged === \"\" ? \"/\" : merged;\n}\n\n/** Directory of an absolute pathname, e.g. `/v1/docs` → `/v1`, `/docs` → ``. */\nfunction dirOf(path: string): string {\n const idx = path.lastIndexOf(\"/\");\n return idx <= 0 ? \"\" : path.slice(0, idx);\n}\n\n/**\n * Compute a URL relative to `from` that points to `to`, both being absolute\n * pathnames (e.g. `/v1/docs` → `/v1/openapi.json` becomes `openapi.json`).\n * Lets the OpenAPI UI fetch the spec without knowing the upstream prefix\n * added by Firebase Functions / reverse proxies.\n */\nfunction relativeUrlFromTo(from: string, to: string): string {\n const fromSegs = from.split(\"/\").filter(Boolean);\n const toSegs = to.split(\"/\").filter(Boolean);\n // Drop the docs page filename so we resolve relative to its directory.\n fromSegs.pop();\n let common = 0;\n while (\n common < fromSegs.length &&\n common < toSegs.length &&\n fromSegs[common] === toSegs[common]\n ) {\n common++;\n }\n const ups = fromSegs.length - common;\n const rel = [\n ...Array(ups).fill(\"..\"),\n ...toSegs.slice(common),\n ].join(\"/\");\n return rel || \"./\";\n}\n\n/**\n * Build the actual Hono handler with input validation, output validation\n * (optional), and error normalisation.\n */\nfunction makeRouteHandler(\n route: AnyRouteDef,\n source: PayloadSource,\n validateOutput: boolean,\n interceptor: RouteInterceptor | undefined,\n services: AnyServicesContainer | undefined,\n errorHandler: ErrorHandler | undefined,\n logger: Logger | undefined,\n) {\n const inputSchema = route.input as z.ZodTypeAny | undefined;\n const outputSchema = route.output as z.ZodTypeAny | undefined;\n const status = route.status ?? 200;\n // Empty fallback so handlers/interceptors always see a `services` field\n // even when the server was started without a container.\n const servicesArg = (services ?? (EMPTY_SERVICES as AnyServicesContainer));\n\n return async (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n c: any,\n ): Promise<Response> => {\n // Apply the injected ErrorHandler, falling back to the built-in envelope.\n // Returns a Response when handled, or null to let the error propagate.\n const applyErrorHandler = async (err: unknown): Promise<Response | null> => {\n if (errorHandler) {\n const handled = await errorHandler.handle({\n error: err,\n c,\n route,\n services: servicesArg,\n logger,\n });\n if (handled) return handled;\n }\n return defaultErrorResponse(c, err);\n };\n\n // `next()` runs validation + handler. Any Zod failure throws\n // `ValidationError` so the interceptor (or default catcher) can shape it.\n const callNext = async (): Promise<unknown> => {\n let payload: unknown = undefined;\n\n // Always read payload if it's expected, even without an input schema.\n // E.g., generic handlers that manually validate the body.\n let raw: unknown;\n try {\n raw = await readPayload(c, source, route.method);\n } catch (err) {\n throw new BadRequestError(\n err instanceof Error ? err.message : String(err),\n );\n }\n\n if (inputSchema) {\n const parsed = inputSchema.safeParse(raw);\n if (!parsed.success) {\n throw new ValidationError(parsed.error, source);\n }\n payload = parsed.data;\n } else {\n payload = raw;\n }\n\n const result = await (route.handler as (ctx: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input: any;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n c: any;\n services: AnyServicesContainer;\n errorHandler: ErrorHandler | undefined;\n logger: Logger | undefined;\n }) => unknown)({\n input: payload,\n c,\n services: servicesArg,\n errorHandler,\n logger,\n });\n\n if (validateOutput && outputSchema && !(result instanceof Response)) {\n const checked = outputSchema.safeParse(result);\n if (!checked.success) {\n throw new OutputValidationError(checked.error);\n }\n return checked.data;\n }\n return result;\n };\n\n let result: unknown;\n if (interceptor) {\n // Interceptor owns the response shape — including validation errors.\n // If it rethrows, the injected ErrorHandler / default catcher applies.\n try {\n result = await interceptor({\n next: callNext,\n route,\n c,\n services: servicesArg,\n errorHandler,\n logger,\n });\n } catch (err) {\n const handled = await applyErrorHandler(err);\n if (handled) return handled;\n throw err;\n }\n } else {\n // Default behaviour — ErrorHandler first, then the built-in\n // ValidationError envelope, else bubble to onError / Hono.\n try {\n result = await callNext();\n } catch (err) {\n const handled = await applyErrorHandler(err);\n if (handled) return handled;\n throw err;\n }\n }\n\n if (result instanceof Response) return result;\n return c.json(result, status);\n };\n}\n\nasync function readPayload(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n c: any,\n source: PayloadSource,\n method: HttpMethod,\n): Promise<unknown> {\n switch (source) {\n case \"json\": {\n if (method === \"get\") return c.req.query();\n const text = await c.req.text();\n if (!text) return {};\n try {\n return JSON.parse(text);\n } catch (err) {\n throw new Error(\n `Invalid JSON body: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n case \"query\":\n return c.req.query();\n case \"form\": {\n const form = await c.req.parseBody();\n return form;\n }\n case \"param\":\n return c.req.param();\n default:\n return {};\n }\n}\n","/**\n * @module servers/crud/mutations\n *\n * Pre-write mutation engine for CRUD payload normalization and server-derived\n * field injection before persisting to Firestore.\n */\n\nimport type { AuthUser } from \"../auth\";\nimport { computeDeepDiff } from \"./rules\";\nimport type {\n CrudBeforeCreateContext,\n CrudBeforeUpdateContext,\n CrudWriteOperation,\n DeepDiffReturn,\n MutationsMap,\n PreWriteMutation,\n} from \"./types\";\n\n/**\n * Helper to define field-by-field (and wildcard `\"*\"`) pre-write mutations\n * with strong typing.\n */\nexport function createMutations<T>(\n mutations: MutationsMap<T>,\n): MutationsMap<T> {\n return mutations;\n}\n\nasync function runEntries<T>(\n entries: PreWriteMutation<T>[] | undefined,\n ctx: {\n body: Partial<T>;\n doc: T | null;\n diff: DeepDiffReturn<T>;\n key: keyof T | \"*\";\n operation: CrudWriteOperation;\n user?: AuthUser;\n },\n): Promise<void> {\n if (!entries?.length) return;\n for (const entry of entries) {\n if (typeof entry === \"function\") {\n await entry(ctx);\n } else if (entry && typeof entry.mutation === \"function\") {\n if (entry.operations && !entry.operations.includes(ctx.operation)) {\n continue;\n }\n await entry.mutation(ctx);\n }\n }\n}\n\n/**\n * Executes a map of pre-write mutations against `body` / `diff`:\n * 1. Runs per-field mutations for each key present in `diff.changes`.\n * 2. Runs wildcard `\"*\"` mutations unconditionally after per-field mutations.\n */\nexport async function applyMutations<T>(\n body: Partial<T>,\n doc: T | null,\n diff: DeepDiffReturn<T>,\n mutationsMap: MutationsMap<T>,\n user?: AuthUser,\n operation: CrudWriteOperation = doc ? \"update\" : \"create\",\n): Promise<void> {\n for (const key of Object.keys(diff.changes) as (keyof T)[]) {\n await runEntries(mutationsMap[key], {\n body,\n doc,\n diff,\n key,\n operation,\n user,\n });\n }\n await runEntries(mutationsMap[\"*\"], {\n body,\n doc,\n diff,\n key: \"*\",\n operation,\n user,\n });\n}\n\n/**\n * Wraps a {@link MutationsMap} into a `hooks.beforeUpdate` handler\n * (analogous to `createBeforeRules`).\n */\nexport function createBeforeUpdateMutations<T>(\n mutationsMap: MutationsMap<T>,\n): (ctx: CrudBeforeUpdateContext<T>) => Promise<void> {\n return async (ctx: CrudBeforeUpdateContext<T>): Promise<void> => {\n await applyMutations(\n ctx.body,\n ctx.doc,\n ctx.diff,\n mutationsMap,\n ctx.user,\n \"update\",\n );\n };\n}\n\n/**\n * Wraps a {@link MutationsMap} into a `hooks.beforeCreate` handler\n * (analogous to `createBeforeRules`).\n */\nexport function createBeforeCreateMutations<T>(\n mutationsMap: MutationsMap<T>,\n): (ctx: CrudBeforeCreateContext<T>) => Promise<void> {\n return async (ctx: CrudBeforeCreateContext<T>): Promise<void> => {\n const diff = computeDeepDiff(\n {} as Record<string, unknown>,\n ctx.body as Record<string, unknown>,\n ) as DeepDiffReturn<T>;\n await applyMutations(\n ctx.body,\n null,\n diff,\n mutationsMap,\n ctx.user,\n \"create\",\n );\n };\n}\n","/**\n * @module servers/crud/effects\n *\n * Reactive post-write effects engine aligned with `rules.ts` / `mutations.ts`.\n * Evaluates field-level and wildcard `\"*\"` effect rules against a recomputed diff,\n * captures per-rule errors without aborting sibling effects, and aggregates\n * optional follow-up document patches (`changesNeeded`).\n */\n\nimport type { AuthUser } from \"../auth\";\nimport type {\n ApplyEffectsResult,\n CrudAfterUpdateContext,\n CrudEffectOperation,\n DeepDiffReturn,\n EffectExecutionResult,\n EffectsMap,\n RuleEffect,\n} from \"./types\";\n\n/**\n * Helper to define field-by-field (and wildcard `\"*\"`) post-write effects\n * with strong typing.\n */\nexport function createEffects<T, TContext>(\n effects: EffectsMap<T, TContext>,\n): EffectsMap<T, TContext> {\n return effects;\n}\n\nasync function runEffectList<T, TContext>(\n rules: RuleEffect<T, TContext>[] | undefined,\n key: keyof T | \"*\",\n diff: DeepDiffReturn<T>,\n context: TContext,\n results: EffectExecutionResult[],\n changesNeeded: Partial<T>,\n user?: AuthUser,\n operation?: CrudEffectOperation,\n): Promise<Partial<T>> {\n if (!rules?.length) return changesNeeded;\n let merged = changesNeeded;\n\n for (const rule of rules) {\n let err: unknown = null;\n let isCalled = false;\n try {\n isCalled = Boolean(await rule.rule({ diff, key, user, operation }));\n if (isCalled) {\n const patch = await rule.handler(context);\n if (patch) merged = { ...merged, ...patch };\n }\n } catch (error) {\n err = error;\n }\n results.push({\n key: String(key),\n description: rule.description,\n isCalled,\n error: err,\n });\n }\n return merged;\n}\n\n/**\n * Executes a map of reactive effects against a computed `diff`:\n * 1. Runs per-field effects for every key in `diff.changes`.\n * 2. Runs wildcard `\"*\"` effects after per-field effects.\n *\n * Each effect is isolated in a `try/catch` so one failure never prevents\n * remaining effects from executing. Any `Partial<T>` patches returned by\n * handlers are merged into `changesNeeded`.\n */\nexport async function applyEffects<T, TContext>(\n diff: DeepDiffReturn<T>,\n effectsMap: EffectsMap<T, TContext>,\n context: TContext,\n user?: AuthUser,\n operation: CrudEffectOperation = \"update\",\n): Promise<ApplyEffectsResult<T>> {\n const results: EffectExecutionResult[] = [];\n let changesNeeded = {} as Partial<T>;\n\n for (const key of Object.keys(diff.changes) as (keyof T)[]) {\n changesNeeded = await runEffectList(\n effectsMap[key],\n key,\n diff,\n context,\n results,\n changesNeeded,\n user,\n operation,\n );\n }\n\n changesNeeded = await runEffectList(\n effectsMap[\"*\"],\n \"*\",\n diff,\n context,\n results,\n changesNeeded,\n user,\n operation,\n );\n\n return {\n results,\n changesNeeded,\n hasErrors: results.some((r) => r.error !== null),\n };\n}\n\n/**\n * Wraps an {@link EffectsMap} into a `hooks.afterUpdate` handler\n * (analogous to `createBeforeRules`).\n */\nexport function createAfterUpdateEffects<T, TContext>(\n effectsMap: EffectsMap<T, TContext>,\n buildContext: (ctx: CrudAfterUpdateContext<T>) => TContext,\n options?: {\n onRuleError?: (\n result: EffectExecutionResult,\n ctx: CrudAfterUpdateContext<T>,\n ) => void | Promise<void>;\n },\n): (ctx: CrudAfterUpdateContext<T>) => Promise<void | Partial<T>> {\n return async (\n ctx: CrudAfterUpdateContext<T>,\n ): Promise<void | Partial<T>> => {\n const context = buildContext(ctx);\n const { results, changesNeeded } = await applyEffects(\n ctx.diff,\n effectsMap,\n context,\n ctx.user,\n \"update\",\n );\n\n if (options?.onRuleError) {\n for (const r of results) {\n if (r.error) {\n await options.onRuleError(r, ctx);\n }\n }\n }\n\n return Object.keys(changesNeeded).length > 0 ? changesNeeded : undefined;\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 { resolveShadowConfig } from \"../../history/inject\";\nimport type { ConfiguredRepository } from \"../../repositories/types\";\nimport { getActorResolverHeaders } from \"../../shared/actor-context\";\nimport { createCrudHandlers } from \"./handlers\";\nimport { generateOpenAPISpec, type OpenAPIDocument } from \"./openapi\";\nimport type {\n CrudRepoEntry,\n CrudRepoRegistry,\n CrudServerOptions,\n OpenAPIHistoryHeadersConfig,\n} from \"./types\";\nimport { HonoServer } from \"../hono/server\";\nimport type { AnyRouteDef } from \"../hono/types\";\nimport { getLinkBase } from \"../utils/link-base\";\n\n\nexport function createCrudServer<\n TRepos extends Record<string, ConfiguredRepository<any>>,\n>(\n options: CrudServerOptions<TRepos>,\n): ((req: any, res: any) => Promise<void>) & { spec: () => OpenAPIDocument; httpsOptions?: HttpsOptions } {\n const {\n basePath = \"/\",\n repos,\n parseBody = true,\n securityHeaders: securityHeadersOpt,\n verbose = false,\n httpsOptions,\n } = options;\n\n const base = basePath === \"/\" ? \"\" : basePath.replace(/\\/$/, \"\");\n\n const registry: CrudRepoRegistry = {};\n for (const [name, cfg] of Object.entries(repos)) {\n if (!cfg.repo) {\n throw new Error(`[createCrudServer] Repository \"${name}\" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);\n }\n\n const resolvedSchema = cfg.schema ?? (cfg.repo as any).schema ?? null;\n if (!resolvedSchema) {\n throw new Error(`[createCrudServer] Repository \"${name}\" has no Zod schema.`);\n }\n\n let filterableFields: string[] | undefined;\n let orderableFields: string[] | undefined;\n let mutableFields: string[] | undefined;\n let createFields: string[] | undefined;\n if (cfg.fieldsConfig) {\n const fc = cfg.fieldsConfig as Record<string, readonly string[]>;\n filterableFields = [];\n orderableFields = [];\n mutableFields = [];\n createFields = [];\n for (const [field, roles] of Object.entries(fc)) {\n for (const role of roles) {\n if (role === \"filterable\") filterableFields.push(field);\n else if (role === \"orderable\") orderableFields.push(field);\n else if (role === \"mutable\") mutableFields.push(field);\n else if (role === \"create\") createFields.push(field);\n }\n }\n if (orderableFields.length === 0) orderableFields = filterableFields;\n if (filterableFields.length === 0) filterableFields = undefined;\n if (orderableFields && orderableFields.length === 0) orderableFields = undefined;\n if (mutableFields.length === 0) mutableFields = undefined;\n if (createFields.length === 0) createFields = undefined;\n }\n\n const parentKeys = (() => {\n const pk = (cfg.repo as any)._parentKeys as string[] | undefined;\n return pk && pk.length > 0 ? pk : undefined;\n })();\n if (parentKeys && createFields) {\n for (const pk of parentKeys) {\n if (!createFields.includes(pk)) createFields.push(pk);\n }\n }\n\n const baseSystemKeys: string[] = (cfg.repo as any)._systemKeys ?? [\n cfg.documentKey ?? \"docId\",\n ];\n const historyIdentityKeys: string[] =\n (cfg.repo as any)._historyIdentityKeys ?? [];\n const systemKeys = Array.from(\n new Set([...baseSystemKeys, ...historyIdentityKeys]),\n );\n\n const historyConfig = (cfg.repo as any)._historyConfig;\n const activeShadow =\n historyConfig?.enabled && historyConfig.autoInjectMeta !== false\n ? resolveShadowConfig(historyConfig)\n : null;\n const historyHeaders = activeShadow\n ? {\n reason: activeShadow.fields.reason !== false,\n comment: activeShadow.fields.comment !== false,\n }\n : undefined;\n\n const entry: CrudRepoEntry = {\n name,\n path: cfg.path,\n repo: cfg.repo,\n schema: resolvedSchema,\n systemKeys,\n documentKey: cfg.documentKey ?? \"docId\",\n pathKey: (cfg.repo as any)._pathKey ?? undefined,\n isGroup: !!(cfg.repo as any)._isGroup,\n parentKeys,\n documentPathTemplate:\n (cfg.repo as any)._documentPathTemplate ?? undefined,\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 hooks: cfg.hooks,\n ...(historyHeaders ? { historyHeaders } : {}),\n };\n\n registry[name] = entry;\n }\n\n const indexesErrorCb = options.indexesError ?? options.onIndexError;\n const handlers = createCrudHandlers(\n registry,\n base,\n verbose,\n indexesErrorCb,\n options.onHookError,\n );\n\n const openapi = options.openapi;\n const openapiOpts = openapi && typeof openapi === \"object\" ? openapi : {};\n const resolvedActorHeaders = getActorResolverHeaders(options.actorResolver);\n const effectiveOpenApiHistoryHeaders: false | OpenAPIHistoryHeadersConfig =\n openapiOpts.historyHeaders === false\n ? false\n : {\n reasonHeader:\n openapiOpts.historyHeaders?.reasonHeader !== undefined\n ? openapiOpts.historyHeaders.reasonHeader\n : resolvedActorHeaders.reasonHeader,\n commentHeader:\n openapiOpts.historyHeaders?.commentHeader !== undefined\n ? openapiOpts.historyHeaders.commentHeader\n : resolvedActorHeaders.commentHeader,\n ...(openapiOpts.historyHeaders?.extraHeaders\n ? { extraHeaders: openapiOpts.historyHeaders.extraHeaders }\n : {}),\n };\n\n // Build CORS Access-Control-Allow-Headers dynamically so custom actorResolver\n // header names & declared extraHeaders work seamlessly from browsers / Scalar UI.\n const corsAllowHeaders = (() => {\n const out: string[] = [\"Content-Type\", \"Authorization\"];\n const seen = new Set(out.map((h) => h.toLowerCase()));\n const addHeader = (h: string | false | undefined) => {\n if (typeof h !== \"string\") return;\n const trimmed = h.trim();\n if (!trimmed || seen.has(trimmed.toLowerCase())) return;\n seen.add(trimmed.toLowerCase());\n out.push(trimmed);\n };\n addHeader(resolvedActorHeaders.reasonHeader);\n addHeader(resolvedActorHeaders.commentHeader);\n if (\n openapiOpts.historyHeaders &&\n typeof openapiOpts.historyHeaders === \"object\"\n ) {\n addHeader(openapiOpts.historyHeaders.reasonHeader);\n addHeader(openapiOpts.historyHeaders.commentHeader);\n if (openapiOpts.historyHeaders.extraHeaders) {\n for (const extra of openapiOpts.historyHeaders.extraHeaders) {\n addHeader(typeof extra === \"string\" ? extra : extra?.name);\n }\n }\n }\n return out.join(\", \");\n })();\n\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 historyHeaders: effectiveOpenApiHistoryHeaders,\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: \"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\": corsAllowHeaders,\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 {\n applyRules,\n computeDeepDiff,\n createBeforeRules,\n createRules,\n} from \"./rules\";\nexport {\n applyMutations,\n createBeforeCreateMutations,\n createBeforeUpdateMutations,\n createMutations,\n} from \"./mutations\";\nexport {\n applyEffects,\n createAfterUpdateEffects,\n createEffects,\n} from \"./effects\";\nexport type {\n AnyCrudHooks,\n ApiResponse,\n ApplyEffectsResult,\n CrudAfterBatchContext,\n CrudAfterBatchCreatedItem,\n CrudAfterBatchDeletedItem,\n CrudAfterBatchUpdatedItem,\n CrudAfterCreateContext,\n CrudAfterDeleteContext,\n CrudAfterUpdateContext,\n CrudBeforeCreateContext,\n CrudBeforeUpdateContext,\n CrudEffectOperation,\n CrudHookErrorCallback,\n CrudHookErrorContext,\n CrudHookName,\n CrudHooks,\n CrudRepoConfig,\n CrudRepoEntry,\n CrudRepoRegistry,\n CrudRules,\n CrudServerOptions,\n CrudUpdateRuleContext,\n CrudWriteOperation,\n DeepDiffReturn,\n EffectExecutionResult,\n EffectPredicateArgs,\n EffectsMap,\n FieldRole,\n IndexErrorCallback,\n IndexErrorContext,\n ListResponseData,\n MutationContext,\n MutationRule,\n MutationsMap,\n OpenAPIHeaderParamSpec,\n OpenAPIHistoryHeadersConfig,\n PreWriteMutation,\n PreWriteMutationFn,\n QueryRequestBody,\n RepoFieldPath,\n RepoRelationKeys,\n Rule,\n RuleEffect,\n RuleResult,\n RulesMap,\n UserFieldPath,\n} from \"./types\";\n"]}