@lpdjs/firestore-repo-service 3.0.7 → 3.0.8
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.
- package/dist/{create-servers-CRTjY8sA.d.cts → create-servers-6tpqVsSh.d.cts} +26 -2
- package/dist/{create-servers-C-X5e62o.d.ts → create-servers-U8q943yf.d.ts} +26 -2
- package/dist/index.cjs +59 -57
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -3
- package/dist/index.d.ts +4 -3
- package/dist/index.js +59 -57
- package/dist/index.js.map +1 -1
- package/dist/llms-full.txt +1 -1
- package/dist/llms.txt +1 -1
- package/dist/{queue-BYbd9y4U.d.cts → queue-CiZNShPZ.d.cts} +1 -1
- package/dist/{queue-I7Y1l3Wu.d.ts → queue-CrH-eNEN.d.ts} +1 -1
- package/dist/servers/index.cjs +97 -95
- package/dist/servers/index.cjs.map +1 -1
- package/dist/servers/index.d.cts +4 -3
- package/dist/servers/index.d.ts +4 -3
- package/dist/servers/index.js +97 -95
- package/dist/servers/index.js.map +1 -1
- package/dist/sync/bigquery.d.cts +1 -1
- package/dist/sync/bigquery.d.ts +1 -1
- package/dist/sync/index.cjs +39 -39
- package/dist/sync/index.cjs.map +1 -1
- package/dist/sync/index.d.cts +5 -5
- package/dist/sync/index.d.ts +5 -5
- package/dist/sync/index.js +39 -39
- package/dist/sync/index.js.map +1 -1
- package/dist/sync/meilisearch.cjs +2 -2
- package/dist/sync/meilisearch.cjs.map +1 -1
- package/dist/sync/meilisearch.d.cts +25 -6
- package/dist/sync/meilisearch.d.ts +25 -6
- package/dist/sync/meilisearch.js +2 -2
- package/dist/sync/meilisearch.js.map +1 -1
- package/dist/{types-B48PI0V9.d.cts → types-C5qxru8j.d.cts} +8 -2
- package/dist/{types-DbtP8YCJ.d.ts → types-HZG1KlML.d.ts} +8 -2
- package/package.json +1 -1
package/dist/sync/bigquery.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { BigQuery } from '@google-cloud/bigquery';
|
|
2
2
|
import { z } from 'zod';
|
|
3
|
-
import { b as SqlAdapter, c as SqlDialect, R as RepoSyncConfig, d as SyncHealthResult, e as SqlTableDef, f as SqlColumn } from '../types-
|
|
3
|
+
import { b as SqlAdapter, c as SqlDialect, R as RepoSyncConfig, d as SyncHealthResult, e as SqlTableDef, f as SqlColumn } from '../types-C5qxru8j.cjs';
|
|
4
4
|
import '../firebase-auth-Ds5P0kXT.cjs';
|
|
5
5
|
import 'firebase-functions/v2/firestore';
|
|
6
6
|
import 'firebase-functions/v2/https';
|
package/dist/sync/bigquery.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { BigQuery } from '@google-cloud/bigquery';
|
|
2
2
|
import { z } from 'zod';
|
|
3
|
-
import { b as SqlAdapter, c as SqlDialect, R as RepoSyncConfig, d as SyncHealthResult, e as SqlTableDef, f as SqlColumn } from '../types-
|
|
3
|
+
import { b as SqlAdapter, c as SqlDialect, R as RepoSyncConfig, d as SyncHealthResult, e as SqlTableDef, f as SqlColumn } from '../types-HZG1KlML.js';
|
|
4
4
|
import '../firebase-auth-Ds5P0kXT.js';
|
|
5
5
|
import 'firebase-functions/v2/firestore';
|
|
6
6
|
import 'firebase-functions/v2/https';
|
package/dist/sync/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';require('firebase-admin/firestore'),require('crypto');var
|
|
1
|
+
'use strict';require('firebase-admin/firestore'),require('crypto');var pe=(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 De(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 ve(n){let e=n.path??n.url??"/",t=e.indexOf("?");return t===-1?e:e.slice(0,t)}var V=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}=De(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=ve(e),o=null,i={};for(let h of this.routes){if(h.method!==r)continue;let R=s.match(h.pattern);if(R){o=h,i={},h.paramNames.forEach((x,P)=>{i[x]=decodeURIComponent(R[P+1]??"");});break}}let u=Object.assign(e,{params:i}),a=o?o.handler:this.notFoundHandler;try{await this.runMiddlewareChain(u,t,a);}catch(h){this.errorHandler(h,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 L(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",u=t??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=n?.hostname??n?.headers?.host??"";return s&&typeof o=="string"&&o.includes("cloudfunctions.net")?`/${s.toLowerCase()}${r}`:r}function ye(n){if(typeof n=="string")return n;if(Array.isArray(n)){let e=n[0];return typeof e=="string"?e:void 0}}function se(n){return !!n&&typeof n=="object"&&n.__authExtension===true}function Ie(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 _e(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?Ie(n?.refCb):[],relationalKeys:n?.relationalKeys,_historyConfig:t,_historySubcollection:t?.enabled?t.subcollection??"history":void 0,_collectionPath:typeof n?.path=="string"?n.path:null}}function he(n,e){let t=_e(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,e,t=new WeakSet,r=0){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 s=n;return e?.stringifyArrays===false?{lat:s.latitude,lng:s.longitude}:JSON.stringify({lat:s.latitude,lng:s.longitude})}if(Array.isArray(n)){let s=n.map(o=>Y(o,e,t,r+1));return e?.stringifyArrays===false?s:JSON.stringify(s)}return typeof n=="object"&&n!==null&&e?.stringifyArrays===false?oe(n,new Set,{},t,r+1):n}var be=32,He=5e3;function we(n,e,t,r=new WeakSet,s=0){if(s>be){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>=He)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)?we(i,u,t,r,s+1):t[u]=Y(i);}r.delete(n);}function oe(n,e,t,r=new WeakSet,s=0){if(s>be)return {__truncated:true};if(r.has(n))return {__cycle:true};r.add(n);let o={};for(let[i,u]of Object.entries(n)){if(e.has(i))continue;let a=t[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]=oe(u,new Set,{},r,s+1):o[a]=Y(u,{stringifyArrays:false},r,s+1);}return r.delete(n),o}function ie(n){let e={};for(let[t,r]of Object.entries(n)){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(t.startsWith("__")||!t.includes("__")){e[t]=s;continue}let o=t.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 K(n,e){let t=e?.flat!==false,r;if(t){let s=new Set(e?.exclude),o=e?.columnMap??{},i={};we(n,"",i),r={};for(let[u,a]of Object.entries(i)){if(s.has(u))continue;let h=u.split("__")[0];if(h!==u&&s.has(h))continue;let R=o[u]??(u.includes("__")?o[u.split("__").pop()]:void 0)??u;r[R]=a;}}else {let s=new Set(e?.exclude),o=e?.columnMap??{};r=oe(n,s,o);}return typeof e?.transformDoc=="function"&&(r=e.transformDoc(r)),r}function B(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
4
|
<title>${n} \u2014 Sync Admin</title>
|
|
@@ -28,84 +28,84 @@
|
|
|
28
28
|
<nav><a href="${e}/">\u2190 Dashboard</a></nav>
|
|
29
29
|
<h1>${n}</h1>
|
|
30
30
|
${t}
|
|
31
|
-
</body></html>`}function
|
|
31
|
+
</body></html>`}function q(n,e,t=200){n.status(t).set("Content-Type","text/html; charset=utf-8").send(e);}function Q(n,e,t=200){n.status(t).set("Content-Type","application/json").send(JSON.stringify(e,null,2));}function X(n){return (n.headers?.accept??"").includes("application/json")}function ae(n,e,t,r,s,o,i,u){let a=(s.basePath??"/").replace(/\/$/,"")||"",h=s.featuresFlag??{},R=ye(s.httpsOptions?.region),x=Array.isArray(e)?e:[e],P=n?.rawMapping,O=[],k=Object.keys(o??{}),m=k.length>0,D=Object.keys(P||n),$=m?k.filter(l=>D.includes(l)||l in n):D;for(let l of $){let d=o[l],y=P?he(P[l],()=>n[l]):n[l],c=!!y._isGroup;if(!m&&c&&!d?.triggerPath)continue;let b=d?.adapters&&d.adapters.length>0?x.filter(A=>d.adapters.includes(A.name)):x;O.push({name:l,schema:y.schema??null,documentKey:y._systemKeys?.[0]??y.documentKey??"docId",tableName:d?.tableName??l,isGroup:c,repoCfg:d,repo:y,adapters:b});}let v=new V;if(s.auth)if(se(s.auth)){let l=s.auth;for(let d of l.routes){let y=`${a}${d.path}`;d.method==="GET"?v.get(y,d.handler):v.post(y,d.handler);}v.use(l.middleware);}else if(typeof s.auth=="function")v.use(s.auth);else {let l=s.auth.realm??"Sync Admin",d="Basic "+Buffer.from(`${s.auth.username}:${s.auth.password}`).toString("base64");v.use((y,c,b)=>{if((y.headers?.authorization??"")!==d){c.status(401).set("WWW-Authenticate",`Basic realm="${l}"`).set("Content-Type","text/plain").send("Unauthorized");return}b();});}return v.get(`${a}/`,(l,d)=>{let y=L(l,a,R),c=O.map(f=>{let w=[];h.healthCheck&&w.push(`<a class="btn" href="${y}/${f.name}/health">Health</a>`),h.manualSync&&w.push(`<a class="btn btn-primary" href="${y}/${f.name}/force-sync">Force Sync</a>`);let S=f.adapters.map(C=>`<span class="badge badge-ok">${C.name}</span>`).join(" ");return `<tr>
|
|
32
32
|
<td><strong>${f.name}</strong></td>
|
|
33
33
|
<td>${f.tableName}</td>
|
|
34
34
|
<td>${S||'<span class="badge badge-warn">none</span>'}</td>
|
|
35
35
|
<td>${f.isGroup?'<span class="badge badge-warn">group</span>':'<span class="badge badge-ok">collection</span>'}</td>
|
|
36
36
|
<td>${f.schema?"\u2713":"\u2717"}</td>
|
|
37
|
-
<td>${
|
|
37
|
+
<td>${w.join(" ")}</td>
|
|
38
38
|
</tr>`}).join(`
|
|
39
|
-
`),
|
|
39
|
+
`),b=h.configCheck?`<p style="margin-top:.5rem"><a class="btn" href="${y}/config-check">\u2699 Config Check</a></p>`:"",A=B("Sync Dashboard",y,`<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
42
|
<tbody>${c}</tbody>
|
|
43
43
|
</table>
|
|
44
|
-
${
|
|
45
|
-
</div>`);
|
|
46
|
-
`),j=
|
|
44
|
+
${b}
|
|
45
|
+
</div>`);q(d,A);}),v.get(`${a}`,(l,d)=>{let y=L(l,a,R);d.status(302).set("Location",`${y}/`).send("");}),h.healthCheck&&v.get(`${a}/:repoName/health`,async(l,d)=>{let y=L(l,a,R),c=O.find(S=>S.name===l.params.repoName);if(!c){q(d,B("Not Found",y,`<p>Unknown repo: ${l.params.repoName}</p>`),404);return}let b=[];for(let S of c.adapters)if(typeof S.healthCheck=="function"){let C=await S.healthCheck({targetName:c.tableName,primaryKey:c.documentKey,schema:c.schema??void 0,repoConfig:c.repoCfg});b.push({adapterName:S.name,health:C});}else try{let C=await S.targetExists(c.tableName);b.push({adapterName:S.name,health:{healthy:C,targetName:c.tableName,targetExists:C,error:C?null:`Target "${c.tableName}" does not exist`}});}catch(C){b.push({adapterName:S.name,health:{healthy:false,targetName:c.tableName,targetExists:false,error:C?.message??String(C)}});}let A=b.length>0&&b.every(S=>S.health.healthy);if(X(l)){Q(d,{repo:c.name,targetName:c.tableName,healthy:A,adapters:b.map(S=>({name:S.adapterName,...S.health}))});return}let f=S=>{let{adapterName:C,health:M}=S,z=M.healthy?'<span class="badge badge-ok">Healthy</span>':'<span class="badge badge-err">Unhealthy</span>',I="",p=M.details;if(p?.expected&&Array.isArray(p.expected)){let g=p.expected,E=new Set(p.actual??[]),T=p.extra??[],N=g.map(_=>{let U=E.has(_.name)?'<span class="badge badge-ok">OK</span>':'<span class="badge badge-err">MISSING</span>';return `<tr><td>${_.name}</td><td>${_.type}</td><td>${_.nullable?"Yes":"No"}</td><td>${_.isPrimaryKey?"\u2713":""}</td><td>${U}</td></tr>`}).join(`
|
|
46
|
+
`),j=T.map(_=>`<tr><td>${_}</td><td colspan="3" class="muted">not in schema</td><td><span class="badge badge-warn">EXTRA</span></td></tr>`).join(`
|
|
47
47
|
`);I=`<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>${
|
|
51
|
-
</table>`;}else
|
|
50
|
+
<tbody>${N}${j}</tbody>
|
|
51
|
+
</table>`;}else p?.numberOfDocuments!==void 0&&(I=`<h2>Index Stats</h2>
|
|
52
52
|
<table>
|
|
53
|
-
<tr><th>Documents Count</th><td>${
|
|
54
|
-
<tr><th>Indexing in Progress</th><td>${
|
|
55
|
-
<tr><th>Primary Key</th><td><code>${
|
|
53
|
+
<tr><th>Documents Count</th><td>${p.numberOfDocuments}</td></tr>
|
|
54
|
+
<tr><th>Indexing in Progress</th><td>${p.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>${p.primaryKey??"default"}</code></td></tr>
|
|
56
56
|
</table>`);return `<div class="card" style="margin-top:1rem">
|
|
57
|
-
<h2>Adapter: <code>${C}</code> ${
|
|
57
|
+
<h2>Adapter: <code>${C}</code> ${z}</h2>
|
|
58
58
|
<p>Target: <code>${M.targetName}</code> ${M.targetExists?"":'<span class="badge badge-err">NOT FOUND</span>'}</p>
|
|
59
59
|
${M.error?`<p class="badge badge-err" style="margin-top:.5rem">Error: ${M.error}</p>`:""}
|
|
60
60
|
${I}
|
|
61
|
-
</div>`},
|
|
62
|
-
<p>Overall status for <strong>${c.name}</strong>: ${
|
|
61
|
+
</div>`},w=B(`Health: ${c.name}`,y,`<div class="card">
|
|
62
|
+
<p>Overall status for <strong>${c.name}</strong>: ${A?'<span class="badge badge-ok">Healthy</span>':'<span class="badge badge-err">Issues detected</span>'}</p>
|
|
63
63
|
</div>
|
|
64
|
-
${
|
|
65
|
-
`)}`);
|
|
64
|
+
${b.map(f).join(`
|
|
65
|
+
`)}`);q(d,w);}),h.manualSync&&(v.get(`${a}/:repoName/force-sync`,(l,d)=>{let y=L(l,a,R),c=O.find(A=>A.name===l.params.repoName);if(!c){q(d,B("Not Found",y,`<p>Unknown repo: ${l.params.repoName}</p>`),404);return}let b=B(`Force Sync: ${c.name}`,y,`<div class="card">
|
|
66
66
|
<p>This will read <strong>all</strong> documents from the <code>${c.name}</code> Firestore collection
|
|
67
|
-
and upsert them into all active target storage adapters (${c.adapters.map(
|
|
67
|
+
and upsert them into all active target storage adapters (${c.adapters.map(A=>A.name).join(", ")}).</p>
|
|
68
68
|
<p class="muted" style="margin:.75rem 0">This may take a while for large collections.</p>
|
|
69
|
-
<form method="POST" action="${
|
|
69
|
+
<form method="POST" action="${y}/${c.name}/force-sync">
|
|
70
70
|
<button type="submit" class="btn btn-primary">Start Force Sync</button>
|
|
71
71
|
</form>
|
|
72
|
-
</div>`);
|
|
73
|
-
<p class="badge badge-err">Error: ${
|
|
74
|
-
<p>Synced ${
|
|
75
|
-
</div>`),500);return}if(
|
|
76
|
-
<pre style="white-space:pre-wrap">${
|
|
72
|
+
</div>`);q(d,b);}),v.post(`${a}/:repoName/force-sync`,async(l,d)=>{let y=L(l,a,R),c=O.find(p=>p.name===l.params.repoName);if(!c){Q(d,{error:`Unknown repo: ${l.params.repoName}`},404);return}let b=c.repo.ref;if(!b){Q(d,{error:`No collection reference for "${c.name}"`},400);return}let A=0,f=0,w=[],S=500,C=b.limit(S),M=null;try{for(;;){let g=await(M?C.startAfter(M):C).get();if(g.empty)break;for(let E of g.docs){let T=E.data(),N=String(T[c.documentKey]??E.id),j=K(T,{exclude:c.repoCfg?.exclude,columnMap:c.repoCfg?.columnMap,flat:c.repoCfg?.flat,transformDoc:c.repoCfg?.transformDoc});try{await r({operation:"UPSERT",repoName:c.name,docId:N,data:j,timestamp:new Date().toISOString()}),A++;}catch(_){f++;let U=_?.message??String(_);console.error(`[ForceSync:${c.name}] doc=${N} failed:`,_),w.length<5&&w.push(`${N}: ${U}`);}}if(M=g.docs[g.docs.length-1],g.docs.length<S)break}for(let p of c.adapters){let g=`${c.name}:${p.name}`,E=t.get(g)??t.get(c.name);E&&await E.flush();}}catch(p){if(X(l)){Q(d,{error:p?.message??String(p),synced:A,errors:f},500);return}q(d,B(`Force Sync: ${c.name}`,y,`<div class="card">
|
|
73
|
+
<p class="badge badge-err">Error: ${p?.message??String(p)}</p>
|
|
74
|
+
<p>Synced ${A} docs before failure (${f} errors).</p>
|
|
75
|
+
</div>`),500);return}if(X(l)){Q(d,{repo:c.name,table:c.tableName,synced:A,errors:f,...w.length>0&&{errorSamples:w}});return}let z=w.length>0?`<details style="margin-top:1rem"><summary>First ${w.length} error(s)</summary>
|
|
76
|
+
<pre style="white-space:pre-wrap">${w.map(p=>p.replace(/[<>&]/g,g=>`&#${g.charCodeAt(0)};`)).join(`
|
|
77
77
|
|
|
78
|
-
`)}</pre></details>`:"",I=
|
|
78
|
+
`)}</pre></details>`:"",I=B(`Force Sync: ${c.name}`,y,`<div class="card">
|
|
79
79
|
<p class="badge ${f>0?"badge-warn":"badge-ok"}">${f>0?"Completed with errors":"Complete"}</p>
|
|
80
|
-
<p>Synced <strong>${
|
|
80
|
+
<p>Synced <strong>${A}</strong> documents to targets (${c.adapters.map(p=>p.name).join(", ")}).</p>
|
|
81
81
|
${f>0?`<p class="badge badge-warn">${f} error(s)</p>`:""}
|
|
82
|
-
${
|
|
83
|
-
</div>`);
|
|
84
|
-
<td>${
|
|
85
|
-
<td><strong>${
|
|
82
|
+
${z}
|
|
83
|
+
</div>`);q(d,I);})),h.configCheck&&v.get(`${a}/config-check`,async(l,d)=>{let y=L(l,a,R),c=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??process.env.GCP_PROJECT??"unknown",b="https://console.cloud.google.com",A=u??"firestore-sync",f=[];for(let p of x)if(p.name==="bigquery")try{await p.targetExists("__nonexistent_health_check__"),f.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable"});}catch(g){let E=g?.message??String(g),T=E.toLowerCase(),N=T.includes("disabled")||T.includes("has not been used")||T.includes("accessnotconfigured"),j=T.includes("permission")||E.includes("403")||T.includes("access denied"),_=T.includes("project")&&T.includes("not found"),U=T.includes("not found")||E.includes("404");N?f.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:`${b}/apis/library/bigquery.googleapis.com?project=${c}`}}):_?f.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:`${b}/home/dashboard`}}):j?f.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:`${b}/iam-admin/iam?project=${c}`}}):U?f.push({name:"BigQuery Dataset",category:"bigquery",status:"error",message:`Dataset not found: ${E}`,fix:{hint:"Create the dataset first",gcloud:`bq mk --dataset ${c}:YOUR_DATASET_ID`,console:`${b}/bigquery?project=${c}`}}):f.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable (table lookup returned expected error)"});}else if(p.name==="meilisearch"||typeof p.checkConnection=="function")try{let g=typeof p.checkConnection=="function"?await p.checkConnection():{healthy:await p.targetExists("__nonexistent__")};f.push({name:"Meilisearch API",category:"meilisearch",status:g.healthy?"ok":"error",message:g.healthy?`Meilisearch is reachable${g.version?` (v${g.version})`:""}`:`Meilisearch connection error: ${g.error??"unknown"}`,...g.error&&{fix:{hint:"Ensure Meilisearch is running and host/apiKey options are valid."}}});}catch(g){f.push({name:"Meilisearch API",category:"meilisearch",status:"error",message:`Meilisearch error: ${g?.message??String(g)}`});}for(let p of O)for(let g of p.adapters){let E=g.name==="bigquery"?"bigquery":g.name==="meilisearch"?"meilisearch":"storage";try{let T=await g.targetExists(p.tableName);f.push({name:`[${g.name}] Target: ${p.tableName}`,category:E,status:T?"ok":"warn",message:T?`Target \`${p.tableName}\` exists`:`Target \`${p.tableName}\` does not exist yet`,...!T&&{fix:{hint:"Target will be auto-created on first sync if autoMigrate is enabled."}}});}catch(T){f.push({name:`[${g.name}] Target: ${p.tableName}`,category:E,status:"error",message:T?.message??String(T)});}}if(i)for(let p of O){let g=`${A}-${p.name}`;try{let E=i.topic(g);if(typeof E.exists=="function"){let[T]=await E.exists();f.push({name:`Topic: ${g}`,category:"pubsub",status:T?"ok":"error",message:T?`Topic \`${g}\` exists`:`Topic \`${g}\` does not exist`,...!T&&{fix:{gcloud:`gcloud pubsub topics create ${g} --project=${c}`,console:`${b}/cloudpubsub/topic/list?project=${c}`}}});}else f.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=${c}`,console:`${b}/cloudpubsub/topic/list?project=${c}`}});}catch(E){let T=E?.message??String(E),N=T.includes("disabled")||T.includes("has not been used");if(f.push({name:N?"Pub/Sub API":`Topic: ${g}`,category:"pubsub",status:"error",message:N?"Pub/Sub API is not enabled":T,fix:N?{gcloud:`gcloud services enable pubsub.googleapis.com --project=${c}`,console:`${b}/apis/library/pubsub.googleapis.com?project=${c}`}:{gcloud:`gcloud pubsub topics create ${g} --project=${c}`,console:`${b}/cloudpubsub/topic/list?project=${c}`}}),N)break}}else f.push({name:"Pub/Sub Client",category:"pubsub",status:"warn",message:"PubSub client not available for config check"});if(X(l)){let p=f.every(g=>g.status==="ok");Q(d,{project:c,healthy:p,checks:f});return}let w=p=>p==="ok"?'<span class="badge badge-ok">OK</span>':p==="warn"?'<span class="badge badge-warn">WARN</span>':'<span class="badge badge-err">ERROR</span>',S={bigquery:f.filter(p=>p.category==="bigquery"),meilisearch:f.filter(p=>p.category==="meilisearch"),pubsub:f.filter(p=>p.category==="pubsub"),firestore:f.filter(p=>p.category==="firestore"),storage:f.filter(p=>p.category==="storage")},C=(p,g)=>{if(g.length===0)return "";let E=g.map(T=>{let N="";if(T.fix){let j=[];T.fix.hint&&j.push(`<p class="muted">${T.fix.hint}</p>`),T.fix.gcloud&&j.push(`<pre>$ ${T.fix.gcloud}</pre>`),T.fix.console&&j.push(`<p><a href="${T.fix.console}" target="_blank">Open GCP Console \u2192</a></p>`),N=`<div style="margin-top:.5rem">${j.join("")}</div>`;}return `<tr>
|
|
84
|
+
<td>${w(T.status)}</td>
|
|
85
|
+
<td><strong>${T.name}</strong><br><span class="muted">${T.message}</span>${N}</td>
|
|
86
86
|
</tr>`}).join(`
|
|
87
|
-
`);return `<h2>${
|
|
87
|
+
`);return `<h2>${p}</h2>
|
|
88
88
|
<table><thead><tr><th style="width:80px">Status</th><th>Check</th></tr></thead>
|
|
89
|
-
<tbody>${E}</tbody></table>`},
|
|
90
|
-
<p>Project: <code>${c}</code> ${
|
|
89
|
+
<tbody>${E}</tbody></table>`},z=f.every(p=>p.status==="ok")?'<span class="badge badge-ok">All checks passed</span>':'<span class="badge badge-warn">Some issues found</span>',I=B("Config Check",y,`<div class="card">
|
|
90
|
+
<p>Project: <code>${c}</code> ${z}</p>
|
|
91
91
|
${C("BigQuery",S.bigquery)}
|
|
92
92
|
${C("Meilisearch",S.meilisearch)}
|
|
93
93
|
${C("Pub/Sub",S.pubsub)}
|
|
94
94
|
${C("Other Targets",S.storage)}
|
|
95
95
|
${C("Firestore",S.firestore)}
|
|
96
|
-
</div>`);
|
|
96
|
+
</div>`);q(d,I);}),async(l,d)=>{await v.handle(l,d);}}var je="firestore-sync";function Fe(n,e){return e?`${e}/{docId}`:(console.warn(`[SyncTriggers] Cannot determine collection path for "${n}". Skipping.`),null)}function ze(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 Le(n){return {isGroup:!!n?._isGroup,documentKey:n?._systemKeys?.[0]??"docId",collectionPath:n?.ref?.path??null}}function ce(n,e){let{onDocumentWritten:t}=e.deps.firestoreTriggers,r=e.deps.pubsub,s=e?.topicPrefix??je,o={},i=new Map;function u(k){let m=i.get(k);return m||(m=r.topic(k),i.set(k,m),m)}async function a(k,m){await u(k).publishMessage({json:m});}let h=n?.rawMapping,R=h?Object.entries(h).map(([k,m])=>[k,ze(m)]):Object.entries(n).map(([k,m])=>[k,Le(m)]),x=e?.repos,O=Object.keys(x??{}).length>0;for(let[k,m]of R){if(O&&(!x||!(k in x)))continue;let D=x?.[k],$;if(m.isGroup){if(!D?.triggerPath){console.warn(`[SyncTriggers] Skipping collection-group repo "${k}". Provide a triggerPath in the sync repos config for group collections.`);continue}$=D.triggerPath;}else $=D?.triggerPath??Fe(k,m.collectionPath);if(!$)continue;let v=m.documentKey,l=`${s}-${k}`;o[`${k}_onSync`]=t($,async d=>{let y=d.data?.before,c=d.data?.after;if(!y&&!c)return;let b=!!y?.exists,A=!!c?.exists;if(!b&&A){let f=c.data();if(!f)return;let w=String(f[v]??c.id),S=K(f,{exclude:D?.exclude,columnMap:D?.columnMap,flat:D?.flat,transformDoc:D?.transformDoc}),C={operation:"INSERT",repoName:k,docId:w,data:S,timestamp:new Date().toISOString(),version:Date.now()};await a(l,C);}else if(b&&A){let f=c.data();if(!f)return;let w=String(f[v]??c.id),S=K(f,{exclude:D?.exclude,columnMap:D?.columnMap,flat:D?.flat,transformDoc:D?.transformDoc}),C={operation:"UPSERT",repoName:k,docId:w,data:S,timestamp:new Date().toISOString(),version:Date.now()};await a(l,C);}else if(b&&!A){let f=y.data(),w=String(f?.[v]??y.id),S={operation:"DELETE",repoName:k,docId:w,data:null,timestamp:new Date().toISOString(),version:Date.now()};await a(l,S);}});}return o}var H="__sync_version";var Be={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 ee(n){let e=n,t=e._zod?.def?.type;if(t)return Be[t]??`Zod${t.charAt(0).toUpperCase()}${t.slice(1)}`;let r=e._def?.typeName;return r||""}function Se(n){let e=n;if(e._zod?.def?.innerType)return e._zod.def.innerType;if(e._def?.innerType)return e._def.innerType}function ue(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 qe=new Set(["ZodOptional","ZodNullable","ZodDefault"]);function Te(n){let e=n,t=false;for(;;){let r=ee(e);if(!qe.has(r))break;(r==="ZodOptional"||r==="ZodNullable")&&(t=true);let s=Se(e);if(!s)break;e=s;}return {inner:e,nullable:t}}var xe={ZodString:"string",ZodNumber:"number",ZodBigInt:"bigint",ZodBoolean:"boolean",ZodDate:"timestamp",ZodEnum:"string",ZodNativeEnum:"string",ZodLiteral:"string"};function Ke(n){let{inner:e}=Te(n);return xe[ee(e)]??"json"}function Re(n,e,t,r,s,o,i,u){for(let[a,h]of Object.entries(n)){let R=t?`${t}__${a}`:a;if(s.has(a)||s.has(R))continue;let{inner:x,nullable:P}=Te(h),O=ee(x),k=r||P;if(O==="ZodObject"){let v=ue(x);Re(v,e,R,k,s,o,i,u);continue}let m=xe[O]??"json",D=R===i||a===i,$=o[R]??o[a]??R;u.push({name:$,sqlType:e.mapType(m),nullable:D?false:k,isPrimaryKey:D});}}function F(n,e,t={}){let{primaryKey:r,exclude:s=[],columnMap:o={}}=t,i=new Set(s),u=ue(n),a=[];return Re(u,e,"",false,i,o,r,a),a.some(h=>h.name===H)||a.push({name:H,sqlType:e.mapType("bigint"),nullable:true,isPrimaryKey:false,description:"Monotonic publish version (Date.now() ms). Internal."}),a}function te(n){let e=n.toUpperCase();switch(e){case "INTEGER":return "INT64";case "FLOAT":return "FLOAT64";case "BOOLEAN":return "BOOL";default:return e}}function ke(n,e){let t=te(n),r=te(e);return t===r?true:{INT64:["NUMERIC","BIGNUMERIC","FLOAT64"],NUMERIC:["BIGNUMERIC","FLOAT64"],DATE:["DATETIME","TIMESTAMP"],DATETIME:["TIMESTAMP"]}[t]?.includes(r)??false}var le=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,"``")+"`"}},Ce=new le,ne=null;function Qe(){return ne||(ne=pe("@google-cloud/bigquery-storage"),ne)}function Ae(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 We(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 Ue(n,e=6,t=200){let r=0;for(;;)try{return await n()}catch(s){if(r++,!We(s)||r>e)throw s;let o=t*Math.pow(2,r),i=Math.random()*o;await new Promise(u=>setTimeout(u,i));}}var Z=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";}},W=class W{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 Ce}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,u=F(s,this.dialect,{primaryKey:r,exclude:o,columnMap:i});if(!await this.tableExists(t))await this.createTable({tableName:t,columns:u});else {let h=await this.getTableColumnsWithTypes(t),R=[];for(let x of u){let P=h.get(x.name);if(P===void 0){R.push(x);continue}if(!ke(P,x.sqlType))throw new Z(t,x.name,P,x.sqlType)}R.length>0&&(await this.addColumns(t,R),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 u=await this.getTableColumns(t),a=F(s,this.dialect,{primaryKey:r,exclude:o?.exclude,columnMap:o?.columnMap}),h=new Set(u),R=new Set(a.map(m=>m.name)),x=a.filter(m=>!h.has(m.name)),P=u.filter(m=>!R.has(m)),O=a.filter(m=>h.has(m.name)),k=x.length===0;return {healthy:k,targetName:t,targetExists:!0,error:k?null:`Missing columns: ${x.map(m=>m.name).join(", ")}`,details:{expected:a.map(m=>({name:m.name,type:m.sqlType,nullable:m.nullable,isPrimaryKey:m.isPrimaryKey})),actual:u,matched:O.map(m=>m.name),missing:x.map(m=>({name:m.name,type:m.sqlType})),extra:P}}}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,te(o.type));return s}async createTable(e){let t=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 h=a.isPrimaryKey?" NOT NULL":"";return ` ${t(a.name)} ${a.sqlType}${h}`}).join(`,
|
|
97
97
|
`),o=[];this.maxStaleness!==null&&o.push(`max_staleness = ${this.maxStaleness}`);let i=o.length>0?`
|
|
98
98
|
OPTIONS(${o.join(", ")})`:"",u=`CREATE TABLE IF NOT EXISTS ${this.fqn(e.tableName)} (
|
|
99
99
|
${s},
|
|
100
100
|
PRIMARY KEY (${t(r)}) NOT ENFORCED
|
|
101
101
|
)
|
|
102
|
-
CLUSTER BY ${t(r)}${i};`;await this.bigquery.query({query:u});}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:
|
|
102
|
+
CLUSTER BY ${t(r)}${i};`;await this.bigquery.query({query:u});}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:Ae(i[H])}));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(u=>({...this.normalizeRow(u,o),_CHANGE_TYPE:"UPSERT",_CHANGE_SEQUENCE_NUMBER:Ae(u[H])}));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]=W.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]=W.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):W.ISO_TIMESTAMP_RE.test(t)}async appendWithRetry(e,t,r){await Ue(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=Qe();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 u=s.adapt.convertBigQuerySchemaToStorageTableSchema(i),a=s.adapt.convertStorageSchemaToProto2Descriptor(u,"Row",s.adapt.withChangeType(),s.adapt.withChangeSequenceNumber()),h=new Set(i.fields.filter(O=>["TIMESTAMP","DATETIME","DATE"].includes(String(O.type??"").toUpperCase())).map(O=>O.name)),R=`projects/${this.projectId}/datasets/${this.datasetId}/tables/${e}`,x=await this.writerClient.createStreamConnection({streamId:s.managedwriter.DefaultStream,destinationTable:R}),P=new s.managedwriter.JSONWriter({connection:x,protoDescriptor:a});return this.writers.set(e,{writer:P,primaryKey:t??"",timestampColumns:h}),P}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{}}};W.ISO_TIMESTAMP_RE=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/;var de=W;var G=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 u=Number(i[H]??0);Number(o.data[H]??0)>=u&&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 Ee=new Set;async function Ze(n,e,t,r,s,o,i){let u=`${n}:${e.name}`;if(!Ee.has(u)){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 a=e,h=F(t,a.dialect,{primaryKey:s,exclude:o,columnMap:i});if(!await a.tableExists(r))await a.createTable({tableName:r,columns:h});else {let x=new Set(await a.getTableColumns(r)),P=h.filter(O=>!x.has(O.name));P.length>0&&(await a.addColumns(r,P),await a.onSchemaChange?.(r));}}Ee.add(u);}}function fe(n,e){let{deps:t,adapter:r,adapters:s,batchSize:o=100,flushIntervalMs:i=5e3,autoMigrate:u=false,topicPrefix:a="firestore-sync",maxDlqAttempts:h=5,workerOptions:R,repos:x={}}=e,O=(s||(Array.isArray(r)?r:r?[r]:[])).map(l=>typeof l=="function"?l():l);function k(l){let d=x[l];if(d?.adapters&&d.adapters.length>0){let y=new Set(d.adapters);return O.filter(c=>y.has(c.name))}return O}let m=new Map;function D(l,d,y){let c=`${l}:${d.name}`,b=m.get(c);if(b)return b;let f=x[l]?.tableName??l,w=`${a}-${l}-${d.name}-dlq`,S=t.pubsub.topic(w),C=false,M=async()=>{if(!C){try{await S.create(),console.info(`[SyncWorker:${d.name}] Created DLQ topic "${w}"`);}catch(I){if(I?.code!==6)throw I}C=true;}},z=async(I,p)=>{console.error(`[SyncWorker:${d.name}] Flush failed for "${l}" (${I.length} events):`,p),await M(),await Promise.all(I.map(g=>{let E=(g.attempts??0)+1;if(h>0&&E>h)return console.error(`[SyncWorker:${d.name}] Dropping event for "${l}" after ${E-1} DLQ attempts:`,{docId:g.docId,operation:g.operation}),Promise.resolve();let T={...g,attempts:E,firstFailedAt:g.firstFailedAt??Date.now()};return S.publishMessage({json:T})}));};return b=new G({adapter:d,tableName:f,primaryKey:y,batchSize:o,flushIntervalMs:i,onFlushError:z}),m.set(c,b),m.has(l)||m.set(l,b),b}async function $(l){let{repoName:d}=l,y=n[d];if(!y){console.warn(`[SyncWorker] Unknown repo "${d}", skipping event`);return}let c=y._systemKeys?.[0]??y.documentKey??"docId",b=x[d],A=b?.columnMap,f=A?.[c]??c;l.data&&(l.data[H]=l.version??Date.now());let w=k(d);for(let S of w){if(u){let M=y.schema??void 0;if(M){let z=b?.tableName??d;await Ze(d,S,M,z,f,b?.exclude,A);}}D(d,S,f).enqueue(l);}}function v(l){let d=async y=>{let c=y.data?.message?.json??y.data?.json;if(!c){console.warn("[SyncWorker] Received empty PubSub message");return}await $(c);let b=k(c.repoName);for(let A of b){let f=`${c.repoName}:${A.name}`,w=m.get(f);w&&await w.flush();}};return R?t.pubsubHandler.onMessagePublished({topic:l,...R},d):t.pubsubHandler.onMessagePublished(l,d)}return {handleMessage:$,createHandler:v,queues:m,async shutdown(){let l=[],d=new Set;for(let y of m.values())d.has(y)||(d.add(y),l.push(y.shutdown()));await Promise.all(l);}}}var Ge="firestore-sync";function Pe(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 Ve(n,e){let{deps:t,adapter:r,adapters:s,topicPrefix:o=Ge,batchSize:i,flushIntervalMs:u,autoMigrate:a,admin:h,workerOptions:R,repos:x}=e,P=Pe(t.pubsub),k=(s||(Array.isArray(r)?r:r?[r]:[])).map(w=>Pe(w)),m=ce(n,{deps:{firestoreTriggers:t.firestoreTriggers,pubsub:P},topicPrefix:o,repos:x}),D=fe(n,{deps:{pubsubHandler:t.pubsubHandler,pubsub:P},adapters:k,batchSize:i,flushIntervalMs:u,autoMigrate:a,topicPrefix:o,workerOptions:R,repos:x}),$={},v=x,l=n?.rawMapping,d=Object.keys(v??{}),y=d.length>0,c=Object.keys(l||n),b=y?d.filter(w=>c.includes(w)||w in n):c;for(let w of b){let S=n?.rawMapping,C=S?!!S[w]?.isGroup:!!n[w]?._isGroup;!y&&C&&!v?.[w]?.triggerPath||($[`sync_${w}`]=D.createHandler(`${o}-${w}`));}let A=null;h&&(A=ae(n,k,D.queues,D.handleMessage,h,x??{},P,o),$.adminsync=h.onRequest?h.httpsOptions?h.onRequest(h.httpsOptions,A):h.onRequest(A):A);let f={functions:{...m,...$},adminHandler:A,handleMessage:D.handleMessage,queues:D.queues,shutdown:D.shutdown};for(let w of ["adminHandler","handleMessage","queues","shutdown"])Object.defineProperty(f,w,{enumerable:false});return f}function Oe(n,e){let t=e.columns.map(r=>{let s=r.isPrimaryKey?" NOT NULL":"";return ` ${n.quoteIdentifier(r.name)} ${r.sqlType}${s}`}).join(`,
|
|
103
103
|
`);return `CREATE TABLE IF NOT EXISTS ${n.quoteIdentifier(e.tableName)} (
|
|
104
104
|
${t}
|
|
105
|
-
);`}function
|
|
106
|
-
`)}function
|
|
105
|
+
);`}function Je(n,e,t){return t.map(r=>`ALTER TABLE ${n.quoteIdentifier(e)} ADD COLUMN ${n.quoteIdentifier(r.name)} ${r.sqlType};`).join(`
|
|
106
|
+
`)}function Ye(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 u=t?.repos?.[s],a=u?.tableName??s,h=o._systemKeys?.[0]??o.documentKey??"docId",R=F(i,e,{primaryKey:h,exclude:u?.exclude,columnMap:u?.columnMap}),x={tableName:a,columns:R};r.push(Oe(e,x));}return r.join(`
|
|
107
107
|
|
|
108
|
-
`)}async function
|
|
108
|
+
`)}async function Xe(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 u=t?.repos?.[s],a=u?.tableName??s,h=o._systemKeys?.[0]??o.documentKey??"docId",R=F(i,e.dialect,{primaryKey:h,exclude:u?.exclude,columnMap:u?.columnMap}),x={tableName:a,columns:R};if(!await e.tableExists(a))await e.createTable(x),r.created.push(a);else {let O=new Set(await e.getTableColumns(a)),k=R.filter(m=>!O.has(m.name));k.length>0?(await e.addColumns(a,k),r.altered.push(a)):r.upToDate.push(a);}}return r}function et(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}=pe("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
109
|
bun add meilisearch # or npm install meilisearch
|
|
110
|
-
Original error: ${e?.message??String(e)}`)}}var
|
|
110
|
+
Original error: ${e?.message??String(e)}`)}}var re=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=et(this.options)),this._client}async targetExists(e){try{return await this.client.getIndex(e),!0}catch(t){if(t?.code==="index_not_found"||t?.cause?.code==="index_not_found"||t?.statusCode===404||t?.status===404||t?.response?.status===404||t?.cause?.status===404||t?.cause?.statusCode===404||t?.cause?.response?.status===404)return false;throw t}}async upsert(e,t,r){if(t.length===0)return;let s=this.options.unflatten!==false,o=t.map(u=>{let a=s?ie(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,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)}}}};function tt(n){return ()=>new re(n)}exports.BigQueryAdapter=de;exports.MeilisearchAdapter=re;exports.SchemaTypeMismatchError=Z;exports.SyncQueue=G;exports.addColumnsDDL=Je;exports.autoMigrate=Xe;exports.bigqueryDialect=Ce;exports.createFirestoreSync=Ve;exports.createSyncTriggers=ce;exports.createSyncWorker=fe;exports.createTableDDL=Oe;exports.createadminsyncServer=ae;exports.defineMeilisearchAdapter=tt;exports.generateDDL=Ye;exports.serializeDocument=K;exports.serializeValue=Y;exports.unflattenDocument=ie;exports.zodSchemaToColumns=F;exports.zodTypeToLogical=Ke;//# sourceMappingURL=index.cjs.map
|
|
111
111
|
//# sourceMappingURL=index.cjs.map
|