@lpdjs/firestore-repo-service 3.0.13 → 3.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/dist/actor-context-DQZgWqj3.d.cts +117 -0
  2. package/dist/actor-context-DQZgWqj3.d.ts +117 -0
  3. package/dist/{create-servers-LyRLAOh3.d.cts → create-servers-B5Z5v2SP.d.cts} +11 -5
  4. package/dist/{create-servers-Db1xUY2N.d.ts → create-servers-p1-jJNTG.d.ts} +11 -5
  5. package/dist/history/index.cjs +1 -1
  6. package/dist/history/index.cjs.map +1 -1
  7. package/dist/history/index.d.cts +67 -7
  8. package/dist/history/index.d.ts +67 -7
  9. package/dist/history/index.js +1 -1
  10. package/dist/history/index.js.map +1 -1
  11. package/dist/index.cjs +81 -81
  12. package/dist/index.cjs.map +1 -1
  13. package/dist/index.d.cts +20 -14
  14. package/dist/index.d.ts +20 -14
  15. package/dist/index.js +81 -81
  16. package/dist/index.js.map +1 -1
  17. package/dist/llms-full.txt +1 -1
  18. package/dist/llms.txt +1 -1
  19. package/dist/{openapi-QVpqnnes.d.cts → openapi-B9utXiEH.d.cts} +1 -1
  20. package/dist/{openapi-CNIA7QRw.d.ts → openapi-Bsqq2zgh.d.ts} +1 -1
  21. package/dist/{queue-BEB-ujA3.d.ts → queue-NFod6hTT.d.ts} +1 -1
  22. package/dist/{queue-CpHe6M5j.d.cts → queue-zw2B7GPx.d.cts} +1 -1
  23. package/dist/{read-15-TcgCz.d.ts → read-BPov7lws.d.ts} +30 -7
  24. package/dist/{read-B15YaPyR.d.cts → read-Dfah1PPl.d.cts} +30 -7
  25. package/dist/{rules-Cafrkb9v.d.ts → rules-18wH7Uak.d.ts} +1 -1
  26. package/dist/{rules-Bu2NB7Eb.d.cts → rules-oSXoV4Js.d.cts} +1 -1
  27. package/dist/servers/admin/index.cjs +5 -5
  28. package/dist/servers/admin/index.cjs.map +1 -1
  29. package/dist/servers/admin/index.d.cts +5 -4
  30. package/dist/servers/admin/index.d.ts +5 -4
  31. package/dist/servers/admin/index.js +5 -5
  32. package/dist/servers/admin/index.js.map +1 -1
  33. package/dist/servers/crud/index.cjs +2 -2
  34. package/dist/servers/crud/index.cjs.map +1 -1
  35. package/dist/servers/crud/index.d.cts +10 -9
  36. package/dist/servers/crud/index.d.ts +10 -9
  37. package/dist/servers/crud/index.js +2 -2
  38. package/dist/servers/crud/index.js.map +1 -1
  39. package/dist/servers/hono/index.cjs +14 -14
  40. package/dist/servers/hono/index.cjs.map +1 -1
  41. package/dist/servers/hono/index.d.cts +11 -3
  42. package/dist/servers/hono/index.d.ts +11 -3
  43. package/dist/servers/hono/index.js +14 -14
  44. package/dist/servers/hono/index.js.map +1 -1
  45. package/dist/servers/index.cjs +94 -94
  46. package/dist/servers/index.cjs.map +1 -1
  47. package/dist/servers/index.d.cts +13 -12
  48. package/dist/servers/index.d.ts +13 -12
  49. package/dist/servers/index.js +94 -94
  50. package/dist/servers/index.js.map +1 -1
  51. package/dist/sync/bigquery.d.cts +2 -2
  52. package/dist/sync/bigquery.d.ts +2 -2
  53. package/dist/sync/index.cjs +55 -55
  54. package/dist/sync/index.cjs.map +1 -1
  55. package/dist/sync/index.d.cts +6 -6
  56. package/dist/sync/index.d.ts +6 -6
  57. package/dist/sync/index.js +55 -55
  58. package/dist/sync/index.js.map +1 -1
  59. package/dist/sync/meilisearch.cjs +2 -2
  60. package/dist/sync/meilisearch.cjs.map +1 -1
  61. package/dist/sync/meilisearch.d.cts +2 -2
  62. package/dist/sync/meilisearch.d.ts +2 -2
  63. package/dist/sync/meilisearch.js +2 -2
  64. package/dist/sync/meilisearch.js.map +1 -1
  65. package/dist/{types-o-9qoExc.d.cts → types-BDTx8VPg.d.cts} +8 -0
  66. package/dist/{types-CNseHqF7.d.cts → types-BGh5_2fl.d.cts} +4 -4
  67. package/dist/{types-DGQURFSq.d.ts → types-B_FrzmO4.d.ts} +1 -1
  68. package/dist/{types-DmXW_fVz.d.ts → types-Cc6lelk1.d.ts} +4 -4
  69. package/dist/{types--RamYGF1.d.cts → types-D6zvWzRt.d.cts} +96 -2
  70. package/dist/{types--RamYGF1.d.ts → types-D6zvWzRt.d.ts} +96 -2
  71. package/dist/{types-VVuLlmfc.d.cts → types-D78FPJeF.d.cts} +1 -1
  72. package/dist/{types-B51LYvQZ.d.cts → types-Dc3lX99O.d.cts} +20 -19
  73. package/dist/{types-Ci0dGbuW.d.ts → types-DgFJLwAu.d.ts} +20 -19
  74. package/dist/{types-D3W_RaDA.d.ts → types-w1rEqs0Z.d.ts} +8 -0
  75. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/shared/path-template.ts","../../src/history/diff.ts","../../src/history/write.ts","../../src/history/triggers.ts","../../src/history/normalize.ts","../../src/history/read.ts"],"names":["extractSegmentParam","segment","parsePathTemplate","rawPath","documentKey","isGroup","segments","s","seg","isEvenSegments","collectionSegments","collectionId","collectionPath","parentKeys","p","documentPathTemplate","valueType","v","Timestamp","t","valuesEqual","a","b","seen","i","ka","kb","k","computeDiff","before","after","opts","excludeSet","includeSet","beforeObj","afterObj","keys","changes","key","oldValue","newValue","MAX_DOC_BYTES","buildHistoryEntry","params","ttl","entry","randomUUID","sizeOf","obj","_k","truncated","change","oldSize","newSize","writeHistoryEntry","historyRef","config","ctx","toWrite","extractMeta","source","src","meta","m","pickStr","userId","userEmail","reason","comment","extras","any","metaFieldsOf","list","DEFAULT_SUBCOLLECTION","metaFromConfig","cfg","historyConfig","systemKeys","parsed","metaFromRepo","repo","docTemplate","buildDocumentPath","repoName","createHistoryTriggers","repoMapping","onDocumentWritten","triggers","rawMapping","entries","name","repoCfg","subcollection","override","documentPath","resolvedGroupPath","metaFields","effectiveTriggerOptions","hasTriggerOptions","triggerHandler","event","operation","docId","parentRef","err","DEFAULT_GROUP_TOLERANCE_MS","isV2","doc","legacyTypeToHistoryType","v2ToEntry","v1MetaOf","extra","anyExtra","v1FieldChange","declaredOld","declaredNew","v1ToEntry","tsClose","toleranceMs","sameAuthor","normalizeHistoryDocs","docs","tol","out","last","DEFAULT_LIMIT","getHistoryRef","documentRef","args","getDocId","createHistoryMethods","raw","pathArgs","ref","direction","q","d","limit","fetchLimit","rawDocs","set","e","byField","field","byOperation","op","recordManual","payload","entityId","result"],"mappings":"wFA2BA,SAASA,EAAoBC,CAAAA,CAAgC,CAE3D,OADcA,CAAAA,CAAQ,KAAA,CAAM,eAAe,CAAA,GAC5B,CAAC,GAAG,IAAA,EAAK,EAAK,IAC/B,CA8CO,SAASC,CAAAA,CACdC,CAAAA,CACAC,CAAAA,CAAc,QACdC,CAAAA,CAAU,KAAA,CACU,CACpB,GAAI,OAAOF,CAAAA,EAAY,QAAA,EAAY,CAACA,CAAAA,CAAQ,MAAK,CAC/C,OAAO,CACL,OAAA,CAASA,CAAAA,EAAW,EAAA,CACpB,YAAA,CAAc,EAAA,CACd,eAAgB,EAAA,CAChB,UAAA,CAAY,EAAC,CACb,qBAAsB,IAAA,CACtB,WAAA,CAAa,KACf,CAAA,CAGF,IAAMG,CAAAA,CAAWH,CAAAA,CACd,KAAA,CAAM,GAAG,CAAA,CACT,GAAA,CAAKI,CAAAA,EAAMA,CAAAA,CAAE,MAAM,CAAA,CACnB,MAAA,CAAO,OAAO,EAEjB,GAAID,CAAAA,CAAS,MAAA,GAAW,CAAA,CACtB,OAAO,CACL,OAAA,CAAAH,CAAAA,CACA,YAAA,CAAcA,CAAAA,CACd,cAAA,CAAgBA,CAAAA,CAChB,UAAA,CAAY,EAAC,CACb,oBAAA,CAAsB,IAAA,CACtB,WAAA,CAAa,KACf,CAAA,CAGF,GAAIG,CAAAA,CAAS,MAAA,GAAW,EAAG,CACzB,IAAME,CAAAA,CAAMF,CAAAA,CAAS,CAAC,CAAA,CACtB,OAAO,CACL,QAAAH,CAAAA,CACA,YAAA,CAAcK,CAAAA,CACd,cAAA,CAAgBA,EAChB,UAAA,CAAY,EAAC,CACb,oBAAA,CAAsBH,EAAU,IAAA,CAA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CAAC,EAEK6E,CAAAA,CAAMP,CAAAA,CAAcC,CAAAA,CAAanC,CAAAA,CAAewC,CAAQ,CAAA,CACxDiB,CAAAA,CAAS,MAAM/F,EAAkB+E,CAAAA,CAAKxF,CAAAA,CAAOW,CAAAA,CAAQ,CACzD,SAAA2B,CAAAA,CACA,KAAA,CAAOiE,CAAAA,CACP,MAAA,CAAQD,EAAQ,MAAA,EAAU,IAAA,CAC1B,KAAA,CAAOA,CAAAA,CAAQ,KAAA,EAAS,IAC1B,CAAC,CAAA,CACD,OAAI,CAACE,CAAAA,CAAO,OAAA,EAAW,CAACA,EAAO,KAAA,CAAc,IAAA,CAEtC,CACL,YAAA,CAAcA,EAAO,KAAA,CAAM,YAAA,CAC3B,iBAAA,CAAmBA,CAAAA,CAAO,KAAA,CAAM,iBAAA,CAChC,YAAA,CAAcA,CAAAA,CAAO,MAAM,YAAA,CAC3B,aAAA,CAAe,CAAA,CACf,SAAA,CAAWA,EAAO,KAAA,CAAM,SAAA,CACxB,IAAA,CAAMA,CAAAA,CAAO,MAAM,IAAA,CACnB,OAAA,CAASA,CAAAA,CAAO,KAAA,CAAM,OACxB,CACF,CAEA,OAAO,CAAE,IAAA,CAAA7E,CAAAA,CAAM,GAAA,CAAA2D,CAAAA,CAAK,QAAAW,CAAAA,CAAS,WAAA,CAAAE,CAAAA,CAAa,YAAA,CAAAE,CAAa,CACzD","file":"index.cjs","sourcesContent":["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 * 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 * Write helpers for history entries.\n *\n * Builds a {@link V2HistoryDoc} from a diff + meta payload and writes it to\n * the entity's history subcollection. Used by {@link createHistoryTriggers}\n * and by the optional `repo.history.recordManual(...)` API.\n */\n\nimport {\n Timestamp,\n type CollectionReference,\n} from \"firebase-admin/firestore\";\nimport { randomUUID } from \"node:crypto\";\nimport type {\n HistoryConfigForModel,\n HistoryFieldChange,\n HistoryMeta,\n HistoryOperation,\n V2HistoryDoc,\n} from \"./types\";\n\nexport interface BuildEntryParams<T> {\n entityId: string;\n operation: HistoryOperation;\n changes: Record<string, HistoryFieldChange>;\n meta: HistoryMeta;\n config: HistoryConfigForModel<T>;\n ttlOverride?: { days: number };\n}\n\n/** Soft size guard — leave ~300 KiB headroom under Firestore's 1 MiB limit. */\nconst MAX_DOC_BYTES = 700_000;\n\nexport function buildHistoryEntry<T>(\n params: BuildEntryParams<T>,\n): V2HistoryDoc {\n const ttl = params.ttlOverride ?? params.config.ttl;\n const id = randomUUID();\n const entry: V2HistoryDoc = {\n schemaVersion: 2,\n historyDocId: id,\n historyToObjectId: params.entityId,\n historySetAt: Timestamp.now(),\n operation: params.operation,\n meta: params.meta,\n changes: params.changes,\n };\n if (ttl) {\n entry.expiresAt = Timestamp.fromMillis(\n Date.now() + ttl.days * 24 * 60 * 60 * 1000,\n );\n }\n\n // Soft size guard — if the JSON projection of `changes` is too large,\n // truncate large fields and mark the doc.\n const sizeOf = (obj: unknown): number => {\n try {\n return Buffer.byteLength(\n JSON.stringify(obj, (_k, v) => {\n if (v instanceof Timestamp) return v.toMillis();\n return v;\n }),\n \"utf8\",\n );\n } catch {\n return 0;\n }\n };\n\n if (sizeOf(entry.changes) > MAX_DOC_BYTES) {\n const truncated: Record<string, HistoryFieldChange> = {};\n for (const [k, change] of Object.entries(entry.changes)) {\n const oldSize = sizeOf(change.oldValue);\n const newSize = sizeOf(change.newValue);\n truncated[k] = {\n oldValue:\n oldSize > 50_000 ? \"[truncated]\" : change.oldValue,\n newValue:\n newSize > 50_000 ? \"[truncated]\" : change.newValue,\n type: change.type,\n };\n }\n entry.changes = truncated;\n entry._truncated = true;\n }\n\n return entry;\n}\n\nexport interface WriteEntryResult {\n written: boolean;\n entry?: V2HistoryDoc;\n reason?: string;\n}\n\n/**\n * Write a single history entry to the given subcollection reference.\n * Returns `{ written: false }` when the entry was dropped by `onBeforeWrite`.\n */\nexport async function writeHistoryEntry<T>(\n historyRef: CollectionReference,\n entry: V2HistoryDoc,\n config: HistoryConfigForModel<T>,\n ctx: { repoName: string; docId: string; before: T | null; after: T | null },\n): Promise<WriteEntryResult> {\n let toWrite: V2HistoryDoc | null = entry;\n if (config.onBeforeWrite) {\n toWrite = await config.onBeforeWrite(entry, ctx);\n }\n if (!toWrite) return { written: false, reason: \"dropped-by-onBeforeWrite\" };\n\n await historyRef.doc(toWrite.historyDocId).set(toWrite);\n return { written: true, entry: toWrite };\n}\n\n/**\n * Extract meta values from a Firestore document snapshot using the\n * declared meta config. Missing fields become `null`.\n */\nexport function extractMeta<T>(\n source: Record<string, unknown> | null | undefined,\n config: HistoryConfigForModel<T>,\n): HistoryMeta {\n const src = source ?? {};\n const meta: HistoryMeta = {};\n const m = config.meta;\n if (!m) return meta;\n\n const pickStr = (key?: string): string | null | undefined => {\n if (!key) return undefined;\n const v = src[key];\n if (v === undefined) return null;\n return v === null ? null : String(v);\n };\n\n const userId = pickStr(m.userId);\n if (userId !== undefined) meta.userId = userId;\n const userEmail = pickStr(m.userEmail);\n if (userEmail !== undefined) meta.userEmail = userEmail;\n const reason = pickStr(m.reason);\n if (reason !== undefined) meta.reason = reason;\n const comment = pickStr(m.comment);\n if (comment !== undefined) meta.comment = comment;\n\n if (m.extras && m.extras.length > 0) {\n const extras: Record<string, unknown> = {};\n let any = false;\n for (const k of m.extras) {\n if (k in src) {\n extras[k] = src[k];\n any = true;\n }\n }\n if (any) meta.extras = extras;\n }\n\n return meta;\n}\n\n/**\n * Returns all field names that should be excluded from the diff because\n * they're declared as meta fields (so we don't log them as their own change).\n */\nexport function metaFieldsOf<T>(config: HistoryConfigForModel<T>): string[] {\n const m = config.meta;\n if (!m) return [];\n const list: string[] = [];\n if (m.userId) list.push(m.userId);\n if (m.userEmail) list.push(m.userEmail);\n if (m.reason) list.push(m.reason);\n if (m.comment) list.push(m.comment);\n if (m.extras) list.push(...m.extras);\n return list;\n}\n","/**\n * `createHistoryTriggers` — generates Firestore Cloud Functions (v2) that\n * capture every write to a configured repository and write a v2 history\n * entry into the entity's history subcollection.\n *\n * Mirrors the DI / per-repo override pattern of {@link createSyncTriggers}.\n *\n * @example\n * ```ts\n * import { createHistoryTriggers } from \"@lpdjs/firestore-repo-service/history\";\n * import * as firestoreTriggers from \"firebase-functions/v2/firestore\";\n *\n * const triggers = createHistoryTriggers(repos, {\n * deps: { onDocumentWritten: firestoreTriggers.onDocumentWritten },\n * defaults: { ttl: { days: 365 } },\n * });\n *\n * export const { residences_onHistory, prevention_workshops_onHistory } = triggers;\n * ```\n */\n\nimport { parsePathTemplate } from \"../shared/path-template\";\nimport { computeDiff } from \"./diff\";\nimport {\n buildHistoryEntry,\n extractMeta,\n metaFieldsOf,\n writeHistoryEntry,\n} from \"./write\";\nimport type {\n HistoryConfigForModel,\n HistoryOperation,\n HistoryTriggersConfig,\n} from \"./types\";\n\nconst DEFAULT_SUBCOLLECTION = \"history\";\n\n/** Static, db-free metadata needed to register a history trigger. */\ninterface RepoHistoryMeta {\n historyConfig: (HistoryConfigForModel<unknown> & { enabled: boolean }) | undefined;\n systemKeys: string[];\n isGroup: boolean;\n /** Collection path of a non-group repo (used to derive the trigger path). */\n collectionPath: string | null;\n /** Auto-derived document trigger path template when path is a full template (e.g. \"residences/{residenceId}/res_events/{docId}\"). */\n documentPathTemplate: string | null;\n}\n\n/** Read history metadata from a **raw repository config** (no db resolution). */\nfunction metaFromConfig(cfg: any): RepoHistoryMeta {\n const historyConfig =\n cfg && typeof cfg.history === \"object\" && cfg.history !== null\n ? cfg.history\n : undefined;\n const systemKeys = [\n cfg?.documentKey,\n cfg?.pathKey,\n cfg?.createdKey,\n cfg?.updatedKey,\n ].filter((k): k is string => typeof k === \"string\");\n const rawPath = typeof cfg?.path === \"string\" ? cfg.path : null;\n const parsed = rawPath\n ? parsePathTemplate(rawPath, cfg?.documentKey ?? \"docId\")\n : null;\n return {\n historyConfig,\n systemKeys,\n isGroup: !!cfg?.isGroup,\n collectionPath: parsed ? parsed.collectionPath : null,\n documentPathTemplate:\n parsed && (!cfg?.isGroup || parsed.collectionPath.includes(\"/\"))\n ? parsed.documentPathTemplate\n : null,\n };\n}\n\n/** Read history metadata from a **resolved repository** (forces db resolution). */\nfunction metaFromRepo(repo: any): RepoHistoryMeta {\n const historyConfig =\n repo._historyConfig ??\n // Backward-compat: older repos exposed the config under `.history`\n // (before that key became the methods namespace).\n (typeof repo.history === \"object\" &&\n repo.history !== null &&\n \"enabled\" in repo.history\n ? repo.history\n : undefined);\n const collectionPath = repo._collectionPath ?? repo.ref?.path ?? null;\n const docTemplate =\n typeof repo._documentPathTemplate === \"string\"\n ? repo._documentPathTemplate\n : null;\n return {\n historyConfig,\n systemKeys: (repo._systemKeys as string[]) ?? [],\n isGroup: !!repo._isGroup,\n collectionPath,\n documentPathTemplate:\n docTemplate && (!repo._isGroup || (collectionPath && collectionPath.includes(\"/\")))\n ? docTemplate\n : null,\n };\n}\n\n/** Determine the trigger document path pattern for a non-group repo. */\nfunction buildDocumentPath(repoName: string, collectionPath: string | null): string | null {\n if (!collectionPath) {\n console.warn(\n `[HistoryTriggers] Cannot determine collection path for \"${repoName}\". Skipping.`,\n );\n return null;\n }\n return `${collectionPath}/{docId}`;\n}\n\nexport function createHistoryTriggers<M extends Record<string, any>>(\n repoMapping: M,\n config: HistoryTriggersConfig<NoInfer<M>>,\n): Record<string, any> {\n const { onDocumentWritten } = config.deps;\n const triggers: Record<string, any> = {};\n\n // Prefer the raw mapping config (exposed by `createRepositoryMapping`) so we\n // register triggers WITHOUT resolving Firestore — mirroring the lazy db\n // initialization used by the repository methods. Falls back to introspecting\n // the resolved repositories when a plain repo object is passed.\n const rawMapping: Record<string, any> | undefined = (repoMapping as any)\n ?.rawMapping;\n const entries: [string, RepoHistoryMeta][] = rawMapping\n ? Object.entries(rawMapping).map(([name, cfg]) => [name, metaFromConfig(cfg)])\n : (Object.entries(repoMapping) as [string, any][]).map(([name, repo]) => [\n name,\n metaFromRepo(repo),\n ]);\n\n for (const [repoName, meta] of entries) {\n const repoCfg = meta.historyConfig;\n if (!repoCfg?.enabled) continue;\n\n const subcollection = repoCfg.subcollection ?? DEFAULT_SUBCOLLECTION;\n const ttl = repoCfg.ttl ?? config.defaults?.ttl;\n\n const override = config.repos?.[repoName as keyof M & string];\n let documentPath: string | null;\n if (meta.isGroup) {\n const resolvedGroupPath =\n override?.triggerPath ?? meta.documentPathTemplate;\n if (!resolvedGroupPath) {\n console.warn(\n `[HistoryTriggers] Skipping collection-group repo \"${repoName}\". ` +\n \"Provide a triggerPath in the history triggers repos override or use a full path template.\",\n );\n continue;\n }\n documentPath = resolvedGroupPath;\n } else {\n documentPath =\n override?.triggerPath ??\n meta.documentPathTemplate ??\n buildDocumentPath(repoName, meta.collectionPath);\n }\n if (!documentPath) continue;\n\n const systemKeys: string[] = meta.systemKeys;\n const documentKey: string = systemKeys[0] ?? \"docId\";\n const metaFields = metaFieldsOf(repoCfg as HistoryConfigForModel<unknown>);\n\n const effectiveTriggerOptions = {\n ...config.triggerOptions,\n ...(repoCfg as any)?.triggerOptions,\n ...override?.triggerOptions,\n };\n const hasTriggerOptions = Object.keys(effectiveTriggerOptions).length > 0;\n\n const triggerHandler = async (event: any) => {\n try {\n const before = event.data?.before?.data() as\n | Record<string, unknown>\n | undefined;\n const after = event.data?.after?.data() as\n | Record<string, unknown>\n | undefined;\n\n let operation: HistoryOperation;\n if (!before && after) operation = \"create\";\n else if (before && !after) operation = \"delete\";\n else if (before && after) operation = \"update\";\n else return;\n\n const docId = String(\n after?.[documentKey] ??\n before?.[documentKey] ??\n event.params?.docId ??\n event.data?.after?.id ??\n event.data?.before?.id ??\n \"\",\n );\n if (!docId) return;\n\n const changes = computeDiff(before ?? {}, after ?? {}, {\n include: repoCfg.include as string[] | undefined,\n exclude: repoCfg.exclude as string[] | undefined,\n metaFields,\n systemKeys,\n });\n\n if (operation === \"update\" && Object.keys(changes).length === 0) {\n return; // no relevant change\n }\n\n const meta = extractMeta(\n after ?? before ?? null,\n repoCfg as HistoryConfigForModel<unknown>,\n );\n\n const entry = buildHistoryEntry({\n entityId: docId,\n operation,\n changes,\n meta,\n config: repoCfg as HistoryConfigForModel<unknown>,\n ttlOverride: ttl,\n });\n\n // Build the subcollection ref from the parent doc ref of the trigger.\n const parentRef =\n event.data?.after?.ref ?? event.data?.before?.ref;\n if (!parentRef) return;\n const historyRef = parentRef.collection(subcollection);\n\n await writeHistoryEntry(\n historyRef,\n entry,\n repoCfg as HistoryConfigForModel<unknown>,\n {\n repoName,\n docId,\n before: (before ?? null) as any,\n after: (after ?? null) as any,\n },\n );\n } catch (err) {\n console.error(\n `[HistoryTriggers] Failed to record history for \"${repoName}\":`,\n err,\n );\n }\n };\n\n triggers[`${repoName}_onHistory`] = hasTriggerOptions\n ? onDocumentWritten(\n { document: documentPath, ...effectiveTriggerOptions } as any,\n triggerHandler,\n )\n : onDocumentWritten(documentPath, triggerHandler);\n }\n\n return triggers;\n}\n","/**\n * v1 ↔ v2 normalisation. The reader returns a unified {@link HistoryEntry}\n * shape regardless of which schema version a Firestore document was written\n * with.\n *\n * v2 doc → pass-through.\n * v1 doc (single field per doc) → wrapped into a 1-field unified entry.\n * Consecutive v1 docs that share the same `historySetAt` timestamp\n * (within a small tolerance) are merged into a single entry, mimicking\n * the original \"one update -> N field docs\" intent.\n */\n\nimport { Timestamp } from \"firebase-admin/firestore\";\nimport type {\n HistoryEntry,\n HistoryFieldChange,\n HistoryMeta,\n HistoryValueType,\n V1HistoryDoc,\n V2HistoryDoc,\n} from \"./types\";\nimport { valueType } from \"./diff\";\n\n/** Default tolerance (ms) used to group v1 docs from the same update. */\nexport const DEFAULT_GROUP_TOLERANCE_MS = 5;\n\ntype AnyHistoryDoc = (V1HistoryDoc | V2HistoryDoc) & Record<string, unknown>;\n\nfunction isV2(doc: AnyHistoryDoc): doc is V2HistoryDoc & Record<string, unknown> {\n return doc.schemaVersion === 2;\n}\n\nfunction legacyTypeToHistoryType(t: unknown): HistoryValueType {\n if (typeof t !== \"string\") return \"object\";\n switch (t) {\n case \"string\":\n case \"number\":\n case \"boolean\":\n case \"object\":\n case \"array\":\n case \"timestamp\":\n case \"date\":\n case \"null\":\n case \"undefined\":\n return t;\n default:\n return \"object\";\n }\n}\n\nfunction v2ToEntry(doc: V2HistoryDoc): HistoryEntry {\n return {\n historyDocId: doc.historyDocId,\n historyToObjectId: doc.historyToObjectId,\n historySetAt: doc.historySetAt,\n schemaVersion: 2,\n operation: doc.operation,\n meta: doc.meta ?? {},\n changes: doc.changes ?? {},\n };\n}\n\nfunction v1MetaOf(doc: V1HistoryDoc & Record<string, unknown>): HistoryMeta {\n const meta: HistoryMeta = {};\n if (doc.historyUserId !== undefined) meta.userId = doc.historyUserId ?? null;\n if (doc.historyUserEmail !== undefined)\n meta.userEmail = doc.historyUserEmail ?? null;\n\n const extra = doc.extraHistoryDetails ?? null;\n if (extra) {\n if (extra.reason !== undefined) meta.reason = extra.reason ?? null;\n if (extra.comment !== undefined) meta.comment = extra.comment ?? null;\n }\n\n const extras: Record<string, unknown> = {};\n let anyExtra = false;\n if (doc.historyDetails && typeof doc.historyDetails === \"object\") {\n for (const [k, v] of Object.entries(doc.historyDetails)) {\n extras[k] = v;\n anyExtra = true;\n }\n }\n if (doc.extraContentKeys && typeof doc.extraContentKeys === \"object\") {\n for (const [k, v] of Object.entries(doc.extraContentKeys)) {\n extras[`content.${k}`] = v;\n anyExtra = true;\n }\n }\n if (anyExtra) meta.extras = extras;\n return meta;\n}\n\nfunction v1FieldChange(doc: V1HistoryDoc): HistoryFieldChange {\n const oldValue = doc.changes?.oldValue ?? null;\n const newValue = doc.changes?.newValue ?? null;\n const declaredOld = doc.types?.oldValue;\n const declaredNew = doc.types?.newValue;\n return {\n oldValue,\n newValue,\n type: {\n old: declaredOld\n ? legacyTypeToHistoryType(declaredOld)\n : valueType(oldValue),\n new: declaredNew\n ? legacyTypeToHistoryType(declaredNew)\n : valueType(newValue),\n },\n };\n}\n\nfunction v1ToEntry(doc: V1HistoryDoc): HistoryEntry {\n const change = v1FieldChange(doc);\n const meta = v1MetaOf(doc as V1HistoryDoc & Record<string, unknown>);\n return {\n historyDocId: doc.historyDocId,\n historyToObjectId: doc.historyToObjectId,\n historySetAt: doc.historySetAt,\n schemaVersion: 1,\n operation: \"update\",\n meta,\n changes: { [doc.field]: change },\n };\n}\n\nfunction tsClose(a: Timestamp, b: Timestamp, toleranceMs: number): boolean {\n return Math.abs(a.toMillis() - b.toMillis()) <= toleranceMs;\n}\n\nfunction sameAuthor(a: HistoryMeta, b: HistoryMeta): boolean {\n return (a.userId ?? null) === (b.userId ?? null);\n}\n\n/**\n * Normalise a list of raw Firestore docs into unified {@link HistoryEntry}.\n * The input list MUST be sorted by `historySetAt` (asc or desc — the function\n * preserves order). v1 docs sharing the same timestamp + author are merged.\n */\nexport function normalizeHistoryDocs(\n docs: AnyHistoryDoc[],\n opts: { groupToleranceMs?: number } = {},\n): HistoryEntry[] {\n const tol = opts.groupToleranceMs ?? DEFAULT_GROUP_TOLERANCE_MS;\n const out: HistoryEntry[] = [];\n\n for (const doc of docs) {\n if (isV2(doc)) {\n out.push(v2ToEntry(doc));\n continue;\n }\n\n const v1 = doc as V1HistoryDoc;\n const entry = v1ToEntry(v1);\n\n const last = out[out.length - 1];\n if (\n last &&\n last.schemaVersion === 1 &&\n tsClose(last.historySetAt, entry.historySetAt, tol) &&\n sameAuthor(last.meta, entry.meta)\n ) {\n // Merge into the previous v1 entry (same logical update).\n Object.assign(last.changes, entry.changes);\n // Keep earliest historyDocId (stable id of the group).\n } else {\n out.push(entry);\n }\n }\n\n return out;\n}\n","/**\n * `repo.history.*` read API.\n *\n * - `list(docId, opts)` → unified, paginated, normalised entries (v1 + v2).\n * - `raw(docId, opts)` → raw Firestore docs (no normalisation).\n * - `byField(docId, field, opts)` / `byOperation(docId, op, opts)` →\n * convenience wrappers.\n * - `recordManual(docId, payload)` → bypass the trigger and write a v2 entry\n * synchronously (use sparingly; prefer trigger-based capture).\n */\n\nimport {\n Timestamp,\n type CollectionReference,\n type DocumentReference,\n} from \"firebase-admin/firestore\";\nimport { computeDiff } from \"./diff\";\nimport { normalizeHistoryDocs } from \"./normalize\";\nimport {\n buildHistoryEntry,\n extractMeta,\n metaFieldsOf,\n writeHistoryEntry,\n} from \"./write\";\nimport type {\n HistoryConfigForModel,\n HistoryEntry,\n HistoryListOptions,\n HistoryMeta,\n HistoryOperation,\n HistoryRawListOptions,\n V1HistoryDoc,\n V2HistoryDoc,\n} from \"./types\";\n\nconst DEFAULT_SUBCOLLECTION = \"history\";\nconst DEFAULT_LIMIT = 50;\n\nfunction getHistoryRef(\n documentRef: (...args: any[]) => DocumentReference,\n subcollection: string,\n args: any[],\n): CollectionReference {\n const docRef = documentRef(...args);\n return docRef.collection(subcollection);\n}\n\nfunction getDocId(args: any[]): string {\n return String(args[args.length - 1] ?? \"\");\n}\n\n/**\n * Build the `repo.history` API for a given configured repository.\n * Returns `null` when history is not enabled — the factory then skips\n * exposing the namespace.\n */\nexport function createHistoryMethods<T>(\n documentRef: (...args: any[]) => DocumentReference,\n systemKeys: string[],\n repoName: string,\n config: HistoryConfigForModel<T> & { enabled: boolean },\n): HistoryMethods<T> | null {\n if (!config?.enabled) return null;\n\n const subcollection = config.subcollection ?? DEFAULT_SUBCOLLECTION;\n\n async function raw(\n ...args: any[]\n ): Promise<Array<{ id: string; data: V1HistoryDoc | V2HistoryDoc }>> {\n let opts: HistoryRawListOptions = {};\n let pathArgs = args;\n const last = args[args.length - 1];\n if (\n last !== null &&\n typeof last === \"object\" &&\n !(last instanceof Timestamp) &&\n (\"limit\" in last || \"cursor\" in last || \"direction\" in last)\n ) {\n opts = last as HistoryRawListOptions;\n pathArgs = args.slice(0, -1);\n }\n\n const ref = getHistoryRef(documentRef, subcollection, pathArgs);\n const direction = opts.direction ?? \"desc\";\n let q = ref.orderBy(\"historySetAt\", direction);\n if (opts.cursor) q = q.startAfter(opts.cursor);\n if (opts.limit && opts.limit > 0) q = q.limit(opts.limit);\n\n const snap = await q.get();\n return snap.docs.map((d) => ({\n id: d.id,\n data: d.data() as V1HistoryDoc | V2HistoryDoc,\n }));\n }\n\n async function list(\n ...args: any[]\n ): Promise<HistoryEntry<T>[]> {\n let opts: HistoryListOptions<T> = {};\n let pathArgs = args;\n const last = args[args.length - 1];\n if (\n last !== null &&\n typeof last === \"object\" &&\n !(last instanceof Timestamp) &&\n (\"limit\" in last ||\n \"cursor\" in last ||\n \"direction\" in last ||\n \"fields\" in last ||\n \"operations\" in last)\n ) {\n opts = last as HistoryListOptions<T>;\n pathArgs = args.slice(0, -1);\n }\n\n const limit = opts.limit ?? DEFAULT_LIMIT;\n // Read a bit more from Firestore because v1 entries get merged afterwards.\n // Cap at limit * 8 to avoid pathological reads.\n const fetchLimit = Math.max(limit, Math.min(limit * 8, 500));\n\n const rawDocs = await raw(...pathArgs, {\n limit: fetchLimit,\n cursor: opts.cursor,\n direction: opts.direction ?? \"desc\",\n });\n\n let entries = normalizeHistoryDocs(\n rawDocs.map((d) => d.data) as any[],\n ) as HistoryEntry<T>[];\n\n if (opts.fields && opts.fields.length > 0) {\n const set = new Set<string>(opts.fields as string[]);\n entries = entries.filter((e) =>\n Object.keys(e.changes).some((k) => set.has(k)),\n );\n }\n if (opts.operations && opts.operations.length > 0) {\n const set = new Set<HistoryOperation>(opts.operations);\n entries = entries.filter((e) => set.has(e.operation));\n }\n\n return entries.slice(0, limit);\n }\n\n async function byField(\n ...args: any[]\n ): Promise<HistoryEntry<T>[]> {\n const last = args[args.length - 1];\n let opts: HistoryListOptions<T> = {};\n let field: keyof T & string;\n let pathArgs: any[];\n if (last !== null && typeof last === \"object\" && !(last instanceof Timestamp)) {\n opts = last as HistoryListOptions<T>;\n field = args[args.length - 2] as keyof T & string;\n pathArgs = args.slice(0, -2);\n } else {\n field = last as keyof T & string;\n pathArgs = args.slice(0, -1);\n }\n return list(...pathArgs, { ...opts, fields: [field] });\n }\n\n async function byOperation(\n ...args: any[]\n ): Promise<HistoryEntry<T>[]> {\n const last = args[args.length - 1];\n let opts: HistoryListOptions<T> = {};\n let op: HistoryOperation;\n let pathArgs: any[];\n if (last !== null && typeof last === \"object\" && !(last instanceof Timestamp)) {\n opts = last as HistoryListOptions<T>;\n op = args[args.length - 2] as HistoryOperation;\n pathArgs = args.slice(0, -2);\n } else {\n op = last as HistoryOperation;\n pathArgs = args.slice(0, -1);\n }\n return list(...pathArgs, { ...opts, operations: [op] });\n }\n\n /**\n * Manually record a history entry. Bypasses the trigger and lets the caller\n * pass an explicit before/after pair plus meta (useful for synchronous flows\n * that need richer context than what the trigger can extract).\n */\n async function recordManual(\n ...args: any[]\n ): Promise<HistoryEntry<T> | null> {\n const payload = args[args.length - 1] as {\n operation: HistoryOperation;\n before?: T | null;\n after?: T | null;\n meta?: HistoryMeta;\n };\n const pathArgs = args.slice(0, -1);\n const entityId = getDocId(pathArgs);\n\n const changes = computeDiff(\n (payload.before ?? {}) as Record<string, unknown>,\n (payload.after ?? {}) as Record<string, unknown>,\n {\n include: config.include as string[] | undefined,\n exclude: config.exclude as string[] | undefined,\n metaFields: metaFieldsOf(config),\n systemKeys,\n },\n );\n if (\n payload.operation === \"update\" &&\n Object.keys(changes).length === 0\n ) {\n return null;\n }\n\n const fallbackMeta = extractMeta(\n (payload.after ?? payload.before ?? null) as Record<string, unknown> | null,\n config,\n );\n const meta: HistoryMeta = { ...fallbackMeta, ...(payload.meta ?? {}) };\n\n const entry = buildHistoryEntry({\n entityId,\n operation: payload.operation,\n changes,\n meta,\n config,\n });\n\n const ref = getHistoryRef(documentRef, subcollection, pathArgs);\n const result = await writeHistoryEntry(ref, entry, config, {\n repoName,\n docId: entityId,\n before: payload.before ?? null,\n after: payload.after ?? null,\n });\n if (!result.written || !result.entry) return null;\n\n return {\n historyDocId: result.entry.historyDocId,\n historyToObjectId: result.entry.historyToObjectId,\n historySetAt: result.entry.historySetAt,\n schemaVersion: 2,\n operation: result.entry.operation,\n meta: result.entry.meta,\n changes: result.entry.changes,\n } as HistoryEntry<T>;\n }\n\n return { list, raw, byField, byOperation, recordManual } as HistoryMethods<T>;\n}\n\n/**\n * Public, strongly-typed surface of the `repo.history` namespace.\n *\n * Exposed on a repository **only when** `history.enabled: true` is set in\n * its config. Reads from the entity's `history` subcollection (or the custom\n * name set via `history.subcollection`) and normalises both schema versions\n * (v1 = one doc per modified field, v2 = one doc per write) into a single\n * {@link HistoryEntry} shape.\n *\n * ### Path arguments\n *\n * Every method's leading positional arguments mirror\n * `Parameters<repo.documentRef>`, so the call signature stays consistent with\n * the rest of the repo API:\n *\n * - **Top-level collection** (`documentRef: (db, docId) => …`)\n * → `repo.history.list(\"doc_42\", opts?)`\n * - **Subcollection** (`documentRef: (db, parentId, docId) => …`)\n * → `repo.history.list(\"parent_1\", \"doc_42\", opts?)`\n *\n * The trailing options/payload argument keeps the same position whatever the\n * depth of the path.\n *\n * ### Pagination\n *\n * `list` / `byField` / `byOperation` use real Firestore cursors via the\n * `cursor` + `limit` options on {@link HistoryListOptions} — no in-memory\n * slicing, safe for large histories.\n *\n * @example Basic read\n * ```ts\n * const entries = await repos.residences.history!.list(\"residence_123\", {\n * limit: 50,\n * direction: \"desc\",\n * });\n * for (const e of entries) {\n * console.log(e.historySetAt.toDate(), e.operation, e.meta.userId);\n * }\n * ```\n *\n * @example Filter by field (autocompleted on `keyof T`)\n * ```ts\n * const addressChanges = await repos.residences.history!.byField(\n * \"residence_123\",\n * \"address\",\n * );\n * ```\n *\n * @template T - The repository's model type. Field-name parameters\n * (e.g. `byField`'s `K`) and `HistoryEntry<T>` payloads\n * are derived from this.\n * @template PathArgs - Tuple of path-segment args inherited from the repo's\n * `documentRef`. Defaults to `[string]` (a single\n * `docId`) when used standalone.\n *\n * @see {@link createHistoryMethods} - factory used internally by `createRepository`.\n * @see {@link HistoryEntry} - normalised return shape.\n * @see {@link HistoryListOptions} - pagination + filter options.\n */\nexport interface HistoryMethods<T, PathArgs extends readonly unknown[] = [string]> {\n /**\n * List normalised history entries for a single document.\n *\n * Reads both v1 and v2 docs and folds v1 field-per-doc entries that share\n * the same author + timestamp (±5 ms) into a single logical entry, so the\n * caller never has to care about the storage version.\n *\n * @param args - `[...pathArgs, options?]`. `pathArgs` mirror the repo's\n * `documentRef`. `options` accepts `limit`, `cursor`,\n * `direction`, `fields`, `operations`.\n * @returns Array of {@link HistoryEntry} ordered by `historySetAt`\n * (`direction` defaults to `\"desc\"`).\n */\n list(\n ...args: [...PathArgs, HistoryListOptions<T>?]\n ): Promise<HistoryEntry<T>[]>;\n\n /**\n * Escape hatch returning **raw** Firestore documents (v1 or v2) without\n * normalisation. Use only when {@link list} doesn't expose the field you\n * need (custom legacy fields, debugging, migrations).\n *\n * @param args - `[...pathArgs, options?]`. Supports the same pagination\n * options as `list`, minus model-aware filters.\n */\n raw(\n ...args: [...PathArgs, HistoryRawListOptions?]\n ): Promise<Array<{ id: string; data: V1HistoryDoc | V2HistoryDoc }>>;\n\n /**\n * Convenience wrapper around {@link list} that only returns entries\n * touching a specific field. Field name is checked against `keyof T` at\n * compile time.\n *\n * @typeParam K - A literal key of the model `T`.\n * @param args - `[...pathArgs, field, options?]`.\n *\n * @example\n * ```ts\n * await repos.users.history!.byField(\"user_42\", \"email\");\n * ```\n */\n byField<K extends keyof T & string>(\n ...args: [...PathArgs, K, HistoryListOptions<T>?]\n ): Promise<HistoryEntry<T>[]>;\n\n /**\n * Convenience wrapper around {@link list} filtering on the operation type.\n *\n * @param args - `[...pathArgs, operation, options?]` where `operation` is\n * `\"create\" | \"update\" | \"delete\"`.\n *\n * @example\n * ```ts\n * await repos.residences.history!.byOperation(\"residence_123\", \"delete\");\n * ```\n */\n byOperation(\n ...args: [...PathArgs, HistoryOperation, HistoryListOptions<T>?]\n ): Promise<HistoryEntry<T>[]>;\n\n /**\n * Synchronously append a custom history entry, bypassing the trigger.\n *\n * Useful when:\n * - You already have richer business context than the trigger can extract\n * (e.g. inside an HTTP handler that knows the authenticated user).\n * - You want to record an event that isn't a Firestore write (e.g.\n * `meta.reason = \"exported-to-pdf\"`).\n *\n * Honours the same `include` / `exclude` / meta auto-exclusion rules as\n * the trigger. Returns `null` when the diff is empty (no changes recorded).\n *\n * > ⚠️ Use sparingly — combining manual records with the trigger can\n * > produce duplicate entries if both fire for the same write.\n *\n * @param args - `[...pathArgs, payload]` where `payload` is\n * `{ operation, before?, after?, meta? }`.\n */\n recordManual(\n ...args: [\n ...PathArgs,\n {\n operation: HistoryOperation;\n before?: T | null;\n after?: T | null;\n meta?: HistoryMeta;\n },\n ]\n ): Promise<HistoryEntry<T> | null>;\n}\n"]}
1
+ {"version":3,"sources":["../../src/shared/path-template.ts","../../src/history/diff.ts","../../src/shared/actor-context.ts","../../src/history/types.ts","../../src/history/inject.ts","../../src/history/write.ts","../../src/history/triggers.ts","../../src/history/normalize.ts","../../src/history/read.ts"],"names":["extractSegmentParam","segment","parsePathTemplate","rawPath","documentKey","isGroup","segments","s","seg","isEvenSegments","collectionSegments","collectionId","collectionPath","parentKeys","p","documentPathTemplate","valueType","v","Timestamp","valuesEqual","a","b","seen","i","ka","kb","k","computeDiff","before","after","opts","excludeSet","includeSet","beforeObj","afterObj","keys","changes","key","oldValue","newValue","ALS_SYMBOL","g","actorStorage","AsyncLocalStorage","readFieldPath","obj","path","cur","part","pickFirstString","paths","val","readHeader","c","name","headerFn","createActorResolver","config","contextKeys","userIdFields","userEmailFields","reasonHeader","commentHeader","extrasFn","user","getFn","candidate","reason","comment","extras","defaultActorResolver","normalizeActorResolver","option","createActorContextMiddleware","resolver","normalized","next","getCurrentActor","store","fromReq","merged","withActor","actor","fn","setRequestActorMeta","meta","prev","nextOverride","DEFAULT_HISTORY_SHADOW_KEY","resolveShadowConfig","shadowOpt","customFields","getHistoryShadowKey","getHistoryIdentityKeys","shadow","stripHistoryShadowField","value","shadowKey","rec","_dropped","rest","injectHistoryMeta","payload","historyConfig","fallback","userId","userEmail","shadowObj","fields","MAX_DOC_BYTES","buildHistoryEntry","params","ttl","entry","randomUUID","sizeOf","_k","truncated","change","oldSize","newSize","writeHistoryEntry","historyRef","ctx","toWrite","extractMeta","source","src","raw","pickShadowStr","field","rawExtras","m","pickStr","any","metaFieldsOf","list","DEFAULT_SUBCOLLECTION","metaFromConfig","cfg","systemKeys","parsed","metaFromRepo","repo","docTemplate","buildDocumentPath","repoName","createHistoryTriggers","repoMapping","onDocumentWritten","triggers","rawMapping","entries","repoCfg","subcollection","override","documentPath","resolvedGroupPath","metaFields","effectiveTriggerOptions","hasTriggerOptions","triggerHandler","event","operation","docId","parentRef","err","DEFAULT_GROUP_TOLERANCE_MS","isV2","doc","legacyTypeToHistoryType","t","v2ToEntry","v1MetaOf","extra","anyExtra","v1FieldChange","declaredOld","declaredNew","v1ToEntry","tsClose","toleranceMs","sameAuthor","normalizeHistoryDocs","docs","tol","out","last","DEFAULT_LIMIT","getHistoryRef","documentRef","args","getDocId","createHistoryMethods","pathArgs","ref","direction","q","d","limit","fetchLimit","rawDocs","set","e","byField","byOperation","op","buildCustomPayload","input","custom","resolveActorMeta","recordManual","entityId","fallbackMeta","result","recordCustom"],"mappings":"2HA2BA,SAASA,EAAAA,CAAoBC,EAAgC,CAE3D,OADcA,CAAAA,CAAQ,KAAA,CAAM,eAAe,CAAA,GAC5B,CAAC,CAAA,EAAG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AAe,CAAA,CACf,SAAA,CAAWA,CAAAA,CAAO,KAAA,CAAM,SAAA,CACxB,IAAA,CAAMA,CAAAA,CAAO,KAAA,CAAM,IAAA,CACnB,GAAIA,CAAAA,CAAO,KAAA,CAAM,MAAA,CAAS,CAAE,MAAA,CAAQA,CAAAA,CAAO,KAAA,CAAM,MAAO,CAAA,CAAI,EAAC,CAC7D,OAAA,CAASA,CAAAA,CAAO,KAAA,CAAM,OACxB,CACF,CAEA,OAAO,CACL,IAAA,CAAA9E,CAAAA,CACA,GAAA,CAAAR,CAAAA,CACA,OAAA,CAAA4E,CAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,YAAA,CAAAM,CAAAA,CACA,YAAA,CAAAI,CACF,CACF","file":"index.cjs","sourcesContent":["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 * 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 * 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\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 extrasFn = config.extras;\n\n return (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\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","/**\n * Write helpers for history entries.\n *\n * Builds a {@link V2HistoryDoc} from a diff + meta payload and writes it to\n * the entity's history subcollection. Used by {@link createHistoryTriggers}\n * and by the optional `repo.history.recordManual(...)` API.\n */\n\nimport {\n Timestamp,\n type CollectionReference,\n} from \"firebase-admin/firestore\";\nimport { randomUUID } from \"node:crypto\";\nimport { resolveShadowConfig } from \"./inject\";\nimport type {\n HistoryConfigForModel,\n HistoryCustomData,\n HistoryFieldChange,\n HistoryMeta,\n HistoryOperation,\n V2HistoryDoc,\n} from \"./types\";\n\nexport interface BuildEntryParams<T> {\n entityId: string;\n operation: HistoryOperation;\n changes: Record<string, HistoryFieldChange>;\n meta: HistoryMeta;\n custom?: HistoryCustomData;\n config: HistoryConfigForModel<T>;\n ttlOverride?: { days: number };\n}\n\n/** Soft size guard — leave ~300 KiB headroom under Firestore's 1 MiB limit. */\nconst MAX_DOC_BYTES = 700_000;\n\nexport function buildHistoryEntry<T>(\n params: BuildEntryParams<T>,\n): V2HistoryDoc {\n const ttl = params.ttlOverride ?? params.config.ttl;\n const id = randomUUID();\n const entry: V2HistoryDoc = {\n schemaVersion: 2,\n historyDocId: id,\n historyToObjectId: params.entityId,\n historySetAt: Timestamp.now(),\n operation: params.operation,\n meta: params.meta,\n ...(params.custom ? { custom: params.custom } : {}),\n changes: params.changes,\n };\n if (ttl) {\n entry.expiresAt = Timestamp.fromMillis(\n Date.now() + ttl.days * 24 * 60 * 60 * 1000,\n );\n }\n\n // Soft size guard — if the JSON projection of `changes` is too large,\n // truncate large fields and mark the doc.\n const sizeOf = (obj: unknown): number => {\n try {\n return Buffer.byteLength(\n JSON.stringify(obj, (_k, v) => {\n if (v instanceof Timestamp) return v.toMillis();\n return v;\n }),\n \"utf8\",\n );\n } catch {\n return 0;\n }\n };\n\n if (sizeOf(entry.changes) > MAX_DOC_BYTES) {\n const truncated: Record<string, HistoryFieldChange> = {};\n for (const [k, change] of Object.entries(entry.changes)) {\n const oldSize = sizeOf(change.oldValue);\n const newSize = sizeOf(change.newValue);\n truncated[k] = {\n oldValue:\n oldSize > 50_000 ? \"[truncated]\" : change.oldValue,\n newValue:\n newSize > 50_000 ? \"[truncated]\" : change.newValue,\n type: change.type,\n };\n }\n entry.changes = truncated;\n entry._truncated = true;\n }\n\n return entry;\n}\n\nexport interface WriteEntryResult {\n written: boolean;\n entry?: V2HistoryDoc;\n reason?: string;\n}\n\n/**\n * Write a single history entry to the given subcollection reference.\n * Returns `{ written: false }` when the entry was dropped by `onBeforeWrite`.\n */\nexport async function writeHistoryEntry<T>(\n historyRef: CollectionReference,\n entry: V2HistoryDoc,\n config: HistoryConfigForModel<T>,\n ctx: { repoName: string; docId: string; before: T | null; after: T | null },\n): Promise<WriteEntryResult> {\n let toWrite: V2HistoryDoc | null = entry;\n if (config.onBeforeWrite) {\n toWrite = await config.onBeforeWrite(entry, ctx);\n }\n if (!toWrite) return { written: false, reason: \"dropped-by-onBeforeWrite\" };\n\n await historyRef.doc(toWrite.historyDocId).set(toWrite);\n return { written: true, entry: toWrite };\n}\n\n/**\n * Extract meta values from a Firestore document snapshot using either the\n * configured shadow field (default `_historyMeta`) or the declared `meta` map.\n * Missing fields become `null`.\n */\nexport function extractMeta<T>(\n source: Record<string, unknown> | null | undefined,\n config: HistoryConfigForModel<T>,\n): HistoryMeta {\n const src = source ?? {};\n const meta: HistoryMeta = {};\n\n const shadow = resolveShadowConfig(config);\n if (shadow) {\n const raw = src[shadow.key];\n if (raw && typeof raw === \"object\" && !Array.isArray(raw)) {\n const obj = raw as Record<string, unknown>;\n const pickShadowStr = (\n field: string | false,\n ): string | null | undefined => {\n if (field === false) return undefined;\n if (!(field in obj)) return undefined;\n const v = obj[field];\n if (v === undefined || v === null) return null;\n return String(v);\n };\n\n const userId = pickShadowStr(shadow.fields.userId);\n if (userId !== undefined) meta.userId = userId;\n const userEmail = pickShadowStr(shadow.fields.userEmail);\n if (userEmail !== undefined) meta.userEmail = userEmail;\n const reason = pickShadowStr(shadow.fields.reason);\n if (reason !== undefined) meta.reason = reason;\n const comment = pickShadowStr(shadow.fields.comment);\n if (comment !== undefined) meta.comment = comment;\n\n if (shadow.fields.extras !== false) {\n const rawExtras = obj[shadow.fields.extras];\n if (\n rawExtras &&\n typeof rawExtras === \"object\" &&\n !Array.isArray(rawExtras) &&\n Object.keys(rawExtras as Record<string, unknown>).length > 0\n ) {\n meta.extras = rawExtras as Record<string, unknown>;\n }\n }\n }\n return meta;\n }\n\n const m = config.meta;\n if (!m) return meta;\n\n const pickStr = (key?: string): string | null | undefined => {\n if (!key) return undefined;\n const v = src[key];\n if (v === undefined) return null;\n return v === null ? null : String(v);\n };\n\n const userId = pickStr(m.userId);\n if (userId !== undefined) meta.userId = userId;\n const userEmail = pickStr(m.userEmail);\n if (userEmail !== undefined) meta.userEmail = userEmail;\n const reason = pickStr(m.reason);\n if (reason !== undefined) meta.reason = reason;\n const comment = pickStr(m.comment);\n if (comment !== undefined) meta.comment = comment;\n\n if (m.extras && m.extras.length > 0) {\n const extras: Record<string, unknown> = {};\n let any = false;\n for (const k of m.extras) {\n if (k in src) {\n extras[k] = src[k];\n any = true;\n }\n }\n if (any) meta.extras = extras;\n }\n\n return meta;\n}\n\n/**\n * Returns all field names that should be excluded from the diff because\n * they hold shadow or declared meta info (so we don't log them as their own change).\n */\nexport function metaFieldsOf<T>(config: HistoryConfigForModel<T>): string[] {\n const list: string[] = [];\n const shadow = resolveShadowConfig(config);\n if (shadow) list.push(shadow.key);\n\n const m = config.meta;\n if (m) {\n if (m.userId) list.push(m.userId);\n if (m.userEmail) list.push(m.userEmail);\n if (m.reason) list.push(m.reason);\n if (m.comment) list.push(m.comment);\n if (m.extras) list.push(...m.extras);\n }\n return list;\n}\n","/**\n * `createHistoryTriggers` — generates Firestore Cloud Functions (v2) that\n * capture every write to a configured repository and write a v2 history\n * entry into the entity's history subcollection.\n *\n * Mirrors the DI / per-repo override pattern of {@link createSyncTriggers}.\n *\n * @example\n * ```ts\n * import { createHistoryTriggers } from \"@lpdjs/firestore-repo-service/history\";\n * import * as firestoreTriggers from \"firebase-functions/v2/firestore\";\n *\n * const triggers = createHistoryTriggers(repos, {\n * deps: { onDocumentWritten: firestoreTriggers.onDocumentWritten },\n * defaults: { ttl: { days: 365 } },\n * });\n *\n * export const { residences_onHistory, prevention_workshops_onHistory } = triggers;\n * ```\n */\n\nimport { parsePathTemplate } from \"../shared/path-template\";\nimport { computeDiff } from \"./diff\";\nimport {\n buildHistoryEntry,\n extractMeta,\n metaFieldsOf,\n writeHistoryEntry,\n} from \"./write\";\nimport type {\n HistoryConfigForModel,\n HistoryOperation,\n HistoryTriggersConfig,\n} from \"./types\";\n\nconst DEFAULT_SUBCOLLECTION = \"history\";\n\n/** Static, db-free metadata needed to register a history trigger. */\ninterface RepoHistoryMeta {\n historyConfig: (HistoryConfigForModel<unknown> & { enabled: boolean }) | undefined;\n systemKeys: string[];\n isGroup: boolean;\n /** Collection path of a non-group repo (used to derive the trigger path). */\n collectionPath: string | null;\n /** Auto-derived document trigger path template when path is a full template (e.g. \"residences/{residenceId}/res_events/{docId}\"). */\n documentPathTemplate: string | null;\n}\n\n/** Read history metadata from a **raw repository config** (no db resolution). */\nfunction metaFromConfig(cfg: any): RepoHistoryMeta {\n const historyConfig =\n cfg && typeof cfg.history === \"object\" && cfg.history !== null\n ? cfg.history\n : undefined;\n const systemKeys = [\n cfg?.documentKey,\n cfg?.pathKey,\n cfg?.createdKey,\n cfg?.updatedKey,\n ].filter((k): k is string => typeof k === \"string\");\n const rawPath = typeof cfg?.path === \"string\" ? cfg.path : null;\n const parsed = rawPath\n ? parsePathTemplate(rawPath, cfg?.documentKey ?? \"docId\")\n : null;\n return {\n historyConfig,\n systemKeys,\n isGroup: !!cfg?.isGroup,\n collectionPath: parsed ? parsed.collectionPath : null,\n documentPathTemplate:\n parsed && (!cfg?.isGroup || parsed.collectionPath.includes(\"/\"))\n ? parsed.documentPathTemplate\n : null,\n };\n}\n\n/** Read history metadata from a **resolved repository** (forces db resolution). */\nfunction metaFromRepo(repo: any): RepoHistoryMeta {\n const historyConfig =\n repo._historyConfig ??\n // Backward-compat: older repos exposed the config under `.history`\n // (before that key became the methods namespace).\n (typeof repo.history === \"object\" &&\n repo.history !== null &&\n \"enabled\" in repo.history\n ? repo.history\n : undefined);\n const collectionPath = repo._collectionPath ?? repo.ref?.path ?? null;\n const docTemplate =\n typeof repo._documentPathTemplate === \"string\"\n ? repo._documentPathTemplate\n : null;\n return {\n historyConfig,\n systemKeys: (repo._systemKeys as string[]) ?? [],\n isGroup: !!repo._isGroup,\n collectionPath,\n documentPathTemplate:\n docTemplate && (!repo._isGroup || (collectionPath && collectionPath.includes(\"/\")))\n ? docTemplate\n : null,\n };\n}\n\n/** Determine the trigger document path pattern for a non-group repo. */\nfunction buildDocumentPath(repoName: string, collectionPath: string | null): string | null {\n if (!collectionPath) {\n console.warn(\n `[HistoryTriggers] Cannot determine collection path for \"${repoName}\". Skipping.`,\n );\n return null;\n }\n return `${collectionPath}/{docId}`;\n}\n\nexport function createHistoryTriggers<M extends Record<string, any>>(\n repoMapping: M,\n config: HistoryTriggersConfig<NoInfer<M>>,\n): Record<string, any> {\n const { onDocumentWritten } = config.deps;\n const triggers: Record<string, any> = {};\n\n // Prefer the raw mapping config (exposed by `createRepositoryMapping`) so we\n // register triggers WITHOUT resolving Firestore — mirroring the lazy db\n // initialization used by the repository methods. Falls back to introspecting\n // the resolved repositories when a plain repo object is passed.\n const rawMapping: Record<string, any> | undefined = (repoMapping as any)\n ?.rawMapping;\n const entries: [string, RepoHistoryMeta][] = rawMapping\n ? Object.entries(rawMapping).map(([name, cfg]) => [name, metaFromConfig(cfg)])\n : (Object.entries(repoMapping) as [string, any][]).map(([name, repo]) => [\n name,\n metaFromRepo(repo),\n ]);\n\n for (const [repoName, meta] of entries) {\n const repoCfg = meta.historyConfig;\n if (!repoCfg?.enabled) continue;\n\n const subcollection = repoCfg.subcollection ?? DEFAULT_SUBCOLLECTION;\n const ttl = repoCfg.ttl ?? config.defaults?.ttl;\n\n const override = config.repos?.[repoName as keyof M & string];\n let documentPath: string | null;\n if (meta.isGroup) {\n const resolvedGroupPath =\n override?.triggerPath ?? meta.documentPathTemplate;\n if (!resolvedGroupPath) {\n console.warn(\n `[HistoryTriggers] Skipping collection-group repo \"${repoName}\". ` +\n \"Provide a triggerPath in the history triggers repos override or use a full path template.\",\n );\n continue;\n }\n documentPath = resolvedGroupPath;\n } else {\n documentPath =\n override?.triggerPath ??\n meta.documentPathTemplate ??\n buildDocumentPath(repoName, meta.collectionPath);\n }\n if (!documentPath) continue;\n\n const systemKeys: string[] = meta.systemKeys;\n const documentKey: string = systemKeys[0] ?? \"docId\";\n const metaFields = metaFieldsOf(repoCfg as HistoryConfigForModel<unknown>);\n\n const effectiveTriggerOptions = {\n ...config.triggerOptions,\n ...(repoCfg as any)?.triggerOptions,\n ...override?.triggerOptions,\n };\n const hasTriggerOptions = Object.keys(effectiveTriggerOptions).length > 0;\n\n const triggerHandler = async (event: any) => {\n try {\n const before = event.data?.before?.data() as\n | Record<string, unknown>\n | undefined;\n const after = event.data?.after?.data() as\n | Record<string, unknown>\n | undefined;\n\n let operation: HistoryOperation;\n if (!before && after) operation = \"create\";\n else if (before && !after) operation = \"delete\";\n else if (before && after) operation = \"update\";\n else return;\n\n const docId = String(\n after?.[documentKey] ??\n before?.[documentKey] ??\n event.params?.docId ??\n event.data?.after?.id ??\n event.data?.before?.id ??\n \"\",\n );\n if (!docId) return;\n\n const changes = computeDiff(before ?? {}, after ?? {}, {\n include: repoCfg.include as string[] | undefined,\n exclude: repoCfg.exclude as string[] | undefined,\n metaFields,\n systemKeys,\n });\n\n if (operation === \"update\" && Object.keys(changes).length === 0) {\n return; // no relevant change\n }\n\n const meta = extractMeta(\n after ?? before ?? null,\n repoCfg as HistoryConfigForModel<unknown>,\n );\n\n const entry = buildHistoryEntry({\n entityId: docId,\n operation,\n changes,\n meta,\n config: repoCfg as HistoryConfigForModel<unknown>,\n ttlOverride: ttl,\n });\n\n // Build the subcollection ref from the parent doc ref of the trigger.\n const parentRef =\n event.data?.after?.ref ?? event.data?.before?.ref;\n if (!parentRef) return;\n const historyRef = parentRef.collection(subcollection);\n\n await writeHistoryEntry(\n historyRef,\n entry,\n repoCfg as HistoryConfigForModel<unknown>,\n {\n repoName,\n docId,\n before: (before ?? null) as any,\n after: (after ?? null) as any,\n },\n );\n } catch (err) {\n console.error(\n `[HistoryTriggers] Failed to record history for \"${repoName}\":`,\n err,\n );\n }\n };\n\n triggers[`${repoName}_onHistory`] = hasTriggerOptions\n ? onDocumentWritten(\n { document: documentPath, ...effectiveTriggerOptions } as any,\n triggerHandler,\n )\n : onDocumentWritten(documentPath, triggerHandler);\n }\n\n return triggers;\n}\n","/**\n * v1 ↔ v2 normalisation. The reader returns a unified {@link HistoryEntry}\n * shape regardless of which schema version a Firestore document was written\n * with.\n *\n * v2 doc → pass-through.\n * v1 doc (single field per doc) → wrapped into a 1-field unified entry.\n * Consecutive v1 docs that share the same `historySetAt` timestamp\n * (within a small tolerance) are merged into a single entry, mimicking\n * the original \"one update -> N field docs\" intent.\n */\n\nimport { Timestamp } from \"firebase-admin/firestore\";\nimport type {\n HistoryEntry,\n HistoryFieldChange,\n HistoryMeta,\n HistoryValueType,\n V1HistoryDoc,\n V2HistoryDoc,\n} from \"./types\";\nimport { valueType } from \"./diff\";\n\n/** Default tolerance (ms) used to group v1 docs from the same update. */\nexport const DEFAULT_GROUP_TOLERANCE_MS = 5;\n\ntype AnyHistoryDoc = (V1HistoryDoc | V2HistoryDoc) & Record<string, unknown>;\n\nfunction isV2(doc: AnyHistoryDoc): doc is V2HistoryDoc & Record<string, unknown> {\n return doc.schemaVersion === 2;\n}\n\nfunction legacyTypeToHistoryType(t: unknown): HistoryValueType {\n if (typeof t !== \"string\") return \"object\";\n switch (t) {\n case \"string\":\n case \"number\":\n case \"boolean\":\n case \"object\":\n case \"array\":\n case \"timestamp\":\n case \"date\":\n case \"null\":\n case \"undefined\":\n return t;\n default:\n return \"object\";\n }\n}\n\nfunction v2ToEntry(doc: V2HistoryDoc): HistoryEntry {\n return {\n historyDocId: doc.historyDocId,\n historyToObjectId: doc.historyToObjectId,\n historySetAt: doc.historySetAt,\n schemaVersion: 2,\n operation: doc.operation,\n meta: doc.meta ?? {},\n ...(doc.custom ? { custom: doc.custom } : {}),\n changes: doc.changes ?? {},\n };\n}\n\nfunction v1MetaOf(doc: V1HistoryDoc & Record<string, unknown>): HistoryMeta {\n const meta: HistoryMeta = {};\n if (doc.historyUserId !== undefined) meta.userId = doc.historyUserId ?? null;\n if (doc.historyUserEmail !== undefined)\n meta.userEmail = doc.historyUserEmail ?? null;\n\n const extra = doc.extraHistoryDetails ?? null;\n if (extra) {\n if (extra.reason !== undefined) meta.reason = extra.reason ?? null;\n if (extra.comment !== undefined) meta.comment = extra.comment ?? null;\n }\n\n const extras: Record<string, unknown> = {};\n let anyExtra = false;\n if (doc.historyDetails && typeof doc.historyDetails === \"object\") {\n for (const [k, v] of Object.entries(doc.historyDetails)) {\n extras[k] = v;\n anyExtra = true;\n }\n }\n if (doc.extraContentKeys && typeof doc.extraContentKeys === \"object\") {\n for (const [k, v] of Object.entries(doc.extraContentKeys)) {\n extras[`content.${k}`] = v;\n anyExtra = true;\n }\n }\n if (anyExtra) meta.extras = extras;\n return meta;\n}\n\nfunction v1FieldChange(doc: V1HistoryDoc): HistoryFieldChange {\n const oldValue = doc.changes?.oldValue ?? null;\n const newValue = doc.changes?.newValue ?? null;\n const declaredOld = doc.types?.oldValue;\n const declaredNew = doc.types?.newValue;\n return {\n oldValue,\n newValue,\n type: {\n old: declaredOld\n ? legacyTypeToHistoryType(declaredOld)\n : valueType(oldValue),\n new: declaredNew\n ? legacyTypeToHistoryType(declaredNew)\n : valueType(newValue),\n },\n };\n}\n\nfunction v1ToEntry(doc: V1HistoryDoc): HistoryEntry {\n const change = v1FieldChange(doc);\n const meta = v1MetaOf(doc as V1HistoryDoc & Record<string, unknown>);\n return {\n historyDocId: doc.historyDocId,\n historyToObjectId: doc.historyToObjectId,\n historySetAt: doc.historySetAt,\n schemaVersion: 1,\n operation: \"update\",\n meta,\n changes: { [doc.field]: change },\n };\n}\n\nfunction tsClose(a: Timestamp, b: Timestamp, toleranceMs: number): boolean {\n return Math.abs(a.toMillis() - b.toMillis()) <= toleranceMs;\n}\n\nfunction sameAuthor(a: HistoryMeta, b: HistoryMeta): boolean {\n return (a.userId ?? null) === (b.userId ?? null);\n}\n\n/**\n * Normalise a list of raw Firestore docs into unified {@link HistoryEntry}.\n * The input list MUST be sorted by `historySetAt` (asc or desc — the function\n * preserves order). v1 docs sharing the same timestamp + author are merged.\n */\nexport function normalizeHistoryDocs(\n docs: AnyHistoryDoc[],\n opts: { groupToleranceMs?: number } = {},\n): HistoryEntry[] {\n const tol = opts.groupToleranceMs ?? DEFAULT_GROUP_TOLERANCE_MS;\n const out: HistoryEntry[] = [];\n\n for (const doc of docs) {\n if (isV2(doc)) {\n out.push(v2ToEntry(doc));\n continue;\n }\n\n const v1 = doc as V1HistoryDoc;\n const entry = v1ToEntry(v1);\n\n const last = out[out.length - 1];\n if (\n last &&\n last.schemaVersion === 1 &&\n tsClose(last.historySetAt, entry.historySetAt, tol) &&\n sameAuthor(last.meta, entry.meta)\n ) {\n // Merge into the previous v1 entry (same logical update).\n Object.assign(last.changes, entry.changes);\n // Keep earliest historyDocId (stable id of the group).\n } else {\n out.push(entry);\n }\n }\n\n return out;\n}\n","/**\n * `repo.history.*` read API.\n *\n * - `list(docId, opts)` → unified, paginated, normalised entries (v1 + v2).\n * - `raw(docId, opts)` → raw Firestore docs (no normalisation).\n * - `byField(docId, field, opts)` / `byOperation(docId, op, opts)` →\n * convenience wrappers.\n * - `recordManual(docId, payload)` → bypass the trigger and write a v2 entry\n * synchronously (use sparingly; prefer trigger-based capture).\n */\n\nimport {\n Timestamp,\n type CollectionReference,\n type DocumentReference,\n} from \"firebase-admin/firestore\";\nimport { getCurrentActor } from \"../shared/actor-context\";\nimport { computeDiff } from \"./diff\";\nimport { normalizeHistoryDocs } from \"./normalize\";\nimport {\n buildHistoryEntry,\n extractMeta,\n metaFieldsOf,\n writeHistoryEntry,\n} from \"./write\";\nimport type {\n HistoryConfigForModel,\n HistoryCustomData,\n HistoryCustomInput,\n HistoryEntry,\n HistoryListOptions,\n HistoryMeta,\n HistoryOperation,\n HistoryRawListOptions,\n V1HistoryDoc,\n V2HistoryDoc,\n} from \"./types\";\n\nconst DEFAULT_SUBCOLLECTION = \"history\";\nconst DEFAULT_LIMIT = 50;\n\nfunction getHistoryRef(\n documentRef: (...args: any[]) => DocumentReference,\n subcollection: string,\n args: any[],\n): CollectionReference {\n const docRef = documentRef(...args);\n return docRef.collection(subcollection);\n}\n\nfunction getDocId(args: any[]): string {\n return String(args[args.length - 1] ?? \"\");\n}\n\n/**\n * Build the `repo.history` API for a given configured repository.\n * Returns `null` when history is not enabled — the factory then skips\n * exposing the namespace.\n */\nexport function createHistoryMethods<T>(\n documentRef: (...args: any[]) => DocumentReference,\n systemKeys: string[],\n repoName: string,\n config: HistoryConfigForModel<T> & { enabled: boolean },\n): HistoryMethods<T> | null {\n if (!config?.enabled) return null;\n\n const subcollection = config.subcollection ?? DEFAULT_SUBCOLLECTION;\n\n async function raw(\n ...args: any[]\n ): Promise<Array<{ id: string; data: V1HistoryDoc | V2HistoryDoc }>> {\n let opts: HistoryRawListOptions = {};\n let pathArgs = args;\n const last = args[args.length - 1];\n if (\n last !== null &&\n typeof last === \"object\" &&\n !(last instanceof Timestamp) &&\n (\"limit\" in last || \"cursor\" in last || \"direction\" in last)\n ) {\n opts = last as HistoryRawListOptions;\n pathArgs = args.slice(0, -1);\n }\n\n const ref = getHistoryRef(documentRef, subcollection, pathArgs);\n const direction = opts.direction ?? \"desc\";\n let q = ref.orderBy(\"historySetAt\", direction);\n if (opts.cursor) q = q.startAfter(opts.cursor);\n if (opts.limit && opts.limit > 0) q = q.limit(opts.limit);\n\n const snap = await q.get();\n return snap.docs.map((d) => ({\n id: d.id,\n data: d.data() as V1HistoryDoc | V2HistoryDoc,\n }));\n }\n\n async function list(\n ...args: any[]\n ): Promise<HistoryEntry<T>[]> {\n let opts: HistoryListOptions<T> = {};\n let pathArgs = args;\n const last = args[args.length - 1];\n if (\n last !== null &&\n typeof last === \"object\" &&\n !(last instanceof Timestamp) &&\n (\"limit\" in last ||\n \"cursor\" in last ||\n \"direction\" in last ||\n \"fields\" in last ||\n \"operations\" in last)\n ) {\n opts = last as HistoryListOptions<T>;\n pathArgs = args.slice(0, -1);\n }\n\n const limit = opts.limit ?? DEFAULT_LIMIT;\n // Read a bit more from Firestore because v1 entries get merged afterwards.\n // Cap at limit * 8 to avoid pathological reads.\n const fetchLimit = Math.max(limit, Math.min(limit * 8, 500));\n\n const rawDocs = await raw(...pathArgs, {\n limit: fetchLimit,\n cursor: opts.cursor,\n direction: opts.direction ?? \"desc\",\n });\n\n let entries = normalizeHistoryDocs(\n rawDocs.map((d) => d.data) as any[],\n ) as HistoryEntry<T>[];\n\n if (opts.fields && opts.fields.length > 0) {\n const set = new Set<string>(opts.fields as string[]);\n entries = entries.filter((e) =>\n Object.keys(e.changes).some((k) => set.has(k)),\n );\n }\n if (opts.operations && opts.operations.length > 0) {\n const set = new Set<HistoryOperation>(opts.operations);\n entries = entries.filter((e) => set.has(e.operation));\n }\n\n return entries.slice(0, limit);\n }\n\n async function byField(\n ...args: any[]\n ): Promise<HistoryEntry<T>[]> {\n const last = args[args.length - 1];\n let opts: HistoryListOptions<T> = {};\n let field: keyof T & string;\n let pathArgs: any[];\n if (last !== null && typeof last === \"object\" && !(last instanceof Timestamp)) {\n opts = last as HistoryListOptions<T>;\n field = args[args.length - 2] as keyof T & string;\n pathArgs = args.slice(0, -2);\n } else {\n field = last as keyof T & string;\n pathArgs = args.slice(0, -1);\n }\n return list(...pathArgs, { ...opts, fields: [field] });\n }\n\n async function byOperation(\n ...args: any[]\n ): Promise<HistoryEntry<T>[]> {\n const last = args[args.length - 1];\n let opts: HistoryListOptions<T> = {};\n let op: HistoryOperation;\n let pathArgs: any[];\n if (last !== null && typeof last === \"object\" && !(last instanceof Timestamp)) {\n opts = last as HistoryListOptions<T>;\n op = args[args.length - 2] as HistoryOperation;\n pathArgs = args.slice(0, -2);\n } else {\n op = last as HistoryOperation;\n pathArgs = args.slice(0, -1);\n }\n return list(...pathArgs, { ...opts, operations: [op] });\n }\n\n function buildCustomPayload(input: HistoryCustomData): HistoryCustomData {\n const custom: HistoryCustomData = {\n title: input.title,\n display: input.display ?? true,\n };\n if (input.description !== undefined) custom.description = input.description;\n if (input.key !== undefined) custom.key = input.key;\n if (input.data !== undefined) custom.data = input.data;\n return custom;\n }\n\n function resolveActorMeta(): HistoryMeta {\n const actor = getCurrentActor();\n const fallback = config.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 return {\n userId,\n userEmail,\n ...(actor?.reason !== undefined ? { reason: actor.reason } : {}),\n ...(actor?.comment !== undefined ? { comment: actor.comment } : {}),\n ...(actor?.extras && Object.keys(actor.extras).length > 0\n ? { extras: actor.extras }\n : {}),\n };\n }\n\n /**\n * Manually record a history entry. Bypasses the trigger and lets the caller\n * pass an explicit before/after pair plus meta (useful for synchronous flows\n * that need richer context than what the trigger can extract).\n */\n async function recordManual(\n ...args: any[]\n ): Promise<HistoryEntry<T> | null> {\n const payload = args[args.length - 1] as {\n operation: HistoryOperation;\n before?: T | null;\n after?: T | null;\n meta?: HistoryMeta;\n custom?: HistoryCustomData;\n };\n const pathArgs = args.slice(0, -1);\n const entityId = getDocId(pathArgs);\n\n const changes = computeDiff(\n (payload.before ?? {}) as Record<string, unknown>,\n (payload.after ?? {}) as Record<string, unknown>,\n {\n include: config.include as string[] | undefined,\n exclude: config.exclude as string[] | undefined,\n metaFields: metaFieldsOf(config),\n systemKeys,\n },\n );\n if (\n payload.operation === \"update\" &&\n Object.keys(changes).length === 0\n ) {\n return null;\n }\n\n const fallbackMeta = extractMeta(\n (payload.after ?? payload.before ?? null) as Record<string, unknown> | null,\n config,\n );\n const actor = getCurrentActor();\n const actorMeta: HistoryMeta = actor\n ? {\n ...(actor.userId !== undefined ? { userId: actor.userId } : {}),\n ...(actor.userEmail !== undefined\n ? { userEmail: actor.userEmail }\n : {}),\n ...(actor.reason !== undefined ? { reason: actor.reason } : {}),\n ...(actor.comment !== undefined ? { comment: actor.comment } : {}),\n ...(actor.extras && Object.keys(actor.extras).length > 0\n ? { extras: actor.extras }\n : {}),\n }\n : {};\n const meta: HistoryMeta = {\n ...actorMeta,\n ...fallbackMeta,\n ...(payload.meta ?? {}),\n };\n const custom = payload.custom\n ? buildCustomPayload(payload.custom)\n : undefined;\n\n const entry = buildHistoryEntry({\n entityId,\n operation: payload.operation,\n changes,\n meta,\n custom,\n config,\n });\n\n const ref = getHistoryRef(documentRef, subcollection, pathArgs);\n const result = await writeHistoryEntry(ref, entry, config, {\n repoName,\n docId: entityId,\n before: payload.before ?? null,\n after: payload.after ?? null,\n });\n if (!result.written || !result.entry) return null;\n\n return {\n historyDocId: result.entry.historyDocId,\n historyToObjectId: result.entry.historyToObjectId,\n historySetAt: result.entry.historySetAt,\n schemaVersion: 2,\n operation: result.entry.operation,\n meta: result.entry.meta,\n ...(result.entry.custom ? { custom: result.entry.custom } : {}),\n changes: result.entry.changes,\n } as HistoryEntry<T>;\n }\n\n /**\n * Record a custom business action (`operation: \"custom\"`) independent of\n * model field diffs (e.g. manual invoice creation, PDF export, email sent).\n *\n * Automatically captures the active actor from `AsyncLocalStorage` (or\n * `fallbackActor`) and merges any explicit `meta` overrides on top.\n */\n async function recordCustom(\n ...args: any[]\n ): Promise<HistoryEntry<T> | null> {\n const payload = args[args.length - 1] as HistoryCustomInput;\n const pathArgs = args.slice(0, -1);\n const entityId = getDocId(pathArgs);\n\n const custom = buildCustomPayload(payload);\n const meta: HistoryMeta = {\n ...resolveActorMeta(),\n ...(payload.meta ?? {}),\n };\n\n const entry = buildHistoryEntry({\n entityId,\n operation: \"custom\",\n changes: {},\n meta,\n custom,\n config,\n });\n\n const ref = getHistoryRef(documentRef, subcollection, pathArgs);\n const result = await writeHistoryEntry(ref, entry, config, {\n repoName,\n docId: entityId,\n before: null,\n after: null,\n });\n if (!result.written || !result.entry) return null;\n\n return {\n historyDocId: result.entry.historyDocId,\n historyToObjectId: result.entry.historyToObjectId,\n historySetAt: result.entry.historySetAt,\n schemaVersion: 2,\n operation: result.entry.operation,\n meta: result.entry.meta,\n ...(result.entry.custom ? { custom: result.entry.custom } : {}),\n changes: result.entry.changes,\n } as HistoryEntry<T>;\n }\n\n return {\n list,\n raw,\n byField,\n byOperation,\n recordManual,\n recordCustom,\n } as HistoryMethods<T>;\n}\n\n/**\n * Public, strongly-typed surface of the `repo.history` namespace.\n *\n * Exposed on a repository **only when** `history.enabled: true` is set in\n * its config. Reads from the entity's `history` subcollection (or the custom\n * name set via `history.subcollection`) and normalises both schema versions\n * (v1 = one doc per modified field, v2 = one doc per write) into a single\n * {@link HistoryEntry} shape.\n *\n * ### Path arguments\n *\n * Every method's leading positional arguments mirror\n * `Parameters<repo.documentRef>`, so the call signature stays consistent with\n * the rest of the repo API:\n *\n * - **Top-level collection** (`documentRef: (db, docId) => …`)\n * → `repo.history.list(\"doc_42\", opts?)`\n * - **Subcollection** (`documentRef: (db, parentId, docId) => …`)\n * → `repo.history.list(\"parent_1\", \"doc_42\", opts?)`\n *\n * The trailing options/payload argument keeps the same position whatever the\n * depth of the path.\n *\n * ### Pagination\n *\n * `list` / `byField` / `byOperation` use real Firestore cursors via the\n * `cursor` + `limit` options on {@link HistoryListOptions} — no in-memory\n * slicing, safe for large histories.\n *\n * @example Basic read\n * ```ts\n * const entries = await repos.residences.history!.list(\"residence_123\", {\n * limit: 50,\n * direction: \"desc\",\n * });\n * for (const e of entries) {\n * console.log(e.historySetAt.toDate(), e.operation, e.meta.userId);\n * }\n * ```\n *\n * @example Filter by field (autocompleted on `keyof T`)\n * ```ts\n * const addressChanges = await repos.residences.history!.byField(\n * \"residence_123\",\n * \"address\",\n * );\n * ```\n *\n * @template T - The repository's model type. Field-name parameters\n * (e.g. `byField`'s `K`) and `HistoryEntry<T>` payloads\n * are derived from this.\n * @template PathArgs - Tuple of path-segment args inherited from the repo's\n * `documentRef`. Defaults to `[string]` (a single\n * `docId`) when used standalone.\n *\n * @see {@link createHistoryMethods} - factory used internally by `createRepository`.\n * @see {@link HistoryEntry} - normalised return shape.\n * @see {@link HistoryListOptions} - pagination + filter options.\n */\nexport interface HistoryMethods<T, PathArgs extends readonly unknown[] = [string]> {\n /**\n * List normalised history entries for a single document.\n *\n * Reads both v1 and v2 docs and folds v1 field-per-doc entries that share\n * the same author + timestamp (±5 ms) into a single logical entry, so the\n * caller never has to care about the storage version.\n *\n * @param args - `[...pathArgs, options?]`. `pathArgs` mirror the repo's\n * `documentRef`. `options` accepts `limit`, `cursor`,\n * `direction`, `fields`, `operations`.\n * @returns Array of {@link HistoryEntry} ordered by `historySetAt`\n * (`direction` defaults to `\"desc\"`).\n */\n list(\n ...args: [...PathArgs, HistoryListOptions<T>?]\n ): Promise<HistoryEntry<T>[]>;\n\n /**\n * Escape hatch returning **raw** Firestore documents (v1 or v2) without\n * normalisation. Use only when {@link list} doesn't expose the field you\n * need (custom legacy fields, debugging, migrations).\n *\n * @param args - `[...pathArgs, options?]`. Supports the same pagination\n * options as `list`, minus model-aware filters.\n */\n raw(\n ...args: [...PathArgs, HistoryRawListOptions?]\n ): Promise<Array<{ id: string; data: V1HistoryDoc | V2HistoryDoc }>>;\n\n /**\n * Convenience wrapper around {@link list} that only returns entries\n * touching a specific field. Field name is checked against `keyof T` at\n * compile time.\n *\n * @typeParam K - A literal key of the model `T`.\n * @param args - `[...pathArgs, field, options?]`.\n *\n * @example\n * ```ts\n * await repos.users.history!.byField(\"user_42\", \"email\");\n * ```\n */\n byField<K extends keyof T & string>(\n ...args: [...PathArgs, K, HistoryListOptions<T>?]\n ): Promise<HistoryEntry<T>[]>;\n\n /**\n * Convenience wrapper around {@link list} filtering on the operation type.\n *\n * @param args - `[...pathArgs, operation, options?]` where `operation` is\n * `\"create\" | \"update\" | \"delete\" | \"custom\"`.\n *\n * @example\n * ```ts\n * await repos.residences.history!.byOperation(\"residence_123\", \"custom\");\n * ```\n */\n byOperation(\n ...args: [...PathArgs, HistoryOperation, HistoryListOptions<T>?]\n ): Promise<HistoryEntry<T>[]>;\n\n /**\n * Synchronously append a custom history entry, bypassing the trigger.\n *\n * Useful when:\n * - You already have richer business context than the trigger can extract\n * (e.g. inside an HTTP handler that knows the authenticated user).\n * - You want to record a diff manually alongside explicit `meta` or `custom`.\n *\n * Honours the same `include` / `exclude` / meta auto-exclusion rules as\n * the trigger. Returns `null` when `operation === \"update\"` and the diff is\n * empty (no changes recorded).\n *\n * > ⚠️ Use sparingly — combining manual records with the trigger can\n * > produce duplicate entries if both fire for the same write.\n *\n * @param args - `[...pathArgs, payload]` where `payload` is\n * `{ operation, before?, after?, meta?, custom? }`.\n */\n recordManual(\n ...args: [\n ...PathArgs,\n {\n operation: HistoryOperation;\n before?: T | null;\n after?: T | null;\n meta?: HistoryMeta;\n custom?: HistoryCustomData;\n },\n ]\n ): Promise<HistoryEntry<T> | null>;\n\n /**\n * Record a custom business action (`operation: \"custom\"`) independent of\n * model fields (e.g. manual invoice creation, PDF export, email sent).\n *\n * Automatically resolves the current actor from `AsyncLocalStorage` (Hono\n * request / `withActor`, falling back to `history.fallbackActor`) and merges\n * any explicit `meta` overrides on top.\n *\n * @param args - `[...pathArgs, payload]` where `payload` is\n * `{ title, description?, key?, display?, data?, meta? }`.\n *\n * @example\n * ```ts\n * await repos.pros.history!.recordCustom(proId, {\n * key: \"invoice_create_manually\",\n * title: \"Création de la facture\",\n * description: \"Facture #F-2026-042 créée manuellement\",\n * data: { invoiceId: \"inv_123\", amount: 150 },\n * });\n * ```\n */\n recordCustom(\n ...args: [...PathArgs, HistoryCustomInput]\n ): Promise<HistoryEntry<T> | null>;\n}\n"]}
@@ -1,8 +1,10 @@
1
- import { H as HistoryTriggersConfig, e as HistoryOperation, h as HistoryFieldChange, f as HistoryMeta, g as HistoryConfigForModel, d as V2HistoryDoc, i as HistoryValueType, V as V1HistoryDoc, b as HistoryEntry } from '../types--RamYGF1.cjs';
2
- export { j as HistoryConfigBase, k as HistoryFirestoreTriggersDep, a as HistoryListOptions, c as HistoryRawListOptions, l as HistoryTriggerOptions, m as HistoryTriggerRepoOverride, T as TriggerOptions } from '../types--RamYGF1.cjs';
3
- export { H as HistoryMethods, c as createHistoryMethods } from '../read-B15YaPyR.cjs';
1
+ import { H as HistoryTriggersConfig, e as HistoryOperation, j as HistoryFieldChange, f as HistoryMeta, g as HistoryCustomData, i as HistoryConfigForModel, d as V2HistoryDoc, k as HistoryValueType, V as V1HistoryDoc, b as HistoryEntry } from '../types-D6zvWzRt.cjs';
2
+ export { D as DEFAULT_HISTORY_SHADOW_KEY, l as HistoryConfigBase, h as HistoryCustomInput, m as HistoryFallbackActor, n as HistoryFirestoreTriggersDep, a as HistoryListOptions, c as HistoryRawListOptions, o as HistoryShadowConfig, p as HistoryShadowFieldsConfig, q as HistoryTriggerOptions, r as HistoryTriggerRepoOverride, T as TriggerOptions } from '../types-D6zvWzRt.cjs';
3
+ export { H as HistoryMethods, c as createHistoryMethods } from '../read-Dfah1PPl.cjs';
4
4
  import { CollectionReference } from 'firebase-admin/firestore';
5
+ export { a as ActorResolver, b as ActorResolverFieldConfig, A as ActorResolverOption, H as HistoryActor, c as createActorContextMiddleware, d as createActorResolver, e as defaultActorResolver, g as getCurrentActor, s as setRequestActorMeta, w as withActor } from '../actor-context-DQZgWqj3.cjs';
5
6
  import 'firebase-functions/v2/firestore';
7
+ import 'hono';
6
8
 
7
9
  /**
8
10
  * `createHistoryTriggers` — generates Firestore Cloud Functions (v2) that
@@ -40,6 +42,7 @@ interface BuildEntryParams<T> {
40
42
  operation: HistoryOperation;
41
43
  changes: Record<string, HistoryFieldChange>;
42
44
  meta: HistoryMeta;
45
+ custom?: HistoryCustomData;
43
46
  config: HistoryConfigForModel<T>;
44
47
  ttlOverride?: {
45
48
  days: number;
@@ -62,16 +65,72 @@ declare function writeHistoryEntry<T>(historyRef: CollectionReference, entry: V2
62
65
  after: T | null;
63
66
  }): Promise<WriteEntryResult>;
64
67
  /**
65
- * Extract meta values from a Firestore document snapshot using the
66
- * declared meta config. Missing fields become `null`.
68
+ * Extract meta values from a Firestore document snapshot using either the
69
+ * configured shadow field (default `_historyMeta`) or the declared `meta` map.
70
+ * Missing fields become `null`.
67
71
  */
68
72
  declare function extractMeta<T>(source: Record<string, unknown> | null | undefined, config: HistoryConfigForModel<T>): HistoryMeta;
69
73
  /**
70
74
  * Returns all field names that should be excluded from the diff because
71
- * they're declared as meta fields (so we don't log them as their own change).
75
+ * they hold shadow or declared meta info (so we don't log them as their own change).
72
76
  */
73
77
  declare function metaFieldsOf<T>(config: HistoryConfigForModel<T>): string[];
74
78
 
79
+ /**
80
+ * Shadow metadata injection, resolution, and read-stripping helpers for the
81
+ * history module.
82
+ *
83
+ * Writes actor metadata from the cross-bundle `AsyncLocalStorage` context into
84
+ * a configurable shadow object (default `_historyMeta`) on Firestore documents
85
+ * without requiring any changes to model Zod schemas.
86
+ */
87
+
88
+ interface ResolvedShadowFields {
89
+ userId: string | false;
90
+ userEmail: string | false;
91
+ reason: string | false;
92
+ comment: string | false;
93
+ extras: string | false;
94
+ }
95
+ interface ResolvedShadowConfig {
96
+ key: string;
97
+ fields: ResolvedShadowFields;
98
+ }
99
+ /**
100
+ * Resolve the effective shadow storage configuration for a repository's
101
+ * `history` config, or `null` when shadow storage is inactive.
102
+ *
103
+ * Shadow storage is active whenever `history.enabled` is `true`, `shadow` is
104
+ * not `false`, and either `meta` is omitted or `shadow` is explicitly provided.
105
+ */
106
+ declare function resolveShadowConfig(config: HistoryConfigForModel<any> | undefined | null): ResolvedShadowConfig | null;
107
+ /**
108
+ * Return the active shadow key for a repository's history config, or `null`
109
+ * when shadow storage is inactive.
110
+ */
111
+ declare function getHistoryShadowKey(config: HistoryConfigForModel<any> | undefined | null): string | null;
112
+ /**
113
+ * Return the reserved identity/shadow keys that must be stripped from incoming
114
+ * CRUD payloads (anti-spoofing) and omitted from Create/Update OpenAPI schemas.
115
+ */
116
+ declare function getHistoryIdentityKeys(config: HistoryConfigForModel<any> | undefined | null): string[];
117
+ /**
118
+ * Strip the internal shadow field from a document returned by repository
119
+ * read/write methods (`get`, `query`, `paginate`, `create`, `set`, `update`,
120
+ * `transaction.get`). Zero-overhead no-op when `shadowKey` is `null` or absent.
121
+ */
122
+ declare function stripHistoryShadowField<T>(value: T, shadowKey: string | null | undefined): T;
123
+ /**
124
+ * Inject the current ALS actor metadata into the configurable shadow field on
125
+ * a Firestore write payload (`create`, `set`, `update`, `batch`, `transaction`,
126
+ * `bulk`).
127
+ *
128
+ * Always writes explicit `null` for absent `reason`, `comment`, `extras`, and
129
+ * applies `fallbackActor` when no actor is active so previous write metadata
130
+ * never leaks — including across Firestore `set(..., { merge: true })`.
131
+ */
132
+ declare function injectHistoryMeta(payload: Record<string, unknown>, historyConfig: HistoryConfigForModel<any> | undefined): void;
133
+
75
134
  /**
76
135
  * Diff helper for the history module.
77
136
  *
@@ -130,4 +189,5 @@ declare function normalizeHistoryDocs(docs: AnyHistoryDoc[], opts?: {
130
189
  groupToleranceMs?: number;
131
190
  }): HistoryEntry[];
132
191
 
133
- export { DEFAULT_GROUP_TOLERANCE_MS, HistoryConfigForModel, HistoryEntry, HistoryFieldChange, HistoryMeta, HistoryOperation, HistoryTriggersConfig, HistoryValueType, V1HistoryDoc, V2HistoryDoc, buildHistoryEntry, computeDiff, createHistoryTriggers, extractMeta, metaFieldsOf, normalizeHistoryDocs, valueType, valuesEqual, writeHistoryEntry };
192
+ export { DEFAULT_GROUP_TOLERANCE_MS, HistoryConfigForModel, HistoryCustomData, HistoryEntry, HistoryFieldChange, HistoryMeta, HistoryOperation, HistoryTriggersConfig, HistoryValueType, V1HistoryDoc, V2HistoryDoc, buildHistoryEntry, computeDiff, createHistoryTriggers, extractMeta, getHistoryIdentityKeys, getHistoryShadowKey, injectHistoryMeta, metaFieldsOf, normalizeHistoryDocs, resolveShadowConfig, stripHistoryShadowField, valueType, valuesEqual, writeHistoryEntry };
193
+ export type { ResolvedShadowConfig, ResolvedShadowFields };