@lpdjs/firestore-repo-service 2.6.57 → 3.0.1

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 (64) hide show
  1. package/README.md +45 -27
  2. package/dist/{create-servers-BxkVVkg9.d.cts → create-servers-Cbvzs_ou.d.cts} +5 -5
  3. package/dist/{create-servers-B84cbslf.d.ts → create-servers-aWdDTcSu.d.ts} +5 -5
  4. package/dist/{firebase-auth-DZ8lb2Ec.d.cts → firebase-auth-Ds5P0kXT.d.cts} +1 -1
  5. package/dist/{firebase-auth-DZ8lb2Ec.d.ts → firebase-auth-Ds5P0kXT.d.ts} +1 -1
  6. package/dist/index.cjs +97 -85
  7. package/dist/index.cjs.map +1 -1
  8. package/dist/index.d.cts +9 -9
  9. package/dist/index.d.ts +9 -9
  10. package/dist/index.js +97 -85
  11. package/dist/index.js.map +1 -1
  12. package/dist/llms-full.txt +237 -263
  13. package/dist/llms.txt +5 -4
  14. package/dist/{openapi-BpbfjSHK.d.ts → openapi-BTu_1vSc.d.ts} +1 -1
  15. package/dist/{openapi-DG7aQUlX.d.cts → openapi-CoKsSOIU.d.cts} +1 -1
  16. package/dist/{queue-B4uwef6c.d.ts → queue-BQxyuEXb.d.ts} +8 -23
  17. package/dist/{queue-CQyWCQBk.d.cts → queue-CMiKvIW1.d.cts} +8 -23
  18. package/dist/rules-B3b-BZLf.d.cts +30 -0
  19. package/dist/rules-BJMT0N0i.d.ts +30 -0
  20. package/dist/servers/admin/index.d.cts +402 -6
  21. package/dist/servers/admin/index.d.ts +402 -6
  22. package/dist/servers/auth/index.d.cts +1 -1
  23. package/dist/servers/auth/index.d.ts +1 -1
  24. package/dist/servers/crud/index.cjs +2 -2
  25. package/dist/servers/crud/index.cjs.map +1 -1
  26. package/dist/servers/crud/index.d.cts +7 -6
  27. package/dist/servers/crud/index.d.ts +7 -6
  28. package/dist/servers/crud/index.js +2 -2
  29. package/dist/servers/crud/index.js.map +1 -1
  30. package/dist/servers/hono/index.d.cts +3 -3
  31. package/dist/servers/hono/index.d.ts +3 -3
  32. package/dist/servers/index.cjs +106 -94
  33. package/dist/servers/index.cjs.map +1 -1
  34. package/dist/servers/index.d.cts +10 -9
  35. package/dist/servers/index.d.ts +10 -9
  36. package/dist/servers/index.js +106 -94
  37. package/dist/servers/index.js.map +1 -1
  38. package/dist/sync/bigquery.cjs +5 -5
  39. package/dist/sync/bigquery.cjs.map +1 -1
  40. package/dist/sync/bigquery.d.cts +28 -3
  41. package/dist/sync/bigquery.d.ts +28 -3
  42. package/dist/sync/bigquery.js +5 -5
  43. package/dist/sync/bigquery.js.map +1 -1
  44. package/dist/sync/index.cjs +74 -54
  45. package/dist/sync/index.cjs.map +1 -1
  46. package/dist/sync/index.d.cts +63 -17
  47. package/dist/sync/index.d.ts +63 -17
  48. package/dist/sync/index.js +74 -54
  49. package/dist/sync/index.js.map +1 -1
  50. package/dist/sync/meilisearch.cjs +4 -0
  51. package/dist/sync/meilisearch.cjs.map +1 -0
  52. package/dist/sync/meilisearch.d.cts +114 -0
  53. package/dist/sync/meilisearch.d.ts +114 -0
  54. package/dist/sync/meilisearch.js +4 -0
  55. package/dist/sync/meilisearch.js.map +1 -0
  56. package/dist/{types-CE-EfugW.d.cts → types-B2e-T8EM.d.cts} +160 -8
  57. package/dist/{types-B4dMmfet.d.cts → types-BIZz3sxN.d.cts} +1 -1
  58. package/dist/{types-DT7Nypd_.d.ts → types-BbFZ57eK.d.ts} +101 -41
  59. package/dist/{types-DyKJJ9UQ.d.ts → types-DSMiiOrU.d.ts} +1 -1
  60. package/dist/{types-cY03CMya.d.ts → types-XRjVKN9r.d.ts} +160 -8
  61. package/dist/{types-BwH1C-wi.d.cts → types-zFrp8RnM.d.cts} +101 -41
  62. package/package.json +19 -1
  63. package/dist/index-D47y5giY.d.ts +0 -469
  64. package/dist/index-dW_7jrlK.d.cts +0 -469
