@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,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.js';
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.js';
3
- export { H as HistoryMethods, c as createHistoryMethods } from '../read-15-TcgCz.js';
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.js';
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.js';
3
+ export { H as HistoryMethods, c as createHistoryMethods } from '../read-BPov7lws.js';
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.js';
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 };
@@ -1,2 +1,2 @@
1
- import {randomUUID}from'crypto';import {Timestamp}from'firebase-admin/firestore';function $(t){return t.match(/^\{([^}]+)\}$/)?.[1]?.trim()||null}function L(t,e="docId",r=false){if(typeof t!="string"||!t.trim())return {rawPath:t??"",collectionId:"",collectionPath:"",parentKeys:[],documentPathTemplate:null,hasTemplate:false};let n=t.split("/").map(o=>o.trim()).filter(Boolean);if(n.length===0)return {rawPath:t,collectionId:t,collectionPath:t,parentKeys:[],documentPathTemplate:null,hasTemplate:false};if(n.length===1){let o=n[0];return {rawPath:t,collectionId:o,collectionPath:o,parentKeys:[],documentPathTemplate:r?null:`${o}/{${e}}`,hasTemplate:t.includes("{")&&t.includes("}")}}let i=n.length%2===0,c=i?n.slice(0,-1):n,l=c[c.length-1],a=c.join("/"),g=c.slice(0,-1).map($).filter(o=>o!==null),s=i?n.join("/"):`${a}/{${e}}`;return {rawPath:t,collectionId:l,collectionPath:a,parentKeys:g,documentPathTemplate:s,hasTemplate:true}}function b(t){if(t===null)return "null";if(t===void 0)return "undefined";if(t instanceof Timestamp)return "timestamp";if(t instanceof Date)return "date";if(Array.isArray(t))return "array";let e=typeof t;return e==="string"||e==="number"||e==="boolean"?e:"object"}function V(t,e,r=new WeakMap){if(t===e)return true;if(t===null||e===null||t===void 0||e===void 0)return t===e;if(t instanceof Timestamp&&e instanceof Timestamp)return t.isEqual(e);if(t instanceof Date&&e instanceof Date)return t.getTime()===e.getTime();if(Array.isArray(t)||Array.isArray(e)){if(!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length)return false;if(r.get(t)===e)return true;r.set(t,e);for(let n=0;n<t.length;n++)if(!V(t[n],e[n],r))return false;return true}if(typeof t=="object"&&typeof e=="object"){if(t instanceof Date||e instanceof Date||t instanceof Timestamp||e instanceof Timestamp)return false;if(r.get(t)===e)return true;r.set(t,e);let n=Object.keys(t),i=Object.keys(e);if(n.length!==i.length)return false;for(let c of n)if(!Object.prototype.hasOwnProperty.call(e,c)||!V(t[c],e[c],r))return false;return true}return false}function x(t,e,r={}){let n=new Set([...r.exclude??[],...r.metaFields??[],...r.systemKeys??[]]),i=r.include?new Set(r.include):null,c=t??{},l=e??{},a=new Set([...Object.keys(c),...Object.keys(l)]),d={};for(let g of a){if(n.has(g)||i&&!i.has(g))continue;let s=c[g],o=l[g];V(s,o)||(d[g]={oldValue:s===void 0?null:s,newValue:o===void 0?null:o,type:{old:b(s),new:b(o)}});}return d}var W=7e5;function M(t){let e=t.ttlOverride??t.config.ttl,n={schemaVersion:2,historyDocId:randomUUID(),historyToObjectId:t.entityId,historySetAt:Timestamp.now(),operation:t.operation,meta:t.meta,changes:t.changes};e&&(n.expiresAt=Timestamp.fromMillis(Date.now()+e.days*24*60*60*1e3));let i=c=>{try{return Buffer.byteLength(JSON.stringify(c,(l,a)=>a instanceof Timestamp?a.toMillis():a),"utf8")}catch{return 0}};if(i(n.changes)>W){let c={};for(let[l,a]of Object.entries(n.changes)){let d=i(a.oldValue),g=i(a.newValue);c[l]={oldValue:d>5e4?"[truncated]":a.oldValue,newValue:g>5e4?"[truncated]":a.newValue,type:a.type};}n.changes=c,n._truncated=true;}return n}async function R(t,e,r,n){let i=e;return r.onBeforeWrite&&(i=await r.onBeforeWrite(e,n)),i?(await t.doc(i.historyDocId).set(i),{written:true,entry:i}):{written:false,reason:"dropped-by-onBeforeWrite"}}function P(t,e){let r=t??{},n={},i=e.meta;if(!i)return n;let c=s=>{if(!s)return;let o=r[s];return o===void 0||o===null?null:String(o)},l=c(i.userId);l!==void 0&&(n.userId=l);let a=c(i.userEmail);a!==void 0&&(n.userEmail=a);let d=c(i.reason);d!==void 0&&(n.reason=d);let g=c(i.comment);if(g!==void 0&&(n.comment=g),i.extras&&i.extras.length>0){let s={},o=false;for(let y of i.extras)y in r&&(s[y]=r[y],o=true);o&&(n.extras=s);}return n}function E(t){let e=t.meta;if(!e)return [];let r=[];return e.userId&&r.push(e.userId),e.userEmail&&r.push(e.userEmail),e.reason&&r.push(e.reason),e.comment&&r.push(e.comment),e.extras&&r.push(...e.extras),r}var z="history";function q(t){let e=t&&typeof t.history=="object"&&t.history!==null?t.history:void 0,r=[t?.documentKey,t?.pathKey,t?.createdKey,t?.updatedKey].filter(c=>typeof c=="string"),n=typeof t?.path=="string"?t.path:null,i=n?L(n,t?.documentKey??"docId"):null;return {historyConfig:e,systemKeys:r,isGroup:!!t?.isGroup,collectionPath:i?i.collectionPath:null,documentPathTemplate:i&&(!t?.isGroup||i.collectionPath.includes("/"))?i.documentPathTemplate:null}}function J(t){let e=t._historyConfig??(typeof t.history=="object"&&t.history!==null&&"enabled"in t.history?t.history:void 0),r=t._collectionPath??t.ref?.path??null,n=typeof t._documentPathTemplate=="string"?t._documentPathTemplate:null;return {historyConfig:e,systemKeys:t._systemKeys??[],isGroup:!!t._isGroup,collectionPath:r,documentPathTemplate:n&&(!t._isGroup||r&&r.includes("/"))?n:null}}function X(t,e){return e?`${e}/{docId}`:(console.warn(`[HistoryTriggers] Cannot determine collection path for "${t}". Skipping.`),null)}function Y(t,e){let{onDocumentWritten:r}=e.deps,n={},i=t?.rawMapping,c=i?Object.entries(i).map(([l,a])=>[l,q(a)]):Object.entries(t).map(([l,a])=>[l,J(a)]);for(let[l,a]of c){let d=a.historyConfig;if(!d?.enabled)continue;let g=d.subcollection??z,s=d.ttl??e.defaults?.ttl,o=e.repos?.[l],y;if(a.isGroup){let f=o?.triggerPath??a.documentPathTemplate;if(!f){console.warn(`[HistoryTriggers] Skipping collection-group repo "${l}". Provide a triggerPath in the history triggers repos override or use a full path template.`);continue}y=f;}else y=o?.triggerPath??a.documentPathTemplate??X(l,a.collectionPath);if(!y)continue;let u=a.systemKeys,p=u[0]??"docId",D=E(d),h={...e.triggerOptions,...d?.triggerOptions,...o?.triggerOptions},T=Object.keys(h).length>0,m=async f=>{try{let H=f.data?.before?.data(),O=f.data?.after?.data(),w;if(!H&&O)w="create";else if(H&&!O)w="delete";else if(H&&O)w="update";else return;let C=String(O?.[p]??H?.[p]??f.params?.docId??f.data?.after?.id??f.data?.before?.id??"");if(!C)return;let j=x(H??{},O??{},{include:d.include,exclude:d.exclude,metaFields:D,systemKeys:u});if(w==="update"&&Object.keys(j).length===0)return;let v=P(O??H??null,d),U=M({entityId:C,operation:w,changes:j,meta:v,config:d,ttlOverride:s}),S=f.data?.after?.ref??f.data?.before?.ref;if(!S)return;let G=S.collection(g);await R(G,U,d,{repoName:l,docId:C,before:H??null,after:O??null});}catch(H){console.error(`[HistoryTriggers] Failed to record history for "${l}":`,H);}};n[`${l}_onHistory`]=r(T?{document:y,...h}:y,m);}return n}var _=5;function Q(t){return t.schemaVersion===2}function K(t){if(typeof t!="string")return "object";switch(t){case "string":case "number":case "boolean":case "object":case "array":case "timestamp":case "date":case "null":case "undefined":return t;default:return "object"}}function Z(t){return {historyDocId:t.historyDocId,historyToObjectId:t.historyToObjectId,historySetAt:t.historySetAt,schemaVersion:2,operation:t.operation,meta:t.meta??{},changes:t.changes??{}}}function tt(t){let e={};t.historyUserId!==void 0&&(e.userId=t.historyUserId??null),t.historyUserEmail!==void 0&&(e.userEmail=t.historyUserEmail??null);let r=t.extraHistoryDetails??null;r&&(r.reason!==void 0&&(e.reason=r.reason??null),r.comment!==void 0&&(e.comment=r.comment??null));let n={},i=false;if(t.historyDetails&&typeof t.historyDetails=="object")for(let[c,l]of Object.entries(t.historyDetails))n[c]=l,i=true;if(t.extraContentKeys&&typeof t.extraContentKeys=="object")for(let[c,l]of Object.entries(t.extraContentKeys))n[`content.${c}`]=l,i=true;return i&&(e.extras=n),e}function et(t){let e=t.changes?.oldValue??null,r=t.changes?.newValue??null,n=t.types?.oldValue,i=t.types?.newValue;return {oldValue:e,newValue:r,type:{old:n?K(n):b(e),new:i?K(i):b(r)}}}function nt(t){let e=et(t),r=tt(t);return {historyDocId:t.historyDocId,historyToObjectId:t.historyToObjectId,historySetAt:t.historySetAt,schemaVersion:1,operation:"update",meta:r,changes:{[t.field]:e}}}function ot(t,e,r){return Math.abs(t.toMillis()-e.toMillis())<=r}function rt(t,e){return (t.userId??null)===(e.userId??null)}function F(t,e={}){let r=e.groupToleranceMs??_,n=[];for(let i of t){if(Q(i)){n.push(Z(i));continue}let l=nt(i),a=n[n.length-1];a&&a.schemaVersion===1&&ot(a.historySetAt,l.historySetAt,r)&&rt(a.meta,l.meta)?Object.assign(a.changes,l.changes):n.push(l);}return n}var it="history",st=50;function B(t,e,r){return t(...r).collection(e)}function at(t){return String(t[t.length-1]??"")}function lt(t,e,r,n){if(!n?.enabled)return null;let i=n.subcollection??it;async function c(...s){let o={},y=s,u=s[s.length-1];u!==null&&typeof u=="object"&&!(u instanceof Timestamp)&&("limit"in u||"cursor"in u||"direction"in u)&&(o=u,y=s.slice(0,-1));let p=B(t,i,y),D=o.direction??"desc",h=p.orderBy("historySetAt",D);return o.cursor&&(h=h.startAfter(o.cursor)),o.limit&&o.limit>0&&(h=h.limit(o.limit)),(await h.get()).docs.map(m=>({id:m.id,data:m.data()}))}async function l(...s){let o={},y=s,u=s[s.length-1];u!==null&&typeof u=="object"&&!(u instanceof Timestamp)&&("limit"in u||"cursor"in u||"direction"in u||"fields"in u||"operations"in u)&&(o=u,y=s.slice(0,-1));let p=o.limit??st,D=Math.max(p,Math.min(p*8,500)),h=await c(...y,{limit:D,cursor:o.cursor,direction:o.direction??"desc"}),T=F(h.map(m=>m.data));if(o.fields&&o.fields.length>0){let m=new Set(o.fields);T=T.filter(f=>Object.keys(f.changes).some(H=>m.has(H)));}if(o.operations&&o.operations.length>0){let m=new Set(o.operations);T=T.filter(f=>m.has(f.operation));}return T.slice(0,p)}async function a(...s){let o=s[s.length-1],y={},u,p;return o!==null&&typeof o=="object"&&!(o instanceof Timestamp)?(y=o,u=s[s.length-2],p=s.slice(0,-2)):(u=o,p=s.slice(0,-1)),l(...p,{...y,fields:[u]})}async function d(...s){let o=s[s.length-1],y={},u,p;return o!==null&&typeof o=="object"&&!(o instanceof Timestamp)?(y=o,u=s[s.length-2],p=s.slice(0,-2)):(u=o,p=s.slice(0,-1)),l(...p,{...y,operations:[u]})}async function g(...s){let o=s[s.length-1],y=s.slice(0,-1),u=at(y),p=x(o.before??{},o.after??{},{include:n.include,exclude:n.exclude,metaFields:E(n),systemKeys:e});if(o.operation==="update"&&Object.keys(p).length===0)return null;let h={...P(o.after??o.before??null,n),...o.meta??{}},T=M({entityId:u,operation:o.operation,changes:p,meta:h,config:n}),m=B(t,i,y),f=await R(m,T,n,{repoName:r,docId:u,before:o.before??null,after:o.after??null});return !f.written||!f.entry?null:{historyDocId:f.entry.historyDocId,historyToObjectId:f.entry.historyToObjectId,historySetAt:f.entry.historySetAt,schemaVersion:2,operation:f.entry.operation,meta:f.entry.meta,changes:f.entry.changes}}return {list:l,raw:c,byField:a,byOperation:d,recordManual:g}}export{_ as DEFAULT_GROUP_TOLERANCE_MS,M as buildHistoryEntry,x as computeDiff,lt as createHistoryMethods,Y as createHistoryTriggers,P as extractMeta,E as metaFieldsOf,F as normalizeHistoryDocs,b as valueType,V as valuesEqual,R as writeHistoryEntry};//# sourceMappingURL=index.js.map
1
+ import {randomUUID}from'crypto';import {Timestamp}from'firebase-admin/firestore';import {AsyncLocalStorage}from'async_hooks';function te(e){return e.match(/^\{([^}]+)\}$/)?.[1]?.trim()||null}function N(e,t="docId",r=false){if(typeof e!="string"||!e.trim())return {rawPath:e??"",collectionId:"",collectionPath:"",parentKeys:[],documentPathTemplate:null,hasTemplate:false};let n=e.split("/").map(a=>a.trim()).filter(Boolean);if(n.length===0)return {rawPath:e,collectionId:e,collectionPath:e,parentKeys:[],documentPathTemplate:null,hasTemplate:false};if(n.length===1){let a=n[0];return {rawPath:e,collectionId:a,collectionPath:a,parentKeys:[],documentPathTemplate:r?null:`${a}/{${t}}`,hasTemplate:e.includes("{")&&e.includes("}")}}let i=n.length%2===0,c=i?n.slice(0,-1):n,u=c[c.length-1],l=c.join("/"),T=c.slice(0,-1).map(te).filter(a=>a!==null),p=i?n.join("/"):`${l}/{${t}}`;return {rawPath:e,collectionId:u,collectionPath:l,parentKeys:T,documentPathTemplate:p,hasTemplate:true}}function R(e){if(e===null)return "null";if(e===void 0)return "undefined";if(e instanceof Timestamp)return "timestamp";if(e instanceof Date)return "date";if(Array.isArray(e))return "array";let t=typeof e;return t==="string"||t==="number"||t==="boolean"?t:"object"}function P(e,t,r=new WeakMap){if(e===t)return true;if(e===null||t===null||e===void 0||t===void 0)return e===t;if(e instanceof Timestamp&&t instanceof Timestamp)return e.isEqual(t);if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return false;if(r.get(e)===t)return true;r.set(e,t);for(let n=0;n<e.length;n++)if(!P(e[n],t[n],r))return false;return true}if(typeof e=="object"&&typeof t=="object"){if(e instanceof Date||t instanceof Date||e instanceof Timestamp||t instanceof Timestamp)return false;if(r.get(e)===t)return true;r.set(e,t);let n=Object.keys(e),i=Object.keys(t);if(n.length!==i.length)return false;for(let c of n)if(!Object.prototype.hasOwnProperty.call(t,c)||!P(e[c],t[c],r))return false;return true}return false}function M(e,t,r={}){let n=new Set([...r.exclude??[],...r.metaFields??[],...r.systemKeys??[]]),i=r.include?new Set(r.include):null,c=e??{},u=t??{},l=new Set([...Object.keys(c),...Object.keys(u)]),y={};for(let T of l){if(n.has(T)||i&&!i.has(T))continue;let p=c[T],a=u[T];P(p,a)||(y[T]={oldValue:p===void 0?null:p,newValue:a===void 0?null:a,type:{old:R(p),new:R(a)}});}return y}var K=Symbol.for("@lpdjs/firestore-repo-service:actorContext"),L=globalThis,v=L[K]??(L[K]=new AsyncLocalStorage);function re(e,t){if(!t.includes("."))return e[t];let r=e;for(let n of t.split(".")){if(!r||typeof r!="object")return;r=r[n];}return r}function q(e,t){for(let r of t){let n=re(e,r);if(typeof n=="string"&&n.length>0)return n;if(typeof n=="number")return String(n)}return null}function z(e,t){if(t===false)return;let r=e?.req?.header;if(typeof r!="function")return;let n=r.call(e.req,t);return typeof n=="string"&&n.length>0?n:void 0}function _(e={}){let t=e.contextKeys??["user","docsUser"],r=e.userIdFields??["uid","id","sub"],n=e.userEmailFields??["email"],i=e.reasonHeader===void 0?"x-history-reason":e.reasonHeader,c=e.commentHeader===void 0?"x-history-comment":e.commentHeader,u=e.extras;return l=>{let y=null,T=l?.get;if(typeof T=="function")for(let o of t){let s=T.call(l,o);if(s&&typeof s=="object"){y=s;break}}let p=z(l,i),a=z(l,c),g=u?u(l,y):void 0;return y?{userId:q(y,r),userEmail:q(y,n),...p!==void 0?{reason:p}:{},...a!==void 0?{comment:a}:{},...g?{extras:g}:{}}:p===void 0&&a===void 0&&!g?null:{...p!==void 0?{reason:p}:{},...a!==void 0?{comment:a}:{},...g?{extras:g}:{}}}}var Y=_();function oe(e){if(e)return typeof e=="function"?e:_(e)}function se(e){let t=oe(e);return async(r,n)=>{await v.run({c:r,resolver:t},async()=>{await n();});}}function D(){let e=v.getStore();if(!e)return null;let t=null;if(e.c)try{t=(e.resolver??Y)(e.c);}catch{t=null;}if(!t&&!e.override)return null;let r={...t??{}};return e.override&&(e.override.userId!==void 0&&(r.userId=e.override.userId),e.override.userEmail!==void 0&&(r.userEmail=e.override.userEmail),e.override.reason!==void 0&&(r.reason=e.override.reason),e.override.comment!==void 0&&(r.comment=e.override.comment),e.override.extras!==void 0&&(r.extras={...t?.extras??{},...e.override.extras})),r}function ie(e,t){return v.run({override:{...e}},t)}function ae(e){let t=v.getStore();if(!t)return false;let r=t.override??{},n={...r,...e};return (r.extras||e.extras)&&(n.extras={...r.extras??{},...e.extras??{}}),t.override=n,true}var U="_historyMeta";function A(e){if(!e?.enabled||e.shadow===false||e.meta&&e.shadow===void 0)return null;let t=e.shadow,r=typeof t=="string"&&t.trim().length>0?t.trim():typeof t=="object"&&t!==null&&typeof t.key=="string"&&t.key.trim().length>0?t.key.trim():U,n=typeof t=="object"&&t!==null?t.fields:void 0;return {key:r,fields:{userId:n?.userId??"userId",userEmail:n?.userEmail??"userEmail",reason:n?.reason??"reason",comment:n?.comment??"comment",extras:n?.extras??"extras"}}}function le(e){return A(e)?.key??null}function ce(e){let t=A(e);return t?[t.key]:[]}function ue(e,t){if(!t||!e||typeof e!="object"||Array.isArray(e))return e;let r=e;if(!(t in r))return e;let{[t]:n,...i}=r;return i}function de(e,t){if(!t?.enabled||t.autoInjectMeta===false)return;let r=A(t);if(!r)return;let n=D(),i=t.fallbackActor??{},c=n?.userId!==void 0?n.userId:i.userId??null,u=n?.userEmail!==void 0?n.userEmail:i.userEmail??null,l=n?.reason??null,y=n?.comment??null,T=n?.extras&&Object.keys(n.extras).length>0?n.extras:null,p={},{fields:a}=r;a.userId!==false&&(p[a.userId]=c),a.userEmail!==false&&(p[a.userEmail]=u),a.reason!==false&&(p[a.reason]=l),a.comment!==false&&(p[a.comment]=y),a.extras!==false&&(p[a.extras]=T),e[r.key]=p;}var ye=7e5;function C(e){let t=e.ttlOverride??e.config.ttl,n={schemaVersion:2,historyDocId:randomUUID(),historyToObjectId:e.entityId,historySetAt:Timestamp.now(),operation:e.operation,meta:e.meta,...e.custom?{custom:e.custom}:{},changes:e.changes};t&&(n.expiresAt=Timestamp.fromMillis(Date.now()+t.days*24*60*60*1e3));let i=c=>{try{return Buffer.byteLength(JSON.stringify(c,(u,l)=>l instanceof Timestamp?l.toMillis():l),"utf8")}catch{return 0}};if(i(n.changes)>ye){let c={};for(let[u,l]of Object.entries(n.changes)){let y=i(l.oldValue),T=i(l.newValue);c[u]={oldValue:y>5e4?"[truncated]":l.oldValue,newValue:T>5e4?"[truncated]":l.newValue,type:l.type};}n.changes=c,n._truncated=true;}return n}async function I(e,t,r,n){let i=t;return r.onBeforeWrite&&(i=await r.onBeforeWrite(t,n)),i?(await e.doc(i.historyDocId).set(i),{written:true,entry:i}):{written:false,reason:"dropped-by-onBeforeWrite"}}function F(e,t){let r=e??{},n={},i=A(t);if(i){let a=r[i.key];if(a&&typeof a=="object"&&!Array.isArray(a)){let g=a,o=x=>{if(x===false||!(x in g))return;let f=g[x];return f==null?null:String(f)},s=o(i.fields.userId);s!==void 0&&(n.userId=s);let h=o(i.fields.userEmail);h!==void 0&&(n.userEmail=h);let d=o(i.fields.reason);d!==void 0&&(n.reason=d);let H=o(i.fields.comment);if(H!==void 0&&(n.comment=H),i.fields.extras!==false){let x=g[i.fields.extras];x&&typeof x=="object"&&!Array.isArray(x)&&Object.keys(x).length>0&&(n.extras=x);}}return n}let c=t.meta;if(!c)return n;let u=a=>{if(!a)return;let g=r[a];return g===void 0||g===null?null:String(g)},l=u(c.userId);l!==void 0&&(n.userId=l);let y=u(c.userEmail);y!==void 0&&(n.userEmail=y);let T=u(c.reason);T!==void 0&&(n.reason=T);let p=u(c.comment);if(p!==void 0&&(n.comment=p),c.extras&&c.extras.length>0){let a={},g=false;for(let o of c.extras)o in r&&(a[o]=r[o],g=true);g&&(n.extras=a);}return n}function S(e){let t=[],r=A(e);r&&t.push(r.key);let n=e.meta;return n&&(n.userId&&t.push(n.userId),n.userEmail&&t.push(n.userEmail),n.reason&&t.push(n.reason),n.comment&&t.push(n.comment),n.extras&&t.push(...n.extras)),t}var me="history";function pe(e){let t=e&&typeof e.history=="object"&&e.history!==null?e.history:void 0,r=[e?.documentKey,e?.pathKey,e?.createdKey,e?.updatedKey].filter(c=>typeof c=="string"),n=typeof e?.path=="string"?e.path:null,i=n?N(n,e?.documentKey??"docId"):null;return {historyConfig:t,systemKeys:r,isGroup:!!e?.isGroup,collectionPath:i?i.collectionPath:null,documentPathTemplate:i&&(!e?.isGroup||i.collectionPath.includes("/"))?i.documentPathTemplate:null}}function ge(e){let t=e._historyConfig??(typeof e.history=="object"&&e.history!==null&&"enabled"in e.history?e.history:void 0),r=e._collectionPath??e.ref?.path??null,n=typeof e._documentPathTemplate=="string"?e._documentPathTemplate:null;return {historyConfig:t,systemKeys:e._systemKeys??[],isGroup:!!e._isGroup,collectionPath:r,documentPathTemplate:n&&(!e._isGroup||r&&r.includes("/"))?n:null}}function he(e,t){return t?`${t}/{docId}`:(console.warn(`[HistoryTriggers] Cannot determine collection path for "${e}". Skipping.`),null)}function He(e,t){let{onDocumentWritten:r}=t.deps,n={},i=e?.rawMapping,c=i?Object.entries(i).map(([u,l])=>[u,pe(l)]):Object.entries(e).map(([u,l])=>[u,ge(l)]);for(let[u,l]of c){let y=l.historyConfig;if(!y?.enabled)continue;let T=y.subcollection??me,p=y.ttl??t.defaults?.ttl,a=t.repos?.[u],g;if(l.isGroup){let f=a?.triggerPath??l.documentPathTemplate;if(!f){console.warn(`[HistoryTriggers] Skipping collection-group repo "${u}". Provide a triggerPath in the history triggers repos override or use a full path template.`);continue}g=f;}else g=a?.triggerPath??l.documentPathTemplate??he(u,l.collectionPath);if(!g)continue;let o=l.systemKeys,s=o[0]??"docId",h=S(y),d={...t.triggerOptions,...y?.triggerOptions,...a?.triggerOptions},H=Object.keys(d).length>0,x=async f=>{try{let w=f.data?.before?.data(),m=f.data?.after?.data(),k;if(!w&&m)k="create";else if(w&&!m)k="delete";else if(w&&m)k="update";else return;let O=String(m?.[s]??w?.[s]??f.params?.docId??f.data?.after?.id??f.data?.before?.id??"");if(!O)return;let V=M(w??{},m??{},{include:y.include,exclude:y.exclude,metaFields:h,systemKeys:o});if(k==="update"&&Object.keys(V).length===0)return;let b=F(m??w??null,y),Z=C({entityId:O,operation:k,changes:V,meta:b,config:y,ttlOverride:p}),$=f.data?.after?.ref??f.data?.before?.ref;if(!$)return;let ee=$.collection(T);await I(ee,Z,y,{repoName:u,docId:O,before:w??null,after:m??null});}catch(w){console.error(`[HistoryTriggers] Failed to record history for "${u}":`,w);}};n[`${u}_onHistory`]=r(H?{document:g,...d}:g,x);}return n}var X=5;function Te(e){return e.schemaVersion===2}function J(e){if(typeof e!="string")return "object";switch(e){case "string":case "number":case "boolean":case "object":case "array":case "timestamp":case "date":case "null":case "undefined":return e;default:return "object"}}function xe(e){return {historyDocId:e.historyDocId,historyToObjectId:e.historyToObjectId,historySetAt:e.historySetAt,schemaVersion:2,operation:e.operation,meta:e.meta??{},...e.custom?{custom:e.custom}:{},changes:e.changes??{}}}function we(e){let t={};e.historyUserId!==void 0&&(t.userId=e.historyUserId??null),e.historyUserEmail!==void 0&&(t.userEmail=e.historyUserEmail??null);let r=e.extraHistoryDetails??null;r&&(r.reason!==void 0&&(t.reason=r.reason??null),r.comment!==void 0&&(t.comment=r.comment??null));let n={},i=false;if(e.historyDetails&&typeof e.historyDetails=="object")for(let[c,u]of Object.entries(e.historyDetails))n[c]=u,i=true;if(e.extraContentKeys&&typeof e.extraContentKeys=="object")for(let[c,u]of Object.entries(e.extraContentKeys))n[`content.${c}`]=u,i=true;return i&&(t.extras=n),t}function be(e){let t=e.changes?.oldValue??null,r=e.changes?.newValue??null,n=e.types?.oldValue,i=e.types?.newValue;return {oldValue:t,newValue:r,type:{old:n?J(n):R(t),new:i?J(i):R(r)}}}function ke(e){let t=be(e),r=we(e);return {historyDocId:e.historyDocId,historyToObjectId:e.historyToObjectId,historySetAt:e.historySetAt,schemaVersion:1,operation:"update",meta:r,changes:{[e.field]:t}}}function Oe(e,t,r){return Math.abs(e.toMillis()-t.toMillis())<=r}function Ae(e,t){return (e.userId??null)===(t.userId??null)}function W(e,t={}){let r=t.groupToleranceMs??X,n=[];for(let i of e){if(Te(i)){n.push(xe(i));continue}let u=ke(i),l=n[n.length-1];l&&l.schemaVersion===1&&Oe(l.historySetAt,u.historySetAt,r)&&Ae(l.meta,u.meta)?Object.assign(l.changes,u.changes):n.push(u);}return n}var Re="history",De=50;function G(e,t,r){return e(...r).collection(t)}function Q(e){return String(e[e.length-1]??"")}function Ce(e,t,r,n){if(!n?.enabled)return null;let i=n.subcollection??Re;async function c(...o){let s={},h=o,d=o[o.length-1];d!==null&&typeof d=="object"&&!(d instanceof Timestamp)&&("limit"in d||"cursor"in d||"direction"in d)&&(s=d,h=o.slice(0,-1));let H=G(e,i,h),x=s.direction??"desc",f=H.orderBy("historySetAt",x);return s.cursor&&(f=f.startAfter(s.cursor)),s.limit&&s.limit>0&&(f=f.limit(s.limit)),(await f.get()).docs.map(m=>({id:m.id,data:m.data()}))}async function u(...o){let s={},h=o,d=o[o.length-1];d!==null&&typeof d=="object"&&!(d instanceof Timestamp)&&("limit"in d||"cursor"in d||"direction"in d||"fields"in d||"operations"in d)&&(s=d,h=o.slice(0,-1));let H=s.limit??De,x=Math.max(H,Math.min(H*8,500)),f=await c(...h,{limit:x,cursor:s.cursor,direction:s.direction??"desc"}),w=W(f.map(m=>m.data));if(s.fields&&s.fields.length>0){let m=new Set(s.fields);w=w.filter(k=>Object.keys(k.changes).some(O=>m.has(O)));}if(s.operations&&s.operations.length>0){let m=new Set(s.operations);w=w.filter(k=>m.has(k.operation));}return w.slice(0,H)}async function l(...o){let s=o[o.length-1],h={},d,H;return s!==null&&typeof s=="object"&&!(s instanceof Timestamp)?(h=s,d=o[o.length-2],H=o.slice(0,-2)):(d=s,H=o.slice(0,-1)),u(...H,{...h,fields:[d]})}async function y(...o){let s=o[o.length-1],h={},d,H;return s!==null&&typeof s=="object"&&!(s instanceof Timestamp)?(h=s,d=o[o.length-2],H=o.slice(0,-2)):(d=s,H=o.slice(0,-1)),u(...H,{...h,operations:[d]})}function T(o){let s={title:o.title,display:o.display??true};return o.description!==void 0&&(s.description=o.description),o.key!==void 0&&(s.key=o.key),o.data!==void 0&&(s.data=o.data),s}function p(){let o=D(),s=n.fallbackActor??{},h=o?.userId!==void 0?o.userId:s.userId??null,d=o?.userEmail!==void 0?o.userEmail:s.userEmail??null;return {userId:h,userEmail:d,...o?.reason!==void 0?{reason:o.reason}:{},...o?.comment!==void 0?{comment:o.comment}:{},...o?.extras&&Object.keys(o.extras).length>0?{extras:o.extras}:{}}}async function a(...o){let s=o[o.length-1],h=o.slice(0,-1),d=Q(h),H=M(s.before??{},s.after??{},{include:n.include,exclude:n.exclude,metaFields:S(n),systemKeys:t});if(s.operation==="update"&&Object.keys(H).length===0)return null;let x=F(s.after??s.before??null,n),f=D(),m={...f?{...f.userId!==void 0?{userId:f.userId}:{},...f.userEmail!==void 0?{userEmail:f.userEmail}:{},...f.reason!==void 0?{reason:f.reason}:{},...f.comment!==void 0?{comment:f.comment}:{},...f.extras&&Object.keys(f.extras).length>0?{extras:f.extras}:{}}:{},...x,...s.meta??{}},k=s.custom?T(s.custom):void 0,O=C({entityId:d,operation:s.operation,changes:H,meta:m,custom:k,config:n}),V=G(e,i,h),b=await I(V,O,n,{repoName:r,docId:d,before:s.before??null,after:s.after??null});return !b.written||!b.entry?null:{historyDocId:b.entry.historyDocId,historyToObjectId:b.entry.historyToObjectId,historySetAt:b.entry.historySetAt,schemaVersion:2,operation:b.entry.operation,meta:b.entry.meta,...b.entry.custom?{custom:b.entry.custom}:{},changes:b.entry.changes}}async function g(...o){let s=o[o.length-1],h=o.slice(0,-1),d=Q(h),H=T(s),x={...p(),...s.meta??{}},f=C({entityId:d,operation:"custom",changes:{},meta:x,custom:H,config:n}),w=G(e,i,h),m=await I(w,f,n,{repoName:r,docId:d,before:null,after:null});return !m.written||!m.entry?null:{historyDocId:m.entry.historyDocId,historyToObjectId:m.entry.historyToObjectId,historySetAt:m.entry.historySetAt,schemaVersion:2,operation:m.entry.operation,meta:m.entry.meta,...m.entry.custom?{custom:m.entry.custom}:{},changes:m.entry.changes}}return {list:u,raw:c,byField:l,byOperation:y,recordManual:a,recordCustom:g}}export{X as DEFAULT_GROUP_TOLERANCE_MS,U as DEFAULT_HISTORY_SHADOW_KEY,C as buildHistoryEntry,M as computeDiff,se as createActorContextMiddleware,_ as createActorResolver,Ce as createHistoryMethods,He as createHistoryTriggers,Y as defaultActorResolver,F as extractMeta,D as getCurrentActor,ce as getHistoryIdentityKeys,le as getHistoryShadowKey,de as injectHistoryMeta,S as metaFieldsOf,W as normalizeHistoryDocs,A as resolveShadowConfig,ae as setRequestActorMeta,ue as stripHistoryShadowField,R as valueType,P as valuesEqual,ie as withActor,I as writeHistoryEntry};//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map