@lpdjs/firestore-repo-service 3.0.19 → 3.0.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +1 -1
  2. package/dist/{create-servers-DydjOOOS.d.cts → create-servers-TfGVAXBQ.d.cts} +3 -3
  3. package/dist/{create-servers-bMJVVjPj.d.ts → create-servers-z-dCkmv2.d.ts} +3 -3
  4. package/dist/{effects-BYvL8JUK.d.ts → effects-DLBSYKuA.d.ts} +1 -1
  5. package/dist/{effects-DcM19dy4.d.cts → effects-DsI4cSpI.d.cts} +1 -1
  6. package/dist/index.cjs +108 -102
  7. package/dist/index.cjs.map +1 -1
  8. package/dist/index.d.cts +11 -7
  9. package/dist/index.d.ts +11 -7
  10. package/dist/index.js +108 -102
  11. package/dist/index.js.map +1 -1
  12. package/dist/llms-full.txt +5 -5
  13. package/dist/llms.txt +1 -1
  14. package/dist/queue-Bh7O8NnJ.d.ts +117 -0
  15. package/dist/queue-CEg5KSo1.d.cts +117 -0
  16. package/dist/servers/admin/index.cjs +51 -51
  17. package/dist/servers/admin/index.cjs.map +1 -1
  18. package/dist/servers/admin/index.d.cts +9 -1
  19. package/dist/servers/admin/index.d.ts +9 -1
  20. package/dist/servers/admin/index.js +51 -51
  21. package/dist/servers/admin/index.js.map +1 -1
  22. package/dist/servers/crud/index.cjs +1 -1
  23. package/dist/servers/crud/index.cjs.map +1 -1
  24. package/dist/servers/crud/index.d.cts +4 -4
  25. package/dist/servers/crud/index.d.ts +4 -4
  26. package/dist/servers/crud/index.js +1 -1
  27. package/dist/servers/crud/index.js.map +1 -1
  28. package/dist/servers/index.cjs +115 -109
  29. package/dist/servers/index.cjs.map +1 -1
  30. package/dist/servers/index.d.cts +6 -6
  31. package/dist/servers/index.d.ts +6 -6
  32. package/dist/servers/index.js +115 -109
  33. package/dist/servers/index.js.map +1 -1
  34. package/dist/sync/index.cjs +67 -61
  35. package/dist/sync/index.cjs.map +1 -1
  36. package/dist/sync/index.d.cts +2 -2
  37. package/dist/sync/index.d.ts +2 -2
  38. package/dist/sync/index.js +67 -61
  39. package/dist/sync/index.js.map +1 -1
  40. package/dist/{types-5Q7JDDba.d.ts → types-6jjeTvcm.d.ts} +7 -2
  41. package/dist/{types-BYPdlGSL.d.cts → types-BLHo_PdM.d.cts} +7 -2
  42. package/package.json +1 -1
  43. package/dist/queue-NFod6hTT.d.ts +0 -62
  44. package/dist/queue-zw2B7GPx.d.cts +0 -62