@@ -1,7 +1,7 @@
1
- 'use strict';require('firebase-admin/firestore'),require('crypto');function ue(t){let e=[],n=t.replace(/[.*+?^${}()|[\]\\]/g,r=>r===":"?r:`\\${r}`).replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,(r,i)=>(e.push(i),"([^/]+)"));return {pattern:new RegExp(`^${n}$`),paramNames:e}}function le(t){let e=t.path??t.url??"/",n=e.indexOf("?");return n===-1?e:e.slice(0,n)}var L=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:i,paramNames:u}=ue(n);return this.routes.push({method:e.toUpperCase(),pattern:i,paramNames:u,handler:r}),this}async handle(e,n){let r=(e.method??"GET").toUpperCase(),i=le(e),u=null,a={};for(let T of this.routes){if(T.method!==r)continue;let k=i.match(T.pattern);if(k){u=T,a={},T.paramNames.forEach((w,A)=>{a[w]=decodeURIComponent(k[A+1]??"");});break}}let b=Object.assign(e,{params:a}),f=u?u.handler:this.notFoundHandler;try{await this.runMiddlewareChain(b,n,f);}catch(T){this.errorHandler(T,e,n);}}async runMiddlewareChain(e,n,r){let i=0,u=async()=>{if(i<this.middlewares.length){let a=this.middlewares[i++];await a(e,n,u);}else await r(e,n);};await u();}};function I(t,e,n){let r=e==="/"?"":e.replace(/\/$/,"");if(process.env.FUNCTIONS_EMULATOR==="true"){let a=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??"demo-project",b=process.env.FUNCTION_REGION??"us-central1",f=(process.env.FUNCTION_TARGET??"").replace(/\./g,"-");return `/${a}/${b}/${f}${r}`}let i=process.env.K_SERVICE,u=t?.hostname??t?.headers?.host??"";return i&&typeof u=="string"&&u.includes("cloudfunctions.net")?`/${i.toLowerCase()}${r}`:r}function W(t){return !!t&&typeof t=="object"&&t.__authExtension===true}function ye(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(i=>i.trim().replace(/\s*[:=].*$/,"").trim()).filter(Boolean);return r.length<=2?[]:r.slice(1,-1)}function me(t){let e=[t?.documentKey,t?.pathKey,t?.createdKey,t?.updatedKey].filter(r=>typeof r=="string"),n=t?.history&&typeof t.history=="object"?t.history:void 0;return {schema:t?.schema,_systemKeys:e,_pathKey:t?.pathKey??null,_isGroup:!!t?.isGroup,_createdKey:t?.createdKey??null,_parentKeys:t?.isGroup?ye(t?.refCb):[],relationalKeys:t?.relationalKeys,_historyConfig:n,_historySubcollection:n?.enabled?n.subcollection??"history":void 0,_collectionPath:typeof t?.path=="string"?t.path:null}}function Y(t,e){let n=me(t),r,i=()=>{let u=r??(r=e());if(!u){let a=n._collectionPath||"unknown";throw new Error(`[makeLazyRepo] Failed to resolve repository for path "${a}". The repository mapping resolved to undefined. This almost always indicates a circular import where the repository was exported as undefined.`)}return u};return new Proxy(n,{get(u,a){return typeof a=="string"&&a in n?n[a]:i()[a]},has(u,a){return typeof a=="string"&&a in n?true:a in i()}})}var ge={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 Q(t){let e=t,n=e._zod?.def?.type;if(n)return ge[n]??`Zod${n.charAt(0).toUpperCase()}${n.slice(1)}`;let r=e._def?.typeName;return r||""}function X(t){let e=t;if(e._zod?.def?.innerType)return e._zod.def.innerType;if(e._def?.innerType)return e._def.innerType}function K(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 H="__sync_version";var he=new Set(["ZodOptional","ZodNullable","ZodDefault"]);function ee(t){let e=t,n=false;for(;;){let r=Q(e);if(!he.has(r))break;(r==="ZodOptional"||r==="ZodNullable")&&(n=true);let i=X(e);if(!i)break;e=i;}return {inner:e,nullable:n}}var te={ZodString:"string",ZodNumber:"number",ZodBigInt:"bigint",ZodBoolean:"boolean",ZodDate:"timestamp",ZodEnum:"string",ZodNativeEnum:"string",ZodLiteral:"string"};function be(t){let{inner:e}=ee(t);return te[Q(e)]??"json"}function ne(t,e,n,r,i,u,a,b){for(let[f,T]of Object.entries(t)){let k=n?`${n}__${f}`:f;if(i.has(f)||i.has(k))continue;let{inner:w,nullable:A}=ee(T),s=Q(w),l=r||A;if(s==="ZodObject"){let S=K(w);ne(S,e,k,l,i,u,a,b);continue}let c=te[s]??"json",o=k===a||f===a,p=u[k]??u[f]??k;b.push({name:p,sqlType:e.mapType(c),nullable:o?false:l,isPrimaryKey:o});}}function $(t,e,n={}){let{primaryKey:r,exclude:i=[],columnMap:u={}}=n,a=new Set(i),b=K(t),f=[];return ne(b,e,"",false,a,u,r,f),f.some(T=>T.name===H)||f.push({name:H,sqlType:e.mapType("bigint"),nullable:true,isPrimaryKey:false,description:"Monotonic publish version (Date.now() ms). Internal."}),f}function q(t){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 e=t;return JSON.stringify({lat:e.latitude,lng:e.longitude})}return Array.isArray(t)?JSON.stringify(t.map(q)):t}var we=32,Te=5e3;function re(t,e,n,r=new WeakSet,i=0){if(i>we){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[u,a]of Object.entries(t)){if(Object.keys(n).length>=Te)break;let b=e?`${e}__${u}`:u;a!=null&&typeof a=="object"&&!Array.isArray(a)&&!(a instanceof Date)&&!Buffer.isBuffer(a)&&!(a instanceof Uint8Array)&&typeof a.toDate!="function"&&!("latitude"in a&&"longitude"in a)?re(a,b,n,r,i+1):n[b]=q(a);}r.delete(t);}function N(t,e){let n=new Set(e?.exclude),r=e?.columnMap??{},i={};re(t,"",i);let u={};for(let[a,b]of Object.entries(i)){if(n.has(a))continue;let f=a.split("__")[0];if(f!==a&&n.has(f))continue;let T=r[a]??(a.includes("__")?r[a.split("__").pop()]:void 0)??a;u[T]=b;}return u}function _(t,e,n){return `<!DOCTYPE html>
1
+ 'use strict';require('firebase-admin/firestore'),require('crypto');var ie=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});function xe(n){let e=[],t=n.replace(/[.*+?^${}()|[\]\\]/g,r=>r===":"?r:`\\${r}`).replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,(r,s)=>(e.push(s),"([^/]+)"));return {pattern:new RegExp(`^${t}$`),paramNames:e}}function Re(n){let e=n.path??n.url??"/",t=e.indexOf("?");return t===-1?e:e.slice(0,t)}var K=class{constructor(){this.routes=[];this.middlewares=[];this.notFoundHandler=(e,t)=>{t.status(404).send("Not Found");};this.errorHandler=(e,t,r)=>{console.error("[MiniRouter]",e),r.status(500).send("Internal Server Error");};}use(e){return this.middlewares.push(e),this}get(e,t){return this.addRoute("GET",e,t)}post(e,t){return this.addRoute("POST",e,t)}put(e,t){return this.addRoute("PUT",e,t)}patch(e,t){return this.addRoute("PATCH",e,t)}delete(e,t){return this.addRoute("DELETE",e,t)}onNotFound(e){return this.notFoundHandler=e,this}onError(e){return this.errorHandler=e,this}addRoute(e,t,r){let{pattern:s,paramNames:o}=xe(t);return this.routes.push({method:e.toUpperCase(),pattern:s,paramNames:o,handler:r}),this}async handle(e,t){let r=(e.method??"GET").toUpperCase(),s=Re(e),o=null,i={};for(let g of this.routes){if(g.method!==r)continue;let C=s.match(g.pattern);if(C){o=g,i={},g.paramNames.forEach((y,w)=>{i[y]=decodeURIComponent(C[w+1]??"");});break}}let m=Object.assign(e,{params:i}),c=o?o.handler:this.notFoundHandler;try{await this.runMiddlewareChain(m,t,c);}catch(g){this.errorHandler(g,e,t);}}async runMiddlewareChain(e,t,r){let s=0,o=async()=>{if(s<this.middlewares.length){let i=this.middlewares[s++];await i(e,t,o);}else await r(e,t);};await o();}};function H(n,e,t){let r=e==="/"?"":e.replace(/\/$/,"");if(process.env.FUNCTIONS_EMULATOR==="true"){let i=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??"demo-project",m=process.env.FUNCTION_REGION??"us-central1",c=(process.env.FUNCTION_TARGET??"").replace(/\./g,"-");return `/${i}/${m}/${c}${r}`}let s=process.env.K_SERVICE,o=n?.hostname??n?.headers?.host??"";return s&&typeof o=="string"&&o.includes("cloudfunctions.net")?`/${s.toLowerCase()}${r}`:r}function J(n){return !!n&&typeof n=="object"&&n.__authExtension===true}function Ee(n){if(typeof n!="function")return [];let t=n.toString().match(/^\s*(?:function\s*\w*\s*)?\(([^)]*)\)/);if(!t?.[1])return [];let r=t[1].split(",").map(s=>s.trim().replace(/\s*[:=].*$/,"").trim()).filter(Boolean);return r.length<=2?[]:r.slice(1,-1)}function Pe(n){let e=[n?.documentKey,n?.pathKey,n?.createdKey,n?.updatedKey].filter(r=>typeof r=="string"),t=n?.history&&typeof n.history=="object"?n.history:void 0;return {schema:n?.schema,_systemKeys:e,_pathKey:n?.pathKey??null,_isGroup:!!n?.isGroup,_createdKey:n?.createdKey??null,_parentKeys:n?.isGroup?Ee(n?.refCb):[],relationalKeys:n?.relationalKeys,_historyConfig:t,_historySubcollection:t?.enabled?t.subcollection??"history":void 0,_collectionPath:typeof n?.path=="string"?n.path:null}}function ue(n,e){let t=Pe(n),r,s=()=>{let o=r??(r=e());if(!o){let i=t._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(t,{get(o,i){return typeof i=="string"&&i in t?t[i]:s()[i]},has(o,i){return typeof i=="string"&&i in t?true:i in s()}})}function Y(n){if(n==null)return null;if(typeof n=="object"&&typeof n.toDate=="function")return n.toDate().toISOString();if(n instanceof Date)return n.toISOString();if(Buffer.isBuffer(n))return n.toString("base64");if(n instanceof Uint8Array)return Buffer.from(n).toString("base64");if(typeof n=="object"&&"latitude"in n&&"longitude"in n){let e=n;return JSON.stringify({lat:e.latitude,lng:e.longitude})}return Array.isArray(n)?JSON.stringify(n.map(Y)):n}var Oe=32,ve=5e3;function le(n,e,t,r=new WeakSet,s=0){if(s>Oe){t[e||"_truncated"]=JSON.stringify({__truncated:true});return}if(r.has(n)){t[e||"_cycle"]=JSON.stringify({__cycle:true});return}r.add(n);for(let[o,i]of Object.entries(n)){if(Object.keys(t).length>=ve)break;let m=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)?le(i,m,t,r,s+1):t[m]=Y(i);}r.delete(n);}function F(n,e){let t=new Set(e?.exclude),r=e?.columnMap??{},s={};le(n,"",s);let o={};for(let[i,m]of Object.entries(s)){if(t.has(i))continue;let c=i.split("__")[0];if(c!==i&&t.has(c))continue;let g=r[i]??(i.includes("__")?r[i.split("__").pop()]:void 0)??i;o[g]=m;}return o}function j(n,e,t){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>${n} \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}
@@ -26,66 +26,86 @@
26
26
  </style>
27
27
  </head><body>
28
28
  <nav><a href="${e}/">\u2190 Dashboard</a></nav>
29
- <h1>${t}</h1>
30
- ${n}
31
- </body></html>`}function M(t,e,n=200){t.status(n).set("Content-Type","text/html; charset=utf-8").send(e);}function j(t,e,n=200){t.status(n).set("Content-Type","application/json").send(JSON.stringify(e,null,2));}function Z(t){return (t.headers?.accept??"").includes("application/json")}function Se(t,e,n,r,i,u,a,b){let f=(i.basePath??"/").replace(/\/$/,"")||"",T=i.featuresFlag??{},k=t?.rawMapping,w=[];for(let s of Object.keys(t)){let l=u[s],c=k?Y(k[s],()=>t[s]):t[s];w.push({name:s,schema:c.schema??null,documentKey:c._systemKeys?.[0]??c.documentKey??"docId",tableName:l?.tableName??s,isGroup:!!c._isGroup,repoCfg:l,repo:c});}let A=new L;if(i.auth)if(W(i.auth)){let s=i.auth;for(let l of s.routes){let c=`${f}${l.path}`;l.method==="GET"?A.get(c,l.handler):A.post(c,l.handler);}A.use(s.middleware);}else if(typeof i.auth=="function")A.use(i.auth);else {let s=i.auth.realm??"Sync Admin",l="Basic "+Buffer.from(`${i.auth.username}:${i.auth.password}`).toString("base64");A.use((c,o,p)=>{if((c.headers?.authorization??"")!==l){o.status(401).set("WWW-Authenticate",`Basic realm="${s}"`).set("Content-Type","text/plain").send("Unauthorized");return}p();});}return A.get(`${f}/`,(s,l)=>{let c=I(s,f),o=w.map(d=>{let h=[];return T.healthCheck&&h.push(`<a class="btn" href="${c}/${d.name}/health">Health</a>`),T.manualSync&&h.push(`<a class="btn btn-primary" href="${c}/${d.name}/force-sync">Force Sync</a>`),`<tr>
32
- <td><strong>${d.name}</strong></td>
33
- <td>${d.tableName}</td>
34
- <td>${d.isGroup?'<span class="badge badge-warn">group</span>':'<span class="badge badge-ok">collection</span>'}</td>
35
- <td>${d.schema?"\u2713":"\u2717"}</td>
36
- <td>${h.join(" ")}</td>
29
+ <h1>${n}</h1>
30
+ ${t}
31
+ </body></html>`}function z(n,e,t=200){n.status(t).set("Content-Type","text/html; charset=utf-8").send(e);}function L(n,e,t=200){n.status(t).set("Content-Type","application/json").send(JSON.stringify(e,null,2));}function U(n){return (n.headers?.accept??"").includes("application/json")}function X(n,e,t,r,s,o,i,m){let c=(s.basePath??"/").replace(/\/$/,"")||"",g=s.featuresFlag??{},C=Array.isArray(e)?e:[e],y=n?.rawMapping,w=[];for(let p of Object.keys(n)){let u=o[p],S=y?ue(y[p],()=>n[p]):n[p],l=u?.adapters&&u.adapters.length>0?C.filter(x=>u.adapters.includes(x.name)):C;w.push({name:p,schema:S.schema??null,documentKey:S._systemKeys?.[0]??S.documentKey??"docId",tableName:u?.tableName??p,isGroup:!!S._isGroup,repoCfg:u,repo:S,adapters:l});}let k=new K;if(s.auth)if(J(s.auth)){let p=s.auth;for(let u of p.routes){let S=`${c}${u.path}`;u.method==="GET"?k.get(S,u.handler):k.post(S,u.handler);}k.use(p.middleware);}else if(typeof s.auth=="function")k.use(s.auth);else {let p=s.auth.realm??"Sync Admin",u="Basic "+Buffer.from(`${s.auth.username}:${s.auth.password}`).toString("base64");k.use((S,l,x)=>{if((S.headers?.authorization??"")!==u){l.status(401).set("WWW-Authenticate",`Basic realm="${p}"`).set("Content-Type","text/plain").send("Unauthorized");return}x();});}return k.get(`${c}/`,(p,u)=>{let S=H(p,c),l=w.map(a=>{let A=[];g.healthCheck&&A.push(`<a class="btn" href="${S}/${a.name}/health">Health</a>`),g.manualSync&&A.push(`<a class="btn btn-primary" href="${S}/${a.name}/force-sync">Force Sync</a>`);let h=a.adapters.map(R=>`<span class="badge badge-ok">${R.name}</span>`).join(" ");return `<tr>
32
+ <td><strong>${a.name}</strong></td>
33
+ <td>${a.tableName}</td>
34
+ <td>${h||'<span class="badge badge-warn">none</span>'}</td>
35
+ <td>${a.isGroup?'<span class="badge badge-warn">group</span>':'<span class="badge badge-ok">collection</span>'}</td>
36
+ <td>${a.schema?"\u2713":"\u2717"}</td>
37
+ <td>${A.join(" ")}</td>
37
38
  </tr>`}).join(`
38
- `),p=T.configCheck?`<p style="margin-top:.5rem"><a class="btn" href="${c}/config-check">\u2699 Config Check</a></p>`:"",S=_("Sync Dashboard",c,`<div class="card">
39
+ `),x=g.configCheck?`<p style="margin-top:.5rem"><a class="btn" href="${S}/config-check">\u2699 Config Check</a></p>`:"",f=j("Sync Dashboard",S,`<div class="card">
39
40
  <table>
40
- <thead><tr><th>Repository</th><th>Table</th><th>Type</th><th>Schema</th><th>Actions</th></tr></thead>
41
- <tbody>${o}</tbody>
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>${l}</tbody>
42
43
  </table>
43
- ${p}
44
- </div>`);M(l,S);}),A.get(`${f}`,(s,l)=>{let c=I(s,f);l.status(302).set("Location",`${c}/`).send("");}),T.healthCheck&&A.get(`${f}/:repoName/health`,async(s,l)=>{let c=I(s,f),o=w.find(m=>m.name===s.params.repoName);if(!o){M(l,_("Not Found",c,`<p>Unknown repo: ${s.params.repoName}</p>`),404);return}if(!o.schema){M(l,_("Health Check",c,`<p class="badge badge-warn">No Zod schema attached to "${o.name}"</p>`));return}let p=$(o.schema,e.dialect,{primaryKey:o.documentKey,exclude:o.repoCfg?.exclude,columnMap:o.repoCfg?.columnMap}),S=[],d=false,h=null;try{d=await e.tableExists(o.tableName),d&&(S=await e.getTableColumns(o.tableName));}catch(m){h=m?.message??String(m);}let C=new Set(S),E=new Set(p.map(m=>m.name)),O=p.filter(m=>!C.has(m.name)),P=S.filter(m=>!E.has(m)),v=p.filter(m=>C.has(m.name)),y=d&&O.length===0&&!h;if(Z(s)){j(l,{repo:o.name,table:o.tableName,tableExists:d,healthy:y,error:h,columns:{expected:p.map(m=>({name:m.name,type:m.sqlType,nullable:m.nullable,isPrimaryKey:m.isPrimaryKey})),actual:S,matched:v.map(m=>m.name),missing:O.map(m=>({name:m.name,type:m.sqlType})),extra:P}});return}let g=y?'<span class="badge badge-ok">Healthy</span>':'<span class="badge badge-err">Unhealthy</span>',x=p.map(m=>{let z=C.has(m.name)?'<span class="badge badge-ok">OK</span>':'<span class="badge badge-err">MISSING</span>';return `<tr><td>${m.name}</td><td>${m.sqlType}</td><td>${m.nullable?"Yes":"No"}</td><td>${m.isPrimaryKey?"\u2713":""}</td><td>${z}</td></tr>`}).join(`
45
- `),R=P.map(m=>`<tr><td>${m}</td><td colspan="3" class="muted">not in schema</td><td><span class="badge badge-warn">EXTRA</span></td></tr>`).join(`
46
- `),D=_(`Health: ${o.name}`,c,`<div class="card">
47
- <p>Table: <code>${o.tableName}</code> ${d?g:'<span class="badge badge-err">NOT FOUND</span>'}</p>
48
- ${h?`<p class="badge badge-err">Error: ${h}</p>`:""}
49
- <h2>Columns</h2>
50
- <table>
51
- <thead><tr><th>Column</th><th>SQL Type</th><th>Nullable</th><th>PK</th><th>Status</th></tr></thead>
52
- <tbody>${x}${R}</tbody>
53
- </table>
54
- </div>`);M(l,D);}),T.manualSync&&(A.get(`${f}/:repoName/force-sync`,(s,l)=>{let c=I(s,f),o=w.find(S=>S.name===s.params.repoName);if(!o){M(l,_("Not Found",c,`<p>Unknown repo: ${s.params.repoName}</p>`),404);return}let p=_(`Force Sync: ${o.name}`,c,`<div class="card">
55
- <p>This will read <strong>all</strong> documents from the <code>${o.name}</code> Firestore collection
56
- and upsert them into the <code>${o.tableName}</code> SQL table.</p>
44
+ ${x}
45
+ </div>`);z(u,f);}),k.get(`${c}`,(p,u)=>{let S=H(p,c);u.status(302).set("Location",`${S}/`).send("");}),g.healthCheck&&k.get(`${c}/:repoName/health`,async(p,u)=>{let S=H(p,c),l=w.find(h=>h.name===p.params.repoName);if(!l){z(u,j("Not Found",S,`<p>Unknown repo: ${p.params.repoName}</p>`),404);return}let x=[];for(let h of l.adapters)if(typeof h.healthCheck=="function"){let R=await h.healthCheck({targetName:l.tableName,primaryKey:l.documentKey,schema:l.schema??void 0,repoConfig:l.repoCfg});x.push({adapterName:h.name,health:R});}else try{let R=await h.targetExists(l.tableName);x.push({adapterName:h.name,health:{healthy:R,targetName:l.tableName,targetExists:R,error:R?null:`Target "${l.tableName}" does not exist`}});}catch(R){x.push({adapterName:h.name,health:{healthy:false,targetName:l.tableName,targetExists:false,error:R?.message??String(R)}});}let f=x.length>0&&x.every(h=>h.health.healthy);if(U(p)){L(u,{repo:l.name,targetName:l.tableName,healthy:f,adapters:x.map(h=>({name:h.adapterName,...h.health}))});return}let a=h=>{let{adapterName:R,health:P}=h,D=P.healthy?'<span class="badge badge-ok">Healthy</span>':'<span class="badge badge-err">Unhealthy</span>',$="",d=P.details;if(d?.expected&&Array.isArray(d.expected)){let b=d.expected,E=new Set(d.actual??[]),T=d.extra??[],O=b.map(v=>{let _=E.has(v.name)?'<span class="badge badge-ok">OK</span>':'<span class="badge badge-err">MISSING</span>';return `<tr><td>${v.name}</td><td>${v.type}</td><td>${v.nullable?"Yes":"No"}</td><td>${v.isPrimaryKey?"\u2713":""}</td><td>${_}</td></tr>`}).join(`
46
+ `),M=T.map(v=>`<tr><td>${v}</td><td colspan="3" class="muted">not in schema</td><td><span class="badge badge-warn">EXTRA</span></td></tr>`).join(`
47
+ `);$=`<h2>Columns</h2>
48
+ <table>
49
+ <thead><tr><th>Column</th><th>SQL Type</th><th>Nullable</th><th>PK</th><th>Status</th></tr></thead>
50
+ <tbody>${O}${M}</tbody>
51
+ </table>`;}else d?.numberOfDocuments!==void 0&&($=`<h2>Index Stats</h2>
52
+ <table>
53
+ <tr><th>Documents Count</th><td>${d.numberOfDocuments}</td></tr>
54
+ <tr><th>Indexing in Progress</th><td>${d.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>${d.primaryKey??"default"}</code></td></tr>
56
+ </table>`);return `<div class="card" style="margin-top:1rem">
57
+ <h2>Adapter: <code>${R}</code> ${D}</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
+ ${$}
61
+ </div>`},A=j(`Health: ${l.name}`,S,`<div class="card">
62
+ <p>Overall status for <strong>${l.name}</strong>: ${f?'<span class="badge badge-ok">Healthy</span>':'<span class="badge badge-err">Issues detected</span>'}</p>
63
+ </div>
64
+ ${x.map(a).join(`
65
+ `)}`);z(u,A);}),g.manualSync&&(k.get(`${c}/:repoName/force-sync`,(p,u)=>{let S=H(p,c),l=w.find(f=>f.name===p.params.repoName);if(!l){z(u,j("Not Found",S,`<p>Unknown repo: ${p.params.repoName}</p>`),404);return}let x=j(`Force Sync: ${l.name}`,S,`<div class="card">
66
+ <p>This will read <strong>all</strong> documents from the <code>${l.name}</code> Firestore collection
67
+ and upsert them into all active target storage adapters (${l.adapters.map(f=>f.name).join(", ")}).</p>
57
68
  <p class="muted" style="margin:.75rem 0">This may take a while for large collections.</p>
58
- <form method="POST" action="${c}/${o.name}/force-sync">
69
+ <form method="POST" action="${S}/${l.name}/force-sync">
59
70
  <button type="submit" class="btn btn-primary">Start Force Sync</button>
60
71
  </form>
61
- </div>`);M(l,p);}),A.post(`${f}/:repoName/force-sync`,async(s,l)=>{let c=I(s,f),o=w.find(y=>y.name===s.params.repoName);if(!o){j(l,{error:`Unknown repo: ${s.params.repoName}`},404);return}let p=o.repo.ref;if(!p){j(l,{error:`No collection reference for "${o.name}"`},400);return}let S=0,d=0,h=[],C=500,E=p.limit(C),O=null;try{for(;;){let x=await(O?E.startAfter(O):E).get();if(x.empty)break;for(let R of x.docs){let D=R.data(),m=String(D[o.documentKey]??R.id),z=N(D,{exclude:o.repoCfg?.exclude,columnMap:o.repoCfg?.columnMap});try{await r({operation:"UPSERT",repoName:o.name,docId:m,data:z,timestamp:new Date().toISOString()}),S++;}catch(U){d++;let ce=U?.message??String(U);console.error(`[ForceSync:${o.name}] doc=${m} failed:`,U),h.length<5&&h.push(`${m}: ${ce}`);}}if(O=x.docs[x.docs.length-1],x.docs.length<C)break}let y=n.get(o.name);y&&await y.flush();}catch(y){if(Z(s)){j(l,{error:y?.message??String(y),synced:S,errors:d},500);return}M(l,_(`Force Sync: ${o.name}`,c,`<div class="card">
62
- <p class="badge badge-err">Error: ${y?.message??String(y)}</p>
63
- <p>Synced ${S} docs before failure (${d} errors).</p>
64
- </div>`),500);return}if(Z(s)){j(l,{repo:o.name,table:o.tableName,synced:S,errors:d,...h.length>0&&{errorSamples:h}});return}let P=h.length>0?`<details style="margin-top:1rem"><summary>First ${h.length} error(s)</summary>
65
- <pre style="white-space:pre-wrap">${h.map(y=>y.replace(/[<>&]/g,g=>`&#${g.charCodeAt(0)};`)).join(`
72
+ </div>`);z(u,x);}),k.post(`${c}/:repoName/force-sync`,async(p,u)=>{let S=H(p,c),l=w.find(d=>d.name===p.params.repoName);if(!l){L(u,{error:`Unknown repo: ${p.params.repoName}`},404);return}let x=l.repo.ref;if(!x){L(u,{error:`No collection reference for "${l.name}"`},400);return}let f=0,a=0,A=[],h=500,R=x.limit(h),P=null;try{for(;;){let b=await(P?R.startAfter(P):R).get();if(b.empty)break;for(let E of b.docs){let T=E.data(),O=String(T[l.documentKey]??E.id),M=F(T,{exclude:l.repoCfg?.exclude,columnMap:l.repoCfg?.columnMap});try{await r({operation:"UPSERT",repoName:l.name,docId:O,data:M,timestamp:new Date().toISOString()}),f++;}catch(v){a++;let _=v?.message??String(v);console.error(`[ForceSync:${l.name}] doc=${O} failed:`,v),A.length<5&&A.push(`${O}: ${_}`);}}if(P=b.docs[b.docs.length-1],b.docs.length<h)break}for(let d of l.adapters){let b=`${l.name}:${d.name}`,E=t.get(b)??t.get(l.name);E&&await E.flush();}}catch(d){if(U(p)){L(u,{error:d?.message??String(d),synced:f,errors:a},500);return}z(u,j(`Force Sync: ${l.name}`,S,`<div class="card">
73
+ <p class="badge badge-err">Error: ${d?.message??String(d)}</p>
74
+ <p>Synced ${f} docs before failure (${a} errors).</p>
75
+ </div>`),500);return}if(U(p)){L(u,{repo:l.name,table:l.tableName,synced:f,errors:a,...A.length>0&&{errorSamples:A}});return}let D=A.length>0?`<details style="margin-top:1rem"><summary>First ${A.length} error(s)</summary>
76
+ <pre style="white-space:pre-wrap">${A.map(d=>d.replace(/[<>&]/g,b=>`&#${b.charCodeAt(0)};`)).join(`
66
77
 
67
- `)}</pre></details>`:"",v=_(`Force Sync: ${o.name}`,c,`<div class="card">
68
- <p class="badge ${d>0?"badge-warn":"badge-ok"}">${d>0?"Completed with errors":"Complete"}</p>
69
- <p>Synced <strong>${S}</strong> documents to <code>${o.tableName}</code>.</p>
70
- ${d>0?`<p class="badge badge-warn">${d} error(s)</p>`:""}
71
- ${P}
72
- </div>`);M(l,v);})),T.configCheck&&A.get(`${f}/config-check`,async(s,l)=>{let c=I(s,f),o=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??process.env.GCP_PROJECT??"unknown",p="https://console.cloud.google.com",S=b??"firestore-sync",d=[];try{await e.tableExists("__nonexistent_health_check__"),d.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable"});}catch(y){let g=y?.message??String(y),x=g.toLowerCase(),R=x.includes("disabled")||x.includes("has not been used")||x.includes("accessnotconfigured"),D=x.includes("permission")||g.includes("403")||x.includes("access denied"),m=x.includes("project")&&x.includes("not found"),z=x.includes("not found")||g.includes("404");R?d.push({name:"BigQuery API",category:"bigquery",status:"error",message:"BigQuery API is not enabled",fix:{gcloud:`gcloud services enable bigquery.googleapis.com --project=${o}`,console:`${p}/apis/library/bigquery.googleapis.com?project=${o}`}}):m?d.push({name:"BigQuery Project",category:"bigquery",status:"error",message:g,fix:{hint:"The GCP project does not exist or the credentials don't have access to it. In the Firebase emulator, GCLOUD_PROJECT may override the configured projectId. Ensure you pass the correct projectId to the BigQuery constructor and have valid credentials.",console:`${p}/home/dashboard`}}):D?d.push({name:"BigQuery API",category:"bigquery",status:"error",message:`Permission denied: ${g}`,fix:{hint:"Grant the service account BigQuery Data Editor + BigQuery Job User roles",gcloud:[`SA=$(gcloud run services describe YOUR_SERVICE --region=YOUR_REGION --format="value(spec.template.spec.serviceAccountName)" --project=${o})`,`gcloud projects add-iam-policy-binding ${o} --member="serviceAccount:$SA" --role="roles/bigquery.dataEditor"`,`gcloud projects add-iam-policy-binding ${o} --member="serviceAccount:$SA" --role="roles/bigquery.jobUser"`].join(`
73
- `),console:`${p}/iam-admin/iam?project=${o}`}}):z?d.push({name:"BigQuery Dataset",category:"bigquery",status:"error",message:`Dataset not found: ${g}`,fix:{hint:"Create the dataset first",gcloud:`bq mk --dataset ${o}:YOUR_DATASET_ID`,console:`${p}/bigquery?project=${o}`}}):d.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable (table lookup returned expected error)"});}for(let y of w)try{let g=await e.tableExists(y.tableName);d.push({name:`Table: ${y.tableName}`,category:"bigquery",status:g?"ok":"warn",message:g?`Table \`${y.tableName}\` exists`:`Table \`${y.tableName}\` does not exist yet`,...!g&&{fix:{hint:"Table will be auto-created on first sync if autoMigrate is enabled. Or create it manually."}}});}catch(g){d.push({name:`Table: ${y.tableName}`,category:"bigquery",status:"error",message:g?.message??String(g)});}if(a)for(let y of w){let g=`${S}-${y.name}`;try{let x=a.topic(g);if(typeof x.exists=="function"){let[R]=await x.exists();d.push({name:`Topic: ${g}`,category:"pubsub",status:R?"ok":"error",message:R?`Topic \`${g}\` exists`:`Topic \`${g}\` does not exist`,...!R&&{fix:{gcloud:`gcloud pubsub topics create ${g} --project=${o}`,console:`${p}/cloudpubsub/topic/list?project=${o}`}}});}else d.push({name:`Topic: ${g}`,category:"pubsub",status:"warn",message:"Cannot verify topic existence (PubSub client doesn't expose .exists())",fix:{gcloud:`gcloud pubsub topics create ${g} --project=${o}`,console:`${p}/cloudpubsub/topic/list?project=${o}`,hint:"Ensure the topic exists. It is auto-created by the Firebase emulator but must exist in production."}});}catch(x){let R=x?.message??String(x),D=R.includes("disabled")||R.includes("has not been used");if(d.push({name:D?"Pub/Sub API":`Topic: ${g}`,category:"pubsub",status:"error",message:D?"Pub/Sub API is not enabled":R,fix:D?{gcloud:`gcloud services enable pubsub.googleapis.com --project=${o}`,console:`${p}/apis/library/pubsub.googleapis.com?project=${o}`}:{gcloud:`gcloud pubsub topics create ${g} --project=${o}`,console:`${p}/cloudpubsub/topic/list?project=${o}`}}),D)break}}else d.push({name:"Pub/Sub Client",category:"pubsub",status:"warn",message:"PubSub client not available for config check"});if(Z(s)){let y=d.every(g=>g.status==="ok");j(l,{project:o,healthy:y,checks:d});return}let h=y=>y==="ok"?'<span class="badge badge-ok">OK</span>':y==="warn"?'<span class="badge badge-warn">WARN</span>':'<span class="badge badge-err">ERROR</span>',C={bigquery:d.filter(y=>y.category==="bigquery"),pubsub:d.filter(y=>y.category==="pubsub"),firestore:d.filter(y=>y.category==="firestore")},E=(y,g)=>{if(g.length===0)return "";let x=g.map(R=>{let D="";if(R.fix){let m=[];R.fix.hint&&m.push(`<p class="muted">${R.fix.hint}</p>`),R.fix.gcloud&&m.push(`<pre>$ ${R.fix.gcloud}</pre>`),R.fix.console&&m.push(`<p><a href="${R.fix.console}" target="_blank">Open GCP Console \u2192</a></p>`),D=`<div style="margin-top:.5rem">${m.join("")}</div>`;}return `<tr>
74
- <td>${h(R.status)}</td>
75
- <td><strong>${R.name}</strong><br><span class="muted">${R.message}</span>${D}</td>
78
+ `)}</pre></details>`:"",$=j(`Force Sync: ${l.name}`,S,`<div class="card">
79
+ <p class="badge ${a>0?"badge-warn":"badge-ok"}">${a>0?"Completed with errors":"Complete"}</p>
80
+ <p>Synced <strong>${f}</strong> documents to targets (${l.adapters.map(d=>d.name).join(", ")}).</p>
81
+ ${a>0?`<p class="badge badge-warn">${a} error(s)</p>`:""}
82
+ ${D}
83
+ </div>`);z(u,$);})),g.configCheck&&k.get(`${c}/config-check`,async(p,u)=>{let S=H(p,c),l=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??process.env.GCP_PROJECT??"unknown",x="https://console.cloud.google.com",f=m??"firestore-sync",a=[];for(let d of C)if(d.name==="bigquery")try{await d.targetExists("__nonexistent_health_check__"),a.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable"});}catch(b){let E=b?.message??String(b),T=E.toLowerCase(),O=T.includes("disabled")||T.includes("has not been used")||T.includes("accessnotconfigured"),M=T.includes("permission")||E.includes("403")||T.includes("access denied"),v=T.includes("project")&&T.includes("not found"),_=T.includes("not found")||E.includes("404");O?a.push({name:"BigQuery API",category:"bigquery",status:"error",message:"BigQuery API is not enabled",fix:{gcloud:`gcloud services enable bigquery.googleapis.com --project=${l}`,console:`${x}/apis/library/bigquery.googleapis.com?project=${l}`}}):v?a.push({name:"BigQuery Project",category:"bigquery",status:"error",message:E,fix:{hint:"The GCP project does not exist or the credentials don't have access to it.",console:`${x}/home/dashboard`}}):M?a.push({name:"BigQuery API",category:"bigquery",status:"error",message:`Permission denied: ${E}`,fix:{hint:"Grant the service account BigQuery Data Editor + BigQuery Job User roles",console:`${x}/iam-admin/iam?project=${l}`}}):_?a.push({name:"BigQuery Dataset",category:"bigquery",status:"error",message:`Dataset not found: ${E}`,fix:{hint:"Create the dataset first",gcloud:`bq mk --dataset ${l}:YOUR_DATASET_ID`,console:`${x}/bigquery?project=${l}`}}):a.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable (table lookup returned expected error)"});}else if(d.name==="meilisearch"||typeof d.checkConnection=="function")try{let b=typeof d.checkConnection=="function"?await d.checkConnection():{healthy:await d.targetExists("__nonexistent__")};a.push({name:"Meilisearch API",category:"meilisearch",status:b.healthy?"ok":"error",message:b.healthy?`Meilisearch is reachable${b.version?` (v${b.version})`:""}`:`Meilisearch connection error: ${b.error??"unknown"}`,...b.error&&{fix:{hint:"Ensure Meilisearch is running and host/apiKey options are valid."}}});}catch(b){a.push({name:"Meilisearch API",category:"meilisearch",status:"error",message:`Meilisearch error: ${b?.message??String(b)}`});}for(let d of w)for(let b of d.adapters){let E=b.name==="bigquery"?"bigquery":b.name==="meilisearch"?"meilisearch":"storage";try{let T=await b.targetExists(d.tableName);a.push({name:`[${b.name}] Target: ${d.tableName}`,category:E,status:T?"ok":"warn",message:T?`Target \`${d.tableName}\` exists`:`Target \`${d.tableName}\` does not exist yet`,...!T&&{fix:{hint:"Target will be auto-created on first sync if autoMigrate is enabled."}}});}catch(T){a.push({name:`[${b.name}] Target: ${d.tableName}`,category:E,status:"error",message:T?.message??String(T)});}}if(i)for(let d of w){let b=`${f}-${d.name}`;try{let E=i.topic(b);if(typeof E.exists=="function"){let[T]=await E.exists();a.push({name:`Topic: ${b}`,category:"pubsub",status:T?"ok":"error",message:T?`Topic \`${b}\` exists`:`Topic \`${b}\` does not exist`,...!T&&{fix:{gcloud:`gcloud pubsub topics create ${b} --project=${l}`,console:`${x}/cloudpubsub/topic/list?project=${l}`}}});}else a.push({name:`Topic: ${b}`,category:"pubsub",status:"warn",message:"Cannot verify topic existence (PubSub client doesn't expose .exists())",fix:{gcloud:`gcloud pubsub topics create ${b} --project=${l}`,console:`${x}/cloudpubsub/topic/list?project=${l}`}});}catch(E){let T=E?.message??String(E),O=T.includes("disabled")||T.includes("has not been used");if(a.push({name:O?"Pub/Sub API":`Topic: ${b}`,category:"pubsub",status:"error",message:O?"Pub/Sub API is not enabled":T,fix:O?{gcloud:`gcloud services enable pubsub.googleapis.com --project=${l}`,console:`${x}/apis/library/pubsub.googleapis.com?project=${l}`}:{gcloud:`gcloud pubsub topics create ${b} --project=${l}`,console:`${x}/cloudpubsub/topic/list?project=${l}`}}),O)break}}else a.push({name:"Pub/Sub Client",category:"pubsub",status:"warn",message:"PubSub client not available for config check"});if(U(p)){let d=a.every(b=>b.status==="ok");L(u,{project:l,healthy:d,checks:a});return}let A=d=>d==="ok"?'<span class="badge badge-ok">OK</span>':d==="warn"?'<span class="badge badge-warn">WARN</span>':'<span class="badge badge-err">ERROR</span>',h={bigquery:a.filter(d=>d.category==="bigquery"),meilisearch:a.filter(d=>d.category==="meilisearch"),pubsub:a.filter(d=>d.category==="pubsub"),firestore:a.filter(d=>d.category==="firestore"),storage:a.filter(d=>d.category==="storage")},R=(d,b)=>{if(b.length===0)return "";let E=b.map(T=>{let O="";if(T.fix){let M=[];T.fix.hint&&M.push(`<p class="muted">${T.fix.hint}</p>`),T.fix.gcloud&&M.push(`<pre>$ ${T.fix.gcloud}</pre>`),T.fix.console&&M.push(`<p><a href="${T.fix.console}" target="_blank">Open GCP Console \u2192</a></p>`),O=`<div style="margin-top:.5rem">${M.join("")}</div>`;}return `<tr>
84
+ <td>${A(T.status)}</td>
85
+ <td><strong>${T.name}</strong><br><span class="muted">${T.message}</span>${O}</td>
76
86
  </tr>`}).join(`
77
- `);return `<h2>${y}</h2>
87
+ `);return `<h2>${d}</h2>
78
88
  <table><thead><tr><th style="width:80px">Status</th><th>Check</th></tr></thead>
79
- <tbody>${x}</tbody></table>`},P=d.every(y=>y.status==="ok")?'<span class="badge badge-ok">All checks passed</span>':'<span class="badge badge-warn">Some issues found</span>',v=_("Config Check",c,`<div class="card">
80
- <p>Project: <code>${o}</code> ${P}</p>
81
- ${E("BigQuery",C.bigquery)}
82
- ${E("Pub/Sub",C.pubsub)}
83
- ${E("Firestore",C.firestore)}
84
- </div>`);M(l,v);}),async(s,l)=>{await A.handle(s,l);}}function oe(t,e){let n=e.columns.map(r=>{let i=r.isPrimaryKey?" NOT NULL":"";return ` ${t.quoteIdentifier(r.name)} ${r.sqlType}${i}`}).join(`,
85
- `);return `CREATE TABLE IF NOT EXISTS ${t.quoteIdentifier(e.tableName)} (
86
- ${n}
87
- );`}function ke(t,e,n){return n.map(r=>`ALTER TABLE ${t.quoteIdentifier(e)} ADD COLUMN ${t.quoteIdentifier(r.name)} ${r.sqlType};`).join(`
88
- `)}function xe(t,e,n){let r=[];for(let[i,u]of Object.entries(t)){let a=u.schema??u._schema??void 0;if(!a)continue;let b=n?.repos?.[i],f=b?.tableName??i,T=u._systemKeys?.[0]??u.documentKey??"docId",k=$(a,e,{primaryKey:T,exclude:b?.exclude,columnMap:b?.columnMap}),w={tableName:f,columns:k};r.push(oe(e,w));}return r.join(`
89
+ <tbody>${E}</tbody></table>`},D=a.every(d=>d.status==="ok")?'<span class="badge badge-ok">All checks passed</span>':'<span class="badge badge-warn">Some issues found</span>',$=j("Config Check",S,`<div class="card">
90
+ <p>Project: <code>${l}</code> ${D}</p>
91
+ ${R("BigQuery",h.bigquery)}
92
+ ${R("Meilisearch",h.meilisearch)}
93
+ ${R("Pub/Sub",h.pubsub)}
94
+ ${R("Other Targets",h.storage)}
95
+ ${R("Firestore",h.firestore)}
96
+ </div>`);z(u,$);}),async(p,u)=>{await k.handle(p,u);}}var De="firestore-sync";function $e(n,e){return e?`${e}/{docId}`:(console.warn(`[SyncTriggers] Cannot determine collection path for "${n}". Skipping.`),null)}function Me(n){let e=[n?.documentKey,n?.pathKey,n?.createdKey,n?.updatedKey].filter(t=>typeof t=="string");return {isGroup:!!n?.isGroup,documentKey:e[0]??"docId",collectionPath:typeof n?.path=="string"?n.path:null}}function Ne(n){return {isGroup:!!n?._isGroup,documentKey:n?._systemKeys?.[0]??"docId",collectionPath:n?.ref?.path??null}}function ee(n,e){let{onDocumentWritten:t}=e.deps.firestoreTriggers,r=e.deps.pubsub,s=e?.topicPrefix??De,o={},i=new Map;function m(y){let w=i.get(y);return w||(w=r.topic(y),i.set(y,w),w)}async function c(y,w){await m(y).publishMessage({json:w});}let g=n?.rawMapping,C=g?Object.entries(g).map(([y,w])=>[y,Me(w)]):Object.entries(n).map(([y,w])=>[y,Ne(w)]);for(let[y,w]of C){let k=e?.repos?.[y],p;if(w.isGroup){if(!k?.triggerPath){console.warn(`[SyncTriggers] Skipping collection-group repo "${y}". Provide a triggerPath in the sync repos config for group collections.`);continue}p=k.triggerPath;}else p=k?.triggerPath??$e(y,w.collectionPath);if(!p)continue;let u=w.documentKey,S=`${s}-${y}`;o[`${y}_onSync`]=t(p,async l=>{let x=l.data?.before,f=l.data?.after;if(!x&&!f)return;let a=!!x?.exists,A=!!f?.exists;if(!a&&A){let h=f.data();if(!h)return;let R=String(h[u]??f.id),P=F(h,{exclude:k?.exclude,columnMap:k?.columnMap}),D={operation:"INSERT",repoName:y,docId:R,data:P,timestamp:new Date().toISOString(),version:Date.now()};await c(S,D);}else if(a&&A){let h=f.data();if(!h)return;let R=String(h[u]??f.id),P=F(h,{exclude:k?.exclude,columnMap:k?.columnMap}),D={operation:"UPSERT",repoName:y,docId:R,data:P,timestamp:new Date().toISOString(),version:Date.now()};await c(S,D);}else if(a&&!A){let h=x.data(),R=String(h?.[u]??x.id),P={operation:"DELETE",repoName:y,docId:R,data:null,timestamp:new Date().toISOString(),version:Date.now()};await c(S,P);}});}return o}var N="__sync_version";var Ie={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 Z(n){let e=n,t=e._zod?.def?.type;if(t)return Ie[t]??`Zod${t.charAt(0).toUpperCase()}${t.slice(1)}`;let r=e._def?.typeName;return r||""}function de(n){let e=n;if(e._zod?.def?.innerType)return e._zod.def.innerType;if(e._def?.innerType)return e._def.innerType}function te(n){let e=n;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 _e=new Set(["ZodOptional","ZodNullable","ZodDefault"]);function pe(n){let e=n,t=false;for(;;){let r=Z(e);if(!_e.has(r))break;(r==="ZodOptional"||r==="ZodNullable")&&(t=true);let s=de(e);if(!s)break;e=s;}return {inner:e,nullable:t}}var fe={ZodString:"string",ZodNumber:"number",ZodBigInt:"bigint",ZodBoolean:"boolean",ZodDate:"timestamp",ZodEnum:"string",ZodNativeEnum:"string",ZodLiteral:"string"};function He(n){let{inner:e}=pe(n);return fe[Z(e)]??"json"}function ye(n,e,t,r,s,o,i,m){for(let[c,g]of Object.entries(n)){let C=t?`${t}__${c}`:c;if(s.has(c)||s.has(C))continue;let{inner:y,nullable:w}=pe(g),k=Z(y),p=r||w;if(k==="ZodObject"){let x=te(y);ye(x,e,C,p,s,o,i,m);continue}let u=fe[k]??"json",S=C===i||c===i,l=o[C]??o[c]??C;m.push({name:l,sqlType:e.mapType(u),nullable:S?false:p,isPrimaryKey:S});}}function I(n,e,t={}){let{primaryKey:r,exclude:s=[],columnMap:o={}}=t,i=new Set(s),m=te(n),c=[];return ye(m,e,"",false,i,o,r,c),c.some(g=>g.name===N)||c.push({name:N,sqlType:e.mapType("bigint"),nullable:true,isPrimaryKey:false,description:"Monotonic publish version (Date.now() ms). Internal."}),c}function G(n){let e=n.toUpperCase();switch(e){case "INTEGER":return "INT64";case "FLOAT":return "FLOAT64";case "BOOLEAN":return "BOOL";default:return e}}function me(n,e){let t=G(n),r=G(e);return t===r?true:{INT64:["NUMERIC","BIGNUMERIC","FLOAT64"],NUMERIC:["BIGNUMERIC","FLOAT64"],DATE:["DATETIME","TIMESTAMP"],DATETIME:["TIMESTAMP"]}[t]?.includes(r)??false}var ne=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,"``")+"`"}},he=new ne,V=null;function je(){return V||(V=ie("@google-cloud/bigquery-storage"),V)}function ge(n){let e;return typeof n=="bigint"?e=n:typeof n=="number"||typeof n=="string"?e=BigInt(n):e=0n,e<0n&&(e=0n),e.toString(16).padStart(16,"0")}function ze(n){if(!n||typeof n!="object")return false;let e=n;return e.code===4||e.code===10||e.code===13||e.code===14}async function Fe(n,e=6,t=200){let r=0;for(;;)try{return await n()}catch(s){if(r++,!ze(s)||r>e)throw s;let o=t*Math.pow(2,r),i=Math.random()*o;await new Promise(m=>setTimeout(m,i));}}var q=class extends Error{constructor(t,r,s,o){super(`Schema drift detected on \`${t}\`: 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=t;this.column=r;this.existingType=s;this.desiredType=o;this.name="SchemaTypeMismatchError";}},B=class B{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 he}async targetExists(e){return this.tableExists(e)}async upsert(e,t,r){return this.upsertRows(e,t,r)}async delete(e,t,r){return this.deleteRows(e,t,r)}async ensureTarget(e){if(!e.schema)return;let{targetName:t,primaryKey:r,schema:s,exclude:o,columnMap:i}=e,m=I(s,this.dialect,{primaryKey:r,exclude:o,columnMap:i});if(!await this.tableExists(t))await this.createTable({tableName:t,columns:m});else {let g=await this.getTableColumnsWithTypes(t),C=[];for(let y of m){let w=g.get(y.name);if(w===void 0){C.push(y);continue}if(!me(w,y.sqlType))throw new q(t,y.name,w,y.sqlType)}C.length>0&&(await this.addColumns(t,C),await this.onSchemaChange?.(t));}}async healthCheck(e){let{targetName:t,primaryKey:r,schema:s,repoConfig:o}=e;if(!s)return {healthy:false,targetName:t,targetExists:false,error:"No Zod schema attached to repository"};try{if(!await this.tableExists(t))return {healthy:!1,targetName:t,targetExists:!1,error:`Table \`${t}\` does not exist`};let m=await this.getTableColumns(t),c=I(s,this.dialect,{primaryKey:r,exclude:o?.exclude,columnMap:o?.columnMap}),g=new Set(m),C=new Set(c.map(u=>u.name)),y=c.filter(u=>!g.has(u.name)),w=m.filter(u=>!C.has(u)),k=c.filter(u=>g.has(u.name)),p=y.length===0;return {healthy:p,targetName:t,targetExists:!0,error:p?null:`Missing columns: ${y.map(u=>u.name).join(", ")}`,details:{expected:c.map(u=>({name:u.name,type:u.sqlType,nullable:u.nullable,isPrimaryKey:u.isPrimaryKey})),actual:m,matched:k.map(u=>u.name),missing:y.map(u=>({name:u.name,type:u.sqlType})),extra:w}}}catch(i){return {healthy:false,targetName:t,targetExists:false,error:i?.message??String(i)}}}async tableExists(e){let[t]=await this.dataset.table(e).exists();return t}async getTableColumns(e){let[t]=await this.dataset.table(e).getMetadata();return (t.schema?.fields??[]).map(s=>s.name)}async getTableColumnsWithTypes(e){let[t]=await this.dataset.table(e).getMetadata(),r=t.schema?.fields??[],s=new Map;for(let o of r)s.set(o.name,G(o.type));return s}async createTable(e){let t=c=>this.dialect.quoteIdentifier(c),r=e.columns.find(c=>c.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(c=>{let g=c.isPrimaryKey?" NOT NULL":"";return ` ${t(c.name)} ${c.sqlType}${g}`}).join(`,
97
+ `),o=[];this.maxStaleness!==null&&o.push(`max_staleness = ${this.maxStaleness}`);let i=o.length>0?`
98
+ OPTIONS(${o.join(", ")})`:"",m=`CREATE TABLE IF NOT EXISTS ${this.fqn(e.tableName)} (
99
+ ${s},
100
+ PRIMARY KEY (${t(r)}) NOT ENFORCED
101
+ )
102
+ CLUSTER BY ${t(r)}${i};`;await this.bigquery.query({query:m});}async addColumns(e,t){let r=s=>this.dialect.quoteIdentifier(s);for(let s of t){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 t=this.writers.get(e);if(t){try{t.writer.close();}catch{}this.writers.delete(e);}}async insertRows(e,t){if(t.length===0)return;let r=await this.getOrCreateWriter(e),s=this.writers.get(e)?.timestampColumns,o=t.map(i=>({...this.normalizeRow(i,s),_CHANGE_TYPE:"UPSERT",_CHANGE_SEQUENCE_NUMBER:ge(i[N])}));await this.appendWithRetry(e,r,o);}async upsertRows(e,t,r){if(t.length===0)return;let s=await this.getOrCreateWriter(e,r),o=this.writers.get(e)?.timestampColumns,i=t.map(m=>({...this.normalizeRow(m,o),_CHANGE_TYPE:"UPSERT",_CHANGE_SEQUENCE_NUMBER:ge(m[N])}));await this.appendWithRetry(e,s,i);}async deleteRows(e,t,r){if(r.length===0)return;let s=await this.getOrCreateWriter(e,t),o=r.map(i=>({[t]: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 t=r=>r.replace(/`/g,"``");return `\`${t(this.datasetId)}.${t(e)}\``}static toEpochMicros(e){let t=e.getTime();return (BigInt(t)*1000n).toString()}normalizeRow(e,t){let r={};for(let[s,o]of Object.entries(e))if(o!==void 0)if(o instanceof Date)r[s]=B.toEpochMicros(o);else if(typeof o=="string"&&this.shouldCoerceTimestamp(s,o,t)){let i=new Date(o);Number.isNaN(i.getTime())?r[s]=o:r[s]=B.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,t,r){return r?r.has(e):B.ISO_TIMESTAMP_RE.test(t)}async appendWithRetry(e,t,r){await Fe(async()=>{try{await t.appendRows(r).getResult();}catch(s){throw this.onSchemaChange(e),s}});}async getOrCreateWriter(e,t){let r=this.writers.get(e);if(r)if(t&&r.primaryKey!==t)this.onSchemaChange(e);else return r.writer;let s=je();this.writerClient||(this.writerClient=new s.managedwriter.WriterClient({projectId:this.projectId}));let[o]=await this.dataset.table(e).getMetadata(),i={fields:o.schema?.fields??[]};t||(t=o.tableConstraints?.primaryKey?.columns?.[0]??i.fields[0]?.name);let m=s.adapt.convertBigQuerySchemaToStorageTableSchema(i),c=s.adapt.convertStorageSchemaToProto2Descriptor(m,"Row",s.adapt.withChangeType(),s.adapt.withChangeSequenceNumber()),g=new Set(i.fields.filter(k=>["TIMESTAMP","DATETIME","DATE"].includes(String(k.type??"").toUpperCase())).map(k=>k.name)),C=`projects/${this.projectId}/datasets/${this.datasetId}/tables/${e}`,y=await this.writerClient.createStreamConnection({streamId:s.managedwriter.DefaultStream,destinationTable:C}),w=new s.managedwriter.JSONWriter({connection:y,protoDescriptor:c});return this.writers.set(e,{writer:w,primaryKey:t??"",timestampColumns:g}),w}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{}}};B.ISO_TIMESTAMP_RE=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/;var re=B;var Q=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 t=e.flushIntervalMs??5e3;t>0&&(this.timer=setInterval(()=>{this.flush();},t),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 t=new Map,r=[];for(let o of e)if(o.operation==="DELETE")r.push(o.docId),t.delete(o.docId);else if(o.data){let i=t.get(o.docId);if(!i)t.set(o.docId,o.data);else {let m=Number(i[N]??0);Number(o.data[N]??0)>=m&&t.set(o.docId,o.data);}}let s=Array.from(t.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(t){if(this.onFlushError)await this.onFlushError(e,t);else return this.buffer.unshift(...e),console.error(`[SyncQueue] Flush failed for ${this.tableName}:`,t),false}return true}async shutdown(){this.timer&&(clearInterval(this.timer),this.timer=null),await this.flush();}};var be=new Set;async function Le(n,e,t,r,s,o,i){let m=`${n}:${e.name}`;if(!be.has(m)){if(typeof e.ensureTarget=="function")await e.ensureTarget({targetName:r,primaryKey:s,schema:t,exclude:o,columnMap:i});else if("dialect"in e&&typeof e.createTable=="function"){let c=e,g=I(t,c.dialect,{primaryKey:s,exclude:o,columnMap:i});if(!await c.tableExists(r))await c.createTable({tableName:r,columns:g});else {let y=new Set(await c.getTableColumns(r)),w=g.filter(k=>!y.has(k.name));w.length>0&&(await c.addColumns(r,w),await c.onSchemaChange?.(r));}}be.add(m);}}function se(n,e){let{deps:t,adapter:r,adapters:s,batchSize:o=100,flushIntervalMs:i=5e3,autoMigrate:m=false,topicPrefix:c="firestore-sync",maxDlqAttempts:g=5,workerOptions:C,repos:y={}}=e,k=(s||(Array.isArray(r)?r:r?[r]:[])).map(f=>typeof f=="function"?f():f);function p(f){let a=y[f];if(a?.adapters&&a.adapters.length>0){let A=new Set(a.adapters);return k.filter(h=>A.has(h.name))}return k}let u=new Map;function S(f,a,A){let h=`${f}:${a.name}`,R=u.get(h);if(R)return R;let D=y[f]?.tableName??f,$=`${c}-${f}-${a.name}-dlq`,d=t.pubsub.topic($),b=false,E=async()=>{if(!b){try{await d.create(),console.info(`[SyncWorker:${a.name}] Created DLQ topic "${$}"`);}catch(O){if(O?.code!==6)throw O}b=true;}},T=async(O,M)=>{console.error(`[SyncWorker:${a.name}] Flush failed for "${f}" (${O.length} events):`,M),await E(),await Promise.all(O.map(v=>{let _=(v.attempts??0)+1;if(g>0&&_>g)return console.error(`[SyncWorker:${a.name}] Dropping event for "${f}" after ${_-1} DLQ attempts:`,{docId:v.docId,operation:v.operation}),Promise.resolve();let Te={...v,attempts:_,firstFailedAt:v.firstFailedAt??Date.now()};return d.publishMessage({json:Te})}));};return R=new Q({adapter:a,tableName:D,primaryKey:A,batchSize:o,flushIntervalMs:i,onFlushError:T}),u.set(h,R),u.has(f)||u.set(f,R),R}async function l(f){let{repoName:a}=f,A=n[a];if(!A){console.warn(`[SyncWorker] Unknown repo "${a}", skipping event`);return}let h=A._systemKeys?.[0]??A.documentKey??"docId",R=y[a],P=R?.columnMap,D=P?.[h]??h;f.data&&(f.data[N]=f.version??Date.now());let $=p(a);for(let d of $){if(m){let E=A.schema??void 0;if(E){let T=R?.tableName??a;await Le(a,d,E,T,D,R?.exclude,P);}}S(a,d,D).enqueue(f);}}function x(f){let a=async A=>{let h=A.data?.message?.json??A.data?.json;if(!h){console.warn("[SyncWorker] Received empty PubSub message");return}await l(h);let R=p(h.repoName);for(let P of R){let D=`${h.repoName}:${P.name}`,$=u.get(D);$&&await $.flush();}};return C?t.pubsubHandler.onMessagePublished({topic:f,...C},a):t.pubsubHandler.onMessagePublished(f,a)}return {handleMessage:l,createHandler:x,queues:u,async shutdown(){let f=[],a=new Set;for(let A of u.values())a.has(A)||(a.add(A),f.push(A.shutdown()));await Promise.all(f);}}}var Be="firestore-sync";function we(n){if(typeof n!="function")return n;let e=n,t;return new Proxy({},{get(r,s){return t||(t=e()),t[s]},has(r,s){return t||(t=e()),s in t}})}function qe(n,e){let{deps:t,adapter:r,adapters:s,topicPrefix:o=Be,batchSize:i,flushIntervalMs:m,autoMigrate:c,admin:g,workerOptions:C,repos:y}=e,w=we(t.pubsub),p=(s||(Array.isArray(r)?r:r?[r]:[])).map(a=>we(a)),u=ee(n,{deps:{firestoreTriggers:t.firestoreTriggers,pubsub:w},topicPrefix:o,repos:y}),S=se(n,{deps:{pubsubHandler:t.pubsubHandler,pubsub:w},adapters:p,batchSize:i,flushIntervalMs:m,autoMigrate:c,topicPrefix:o,workerOptions:C,repos:y}),l={};for(let a of Object.keys(n))l[`sync_${a}`]=S.createHandler(`${o}-${a}`);let x=null;g&&(x=X(n,p,S.queues,S.handleMessage,g,y??{},w,o),l.adminsync=g.onRequest?g.httpsOptions?g.onRequest(g.httpsOptions,x):g.onRequest(x):x);let f={functions:{...u,...l},adminHandler:x,handleMessage:S.handleMessage,queues:S.queues,shutdown:S.shutdown};for(let a of ["adminHandler","handleMessage","queues","shutdown"])Object.defineProperty(f,a,{enumerable:false});return f}function Se(n,e){let t=e.columns.map(r=>{let s=r.isPrimaryKey?" NOT NULL":"";return ` ${n.quoteIdentifier(r.name)} ${r.sqlType}${s}`}).join(`,
103
+ `);return `CREATE TABLE IF NOT EXISTS ${n.quoteIdentifier(e.tableName)} (
104
+ ${t}
105
+ );`}function Qe(n,e,t){return t.map(r=>`ALTER TABLE ${n.quoteIdentifier(e)} ADD COLUMN ${n.quoteIdentifier(r.name)} ${r.sqlType};`).join(`
106
+ `)}function Ke(n,e,t){let r=[];for(let[s,o]of Object.entries(n)){let i=o.schema??o._schema??void 0;if(!i)continue;let m=t?.repos?.[s],c=m?.tableName??s,g=o._systemKeys?.[0]??o.documentKey??"docId",C=I(i,e,{primaryKey:g,exclude:m?.exclude,columnMap:m?.columnMap}),y={tableName:c,columns:C};r.push(Se(e,y));}return r.join(`
89
107
 
90
- `)}async function Re(t,e,n){let r={created:[],altered:[],upToDate:[],skipped:[]};for(let[i,u]of Object.entries(t)){let a=u.schema??void 0;if(!a){r.skipped.push(i);continue}let b=n?.repos?.[i],f=b?.tableName??i,T=u._systemKeys?.[0]??u.documentKey??"docId",k=$(a,e.dialect,{primaryKey:T,exclude:b?.exclude,columnMap:b?.columnMap}),w={tableName:f,columns:k};if(!await e.tableExists(f))await e.createTable(w),r.created.push(f);else {let s=new Set(await e.getTableColumns(f)),l=k.filter(c=>!s.has(c.name));l.length>0?(await e.addColumns(f,l),r.altered.push(f)):r.upToDate.push(f);}}return r}var F=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 u of e)if(u.operation==="DELETE")r.push(u.docId),n.delete(u.docId);else if(u.data){let a=n.get(u.docId);if(!a)n.set(u.docId,u.data);else {let b=Number(a[H]??0);Number(u.data[H]??0)>=b&&n.set(u.docId,u.data);}}let i=Array.from(n.values());i.length>0&&await this.adapter.upsertRows(this.tableName,i,this.primaryKey),r.length>0&&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 Ae="firestore-sync";function Ce(t,e){return e?`${e}/{docId}`:(console.warn(`[SyncTriggers] Cannot determine collection path for "${t}". Skipping.`),null)}function Ee(t){let e=[t?.documentKey,t?.pathKey,t?.createdKey,t?.updatedKey].filter(n=>typeof n=="string");return {isGroup:!!t?.isGroup,documentKey:e[0]??"docId",collectionPath:typeof t?.path=="string"?t.path:null}}function Oe(t){return {isGroup:!!t?._isGroup,documentKey:t?._systemKeys?.[0]??"docId",collectionPath:t?.ref?.path??null}}function Pe(t,e){let{onDocumentCreated:n,onDocumentUpdated:r,onDocumentDeleted:i}=e.deps.firestoreTriggers,u=e.deps.pubsub,a=e?.topicPrefix??Ae,b={},f=new Map;function T(s){let l=f.get(s);return l||(l=u.topic(s),f.set(s,l),l)}async function k(s,l){await T(s).publishMessage({json:l});}let w=t?.rawMapping,A=w?Object.entries(w).map(([s,l])=>[s,Ee(l)]):Object.entries(t).map(([s,l])=>[s,Oe(l)]);for(let[s,l]of A){let c=e?.repos?.[s],o;if(l.isGroup){if(!c?.triggerPath){console.warn(`[SyncTriggers] Skipping collection-group repo "${s}". Provide a triggerPath in the sync repos config for group collections.`);continue}o=c.triggerPath;}else o=c?.triggerPath??Ce(s,l.collectionPath);if(!o)continue;let p=l.documentKey,S=`${a}-${s}`;b[`${s}_onCreate`]=n(o,async d=>{let h=d.data;if(!h)return;let C=h.data();if(!C)return;let E=String(C[p]??h.id),O=N(C,{exclude:c?.exclude,columnMap:c?.columnMap}),P={operation:"INSERT",repoName:s,docId:E,data:O,timestamp:new Date().toISOString(),version:Date.now()};await k(S,P);}),b[`${s}_onUpdate`]=r(o,async d=>{let h=d.data?.after;if(!h)return;let C=h.data();if(!C)return;let E=String(C[p]??h.id),O=N(C,{exclude:c?.exclude,columnMap:c?.columnMap}),P={operation:"UPSERT",repoName:s,docId:E,data:O,timestamp:new Date().toISOString(),version:Date.now()};await k(S,P);}),b[`${s}_onDelete`]=i(o,async d=>{let h=d.data;if(!h)return;let C=h.data(),E=String(C?.[p]??h.id),O={operation:"DELETE",repoName:s,docId:E,data:null,timestamp:new Date().toISOString(),version:Date.now()};await k(S,O);});}return b}function se(t){let e=t.toUpperCase();switch(e){case "INTEGER":return "INT64";case "FLOAT":return "FLOAT64";case "BOOLEAN":return "BOOL";default:return e}}function ie(t,e){let n=se(t),r=se(e);return n===r?true:{INT64:["NUMERIC","BIGNUMERIC","FLOAT64"],NUMERIC:["BIGNUMERIC","FLOAT64"],DATE:["DATETIME","TIMESTAMP"],DATETIME:["TIMESTAMP"]}[n]?.includes(r)??false}var ae=new Set,G=class extends Error{constructor(n,r,i,u){super(`Schema drift detected on \`${n}\`: column \`${r}\` has type ${i} in BigQuery but the current Zod schema maps it to ${u}. 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=i;this.desiredType=u;this.name="SchemaTypeMismatchError";}};async function De(t,e,n,r,i,u,a){if(ae.has(t))return;let b=$(n,e.dialect,{primaryKey:i,exclude:u,columnMap:a});if(!await e.tableExists(r))await e.createTable({tableName:r,columns:b});else if(e.getTableColumnsWithTypes){let T=await e.getTableColumnsWithTypes(r),k=[];for(let w of b){let A=T.get(w.name);if(A===void 0){k.push(w);continue}if(e.dialect.name==="bigquery"&&!ie(A,w.sqlType))throw new G(r,w.name,A,w.sqlType)}k.length>0&&(await e.addColumns(r,k),await e.onSchemaChange?.(r));}else {let T=new Set(await e.getTableColumns(r)),k=b.filter(w=>!T.has(w.name));k.length>0&&(await e.addColumns(r,k),await e.onSchemaChange?.(r));}ae.add(t);}function ve(t,e){let{deps:n,adapter:r,batchSize:i=100,flushIntervalMs:u=5e3,autoMigrate:a=false,topicPrefix:b="firestore-sync",maxDlqAttempts:f=5,workerOptions:T,repos:k={}}=e,w=new Map;function A(c,o){let p=w.get(c);if(p)return p;let d=k[c]?.tableName??c,h=`${b}-${c}-dlq`,C=n.pubsub.topic(h),E=false,O=async()=>{if(!E){try{await C.create(),console.info(`[SyncWorker] Created DLQ topic "${h}"`);}catch(v){if(v?.code!==6)throw v}E=true;}},P=async(v,y)=>{console.error(`[SyncWorker] Flush failed for "${c}" (${v.length} events):`,y),await O(),await Promise.all(v.map(g=>{let x=(g.attempts??0)+1;if(f>0&&x>f)return console.error(`[SyncWorker] Dropping event for "${c}" after ${x-1} DLQ attempts:`,{docId:g.docId,operation:g.operation}),Promise.resolve();let R={...g,attempts:x,firstFailedAt:g.firstFailedAt??Date.now()};return C.publishMessage({json:R})}));};return p=new F({adapter:r,tableName:d,primaryKey:o,batchSize:i,flushIntervalMs:u,onFlushError:P}),w.set(c,p),p}async function s(c){let{repoName:o}=c,p=t[o];if(!p){console.warn(`[SyncWorker] Unknown repo "${o}", skipping event`);return}let S=p._systemKeys?.[0]??p.documentKey??"docId",d=k[o],h=d?.columnMap,C=h?.[S]??S;if(a){let O=p.schema??void 0;if(O){let P=d?.tableName??o;await De(o,r,O,P,S,d?.exclude,h);}}let E=A(o,C);c.data&&(c.data[H]=c.version??Date.now()),E.enqueue(c);}function l(c){let o=async p=>{let S=p.data?.message?.json??p.data?.json;if(!S){console.warn("[SyncWorker] Received empty PubSub message");return}await s(S);let d=w.get(S.repoName);d&&await d.flush();};return T?n.pubsubHandler.onMessagePublished({topic:c,...T},o):n.pubsubHandler.onMessagePublished(c,o)}return {handleMessage:s,createHandler:l,queues:w,async shutdown(){let c=[];for(let o of w.values())c.push(o.shutdown());await Promise.all(c);}}}exports.SyncQueue=F;exports.addColumnsDDL=ke;exports.autoMigrate=Re;exports.createSyncTriggers=Pe;exports.createSyncWorker=ve;exports.createTableDDL=oe;exports.createadminsyncServer=Se;exports.generateDDL=xe;exports.serializeDocument=N;exports.serializeValue=q;exports.zodSchemaToColumns=$;exports.zodTypeToLogical=be;//# sourceMappingURL=index.cjs.map
108
+ `)}async function We(n,e,t){let r={created:[],altered:[],upToDate:[],skipped:[]};for(let[s,o]of Object.entries(n)){let i=o.schema??void 0;if(!i){r.skipped.push(s);continue}let m=t?.repos?.[s],c=m?.tableName??s,g=o._systemKeys?.[0]??o.documentKey??"docId",C=I(i,e.dialect,{primaryKey:g,exclude:m?.exclude,columnMap:m?.columnMap}),y={tableName:c,columns:C};if(!await e.tableExists(c))await e.createTable(y),r.created.push(c);else {let k=new Set(await e.getTableColumns(c)),p=C.filter(u=>!k.has(u.name));p.length>0?(await e.addColumns(c,p),r.altered.push(c)):r.upToDate.push(c);}}return r}function Ue(n){if(n.client)return n.client;if(!n.host)throw new Error("MeilisearchAdapter requires either a `client` instance or a `host` option.");try{let{MeiliSearch:e}=ie("meilisearch");return new e({host:n.host,apiKey:n.apiKey})}catch(e){throw new Error(`Failed to load the "meilisearch" package. Please install it with:
109
+ bun add meilisearch # or npm install meilisearch
110
+ Original error: ${e?.message??String(e)}`)}}var oe=class{constructor(e){this.name="meilisearch";this._client=null;this.options=e,e.client&&(this._client=e.client);}get client(){return this._client||(this._client=Ue(this.options)),this._client}async targetExists(e){try{return await this.client.getIndex(e),!0}catch(t){if(t?.code==="index_not_found"||t?.statusCode===404||t?.status===404)return false;throw t}}async upsert(e,t,r){if(t.length===0)return;await this.client.index(e).addDocuments(t,{primaryKey:r});}async delete(e,t,r){if(r.length===0)return;await this.client.index(e).deleteDocuments(r);}async ensureTarget(e){let{targetName:t,primaryKey:r}=e;await this.targetExists(t)||await this.client.createIndex(t,{primaryKey:r});let o=this.options.indexesSettings?.[t];o&&await this.client.index(t).updateSettings(o);}async healthCheck(e){let{targetName:t}=e;try{if(!await this.targetExists(t))return {healthy:!1,targetName:t,targetExists:!1,error:`Meilisearch index "${t}" does not exist`};let s=this.client.index(t),o=await s.getStats(),i=typeof s.getRawInfo=="function"?await s.getRawInfo():{};return {healthy:!0,targetName:t,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:t,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 t;return typeof this.client.getVersion=="function"&&(t=(await this.client.getVersion())?.pkgVersion),{healthy:e,version:t}}catch(e){return {healthy:false,error:e?.message??String(e)}}}};exports.BigQueryAdapter=re;exports.MeilisearchAdapter=oe;exports.SchemaTypeMismatchError=q;exports.SyncQueue=Q;exports.addColumnsDDL=Qe;exports.autoMigrate=We;exports.bigqueryDialect=he;exports.createFirestoreSync=qe;exports.createSyncTriggers=ee;exports.createSyncWorker=se;exports.createTableDDL=Se;exports.createadminsyncServer=X;exports.generateDDL=Ke;exports.serializeDocument=F;exports.serializeValue=Y;exports.zodSchemaToColumns=I;exports.zodTypeToLogical=He;//# sourceMappingURL=index.cjs.map
91
111
  //# sourceMappingURL=index.cjs.map