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