@@ -1,7 +1,7 @@
1
- 'use strict';var async_hooks=require('async_hooks');require('firebase-admin/firestore'),require('crypto');var Te=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});function ze(t){let e=[],n=t.replace(/[.*+?^${}()|[\]\\]/g,r=>r===":"?r:`\\${r}`).replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,(r,s)=>(e.push(s),"([^/]+)"));return {pattern:new RegExp(`^${n}$`),paramNames:e}}function Ke(t){let e=t.path??t.url??"/",n=e.indexOf("?");return n===-1?e:e.slice(0,n)}var J=class{constructor(){this.routes=[];this.middlewares=[];this.notFoundHandler=(e,n)=>{n.status(404).send("Not Found");};this.errorHandler=(e,n,r)=>{console.error("[MiniRouter]",e),r.status(500).send("Internal Server Error");};}use(e){return this.middlewares.push(e),this}get(e,n){return this.addRoute("GET",e,n)}post(e,n){return this.addRoute("POST",e,n)}put(e,n){return this.addRoute("PUT",e,n)}patch(e,n){return this.addRoute("PATCH",e,n)}delete(e,n){return this.addRoute("DELETE",e,n)}onNotFound(e){return this.notFoundHandler=e,this}onError(e){return this.errorHandler=e,this}addRoute(e,n,r){let{pattern:s,paramNames:o}=ze(n);return this.routes.push({method:e.toUpperCase(),pattern:s,paramNames:o,handler:r}),this}async handle(e,n){let r=(e.method??"GET").toUpperCase(),s=Ke(e),o=null,i={};for(let y of this.routes){if(y.method!==r)continue;let b=s.match(y.pattern);if(b){o=y,i={},y.paramNames.forEach((g,O)=>{i[g]=decodeURIComponent(b[O+1]??"");});break}}let c=Object.assign(e,{params:i}),a=o?o.handler:this.notFoundHandler;try{await this.runMiddlewareChain(c,n,a);}catch(y){this.errorHandler(y,e,n);}}async runMiddlewareChain(e,n,r){let s=0,o=async()=>{if(s<this.middlewares.length){let i=this.middlewares[s++];await i(e,n,o);}else await r(e,n);};await o();}};function z(t,e,n){let r=e==="/"?"":e.replace(/\/$/,"");if(process.env.FUNCTIONS_EMULATOR==="true"){let i=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??"demo-project",c=n??process.env.FUNCTION_REGION??"us-central1",a=(process.env.FUNCTION_TARGET??"").replace(/\./g,"-");return `/${i}/${c}/${a}${r}`}let s=process.env.K_SERVICE,o=t?.hostname??t?.headers?.host??"";return s&&typeof o=="string"&&o.includes("cloudfunctions.net")?`/${s.toLowerCase()}${r}`:r}function Se(t){if(typeof t=="string")return t;if(Array.isArray(t)){let e=t[0];return typeof e=="string"?e:void 0}}function ie(t){return !!t&&typeof t=="object"&&t.__authExtension===true}var We="X-History-Reason",Ge="X-History-Comment",Ve=Symbol.for("@lpdjs/firestore-repo-service:actorResolverHeaders"),ae=Symbol.for("@lpdjs/firestore-repo-service:actorContext"),ce=globalThis;ce[ae]??(ce[ae]=new async_hooks.AsyncLocalStorage);function Ze(t,e){if(!e.includes("."))return t[e];let n=t;for(let r of e.split(".")){if(!n||typeof n!="object")return;n=n[r];}return n}function xe(t,e){for(let n of e){let r=Ze(t,n);if(typeof r=="string"&&r.length>0)return r;if(typeof r=="number")return String(r)}return null}function Re(t,e){if(e===false)return;let n=t?.req?.header;if(typeof n!="function")return;let r=n.call(t.req,e);return typeof r=="string"&&r.length>0?r:void 0}function Je(t={}){let e=t.contextKeys??["user","docsUser"],n=t.userIdFields??["uid","id","sub"],r=t.userEmailFields??["email"],s=t.reasonHeader===void 0?"x-history-reason":t.reasonHeader,o=t.commentHeader===void 0?"x-history-comment":t.commentHeader,i=t.reasonHeader===void 0?We:t.reasonHeader,c=t.commentHeader===void 0?Ge:t.commentHeader,a=t.extras,y=b=>{let g=null,O=b?.get;if(typeof O=="function")for(let v of e){let I=O.call(b,v);if(I&&typeof I=="object"){g=I;break}}let k=Re(b,s),x=Re(b,o),p=a?a(b,g):void 0;return g?{userId:xe(g,n),userEmail:xe(g,r),...k!==void 0?{reason:k}:{},...x!==void 0?{comment:x}:{},...p?{extras:p}:{}}:k===void 0&&x===void 0&&!p?null:{...k!==void 0?{reason:k}:{},...x!==void 0?{comment:x}:{},...p?{extras:p}:{}}};return Object.defineProperty(y,Ve,{value:{reasonHeader:i,commentHeader:c},enumerable:false,configurable:false}),y}Je();var ke="_historyMeta";function ue(t){if(!t?.enabled||t.shadow===false||t.meta&&t.shadow===void 0)return null;let e=t.shadow,n=typeof e=="string"&&e.trim().length>0?e.trim():typeof e=="object"&&e!==null&&typeof e.key=="string"&&e.key.trim().length>0?e.key.trim():ke,r=typeof e=="object"&&e!==null?e.fields:void 0;return {key:n,fields:{userId:r?.userId??"userId",userEmail:r?.userEmail??"userEmail",reason:r?.reason??"reason",comment:r?.comment??"comment",extras:r?.extras??"extras"}}}function L(t){return ue(t)?.key??null}function Ae(t){let e=ue(t);return e?[e.key]:[]}function Xe(t){return t.match(/^\{([^}]+)\}$/)?.[1]?.trim()||null}function Y(t,e="docId",n=false){if(typeof t!="string"||!t.trim())return {rawPath:t??"",collectionId:"",collectionPath:"",parentKeys:[],documentPathTemplate:null,hasTemplate:false};let r=t.split("/").map(g=>g.trim()).filter(Boolean);if(r.length===0)return {rawPath:t,collectionId:t,collectionPath:t,parentKeys:[],documentPathTemplate:null,hasTemplate:false};if(r.length===1){let g=r[0];return {rawPath:t,collectionId:g,collectionPath:g,parentKeys:[],documentPathTemplate:n?null:`${g}/{${e}}`,hasTemplate:t.includes("{")&&t.includes("}")}}let s=r.length%2===0,o=s?r.slice(0,-1):r,i=o[o.length-1],c=o.join("/"),y=o.slice(0,-1).map(Xe).filter(g=>g!==null),b=s?r.join("/"):`${c}/{${e}}`;return {rawPath:t,collectionId:i,collectionPath:c,parentKeys:y,documentPathTemplate:b,hasTemplate:true}}function tt(t){if(typeof t!="function")return [];let n=t.toString().match(/^\s*(?:function\s*\w*\s*)?\(([^)]*)\)/);if(!n?.[1])return [];let r=n[1].split(",").map(s=>s.trim().replace(/\s*[:=].*$/,"").trim()).filter(Boolean);return r.length<=2?[]:r.slice(1,-1)}function nt(t){let e=t?.documentKey??"docId",n=!!t?.isGroup,r=Y(typeof t?.path=="string"?t.path:"",e,n),s=r.parentKeys.length>0?r.parentKeys:n?tt(t?.refCb):[],o=[t?.documentKey,t?.pathKey,t?.createdKey,t?.updatedKey].filter(c=>typeof c=="string"),i=t?.history&&typeof t.history=="object"?t.history:void 0;return {schema:t?.schema,_systemKeys:o,_pathKey:t?.pathKey??null,_isGroup:n,_createdKey:t?.createdKey??null,_parentKeys:s,_documentPathTemplate:r.documentPathTemplate,_collectionId:typeof t?.path=="string"?r.collectionId:null,relationalKeys:t?.relationalKeys,_historyConfig:i,_historyShadowKey:L(i),_historyIdentityKeys:Ae(i),_historySubcollection:i?.enabled?i.subcollection??"history":void 0,_collectionPath:typeof t?.path=="string"?r.collectionPath:null}}function Oe(t,e){let n=nt(t),r,s=()=>{let o=r??(r=e());if(!o){let i=n._collectionPath||"unknown";throw new Error(`[makeLazyRepo] Failed to resolve repository for path "${i}". The repository mapping resolved to undefined. This almost always indicates a circular import where the repository was exported as undefined.`)}return o};return new Proxy(n,{get(o,i){return typeof i=="string"&&i in n?n[i]:s()[i]},has(o,i){return typeof i=="string"&&i in n?true:i in s()}})}function ee(t,e,n=new WeakSet,r=0){if(t==null)return null;if(typeof t=="object"&&typeof t.toDate=="function")return t.toDate().toISOString();if(t instanceof Date)return t.toISOString();if(Buffer.isBuffer(t))return t.toString("base64");if(t instanceof Uint8Array)return Buffer.from(t).toString("base64");if(typeof t=="object"&&"latitude"in t&&"longitude"in t){let s=t;return e?.stringifyArrays===false?{lat:s.latitude,lng:s.longitude}:JSON.stringify({lat:s.latitude,lng:s.longitude})}if(Array.isArray(t)){let s=t.map(o=>ee(o,e,n,r+1));return e?.stringifyArrays===false?s:JSON.stringify(s)}return typeof t=="object"&&t!==null&&e?.stringifyArrays===false?fe(t,new Set,{},n,r+1):t}var Pe=32,rt=5e3;function De(t,e,n,r=new WeakSet,s=0){if(s>Pe){n[e||"_truncated"]=JSON.stringify({__truncated:true});return}if(r.has(t)){n[e||"_cycle"]=JSON.stringify({__cycle:true});return}r.add(t);for(let[o,i]of Object.entries(t)){if(Object.keys(n).length>=rt)break;let c=e?`${e}__${o}`:o;i!=null&&typeof i=="object"&&!Array.isArray(i)&&!(i instanceof Date)&&!Buffer.isBuffer(i)&&!(i instanceof Uint8Array)&&typeof i.toDate!="function"&&!("latitude"in i&&"longitude"in i)?De(i,c,n,r,s+1):n[c]=ee(i);}r.delete(t);}function fe(t,e,n,r=new WeakSet,s=0){if(s>Pe)return {__truncated:true};if(r.has(t))return {__cycle:true};r.add(t);let o={};for(let[i,c]of Object.entries(t)){if(e.has(i))continue;let a=n[i]??i;c!=null&&typeof c=="object"&&!Array.isArray(c)&&!(c instanceof Date)&&!Buffer.isBuffer(c)&&!(c instanceof Uint8Array)&&typeof c.toDate!="function"&&!("latitude"in c&&"longitude"in c)?o[a]=fe(c,new Set,{},r,s+1):o[a]=ee(c,{stringifyArrays:false},r,s+1);}return r.delete(t),o}function pe(t){let e={};for(let[n,r]of Object.entries(t)){let s=r;if(typeof s=="string"){let c=s.trim();if(c.startsWith("[")&&c.endsWith("]")||c.startsWith("{")&&c.endsWith("}"))try{s=JSON.parse(c);}catch{}}if(n.startsWith("__")||!n.includes("__")){e[n]=s;continue}let o=n.split("__").filter(Boolean),i=e;for(let c=0;c<o.length-1;c++){let a=o[c];(!i[a]||typeof i[a]!="object"||Array.isArray(i[a]))&&(i[a]={}),i=i[a];}i[o[o.length-1]]=s;}return e}function U(t,e){let n=e?.flat!==false,r;if(n){let s=new Set(e?.exclude),o=e?.columnMap??{},i=t;if(s.size>0){let a=false,y={};for(let[b,g]of Object.entries(t)){if(s.has(b)){a=true;continue}y[b]=g;}a&&(i=y);}let c={};De(i,"",c),r={};for(let[a,y]of Object.entries(c)){if(s.has(a))continue;let b=a.split("__")[0];if(b!==a&&s.has(b))continue;let g=o[a]??(a.includes("__")?o[a.split("__").pop()]:void 0)??a;r[g]=y;}}else {let s=new Set(e?.exclude),o=e?.columnMap??{};r=fe(t,s,o);}return typeof e?.transformDoc=="function"&&(r=e.transformDoc(r)),r}function K(t,e,n){return `<!DOCTYPE html>
1
+ 'use strict';var firestore=require('firebase-admin/firestore'),async_hooks=require('async_hooks');require('crypto');var He=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});function st(t){let e=[],n=t.replace(/[.*+?^${}()|[\]\\]/g,r=>r===":"?r:`\\${r}`).replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,(r,s)=>(e.push(s),"([^/]+)"));return {pattern:new RegExp(`^${n}$`),paramNames:e}}function ot(t){let e=t.path??t.url??"/",n=e.indexOf("?");return n===-1?e:e.slice(0,n)}var ce=class{constructor(){this.routes=[];this.middlewares=[];this.notFoundHandler=(e,n)=>{n.status(404).send("Not Found");};this.errorHandler=(e,n,r)=>{console.error("[MiniRouter]",e),r.status(500).send("Internal Server Error");};}use(e){return this.middlewares.push(e),this}get(e,n){return this.addRoute("GET",e,n)}post(e,n){return this.addRoute("POST",e,n)}put(e,n){return this.addRoute("PUT",e,n)}patch(e,n){return this.addRoute("PATCH",e,n)}delete(e,n){return this.addRoute("DELETE",e,n)}onNotFound(e){return this.notFoundHandler=e,this}onError(e){return this.errorHandler=e,this}addRoute(e,n,r){let{pattern:s,paramNames:o}=st(n);return this.routes.push({method:e.toUpperCase(),pattern:s,paramNames:o,handler:r}),this}async handle(e,n){let r=(e.method??"GET").toUpperCase(),s=ot(e),o=null,i={};for(let f of this.routes){if(f.method!==r)continue;let h=s.match(f.pattern);if(h){o=f,i={},f.paramNames.forEach((y,O)=>{i[y]=decodeURIComponent(h[O+1]??"");});break}}let u=Object.assign(e,{params:i}),a=o?o.handler:this.notFoundHandler;try{await this.runMiddlewareChain(u,n,a);}catch(f){this.errorHandler(f,e,n);}}async runMiddlewareChain(e,n,r){let s=0,o=async()=>{if(s<this.middlewares.length){let i=this.middlewares[s++];await i(e,n,o);}else await r(e,n);};await o();}};function Y(t,e,n){let r=e==="/"?"":e.replace(/\/$/,"");if(process.env.FUNCTIONS_EMULATOR==="true"){let i=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??"demo-project",u=n??process.env.FUNCTION_REGION??"us-central1",a=(process.env.FUNCTION_TARGET??"").replace(/\./g,"-");return `/${i}/${u}/${a}${r}`}let s=process.env.K_SERVICE,o=t?.hostname??t?.headers?.host??"";return s&&typeof o=="string"&&o.includes("cloudfunctions.net")?`/${s.toLowerCase()}${r}`:r}function Ie(t){if(typeof t=="string")return t;if(Array.isArray(t)){let e=t[0];return typeof e=="string"?e:void 0}}function he(t){return !!t&&typeof t=="object"&&t.__authExtension===true}var ut="X-History-Reason",lt="X-History-Comment",dt=Symbol.for("@lpdjs/firestore-repo-service:actorResolverHeaders"),be=Symbol.for("@lpdjs/firestore-repo-service:actorContext"),we=globalThis;we[be]??(we[be]=new async_hooks.AsyncLocalStorage);function ft(t,e){if(!e.includes("."))return t[e];let n=t;for(let r of e.split(".")){if(!n||typeof n!="object")return;n=n[r];}return n}function Me(t,e){for(let n of e){let r=ft(t,n);if(typeof r=="string"&&r.length>0)return r;if(typeof r=="number")return String(r)}return null}function Ne(t,e){if(e===false)return;let n=t?.req?.header;if(typeof n!="function")return;let r=n.call(t.req,e);return typeof r=="string"&&r.length>0?r:void 0}function pt(t={}){let e=t.contextKeys??["user","docsUser"],n=t.userIdFields??["uid","id","sub"],r=t.userEmailFields??["email"],s=t.reasonHeader===void 0?"x-history-reason":t.reasonHeader,o=t.commentHeader===void 0?"x-history-comment":t.commentHeader,i=t.reasonHeader===void 0?ut:t.reasonHeader,u=t.commentHeader===void 0?lt:t.commentHeader,a=t.extras,f=h=>{let y=null,O=h?.get;if(typeof O=="function")for(let H of e){let N=O.call(h,H);if(N&&typeof N=="object"){y=N;break}}let C=Ne(h,s),A=Ne(h,o),d=a?a(h,y):void 0;return y?{userId:Me(y,n),userEmail:Me(y,r),...C!==void 0?{reason:C}:{},...A!==void 0?{comment:A}:{},...d?{extras:d}:{}}:C===void 0&&A===void 0&&!d?null:{...C!==void 0?{reason:C}:{},...A!==void 0?{comment:A}:{},...d?{extras:d}:{}}};return Object.defineProperty(f,dt,{value:{reasonHeader:i,commentHeader:u},enumerable:false,configurable:false}),f}pt();var _e="_historyMeta";function Se(t){if(!t?.enabled||t.shadow===false||t.meta&&t.shadow===void 0)return null;let e=t.shadow,n=typeof e=="string"&&e.trim().length>0?e.trim():typeof e=="object"&&e!==null&&typeof e.key=="string"&&e.key.trim().length>0?e.key.trim():_e,r=typeof e=="object"&&e!==null?e.fields:void 0;return {key:n,fields:{userId:r?.userId??"userId",userEmail:r?.userEmail??"userEmail",reason:r?.reason??"reason",comment:r?.comment??"comment",extras:r?.extras??"extras"}}}function G(t){return Se(t)?.key??null}function $e(t){let e=Se(t);return e?[e.key]:[]}function mt(t){return t.match(/^\{([^}]+)\}$/)?.[1]?.trim()||null}function ue(t,e="docId",n=false){if(typeof t!="string"||!t.trim())return {rawPath:t??"",collectionId:"",collectionPath:"",parentKeys:[],documentPathTemplate:null,hasTemplate:false};let r=t.split("/").map(y=>y.trim()).filter(Boolean);if(r.length===0)return {rawPath:t,collectionId:t,collectionPath:t,parentKeys:[],documentPathTemplate:null,hasTemplate:false};if(r.length===1){let y=r[0];return {rawPath:t,collectionId:y,collectionPath:y,parentKeys:[],documentPathTemplate:n?null:`${y}/{${e}}`,hasTemplate:t.includes("{")&&t.includes("}")}}let s=r.length%2===0,o=s?r.slice(0,-1):r,i=o[o.length-1],u=o.join("/"),f=o.slice(0,-1).map(mt).filter(y=>y!==null),h=s?r.join("/"):`${u}/{${e}}`;return {rawPath:t,collectionId:i,collectionPath:u,parentKeys:f,documentPathTemplate:h,hasTemplate:true}}function ht(t){if(typeof t!="function")return [];let n=t.toString().match(/^\s*(?:function\s*\w*\s*)?\(([^)]*)\)/);if(!n?.[1])return [];let r=n[1].split(",").map(s=>s.trim().replace(/\s*[:=].*$/,"").trim()).filter(Boolean);return r.length<=2?[]:r.slice(1,-1)}function bt(t){let e=t?.documentKey??"docId",n=!!t?.isGroup,r=ue(typeof t?.path=="string"?t.path:"",e,n),s=r.parentKeys.length>0?r.parentKeys:n?ht(t?.refCb):[],o=[t?.documentKey,t?.pathKey,t?.createdKey,t?.updatedKey].filter(u=>typeof u=="string"),i=t?.history&&typeof t.history=="object"?t.history:void 0;return {schema:t?.schema,_systemKeys:o,_pathKey:t?.pathKey??null,_isGroup:n,_createdKey:t?.createdKey??null,_parentKeys:s,_documentPathTemplate:r.documentPathTemplate,_collectionId:typeof t?.path=="string"?r.collectionId:null,relationalKeys:t?.relationalKeys,_historyConfig:i,_historyShadowKey:G(i),_historyIdentityKeys:$e(i),_historySubcollection:i?.enabled?i.subcollection??"history":void 0,_collectionPath:typeof t?.path=="string"?r.collectionPath:null}}function Be(t,e){let n=bt(t),r,s=()=>{let o=r??(r=e());if(!o){let i=n._collectionPath||"unknown";throw new Error(`[makeLazyRepo] Failed to resolve repository for path "${i}". The repository mapping resolved to undefined. This almost always indicates a circular import where the repository was exported as undefined.`)}return o};return new Proxy(n,{get(o,i){return typeof i=="string"&&i in n?n[i]:s()[i]},has(o,i){return typeof i=="string"&&i in n?true:i in s()}})}function de(t,e,n=new WeakSet,r=0){if(t==null)return null;if(typeof t=="object"&&typeof t.toDate=="function")return t.toDate().toISOString();if(t instanceof Date)return t.toISOString();if(Buffer.isBuffer(t))return t.toString("base64");if(t instanceof Uint8Array)return Buffer.from(t).toString("base64");if(typeof t=="object"&&"latitude"in t&&"longitude"in t){let s=t;return e?.stringifyArrays===false?{lat:s.latitude,lng:s.longitude}:JSON.stringify({lat:s.latitude,lng:s.longitude})}if(Array.isArray(t)){let s=t.map(o=>de(o,e,n,r+1));return e?.stringifyArrays===false?s:JSON.stringify(s)}return typeof t=="object"&&t!==null&&e?.stringifyArrays===false?Re(t,new Set,{},n,r+1):t}var Le=32,wt=5e3;function ze(t,e,n,r=new WeakSet,s=0){if(s>Le){n[e||"_truncated"]=JSON.stringify({__truncated:true});return}if(r.has(t)){n[e||"_cycle"]=JSON.stringify({__cycle:true});return}r.add(t);for(let[o,i]of Object.entries(t)){if(Object.keys(n).length>=wt)break;let u=e?`${e}__${o}`:o;i!=null&&typeof i=="object"&&!Array.isArray(i)&&!(i instanceof Date)&&!Buffer.isBuffer(i)&&!(i instanceof Uint8Array)&&typeof i.toDate!="function"&&!("latitude"in i&&"longitude"in i)?ze(i,u,n,r,s+1):n[u]=de(i);}r.delete(t);}function Re(t,e,n,r=new WeakSet,s=0){if(s>Le)return {__truncated:true};if(r.has(t))return {__cycle:true};r.add(t);let o={};for(let[i,u]of Object.entries(t)){if(e.has(i))continue;let a=n[i]??i;u!=null&&typeof u=="object"&&!Array.isArray(u)&&!(u instanceof Date)&&!Buffer.isBuffer(u)&&!(u instanceof Uint8Array)&&typeof u.toDate!="function"&&!("latitude"in u&&"longitude"in u)?o[a]=Re(u,new Set,{},r,s+1):o[a]=de(u,{stringifyArrays:false},r,s+1);}return r.delete(t),o}function Ae(t){let e={};for(let[n,r]of Object.entries(t)){let s=r;if(typeof s=="string"){let u=s.trim();if(u.startsWith("[")&&u.endsWith("]")||u.startsWith("{")&&u.endsWith("}"))try{s=JSON.parse(u);}catch{}}if(n.startsWith("__")||!n.includes("__")){e[n]=s;continue}let o=n.split("__").filter(Boolean),i=e;for(let u=0;u<o.length-1;u++){let a=o[u];(!i[a]||typeof i[a]!="object"||Array.isArray(i[a]))&&(i[a]={}),i=i[a];}i[o[o.length-1]]=s;}return e}function te(t,e){let n=e?.flat!==false,r;if(n){let s=new Set(e?.exclude),o=e?.columnMap??{},i=t;if(s.size>0){let a=false,f={};for(let[h,y]of Object.entries(t)){if(s.has(h)){a=true;continue}f[h]=y;}a&&(i=f);}let u={};ze(i,"",u),r={};for(let[a,f]of Object.entries(u)){if(s.has(a))continue;let h=a.split("__")[0];if(h!==a&&s.has(h))continue;let y=o[a]??(a.includes("__")?o[a.split("__").pop()]:void 0)??a;r[y]=f;}}else {let s=new Set(e?.exclude),o=e?.columnMap??{};r=Re(t,s,o);}return typeof e?.transformDoc=="function"&&(r=e.transformDoc(r)),r}function v(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Z(t,e,n){let r=v(t),s=v(e);return `<!DOCTYPE html>
2
2
  <html lang="en"><head>
3
3
  <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
4
- <title>${t} \u2014 Sync Admin</title>
4
+ <title>${r} \u2014 Sync Admin</title>
5
5
  <style>
6
6
  *{box-sizing:border-box;margin:0;padding:0}
7
7
  body{font-family:system-ui,-apple-system,sans-serif;background:#f5f5f5;color:#1a1a1a;padding:2rem}
@@ -25,87 +25,93 @@
25
25
  .muted{color:#656d76;font-size:.85rem}
26
26
  </style>
27
27
  </head><body>
28
- <nav><a href="${e}/">\u2190 Dashboard</a></nav>
29
- <h1>${t}</h1>
28
+ <nav><a href="${s}/">\u2190 Dashboard</a></nav>
29
+ <h1>${r}</h1>
30
30
  ${n}
31
- </body></html>`}function q(t,e,n=200){t.status(n).set("Content-Type","text/html; charset=utf-8").send(e);}function W(t,e,n=200){t.status(n).set("Content-Type","application/json").send(JSON.stringify(e,null,2));}function te(t){return (t.headers?.accept??"").includes("application/json")}function ye(t,e,n,r,s,o,i,c){let a=(s.basePath??"/").replace(/\/$/,"")||"",y=s.featuresFlag??{},b=Se(s.httpsOptions?.region),g=Array.isArray(e)?e:[e],O=t?.rawMapping,k=[],x=Object.keys(o??{}),p=x.length>0,v=Object.keys(O||t),I=p?x.filter(l=>v.includes(l)||l in t):v;for(let l of I){let d=o[l],h=O?Oe(O[l],()=>t[l]):t[l],u=!!h._isGroup,S=h._collectionPath,E=typeof S=="string"&&S.includes("/");if(!p&&u&&!d?.triggerPath&&!E)continue;let m=d?.adapters&&d.adapters.length>0?g.filter(w=>d.adapters.includes(w.name)):g,A=typeof h._historyShadowKey=="string"?h._historyShadowKey:L(h._historyConfig);k.push({name:l,schema:h.schema??null,documentKey:h._systemKeys?.[0]??h.documentKey??"docId",tableName:d?.tableName??l,isGroup:u,repoCfg:d,repo:h,adapters:m,historyShadowKey:A});}let H=new J;if(s.auth)if(ie(s.auth)){let l=s.auth;for(let d of l.routes){let h=`${a}${d.path}`;d.method==="GET"?H.get(h,d.handler):H.post(h,d.handler);}H.use(l.middleware);}else if(typeof s.auth=="function")H.use(s.auth);else {let l=s.auth.realm??"Sync Admin",d="Basic "+Buffer.from(`${s.auth.username}:${s.auth.password}`).toString("base64");H.use((h,u,S)=>{if((h.headers?.authorization??"")!==d){u.status(401).set("WWW-Authenticate",`Basic realm="${l}"`).set("Content-Type","text/plain").send("Unauthorized");return}S();});}return H.get(`${a}/`,(l,d)=>{let h=z(l,a,b),u=k.map(m=>{let A=[];y.healthCheck&&A.push(`<a class="btn" href="${h}/${m.name}/health">Health</a>`),y.manualSync&&A.push(`<a class="btn btn-primary" href="${h}/${m.name}/force-sync">Force Sync</a>`);let w=m.adapters.map(C=>`<span class="badge badge-ok">${C.name}</span>`).join(" ");return `<tr>
32
- <td><strong>${m.name}</strong></td>
33
- <td>${m.tableName}</td>
34
- <td>${w||'<span class="badge badge-warn">none</span>'}</td>
35
- <td>${m.isGroup?'<span class="badge badge-warn">group</span>':'<span class="badge badge-ok">collection</span>'}</td>
36
- <td>${m.schema?"\u2713":"\u2717"}</td>
37
- <td>${A.join(" ")}</td>
31
+ </body></html>`}function J(t,e,n=200){t.status(n).set("Content-Type","text/html; charset=utf-8").send(e);}function X(t,e,n=200){t.status(n).set("Content-Type","application/json").send(JSON.stringify(e,null,2));}function oe(t){return (t.headers?.accept??"").includes("application/json")}function ne(t){if(t===true||t===1)return true;if(Array.isArray(t))return t.some(ne);if(typeof t=="string"){let e=t.trim().toLowerCase();return e==="true"||e==="1"||e==="yes"||e==="on"}return false}function Tt(t){if(t.query&&ne(t.query.dryRun))return true;let e=t.url??t.originalUrl??"",n=e.indexOf("?");if(n!==-1){let s=new URLSearchParams(e.slice(n+1));if(ne(s.get("dryRun")))return true}let r=t.body;if(r&&typeof r=="object"){if(ne(r.dryRun))return true}else if(typeof r=="string"&&r.trim().length>0){let s=r.trim();if(s.startsWith("{"))try{let o=JSON.parse(s);if(o&&typeof o=="object"&&ne(o.dryRun))return !0}catch{}else {let o=new URLSearchParams(s);if(ne(o.get("dryRun")))return true}}return false}var xt=new Set([4,8,10,13,14,"4","8","10","13","14","DEADLINE_EXCEEDED","RESOURCE_EXHAUSTED","ABORTED","INTERNAL","UNAVAILABLE"]);function Rt(t){if(!t||typeof t!="object")return false;let e=t.code;return (typeof e=="number"||typeof e=="string")&&xt.has(e)}async function At(t,e=3,n=100){let r=0;for(;;){r++;try{return await t()}catch(s){if(r>=e||!Rt(s))throw s;let o=n*2**(r-1);await new Promise(i=>setTimeout(i,o));}}}function ke(t,e){let n=new Set,r=[];for(let s of t.adapters){let o=`${t.name}:${s.name}`,i=e.get(o);i&&!n.has(i)&&(n.add(i),r.push({adapterName:s.name??"default",queue:i}));}if(r.length===0){let s=e.get(t.name);s&&!n.has(s)&&(n.add(s),r.push({adapterName:t.adapters[0]?.name??"default",queue:s}));}return r}function Ee(t,e,n,r,s,o,i,u){let a=(s.basePath??"/").replace(/\/$/,"")||"",f=s.featuresFlag??{},h=Ie(s.httpsOptions?.region),y=Array.isArray(e)?e:[e],O=t?.rawMapping,C=[],A=Object.keys(o??{}),d=A.length>0,H=Object.keys(O||t),N=d?A.filter(l=>H.includes(l)||l in t):H;for(let l of N){let p=o[l],b=O?Be(O[l],()=>t[l]):t[l],c=!!b._isGroup,x=b._collectionPath,k=typeof x=="string"&&x.includes("/");if(!d&&c&&!p?.triggerPath&&!k)continue;let m=p?.adapters&&p.adapters.length>0?y.filter(R=>p.adapters.includes(R.name)):y,T=typeof b._historyShadowKey=="string"?b._historyShadowKey:G(b._historyConfig);C.push({name:l,schema:b.schema??null,documentKey:b._systemKeys?.[0]??b.documentKey??"docId",tableName:p?.tableName??l,isGroup:c,repoCfg:p,repo:b,adapters:m,historyShadowKey:T});}let I=new ce,P=new Set;if(s.auth)if(he(s.auth)){let l=s.auth;for(let p of l.routes){let b=`${a}${p.path}`;p.method==="GET"?I.get(b,p.handler):I.post(b,p.handler);}I.use(l.middleware);}else if(typeof s.auth=="function")I.use(s.auth);else {let l=s.auth.realm??"Sync Admin",p="Basic "+Buffer.from(`${s.auth.username}:${s.auth.password}`).toString("base64");I.use((b,c,x)=>{if((b.headers?.authorization??"")!==p){c.status(401).set("WWW-Authenticate",`Basic realm="${l}"`).set("Content-Type","text/plain").send("Unauthorized");return}x();});}return I.get(`${a}/`,(l,p)=>{let b=Y(l,a,h),c=v(b),x=C.map(T=>{let R=v(T.name),w=encodeURIComponent(T.name),D=[];f.healthCheck&&D.push(`<a class="btn" href="${c}/${w}/health">Health</a>`),f.manualSync&&D.push(`<a class="btn btn-primary" href="${c}/${w}/force-sync">Force Sync</a>`);let $=T.adapters.map(L=>`<span class="badge badge-ok">${v(L.name)}</span>`).join(" ");return `<tr>
32
+ <td><strong>${R}</strong></td>
33
+ <td>${v(T.tableName)}</td>
34
+ <td>${$||'<span class="badge badge-warn">none</span>'}</td>
35
+ <td>${T.isGroup?'<span class="badge badge-warn">group</span>':'<span class="badge badge-ok">collection</span>'}</td>
36
+ <td>${T.schema?"\u2713":"\u2717"}</td>
37
+ <td>${D.join(" ")}</td>
38
38
  </tr>`}).join(`
39
- `),S=y.configCheck?`<p style="margin-top:.5rem"><a class="btn" href="${h}/config-check">\u2699 Config Check</a></p>`:"",E=K("Sync Dashboard",h,`<div class="card">
39
+ `),k=f.configCheck?`<p style="margin-top:.5rem"><a class="btn" href="${c}/config-check">\u2699 Config Check</a></p>`:"",m=Z("Sync Dashboard",b,`<div class="card">
40
40
  <table>
41
41
  <thead><tr><th>Repository</th><th>Target Name</th><th>Adapters</th><th>Type</th><th>Schema</th><th>Actions</th></tr></thead>
42
- <tbody>${u}</tbody>
42
+ <tbody>${x}</tbody>
43
43
  </table>
44
- ${S}
45
- </div>`);q(d,E);}),H.get(`${a}`,(l,d)=>{let h=z(l,a,b);d.status(302).set("Location",`${h}/`).send("");}),y.healthCheck&&H.get(`${a}/:repoName/health`,async(l,d)=>{let h=z(l,a,b),u=k.find(w=>w.name===l.params.repoName);if(!u){q(d,K("Not Found",h,`<p>Unknown repo: ${l.params.repoName}</p>`),404);return}let S=[];for(let w of u.adapters)if(typeof w.healthCheck=="function"){let C=await w.healthCheck({targetName:u.tableName,primaryKey:u.documentKey,schema:u.schema??void 0,repoConfig:u.repoCfg});S.push({adapterName:w.name,health:C});}else try{let C=await w.targetExists(u.tableName);S.push({adapterName:w.name,health:{healthy:C,targetName:u.tableName,targetExists:C,error:C?null:`Target "${u.tableName}" does not exist`}});}catch(C){S.push({adapterName:w.name,health:{healthy:false,targetName:u.tableName,targetExists:false,error:C?.message??String(C)}});}let E=S.length>0&&S.every(w=>w.health.healthy);if(te(l)){W(d,{repo:u.name,targetName:u.tableName,healthy:E,adapters:S.map(w=>({name:w.adapterName,...w.health}))});return}let m=w=>{let{adapterName:C,health:P}=w,N=P.healthy?'<span class="badge badge-ok">Healthy</span>':'<span class="badge badge-err">Unhealthy</span>',M="",f=P.details;if(f?.expected&&Array.isArray(f.expected)){let T=f.expected,D=new Set(f.actual??[]),R=f.extra??[],_=T.map(F=>{let Q=D.has(F.name)?'<span class="badge badge-ok">OK</span>':'<span class="badge badge-err">MISSING</span>';return `<tr><td>${F.name}</td><td>${F.type}</td><td>${F.nullable?"Yes":"No"}</td><td>${F.isPrimaryKey?"\u2713":""}</td><td>${Q}</td></tr>`}).join(`
46
- `),$=R.map(F=>`<tr><td>${F}</td><td colspan="3" class="muted">not in schema</td><td><span class="badge badge-warn">EXTRA</span></td></tr>`).join(`
47
- `);M=`<h2>Columns</h2>
44
+ ${k}
45
+ </div>`);J(p,m);}),I.get(`${a}`,(l,p)=>{let b=Y(l,a,h);p.status(302).set("Location",`${b}/`).send("");}),f.healthCheck&&I.get(`${a}/:repoName/health`,async(l,p)=>{let b=Y(l,a,h),c=C.find(R=>R.name===l.params.repoName);if(!c){J(p,Z("Not Found",b,`<p>Unknown repo: ${v(l.params.repoName)}</p>`),404);return}let x=[];for(let R of c.adapters)if(typeof R.healthCheck=="function"){let w=await R.healthCheck({targetName:c.tableName,primaryKey:c.documentKey,schema:c.schema??void 0,repoConfig:c.repoCfg});x.push({adapterName:R.name,health:w});}else try{let w=await R.targetExists(c.tableName);x.push({adapterName:R.name,health:{healthy:w,targetName:c.tableName,targetExists:w,error:w?null:`Target "${c.tableName}" does not exist`}});}catch(w){x.push({adapterName:R.name,health:{healthy:false,targetName:c.tableName,targetExists:false,error:w?.message??String(w)}});}let k=x.length>0&&x.every(R=>R.health.healthy);if(oe(l)){X(p,{repo:c.name,targetName:c.tableName,healthy:k,adapters:x.map(R=>({name:R.adapterName,...R.health}))});return}let m=R=>{let{adapterName:w,health:D}=R,$=D.healthy?'<span class="badge badge-ok">Healthy</span>':'<span class="badge badge-err">Unhealthy</span>',L="",g=D.details;if(g?.expected&&Array.isArray(g.expected)){let S=g.expected,M=new Set(g.actual??[]),E=g.extra??[],Q=S.map(j=>{let se=M.has(j.name)?'<span class="badge badge-ok">OK</span>':'<span class="badge badge-err">MISSING</span>';return `<tr><td>${v(j.name)}</td><td>${v(j.type)}</td><td>${j.nullable?"Yes":"No"}</td><td>${j.isPrimaryKey?"\u2713":""}</td><td>${se}</td></tr>`}).join(`
46
+ `),U=E.map(j=>`<tr><td>${v(j)}</td><td colspan="3" class="muted">not in schema</td><td><span class="badge badge-warn">EXTRA</span></td></tr>`).join(`
47
+ `);L=`<h2>Columns</h2>
48
48
  <table>
49
49
  <thead><tr><th>Column</th><th>SQL Type</th><th>Nullable</th><th>PK</th><th>Status</th></tr></thead>
50
- <tbody>${_}${$}</tbody>
51
- </table>`;}else f?.numberOfDocuments!==void 0&&(M=`<h2>Index Stats</h2>
50
+ <tbody>${Q}${U}</tbody>
51
+ </table>`;}else g?.numberOfDocuments!==void 0&&(L=`<h2>Index Stats</h2>
52
52
  <table>
53
- <tr><th>Documents Count</th><td>${f.numberOfDocuments}</td></tr>
54
- <tr><th>Indexing in Progress</th><td>${f.isIndexing?'<span class="badge badge-warn">Yes</span>':'<span class="badge badge-ok">No</span>'}</td></tr>
55
- <tr><th>Primary Key</th><td><code>${f.primaryKey??"default"}</code></td></tr>
53
+ <tr><th>Documents Count</th><td>${v(g.numberOfDocuments)}</td></tr>
54
+ <tr><th>Indexing in Progress</th><td>${g.isIndexing?'<span class="badge badge-warn">Yes</span>':'<span class="badge badge-ok">No</span>'}</td></tr>
55
+ <tr><th>Primary Key</th><td><code>${v(g.primaryKey??"default")}</code></td></tr>
56
56
  </table>`);return `<div class="card" style="margin-top:1rem">
57
- <h2>Adapter: <code>${C}</code> ${N}</h2>
58
- <p>Target: <code>${P.targetName}</code> ${P.targetExists?"":'<span class="badge badge-err">NOT FOUND</span>'}</p>
59
- ${P.error?`<p class="badge badge-err" style="margin-top:.5rem">Error: ${P.error}</p>`:""}
60
- ${M}
61
- </div>`},A=K(`Health: ${u.name}`,h,`<div class="card">
62
- <p>Overall status for <strong>${u.name}</strong>: ${E?'<span class="badge badge-ok">Healthy</span>':'<span class="badge badge-err">Issues detected</span>'}</p>
57
+ <h2>Adapter: <code>${v(w)}</code> ${$}</h2>
58
+ <p>Target: <code>${v(D.targetName)}</code> ${D.targetExists?"":'<span class="badge badge-err">NOT FOUND</span>'}</p>
59
+ ${D.error?`<p class="badge badge-err" style="margin-top:.5rem">Error: ${v(D.error)}</p>`:""}
60
+ ${L}
61
+ </div>`},T=Z(`Health: ${c.name}`,b,`<div class="card">
62
+ <p>Overall status for <strong>${v(c.name)}</strong>: ${k?'<span class="badge badge-ok">Healthy</span>':'<span class="badge badge-err">Issues detected</span>'}</p>
63
63
  </div>
64
- ${S.map(m).join(`
65
- `)}`);q(d,A);}),y.manualSync&&(H.get(`${a}/:repoName/force-sync`,(l,d)=>{let h=z(l,a,b),u=k.find(E=>E.name===l.params.repoName);if(!u){q(d,K("Not Found",h,`<p>Unknown repo: ${l.params.repoName}</p>`),404);return}let S=K(`Force Sync: ${u.name}`,h,`<div class="card">
66
- <p>This will read <strong>all</strong> documents from the <code>${u.name}</code> Firestore collection
67
- and upsert them into all active target storage adapters (${u.adapters.map(E=>E.name).join(", ")}).</p>
64
+ ${x.map(m).join(`
65
+ `)}`);J(p,T);}),f.manualSync&&(I.get(`${a}/:repoName/force-sync`,(l,p)=>{let b=Y(l,a,h),c=C.find(T=>T.name===l.params.repoName);if(!c){J(p,Z("Not Found",b,`<p>Unknown repo: ${v(l.params.repoName)}</p>`),404);return}let x=v(c.name),k=c.adapters.map(T=>v(T.name)).join(", "),m=Z(`Force Sync: ${c.name}`,b,`<div class="card">
66
+ <p>This will read <strong>all</strong> documents from the <code>${x}</code> Firestore collection
67
+ and upsert them into all active target storage adapters (${k}).</p>
68
68
  <p class="muted" style="margin:.75rem 0">This may take a while for large collections.</p>
69
- <form method="POST" action="${h}/${u.name}/force-sync">
69
+ <form method="POST" action="${v(b)}/${encodeURIComponent(c.name)}/force-sync">
70
+ <label style="display:block;margin-bottom:.75rem">
71
+ <input type="checkbox" name="dryRun" value="true"> Dry run (scan &amp; validate serialization only, no writes)
72
+ </label>
70
73
  <button type="submit" class="btn btn-primary">Start Force Sync</button>
71
74
  </form>
72
- </div>`);q(d,S);}),H.post(`${a}/:repoName/force-sync`,async(l,d)=>{let h=z(l,a,b),u=k.find(f=>f.name===l.params.repoName);if(!u){W(d,{error:`Unknown repo: ${l.params.repoName}`},404);return}let S=u.repo.ref;if(!S){W(d,{error:`No collection reference for "${u.name}"`},400);return}let E=0,m=0,A=[],w=500,C=S.limit(w),P=null;try{for(;;){let T=await(P?C.startAfter(P):C).get();if(T.empty)break;let D=u.historyShadowKey?Array.from(new Set([...u.repoCfg?.exclude??[],u.historyShadowKey])):u.repoCfg?.exclude;for(let R of T.docs){let _=R.data(),$=String(_[u.documentKey]??R.id),F=U(_,{exclude:D,columnMap:u.repoCfg?.columnMap,flat:u.repoCfg?.flat,transformDoc:u.repoCfg?.transformDoc});try{await r({operation:"UPSERT",repoName:u.name,docId:$,data:F,timestamp:new Date().toISOString()}),E++;}catch(Q){m++;let Le=Q?.message??String(Q);console.error(`[ForceSync:${u.name}] doc=${$} failed:`,Q),A.length<5&&A.push(`${$}: ${Le}`);}}if(P=T.docs[T.docs.length-1],T.docs.length<w)break}for(let f of u.adapters){let T=`${u.name}:${f.name}`,D=n.get(T)??n.get(u.name);D&&await D.flush();}}catch(f){if(te(l)){W(d,{error:f?.message??String(f),synced:E,errors:m},500);return}q(d,K(`Force Sync: ${u.name}`,h,`<div class="card">
73
- <p class="badge badge-err">Error: ${f?.message??String(f)}</p>
74
- <p>Synced ${E} docs before failure (${m} errors).</p>
75
- </div>`),500);return}if(te(l)){W(d,{repo:u.name,table:u.tableName,synced:E,errors:m,...A.length>0&&{errorSamples:A}});return}let N=A.length>0?`<details style="margin-top:1rem"><summary>First ${A.length} error(s)</summary>
76
- <pre style="white-space:pre-wrap">${A.map(f=>f.replace(/[<>&]/g,T=>`&#${T.charCodeAt(0)};`)).join(`
75
+ </div>`);J(p,m);}),I.post(`${a}/:repoName/force-sync`,async(l,p)=>{let b=Y(l,a,h),c=C.find(k=>k.name===l.params.repoName);if(!c){X(p,{error:`Unknown repo: ${l.params.repoName}`},404);return}let x=c.repo.ref;if(!x){X(p,{error:`No collection reference for "${c.name}"`},400);return}if(P.has(c.name)){if(oe(l)){X(p,{error:`Force sync is already running for "${c.name}"`,repo:c.name},409);return}J(p,Z(`Force Sync: ${c.name}`,b,`<div class="card">
76
+ <p class="badge badge-warn">Already Running</p>
77
+ <p>A force sync is already in progress for <strong>${v(c.name)}</strong>. Please wait for it to finish before starting another.</p>
78
+ </div>`),409);return}P.add(c.name);try{let k=Tt(l),m=0,T=0,R=0,w=[],D=500,L=(typeof x.orderBy=="function"?x.orderBy(firestore.FieldPath.documentId()):x).limit(D),g=null,S=new Map,M=()=>{for(let[z,B]of S.entries()){if(typeof z.getStats!="function")continue;let _=z.getStats();for(let F of _.recentErrors)F.seq>B.lastErrorSeq&&w.length<5&&w.push(`[${B.adapterName}] flush failed (${F.count} event(s)): ${F.message}`);B.lastErrorSeq=_.errorSeq;}},E=()=>{if(k)return {synced:0,errors:R};let z=Array.from(S.entries()).filter(([F])=>typeof F.getStats=="function");if(z.length===0)return {synced:T,errors:R};let B=T,_=0;for(let[F,K]of z){let q=F.getStats(),ee=Math.max(0,q.flushedEvents-K.flushedEvents),rt=Math.max(0,q.failedEvents-K.failedEvents);ee<B&&(B=ee),_+=rt;}return {synced:B,errors:R+_}},Q=c.historyShadowKey?Array.from(new Set([...c.repoCfg?.exclude??[],c.historyShadowKey])):c.repoCfg?.exclude;try{if(!k){let z=ke(c,n);for(let{adapterName:B,queue:_}of z)if(await _.flush(),typeof _.getStats=="function"){let F=_.getStats();S.set(_,{adapterName:B,flushedEvents:F.flushedEvents,failedEvents:F.failedEvents,lastErrorSeq:F.errorSeq});}else S.set(_,{adapterName:B,flushedEvents:0,failedEvents:0,lastErrorSeq:0});}for(;;){let z=g?L.startAfter(g):L,B=Date.now(),_=await At(()=>(B=Date.now(),z.get()));if(_.empty||_.docs.length===0)break;for(let F of _.docs){m++;let K=String(F.id??"unknown");try{let q=F.data();K=String(q?.[c.documentKey]??F.id);let ee=te(q,{exclude:Q,columnMap:c.repoCfg?.columnMap,flat:c.repoCfg?.flat,transformDoc:c.repoCfg?.transformDoc});k||(await r({operation:"UPSERT",repoName:c.name,docId:K,data:ee,timestamp:new Date(B).toISOString(),version:B}),T++);}catch(q){R++;let ee=q?.message??String(q);console.error(`[ForceSync:${c.name}] doc=${K} failed:`,q),w.length<5&&w.push(`${K}: ${ee}`);}}if(!k){let F=ke(c,n);for(let{adapterName:K,queue:q}of F)S.has(q)||S.set(q,{adapterName:K,flushedEvents:0,failedEvents:0,lastErrorSeq:0}),await q.flush();M();}if(g=_.docs[_.docs.length-1],_.docs.length<D)break}}catch(z){if(!k){for(let{adapterName:K,queue:q}of ke(c,n))S.has(q)||S.set(q,{adapterName:K,flushedEvents:0,failedEvents:0,lastErrorSeq:0});M();}let{synced:B,errors:_}=E(),F=z?.message??String(z);if(oe(l)){X(p,{error:F,...k&&{dryRun:!0},scanned:m,synced:B,errors:_,...w.length>0&&{errorSamples:w}},500);return}J(p,Z(`Force Sync: ${c.name}`,b,`<div class="card">
79
+ <p class="badge badge-err">Error: ${v(F)}</p>
80
+ <p>Scanned ${m} docs, synced ${B} docs before failure (${_} errors).</p>
81
+ </div>`),500);return}let{synced:U,errors:j}=E();if(oe(l)){X(p,{...k&&{dryRun:!0},repo:c.name,table:c.tableName,scanned:m,synced:U,errors:j,...w.length>0&&{errorSamples:w}});return}let se=w.length>0?`<details style="margin-top:1rem"><summary>First ${w.length} error(s)</summary>
82
+ <pre style="white-space:pre-wrap">${w.map(z=>v(z)).join(`
77
83
 
78
- `)}</pre></details>`:"",M=K(`Force Sync: ${u.name}`,h,`<div class="card">
79
- <p class="badge ${m>0?"badge-warn":"badge-ok"}">${m>0?"Completed with errors":"Complete"}</p>
80
- <p>Synced <strong>${E}</strong> documents to targets (${u.adapters.map(f=>f.name).join(", ")}).</p>
81
- ${m>0?`<p class="badge badge-warn">${m} error(s)</p>`:""}
82
- ${N}
83
- </div>`);q(d,M);})),y.configCheck&&H.get(`${a}/config-check`,async(l,d)=>{let h=z(l,a,b),u=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??process.env.GCP_PROJECT??"unknown",S="https://console.cloud.google.com",E=c??"firestore-sync",m=[];for(let f of g)if(f.name==="bigquery")try{await f.targetExists("__nonexistent_health_check__"),m.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable"});}catch(T){let D=T?.message??String(T),R=D.toLowerCase(),_=R.includes("disabled")||R.includes("has not been used")||R.includes("accessnotconfigured"),$=R.includes("permission")||D.includes("403")||R.includes("access denied"),F=R.includes("project")&&R.includes("not found"),Q=R.includes("not found")||D.includes("404");_?m.push({name:"BigQuery API",category:"bigquery",status:"error",message:"BigQuery API is not enabled",fix:{gcloud:`gcloud services enable bigquery.googleapis.com --project=${u}`,console:`${S}/apis/library/bigquery.googleapis.com?project=${u}`}}):F?m.push({name:"BigQuery Project",category:"bigquery",status:"error",message:D,fix:{hint:"The GCP project does not exist or the credentials don't have access to it.",console:`${S}/home/dashboard`}}):$?m.push({name:"BigQuery API",category:"bigquery",status:"error",message:`Permission denied: ${D}`,fix:{hint:"Grant the service account BigQuery Data Editor + BigQuery Job User roles",console:`${S}/iam-admin/iam?project=${u}`}}):Q?m.push({name:"BigQuery Dataset",category:"bigquery",status:"error",message:`Dataset not found: ${D}`,fix:{hint:"Create the dataset first",gcloud:`bq mk --dataset ${u}:YOUR_DATASET_ID`,console:`${S}/bigquery?project=${u}`}}):m.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable (table lookup returned expected error)"});}else if(f.name==="meilisearch"||typeof f.checkConnection=="function")try{let T=typeof f.checkConnection=="function"?await f.checkConnection():{healthy:await f.targetExists("__nonexistent__")};m.push({name:"Meilisearch API",category:"meilisearch",status:T.healthy?"ok":"error",message:T.healthy?`Meilisearch is reachable${T.version?` (v${T.version})`:""}`:`Meilisearch connection error: ${T.error??"unknown"}`,...T.error&&{fix:{hint:"Ensure Meilisearch is running and host/apiKey options are valid."}}});}catch(T){m.push({name:"Meilisearch API",category:"meilisearch",status:"error",message:`Meilisearch error: ${T?.message??String(T)}`});}for(let f of k)for(let T of f.adapters){let D=T.name==="bigquery"?"bigquery":T.name==="meilisearch"?"meilisearch":"storage";try{let R=await T.targetExists(f.tableName);m.push({name:`[${T.name}] Target: ${f.tableName}`,category:D,status:R?"ok":"warn",message:R?`Target \`${f.tableName}\` exists`:`Target \`${f.tableName}\` does not exist yet`,...!R&&{fix:{hint:"Target will be auto-created on first sync if autoMigrate is enabled."}}});}catch(R){m.push({name:`[${T.name}] Target: ${f.tableName}`,category:D,status:"error",message:R?.message??String(R)});}}if(i)for(let f of k){let T=`${E}-${f.name}`;try{let D=i.topic(T);if(typeof D.exists=="function"){let[R]=await D.exists();m.push({name:`Topic: ${T}`,category:"pubsub",status:R?"ok":"error",message:R?`Topic \`${T}\` exists`:`Topic \`${T}\` does not exist`,...!R&&{fix:{gcloud:`gcloud pubsub topics create ${T} --project=${u}`,console:`${S}/cloudpubsub/topic/list?project=${u}`}}});}else m.push({name:`Topic: ${T}`,category:"pubsub",status:"warn",message:"Cannot verify topic existence (PubSub client doesn't expose .exists())",fix:{gcloud:`gcloud pubsub topics create ${T} --project=${u}`,console:`${S}/cloudpubsub/topic/list?project=${u}`}});}catch(D){let R=D?.message??String(D),_=R.includes("disabled")||R.includes("has not been used");if(m.push({name:_?"Pub/Sub API":`Topic: ${T}`,category:"pubsub",status:"error",message:_?"Pub/Sub API is not enabled":R,fix:_?{gcloud:`gcloud services enable pubsub.googleapis.com --project=${u}`,console:`${S}/apis/library/pubsub.googleapis.com?project=${u}`}:{gcloud:`gcloud pubsub topics create ${T} --project=${u}`,console:`${S}/cloudpubsub/topic/list?project=${u}`}}),_)break}}else m.push({name:"Pub/Sub Client",category:"pubsub",status:"warn",message:"PubSub client not available for config check"});if(te(l)){let f=m.every(T=>T.status==="ok");W(d,{project:u,healthy:f,checks:m});return}let A=f=>f==="ok"?'<span class="badge badge-ok">OK</span>':f==="warn"?'<span class="badge badge-warn">WARN</span>':'<span class="badge badge-err">ERROR</span>',w={bigquery:m.filter(f=>f.category==="bigquery"),meilisearch:m.filter(f=>f.category==="meilisearch"),pubsub:m.filter(f=>f.category==="pubsub"),firestore:m.filter(f=>f.category==="firestore"),storage:m.filter(f=>f.category==="storage")},C=(f,T)=>{if(T.length===0)return "";let D=T.map(R=>{let _="";if(R.fix){let $=[];R.fix.hint&&$.push(`<p class="muted">${R.fix.hint}</p>`),R.fix.gcloud&&$.push(`<pre>$ ${R.fix.gcloud}</pre>`),R.fix.console&&$.push(`<p><a href="${R.fix.console}" target="_blank">Open GCP Console \u2192</a></p>`),_=`<div style="margin-top:.5rem">${$.join("")}</div>`;}return `<tr>
84
- <td>${A(R.status)}</td>
85
- <td><strong>${R.name}</strong><br><span class="muted">${R.message}</span>${_}</td>
84
+ `)}</pre></details>`:"",Xe=c.adapters.map(z=>v(z.name)).join(", "),et=k?`<p class="badge ${j>0?"badge-warn":"badge-ok"}">${j>0?"Dry run completed with errors":"Dry run complete"}</p>`:`<p class="badge ${j>0?"badge-warn":"badge-ok"}">${j>0?"Completed with errors":"Complete"}</p>`,tt=k?`<p>Dry run scanned <strong>${m}</strong> documents (0 synced, no writes performed).</p>`:`<p>Scanned <strong>${m}</strong> documents, synced <strong>${U}</strong> documents to targets (${Xe}).</p>`,nt=Z(`Force Sync: ${c.name}`,b,`<div class="card">
85
+ ${et}
86
+ ${tt}
87
+ ${j>0?`<p class="badge badge-warn">${j} error(s)</p>`:""}
88
+ ${se}
89
+ </div>`);J(p,nt);}finally{P.delete(c.name);}})),f.configCheck&&I.get(`${a}/config-check`,async(l,p)=>{let b=Y(l,a,h),c=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??process.env.GCP_PROJECT??"unknown",x="https://console.cloud.google.com",k=u??"firestore-sync",m=[];for(let g of y)if(g.name==="bigquery")try{await g.targetExists("__nonexistent_health_check__"),m.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable"});}catch(S){let M=S?.message??String(S),E=M.toLowerCase(),Q=E.includes("disabled")||E.includes("has not been used")||E.includes("accessnotconfigured"),U=E.includes("permission")||M.includes("403")||E.includes("access denied"),j=E.includes("project")&&E.includes("not found"),se=E.includes("not found")||M.includes("404");Q?m.push({name:"BigQuery API",category:"bigquery",status:"error",message:"BigQuery API is not enabled",fix:{gcloud:`gcloud services enable bigquery.googleapis.com --project=${c}`,console:`${x}/apis/library/bigquery.googleapis.com?project=${c}`}}):j?m.push({name:"BigQuery Project",category:"bigquery",status:"error",message:M,fix:{hint:"The GCP project does not exist or the credentials don't have access to it.",console:`${x}/home/dashboard`}}):U?m.push({name:"BigQuery API",category:"bigquery",status:"error",message:`Permission denied: ${M}`,fix:{hint:"Grant the service account BigQuery Data Editor + BigQuery Job User roles",console:`${x}/iam-admin/iam?project=${c}`}}):se?m.push({name:"BigQuery Dataset",category:"bigquery",status:"error",message:`Dataset not found: ${M}`,fix:{hint:"Create the dataset first",gcloud:`bq mk --dataset ${c}:YOUR_DATASET_ID`,console:`${x}/bigquery?project=${c}`}}):m.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable (table lookup returned expected error)"});}else if(g.name==="meilisearch"||typeof g.checkConnection=="function")try{let S=typeof g.checkConnection=="function"?await g.checkConnection():{healthy:await g.targetExists("__nonexistent__")};m.push({name:"Meilisearch API",category:"meilisearch",status:S.healthy?"ok":"error",message:S.healthy?`Meilisearch is reachable${S.version?` (v${S.version})`:""}`:`Meilisearch connection error: ${S.error??"unknown"}`,...S.error&&{fix:{hint:"Ensure Meilisearch is running and host/apiKey options are valid."}}});}catch(S){m.push({name:"Meilisearch API",category:"meilisearch",status:"error",message:`Meilisearch error: ${S?.message??String(S)}`});}for(let g of C)for(let S of g.adapters){let M=S.name==="bigquery"?"bigquery":S.name==="meilisearch"?"meilisearch":"storage";try{let E=await S.targetExists(g.tableName);m.push({name:`[${S.name}] Target: ${g.tableName}`,category:M,status:E?"ok":"warn",message:E?`Target \`${g.tableName}\` exists`:`Target \`${g.tableName}\` does not exist yet`,...!E&&{fix:{hint:"Target will be auto-created on first sync if autoMigrate is enabled."}}});}catch(E){m.push({name:`[${S.name}] Target: ${g.tableName}`,category:M,status:"error",message:E?.message??String(E)});}}if(i)for(let g of C){let S=`${k}-${g.name}`;try{let M=i.topic(S);if(typeof M.exists=="function"){let[E]=await M.exists();m.push({name:`Topic: ${S}`,category:"pubsub",status:E?"ok":"error",message:E?`Topic \`${S}\` exists`:`Topic \`${S}\` does not exist`,...!E&&{fix:{gcloud:`gcloud pubsub topics create ${S} --project=${c}`,console:`${x}/cloudpubsub/topic/list?project=${c}`}}});}else m.push({name:`Topic: ${S}`,category:"pubsub",status:"warn",message:"Cannot verify topic existence (PubSub client doesn't expose .exists())",fix:{gcloud:`gcloud pubsub topics create ${S} --project=${c}`,console:`${x}/cloudpubsub/topic/list?project=${c}`}});}catch(M){let E=M?.message??String(M),Q=E.includes("disabled")||E.includes("has not been used");if(m.push({name:Q?"Pub/Sub API":`Topic: ${S}`,category:"pubsub",status:"error",message:Q?"Pub/Sub API is not enabled":E,fix:Q?{gcloud:`gcloud services enable pubsub.googleapis.com --project=${c}`,console:`${x}/apis/library/pubsub.googleapis.com?project=${c}`}:{gcloud:`gcloud pubsub topics create ${S} --project=${c}`,console:`${x}/cloudpubsub/topic/list?project=${c}`}}),Q)break}}else m.push({name:"Pub/Sub Client",category:"pubsub",status:"warn",message:"PubSub client not available for config check"});if(oe(l)){let g=m.every(S=>S.status==="ok");X(p,{project:c,healthy:g,checks:m});return}let T=g=>g==="ok"?'<span class="badge badge-ok">OK</span>':g==="warn"?'<span class="badge badge-warn">WARN</span>':'<span class="badge badge-err">ERROR</span>',R={bigquery:m.filter(g=>g.category==="bigquery"),meilisearch:m.filter(g=>g.category==="meilisearch"),pubsub:m.filter(g=>g.category==="pubsub"),firestore:m.filter(g=>g.category==="firestore"),storage:m.filter(g=>g.category==="storage")},w=(g,S)=>{if(S.length===0)return "";let M=S.map(E=>{let Q="";if(E.fix){let U=[];E.fix.hint&&U.push(`<p class="muted">${v(E.fix.hint)}</p>`),E.fix.gcloud&&U.push(`<pre>$ ${v(E.fix.gcloud)}</pre>`),E.fix.console&&U.push(`<p><a href="${v(E.fix.console)}" target="_blank">Open GCP Console \u2192</a></p>`),Q=`<div style="margin-top:.5rem">${U.join("")}</div>`;}return `<tr>
90
+ <td>${T(E.status)}</td>
91
+ <td><strong>${v(E.name)}</strong><br><span class="muted">${v(E.message)}</span>${Q}</td>
86
92
  </tr>`}).join(`
87
- `);return `<h2>${f}</h2>
93
+ `);return `<h2>${v(g)}</h2>
88
94
  <table><thead><tr><th style="width:80px">Status</th><th>Check</th></tr></thead>
89
- <tbody>${D}</tbody></table>`},N=m.every(f=>f.status==="ok")?'<span class="badge badge-ok">All checks passed</span>':'<span class="badge badge-warn">Some issues found</span>',M=K("Config Check",h,`<div class="card">
90
- <p>Project: <code>${u}</code> ${N}</p>
91
- ${C("BigQuery",w.bigquery)}
92
- ${C("Meilisearch",w.meilisearch)}
93
- ${C("Pub/Sub",w.pubsub)}
94
- ${C("Other Targets",w.storage)}
95
- ${C("Firestore",w.firestore)}
96
- </div>`);q(d,M);}),async(l,d)=>{await H.handle(l,d);}}var st="firestore-sync";function ot(t,e){return e?`${e}/{docId}`:(console.warn(`[SyncTriggers] Cannot determine collection path for "${t}". Skipping.`),null)}function it(t){let e=[t?.documentKey,t?.pathKey,t?.createdKey,t?.updatedKey].filter(s=>typeof s=="string"),n=typeof t?.path=="string"?t.path:null,r=n?Y(n,t?.documentKey??"docId"):null;return {isGroup:!!t?.isGroup,documentKey:e[0]??"docId",collectionPath:r?r.collectionPath:null,documentPathTemplate:r&&(!t?.isGroup||r.collectionPath.includes("/"))?r.documentPathTemplate:null,historyShadowKey:L(t?.history)}}function at(t){let e=t?._collectionPath??t?.ref?.path??null,n=typeof t?._documentPathTemplate=="string"?t._documentPathTemplate:null;return {isGroup:!!t?._isGroup,documentKey:t?._systemKeys?.[0]??"docId",collectionPath:e,documentPathTemplate:n&&(!t?._isGroup||e&&e.includes("/"))?n:null,historyShadowKey:typeof t?._historyShadowKey=="string"?t._historyShadowKey:L(t?._historyConfig)}}function me(t,e){let{onDocumentWritten:n}=e.deps.firestoreTriggers,r=e.deps.pubsub,s=e?.topicPrefix??st,o={},i=new Map;function c(x){let p=i.get(x);return p||(p=r.topic(x),i.set(x,p),p)}async function a(x,p){await c(x).publishMessage({json:p});}let y=t?.rawMapping,b=y?Object.entries(y).map(([x,p])=>[x,it(p)]):Object.entries(t).map(([x,p])=>[x,at(p)]),g=e?.repos,k=Object.keys(g??{}).length>0;for(let[x,p]of b){if(k&&(!g||!(x in g)))continue;let v=g?.[x],I;if(p.isGroup){let E=v?.triggerPath??p.documentPathTemplate;if(!E){console.warn(`[SyncTriggers] Skipping collection-group repo "${x}". Provide a triggerPath in the sync repos config for group collections or use a full path template.`);continue}I=E;}else I=v?.triggerPath??p.documentPathTemplate??ot(x,p.collectionPath);if(!I)continue;let H=p.documentKey,l=p.historyShadowKey?Array.from(new Set([...v?.exclude??[],p.historyShadowKey])):v?.exclude,d=`${s}-${x}`,h={...e?.triggerOptions,...v?.triggerOptions},u=Object.keys(h).length>0,S=async E=>{let m=E.data?.before,A=E.data?.after;if(!m&&!A)return;let w=!!m?.exists,C=!!A?.exists;if(!w&&C){let P=A.data();if(!P)return;let N=String(P[H]??A.id),M=U(P,{exclude:l,columnMap:v?.columnMap,flat:v?.flat,transformDoc:v?.transformDoc}),f={operation:"INSERT",repoName:x,docId:N,data:M,timestamp:new Date().toISOString(),version:Date.now()};await a(d,f);}else if(w&&C){let P=A.data();if(!P)return;let N=String(P[H]??A.id),M=U(P,{exclude:l,columnMap:v?.columnMap,flat:v?.flat,transformDoc:v?.transformDoc}),f={operation:"UPSERT",repoName:x,docId:N,data:M,timestamp:new Date().toISOString(),version:Date.now()};await a(d,f);}else if(w&&!C){let P=m.data(),N=String(P?.[H]??m.id),M={operation:"DELETE",repoName:x,docId:N,data:null,timestamp:new Date().toISOString(),version:Date.now()};await a(d,M);}};o[`${x}_onSync`]=n(u?{document:I,...h}:I,S);}return o}var j="__sync_version";var ct={string:"ZodString",number:"ZodNumber",bigint:"ZodBigInt",boolean:"ZodBoolean",date:"ZodDate",enum:"ZodEnum",nativeEnum:"ZodNativeEnum",literal:"ZodLiteral",object:"ZodObject",array:"ZodArray",optional:"ZodOptional",nullable:"ZodNullable",default:"ZodDefault",coerce:"ZodCoerce",union:"ZodUnion",undefined:"ZodUndefined",unknown:"ZodUnknown",any:"ZodAny",record:"ZodRecord"};function ne(t){let e=t,n=e._zod?.def?.type;if(n)return ct[n]??`Zod${n.charAt(0).toUpperCase()}${n.slice(1)}`;let r=e._def?.typeName;return r||""}function ve(t){let e=t;if(e._zod?.def?.innerType)return e._zod.def.innerType;if(e._def?.innerType)return e._def.innerType}function ge(t){let e=t;return e.shape&&typeof e.shape=="object"?e.shape:e._zod?.def?.shape&&typeof e._zod.def.shape=="object"?e._zod.def.shape:e._def?.shape?typeof e._def.shape=="function"?e._def.shape():e._def.shape:{}}var ut=new Set(["ZodOptional","ZodNullable","ZodDefault"]);function He(t){let e=t,n=false;for(;;){let r=ne(e);if(!ut.has(r))break;(r==="ZodOptional"||r==="ZodNullable")&&(n=true);let s=ve(e);if(!s)break;e=s;}return {inner:e,nullable:n}}var Ie={ZodString:"string",ZodNumber:"number",ZodBigInt:"bigint",ZodBoolean:"boolean",ZodDate:"timestamp",ZodEnum:"string",ZodNativeEnum:"string",ZodLiteral:"string"};function lt(t){let{inner:e}=He(t);return Ie[ne(e)]??"json"}function Me(t,e,n,r,s,o,i,c){for(let[a,y]of Object.entries(t)){let b=n?`${n}__${a}`:a;if(s.has(a)||s.has(b))continue;let{inner:g,nullable:O}=He(y),k=ne(g),x=r||O;if(k==="ZodObject"){let H=ge(g);Me(H,e,b,x,s,o,i,c);continue}let p=Ie[k]??"json",v=b===i||a===i,I=o[b]??o[a]??b;c.push({name:I,sqlType:e.mapType(p),nullable:v?false:x,isPrimaryKey:v});}}function B(t,e,n={}){let{primaryKey:r,exclude:s=[],columnMap:o={}}=n,i=new Set(s),c=ge(t),a=[];return Me(c,e,"",false,i,o,r,a),a.some(y=>y.name===j)||a.push({name:j,sqlType:e.mapType("bigint"),nullable:true,isPrimaryKey:false,description:"Monotonic publish version (Date.now() ms). Internal."}),a}function re(t){let e=t.toUpperCase();switch(e){case "INTEGER":return "INT64";case "FLOAT":return "FLOAT64";case "BOOLEAN":return "BOOL";default:return e}}function Ne(t,e){let n=re(t),r=re(e);return n===r?true:{INT64:["NUMERIC","BIGNUMERIC","FLOAT64"],NUMERIC:["BIGNUMERIC","FLOAT64"],DATE:["DATETIME","TIMESTAMP"],DATETIME:["TIMESTAMP"]}[n]?.includes(r)??false}var he=class{constructor(){this.name="bigquery";}mapType(e){switch(e){case "string":return "STRING";case "number":return "FLOAT64";case "bigint":return "INT64";case "boolean":return "BOOL";case "timestamp":return "TIMESTAMP";case "json":return "JSON";case "text":return "STRING"}}quoteIdentifier(e){return "`"+e.replace(/`/g,"``")+"`"}},$e=new he,se=null;function dt(){return se||(se=Te("@google-cloud/bigquery-storage"),se)}function _e(t){let e;return typeof t=="bigint"?e=t:typeof t=="number"||typeof t=="string"?e=BigInt(t):e=0n,e<0n&&(e=0n),e.toString(16).padStart(16,"0")}function ft(t){if(!t||typeof t!="object")return false;let e=t;return e.code===4||e.code===10||e.code===13||e.code===14}async function pt(t,e=6,n=200){let r=0;for(;;)try{return await t()}catch(s){if(r++,!ft(s)||r>e)throw s;let o=n*Math.pow(2,r),i=Math.random()*o;await new Promise(c=>setTimeout(c,i));}}var V=class extends Error{constructor(n,r,s,o){super(`Schema drift detected on \`${n}\`: column \`${r}\` has type ${s} in BigQuery but the current Zod schema maps it to ${o}. BigQuery cannot safely convert between these types \u2014 to resolve, either (a) keep the BigQuery type and add a transform in your repo to coerce values, (b) rename the field in your Zod schema (creates a new column), or (c) drop & recreate the table.`);this.tableName=n;this.column=r;this.existingType=s;this.desiredType=o;this.name="SchemaTypeMismatchError";}},G=class G{constructor(e){this.name="bigquery";this.writers=new Map;this.bigquery=e.bigquery,this.projectId=e.projectId,this.datasetId=e.datasetId,this.maxStaleness=e.maxStaleness===void 0?"INTERVAL 15 MINUTE":e.maxStaleness,this.writerClient=e.writerClient;}get dialect(){return $e}async targetExists(e){return this.tableExists(e)}async upsert(e,n,r){return this.upsertRows(e,n,r)}async delete(e,n,r){return this.deleteRows(e,n,r)}async ensureTarget(e){if(!e.schema)return;let{targetName:n,primaryKey:r,schema:s,exclude:o,columnMap:i}=e,c=B(s,this.dialect,{primaryKey:r,exclude:o,columnMap:i});if(!await this.tableExists(n))await this.createTable({tableName:n,columns:c});else {let y=await this.getTableColumnsWithTypes(n),b=[];for(let g of c){let O=y.get(g.name);if(O===void 0){b.push(g);continue}if(!Ne(O,g.sqlType))throw new V(n,g.name,O,g.sqlType)}b.length>0&&(await this.addColumns(n,b),await this.onSchemaChange?.(n));}}async healthCheck(e){let{targetName:n,primaryKey:r,schema:s,repoConfig:o}=e;if(!s)return {healthy:false,targetName:n,targetExists:false,error:"No Zod schema attached to repository"};try{if(!await this.tableExists(n))return {healthy:!1,targetName:n,targetExists:!1,error:`Table \`${n}\` does not exist`};let c=await this.getTableColumns(n),a=B(s,this.dialect,{primaryKey:r,exclude:o?.exclude,columnMap:o?.columnMap}),y=new Set(c),b=new Set(a.map(p=>p.name)),g=a.filter(p=>!y.has(p.name)),O=c.filter(p=>!b.has(p)),k=a.filter(p=>y.has(p.name)),x=g.length===0;return {healthy:x,targetName:n,targetExists:!0,error:x?null:`Missing columns: ${g.map(p=>p.name).join(", ")}`,details:{expected:a.map(p=>({name:p.name,type:p.sqlType,nullable:p.nullable,isPrimaryKey:p.isPrimaryKey})),actual:c,matched:k.map(p=>p.name),missing:g.map(p=>({name:p.name,type:p.sqlType})),extra:O}}}catch(i){return {healthy:false,targetName:n,targetExists:false,error:i?.message??String(i)}}}async tableExists(e){let[n]=await this.dataset.table(e).exists();return n}async getTableColumns(e){let[n]=await this.dataset.table(e).getMetadata();return (n.schema?.fields??[]).map(s=>s.name)}async getTableColumnsWithTypes(e){let[n]=await this.dataset.table(e).getMetadata(),r=n.schema?.fields??[],s=new Map;for(let o of r)s.set(o.name,re(o.type));return s}async createTable(e){let n=a=>this.dialect.quoteIdentifier(a),r=e.columns.find(a=>a.isPrimaryKey)?.name;if(!r)throw new Error(`BigQueryAdapter requires a primary key on table \`${e.tableName}\` (Storage Write CDC mode needs PRIMARY KEY NOT ENFORCED).`);let s=e.columns.map(a=>{let y=a.isPrimaryKey?" NOT NULL":"";return ` ${n(a.name)} ${a.sqlType}${y}`}).join(`,
95
+ <tbody>${M}</tbody></table>`},$=m.every(g=>g.status==="ok")?'<span class="badge badge-ok">All checks passed</span>':'<span class="badge badge-warn">Some issues found</span>',L=Z("Config Check",b,`<div class="card">
96
+ <p>Project: <code>${v(c)}</code> ${$}</p>
97
+ ${w("BigQuery",R.bigquery)}
98
+ ${w("Meilisearch",R.meilisearch)}
99
+ ${w("Pub/Sub",R.pubsub)}
100
+ ${w("Other Targets",R.storage)}
101
+ ${w("Firestore",R.firestore)}
102
+ </div>`);J(p,L);}),async(l,p)=>{await I.handle(l,p);}}var kt="firestore-sync";function Et(t,e){return e?`${e}/{docId}`:(console.warn(`[SyncTriggers] Cannot determine collection path for "${t}". Skipping.`),null)}function Ct(t){let e=[t?.documentKey,t?.pathKey,t?.createdKey,t?.updatedKey].filter(s=>typeof s=="string"),n=typeof t?.path=="string"?t.path:null,r=n?ue(n,t?.documentKey??"docId"):null;return {isGroup:!!t?.isGroup,documentKey:e[0]??"docId",collectionPath:r?r.collectionPath:null,documentPathTemplate:r&&(!t?.isGroup||r.collectionPath.includes("/"))?r.documentPathTemplate:null,historyShadowKey:G(t?.history)}}function Pt(t){let e=t?._collectionPath??t?.ref?.path??null,n=typeof t?._documentPathTemplate=="string"?t._documentPathTemplate:null;return {isGroup:!!t?._isGroup,documentKey:t?._systemKeys?.[0]??"docId",collectionPath:e,documentPathTemplate:n&&(!t?._isGroup||e&&e.includes("/"))?n:null,historyShadowKey:typeof t?._historyShadowKey=="string"?t._historyShadowKey:G(t?._historyConfig)}}function Ce(t,e){let{onDocumentWritten:n}=e.deps.firestoreTriggers,r=e.deps.pubsub,s=e?.topicPrefix??kt,o={},i=new Map;function u(A){let d=i.get(A);return d||(d=r.topic(A),i.set(A,d),d)}async function a(A,d){await u(A).publishMessage({json:d});}let f=t?.rawMapping,h=f?Object.entries(f).map(([A,d])=>[A,Ct(d)]):Object.entries(t).map(([A,d])=>[A,Pt(d)]),y=e?.repos,C=Object.keys(y??{}).length>0;for(let[A,d]of h){if(C&&(!y||!(A in y)))continue;let H=y?.[A],N;if(d.isGroup){let x=H?.triggerPath??d.documentPathTemplate;if(!x){console.warn(`[SyncTriggers] Skipping collection-group repo "${A}". Provide a triggerPath in the sync repos config for group collections or use a full path template.`);continue}N=x;}else N=H?.triggerPath??d.documentPathTemplate??Et(A,d.collectionPath);if(!N)continue;let I=d.documentKey,P=d.historyShadowKey?Array.from(new Set([...H?.exclude??[],d.historyShadowKey])):H?.exclude,l=`${s}-${A}`,p={...e?.triggerOptions,...H?.triggerOptions},b=Object.keys(p).length>0,c=async x=>{let k=x.data?.before,m=x.data?.after;if(!k&&!m)return;let T=!!k?.exists,R=!!m?.exists;if(!T&&R){let w=m.data();if(!w)return;let D=String(w[I]??m.id),$=te(w,{exclude:P,columnMap:H?.columnMap,flat:H?.flat,transformDoc:H?.transformDoc}),L={operation:"INSERT",repoName:A,docId:D,data:$,timestamp:new Date().toISOString(),version:Date.now()};await a(l,L);}else if(T&&R){let w=m.data();if(!w)return;let D=String(w[I]??m.id),$=te(w,{exclude:P,columnMap:H?.columnMap,flat:H?.flat,transformDoc:H?.transformDoc}),L={operation:"UPSERT",repoName:A,docId:D,data:$,timestamp:new Date().toISOString(),version:Date.now()};await a(l,L);}else if(T&&!R){let w=k.data(),D=String(w?.[I]??k.id),$={operation:"DELETE",repoName:A,docId:D,data:null,timestamp:new Date().toISOString(),version:Date.now()};await a(l,$);}};o[`${A}_onSync`]=n(b?{document:N,...p}:N,c);}return o}var W="__sync_version";var Ot={string:"ZodString",number:"ZodNumber",bigint:"ZodBigInt",boolean:"ZodBoolean",date:"ZodDate",enum:"ZodEnum",nativeEnum:"ZodNativeEnum",literal:"ZodLiteral",object:"ZodObject",array:"ZodArray",optional:"ZodOptional",nullable:"ZodNullable",default:"ZodDefault",coerce:"ZodCoerce",union:"ZodUnion",undefined:"ZodUndefined",unknown:"ZodUnknown",any:"ZodAny",record:"ZodRecord"};function fe(t){let e=t,n=e._zod?.def?.type;if(n)return Ot[n]??`Zod${n.charAt(0).toUpperCase()}${n.slice(1)}`;let r=e._def?.typeName;return r||""}function qe(t){let e=t;if(e._zod?.def?.innerType)return e._zod.def.innerType;if(e._def?.innerType)return e._def.innerType}function Pe(t){let e=t;return e.shape&&typeof e.shape=="object"?e.shape:e._zod?.def?.shape&&typeof e._zod.def.shape=="object"?e._zod.def.shape:e._def?.shape?typeof e._def.shape=="function"?e._def.shape():e._def.shape:{}}var vt=new Set(["ZodOptional","ZodNullable","ZodDefault"]);function Qe(t){let e=t,n=false;for(;;){let r=fe(e);if(!vt.has(r))break;(r==="ZodOptional"||r==="ZodNullable")&&(n=true);let s=qe(e);if(!s)break;e=s;}return {inner:e,nullable:n}}var Ue={ZodString:"string",ZodNumber:"number",ZodBigInt:"bigint",ZodBoolean:"boolean",ZodDate:"timestamp",ZodEnum:"string",ZodNativeEnum:"string",ZodLiteral:"string"};function Dt(t){let{inner:e}=Qe(t);return Ue[fe(e)]??"json"}function Ke(t,e,n,r,s,o,i,u){for(let[a,f]of Object.entries(t)){let h=n?`${n}__${a}`:a;if(s.has(a)||s.has(h))continue;let{inner:y,nullable:O}=Qe(f),C=fe(y),A=r||O;if(C==="ZodObject"){let I=Pe(y);Ke(I,e,h,A,s,o,i,u);continue}let d=Ue[C]??"json",H=h===i||a===i,N=o[h]??o[a]??h;u.push({name:N,sqlType:e.mapType(d),nullable:H?false:A,isPrimaryKey:H});}}function V(t,e,n={}){let{primaryKey:r,exclude:s=[],columnMap:o={}}=n,i=new Set(s),u=Pe(t),a=[];return Ke(u,e,"",false,i,o,r,a),a.some(f=>f.name===W)||a.push({name:W,sqlType:e.mapType("bigint"),nullable:true,isPrimaryKey:false,description:"Monotonic publish version (Date.now() ms). Internal."}),a}function pe(t){let e=t.toUpperCase();switch(e){case "INTEGER":return "INT64";case "FLOAT":return "FLOAT64";case "BOOLEAN":return "BOOL";default:return e}}function We(t,e){let n=pe(t),r=pe(e);return n===r?true:{INT64:["NUMERIC","BIGNUMERIC","FLOAT64"],NUMERIC:["BIGNUMERIC","FLOAT64"],DATE:["DATETIME","TIMESTAMP"],DATETIME:["TIMESTAMP"]}[n]?.includes(r)??false}var Oe=class{constructor(){this.name="bigquery";}mapType(e){switch(e){case "string":return "STRING";case "number":return "FLOAT64";case "bigint":return "INT64";case "boolean":return "BOOL";case "timestamp":return "TIMESTAMP";case "json":return "JSON";case "text":return "STRING"}}quoteIdentifier(e){return "`"+e.replace(/`/g,"``")+"`"}},Ge=new Oe,ye=null;function Ht(){return ye||(ye=He("@google-cloud/bigquery-storage"),ye)}function Ve(t){let e;return typeof t=="bigint"?e=t:typeof t=="number"||typeof t=="string"?e=BigInt(t):e=0n,e<0n&&(e=0n),e.toString(16).padStart(16,"0")}function It(t){if(!t||typeof t!="object")return false;let e=t;return e.code===4||e.code===10||e.code===13||e.code===14}async function Mt(t,e=6,n=200){let r=0;for(;;)try{return await t()}catch(s){if(r++,!It(s)||r>e)throw s;let o=n*Math.pow(2,r),i=Math.random()*o;await new Promise(u=>setTimeout(u,i));}}var ie=class extends Error{constructor(n,r,s,o){super(`Schema drift detected on \`${n}\`: column \`${r}\` has type ${s} in BigQuery but the current Zod schema maps it to ${o}. BigQuery cannot safely convert between these types \u2014 to resolve, either (a) keep the BigQuery type and add a transform in your repo to coerce values, (b) rename the field in your Zod schema (creates a new column), or (c) drop & recreate the table.`);this.tableName=n;this.column=r;this.existingType=s;this.desiredType=o;this.name="SchemaTypeMismatchError";}},re=class re{constructor(e){this.name="bigquery";this.writers=new Map;this.bigquery=e.bigquery,this.projectId=e.projectId,this.datasetId=e.datasetId,this.maxStaleness=e.maxStaleness===void 0?"INTERVAL 15 MINUTE":e.maxStaleness,this.writerClient=e.writerClient;}get dialect(){return Ge}async targetExists(e){return this.tableExists(e)}async upsert(e,n,r){return this.upsertRows(e,n,r)}async delete(e,n,r){return this.deleteRows(e,n,r)}async ensureTarget(e){if(!e.schema)return;let{targetName:n,primaryKey:r,schema:s,exclude:o,columnMap:i}=e,u=V(s,this.dialect,{primaryKey:r,exclude:o,columnMap:i});if(!await this.tableExists(n))await this.createTable({tableName:n,columns:u});else {let f=await this.getTableColumnsWithTypes(n),h=[];for(let y of u){let O=f.get(y.name);if(O===void 0){h.push(y);continue}if(!We(O,y.sqlType))throw new ie(n,y.name,O,y.sqlType)}h.length>0&&(await this.addColumns(n,h),await this.onSchemaChange?.(n));}}async healthCheck(e){let{targetName:n,primaryKey:r,schema:s,repoConfig:o}=e;if(!s)return {healthy:false,targetName:n,targetExists:false,error:"No Zod schema attached to repository"};try{if(!await this.tableExists(n))return {healthy:!1,targetName:n,targetExists:!1,error:`Table \`${n}\` does not exist`};let u=await this.getTableColumns(n),a=V(s,this.dialect,{primaryKey:r,exclude:o?.exclude,columnMap:o?.columnMap}),f=new Set(u),h=new Set(a.map(d=>d.name)),y=a.filter(d=>!f.has(d.name)),O=u.filter(d=>!h.has(d)),C=a.filter(d=>f.has(d.name)),A=y.length===0;return {healthy:A,targetName:n,targetExists:!0,error:A?null:`Missing columns: ${y.map(d=>d.name).join(", ")}`,details:{expected:a.map(d=>({name:d.name,type:d.sqlType,nullable:d.nullable,isPrimaryKey:d.isPrimaryKey})),actual:u,matched:C.map(d=>d.name),missing:y.map(d=>({name:d.name,type:d.sqlType})),extra:O}}}catch(i){return {healthy:false,targetName:n,targetExists:false,error:i?.message??String(i)}}}async tableExists(e){let[n]=await this.dataset.table(e).exists();return n}async getTableColumns(e){let[n]=await this.dataset.table(e).getMetadata();return (n.schema?.fields??[]).map(s=>s.name)}async getTableColumnsWithTypes(e){let[n]=await this.dataset.table(e).getMetadata(),r=n.schema?.fields??[],s=new Map;for(let o of r)s.set(o.name,pe(o.type));return s}async createTable(e){let n=a=>this.dialect.quoteIdentifier(a),r=e.columns.find(a=>a.isPrimaryKey)?.name;if(!r)throw new Error(`BigQueryAdapter requires a primary key on table \`${e.tableName}\` (Storage Write CDC mode needs PRIMARY KEY NOT ENFORCED).`);let s=e.columns.map(a=>{let f=a.isPrimaryKey?" NOT NULL":"";return ` ${n(a.name)} ${a.sqlType}${f}`}).join(`,
97
103
  `),o=[];this.maxStaleness!==null&&o.push(`max_staleness = ${this.maxStaleness}`);let i=o.length>0?`
98
- OPTIONS(${o.join(", ")})`:"",c=`CREATE TABLE IF NOT EXISTS ${this.fqn(e.tableName)} (
104
+ OPTIONS(${o.join(", ")})`:"",u=`CREATE TABLE IF NOT EXISTS ${this.fqn(e.tableName)} (
99
105
  ${s},
100
106
  PRIMARY KEY (${n(r)}) NOT ENFORCED
101
107
  )
102
- CLUSTER BY ${n(r)}${i};`;await this.bigquery.query({query:c});}async addColumns(e,n){let r=s=>this.dialect.quoteIdentifier(s);for(let s of n){let o=`ALTER TABLE ${this.fqn(e)} ADD COLUMN ${r(s.name)} ${s.sqlType};`;await this.bigquery.query({query:o});}}async executeRaw(e){await this.bigquery.query({query:e});}onSchemaChange(e){let n=this.writers.get(e);if(n){try{n.writer.close();}catch{}this.writers.delete(e);}}async insertRows(e,n){if(n.length===0)return;let r=await this.getOrCreateWriter(e),s=this.writers.get(e)?.timestampColumns,o=n.map(i=>({...this.normalizeRow(i,s),_CHANGE_TYPE:"UPSERT",_CHANGE_SEQUENCE_NUMBER:_e(i[j])}));await this.appendWithRetry(e,r,o);}async upsertRows(e,n,r){if(n.length===0)return;let s=await this.getOrCreateWriter(e,r),o=this.writers.get(e)?.timestampColumns,i=n.map(c=>({...this.normalizeRow(c,o),_CHANGE_TYPE:"UPSERT",_CHANGE_SEQUENCE_NUMBER:_e(c[j])}));await this.appendWithRetry(e,s,i);}async deleteRows(e,n,r){if(r.length===0)return;let s=await this.getOrCreateWriter(e,n),o=r.map(i=>({[n]:i,_CHANGE_TYPE:"DELETE",_CHANGE_SEQUENCE_NUMBER:"ffffffffffffffff"}));await this.appendWithRetry(e,s,o);}get dataset(){return this.bigquery.dataset(this.datasetId)}fqn(e){let n=r=>r.replace(/`/g,"``");return `\`${n(this.datasetId)}.${n(e)}\``}static toEpochMicros(e){let n=e.getTime();return (BigInt(n)*1000n).toString()}normalizeRow(e,n){let r={};for(let[s,o]of Object.entries(e))if(o!==void 0)if(o instanceof Date)r[s]=G.toEpochMicros(o);else if(typeof o=="string"&&this.shouldCoerceTimestamp(s,o,n)){let i=new Date(o);Number.isNaN(i.getTime())?r[s]=o:r[s]=G.toEpochMicros(i);}else typeof o=="object"&&o!==null?r[s]=JSON.stringify(o):typeof o=="bigint"?r[s]=o.toString():r[s]=o;return r}shouldCoerceTimestamp(e,n,r){return r?r.has(e):G.ISO_TIMESTAMP_RE.test(n)}async appendWithRetry(e,n,r){await pt(async()=>{try{await n.appendRows(r).getResult();}catch(s){throw this.onSchemaChange(e),s}});}async getOrCreateWriter(e,n){let r=this.writers.get(e);if(r)if(n&&r.primaryKey!==n)this.onSchemaChange(e);else return r.writer;let s=dt();this.writerClient||(this.writerClient=new s.managedwriter.WriterClient({projectId:this.projectId}));let[o]=await this.dataset.table(e).getMetadata(),i={fields:o.schema?.fields??[]};n||(n=o.tableConstraints?.primaryKey?.columns?.[0]??i.fields[0]?.name);let c=s.adapt.convertBigQuerySchemaToStorageTableSchema(i),a=s.adapt.convertStorageSchemaToProto2Descriptor(c,"Row",s.adapt.withChangeType(),s.adapt.withChangeSequenceNumber()),y=new Set(i.fields.filter(k=>["TIMESTAMP","DATETIME","DATE"].includes(String(k.type??"").toUpperCase())).map(k=>k.name)),b=`projects/${this.projectId}/datasets/${this.datasetId}/tables/${e}`,g=await this.writerClient.createStreamConnection({streamId:s.managedwriter.DefaultStream,destinationTable:b}),O=new s.managedwriter.JSONWriter({connection:g,protoDescriptor:a});return this.writers.set(e,{writer:O,primaryKey:n??"",timestampColumns:y}),O}async close(){for(let{writer:e}of this.writers.values())try{e.close();}catch{}if(this.writers.clear(),this.writerClient&&typeof this.writerClient.close=="function")try{this.writerClient.close();}catch{}}};G.ISO_TIMESTAMP_RE=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/;var be=G;var Z=class{constructor(e){this.buffer=[];this.flushing=false;this.flushPromise=null;this.timer=null;this.adapter=e.adapter,this.tableName=e.tableName,this.primaryKey=e.primaryKey,this.batchSize=e.batchSize??100,this.onFlushError=e.onFlushError;let n=e.flushIntervalMs??5e3;n>0&&(this.timer=setInterval(()=>{this.flush();},n),typeof this.timer=="object"&&"unref"in this.timer&&this.timer.unref());}get size(){return this.buffer.length}enqueue(...e){this.buffer.push(...e),this.buffer.length>=this.batchSize&&this.flush();}async flush(){for(;this.flushPromise;)await this.flushPromise;this.buffer.length!==0&&(this.flushing=true,this.flushPromise=this._drain().finally(()=>{this.flushing=false,this.flushPromise=null;}),await this.flushPromise);}async _drain(){for(;this.buffer.length>0&&await this._doFlush(););}async _doFlush(){let e=this.buffer.splice(0,this.batchSize);try{let n=new Map,r=[];for(let o of e)if(o.operation==="DELETE")r.push(o.docId),n.delete(o.docId);else if(o.data){let i=n.get(o.docId);if(!i)n.set(o.docId,o.data);else {let c=Number(i[j]??0);Number(o.data[j]??0)>=c&&n.set(o.docId,o.data);}}let s=Array.from(n.values());s.length>0&&(typeof this.adapter.upsert=="function"?await this.adapter.upsert(this.tableName,s,this.primaryKey):typeof this.adapter.upsertRows=="function"&&await this.adapter.upsertRows(this.tableName,s,this.primaryKey)),r.length>0&&(typeof this.adapter.delete=="function"?await this.adapter.delete(this.tableName,this.primaryKey,r):typeof this.adapter.deleteRows=="function"&&await this.adapter.deleteRows(this.tableName,this.primaryKey,r));}catch(n){if(this.onFlushError)await this.onFlushError(e,n);else return this.buffer.unshift(...e),console.error(`[SyncQueue] Flush failed for ${this.tableName}:`,n),false}return true}async shutdown(){this.timer&&(clearInterval(this.timer),this.timer=null),await this.flush();}};var Fe=new Set;async function yt(t,e,n,r,s,o,i){let c=`${t}:${e.name}`;if(!Fe.has(c)){if(typeof e.ensureTarget=="function")await e.ensureTarget({targetName:r,primaryKey:s,schema:n,exclude:o,columnMap:i});else if("dialect"in e&&typeof e.createTable=="function"){let a=e,y=B(n,a.dialect,{primaryKey:s,exclude:o,columnMap:i});if(!await a.tableExists(r))await a.createTable({tableName:r,columns:y});else {let g=new Set(await a.getTableColumns(r)),O=y.filter(k=>!g.has(k.name));O.length>0&&(await a.addColumns(r,O),await a.onSchemaChange?.(r));}}Fe.add(c);}}function we(t,e){let{deps:n,adapter:r,adapters:s,batchSize:o=100,flushIntervalMs:i=5e3,autoMigrate:c=false,topicPrefix:a="firestore-sync",maxDlqAttempts:y=5,workerOptions:b,repos:g={}}=e,k=(s||(Array.isArray(r)?r:r?[r]:[])).map(l=>typeof l=="function"?l():l);function x(l){let d=g[l];if(d?.adapters&&d.adapters.length>0){let h=new Set(d.adapters);return k.filter(u=>h.has(u.name))}return k}let p=new Map;function v(l,d,h){let u=`${l}:${d.name}`,S=p.get(u);if(S)return S;let m=g[l]?.tableName??l,A=`${a}-${l}-${d.name}-dlq`,w=n.pubsub.topic(A),C=false,P=async()=>{if(!C){try{await w.create(),console.info(`[SyncWorker:${d.name}] Created DLQ topic "${A}"`);}catch(M){if(M?.code!==6)throw M}C=true;}},N=async(M,f)=>{console.error(`[SyncWorker:${d.name}] Flush failed for "${l}" (${M.length} events):`,f),await P(),await Promise.all(M.map(T=>{let D=(T.attempts??0)+1;if(y>0&&D>y)return console.error(`[SyncWorker:${d.name}] Dropping event for "${l}" after ${D-1} DLQ attempts:`,{docId:T.docId,operation:T.operation}),Promise.resolve();let R={...T,attempts:D,firstFailedAt:T.firstFailedAt??Date.now()};return w.publishMessage({json:R})}));};return S=new Z({adapter:d,tableName:m,primaryKey:h,batchSize:o,flushIntervalMs:i,onFlushError:N}),p.set(u,S),p.has(l)||p.set(l,S),S}async function I(l){let{repoName:d}=l,h=t[d];if(!h){console.warn(`[SyncWorker] Unknown repo "${d}", skipping event`);return}let u=h._systemKeys?.[0]??h.documentKey??"docId",S=g[d],E=S?.columnMap,m=E?.[u]??u;l.data&&(l.data[j]=l.version??Date.now());let A=x(d);for(let w of A){if(c){let P=h.schema??void 0;if(P){let N=S?.tableName??d;await yt(d,w,P,N,m,S?.exclude,E);}}v(d,w,m).enqueue(l);}}function H(l){let d=async h=>{let u=h.data?.message?.json??h.data?.json;if(!u){console.warn("[SyncWorker] Received empty PubSub message");return}await I(u);let S=x(u.repoName);for(let E of S){let m=`${u.repoName}:${E.name}`,A=p.get(m);A&&await A.flush();}};return b?n.pubsubHandler.onMessagePublished({topic:l,...b},d):n.pubsubHandler.onMessagePublished(l,d)}return {handleMessage:I,createHandler:H,queues:p,async shutdown(){let l=[],d=new Set;for(let h of p.values())d.has(h)||(d.add(h),l.push(h.shutdown()));await Promise.all(l);}}}var mt="firestore-sync";function je(t){if(typeof t!="function")return t;let e=t,n;return new Proxy({},{get(r,s){return n||(n=e()),n[s]},has(r,s){return n||(n=e()),s in n}})}function gt(t,e){let{deps:n,adapter:r,adapters:s,topicPrefix:o=mt,batchSize:i,flushIntervalMs:c,autoMigrate:a,admin:y,workerOptions:b,triggerOptions:g,repos:O}=e,k=je(n.pubsub),p=(s||(Array.isArray(r)?r:r?[r]:[])).map(w=>je(w)),v=me(t,{deps:{firestoreTriggers:n.firestoreTriggers,pubsub:k},topicPrefix:o,triggerOptions:g,repos:O}),I=we(t,{deps:{pubsubHandler:n.pubsubHandler,pubsub:k},adapters:p,batchSize:i,flushIntervalMs:c,autoMigrate:a,topicPrefix:o,workerOptions:b,repos:O}),H={},l=O,d=t?.rawMapping,h=Object.keys(l??{}),u=h.length>0,S=Object.keys(d||t),E=u?h.filter(w=>S.includes(w)||w in t):S;for(let w of E){let C=t?.rawMapping,P=C?!!C[w]?.isGroup:!!t[w]?._isGroup,N=C?C[w]?.path:t[w]?._collectionPath,M=typeof N=="string"&&N.includes("/");!u&&P&&!l?.[w]?.triggerPath&&!M||(H[`sync_${w}`]=I.createHandler(`${o}-${w}`));}let m=null;y&&(m=ye(t,p,I.queues,I.handleMessage,y,O??{},k,o),H.adminsync=y.onRequest?y.httpsOptions?y.onRequest(y.httpsOptions,m):y.onRequest(m):m);let A={functions:{...v,...H},adminHandler:m,handleMessage:I.handleMessage,queues:I.queues,shutdown:I.shutdown};for(let w of ["adminHandler","handleMessage","queues","shutdown"])Object.defineProperty(A,w,{enumerable:false});return A}function Be(t,e){let n=e.columns.map(r=>{let s=r.isPrimaryKey?" NOT NULL":"";return ` ${t.quoteIdentifier(r.name)} ${r.sqlType}${s}`}).join(`,
108
+ CLUSTER BY ${n(r)}${i};`;await this.bigquery.query({query:u});}async addColumns(e,n){let r=s=>this.dialect.quoteIdentifier(s);for(let s of n){let o=`ALTER TABLE ${this.fqn(e)} ADD COLUMN ${r(s.name)} ${s.sqlType};`;await this.bigquery.query({query:o});}}async executeRaw(e){await this.bigquery.query({query:e});}onSchemaChange(e){let n=this.writers.get(e);if(n){try{n.writer.close();}catch{}this.writers.delete(e);}}async insertRows(e,n){if(n.length===0)return;let r=await this.getOrCreateWriter(e),s=this.writers.get(e)?.timestampColumns,o=n.map(i=>({...this.normalizeRow(i,s),_CHANGE_TYPE:"UPSERT",_CHANGE_SEQUENCE_NUMBER:Ve(i[W])}));await this.appendWithRetry(e,r,o);}async upsertRows(e,n,r){if(n.length===0)return;let s=await this.getOrCreateWriter(e,r),o=this.writers.get(e)?.timestampColumns,i=n.map(u=>({...this.normalizeRow(u,o),_CHANGE_TYPE:"UPSERT",_CHANGE_SEQUENCE_NUMBER:Ve(u[W])}));await this.appendWithRetry(e,s,i);}async deleteRows(e,n,r){if(r.length===0)return;let s=await this.getOrCreateWriter(e,n),o=r.map(i=>({[n]:i,_CHANGE_TYPE:"DELETE",_CHANGE_SEQUENCE_NUMBER:"ffffffffffffffff"}));await this.appendWithRetry(e,s,o);}get dataset(){return this.bigquery.dataset(this.datasetId)}fqn(e){let n=r=>r.replace(/`/g,"``");return `\`${n(this.datasetId)}.${n(e)}\``}static toEpochMicros(e){let n=e.getTime();return (BigInt(n)*1000n).toString()}normalizeRow(e,n){let r={};for(let[s,o]of Object.entries(e))if(o!==void 0)if(o instanceof Date)r[s]=re.toEpochMicros(o);else if(typeof o=="string"&&this.shouldCoerceTimestamp(s,o,n)){let i=new Date(o);Number.isNaN(i.getTime())?r[s]=o:r[s]=re.toEpochMicros(i);}else typeof o=="object"&&o!==null?r[s]=JSON.stringify(o):typeof o=="bigint"?r[s]=o.toString():r[s]=o;return r}shouldCoerceTimestamp(e,n,r){return r?r.has(e):re.ISO_TIMESTAMP_RE.test(n)}async appendWithRetry(e,n,r){await Mt(async()=>{try{await n.appendRows(r).getResult();}catch(s){throw this.onSchemaChange(e),s}});}async getOrCreateWriter(e,n){let r=this.writers.get(e);if(r)if(n&&r.primaryKey!==n)this.onSchemaChange(e);else return r.writer;let s=Ht();this.writerClient||(this.writerClient=new s.managedwriter.WriterClient({projectId:this.projectId}));let[o]=await this.dataset.table(e).getMetadata(),i={fields:o.schema?.fields??[]};n||(n=o.tableConstraints?.primaryKey?.columns?.[0]??i.fields[0]?.name);let u=s.adapt.convertBigQuerySchemaToStorageTableSchema(i),a=s.adapt.convertStorageSchemaToProto2Descriptor(u,"Row",s.adapt.withChangeType(),s.adapt.withChangeSequenceNumber()),f=new Set(i.fields.filter(C=>["TIMESTAMP","DATETIME","DATE"].includes(String(C.type??"").toUpperCase())).map(C=>C.name)),h=`projects/${this.projectId}/datasets/${this.datasetId}/tables/${e}`,y=await this.writerClient.createStreamConnection({streamId:s.managedwriter.DefaultStream,destinationTable:h}),O=new s.managedwriter.JSONWriter({connection:y,protoDescriptor:a});return this.writers.set(e,{writer:O,primaryKey:n??"",timestampColumns:f}),O}async close(){for(let{writer:e}of this.writers.values())try{e.close();}catch{}if(this.writers.clear(),this.writerClient&&typeof this.writerClient.close=="function")try{this.writerClient.close();}catch{}}};re.ISO_TIMESTAMP_RE=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/;var ve=re;var me=class me{constructor(e){this.buffer=[];this.flushing=false;this.lastFlushFailed=false;this.flushPromise=null;this.timer=null;this.flushedEvents=0;this.failedEvents=0;this.flushedBatches=0;this.failedBatches=0;this.errorSeq=0;this.recentErrors=[];this.adapter=e.adapter,this.tableName=e.tableName,this.primaryKey=e.primaryKey,this.batchSize=e.batchSize??100,this.onFlushError=e.onFlushError;let n=e.flushIntervalMs??5e3;n>0&&(this.timer=setInterval(()=>{this.flush().catch(r=>{console.error(`[SyncQueue] Scheduled flush failed for ${this.tableName}:`,r);});},n),typeof this.timer=="object"&&"unref"in this.timer&&this.timer.unref());}get size(){return this.buffer.length}getStats(){return {flushedEvents:this.flushedEvents,failedEvents:this.failedEvents,flushedBatches:this.flushedBatches,failedBatches:this.failedBatches,errorSeq:this.errorSeq,recentErrors:this.recentErrors.map(e=>({...e}))}}enqueue(...e){this.buffer.push(...e),this.buffer.length>=this.batchSize&&!this.flushing&&!this.lastFlushFailed&&this._autoFlush().catch(n=>{console.error(`[SyncQueue] Auto-flush failed for ${this.tableName}:`,n);});}async _autoFlush(){for(;this.flushPromise;)await this.flushPromise;this.buffer.length<this.batchSize||this.lastFlushFailed||(this.flushing=true,this.flushPromise=this._drain(true).finally(()=>{this.flushing=false,this.flushPromise=null;}),await this.flushPromise);}async flush(){for(;this.flushPromise;)await this.flushPromise;this.buffer.length!==0&&(this.flushing=true,this.flushPromise=this._drain(false).finally(()=>{this.flushing=false,this.flushPromise=null;}),await this.flushPromise);}async flushWithReport(){let e=this.getStats();await this.flush();let n=this.getStats();return {flushed:n.flushedEvents-e.flushedEvents,failed:n.failedEvents-e.failedEvents,errors:n.recentErrors.filter(r=>r.seq>e.errorSeq).map(r=>r.message)}}async _drain(e){try{for(;(e?this.buffer.length>=this.batchSize:this.buffer.length>0)&&await this._doFlush(););}finally{this.flushing=false;}}async _doFlush(){let e=this.buffer.splice(0,this.batchSize);if(e.length===0)return false;try{let n=new Map,r=[];for(let o of e)if(o.operation==="DELETE")r.push(o.docId),n.delete(o.docId);else if(o.data){let i=n.get(o.docId);if(!i)n.set(o.docId,o.data);else {let u=Number(i[W]??0);Number(o.data[W]??0)>=u&&n.set(o.docId,o.data);}}let s=Array.from(n.values());s.length>0&&(typeof this.adapter.upsert=="function"?await this.adapter.upsert(this.tableName,s,this.primaryKey):typeof this.adapter.upsertRows=="function"&&await this.adapter.upsertRows(this.tableName,s,this.primaryKey)),r.length>0&&(typeof this.adapter.delete=="function"?await this.adapter.delete(this.tableName,this.primaryKey,r):typeof this.adapter.deleteRows=="function"&&await this.adapter.deleteRows(this.tableName,this.primaryKey,r)),this.flushedEvents+=e.length,this.flushedBatches++,this.lastFlushFailed=!1;}catch(n){let r=n instanceof Error?n.message:String(n);if(this.failedEvents+=e.length,this.failedBatches++,this.errorSeq++,this.recentErrors.push({seq:this.errorSeq,message:r,count:e.length,timestamp:Date.now()}),this.recentErrors.length>me.MAX_RECENT_ERRORS&&this.recentErrors.shift(),this.onFlushError)await this.onFlushError(e,n);else return this.buffer.unshift(...e),this.lastFlushFailed=true,console.error(`[SyncQueue] Flush failed for ${this.tableName}:`,n),false}return true}async shutdown(){this.timer&&(clearInterval(this.timer),this.timer=null),await this.flush();}};me.MAX_RECENT_ERRORS=50;var ae=me;var Ze=new Set;async function Nt(t,e,n,r,s,o,i){let u=`${t}:${e.name}`;if(!Ze.has(u)){if(typeof e.ensureTarget=="function")await e.ensureTarget({targetName:r,primaryKey:s,schema:n,exclude:o,columnMap:i});else if("dialect"in e&&typeof e.createTable=="function"){let a=e,f=V(n,a.dialect,{primaryKey:s,exclude:o,columnMap:i});if(!await a.tableExists(r))await a.createTable({tableName:r,columns:f});else {let y=new Set(await a.getTableColumns(r)),O=f.filter(C=>!y.has(C.name));O.length>0&&(await a.addColumns(r,O),await a.onSchemaChange?.(r));}}Ze.add(u);}}function De(t,e){let{deps:n,adapter:r,adapters:s,batchSize:o=100,flushIntervalMs:i=5e3,autoMigrate:u=false,topicPrefix:a="firestore-sync",maxDlqAttempts:f=5,workerOptions:h,repos:y={}}=e,C=(s||(Array.isArray(r)?r:r?[r]:[])).map(P=>typeof P=="function"?P():P);function A(P){let l=y[P];if(l?.adapters&&l.adapters.length>0){let p=new Set(l.adapters);return C.filter(b=>p.has(b.name))}return C}let d=new Map;function H(P,l,p){let b=`${P}:${l.name}`,c=d.get(b);if(c)return c;let k=y[P]?.tableName??P,m=`${a}-${P}-${l.name}-dlq`,T=n.pubsub.topic(m),R=false,w=async()=>{if(!R){try{await T.create(),console.info(`[SyncWorker:${l.name}] Created DLQ topic "${m}"`);}catch($){if($?.code!==6)throw $}R=true;}},D=async($,L)=>{console.error(`[SyncWorker:${l.name}] Flush failed for "${P}" (${$.length} events):`,L),await w(),await Promise.all($.map(g=>{let S=(g.attempts??0)+1;if(f>0&&S>f)return console.error(`[SyncWorker:${l.name}] Dropping event for "${P}" after ${S-1} DLQ attempts:`,{docId:g.docId,operation:g.operation}),Promise.resolve();let M={...g,attempts:S,firstFailedAt:g.firstFailedAt??Date.now()};return T.publishMessage({json:M})}));};return c=new ae({adapter:l,tableName:k,primaryKey:p,batchSize:o,flushIntervalMs:i,onFlushError:D}),d.set(b,c),d.has(P)||d.set(P,c),c}async function N(P){let{repoName:l}=P,p=t[l];if(!p){console.warn(`[SyncWorker] Unknown repo "${l}", skipping event`);return}let b=p._systemKeys?.[0]??p.documentKey??"docId",c=y[l],x=c?.columnMap,k=x?.[b]??b;P.data&&(P.data[W]=P.version??Date.now());let m=A(l);for(let T of m){if(u){let w=p.schema??void 0;if(w){let D=c?.tableName??l;await Nt(l,T,w,D,k,c?.exclude,x);}}H(l,T,k).enqueue(P);}}function I(P){let l=async p=>{let b=p.data?.message?.json??p.data?.json;if(!b){console.warn("[SyncWorker] Received empty PubSub message");return}await N(b);let c=A(b.repoName);for(let x of c){let k=`${b.repoName}:${x.name}`,m=d.get(k);m&&await m.flush();}};return h?n.pubsubHandler.onMessagePublished({topic:P,...h},l):n.pubsubHandler.onMessagePublished(P,l)}return {handleMessage:N,createHandler:I,queues:d,async shutdown(){let P=[],l=new Set;for(let p of d.values())l.has(p)||(l.add(p),P.push(p.shutdown()));await Promise.all(P);}}}var _t="firestore-sync";function Je(t){if(typeof t!="function")return t;let e=t,n;return new Proxy({},{get(r,s){return n||(n=e()),n[s]},has(r,s){return n||(n=e()),s in n}})}function $t(t,e){let{deps:n,adapter:r,adapters:s,topicPrefix:o=_t,batchSize:i,flushIntervalMs:u,autoMigrate:a,admin:f,workerOptions:h,triggerOptions:y,repos:O}=e,C=Je(n.pubsub),d=(s||(Array.isArray(r)?r:r?[r]:[])).map(T=>Je(T)),H=Ce(t,{deps:{firestoreTriggers:n.firestoreTriggers,pubsub:C},topicPrefix:o,triggerOptions:y,repos:O}),N=De(t,{deps:{pubsubHandler:n.pubsubHandler,pubsub:C},adapters:d,batchSize:i,flushIntervalMs:u,autoMigrate:a,topicPrefix:o,workerOptions:h,repos:O}),I={},P=O,l=t?.rawMapping,p=Object.keys(P??{}),b=p.length>0,c=Object.keys(l||t),x=b?p.filter(T=>c.includes(T)||T in t):c;for(let T of x){let R=t?.rawMapping,w=R?!!R[T]?.isGroup:!!t[T]?._isGroup,D=R?R[T]?.path:t[T]?._collectionPath,$=typeof D=="string"&&D.includes("/");!b&&w&&!P?.[T]?.triggerPath&&!$||(I[`sync_${T}`]=N.createHandler(`${o}-${T}`));}let k=null;f&&(k=Ee(t,d,N.queues,N.handleMessage,f,O??{},C,o),I.adminsync=f.onRequest?f.httpsOptions?f.onRequest(f.httpsOptions,k):f.onRequest(k):k);let m={functions:{...H,...I},adminHandler:k,handleMessage:N.handleMessage,queues:N.queues,shutdown:N.shutdown};for(let T of ["adminHandler","handleMessage","queues","shutdown"])Object.defineProperty(m,T,{enumerable:false});return m}function Ye(t,e){let n=e.columns.map(r=>{let s=r.isPrimaryKey?" NOT NULL":"";return ` ${t.quoteIdentifier(r.name)} ${r.sqlType}${s}`}).join(`,
103
109
  `);return `CREATE TABLE IF NOT EXISTS ${t.quoteIdentifier(e.tableName)} (
104
110
  ${n}
105
- );`}function ht(t,e,n){return n.map(r=>`ALTER TABLE ${t.quoteIdentifier(e)} ADD COLUMN ${t.quoteIdentifier(r.name)} ${r.sqlType};`).join(`
106
- `)}function bt(t,e,n){let r=[];for(let[s,o]of Object.entries(t)){let i=o.schema??o._schema??void 0;if(!i)continue;let c=n?.repos?.[s],a=c?.tableName??s,y=o._systemKeys?.[0]??o.documentKey??"docId",b=B(i,e,{primaryKey:y,exclude:c?.exclude,columnMap:c?.columnMap}),g={tableName:a,columns:b};r.push(Be(e,g));}return r.join(`
111
+ );`}function Ft(t,e,n){return n.map(r=>`ALTER TABLE ${t.quoteIdentifier(e)} ADD COLUMN ${t.quoteIdentifier(r.name)} ${r.sqlType};`).join(`
112
+ `)}function jt(t,e,n){let r=[];for(let[s,o]of Object.entries(t)){let i=o.schema??o._schema??void 0;if(!i)continue;let u=n?.repos?.[s],a=u?.tableName??s,f=o._systemKeys?.[0]??o.documentKey??"docId",h=V(i,e,{primaryKey:f,exclude:u?.exclude,columnMap:u?.columnMap}),y={tableName:a,columns:h};r.push(Ye(e,y));}return r.join(`
107
113
 
108
- `)}async function wt(t,e,n){let r={created:[],altered:[],upToDate:[],skipped:[]};for(let[s,o]of Object.entries(t)){let i=o.schema??void 0;if(!i){r.skipped.push(s);continue}let c=n?.repos?.[s],a=c?.tableName??s,y=o._systemKeys?.[0]??o.documentKey??"docId",b=B(i,e.dialect,{primaryKey:y,exclude:c?.exclude,columnMap:c?.columnMap}),g={tableName:a,columns:b};if(!await e.tableExists(a))await e.createTable(g),r.created.push(a);else {let k=new Set(await e.getTableColumns(a)),x=b.filter(p=>!k.has(p.name));x.length>0?(await e.addColumns(a,x),r.altered.push(a)):r.upToDate.push(a);}}return r}function Tt(t){if(t.client)return t.client;if(!t.host)throw new Error("MeilisearchAdapter requires either a `client` instance or a `host` option.");try{let{MeiliSearch:e}=Te("meilisearch");return new e({host:t.host,apiKey:t.apiKey})}catch(e){throw new Error(`Failed to load the "meilisearch" package. Please install it with:
114
+ `)}async function Bt(t,e,n){let r={created:[],altered:[],upToDate:[],skipped:[]};for(let[s,o]of Object.entries(t)){let i=o.schema??void 0;if(!i){r.skipped.push(s);continue}let u=n?.repos?.[s],a=u?.tableName??s,f=o._systemKeys?.[0]??o.documentKey??"docId",h=V(i,e.dialect,{primaryKey:f,exclude:u?.exclude,columnMap:u?.columnMap}),y={tableName:a,columns:h};if(!await e.tableExists(a))await e.createTable(y),r.created.push(a);else {let C=new Set(await e.getTableColumns(a)),A=h.filter(d=>!C.has(d.name));A.length>0?(await e.addColumns(a,A),r.altered.push(a)):r.upToDate.push(a);}}return r}function Lt(t){if(t.client)return t.client;if(!t.host)throw new Error("MeilisearchAdapter requires either a `client` instance or a `host` option.");try{let{MeiliSearch:e}=He("meilisearch");return new e({host:t.host,apiKey:t.apiKey})}catch(e){throw new Error(`Failed to load the "meilisearch" package. Please install it with:
109
115
  bun add meilisearch # or npm install meilisearch
110
- Original error: ${e?.message??String(e)}`)}}function St(t,e){if(!t||!e)return false;for(let[n,r]of Object.entries(e)){if(r===void 0)continue;let s=t[n];if(Array.isArray(r)){if(!Array.isArray(s)||r.length!==s.length)return false;for(let o=0;o<r.length;o++)if(r[o]!==s[o])return false}else if(typeof r=="object"&&r!==null){if(JSON.stringify(r)!==JSON.stringify(s))return false}else if(r!==s)return false}return true}var oe=class{constructor(e){this.name="meilisearch";this._client=null;this.options=e,e.client&&(this._client=e.client);}get indexesSettings(){return this.options.indexesSettings}get client(){return this._client||(this._client=Tt(this.options)),this._client}async targetExists(e){try{return await this.client.getIndex(e),!0}catch(n){if(n?.code==="index_not_found"||n?.cause?.code==="index_not_found"||n?.statusCode===404||n?.status===404||n?.response?.status===404||n?.cause?.status===404||n?.cause?.statusCode===404||n?.cause?.response?.status===404)return false;throw n}}async upsert(e,n,r){if(n.length===0)return;let s=this.options.unflatten!==false,o=n.map(c=>{let a=s?pe(c):c;return typeof this.options.transformDoc=="function"&&(a=this.options.transformDoc(a)),a});await this.client.index(e).addDocuments(o,{primaryKey:r});}async delete(e,n,r){if(r.length===0)return;await this.client.index(e).deleteDocuments(r);}async ensureTarget(e){let{targetName:n,primaryKey:r}=e;await this.targetExists(n)||await this.client.createIndex(n,{primaryKey:r});let o=this.options.indexesSettings?.[n];if(o){let{retrievableAttributes:i,attributesToRetrieve:c,...a}=o,y={...a,displayedAttributes:a.displayedAttributes??i??c};y.displayedAttributes===void 0&&delete y.displayedAttributes;let b=this.client.index(n);if(typeof b.getSettings=="function")try{let g=await b.getSettings();if(St(g,y))return}catch{}await b.updateSettings(y);}}async healthCheck(e){let{targetName:n}=e;try{if(!await this.targetExists(n))return {healthy:!1,targetName:n,targetExists:!1,error:`Meilisearch index "${n}" does not exist`};let s=this.client.index(n),o=await s.getStats(),i=typeof s.getRawInfo=="function"?await s.getRawInfo():{};return {healthy:!0,targetName:n,targetExists:!0,error:null,details:{numberOfDocuments:o?.numberOfDocuments??0,isIndexing:o?.isIndexing??!1,fieldDistribution:o?.fieldDistribution??{},primaryKey:i?.primaryKey??e.primaryKey}}}catch(r){return {healthy:false,targetName:n,targetExists:false,error:r?.message??String(r)}}}async checkConnection(){try{let e=!0;if(typeof this.client.isHealthy=="function"){let r=await this.client.isHealthy();e=r?.status==="available"||r===!0;}else if(typeof this.client.health=="function"){let r=await this.client.health();e=r?.status==="available"||r===!0;}let n;return typeof this.client.getVersion=="function"&&(n=(await this.client.getVersion())?.pkgVersion),{healthy:e,version:n}}catch(e){return {healthy:false,error:e?.message??String(e)}}}};function xt(t){return ()=>new oe(t)}exports.BigQueryAdapter=be;exports.MeilisearchAdapter=oe;exports.SchemaTypeMismatchError=V;exports.SyncQueue=Z;exports.addColumnsDDL=ht;exports.autoMigrate=wt;exports.bigqueryDialect=$e;exports.createFirestoreSync=gt;exports.createSyncTriggers=me;exports.createSyncWorker=we;exports.createTableDDL=Be;exports.createadminsyncServer=ye;exports.defineMeilisearchAdapter=xt;exports.generateDDL=bt;exports.serializeDocument=U;exports.serializeValue=ee;exports.unflattenDocument=pe;exports.zodSchemaToColumns=B;exports.zodTypeToLogical=lt;//# sourceMappingURL=index.cjs.map
116
+ Original error: ${e?.message??String(e)}`)}}function zt(t,e){if(!t||!e)return false;for(let[n,r]of Object.entries(e)){if(r===void 0)continue;let s=t[n];if(Array.isArray(r)){if(!Array.isArray(s)||r.length!==s.length)return false;for(let o=0;o<r.length;o++)if(r[o]!==s[o])return false}else if(typeof r=="object"&&r!==null){if(JSON.stringify(r)!==JSON.stringify(s))return false}else if(r!==s)return false}return true}var ge=class{constructor(e){this.name="meilisearch";this._client=null;this.options=e,e.client&&(this._client=e.client);}get indexesSettings(){return this.options.indexesSettings}get client(){return this._client||(this._client=Lt(this.options)),this._client}async targetExists(e){try{return await this.client.getIndex(e),!0}catch(n){if(n?.code==="index_not_found"||n?.cause?.code==="index_not_found"||n?.statusCode===404||n?.status===404||n?.response?.status===404||n?.cause?.status===404||n?.cause?.statusCode===404||n?.cause?.response?.status===404)return false;throw n}}async upsert(e,n,r){if(n.length===0)return;let s=this.options.unflatten!==false,o=n.map(u=>{let a=s?Ae(u):u;return typeof this.options.transformDoc=="function"&&(a=this.options.transformDoc(a)),a});await this.client.index(e).addDocuments(o,{primaryKey:r});}async delete(e,n,r){if(r.length===0)return;await this.client.index(e).deleteDocuments(r);}async ensureTarget(e){let{targetName:n,primaryKey:r}=e;await this.targetExists(n)||await this.client.createIndex(n,{primaryKey:r});let o=this.options.indexesSettings?.[n];if(o){let{retrievableAttributes:i,attributesToRetrieve:u,...a}=o,f={...a,displayedAttributes:a.displayedAttributes??i??u};f.displayedAttributes===void 0&&delete f.displayedAttributes;let h=this.client.index(n);if(typeof h.getSettings=="function")try{let y=await h.getSettings();if(zt(y,f))return}catch{}await h.updateSettings(f);}}async healthCheck(e){let{targetName:n}=e;try{if(!await this.targetExists(n))return {healthy:!1,targetName:n,targetExists:!1,error:`Meilisearch index "${n}" does not exist`};let s=this.client.index(n),o=await s.getStats(),i=typeof s.getRawInfo=="function"?await s.getRawInfo():{};return {healthy:!0,targetName:n,targetExists:!0,error:null,details:{numberOfDocuments:o?.numberOfDocuments??0,isIndexing:o?.isIndexing??!1,fieldDistribution:o?.fieldDistribution??{},primaryKey:i?.primaryKey??e.primaryKey}}}catch(r){return {healthy:false,targetName:n,targetExists:false,error:r?.message??String(r)}}}async checkConnection(){try{let e=!0;if(typeof this.client.isHealthy=="function"){let r=await this.client.isHealthy();e=r?.status==="available"||r===!0;}else if(typeof this.client.health=="function"){let r=await this.client.health();e=r?.status==="available"||r===!0;}let n;return typeof this.client.getVersion=="function"&&(n=(await this.client.getVersion())?.pkgVersion),{healthy:e,version:n}}catch(e){return {healthy:false,error:e?.message??String(e)}}}};function qt(t){return ()=>new ge(t)}exports.BigQueryAdapter=ve;exports.MeilisearchAdapter=ge;exports.SchemaTypeMismatchError=ie;exports.SyncQueue=ae;exports.addColumnsDDL=Ft;exports.autoMigrate=Bt;exports.bigqueryDialect=Ge;exports.createFirestoreSync=$t;exports.createSyncTriggers=Ce;exports.createSyncWorker=De;exports.createTableDDL=Ye;exports.createadminsyncServer=Ee;exports.defineMeilisearchAdapter=qt;exports.generateDDL=jt;exports.serializeDocument=te;exports.serializeValue=de;exports.unflattenDocument=Ae;exports.zodSchemaToColumns=V;exports.zodTypeToLogical=Dt;//# sourceMappingURL=index.cjs.map
111
117
  //# sourceMappingURL=index.cjs.map