@lpdjs/firestore-repo-service 3.0.20 → 3.0.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import {jsx,jsxs,Fragment}from'hono/jsx/jsx-runtime';import {Timestamp,FieldPath}from'firebase-admin/firestore';import {AsyncLocalStorage}from'async_hooks';import {randomUUID,randomBytes}from'crypto';import {z}from'zod';import {renderToString}from'hono/jsx/dom/server';import {extendZodWithOpenApi,OpenAPIRegistry,OpenApiGeneratorV31,getOpenApiMetadata}from'@asteasolutions/zod-to-openapi';import {Hono}from'hono';import {getRequestListener}from'@hono/node-server';var Hn=Object.defineProperty;var Bs=Object.getOwnPropertyDescriptor;var zs=Object.getOwnPropertyNames;var qs=Object.prototype.hasOwnProperty;var Lr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var xt=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Kr=(e,t)=>{for(var n in t)Hn(e,n,{get:t[n],enumerable:true});},Us=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of zs(t))!qs.call(e,o)&&o!==n&&Hn(e,o,{get:()=>t[o],enumerable:!(r=Bs(t,o))||r.enumerable});return e};var Ls=e=>Us(Hn({},"__esModule",{value:true}),e);function J(e){let t=e,n=t._zod?.def?.type;if(n)return Va[n]??`Zod${n.charAt(0).toUpperCase()}${n.slice(1)}`;let r=t._def?.typeName;return r||""}function ye(e){let t=e;if(t._zod?.def?.innerType)return t._zod.def.innerType;if(t._def?.innerType)return t._def.innerType}function Dt(e){let t=e,n=t._zod?.def?.in;if(n)return n;if(t._def?.schema)return t._def.schema}function un(e){let t=e;if(t._zod?.def?.element)return t._zod.def.element;if(t._def?.type)return t._def.type}function Oo(e){let t=e;if(t._zod?.def?.defaultValue!==void 0)return t._zod.def.defaultValue;let n=t._def?.defaultValue;return typeof n=="function"?n():n}function me(e){let t=e;return t.shape&&typeof t.shape=="object"?t.shape:t._zod?.def?.shape&&typeof t._zod.def.shape=="object"?t._zod.def.shape:t._def?.shape?typeof t._def.shape=="function"?t._def.shape():t._def.shape:{}}function $t(e){let t=e;return Array.isArray(t.options)?t.options:t._zod?.def?.entries?Object.values(t._zod.def.entries):Array.isArray(t._def?.values)?t._def.values:[]}function Ht(e){let t=e;return t._zod?.def?.entries?t._zod.def.entries:t.enum&&typeof t.enum=="object"?t.enum:t._def?.values&&typeof t._def.values=="object"?t._def.values:{}}function Mt(e){let t=e;return Array.isArray(t._zod?.def?.values)?t._zod.def.values[0]:t._def?.value}function _t(e){let t=e;return Array.isArray(t.options)?t.options:Array.isArray(t._zod?.def?.options)?t._zod.def.options:Array.isArray(t._def?.options)?t._def.options:[]}function Po(e){let t=e,n=[],r=t._zod?.def?.checks;if(Array.isArray(r)){for(let s of r)s.format&&n.push(s.format);if(n.length>0)return n}let o=t._def?.checks;if(Array.isArray(o))for(let s of o)s.kind&&n.push(s.kind);return n}var Va,ut=xt(()=>{"use strict";Va={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 Zo({val:e}){return jsx("span",{class:"text-sm text-base-content/80 font-mono tabular-nums whitespace-nowrap",children:e.toLocaleString()})}function gi({message:e}){return jsx("span",{class:"tooltip tooltip-warning tooltip-right inline-flex align-middle ml-1 text-warning","data-tip":e,role:"img","aria-label":e,children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",class:"size-3.5",children:jsx("path",{d:"M12 2 1 22h22L12 2zm0 6 7.5 13h-15L12 8zm-1 4v4h2v-4h-2zm0 5v2h2v-2h-2z"})})})}function yt({val:e,mismatch:t}){let n=dr(e);return t?jsxs("span",{class:"inline-flex items-start gap-0.5",children:[n,jsx(gi,{message:t})]}):n}function dr(e){if(e==null)return jsx("span",{class:"opacity-30 italic text-xs",children:"\u2014"});if(typeof e=="boolean")return e?jsx("span",{class:"badge badge-success badge-sm",children:"true"}):jsx("span",{class:"badge badge-error badge-sm",children:"false"});if(e instanceof Date)return jsx(Zo,{val:e});if(typeof e=="object"&&e!==null&&typeof e.toDate=="function")return jsx(Zo,{val:e.toDate()});if(typeof e=="number")return jsx("span",{class:"text-sm font-mono tabular-nums",children:String(e)});if(Array.isArray(e))return e.length===0?jsx("span",{class:"text-xs text-base-content/30",children:"[]"}):jsxs("ul",{class:"list-none p-0 m-0 space-y-0.5 text-xs",children:[e.slice(0,8).map((n,r)=>jsx("li",{class:"break-all",children:dr(n)},r)),e.length>8&&jsxs("li",{class:"text-base-content/40 italic",children:["+",e.length-8," more\u2026"]})]});if(typeof e=="object"&&e!==null){let n=Object.entries(e);return n.length===0?jsx("span",{class:"text-xs text-base-content/30",children:"{}"}):jsxs("dl",{class:"grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5 text-xs m-0",children:[n.slice(0,8).map(([r,o])=>jsxs(Fragment,{children:[jsx("dt",{class:"text-base-content/50 font-semibold whitespace-nowrap",children:r}),jsx("dd",{class:"break-all",children:dr(o)})]})),n.length>8&&jsxs("dt",{class:"col-span-2 text-base-content/40 italic",children:["+",n.length-8," more\u2026"]})]})}let t=String(e);return jsx("span",{class:"text-sm break-all",children:t})}var wn=xt(()=>{"use strict";});function zt(e){if(!e)return "unknown";let t=ur(e);switch(J(t)){case "ZodString":return "string";case "ZodNumber":return "number";case "ZodBigInt":return "bigint";case "ZodBoolean":return "boolean";case "ZodDate":return "date";case "ZodArray":return "array";case "ZodObject":case "ZodRecord":return "object";case "ZodEnum":case "ZodNativeEnum":return "enum";case "ZodLiteral":return "literal";default:return "unknown"}}function ur(e){let t=J(e);if(t==="ZodOptional"||t==="ZodNullable"||t==="ZodDefault"){let n=ye(e);return n?ur(n):e}return e}function qt(e,t){if(!e)return;let n=t.split("."),r=e;for(let o of n){if(!r)return;let s=ur(r);if(J(s)!=="ZodObject")return;r=me(s)[o];}return r}function Ri(e){return e==null?"null":e instanceof Date?"date":Array.isArray(e)?"array":typeof e=="string"?"string":typeof e=="boolean"?"boolean":typeof e=="bigint"?"bigint":typeof e=="number"?"number":typeof e=="object"?typeof e.toDate=="function"?"date":"object":"unknown"}function Ut(e,t){if(e==="unknown")return null;let n=Ri(t);return n==="null"?null:e==="enum"||e==="literal"?n==="string"||n==="number"?null:`Expected ${e} (string/number), got ${n}`:e===n||e==="number"&&n==="bigint"||e==="bigint"&&n==="number"?null:`Expected ${e}, got ${n}`}var pr=xt(()=>{"use strict";ut();});var Vo={};Kr(Vo,{PanelMany:()=>vi,PanelOne:()=>Si,RightPanel:()=>fr});function Si({doc:e,repoName:t,basePath:n,schema:r,columns:o}){if(!e)return jsx("div",{class:"text-center py-12 text-base-content/50",children:"Document not found."});let s=String(e.docId??e.id??""),a=`${n}/${t}/${encodeURIComponent(s)}/edit`,l=Qo(r,o);return jsxs("div",{class:"space-y-4",children:[jsxs("div",{class:"flex items-center justify-between gap-2",children:[jsxs("div",{class:"text-xs text-base-content/60",children:[jsx("span",{class:"font-mono",children:t}),jsx("span",{class:"opacity-50",children:" \xB7 "}),jsx("span",{class:"font-mono break-all",children:s})]}),jsx("a",{href:a,class:"btn btn-sm btn-primary",children:"Edit \u2192"})]}),jsx("dl",{class:"grid grid-cols-[max-content_1fr] gap-x-4 gap-y-2 border border-base-300 rounded-box p-4 bg-base-100",children:o.map(c=>{let u=e[c],p=l[c],f=p?Ut(p,u):null;return jsxs(Fragment,{children:[jsx("dt",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide pt-0.5",children:c}),jsx("dd",{class:"min-w-0",children:jsx(yt,{val:u,mismatch:f})})]})})})]})}function vi({docs:e,repoName:t,basePath:n,fk:r,fv:o,columns:s,schema:a,pagination:l}){let c=`${n}/${t}?fv_${r}=${encodeURIComponent(o)}`,u=Qo(a,s);return jsxs("div",{class:"space-y-4",children:[jsxs("div",{class:"flex items-center justify-between gap-2",children:[jsxs("div",{class:"text-xs text-base-content/60",children:[jsx("span",{class:"font-mono",children:t}),jsx("span",{class:"opacity-50",children:" where "}),jsx("span",{class:"font-mono",children:r}),jsx("span",{class:"opacity-50",children:" = "}),jsx("span",{class:"font-mono break-all",children:o}),jsx("span",{class:"opacity-50",children:" \xB7 "}),jsxs("span",{children:[e.length," doc",e.length!==1?"s":""]})]}),jsx("a",{href:c,class:"btn btn-sm btn-outline",children:"Full view \u2192"})]}),jsx("div",{class:"overflow-x-auto rounded-box border border-base-300 bg-base-100",children:jsxs("table",{class:"table table-xs w-full",children:[jsx("thead",{children:jsxs("tr",{class:"bg-base-200/50",children:[s.map((p,f)=>jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:p},f)),jsx("th",{})]})}),jsx("tbody",{children:e.length===0?jsx("tr",{children:jsx("td",{colspan:s.length+1,class:"text-center py-10 text-base-content/40",children:"No related documents"})}):e.map((p,f)=>{let w=String(p.docId??p.id??""),h=`${n}/${t}/${encodeURIComponent(w)}/edit`;return jsxs("tr",{class:"hover",children:[s.map((b,T)=>{let S=p[b],I=u[b],C=I?Ut(I,S):null;return jsx("td",{class:"align-top py-1.5",children:jsx(yt,{val:S,mismatch:C})},T)}),jsx("td",{class:"text-right py-1.5",children:jsx("a",{href:h,class:"btn btn-xs btn-ghost",children:"Edit"})})]},f)})})]})}),(l.hasPrev||l.hasNext)&&jsxs("div",{class:"flex justify-center items-center gap-2",children:[l.hasPrev?jsx("button",{type:"button",class:"btn btn-xs btn-outline","data-frs-panel-page":"prev","data-cursor":l.prevCursor,children:"\u2190 Previous"}):jsx("button",{class:"btn btn-xs btn-outline",disabled:true,children:"\u2190 Previous"}),l.hasNext?jsx("button",{type:"button",class:"btn btn-xs btn-outline","data-frs-panel-page":"next","data-cursor":l.nextCursor,children:"Next \u2192"}):jsx("button",{class:"btn btn-xs btn-outline",disabled:true,children:"Next \u2192"})]})]})}function Qo(e,t){if(!e)return {};let n={};for(let r of t)n[r]=zt(qt(e,r));return n}var fr,yr=xt(()=>{"use strict";wn();pr();fr=({basePath:e=""})=>jsxs("div",{class:"fixed inset-0 z-[100] hidden pointer-events-none","data-frs-panel-root":!0,"data-frs-base-path":e,"aria-hidden":"true",children:[jsx("div",{class:"absolute inset-0 bg-black/30 opacity-0 transition-opacity duration-200 pointer-events-auto","data-frs-panel-backdrop":!0}),jsxs("aside",{class:"absolute top-0 right-0 h-full w-full md:w-1/2 bg-base-100 shadow-2xl border-l border-base-300 translate-x-full transition-transform duration-200 pointer-events-auto flex flex-col","data-frs-panel":!0,role:"dialog","aria-label":"Relation preview",children:[jsxs("header",{class:"flex items-center justify-between px-5 py-3 border-b border-base-300 bg-base-200/40 shrink-0",children:[jsx("h2",{class:"font-semibold text-base truncate","data-frs-panel-title":!0,children:"Relation"}),jsx("button",{type:"button",class:"btn btn-sm btn-ghost btn-circle","data-frs-panel-close":!0,"aria-label":"Close panel",children:"\u2715"})]}),jsx("div",{class:"flex-1 overflow-auto p-5 text-sm","data-frs-panel-body":!0,children:jsx("div",{class:"flex items-center justify-center py-12 text-base-content/40",children:jsx("span",{class:"loading loading-spinner loading-md"})})})]})]});});var ds={};Kr(ds,{DEFAULT_HTML_CSP:()=>Cr,securityHeaders:()=>vn});function vn(e={}){let t=e.csp===void 0?Cr:e.csp,n=e.frameOptions===void 0?"DENY":e.frameOptions,r=e.referrerPolicy===void 0?"no-referrer":e.referrerPolicy,o=e.cacheControl===void 0?"private, no-store":e.cacheControl;return async(s,a,l)=>{typeof a?.setHeader=="function"&&(a.setHeader("X-Content-Type-Options","nosniff"),n&&a.setHeader("X-Frame-Options",n),r&&a.setHeader("Referrer-Policy",r),o&&a.setHeader("Cache-Control",o),t&&a.setHeader("Content-Security-Policy",t)),await l();}}var cs,ls,Cr,Tn=xt(()=>{"use strict";cs="https://cdn.jsdelivr.net",ls="https://www.gstatic.com",Cr=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${cs} ${ls}`,`style-src 'self' 'unsafe-inline' ${cs}`,`connect-src 'self' ${ls} https://*.googleapis.com https://*.firebaseio.com https://identitytoolkit.googleapis.com`,"img-src 'self' data:","font-src 'self' data:","frame-ancestors 'none'","base-uri 'self'","form-action 'self'"].join("; ");});var Yt="__name__",Ks=new Set(["<","<=",">",">=","!=","not-in"]);var Zs=55296,Ws=57343;function Zr(e){return e>=Zs&&e<=Ws}function ct(e,t){let n=Math.min(e.length,t.length);for(let r=0;r<n;r++){let o=e.charCodeAt(r),s=t.charCodeAt(r);if(o!==s){let a=Zr(o),l=Zr(s);return a===l?o<s?-1:1:a?1:-1}}return e.length<t.length?-1:e.length>t.length?1:0}function Wr(e){return e.length>6&&e.startsWith("__id")&&e.endsWith("__")&&/^-?\d+$/.test(e.slice(4,-2))}function Qs(e,t){let n=Wr(e),r=Wr(t);if(n&&!r)return -1;if(!n&&r)return 1;if(n&&r){let o=BigInt(e.slice(4,-2)),s=BigInt(t.slice(4,-2));return o<s?-1:o>s?1:0}return ct(e,t)}function Yr(e,t){let n=e.split("/"),r=t.split("/"),o=Math.min(n.length,r.length);for(let s=0;s<o;s++){let a=Qs(n[s],r[s]);if(a!==0)return a}return n.length<r.length?-1:n.length>r.length?1:0}function Vs(e,t){let n=e.split("."),r=t.split("."),o=Math.min(n.length,r.length);for(let s=0;s<o;s++){let a=ct(n[s],r[s]);if(a!==0)return a}return n.length<r.length?-1:n.length>r.length?1:0}function Rt(e,t){return e<t?-1:e>t?1:e===t?0:Number.isNaN(e)?Number.isNaN(t)?0:-1:1}function Mn(e){if(e instanceof Date){let t=e.getTime();if(Number.isNaN(t))return {seconds:Number.NaN,nanos:0};let n=Math.floor(t/1e3),r=(t%1e3+1e3)%1e3;return {seconds:n,nanos:r*1e6}}if(typeof e=="object"&&e!==null){let t=e;if(typeof t.seconds=="number"&&typeof t.nanoseconds=="number"&&typeof t.toDate=="function")return {seconds:t.seconds,nanos:t.nanoseconds};if(typeof t._seconds=="number"&&typeof t._nanoseconds=="number"&&Object.keys(t).length===2)return {seconds:t._seconds,nanos:t._nanoseconds}}return null}function Gs(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.path=="string"&&typeof t.id=="string"&&typeof t.firestore=="object"&&t.firestore!==null}function Js(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.latitude=="number"&&typeof t.longitude=="number"&&typeof t.isEqual=="function"}function Qr(e){if(e===void 0)return -1;if(e===null)return 0;let t=typeof e;return t==="boolean"?1:t==="number"||t==="bigint"?2:t==="string"?4:e instanceof Uint8Array?5:Mn(e)!==null?3:Gs(e)?6:Js(e)?7:Array.isArray(e)?8:9}function Ys(e,t){let n=Math.min(e.length,t.length);for(let r=0;r<n;r++){let o=e[r],s=t[r];if(o!==s)return o<s?-1:1}return e.length<t.length?-1:e.length>t.length?1:0}function _n(e,t){let n=Qr(e),r=Qr(t);if(n!==r)return n<r?-1:1;switch(n){case -1:case 0:return 0;case 1:return e===t?0:e?1:-1;case 2:return Rt(Number(e),Number(t));case 3:{let o=Mn(e),s=Mn(t),a=Rt(o.seconds,s.seconds);return a!==0?a:Rt(o.nanos,s.nanos)}case 4:return ct(e,t);case 5:return Ys(e,t);case 6:return Yr(e.path,t.path);case 7:{let o=e,s=t,a=Rt(o.latitude,s.latitude);return a!==0?a:Rt(o.longitude,s.longitude)}case 8:{let o=e,s=t,a=Math.min(o.length,s.length);for(let l=0;l<a;l++){let c=_n(o[l],s[l]);if(c!==0)return c}return o.length<s.length?-1:o.length>s.length?1:0}case 9:{let o=e,s=t,a=Object.keys(o).sort(ct),l=Object.keys(s).sort(ct),c=Math.min(a.length,l.length);for(let u=0;u<c;u++){let p=a[u],f=l[u],w=ct(p,f);if(w!==0)return w;let h=_n(o[p],s[f]);if(h!==0)return h}return a.length<l.length?-1:a.length>l.length?1:0}}}function Nn(e){return e.ref?.path??e.id}function Vr(e,t){if(typeof e.get=="function")return e.get(t);let n=e.data();if(!n)return;if(!t.includes("."))return n[t];let r=n;for(let o of t.split(".")){if(r==null||typeof r!="object")return;r=r[o];}return r}function Xs(e,t){let n=[],r=new Set;if(e.orderBy)for(let a of e.orderBy){let l=String(a.field),c=a.direction==="desc"?"desc":"asc";r.has(l)||(n.push({field:l,direction:c}),r.add(l));}let o=n.length>0?n[n.length-1].direction:"asc",s=[];for(let[a,l]of t){let c=String(a);Ks.has(l)&&c!==Yt&&!r.has(c)&&(s.push(c),r.add(c));}s.sort(Vs);for(let a of s)n.push({field:a,direction:o});return r.has(Yt)||n.push({field:Yt,direction:o}),n}function ea(e,t,n){for(let r of n){let o=r.field===Yt?Yr(Nn(e),Nn(t)):_n(Vr(e,r.field),Vr(t,r.field));if(o!==0)return r.direction==="desc"?-o:o}return 0}function ta(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function it(e,t){return t.orderBy&&t.orderBy.forEach(n=>{e=e.orderBy(String(n.field),n.direction??"asc");}),t.limit&&(e=e.limit(t.limit)),t.offset&&(e=e.offset(t.offset)),t.select&&t.select.length>0&&(e=e.select(...t.select.map(n=>String(n)))),t.startAt&&(e=Array.isArray(t.startAt)?e.startAt(...t.startAt):e.startAt(t.startAt)),t.startAfter&&(e=Array.isArray(t.startAfter)?e.startAfter(...t.startAfter):e.startAfter(t.startAfter)),t.endAt&&(e=Array.isArray(t.endAt)?e.endAt(...t.endAt):e.endAt(t.endAt)),t.endBefore&&(e=Array.isArray(t.endBefore)?e.endBefore(...t.endBefore):e.endBefore(t.endBefore)),e}function Gr(e){if(!e.offset||e.offset<=0)return e;let{offset:t,limit:n,...r}=e;return {...r,...n&&n>0?{limit:t+n}:{}}}function St(e){let[,t,n]=e;return (t==="in"||t==="array-contains-any")&&Array.isArray(n)&&n.length>30}function Xt(e){let[t,n,r]=e;return St(e)?ta(r,30).map(s=>[t,n,s]):[e]}function $e(e,t){let n=e;for(let[r,o,s]of t)n=n.where(String(r),o,s);return n}async function Jr(e,t,n){let r=await Promise.all(e.map(f=>f.get())),o=new Map;r.forEach(f=>{f.docs.forEach(w=>{let h=Nn(w);o.has(h)||o.set(h,w);});});let s=r[0];if(!s)throw new Error("No snapshots returned");let a=Xs(t,n),l=Array.from(o.values()).sort((f,w)=>ea(f,w,a)),c=t.offset&&t.offset>0?t.offset:0,u=t.limit&&t.limit>0?c+t.limit:void 0,p=c>0||u!==void 0?l.slice(c,u):l;return {...s,docs:p,size:p.length,empty:p.length===0,forEach:(f,w)=>{p.forEach(h=>f.call(w,h));}}}async function We(e,t){let n=t.orWhere&&t.orWhere.length>0,r=t.orWhereGroups&&t.orWhereGroups.length>0;if(!n&&!r){if(!t.where||t.where.length===0)return it(e,t).get();if(!t.where.some(St)){let b=$e(e,t.where);return b=it(b,t),b.get()}let p=t.where.map(Xt),f=vt(p);if(f.length===1){let b=$e(e,f[0]);return b=it(b,t),b.get()}let w=Gr(t),h=f.map(b=>{let T=$e(e,b);return T=it(T,w),T});return Jr(h,t,t.where)}let o=t.where??[],s=[...t.orWhere?.map(u=>[u])??[],...t.orWhereGroups??[]],a=[];for(let u of s){let p=[...o,...u];if(!p.some(St))a.push(p);else {let w=p.map(Xt),h=vt(w);a.push(...h);}}if(a.length===1){let u=$e(e,a[0]);return u=it(u,t),u.get()}let l=Gr(t),c=a.map(u=>{let p=$e(e,u);return p=it(p,l),p});return Jr(c,t,o)}function vt(e){if(e.length===0)return [[]];let t=e[0];if(e.length===1&&t)return t.map(s=>[s]);if(!t)return [[]];let n=e.slice(1),r=vt(n),o=[];for(let s of t)for(let a of r)o.push([s,...a]);return o}async function Fn(e,t){let n=t.orWhere&&t.orWhere.length>0,r=t.orWhereGroups&&t.orWhereGroups.length>0;if(!n&&!r){if(!t.where||t.where.length===0)return {count:(await e.count().get()).data().count,isExact:true};if(!t.where.some(St))return {count:(await $e(e,t.where).count().get()).data().count,isExact:true};let p=t.where.map(Xt),f=vt(p);return {count:(await Promise.all(f.map(b=>$e(e,b).count().get()))).reduce((b,T)=>b+T.data().count,0),isExact:true}}let o=t.where??[],s=[...t.orWhere?.map(u=>[u])??[],...t.orWhereGroups??[]],a=[];for(let u of s){let p=[...o,...u];if(!p.some(St))a.push($e(e,p));else {let w=p.map(Xt),b=vt(w).map(T=>$e(e,T));a.push(...b);}}return {count:(await Promise.all(a.map(u=>u.count().get()))).reduce((u,p)=>u+p.data().count,0),isExact:false}}var jn="preserve";function na(e){jn=e;}function tn(){return jn}function ra(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function Bn(e){if(e==null)return null;if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(e instanceof Timestamp)return e.toDate();if(ra(e))return new Date(e._seconds*1e3+Math.floor(e._nanoseconds/1e6));if(typeof e=="string"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}if(typeof e=="number"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null}function oa(e){if(typeof e!="object"||e===null)return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function en(e){if(e instanceof Timestamp)return e.toDate();if(Array.isArray(e))return e.map(t=>en(t));if(oa(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=en(r);return t}return e}function ce(e){return jn==="normalize"?en(e):e}function eo(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function He(e){return e.charAt(0).toUpperCase()+e.slice(1)}function je(e,t){return t.where&&t.where.forEach(([n,r,o])=>{e=e.where(String(n),r,o);}),t.orderBy&&t.orderBy.forEach(n=>{e=e.orderBy(String(n.field),n.direction??"asc");}),t.limit&&(e=e.limit(t.limit)),t.offset&&(e=e.offset(t.offset)),t.select&&t.select.length>0&&(e=e.select(...t.select.map(n=>String(n)))),t.startAt&&(e=Array.isArray(t.startAt)?e.startAt(...t.startAt):e.startAt(t.startAt)),t.startAfter&&(e=Array.isArray(t.startAfter)?e.startAfter(...t.startAfter):e.startAfter(t.startAfter)),t.endAt&&(e=Array.isArray(t.endAt)?e.endAt(...t.endAt):e.endAt(t.endAt)),t.endBefore&&(e=Array.isArray(t.endBefore)?e.endBefore(...t.endBefore):e.endBefore(t.endBefore)),e}async function nn(e,t){let n={...t,limit:t.pageSize+1};t.cursor&&(t.direction==="prev"?n.endBefore=t.cursor:n.startAfter=t.cursor);let[r,o]=await Promise.all([We(e,n),t.withTotal?Fn(e,t):Promise.resolve(void 0)]),s=r.docs,a=s.length>t.pageSize,l=a?s.slice(0,t.pageSize):s,c=l.map(p=>ce({...p.data(),docId:p.id})),u=t.direction==="prev";return {data:c,nextCursor:u?l.length>0?l[l.length-1]:void 0:a?l[l.length-1]:void 0,prevCursor:u?a?l[0]:void 0:l[0],hasNextPage:u?!!t.cursor:a,hasPrevPage:u?a:!!t.cursor,pageSize:c.length,...o!==void 0?{totalCount:o.count,totalCountIsExact:o.isExact}:{}}}async function*zn(e,t){let n,r=true;for(;r;){let o=await nn(e,{...t,cursor:n,direction:"next"});yield o,r=o.hasNextPage,n=o.nextCursor;}}var Qe="X-History-Reason",Ve="X-History-Comment",ro=Symbol.for("@lpdjs/firestore-repo-service:actorResolverHeaders"),qn=Symbol.for("@lpdjs/firestore-repo-service:actorContext"),Un=globalThis,rn=Un[qn]??(Un[qn]=new AsyncLocalStorage);function aa(e,t){if(!t.includes("."))return e[t];let n=e;for(let r of t.split(".")){if(!n||typeof n!="object")return;n=n[r];}return n}function to(e,t){for(let n of t){let r=aa(e,n);if(typeof r=="string"&&r.length>0)return r;if(typeof r=="number")return String(r)}return null}function no(e,t){if(t===false)return;let n=e?.req?.header;if(typeof n!="function")return;let r=n.call(e.req,t);return typeof r=="string"&&r.length>0?r:void 0}function Ln(e={}){let t=e.contextKeys??["user","docsUser"],n=e.userIdFields??["uid","id","sub"],r=e.userEmailFields??["email"],o=e.reasonHeader===void 0?"x-history-reason":e.reasonHeader,s=e.commentHeader===void 0?"x-history-comment":e.commentHeader,a=e.reasonHeader===void 0?Qe:e.reasonHeader,l=e.commentHeader===void 0?Ve:e.commentHeader,c=e.extras,u=p=>{let f=null,w=p?.get;if(typeof w=="function")for(let S of t){let I=w.call(p,S);if(I&&typeof I=="object"){f=I;break}}let h=no(p,o),b=no(p,s),T=c?c(p,f):void 0;return f?{userId:to(f,n),userEmail:to(f,r),...h!==void 0?{reason:h}:{},...b!==void 0?{comment:b}:{},...T?{extras:T}:{}}:h===void 0&&b===void 0&&!T?null:{...h!==void 0?{reason:h}:{},...b!==void 0?{comment:b}:{},...T?{extras:T}:{}}};return Object.defineProperty(u,ro,{value:{reasonHeader:a,commentHeader:l},enumerable:false,configurable:false}),u}function Kn(e){if(!e)return {reasonHeader:Qe,commentHeader:Ve};if(typeof e=="function"){let t=e[ro];return t?{...t}:{reasonHeader:Qe,commentHeader:Ve}}return {reasonHeader:e.reasonHeader===void 0?Qe:e.reasonHeader,commentHeader:e.commentHeader===void 0?Ve:e.commentHeader}}var oo=Ln();function ia(e){if(e)return typeof e=="function"?e:Ln(e)}function Zn(e){let t=ia(e);return async(n,r)=>{await rn.run({c:n,resolver:t},async()=>{await r();});}}function lt(){let e=rn.getStore();if(!e)return null;let t=null;if(e.c)try{t=(e.resolver??oo)(e.c);}catch{t=null;}if(!t&&!e.override)return null;let n={...t??{}};return e.override&&(e.override.userId!==void 0&&(n.userId=e.override.userId),e.override.userEmail!==void 0&&(n.userEmail=e.override.userEmail),e.override.reason!==void 0&&(n.reason=e.override.reason),e.override.comment!==void 0&&(n.comment=e.override.comment),e.override.extras!==void 0&&(n.extras={...t?.extras??{},...e.override.extras})),n}function ca(e,t){return rn.run({override:{...e}},t)}function la(e){let t=rn.getStore();if(!t)return false;let n=t.override??{},r={...n,...e};return (n.extras||e.extras)&&(r.extras={...n.extras??{},...e.extras??{}}),t.override=r,true}var Wn="_historyMeta";function Ce(e){if(!e?.enabled||e.shadow===false||e.meta&&e.shadow===void 0)return null;let t=e.shadow,n=typeof t=="string"&&t.trim().length>0?t.trim():typeof t=="object"&&t!==null&&typeof t.key=="string"&&t.key.trim().length>0?t.key.trim():Wn,r=typeof t=="object"&&t!==null?t.fields:void 0;return {key:n,fields:{userId:r?.userId??"userId",userEmail:r?.userEmail??"userEmail",reason:r?.reason??"reason",comment:r?.comment??"comment",extras:r?.extras??"extras"}}}function ve(e){return Ce(e)?.key??null}function Qn(e){let t=Ce(e);return t?[t.key]:[]}function ue(e,t){if(!t||!e||typeof e!="object"||Array.isArray(e))return e;let n=e;if(!(t in n))return e;let{[t]:r,...o}=n;return o}function xe(e,t){if(!t?.enabled||t.autoInjectMeta===false)return;let n=Ce(t);if(!n)return;let r=lt(),o=t.fallbackActor??{},s=r?.userId!==void 0?r.userId:o.userId??null,a=r?.userEmail!==void 0?r.userEmail:o.userEmail??null,l=r?.reason??null,c=r?.comment??null,u=r?.extras&&Object.keys(r.extras).length>0?r.extras:null,p={},{fields:f}=n;f.userId!==false&&(p[f.userId]=s),f.userEmail!==false&&(p[f.userEmail]=a),f.reason!==false&&(p[f.reason]=l),f.comment!==false&&(p[f.comment]=c),f.extras!==false&&(p[f.extras]=u),e[n.key]=p;}function kt(e){if(e===null)return "null";if(e===void 0)return "undefined";if(e instanceof Timestamp)return "timestamp";if(e instanceof Date)return "date";if(Array.isArray(e))return "array";let t=typeof e;return t==="string"||t==="number"||t==="boolean"?t:"object"}function At(e,t,n=new WeakMap){if(e===t)return true;if(e===null||t===null||e===void 0||t===void 0)return e===t;if(e instanceof Timestamp&&t instanceof Timestamp)return e.isEqual(t);if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return false;if(n.get(e)===t)return true;n.set(e,t);for(let r=0;r<e.length;r++)if(!At(e[r],t[r],n))return false;return true}if(typeof e=="object"&&typeof t=="object"){if(e instanceof Date||t instanceof Date||e instanceof Timestamp||t instanceof Timestamp)return false;if(n.get(e)===t)return true;n.set(e,t);let r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return false;for(let s of r)if(!Object.prototype.hasOwnProperty.call(t,s)||!At(e[s],t[s],n))return false;return true}return false}function on(e,t,n={}){let r=new Set([...n.exclude??[],...n.metaFields??[],...n.systemKeys??[]]),o=n.include?new Set(n.include):null,s=e??{},a=t??{},l=new Set([...Object.keys(s),...Object.keys(a)]),c={};for(let u of l){if(r.has(u)||o&&!o.has(u))continue;let p=s[u],f=a[u];At(p,f)||(c[u]={oldValue:p===void 0?null:p,newValue:f===void 0?null:f,type:{old:kt(p),new:kt(f)}});}return c}var da=5;function ua(e){return e.schemaVersion===2}function so(e){if(typeof e!="string")return "object";switch(e){case "string":case "number":case "boolean":case "object":case "array":case "timestamp":case "date":case "null":case "undefined":return e;default:return "object"}}function pa(e){return {historyDocId:e.historyDocId,historyToObjectId:e.historyToObjectId,historySetAt:e.historySetAt,schemaVersion:2,operation:e.operation,meta:e.meta??{},...e.custom?{custom:e.custom}:{},changes:e.changes??{}}}function fa(e){let t={};e.historyUserId!==void 0&&(t.userId=e.historyUserId??null),e.historyUserEmail!==void 0&&(t.userEmail=e.historyUserEmail??null);let n=e.extraHistoryDetails??null;n&&(n.reason!==void 0&&(t.reason=n.reason??null),n.comment!==void 0&&(t.comment=n.comment??null));let r={},o=false;if(e.historyDetails&&typeof e.historyDetails=="object")for(let[s,a]of Object.entries(e.historyDetails))r[s]=a,o=true;if(e.extraContentKeys&&typeof e.extraContentKeys=="object")for(let[s,a]of Object.entries(e.extraContentKeys))r[`content.${s}`]=a,o=true;return o&&(t.extras=r),t}function ya(e){let t=e.changes?.oldValue??null,n=e.changes?.newValue??null,r=e.types?.oldValue,o=e.types?.newValue;return {oldValue:t,newValue:n,type:{old:r?so(r):kt(t),new:o?so(o):kt(n)}}}function ma(e){let t=ya(e),n=fa(e);return {historyDocId:e.historyDocId,historyToObjectId:e.historyToObjectId,historySetAt:e.historySetAt,schemaVersion:1,operation:"update",meta:n,changes:{[e.field]:t}}}function ha(e,t,n){return Math.abs(e.toMillis()-t.toMillis())<=n}function ga(e,t){return (e.userId??null)===(t.userId??null)}function ao(e,t={}){let n=t.groupToleranceMs??da,r=[];for(let o of e){if(ua(o)){r.push(pa(o));continue}let a=ma(o),l=r[r.length-1];l&&l.schemaVersion===1&&ha(l.historySetAt,a.historySetAt,n)&&ga(l.meta,a.meta)?Object.assign(l.changes,a.changes):r.push(a);}return r}var wa=7e5;function Ct(e){let t=e.ttlOverride??e.config.ttl,r={schemaVersion:2,historyDocId:randomUUID(),historyToObjectId:e.entityId,historySetAt:Timestamp.now(),operation:e.operation,meta:e.meta,...e.custom?{custom:e.custom}:{},changes:e.changes};t&&(r.expiresAt=Timestamp.fromMillis(Date.now()+t.days*24*60*60*1e3));let o=s=>{try{return Buffer.byteLength(JSON.stringify(s,(a,l)=>l instanceof Timestamp?l.toMillis():l),"utf8")}catch{return 0}};if(o(r.changes)>wa){let s={};for(let[a,l]of Object.entries(r.changes)){let c=o(l.oldValue),u=o(l.newValue);s[a]={oldValue:c>5e4?"[truncated]":l.oldValue,newValue:u>5e4?"[truncated]":l.newValue,type:l.type};}r.changes=s,r._truncated=true;}return r}async function Et(e,t,n,r){let o=t;return n.onBeforeWrite&&(o=await n.onBeforeWrite(t,r)),o?(await e.doc(o.historyDocId).set(o),{written:true,entry:o}):{written:false,reason:"dropped-by-onBeforeWrite"}}function sn(e,t){let n=e??{},r={},o=Ce(t);if(o){let f=n[o.key];if(f&&typeof f=="object"&&!Array.isArray(f)){let w=f,h=C=>{if(C===false||!(C in w))return;let O=w[C];return O==null?null:String(O)},b=h(o.fields.userId);b!==void 0&&(r.userId=b);let T=h(o.fields.userEmail);T!==void 0&&(r.userEmail=T);let S=h(o.fields.reason);S!==void 0&&(r.reason=S);let I=h(o.fields.comment);if(I!==void 0&&(r.comment=I),o.fields.extras!==false){let C=w[o.fields.extras];C&&typeof C=="object"&&!Array.isArray(C)&&Object.keys(C).length>0&&(r.extras=C);}}return r}let s=t.meta;if(!s)return r;let a=f=>{if(!f)return;let w=n[f];return w===void 0||w===null?null:String(w)},l=a(s.userId);l!==void 0&&(r.userId=l);let c=a(s.userEmail);c!==void 0&&(r.userEmail=c);let u=a(s.reason);u!==void 0&&(r.reason=u);let p=a(s.comment);if(p!==void 0&&(r.comment=p),s.extras&&s.extras.length>0){let f={},w=false;for(let h of s.extras)h in n&&(f[h]=n[h],w=true);w&&(r.extras=f);}return r}function an(e){let t=[],n=Ce(e);n&&t.push(n.key);let r=e.meta;return r&&(r.userId&&t.push(r.userId),r.userEmail&&t.push(r.userEmail),r.reason&&t.push(r.reason),r.comment&&t.push(r.comment),r.extras&&t.push(...r.extras)),t}var xa="history",Ra=50;function Gn(e,t,n){return e(...n).collection(t)}function io(e){return String(e[e.length-1]??"")}function co(e,t,n,r){if(!r?.enabled)return null;let o=r.subcollection??xa;async function s(...h){let b={},T=h,S=h[h.length-1];S!==null&&typeof S=="object"&&!(S instanceof Timestamp)&&("limit"in S||"cursor"in S||"direction"in S)&&(b=S,T=h.slice(0,-1));let I=Gn(e,o,T),C=b.direction??"desc",O=I.orderBy("historySetAt",C);return b.cursor&&(O=O.startAfter(b.cursor)),b.limit&&b.limit>0&&(O=O.limit(b.limit)),(await O.get()).docs.map(d=>({id:d.id,data:d.data()}))}async function a(...h){let b={},T=h,S=h[h.length-1];S!==null&&typeof S=="object"&&!(S instanceof Timestamp)&&("limit"in S||"cursor"in S||"direction"in S||"fields"in S||"operations"in S)&&(b=S,T=h.slice(0,-1));let I=b.limit??Ra,C=Math.max(I,Math.min(I*8,500)),O=await s(...T,{limit:C,cursor:b.cursor,direction:b.direction??"desc"}),x=ao(O.map(d=>d.data));if(b.fields&&b.fields.length>0){let d=new Set(b.fields);x=x.filter(y=>Object.keys(y.changes).some(i=>d.has(i)));}if(b.operations&&b.operations.length>0){let d=new Set(b.operations);x=x.filter(y=>d.has(y.operation));}return x.slice(0,I)}async function l(...h){let b=h[h.length-1],T={},S,I;return b!==null&&typeof b=="object"&&!(b instanceof Timestamp)?(T=b,S=h[h.length-2],I=h.slice(0,-2)):(S=b,I=h.slice(0,-1)),a(...I,{...T,fields:[S]})}async function c(...h){let b=h[h.length-1],T={},S,I;return b!==null&&typeof b=="object"&&!(b instanceof Timestamp)?(T=b,S=h[h.length-2],I=h.slice(0,-2)):(S=b,I=h.slice(0,-1)),a(...I,{...T,operations:[S]})}function u(h){let b={title:h.title,display:h.display??true};return h.description!==void 0&&(b.description=h.description),h.key!==void 0&&(b.key=h.key),h.data!==void 0&&(b.data=h.data),b}function p(){let h=lt(),b=r.fallbackActor??{},T=h?.userId!==void 0?h.userId:b.userId??null,S=h?.userEmail!==void 0?h.userEmail:b.userEmail??null;return {userId:T,userEmail:S,...h?.reason!==void 0?{reason:h.reason}:{},...h?.comment!==void 0?{comment:h.comment}:{},...h?.extras&&Object.keys(h.extras).length>0?{extras:h.extras}:{}}}async function f(...h){let b=h[h.length-1],T=h.slice(0,-1),S=io(T),I=on(b.before??{},b.after??{},{include:r.include,exclude:r.exclude,metaFields:an(r),systemKeys:t});if(b.operation==="update"&&Object.keys(I).length===0)return null;let C=sn(b.after??b.before??null,r),O=lt(),d={...O?{...O.userId!==void 0?{userId:O.userId}:{},...O.userEmail!==void 0?{userEmail:O.userEmail}:{},...O.reason!==void 0?{reason:O.reason}:{},...O.comment!==void 0?{comment:O.comment}:{},...O.extras&&Object.keys(O.extras).length>0?{extras:O.extras}:{}}:{},...C,...b.meta??{}},y=b.custom?u(b.custom):void 0,i=Ct({entityId:S,operation:b.operation,changes:I,meta:d,custom:y,config:r}),g=Gn(e,o,T),m=await Et(g,i,r,{repoName:n,docId:S,before:b.before??null,after:b.after??null});return !m.written||!m.entry?null:{historyDocId:m.entry.historyDocId,historyToObjectId:m.entry.historyToObjectId,historySetAt:m.entry.historySetAt,schemaVersion:2,operation:m.entry.operation,meta:m.entry.meta,...m.entry.custom?{custom:m.entry.custom}:{},changes:m.entry.changes}}async function w(...h){let b=h[h.length-1],T=h.slice(0,-1),S=io(T),I=u(b),C={...p(),...b.meta??{}},O=Ct({entityId:S,operation:"custom",changes:{},meta:C,custom:I,config:r}),x=Gn(e,o,T),d=await Et(x,O,r,{repoName:n,docId:S,before:null,after:null});return !d.written||!d.entry?null:{historyDocId:d.entry.historyDocId,historyToObjectId:d.entry.historyToObjectId,historySetAt:d.entry.historySetAt,schemaVersion:2,operation:d.entry.operation,meta:d.entry.meta,...d.entry.custom?{custom:d.entry.custom}:{},changes:d.entry.changes}}return {list:a,raw:s,byField:l,byOperation:c,recordManual:f,recordCustom:w}}function lo(e){return {count:async(t={})=>{let n=e;return n=je(n,t),(await n.count().get()).data().count},sum:async(t,n={})=>{let r=e;r=je(r,n);let o=await r.get(),s=0;return o.forEach(a=>{let l=a.data()[t];typeof l=="number"&&(s+=l);}),s},average:async(t,n={})=>{let r=e;r=je(r,n);let o=await r.get();if(o.empty)return null;let s=0,a=0;return o.forEach(l=>{let c=l.data()[t];typeof c=="number"&&(s+=c,a++);}),a>0?s/a:null}}}function uo(e,t,n,r,o,s,a){let l=()=>new Date;return {create:()=>{let c=e.batch();return {batch:c,set:(...u)=>{let p=u[u.length-1],f=typeof p=="object"&&p!==null&&"merge"in p,w=f?u[u.length-2]:u[u.length-1],h=f?u.slice(0,-2):u.slice(0,-1),b=f?p:{merge:true},T=t(...h),S={...w},I=h[h.length-1];n&&I&&(S[n]=I),r&&(S[r]=T.path),o&&S[o]===void 0&&(S[o]=l()),s&&(S[s]=l()),xe(S,a),c.set(T,S,b);},update:(...u)=>{let p=u.pop(),w=t(...u),h={...p};s&&(h[s]=l()),xe(h,a),c.update(w,h);},delete:(...u)=>{let p=t(...u);c.delete(p);},commit:async()=>{await c.commit();}}}}}var Sa=new Set([4,8,10,13,14]);function Jn(e,t){let n=[],r=t.maxAttempts??5;return e.onWriteError(o=>{let s=o?.code;if(o.failedAttempts<r&&s!==void 0&&Sa.has(s))return true;let a={ref:o.documentRef,error:o};return n.push(a),t.onError?.(a),false}),t.onSuccess&&e.onWriteResult(o=>t.onSuccess(o)),n}function Yn(e,t){if(e.length>0&&!t.onError){let n=new Error(`bulk operation failed for ${e.length} document(s): `+e.slice(0,5).map(r=>`${r.ref.path} (${r.error.message})`).join("; "));throw n.failures=e,n}return {failures:e}}function po(e,t,n,r){let o=()=>new Date;return {set:async(s,a={})=>{let l=e.bulkWriter(),c=Jn(l,a);try{for(let u of s){if(!u)continue;let{docRef:p,data:f,merge:w=!0}=u,h={...f};t&&h[t]===void 0&&(h[t]=o()),n&&(h[n]=o()),xe(h,r),Promise.resolve(l.set(p,h,{merge:w})).catch(()=>{});}}finally{await l.close();}return Yn(c,a)},update:async(s,a={})=>{let l=e.bulkWriter(),c=Jn(l,a);try{for(let u of s){if(!u)continue;let{docRef:p,data:f}=u,w={...f};n&&(w[n]=o()),xe(w,r),Promise.resolve(l.update(p,w)).catch(()=>{});}}finally{await l.close();}return Yn(c,a)},delete:async(s,a={})=>{let l=e.bulkWriter(),c=Jn(l,a);try{for(let u of s)u&&Promise.resolve(l.delete(u)).catch(()=>{});}finally{await l.close();}return Yn(c,a)}}}var Xn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Be(){let e="";for(;e.length<20;){let t=randomBytes(20);for(let n=0;n<t.length&&e.length<20;n++){let r=t[n];r>=Xn.length*4||(e+=Xn.charAt(r%Xn.length));}}return e}function er(e){return e.match(/^\{([^}]+)\}$/)?.[1]?.trim()||null}function Me(e,t="docId",n=false){if(typeof e!="string"||!e.trim())return {rawPath:e??"",collectionId:"",collectionPath:"",parentKeys:[],documentPathTemplate:null,hasTemplate:false};let r=e.split("/").map(f=>f.trim()).filter(Boolean);if(r.length===0)return {rawPath:e,collectionId:e,collectionPath:e,parentKeys:[],documentPathTemplate:null,hasTemplate:false};if(r.length===1){let f=r[0];return {rawPath:e,collectionId:f,collectionPath:f,parentKeys:[],documentPathTemplate:n?null:`${f}/{${t}}`,hasTemplate:e.includes("{")&&e.includes("}")}}let o=r.length%2===0,s=o?r.slice(0,-1):r,a=s[s.length-1],l=s.join("/"),u=s.slice(0,-1).map(er).filter(f=>f!==null),p=o?r.join("/"):`${l}/{${t}}`;return {rawPath:e,collectionId:a,collectionPath:l,parentKeys:u,documentPathTemplate:p,hasTemplate:true}}function fo(e,t,n){let r=t.split("/").map(c=>c.trim()).filter(Boolean),o=0,s=[];for(let c of r){let u=er(c);if(u!==null){let p=n[o++];if(typeof p!="string"||p.trim()==="")throw new Error(`Missing or empty path parameter "${u}" when resolving document reference for "${t}".`);s.push(p);}else s.push(c);}let a=e;if(typeof a?.collection=="function"&&s.length>=2){let c=a,u=true;for(let p=0;p<s.length;p+=2){let f=s[p],w=s[p+1];if(typeof c?.collection!="function"){u=false;break}let h=c.collection(f);if(typeof h?.doc!="function"){u=false;break}c=h.doc(w);}if(u&&c&&c!==a)return c}let l=s.join("/");if(typeof a?.doc=="function")return a.doc(l);if(typeof a?.collection=="function"&&s.length>=2){let c=s.slice(0,-1).join("/"),u=s[s.length-1],p=a.collection(c);return typeof p?.doc=="function"?p.doc(u):p}throw new Error(`Cannot resolve DocumentReference for "${l}": Firestore instance does not expose .collection() or .doc().`)}function Ge(e,t={}){if(!e||typeof e!="object")return;let{pathKey:n,documentKey:r="docId",parentKeys:o,documentPathTemplate:s,isGroup:a}=t,l=n&&typeof e[n]=="string"&&e[n]?e[n]:void 0;if(l&&s){let c=l.split("/").filter(Boolean),u=s.split("/").filter(Boolean);if(c.length===u.length){let p=[];for(let f=0;f<u.length;f++)er(u[f])!==null&&p.push(c[f]);if(p.length>0)return p}}if(o&&o.length>0){let c=o.length+1;if(l){let p=l.split("/").filter(Boolean),f=[];for(let w=1;w<p.length;w+=2)f.push(p[w]);if(f.length>=c)return f.slice(f.length-c)}let u=r?e[r]:void 0;if(typeof u=="string"&&u.trim()!==""){let p=[],f=true;for(let w of o){let h=e[w];if(typeof h=="string"&&h.trim()!=="")p.push(h);else {f=false;break}}if(f)return [...p,u]}}if(l){let c=l.split("/").filter(Boolean),u=[];for(let p=1;p<c.length;p+=2)u.push(c[p]);if(u.length>0)return !a&&(!o||o.length===0)?[u[u.length-1]]:u}}function yo(e,t,n,r,o,s,a=[],l,c){let u=()=>new Date,p=ve(c);return {create:async(...T)=>{let S=T[T.length-1],I=T.slice(0,-1);if(!S||typeof S!="object")throw new Error("Create data payload must be an object.");let C,O,x=typeof S[n]=="string"&&S[n].trim()!=="",d={...S};if(o&&d[o]===void 0&&(d[o]=u()),s&&(d[s]=u()),xe(d,c),e&&I.length===0)if(x){O=S[n],C=typeof e.doc=="function"?e.doc(O):t(O),d[n]=O;let y=r&&C?.path?{...d,[r]:C.path}:d;await C.set(y),r&&C?.path&&(d[r]=C.path);}else if(typeof e.add=="function"){C=await e.add(d),O=C.id,d[n]=O;let y={[n]:O};r&&C?.path&&(y[r]=C.path,d[r]=C.path),await C.update(y);}else O=Be(),C=typeof e.doc=="function"?e.doc(O):t(O),d[n]=C?.id??O,r&&C?.path&&(d[r]=C.path),await C.set(d);else {let y=[];if(I.length>0)for(let i=0;i<I.length;i++){let g=I[i];if(typeof g!="string"||g.trim()===""){let m=a[i]??`arg[${i}]`;throw new Error(`Missing or empty parent key "${m}" for subcollection create()`)}y.push(g);}else if(a.length>0){let i=[];for(let g of a){let m=S[g];typeof m=="string"&&m.trim()!==""?y.push(m):i.push(g);}if(i.length>0){let g=Ge(S,{pathKey:r,documentKey:n,parentKeys:a,documentPathTemplate:l,isGroup:true});if(g&&g.length>=a.length)y=g.slice(0,a.length);else throw new Error(`Missing or empty required parent key(s) in data for subcollection create(): ${i.join(", ")}`)}}else if(r&&typeof S[r]=="string"&&S[r].trim()!==""){let i=Ge(S,{pathKey:r,documentKey:n,parentKeys:a,documentPathTemplate:l,isGroup:true});i&&i.length>1&&(y=i.slice(0,-1));}if(y.length===0)throw new Error("Cannot use create() on collection groups without parent keys. Configure a path template (e.g. 'residences/{residenceId}/events') or provide parent keys in data.");O=x?S[n]:Be(),C=t(...y,O),d[n]=C?.id??O,r&&C?.path&&(d[r]=C.path),await C.set(d);}if(typeof C?.get=="function"){let y=await C.get(),i=typeof y?.data=="function"?y.data():d;return ue(ce(i??d),p)}return ue(ce(d),p)},set:async(...T)=>{let S=T[T.length-1],I=typeof S=="object"&&S!==null&&"merge"in S,C=I?T[T.length-2]:T[T.length-1],O=I?T.slice(0,-2):T.slice(0,-1),x=I?S:{merge:true},d={...C};o&&d[o]===void 0&&(d[o]=u()),s&&(d[s]=u()),xe(d,c);let y=t(...O),i=O[O.length-1];if(n&&i!=null&&(d[n]=i),r&&(d[r]=y.path),await y.set(d,x),typeof y?.get=="function"){let g=await y.get(),m=typeof g?.data=="function"?g.data():d;return ue(ce(m??d),p)}return ue(ce(d),p)},update:async(...T)=>{let S=T.pop(),I=T,C={...S};s&&(C[s]=u()),xe(C,c);let O=t(...I);await O.update(C);let x=await O.get();return ue(ce(x.data()),p)},delete:async(...T)=>{await t(...T).delete();}}}function mo(e,t,n,r,o,s=null){let a={};return a.byList=async(l,c,u="in",p={})=>{if(c.length===0)return [];let f=[],w=eo(c,30);for(let h of w){let b=e;b=b.where(l,u,h),p.select&&p.select.length>0&&(b=b.select(...p.select.map(S=>String(S)))),(await b.get()).forEach(S=>{let I=ue(ce(S.data()),s);f.push(p.returnDoc?{data:I,doc:S}:I);});}return f},t.forEach(l=>{let c=`by${He(String(l))}`;a[c]=async(...u)=>{let p={},f=u[u.length-1];if(typeof f=="boolean"?(p={returnDoc:f},u=u.slice(0,-1)):typeof f=="object"&&f!==null&&!Array.isArray(f)&&(p=f,u=u.slice(0,-1)),String(l)===o&&(u.length>1||u.length===1&&n!==null)){let C=await r(...u).get();if(!C.exists)return null;let O=ue(ce(C.data()),s);return p.returnDoc?{data:O,doc:C}:O}let w=u[0];if(w===void 0)return null;let h=e;h=h.where(String(l),"==",w).limit(1),p.select&&p.select.length>0&&(h=h.select(...p.select.map(I=>String(I))));let b=await h.get();if(b.empty)return null;let T=b.docs[0];if(!T)return null;let S=ue(ce(T.data()),s);return p.returnDoc?{data:S,doc:T}:S};}),a}function ho(e,t,n,r,o=null){let s={},a=c=>ue(ce(c),o),l=async(c,u)=>{if(!n||!r||u.length===0)return c;let p=u.map(f=>typeof f=="string"?{key:f}:{key:f.relation,select:f.select});return Promise.all(c.map(async f=>{let w=await Promise.all(p.map(async({key:b,select:T})=>{let S=n[b];if(!S)return [b,void 0];let I=r[S.repo];if(!I)return [b,void 0];let C=S.sourceKey||b,O=f[C];if(O==null)return [b,S.type==="one"?null:[]];let x=T?{select:T}:void 0;try{if(S.type==="one"){let d=`by${He(S.key)}`,y=typeof I.get?.[d]=="function"?await I.get[d](O,x):null;return [b,y]}else {let d=`by${He(S.key)}`,y=typeof I.query?.[d]=="function"?await I.query[d](O,x):[];return [b,y]}}catch(d){return console.error(`[include] Error populating "${b}":`,d),[b,S.type==="one"?null:[]]}})),h={};for(let[b,T]of w)b!==void 0&&(h[b]=T);return {...f,populated:h}}))};return t.forEach(c=>{let u=`by${He(c)}`;s[u]=async(p,f={})=>{let w={...f,where:[[c,"==",p],...f.where??[]]};return (await We(e,w)).docs.map(b=>a(b.data()))};}),s.by=async c=>(await We(e,c)).docs.map(p=>a(p.data())),s.getAll=async(c={})=>(await We(e,c)).docs.map(p=>a(p.data())),s.onSnapshot=(c,u,p)=>je(e,c).onSnapshot(w=>{u(w.docs.map(h=>a(h.data())));},p),s.paginate=async c=>{let{include:u,...p}=c,f=await nn(e,p),w=o?{...f,data:f.data.map(h=>ue(h,o))}:f;if(u&&u.length>0){let h=await l(w.data,u);return {...w,data:h}}return w},s.paginateAll=async function*(c){let{include:u,...p}=c;for await(let f of zn(e,p)){let w=o?{...f,data:f.data.map(h=>ue(h,o))}:f;if(u&&u.length>0){let h=await l(w.data,u);yield {...w,data:h};}else yield w;}},s}function go(e,t){return {populate:async(n,r)=>{if(!e.relationalKeys)return {...n,populated:{}};let o,s={};if(typeof r=="object"&&!Array.isArray(r))if("relation"in r){let c=r;o=[c.relation],c.select&&(s[c.relation]=c.select);}else if("relations"in r){let c=r;o=Array.isArray(c.relations)?c.relations:[c.relations],s=c.select??{};}else o=[];else o=Array.isArray(r)?r:[r];let a=await Promise.all(o.map(async c=>{let u=e.relationalKeys?.[c];if(!u)return console.warn(`[populate] Relation "${c}" not found in config`),[c,void 0];let p=t[u.repo];if(!p)return console.warn(`[populate] Repository "${u.repo}" not found in mapping`),[c,void 0];let f=u.sourceKey||c,w=n[f];if(w==null)return [c,u.type==="one"?null:[]];let h=s[c],b=h?{select:h}:void 0;try{if(u.type==="one"){let T=`by${He(u.key)}`,S=typeof p.get?.[T]=="function"?await p.get[T](w,b):null;return [c,S]}else {let T=`by${He(u.key)}`,S=typeof p.query?.[T]=="function"?await p.query[T](w,b):[];return [c,S]}}catch(T){return console.error(`[populate] Error populating "${c}":`,T),[c,u.type==="one"?null:[]]}})),l={};for(let[c,u]of a)u!==void 0&&(l[c]=u);return {...n,populated:l}}}}var bo=new Set([4,8,10,13,14]),ka=5,Aa=3,Ca=100,Ea=500;async function Oa(e){let t=0;for(;;){t++;try{return await e.get()}catch(n){let r=n?.code;if(!(typeof r=="number"&&bo.has(r))||t>=Aa)throw n;let s=Ca*2**(t-1);await new Promise(a=>setTimeout(a,s));}}}function wo(e,t,n,r,o,s){let a=()=>new Date;return {backfillKeys:async(c={})=>{let{overwriteCreated:u=false,touchUpdated:p=true,overwritePath:f=false,pageSize:w=300,dryRun:h=false,maxAttempts:b=5,flushThreshold:T=Ea,onError:S,onSuccess:I}=c,C=Math.max(1,T),O=Array.from(new Set([n,r,o,s].filter(A=>typeof A=="string"&&A.length>0))),x=[],d=0,y=0,i=0,g=0,m=h?null:e.bulkWriter();try{m&&(m.onWriteError(k=>{let R=k?.code;if(R===ka)return i++,!1;if(k.failedAttempts<b&&R!==void 0&&bo.has(R))return !0;let P={path:k?.documentRef?.path??"(unknown)",error:k};return x.push(P),S?.(P),!1}),m.onWriteResult(k=>{y++,I?.(k.path);}));let A;for(;;){let k=t.orderBy(FieldPath.documentId());O.length>0&&typeof k.select=="function"&&(k=k.select(...O)),A&&(k=k.startAfter(A)),k=k.limit(w);let R=await Oa(k);if(R.empty)break;for(let P of R.docs){d++;let M=P.data(),$={};if(n&&(M[n]==null||M[n]==="")&&($[n]=P.id),r&&(f||M[r]==null||M[r]==="")&&M[r]!==P.ref.path&&($[r]=P.ref.path),o&&(u||M[o]==null)&&($[o]=P.createTime?.toDate?.()??a()),p&&s&&M[s]==null&&($[s]=P.updateTime?.toDate?.()??P.createTime?.toDate?.()??a()),Object.keys($).length===0){i++;continue}m?(Promise.resolve(m.update(P.ref,$)).catch(()=>{}),g++,g>=C&&typeof m.flush=="function"&&(await m.flush(),g=0)):y++;}if(R.size<w)break;A=R.docs[R.docs.length-1];}}finally{m&&await m.close();}return {scanned:d,written:y,skipped:i,failures:x}}}}function xo(e,t,n,r,o,s,a){let l=()=>new Date,c=ve(a);return {run:async u=>e.runTransaction(async p=>u({get:async(...w)=>{let h=t(...w),b=await p.get(h);return b.exists?ue(ce({...b.data(),docId:b.id}),c):null},set:(...w)=>{let h=w[w.length-1],b=typeof h=="object"&&h!==null&&"merge"in h,T=b?w[w.length-2]:w[w.length-1],S=b?w.slice(0,-2):w.slice(0,-1),I=b?h:{merge:true},C=t(...S),O={...T},x=S[S.length-1];n&&x&&(O[n]=x),r&&(O[r]=C.path),o&&O[o]===void 0&&(O[o]=l()),s&&(O[s]=l()),xe(O,a),p.set(C,O,I);},update:(...w)=>{let h=w[w.length-1],b=w.slice(0,-1),T=t(...b),S={...h};s&&(S[s]=l()),xe(S,a),p.update(T,S);},delete:(...w)=>{let h=t(...w);p.delete(h);},raw:p}))}}function Ro(e){if(typeof e!="function")return [];let n=e.toString().match(/^\s*(?:function\s*\w*\s*)?\(([^)]*)\)/);if(!n?.[1])return [];let r=n[1].split(",").map(o=>o.trim().replace(/\s*[:=].*$/,"").trim()).filter(Boolean);return r.length<=2?[]:r.slice(1,-1)}function Pa(e){let t=e?.documentKey??"docId",n=!!e?.isGroup,r=Me(typeof e?.path=="string"?e.path:"",t,n),o=r.parentKeys.length>0?r.parentKeys:n?Ro(e?.refCb):[],s=[e?.documentKey,e?.pathKey,e?.createdKey,e?.updatedKey].filter(l=>typeof l=="string"),a=e?.history&&typeof e.history=="object"?e.history:void 0;return {schema:e?.schema,_systemKeys:s,_pathKey:e?.pathKey??null,_isGroup:n,_createdKey:e?.createdKey??null,_parentKeys:o,_documentPathTemplate:r.documentPathTemplate,_collectionId:typeof e?.path=="string"?r.collectionId:null,relationalKeys:e?.relationalKeys,_historyConfig:a,_historyShadowKey:ve(a),_historyIdentityKeys:Qn(a),_historySubcollection:a?.enabled?a.subcollection??"history":void 0,_collectionPath:typeof e?.path=="string"?r.collectionPath:null}}function ln(e,t){let n=Pa(e),r,o=()=>{let s=r??(r=t());if(!s){let a=n._collectionPath||"unknown";throw new Error(`[makeLazyRepo] Failed to resolve repository for path "${a}". The repository mapping resolved to undefined. This almost always indicates a circular import where the repository was exported as undefined.`)}return s};return new Proxy(n,{get(s,a){return typeof a=="string"&&a in n?n[a]:o()[a]},has(s,a){return typeof a=="string"&&a in n?true:a in o()}})}function tr(e,t,n={}){let r=t.documentKey,o=Me(t.path,r,!!t.isGroup),s=o.parentKeys.length>0?o.parentKeys:t.isGroup?Ro(t.refCb):[],a=t.isGroup?e.collectionGroup(o.collectionId):e.collection(o.collectionPath),l=t.isGroup?null:e.collection(o.collectionPath),c=typeof t.refCb=="function"?(...y)=>t.refCb(e,...y):(...y)=>fo(e,o.documentPathTemplate??`${o.collectionPath}/{${r}}`,y),u=t.history,p=ve(u),f=Qn(u),w=mo(a,t.foreignKeys,l,c,r,p),h=ho(a,t.queryKeys,t.relationalKeys,n,p),b=lo(a),T=yo(l,c,r,t.pathKey,t.createdKey,t.updatedKey,s,o.documentPathTemplate,u),S=uo(e,c,t.documentKey,t.pathKey,t.createdKey,t.updatedKey,u),I=xo(e,c,t.documentKey,t.pathKey,t.createdKey,t.updatedKey,u),C=po(e,t.createdKey,t.updatedKey,u),O=wo(e,a,t.documentKey,t.pathKey,t.createdKey,t.updatedKey),x=go(t,n),d=u?.enabled?co(c,[t.documentKey,t.pathKey,t.createdKey,t.updatedKey].filter(y=>typeof y=="string"),t.path??"(unknown)",u):null;return {ref:a,documentRef:c,get:w,query:h,aggregate:b,...T,batch:S,transaction:I,bulk:C,system:O,...x,...d?{history:d}:{},_historySubcollection:d?u?.subcollection??"history":void 0,_historyConfig:u,_historyShadowKey:p,_historyIdentityKeys:f,schema:t.schema,relationalKeys:t.relationalKeys,_systemKeys:[t.documentKey,t.pathKey,t.createdKey,t.updatedKey].filter(y=>typeof y=="string"),_pathKey:t.pathKey??null,_isGroup:!!t.isGroup,_parentKeys:s,_documentPathTemplate:o.documentPathTemplate,_collectionId:o.collectionId,_collectionPath:o.collectionPath,_createdKey:t.createdKey??null}}var Ia="history";function Da(e){let t=e&&typeof e.history=="object"&&e.history!==null?e.history:void 0,n=[e?.documentKey,e?.pathKey,e?.createdKey,e?.updatedKey].filter(s=>typeof s=="string"),r=typeof e?.path=="string"?e.path:null,o=r?Me(r,e?.documentKey??"docId"):null;return {historyConfig:t,systemKeys:n,isGroup:!!e?.isGroup,collectionPath:o?o.collectionPath:null,documentPathTemplate:o&&(!e?.isGroup||o.collectionPath.includes("/"))?o.documentPathTemplate:null}}function $a(e){let t=e._historyConfig??(typeof e.history=="object"&&e.history!==null&&"enabled"in e.history?e.history:void 0),n=e._collectionPath??e.ref?.path??null,r=typeof e._documentPathTemplate=="string"?e._documentPathTemplate:null;return {historyConfig:t,systemKeys:e._systemKeys??[],isGroup:!!e._isGroup,collectionPath:n,documentPathTemplate:r&&(!e._isGroup||n&&n.includes("/"))?r:null}}function Ha(e,t){return t?`${t}/{docId}`:(console.warn(`[HistoryTriggers] Cannot determine collection path for "${e}". Skipping.`),null)}function So(e,t){let{onDocumentWritten:n}=t.deps,r={},o=e?.rawMapping,s=o?Object.entries(o).map(([a,l])=>[a,Da(l)]):Object.entries(e).map(([a,l])=>[a,$a(l)]);for(let[a,l]of s){let c=l.historyConfig;if(!c?.enabled)continue;let u=c.subcollection??Ia,p=c.ttl??t.defaults?.ttl,f=t.repos?.[a],w;if(l.isGroup){let O=f?.triggerPath??l.documentPathTemplate;if(!O){console.warn(`[HistoryTriggers] Skipping collection-group repo "${a}". Provide a triggerPath in the history triggers repos override or use a full path template.`);continue}w=O;}else w=f?.triggerPath??l.documentPathTemplate??Ha(a,l.collectionPath);if(!w)continue;let h=l.systemKeys,b=h[0]??"docId",T=an(c),S={...t.triggerOptions,...c?.triggerOptions,...f?.triggerOptions},I=Object.keys(S).length>0,C=async O=>{try{let x=O.data?.before?.data(),d=O.data?.after?.data(),y;if(!x&&d)y="create";else if(x&&!d)y="delete";else if(x&&d)y="update";else return;let i=String(d?.[b]??x?.[b]??O.params?.docId??O.data?.after?.id??O.data?.before?.id??"");if(!i)return;let g=on(x??{},d??{},{include:c.include,exclude:c.exclude,metaFields:T,systemKeys:h});if(y==="update"&&Object.keys(g).length===0)return;let m=sn(d??x??null,c),A=Ct({entityId:i,operation:y,changes:g,meta:m,config:c,ttlOverride:p}),k=O.data?.after?.ref??O.data?.before?.ref;if(!k)return;let R=k.collection(u);await Et(R,A,c,{repoName:a,docId:i,before:x??null,after:d??null});}catch(x){console.error(`[HistoryTriggers] Failed to record history for "${a}":`,x);}};r[`${a}_onHistory`]=n(I?{document:w,...S}:w,C);}return r}function Ma(e){let t=[],n=e.replace(/[.*+?^${}()|[\]\\]/g,r=>r===":"?r:`\\${r}`).replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,(r,o)=>(t.push(o),"([^/]+)"));return {pattern:new RegExp(`^${n}$`),paramNames:t}}function _a(e){let t=e.path??e.url??"/",n=t.indexOf("?");return n===-1?t:t.slice(0,n)}var _e=class{constructor(){this.routes=[];this.middlewares=[];this.notFoundHandler=(t,n)=>{n.status(404).send("Not Found");};this.errorHandler=(t,n,r)=>{console.error("[MiniRouter]",t),r.status(500).send("Internal Server Error");};}use(t){return this.middlewares.push(t),this}get(t,n){return this.addRoute("GET",t,n)}post(t,n){return this.addRoute("POST",t,n)}put(t,n){return this.addRoute("PUT",t,n)}patch(t,n){return this.addRoute("PATCH",t,n)}delete(t,n){return this.addRoute("DELETE",t,n)}onNotFound(t){return this.notFoundHandler=t,this}onError(t){return this.errorHandler=t,this}addRoute(t,n,r){let{pattern:o,paramNames:s}=Ma(n);return this.routes.push({method:t.toUpperCase(),pattern:o,paramNames:s,handler:r}),this}async handle(t,n){let r=(t.method??"GET").toUpperCase(),o=_a(t),s=null,a={};for(let u of this.routes){if(u.method!==r)continue;let p=o.match(u.pattern);if(p){s=u,a={},u.paramNames.forEach((f,w)=>{a[f]=decodeURIComponent(p[w+1]??"");});break}}let l=Object.assign(t,{params:a}),c=s?s.handler:this.notFoundHandler;try{await this.runMiddlewareChain(l,n,c);}catch(u){this.errorHandler(u,t,n);}}async runMiddlewareChain(t,n,r){let o=0,s=async()=>{if(o<this.middlewares.length){let a=this.middlewares[o++];await a(t,n,s);}else await r(t,n);};await s();}};function Ee(e,t,n){let r=t==="/"?"":t.replace(/\/$/,"");if(process.env.FUNCTIONS_EMULATOR==="true"){let a=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??"demo-project",l=n??process.env.FUNCTION_REGION??"us-central1",c=(process.env.FUNCTION_TARGET??"").replace(/\./g,"-");return `/${a}/${l}/${c}${r}`}let o=process.env.K_SERVICE,s=e?.hostname??e?.headers?.host??"";return o&&typeof s=="string"&&s.includes("cloudfunctions.net")?`/${o.toLowerCase()}${r}`:r}function dn(e){if(typeof e=="string")return e;if(Array.isArray(e)){let t=e[0];return typeof t=="string"?t:void 0}}function Ot(e){return !!e&&typeof e=="object"&&e.__authExtension===true}function nr(e,t,n=new WeakSet,r=0){if(e==null)return null;if(typeof e=="object"&&typeof e.toDate=="function")return e.toDate().toISOString();if(e instanceof Date)return e.toISOString();if(Buffer.isBuffer(e))return e.toString("base64");if(e instanceof Uint8Array)return Buffer.from(e).toString("base64");if(typeof e=="object"&&"latitude"in e&&"longitude"in e){let o=e;return t?.stringifyArrays===false?{lat:o.latitude,lng:o.longitude}:JSON.stringify({lat:o.latitude,lng:o.longitude})}if(Array.isArray(e)){let o=e.map(s=>nr(s,t,n,r+1));return t?.stringifyArrays===false?o:JSON.stringify(o)}return typeof e=="object"&&e!==null&&t?.stringifyArrays===false?rr(e,new Set,{},n,r+1):e}var To=32,ja=5e3;function ko(e,t,n,r=new WeakSet,o=0){if(o>To){n[t||"_truncated"]=JSON.stringify({__truncated:true});return}if(r.has(e)){n[t||"_cycle"]=JSON.stringify({__cycle:true});return}r.add(e);for(let[s,a]of Object.entries(e)){if(Object.keys(n).length>=ja)break;let l=t?`${t}__${s}`:s;a!=null&&typeof a=="object"&&!Array.isArray(a)&&!(a instanceof Date)&&!Buffer.isBuffer(a)&&!(a instanceof Uint8Array)&&typeof a.toDate!="function"&&!("latitude"in a&&"longitude"in a)?ko(a,l,n,r,o+1):n[l]=nr(a);}r.delete(e);}function rr(e,t,n,r=new WeakSet,o=0){if(o>To)return {__truncated:true};if(r.has(e))return {__cycle:true};r.add(e);let s={};for(let[a,l]of Object.entries(e)){if(t.has(a))continue;let c=n[a]??a;l!=null&&typeof l=="object"&&!Array.isArray(l)&&!(l instanceof Date)&&!Buffer.isBuffer(l)&&!(l instanceof Uint8Array)&&typeof l.toDate!="function"&&!("latitude"in l&&"longitude"in l)?s[c]=rr(l,new Set,{},r,o+1):s[c]=nr(l,{stringifyArrays:false},r,o+1);}return r.delete(e),s}function Ao(e){let t={};for(let[n,r]of Object.entries(e)){let o=r;if(typeof o=="string"){let l=o.trim();if(l.startsWith("[")&&l.endsWith("]")||l.startsWith("{")&&l.endsWith("}"))try{o=JSON.parse(l);}catch{}}if(n.startsWith("__")||!n.includes("__")){t[n]=o;continue}let s=n.split("__").filter(Boolean),a=t;for(let l=0;l<s.length-1;l++){let c=s[l];(!a[c]||typeof a[c]!="object"||Array.isArray(a[c]))&&(a[c]={}),a=a[c];}a[s[s.length-1]]=o;}return t}function Pt(e,t){let n=t?.flat!==false,r;if(n){let o=new Set(t?.exclude),s=t?.columnMap??{},a=e;if(o.size>0){let c=false,u={};for(let[p,f]of Object.entries(e)){if(o.has(p)){c=true;continue}u[p]=f;}c&&(a=u);}let l={};ko(a,"",l),r={};for(let[c,u]of Object.entries(l)){if(o.has(c))continue;let p=c.split("__")[0];if(p!==c&&o.has(p))continue;let f=s[c]??(c.includes("__")?s[c.split("__").pop()]:void 0)??c;r[f]=u;}}else {let o=new Set(t?.exclude),s=t?.columnMap??{};r=rr(e,o,s);}return typeof t?.transformDoc=="function"&&(r=t.transformDoc(r)),r}function G(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Ne(e,t,n){let r=G(e),o=G(t);return `<!DOCTYPE html>
1
+ import {jsx,jsxs,Fragment}from'hono/jsx/jsx-runtime';import {Timestamp,Filter,Query,FieldPath}from'firebase-admin/firestore';import {AsyncLocalStorage}from'async_hooks';import {randomUUID,randomBytes}from'crypto';import {z}from'zod';import {renderToString}from'hono/jsx/dom/server';import {extendZodWithOpenApi,OpenAPIRegistry,OpenApiGeneratorV31,getOpenApiMetadata}from'@asteasolutions/zod-to-openapi';import {Hono}from'hono';import {getRequestListener}from'@hono/node-server';var _n=Object.defineProperty;var Us=Object.getOwnPropertyDescriptor;var Ls=Object.getOwnPropertyNames;var Ks=Object.prototype.hasOwnProperty;var Kr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var St=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Zr=(e,t)=>{for(var n in t)_n(e,n,{get:t[n],enumerable:true});},Zs=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ls(t))!Ks.call(e,o)&&o!==n&&_n(e,o,{get:()=>t[o],enumerable:!(r=Us(t,o))||r.enumerable});return e};var Ws=e=>Zs(_n({},"__esModule",{value:true}),e);function J(e){let t=e,n=t._zod?.def?.type;if(n)return oi[n]??`Zod${n.charAt(0).toUpperCase()}${n.slice(1)}`;let r=t._def?.typeName;return r||""}function ye(e){let t=e;if(t._zod?.def?.innerType)return t._zod.def.innerType;if(t._def?.innerType)return t._def.innerType}function $t(e){let t=e,n=t._zod?.def?.in;if(n)return n;if(t._def?.schema)return t._def.schema}function pn(e){let t=e;if(t._zod?.def?.element)return t._zod.def.element;if(t._def?.type)return t._def.type}function Do(e){let t=e;if(t._zod?.def?.defaultValue!==void 0)return t._zod.def.defaultValue;let n=t._def?.defaultValue;return typeof n=="function"?n():n}function me(e){let t=e;return t.shape&&typeof t.shape=="object"?t.shape:t._zod?.def?.shape&&typeof t._zod.def.shape=="object"?t._zod.def.shape:t._def?.shape?typeof t._def.shape=="function"?t._def.shape():t._def.shape:{}}function Ht(e){let t=e;return Array.isArray(t.options)?t.options:t._zod?.def?.entries?Object.values(t._zod.def.entries):Array.isArray(t._def?.values)?t._def.values:[]}function _t(e){let t=e;return t._zod?.def?.entries?t._zod.def.entries:t.enum&&typeof t.enum=="object"?t.enum:t._def?.values&&typeof t._def.values=="object"?t._def.values:{}}function Mt(e){let t=e;return Array.isArray(t._zod?.def?.values)?t._zod.def.values[0]:t._def?.value}function Ft(e){let t=e;return Array.isArray(t.options)?t.options:Array.isArray(t._zod?.def?.options)?t._zod.def.options:Array.isArray(t._def?.options)?t._def.options:[]}function $o(e){let t=e,n=[],r=t._zod?.def?.checks;if(Array.isArray(r)){for(let s of r)s.format&&n.push(s.format);if(n.length>0)return n}let o=t._def?.checks;if(Array.isArray(o))for(let s of o)s.kind&&n.push(s.kind);return n}var oi,ft=St(()=>{"use strict";oi={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 Vo({val:e}){return jsx("span",{class:"text-sm text-base-content/80 font-mono tabular-nums whitespace-nowrap",children:e.toLocaleString()})}function Ci({message:e}){return jsx("span",{class:"tooltip tooltip-warning tooltip-right inline-flex align-middle ml-1 text-warning","data-tip":e,role:"img","aria-label":e,children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",class:"size-3.5",children:jsx("path",{d:"M12 2 1 22h22L12 2zm0 6 7.5 13h-15L12 8zm-1 4v4h2v-4h-2zm0 5v2h2v-2h-2z"})})})}function ht({val:e,mismatch:t}){let n=ur(e);return t?jsxs("span",{class:"inline-flex items-start gap-0.5",children:[n,jsx(Ci,{message:t})]}):n}function ur(e){if(e==null)return jsx("span",{class:"opacity-30 italic text-xs",children:"\u2014"});if(typeof e=="boolean")return e?jsx("span",{class:"badge badge-success badge-sm",children:"true"}):jsx("span",{class:"badge badge-error badge-sm",children:"false"});if(e instanceof Date)return jsx(Vo,{val:e});if(typeof e=="object"&&e!==null&&typeof e.toDate=="function")return jsx(Vo,{val:e.toDate()});if(typeof e=="number")return jsx("span",{class:"text-sm font-mono tabular-nums",children:String(e)});if(Array.isArray(e))return e.length===0?jsx("span",{class:"text-xs text-base-content/30",children:"[]"}):jsxs("ul",{class:"list-none p-0 m-0 space-y-0.5 text-xs",children:[e.slice(0,8).map((n,r)=>jsx("li",{class:"break-all",children:ur(n)},r)),e.length>8&&jsxs("li",{class:"text-base-content/40 italic",children:["+",e.length-8," more\u2026"]})]});if(typeof e=="object"&&e!==null){let n=Object.entries(e);return n.length===0?jsx("span",{class:"text-xs text-base-content/30",children:"{}"}):jsxs("dl",{class:"grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5 text-xs m-0",children:[n.slice(0,8).map(([r,o])=>jsxs(Fragment,{children:[jsx("dt",{class:"text-base-content/50 font-semibold whitespace-nowrap",children:r}),jsx("dd",{class:"break-all",children:ur(o)})]})),n.length>8&&jsxs("dt",{class:"col-span-2 text-base-content/40 italic",children:["+",n.length-8," more\u2026"]})]})}let t=String(e);return jsx("span",{class:"text-sm break-all",children:t})}var xn=St(()=>{"use strict";});function qt(e){if(!e)return "unknown";let t=pr(e);switch(J(t)){case "ZodString":return "string";case "ZodNumber":return "number";case "ZodBigInt":return "bigint";case "ZodBoolean":return "boolean";case "ZodDate":return "date";case "ZodArray":return "array";case "ZodObject":case "ZodRecord":return "object";case "ZodEnum":case "ZodNativeEnum":return "enum";case "ZodLiteral":return "literal";default:return "unknown"}}function pr(e){let t=J(e);if(t==="ZodOptional"||t==="ZodNullable"||t==="ZodDefault"){let n=ye(e);return n?pr(n):e}return e}function Ut(e,t){if(!e)return;let n=t.split("."),r=e;for(let o of n){if(!r)return;let s=pr(r);if(J(s)!=="ZodObject")return;r=me(s)[o];}return r}function Pi(e){return e==null?"null":e instanceof Date?"date":Array.isArray(e)?"array":typeof e=="string"?"string":typeof e=="boolean"?"boolean":typeof e=="bigint"?"bigint":typeof e=="number"?"number":typeof e=="object"?typeof e.toDate=="function"?"date":"object":"unknown"}function Lt(e,t){if(e==="unknown")return null;let n=Pi(t);return n==="null"?null:e==="enum"||e==="literal"?n==="string"||n==="number"?null:`Expected ${e} (string/number), got ${n}`:e===n||e==="number"&&n==="bigint"||e==="bigint"&&n==="number"?null:`Expected ${e}, got ${n}`}var fr=St(()=>{"use strict";ft();});var Yo={};Zr(Yo,{PanelMany:()=>Di,PanelOne:()=>Ii,RightPanel:()=>yr});function Ii({doc:e,repoName:t,basePath:n,schema:r,columns:o}){if(!e)return jsx("div",{class:"text-center py-12 text-base-content/50",children:"Document not found."});let s=String(e.docId??e.id??""),a=`${n}/${t}/${encodeURIComponent(s)}/edit`,l=Jo(r,o);return jsxs("div",{class:"space-y-4",children:[jsxs("div",{class:"flex items-center justify-between gap-2",children:[jsxs("div",{class:"text-xs text-base-content/60",children:[jsx("span",{class:"font-mono",children:t}),jsx("span",{class:"opacity-50",children:" \xB7 "}),jsx("span",{class:"font-mono break-all",children:s})]}),jsx("a",{href:a,class:"btn btn-sm btn-primary",children:"Edit \u2192"})]}),jsx("dl",{class:"grid grid-cols-[max-content_1fr] gap-x-4 gap-y-2 border border-base-300 rounded-box p-4 bg-base-100",children:o.map(c=>{let u=e[c],p=l[c],f=p?Lt(p,u):null;return jsxs(Fragment,{children:[jsx("dt",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide pt-0.5",children:c}),jsx("dd",{class:"min-w-0",children:jsx(ht,{val:u,mismatch:f})})]})})})]})}function Di({docs:e,repoName:t,basePath:n,fk:r,fv:o,columns:s,schema:a,pagination:l}){let c=`${n}/${t}?fv_${r}=${encodeURIComponent(o)}`,u=Jo(a,s);return jsxs("div",{class:"space-y-4",children:[jsxs("div",{class:"flex items-center justify-between gap-2",children:[jsxs("div",{class:"text-xs text-base-content/60",children:[jsx("span",{class:"font-mono",children:t}),jsx("span",{class:"opacity-50",children:" where "}),jsx("span",{class:"font-mono",children:r}),jsx("span",{class:"opacity-50",children:" = "}),jsx("span",{class:"font-mono break-all",children:o}),jsx("span",{class:"opacity-50",children:" \xB7 "}),jsxs("span",{children:[e.length," doc",e.length!==1?"s":""]})]}),jsx("a",{href:c,class:"btn btn-sm btn-outline",children:"Full view \u2192"})]}),jsx("div",{class:"overflow-x-auto rounded-box border border-base-300 bg-base-100",children:jsxs("table",{class:"table table-xs w-full",children:[jsx("thead",{children:jsxs("tr",{class:"bg-base-200/50",children:[s.map((p,f)=>jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:p},f)),jsx("th",{})]})}),jsx("tbody",{children:e.length===0?jsx("tr",{children:jsx("td",{colspan:s.length+1,class:"text-center py-10 text-base-content/40",children:"No related documents"})}):e.map((p,f)=>{let b=String(p.docId??p.id??""),h=`${n}/${t}/${encodeURIComponent(b)}/edit`;return jsxs("tr",{class:"hover",children:[s.map((w,T)=>{let S=p[w],I=u[w],A=I?Lt(I,S):null;return jsx("td",{class:"align-top py-1.5",children:jsx(ht,{val:S,mismatch:A})},T)}),jsx("td",{class:"text-right py-1.5",children:jsx("a",{href:h,class:"btn btn-xs btn-ghost",children:"Edit"})})]},f)})})]})}),(l.hasPrev||l.hasNext)&&jsxs("div",{class:"flex justify-center items-center gap-2",children:[l.hasPrev?jsx("button",{type:"button",class:"btn btn-xs btn-outline","data-frs-panel-page":"prev","data-cursor":l.prevCursor,children:"\u2190 Previous"}):jsx("button",{class:"btn btn-xs btn-outline",disabled:true,children:"\u2190 Previous"}),l.hasNext?jsx("button",{type:"button",class:"btn btn-xs btn-outline","data-frs-panel-page":"next","data-cursor":l.nextCursor,children:"Next \u2192"}):jsx("button",{class:"btn btn-xs btn-outline",disabled:true,children:"Next \u2192"})]})]})}function Jo(e,t){if(!e)return {};let n={};for(let r of t)n[r]=qt(Ut(e,r));return n}var yr,mr=St(()=>{"use strict";xn();fr();yr=({basePath:e=""})=>jsxs("div",{class:"fixed inset-0 z-[100] hidden pointer-events-none","data-frs-panel-root":!0,"data-frs-base-path":e,"aria-hidden":"true",children:[jsx("div",{class:"absolute inset-0 bg-black/30 opacity-0 transition-opacity duration-200 pointer-events-auto","data-frs-panel-backdrop":!0}),jsxs("aside",{class:"absolute top-0 right-0 h-full w-full md:w-1/2 bg-base-100 shadow-2xl border-l border-base-300 translate-x-full transition-transform duration-200 pointer-events-auto flex flex-col","data-frs-panel":!0,role:"dialog","aria-label":"Relation preview",children:[jsxs("header",{class:"flex items-center justify-between px-5 py-3 border-b border-base-300 bg-base-200/40 shrink-0",children:[jsx("h2",{class:"font-semibold text-base truncate","data-frs-panel-title":!0,children:"Relation"}),jsx("button",{type:"button",class:"btn btn-sm btn-ghost btn-circle","data-frs-panel-close":!0,"aria-label":"Close panel",children:"\u2715"})]}),jsx("div",{class:"flex-1 overflow-auto p-5 text-sm","data-frs-panel-body":!0,children:jsx("div",{class:"flex items-center justify-center py-12 text-base-content/40",children:jsx("span",{class:"loading loading-spinner loading-md"})})})]})]});});var fs={};Zr(fs,{DEFAULT_HTML_CSP:()=>Er,securityHeaders:()=>Tn});function Tn(e={}){let t=e.csp===void 0?Er:e.csp,n=e.frameOptions===void 0?"DENY":e.frameOptions,r=e.referrerPolicy===void 0?"no-referrer":e.referrerPolicy,o=e.cacheControl===void 0?"private, no-store":e.cacheControl;return async(s,a,l)=>{typeof a?.setHeader=="function"&&(a.setHeader("X-Content-Type-Options","nosniff"),n&&a.setHeader("X-Frame-Options",n),r&&a.setHeader("Referrer-Policy",r),o&&a.setHeader("Cache-Control",o),t&&a.setHeader("Content-Security-Policy",t)),await l();}}var us,ps,Er,kn=St(()=>{"use strict";us="https://cdn.jsdelivr.net",ps="https://www.gstatic.com",Er=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${us} ${ps}`,`style-src 'self' 'unsafe-inline' ${us}`,`connect-src 'self' ${ps} https://*.googleapis.com https://*.firebaseio.com https://identitytoolkit.googleapis.com`,"img-src 'self' data:","font-src 'self' data:","frame-ancestors 'none'","base-uri 'self'","form-action 'self'"].join("; ");});var Qs=30,Vs=99,Xt="__name__",Gs=new Set(["<","<=",">",">=","!=","not-in"]);var Js=55296,Ys=57343;function Qr(e){return e>=Js&&e<=Ys}function lt(e,t){let n=Math.min(e.length,t.length);for(let r=0;r<n;r++){let o=e.charCodeAt(r),s=t.charCodeAt(r);if(o!==s){let a=Qr(o),l=Qr(s);return a===l?o<s?-1:1:a?1:-1}}return e.length<t.length?-1:e.length>t.length?1:0}function Vr(e){return e.length>6&&e.startsWith("__id")&&e.endsWith("__")&&/^-?\d+$/.test(e.slice(4,-2))}function Xs(e,t){let n=Vr(e),r=Vr(t);if(n&&!r)return -1;if(!n&&r)return 1;if(n&&r){let o=BigInt(e.slice(4,-2)),s=BigInt(t.slice(4,-2));return o<s?-1:o>s?1:0}return lt(e,t)}function to(e,t){let n=e.split("/"),r=t.split("/"),o=Math.min(n.length,r.length);for(let s=0;s<o;s++){let a=Xs(n[s],r[s]);if(a!==0)return a}return n.length<r.length?-1:n.length>r.length?1:0}function ea(e,t){let n=e.split("."),r=t.split("."),o=Math.min(n.length,r.length);for(let s=0;s<o;s++){let a=lt(n[s],r[s]);if(a!==0)return a}return n.length<r.length?-1:n.length>r.length?1:0}function vt(e,t){return e<t?-1:e>t?1:e===t?0:Number.isNaN(e)?Number.isNaN(t)?0:-1:1}function Mn(e){if(e instanceof Date){let t=e.getTime();if(Number.isNaN(t))return {seconds:Number.NaN,nanos:0};let n=Math.floor(t/1e3),r=(t%1e3+1e3)%1e3;return {seconds:n,nanos:r*1e6}}if(typeof e=="object"&&e!==null){let t=e;if(typeof t.seconds=="number"&&typeof t.nanoseconds=="number"&&typeof t.toDate=="function")return {seconds:t.seconds,nanos:t.nanoseconds};if(typeof t._seconds=="number"&&typeof t._nanoseconds=="number"&&Object.keys(t).length===2)return {seconds:t._seconds,nanos:t._nanoseconds}}return null}function ta(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.path=="string"&&typeof t.id=="string"&&typeof t.firestore=="object"&&t.firestore!==null}function na(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.latitude=="number"&&typeof t.longitude=="number"&&typeof t.isEqual=="function"}function Gr(e){if(e===void 0)return -1;if(e===null)return 0;let t=typeof e;return t==="boolean"?1:t==="number"||t==="bigint"?2:t==="string"?4:e instanceof Uint8Array?5:Mn(e)!==null?3:ta(e)?6:na(e)?7:Array.isArray(e)?8:9}function ra(e,t){let n=Math.min(e.length,t.length);for(let r=0;r<n;r++){let o=e[r],s=t[r];if(o!==s)return o<s?-1:1}return e.length<t.length?-1:e.length>t.length?1:0}function Fn(e,t){let n=Gr(e),r=Gr(t);if(n!==r)return n<r?-1:1;switch(n){case -1:case 0:return 0;case 1:return e===t?0:e?1:-1;case 2:return vt(Number(e),Number(t));case 3:{let o=Mn(e),s=Mn(t),a=vt(o.seconds,s.seconds);return a!==0?a:vt(o.nanos,s.nanos)}case 4:return lt(e,t);case 5:return ra(e,t);case 6:return to(e.path,t.path);case 7:{let o=e,s=t,a=vt(o.latitude,s.latitude);return a!==0?a:vt(o.longitude,s.longitude)}case 8:{let o=e,s=t,a=Math.min(o.length,s.length);for(let l=0;l<a;l++){let c=Fn(o[l],s[l]);if(c!==0)return c}return o.length<s.length?-1:o.length>s.length?1:0}case 9:{let o=e,s=t,a=Object.keys(o).sort(lt),l=Object.keys(s).sort(lt),c=Math.min(a.length,l.length);for(let u=0;u<c;u++){let p=a[u],f=l[u],b=lt(p,f);if(b!==0)return b;let h=Fn(o[p],s[f]);if(h!==0)return h}return a.length<l.length?-1:a.length>l.length?1:0}}}function Nn(e){return e.ref?.path??e.id}function Jr(e,t){if(typeof e.get=="function")return e.get(t);let n=e.data();if(!n)return;if(!t.includes("."))return n[t];let r=n;for(let o of t.split(".")){if(r==null||typeof r!="object")return;r=r[o];}return r}function oa(e,t){let n=[],r=new Set;if(e.orderBy)for(let a of e.orderBy){let l=String(a.field),c=a.direction==="desc"?"desc":"asc";r.has(l)||(n.push({field:l,direction:c}),r.add(l));}let o=n.length>0?n[n.length-1].direction:"asc",s=[];for(let[a,l]of t){let c=String(a);Gs.has(l)&&c!==Xt&&!r.has(c)&&(s.push(c),r.add(c));}s.sort(ea);for(let a of s)n.push({field:a,direction:o});return r.has(Xt)||n.push({field:Xt,direction:o}),n}function sa(e,t,n){for(let r of n){let o=r.field===Xt?to(Nn(e),Nn(t)):Fn(Jr(e,r.field),Jr(t,r.field));if(o!==0)return r.direction==="desc"?-o:o}return 0}function aa(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function ct(e,t){return t.orderBy&&t.orderBy.forEach(n=>{e=e.orderBy(String(n.field),n.direction??"asc");}),t.limit&&(e=e.limit(t.limit)),t.offset&&(e=e.offset(t.offset)),t.select&&t.select.length>0&&(e=e.select(...t.select.map(n=>String(n)))),t.startAt&&(e=Array.isArray(t.startAt)?e.startAt(...t.startAt):e.startAt(t.startAt)),t.startAfter&&(e=Array.isArray(t.startAfter)?e.startAfter(...t.startAfter):e.startAfter(t.startAfter)),t.endAt&&(e=Array.isArray(t.endAt)?e.endAt(...t.endAt):e.endAt(t.endAt)),t.endBefore&&(e=Array.isArray(t.endBefore)?e.endBefore(...t.endBefore):e.endBefore(t.endBefore)),e}function Yr(e){if(!e.offset||e.offset<=0)return e;let{offset:t,limit:n,...r}=e;return {...r,...n&&n>0?{limit:t+n}:{}}}function We(e){let[,t,n]=e;return (t==="in"||t==="array-contains-any")&&Array.isArray(n)&&n.length>30}function en(e){let[t,n,r]=e;return We(e)?aa(r,30).map(s=>[t,n,s]):[e]}function Ae(e,t){let n=e;for(let[r,o,s]of t)n=n.where(String(r),o,s);return n}async function Xr(e,t,n){let r=await Promise.all(e.map(f=>f.get())),o=new Map;r.forEach(f=>{f.docs.forEach(b=>{let h=Nn(b);o.has(h)||o.set(h,b);});});let s=r[0];if(!s)throw new Error("No snapshots returned");let a=oa(t,n),l=Array.from(o.values()).sort((f,b)=>sa(f,b,a)),c=t.offset&&t.offset>0?t.offset:0,u=t.limit&&t.limit>0?c+t.limit:void 0,p=c>0||u!==void 0?l.slice(c,u):l;return {...s,docs:p,size:p.length,empty:p.length===0,forEach:(f,b)=>{p.forEach(h=>f.call(b,h));}}}async function Qe(e,t){let n=t.orWhere&&t.orWhere.length>0,r=t.orWhereGroups&&t.orWhereGroups.length>0;if(!n&&!r){if(!t.where||t.where.length===0)return ct(e,t).get();if(!t.where.some(We)){let w=Ae(e,t.where);return w=ct(w,t),w.get()}let p=t.where.map(en),f=Tt(p);if(f.length===1){let w=Ae(e,f[0]);return w=ct(w,t),w.get()}let b=Yr(t),h=f.map(w=>{let T=Ae(e,w);return T=ct(T,b),T});return Xr(h,t,t.where)}let o=t.where??[],s=[...t.orWhere?.map(u=>[u])??[],...t.orWhereGroups??[]],a=[];for(let u of s){let p=[...o,...u];if(!p.some(We))a.push(p);else {let b=p.map(en),h=Tt(b);a.push(...h);}}if(a.length===1){let u=Ae(e,a[0]);return u=ct(u,t),u.get()}let l=Yr(t),c=a.map(u=>{let p=Ae(e,u);return p=ct(p,l),p});return Xr(c,t,o)}function Tt(e){if(e.length===0)return [[]];let t=e[0];if(e.length===1&&t)return t.map(s=>[s]);if(!t)return [[]];let n=e.slice(1),r=Tt(n),o=[];for(let s of t)for(let a of r)o.push([s,...a]);return o}function ia(e){return typeof Filter?.or=="function"&&typeof Filter?.and=="function"&&typeof Filter?.where=="function"&&typeof Query=="function"&&e instanceof Query}function ca(e,t){if(t.length<2)return false;let n=0,r=a=>{let[,l,c]=a;return !(We(a)||l==="not-in"||(l==="in"||l==="array-contains-any")&&(!Array.isArray(c)||c.length===0)||l==="!="&&(n++,n>1))};for(let a of e)if(!r(a))return false;let o=0,s=0;for(let a of t){for(let p of a)if(!r(p))return false;let l=[...e,...a],c=0,u=1;for(let[,p,f]of l)if((p==="array-contains"||p==="array-contains-any")&&(c++,c>1)||(p==="in"||p==="array-contains-any"?u*=f.length:p==="!="&&(u*=2),o+u>Qs))return false;if(o+=u,s+=u*l.length,s>Vs)return false}return true}function la(e,t,n){let r=n.map(s=>{let a=s.map(([l,c,u])=>Filter.where(String(l),c,u));return a.length===1?a[0]:Filter.and(...a)});return (t.length>0?Ae(e,t):e).where(Filter.or(...r))}function da(e){if(typeof e!="object"||e===null)return false;let t=e.code;if(t===3||t===9)return true;if(typeof t=="string"){let n=t.toLowerCase();return n==="invalid-argument"||n==="invalid_argument"||n==="failed-precondition"||n==="failed_precondition"}return false}async function eo(e,t){if(t.length===0)return {count:(await e.count().get()).data().count,isExact:true};if(!t.some(We))return {count:(await Ae(e,t).count().get()).data().count,isExact:true};let r=t.map(en),o=Tt(r),a=(await Promise.all(o.map(c=>Ae(e,c).count().get()))).reduce((c,u)=>c+u.data().count,0),l=t.some(c=>c[1]==="array-contains-any"&&We(c));return {count:a,isExact:!l}}async function jn(e,t){let n=t.where??[],r=[...t.orWhere?.map(l=>[l])??[],...t.orWhereGroups??[]].filter(l=>l.length>0);if(r.length===0)return eo(e,n);if(r.length===1)return eo(e,[...n,...r[0]]);if(ia(e)&&ca(n,r))try{return {count:(await la(e,n,r).count().get()).data().count,isExact:!0}}catch(l){if(!da(l))throw l}let o=[];for(let l of r){let c=[...n,...l];if(!c.some(We))o.push(Ae(e,c));else {let p=c.map(en),b=Tt(p).map(h=>Ae(e,h));o.push(...b);}}return {count:(await Promise.all(o.map(l=>l.count().get()))).reduce((l,c)=>l+c.data().count,0),isExact:false}}var Bn="preserve";function ua(e){Bn=e;}function nn(){return Bn}function pa(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function zn(e){if(e==null)return null;if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(e instanceof Timestamp)return e.toDate();if(pa(e))return new Date(e._seconds*1e3+Math.floor(e._nanoseconds/1e6));if(typeof e=="string"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}if(typeof e=="number"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null}function fa(e){if(typeof e!="object"||e===null)return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function tn(e){if(e instanceof Timestamp)return e.toDate();if(Array.isArray(e))return e.map(t=>tn(t));if(fa(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=tn(r);return t}return e}function ce(e){return Bn==="normalize"?tn(e):e}function ro(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function He(e){return e.charAt(0).toUpperCase()+e.slice(1)}function je(e,t){return t.where&&t.where.forEach(([n,r,o])=>{e=e.where(String(n),r,o);}),t.orderBy&&t.orderBy.forEach(n=>{e=e.orderBy(String(n.field),n.direction??"asc");}),t.limit&&(e=e.limit(t.limit)),t.offset&&(e=e.offset(t.offset)),t.select&&t.select.length>0&&(e=e.select(...t.select.map(n=>String(n)))),t.startAt&&(e=Array.isArray(t.startAt)?e.startAt(...t.startAt):e.startAt(t.startAt)),t.startAfter&&(e=Array.isArray(t.startAfter)?e.startAfter(...t.startAfter):e.startAfter(t.startAfter)),t.endAt&&(e=Array.isArray(t.endAt)?e.endAt(...t.endAt):e.endAt(t.endAt)),t.endBefore&&(e=Array.isArray(t.endBefore)?e.endBefore(...t.endBefore):e.endBefore(t.endBefore)),e}async function rn(e,t){let n={...t,limit:t.pageSize+1};t.cursor&&(t.direction==="prev"?n.endBefore=t.cursor:n.startAfter=t.cursor);let[r,o]=await Promise.all([Qe(e,n),t.withTotal?jn(e,t):Promise.resolve(void 0)]),s=r.docs,a=s.length>t.pageSize,l=a?s.slice(0,t.pageSize):s,c=l.map(p=>ce({...p.data(),docId:p.id})),u=t.direction==="prev";return {data:c,nextCursor:u?l.length>0?l[l.length-1]:void 0:a?l[l.length-1]:void 0,prevCursor:u?a?l[0]:void 0:l[0],hasNextPage:u?!!t.cursor:a,hasPrevPage:u?a:!!t.cursor,pageSize:c.length,...o!==void 0?{totalCount:o.count,totalCountIsExact:o.isExact}:{}}}async function*qn(e,t){let n,r=true;for(;r;){let o=await rn(e,{...t,cursor:n,direction:"next"});yield o,r=o.hasNextPage,n=o.nextCursor;}}var Ve="X-History-Reason",Ge="X-History-Comment",ao=Symbol.for("@lpdjs/firestore-repo-service:actorResolverHeaders"),Un=Symbol.for("@lpdjs/firestore-repo-service:actorContext"),Ln=globalThis,on=Ln[Un]??(Ln[Un]=new AsyncLocalStorage);function ma(e,t){if(!t.includes("."))return e[t];let n=e;for(let r of t.split(".")){if(!n||typeof n!="object")return;n=n[r];}return n}function oo(e,t){for(let n of t){let r=ma(e,n);if(typeof r=="string"&&r.length>0)return r;if(typeof r=="number")return String(r)}return null}function so(e,t){if(t===false)return;let n=e?.req?.header;if(typeof n!="function")return;let r=n.call(e.req,t);return typeof r=="string"&&r.length>0?r:void 0}function Kn(e={}){let t=e.contextKeys??["user","docsUser"],n=e.userIdFields??["uid","id","sub"],r=e.userEmailFields??["email"],o=e.reasonHeader===void 0?"x-history-reason":e.reasonHeader,s=e.commentHeader===void 0?"x-history-comment":e.commentHeader,a=e.reasonHeader===void 0?Ve:e.reasonHeader,l=e.commentHeader===void 0?Ge:e.commentHeader,c=e.extras,u=p=>{let f=null,b=p?.get;if(typeof b=="function")for(let S of t){let I=b.call(p,S);if(I&&typeof I=="object"){f=I;break}}let h=so(p,o),w=so(p,s),T=c?c(p,f):void 0;return f?{userId:oo(f,n),userEmail:oo(f,r),...h!==void 0?{reason:h}:{},...w!==void 0?{comment:w}:{},...T?{extras:T}:{}}:h===void 0&&w===void 0&&!T?null:{...h!==void 0?{reason:h}:{},...w!==void 0?{comment:w}:{},...T?{extras:T}:{}}};return Object.defineProperty(u,ao,{value:{reasonHeader:a,commentHeader:l},enumerable:false,configurable:false}),u}function Zn(e){if(!e)return {reasonHeader:Ve,commentHeader:Ge};if(typeof e=="function"){let t=e[ao];return t?{...t}:{reasonHeader:Ve,commentHeader:Ge}}return {reasonHeader:e.reasonHeader===void 0?Ve:e.reasonHeader,commentHeader:e.commentHeader===void 0?Ge:e.commentHeader}}var io=Kn();function ha(e){if(e)return typeof e=="function"?e:Kn(e)}function Wn(e){let t=ha(e);return async(n,r)=>{await on.run({c:n,resolver:t},async()=>{await r();});}}function ut(){let e=on.getStore();if(!e)return null;let t=null;if(e.c)try{t=(e.resolver??io)(e.c);}catch{t=null;}if(!t&&!e.override)return null;let n={...t??{}};return e.override&&(e.override.userId!==void 0&&(n.userId=e.override.userId),e.override.userEmail!==void 0&&(n.userEmail=e.override.userEmail),e.override.reason!==void 0&&(n.reason=e.override.reason),e.override.comment!==void 0&&(n.comment=e.override.comment),e.override.extras!==void 0&&(n.extras={...t?.extras??{},...e.override.extras})),n}function ga(e,t){return on.run({override:{...e}},t)}function ba(e){let t=on.getStore();if(!t)return false;let n=t.override??{},r={...n,...e};return (n.extras||e.extras)&&(r.extras={...n.extras??{},...e.extras??{}}),t.override=r,true}var Qn="_historyMeta";function Ee(e){if(!e?.enabled||e.shadow===false||e.meta&&e.shadow===void 0)return null;let t=e.shadow,n=typeof t=="string"&&t.trim().length>0?t.trim():typeof t=="object"&&t!==null&&typeof t.key=="string"&&t.key.trim().length>0?t.key.trim():Qn,r=typeof t=="object"&&t!==null?t.fields:void 0;return {key:n,fields:{userId:r?.userId??"userId",userEmail:r?.userEmail??"userEmail",reason:r?.reason??"reason",comment:r?.comment??"comment",extras:r?.extras??"extras"}}}function ve(e){return Ee(e)?.key??null}function Vn(e){let t=Ee(e);return t?[t.key]:[]}function ue(e,t){if(!t||!e||typeof e!="object"||Array.isArray(e))return e;let n=e;if(!(t in n))return e;let{[t]:r,...o}=n;return o}function xe(e,t){if(!t?.enabled||t.autoInjectMeta===false)return;let n=Ee(t);if(!n)return;let r=ut(),o=t.fallbackActor??{},s=r?.userId!==void 0?r.userId:o.userId??null,a=r?.userEmail!==void 0?r.userEmail:o.userEmail??null,l=r?.reason??null,c=r?.comment??null,u=r?.extras&&Object.keys(r.extras).length>0?r.extras:null,p={},{fields:f}=n;f.userId!==false&&(p[f.userId]=s),f.userEmail!==false&&(p[f.userEmail]=a),f.reason!==false&&(p[f.reason]=l),f.comment!==false&&(p[f.comment]=c),f.extras!==false&&(p[f.extras]=u),e[n.key]=p;}function Ct(e){if(e===null)return "null";if(e===void 0)return "undefined";if(e instanceof Timestamp)return "timestamp";if(e instanceof Date)return "date";if(Array.isArray(e))return "array";let t=typeof e;return t==="string"||t==="number"||t==="boolean"?t:"object"}function At(e,t,n=new WeakMap){if(e===t)return true;if(e===null||t===null||e===void 0||t===void 0)return e===t;if(e instanceof Timestamp&&t instanceof Timestamp)return e.isEqual(t);if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return false;if(n.get(e)===t)return true;n.set(e,t);for(let r=0;r<e.length;r++)if(!At(e[r],t[r],n))return false;return true}if(typeof e=="object"&&typeof t=="object"){if(e instanceof Date||t instanceof Date||e instanceof Timestamp||t instanceof Timestamp)return false;if(n.get(e)===t)return true;n.set(e,t);let r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return false;for(let s of r)if(!Object.prototype.hasOwnProperty.call(t,s)||!At(e[s],t[s],n))return false;return true}return false}function sn(e,t,n={}){let r=new Set([...n.exclude??[],...n.metaFields??[],...n.systemKeys??[]]),o=n.include?new Set(n.include):null,s=e??{},a=t??{},l=new Set([...Object.keys(s),...Object.keys(a)]),c={};for(let u of l){if(r.has(u)||o&&!o.has(u))continue;let p=s[u],f=a[u];At(p,f)||(c[u]={oldValue:p===void 0?null:p,newValue:f===void 0?null:f,type:{old:Ct(p),new:Ct(f)}});}return c}var wa=5;function xa(e){return e.schemaVersion===2}function co(e){if(typeof e!="string")return "object";switch(e){case "string":case "number":case "boolean":case "object":case "array":case "timestamp":case "date":case "null":case "undefined":return e;default:return "object"}}function Ra(e){return {historyDocId:e.historyDocId,historyToObjectId:e.historyToObjectId,historySetAt:e.historySetAt,schemaVersion:2,operation:e.operation,meta:e.meta??{},...e.custom?{custom:e.custom}:{},changes:e.changes??{}}}function Sa(e){let t={};e.historyUserId!==void 0&&(t.userId=e.historyUserId??null),e.historyUserEmail!==void 0&&(t.userEmail=e.historyUserEmail??null);let n=e.extraHistoryDetails??null;n&&(n.reason!==void 0&&(t.reason=n.reason??null),n.comment!==void 0&&(t.comment=n.comment??null));let r={},o=false;if(e.historyDetails&&typeof e.historyDetails=="object")for(let[s,a]of Object.entries(e.historyDetails))r[s]=a,o=true;if(e.extraContentKeys&&typeof e.extraContentKeys=="object")for(let[s,a]of Object.entries(e.extraContentKeys))r[`content.${s}`]=a,o=true;return o&&(t.extras=r),t}function va(e){let t=e.changes?.oldValue??null,n=e.changes?.newValue??null,r=e.types?.oldValue,o=e.types?.newValue;return {oldValue:t,newValue:n,type:{old:r?co(r):Ct(t),new:o?co(o):Ct(n)}}}function Ta(e){let t=va(e),n=Sa(e);return {historyDocId:e.historyDocId,historyToObjectId:e.historyToObjectId,historySetAt:e.historySetAt,schemaVersion:1,operation:"update",meta:n,changes:{[e.field]:t}}}function ka(e,t,n){return Math.abs(e.toMillis()-t.toMillis())<=n}function Ca(e,t){return (e.userId??null)===(t.userId??null)}function lo(e,t={}){let n=t.groupToleranceMs??wa,r=[];for(let o of e){if(xa(o)){r.push(Ra(o));continue}let a=Ta(o),l=r[r.length-1];l&&l.schemaVersion===1&&ka(l.historySetAt,a.historySetAt,n)&&Ca(l.meta,a.meta)?Object.assign(l.changes,a.changes):r.push(a);}return r}var Ea=7e5;function Et(e){let t=e.ttlOverride??e.config.ttl,r={schemaVersion:2,historyDocId:randomUUID(),historyToObjectId:e.entityId,historySetAt:Timestamp.now(),operation:e.operation,meta:e.meta,...e.custom?{custom:e.custom}:{},changes:e.changes};t&&(r.expiresAt=Timestamp.fromMillis(Date.now()+t.days*24*60*60*1e3));let o=s=>{try{return Buffer.byteLength(JSON.stringify(s,(a,l)=>l instanceof Timestamp?l.toMillis():l),"utf8")}catch{return 0}};if(o(r.changes)>Ea){let s={};for(let[a,l]of Object.entries(r.changes)){let c=o(l.oldValue),u=o(l.newValue);s[a]={oldValue:c>5e4?"[truncated]":l.oldValue,newValue:u>5e4?"[truncated]":l.newValue,type:l.type};}r.changes=s,r._truncated=true;}return r}async function Ot(e,t,n,r){let o=t;return n.onBeforeWrite&&(o=await n.onBeforeWrite(t,r)),o?(await e.doc(o.historyDocId).set(o),{written:true,entry:o}):{written:false,reason:"dropped-by-onBeforeWrite"}}function an(e,t){let n=e??{},r={},o=Ee(t);if(o){let f=n[o.key];if(f&&typeof f=="object"&&!Array.isArray(f)){let b=f,h=A=>{if(A===false||!(A in b))return;let O=b[A];return O==null?null:String(O)},w=h(o.fields.userId);w!==void 0&&(r.userId=w);let T=h(o.fields.userEmail);T!==void 0&&(r.userEmail=T);let S=h(o.fields.reason);S!==void 0&&(r.reason=S);let I=h(o.fields.comment);if(I!==void 0&&(r.comment=I),o.fields.extras!==false){let A=b[o.fields.extras];A&&typeof A=="object"&&!Array.isArray(A)&&Object.keys(A).length>0&&(r.extras=A);}}return r}let s=t.meta;if(!s)return r;let a=f=>{if(!f)return;let b=n[f];return b===void 0||b===null?null:String(b)},l=a(s.userId);l!==void 0&&(r.userId=l);let c=a(s.userEmail);c!==void 0&&(r.userEmail=c);let u=a(s.reason);u!==void 0&&(r.reason=u);let p=a(s.comment);if(p!==void 0&&(r.comment=p),s.extras&&s.extras.length>0){let f={},b=false;for(let h of s.extras)h in n&&(f[h]=n[h],b=true);b&&(r.extras=f);}return r}function cn(e){let t=[],n=Ee(e);n&&t.push(n.key);let r=e.meta;return r&&(r.userId&&t.push(r.userId),r.userEmail&&t.push(r.userEmail),r.reason&&t.push(r.reason),r.comment&&t.push(r.comment),r.extras&&t.push(...r.extras)),t}var Oa="history",Pa=50;function Jn(e,t,n){return e(...n).collection(t)}function uo(e){return String(e[e.length-1]??"")}function po(e,t,n,r){if(!r?.enabled)return null;let o=r.subcollection??Oa;async function s(...h){let w={},T=h,S=h[h.length-1];S!==null&&typeof S=="object"&&!(S instanceof Timestamp)&&("limit"in S||"cursor"in S||"direction"in S)&&(w=S,T=h.slice(0,-1));let I=Jn(e,o,T),A=w.direction??"desc",O=I.orderBy("historySetAt",A);return w.cursor&&(O=O.startAfter(w.cursor)),w.limit&&w.limit>0&&(O=O.limit(w.limit)),(await O.get()).docs.map(d=>({id:d.id,data:d.data()}))}async function a(...h){let w={},T=h,S=h[h.length-1];S!==null&&typeof S=="object"&&!(S instanceof Timestamp)&&("limit"in S||"cursor"in S||"direction"in S||"fields"in S||"operations"in S)&&(w=S,T=h.slice(0,-1));let I=w.limit??Pa,A=Math.max(I,Math.min(I*8,500)),O=await s(...T,{limit:A,cursor:w.cursor,direction:w.direction??"desc"}),x=lo(O.map(d=>d.data));if(w.fields&&w.fields.length>0){let d=new Set(w.fields);x=x.filter(y=>Object.keys(y.changes).some(i=>d.has(i)));}if(w.operations&&w.operations.length>0){let d=new Set(w.operations);x=x.filter(y=>d.has(y.operation));}return x.slice(0,I)}async function l(...h){let w=h[h.length-1],T={},S,I;return w!==null&&typeof w=="object"&&!(w instanceof Timestamp)?(T=w,S=h[h.length-2],I=h.slice(0,-2)):(S=w,I=h.slice(0,-1)),a(...I,{...T,fields:[S]})}async function c(...h){let w=h[h.length-1],T={},S,I;return w!==null&&typeof w=="object"&&!(w instanceof Timestamp)?(T=w,S=h[h.length-2],I=h.slice(0,-2)):(S=w,I=h.slice(0,-1)),a(...I,{...T,operations:[S]})}function u(h){let w={title:h.title,display:h.display??true};return h.description!==void 0&&(w.description=h.description),h.key!==void 0&&(w.key=h.key),h.data!==void 0&&(w.data=h.data),w}function p(){let h=ut(),w=r.fallbackActor??{},T=h?.userId!==void 0?h.userId:w.userId??null,S=h?.userEmail!==void 0?h.userEmail:w.userEmail??null;return {userId:T,userEmail:S,...h?.reason!==void 0?{reason:h.reason}:{},...h?.comment!==void 0?{comment:h.comment}:{},...h?.extras&&Object.keys(h.extras).length>0?{extras:h.extras}:{}}}async function f(...h){let w=h[h.length-1],T=h.slice(0,-1),S=uo(T),I=sn(w.before??{},w.after??{},{include:r.include,exclude:r.exclude,metaFields:cn(r),systemKeys:t});if(w.operation==="update"&&Object.keys(I).length===0)return null;let A=an(w.after??w.before??null,r),O=ut(),d={...O?{...O.userId!==void 0?{userId:O.userId}:{},...O.userEmail!==void 0?{userEmail:O.userEmail}:{},...O.reason!==void 0?{reason:O.reason}:{},...O.comment!==void 0?{comment:O.comment}:{},...O.extras&&Object.keys(O.extras).length>0?{extras:O.extras}:{}}:{},...A,...w.meta??{}},y=w.custom?u(w.custom):void 0,i=Et({entityId:S,operation:w.operation,changes:I,meta:d,custom:y,config:r}),g=Jn(e,o,T),m=await Ot(g,i,r,{repoName:n,docId:S,before:w.before??null,after:w.after??null});return !m.written||!m.entry?null:{historyDocId:m.entry.historyDocId,historyToObjectId:m.entry.historyToObjectId,historySetAt:m.entry.historySetAt,schemaVersion:2,operation:m.entry.operation,meta:m.entry.meta,...m.entry.custom?{custom:m.entry.custom}:{},changes:m.entry.changes}}async function b(...h){let w=h[h.length-1],T=h.slice(0,-1),S=uo(T),I=u(w),A={...p(),...w.meta??{}},O=Et({entityId:S,operation:"custom",changes:{},meta:A,custom:I,config:r}),x=Jn(e,o,T),d=await Ot(x,O,r,{repoName:n,docId:S,before:null,after:null});return !d.written||!d.entry?null:{historyDocId:d.entry.historyDocId,historyToObjectId:d.entry.historyToObjectId,historySetAt:d.entry.historySetAt,schemaVersion:2,operation:d.entry.operation,meta:d.entry.meta,...d.entry.custom?{custom:d.entry.custom}:{},changes:d.entry.changes}}return {list:a,raw:s,byField:l,byOperation:c,recordManual:f,recordCustom:b}}function fo(e){return {count:async(t={})=>{let n=e;return n=je(n,t),(await n.count().get()).data().count},sum:async(t,n={})=>{let r=e;r=je(r,n);let o=await r.get(),s=0;return o.forEach(a=>{let l=a.data()[t];typeof l=="number"&&(s+=l);}),s},average:async(t,n={})=>{let r=e;r=je(r,n);let o=await r.get();if(o.empty)return null;let s=0,a=0;return o.forEach(l=>{let c=l.data()[t];typeof c=="number"&&(s+=c,a++);}),a>0?s/a:null}}}function yo(e,t,n,r,o,s,a){let l=()=>new Date;return {create:()=>{let c=e.batch();return {batch:c,set:(...u)=>{let p=u[u.length-1],f=typeof p=="object"&&p!==null&&"merge"in p,b=f?u[u.length-2]:u[u.length-1],h=f?u.slice(0,-2):u.slice(0,-1),w=f?p:{merge:true},T=t(...h),S={...b},I=h[h.length-1];n&&I&&(S[n]=I),r&&(S[r]=T.path),o&&S[o]===void 0&&(S[o]=l()),s&&(S[s]=l()),xe(S,a),c.set(T,S,w);},update:(...u)=>{let p=u.pop(),b=t(...u),h={...p};s&&(h[s]=l()),xe(h,a),c.update(b,h);},delete:(...u)=>{let p=t(...u);c.delete(p);},commit:async()=>{await c.commit();}}}}}var Ia=new Set([4,8,10,13,14]);function Yn(e,t){let n=[],r=t.maxAttempts??5;return e.onWriteError(o=>{let s=o?.code;if(o.failedAttempts<r&&s!==void 0&&Ia.has(s))return true;let a={ref:o.documentRef,error:o};return n.push(a),t.onError?.(a),false}),t.onSuccess&&e.onWriteResult(o=>t.onSuccess(o)),n}function Xn(e,t){if(e.length>0&&!t.onError){let n=new Error(`bulk operation failed for ${e.length} document(s): `+e.slice(0,5).map(r=>`${r.ref.path} (${r.error.message})`).join("; "));throw n.failures=e,n}return {failures:e}}function mo(e,t,n,r){let o=()=>new Date;return {set:async(s,a={})=>{let l=e.bulkWriter(),c=Yn(l,a);try{for(let u of s){if(!u)continue;let{docRef:p,data:f,merge:b=!0}=u,h={...f};t&&h[t]===void 0&&(h[t]=o()),n&&(h[n]=o()),xe(h,r),Promise.resolve(l.set(p,h,{merge:b})).catch(()=>{});}}finally{await l.close();}return Xn(c,a)},update:async(s,a={})=>{let l=e.bulkWriter(),c=Yn(l,a);try{for(let u of s){if(!u)continue;let{docRef:p,data:f}=u,b={...f};n&&(b[n]=o()),xe(b,r),Promise.resolve(l.update(p,b)).catch(()=>{});}}finally{await l.close();}return Xn(c,a)},delete:async(s,a={})=>{let l=e.bulkWriter(),c=Yn(l,a);try{for(let u of s)u&&Promise.resolve(l.delete(u)).catch(()=>{});}finally{await l.close();}return Xn(c,a)}}}var er="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Be(){let e="";for(;e.length<20;){let t=randomBytes(20);for(let n=0;n<t.length&&e.length<20;n++){let r=t[n];r>=er.length*4||(e+=er.charAt(r%er.length));}}return e}function tr(e){return e.match(/^\{([^}]+)\}$/)?.[1]?.trim()||null}function _e(e,t="docId",n=false){if(typeof e!="string"||!e.trim())return {rawPath:e??"",collectionId:"",collectionPath:"",parentKeys:[],documentPathTemplate:null,hasTemplate:false};let r=e.split("/").map(f=>f.trim()).filter(Boolean);if(r.length===0)return {rawPath:e,collectionId:e,collectionPath:e,parentKeys:[],documentPathTemplate:null,hasTemplate:false};if(r.length===1){let f=r[0];return {rawPath:e,collectionId:f,collectionPath:f,parentKeys:[],documentPathTemplate:n?null:`${f}/{${t}}`,hasTemplate:e.includes("{")&&e.includes("}")}}let o=r.length%2===0,s=o?r.slice(0,-1):r,a=s[s.length-1],l=s.join("/"),u=s.slice(0,-1).map(tr).filter(f=>f!==null),p=o?r.join("/"):`${l}/{${t}}`;return {rawPath:e,collectionId:a,collectionPath:l,parentKeys:u,documentPathTemplate:p,hasTemplate:true}}function ho(e,t,n){let r=t.split("/").map(c=>c.trim()).filter(Boolean),o=0,s=[];for(let c of r){let u=tr(c);if(u!==null){let p=n[o++];if(typeof p!="string"||p.trim()==="")throw new Error(`Missing or empty path parameter "${u}" when resolving document reference for "${t}".`);s.push(p);}else s.push(c);}let a=e;if(typeof a?.collection=="function"&&s.length>=2){let c=a,u=true;for(let p=0;p<s.length;p+=2){let f=s[p],b=s[p+1];if(typeof c?.collection!="function"){u=false;break}let h=c.collection(f);if(typeof h?.doc!="function"){u=false;break}c=h.doc(b);}if(u&&c&&c!==a)return c}let l=s.join("/");if(typeof a?.doc=="function")return a.doc(l);if(typeof a?.collection=="function"&&s.length>=2){let c=s.slice(0,-1).join("/"),u=s[s.length-1],p=a.collection(c);return typeof p?.doc=="function"?p.doc(u):p}throw new Error(`Cannot resolve DocumentReference for "${l}": Firestore instance does not expose .collection() or .doc().`)}function Je(e,t={}){if(!e||typeof e!="object")return;let{pathKey:n,documentKey:r="docId",parentKeys:o,documentPathTemplate:s,isGroup:a}=t,l=n&&typeof e[n]=="string"&&e[n]?e[n]:void 0;if(l&&s){let c=l.split("/").filter(Boolean),u=s.split("/").filter(Boolean);if(c.length===u.length){let p=[];for(let f=0;f<u.length;f++)tr(u[f])!==null&&p.push(c[f]);if(p.length>0)return p}}if(o&&o.length>0){let c=o.length+1;if(l){let p=l.split("/").filter(Boolean),f=[];for(let b=1;b<p.length;b+=2)f.push(p[b]);if(f.length>=c)return f.slice(f.length-c)}let u=r?e[r]:void 0;if(typeof u=="string"&&u.trim()!==""){let p=[],f=true;for(let b of o){let h=e[b];if(typeof h=="string"&&h.trim()!=="")p.push(h);else {f=false;break}}if(f)return [...p,u]}}if(l){let c=l.split("/").filter(Boolean),u=[];for(let p=1;p<c.length;p+=2)u.push(c[p]);if(u.length>0)return !a&&(!o||o.length===0)?[u[u.length-1]]:u}}function go(e,t,n,r,o,s,a=[],l,c){let u=()=>new Date,p=ve(c);return {create:async(...T)=>{let S=T[T.length-1],I=T.slice(0,-1);if(!S||typeof S!="object")throw new Error("Create data payload must be an object.");let A,O,x=typeof S[n]=="string"&&S[n].trim()!=="",d={...S};if(o&&d[o]===void 0&&(d[o]=u()),s&&(d[s]=u()),xe(d,c),e&&I.length===0)if(x){O=S[n],A=typeof e.doc=="function"?e.doc(O):t(O),d[n]=O;let y=r&&A?.path?{...d,[r]:A.path}:d;await A.set(y),r&&A?.path&&(d[r]=A.path);}else if(typeof e.add=="function"){A=await e.add(d),O=A.id,d[n]=O;let y={[n]:O};r&&A?.path&&(y[r]=A.path,d[r]=A.path),await A.update(y);}else O=Be(),A=typeof e.doc=="function"?e.doc(O):t(O),d[n]=A?.id??O,r&&A?.path&&(d[r]=A.path),await A.set(d);else {let y=[];if(I.length>0)for(let i=0;i<I.length;i++){let g=I[i];if(typeof g!="string"||g.trim()===""){let m=a[i]??`arg[${i}]`;throw new Error(`Missing or empty parent key "${m}" for subcollection create()`)}y.push(g);}else if(a.length>0){let i=[];for(let g of a){let m=S[g];typeof m=="string"&&m.trim()!==""?y.push(m):i.push(g);}if(i.length>0){let g=Je(S,{pathKey:r,documentKey:n,parentKeys:a,documentPathTemplate:l,isGroup:true});if(g&&g.length>=a.length)y=g.slice(0,a.length);else throw new Error(`Missing or empty required parent key(s) in data for subcollection create(): ${i.join(", ")}`)}}else if(r&&typeof S[r]=="string"&&S[r].trim()!==""){let i=Je(S,{pathKey:r,documentKey:n,parentKeys:a,documentPathTemplate:l,isGroup:true});i&&i.length>1&&(y=i.slice(0,-1));}if(y.length===0)throw new Error("Cannot use create() on collection groups without parent keys. Configure a path template (e.g. 'residences/{residenceId}/events') or provide parent keys in data.");O=x?S[n]:Be(),A=t(...y,O),d[n]=A?.id??O,r&&A?.path&&(d[r]=A.path),await A.set(d);}if(typeof A?.get=="function"){let y=await A.get(),i=typeof y?.data=="function"?y.data():d;return ue(ce(i??d),p)}return ue(ce(d),p)},set:async(...T)=>{let S=T[T.length-1],I=typeof S=="object"&&S!==null&&"merge"in S,A=I?T[T.length-2]:T[T.length-1],O=I?T.slice(0,-2):T.slice(0,-1),x=I?S:{merge:true},d={...A};o&&d[o]===void 0&&(d[o]=u()),s&&(d[s]=u()),xe(d,c);let y=t(...O),i=O[O.length-1];if(n&&i!=null&&(d[n]=i),r&&(d[r]=y.path),await y.set(d,x),typeof y?.get=="function"){let g=await y.get(),m=typeof g?.data=="function"?g.data():d;return ue(ce(m??d),p)}return ue(ce(d),p)},update:async(...T)=>{let S=T.pop(),I=T,A={...S};s&&(A[s]=u()),xe(A,c);let O=t(...I);await O.update(A);let x=await O.get();return ue(ce(x.data()),p)},delete:async(...T)=>{await t(...T).delete();}}}function bo(e,t,n,r,o,s=null){let a={};return a.byList=async(l,c,u="in",p={})=>{if(c.length===0)return [];let f=[],b=ro(c,30);for(let h of b){let w=e;w=w.where(l,u,h),p.select&&p.select.length>0&&(w=w.select(...p.select.map(S=>String(S)))),(await w.get()).forEach(S=>{let I=ue(ce(S.data()),s);f.push(p.returnDoc?{data:I,doc:S}:I);});}return f},t.forEach(l=>{let c=`by${He(String(l))}`;a[c]=async(...u)=>{let p={},f=u[u.length-1];if(typeof f=="boolean"?(p={returnDoc:f},u=u.slice(0,-1)):typeof f=="object"&&f!==null&&!Array.isArray(f)&&(p=f,u=u.slice(0,-1)),String(l)===o&&(u.length>1||u.length===1&&n!==null)){let A=await r(...u).get();if(!A.exists)return null;let O=ue(ce(A.data()),s);return p.returnDoc?{data:O,doc:A}:O}let b=u[0];if(b===void 0)return null;let h=e;h=h.where(String(l),"==",b).limit(1),p.select&&p.select.length>0&&(h=h.select(...p.select.map(I=>String(I))));let w=await h.get();if(w.empty)return null;let T=w.docs[0];if(!T)return null;let S=ue(ce(T.data()),s);return p.returnDoc?{data:S,doc:T}:S};}),a}function wo(e,t,n,r,o=null){let s={},a=c=>ue(ce(c),o),l=async(c,u)=>{if(!n||!r||u.length===0)return c;let p=u.map(f=>typeof f=="string"?{key:f}:{key:f.relation,select:f.select});return Promise.all(c.map(async f=>{let b=await Promise.all(p.map(async({key:w,select:T})=>{let S=n[w];if(!S)return [w,void 0];let I=r[S.repo];if(!I)return [w,void 0];let A=S.sourceKey||w,O=f[A];if(O==null)return [w,S.type==="one"?null:[]];let x=T?{select:T}:void 0;try{if(S.type==="one"){let d=`by${He(S.key)}`,y=typeof I.get?.[d]=="function"?await I.get[d](O,x):null;return [w,y]}else {let d=`by${He(S.key)}`,y=typeof I.query?.[d]=="function"?await I.query[d](O,x):[];return [w,y]}}catch(d){return console.error(`[include] Error populating "${w}":`,d),[w,S.type==="one"?null:[]]}})),h={};for(let[w,T]of b)w!==void 0&&(h[w]=T);return {...f,populated:h}}))};return t.forEach(c=>{let u=`by${He(c)}`;s[u]=async(p,f={})=>{let b={...f,where:[[c,"==",p],...f.where??[]]};return (await Qe(e,b)).docs.map(w=>a(w.data()))};}),s.by=async c=>(await Qe(e,c)).docs.map(p=>a(p.data())),s.getAll=async(c={})=>(await Qe(e,c)).docs.map(p=>a(p.data())),s.onSnapshot=(c,u,p)=>je(e,c).onSnapshot(b=>{u(b.docs.map(h=>a(h.data())));},p),s.paginate=async c=>{let{include:u,...p}=c,f=await rn(e,p),b=o?{...f,data:f.data.map(h=>ue(h,o))}:f;if(u&&u.length>0){let h=await l(b.data,u);return {...b,data:h}}return b},s.paginateAll=async function*(c){let{include:u,...p}=c;for await(let f of qn(e,p)){let b=o?{...f,data:f.data.map(h=>ue(h,o))}:f;if(u&&u.length>0){let h=await l(b.data,u);yield {...b,data:h};}else yield b;}},s}function xo(e,t){return {populate:async(n,r)=>{if(!e.relationalKeys)return {...n,populated:{}};let o,s={};if(typeof r=="object"&&!Array.isArray(r))if("relation"in r){let c=r;o=[c.relation],c.select&&(s[c.relation]=c.select);}else if("relations"in r){let c=r;o=Array.isArray(c.relations)?c.relations:[c.relations],s=c.select??{};}else o=[];else o=Array.isArray(r)?r:[r];let a=await Promise.all(o.map(async c=>{let u=e.relationalKeys?.[c];if(!u)return console.warn(`[populate] Relation "${c}" not found in config`),[c,void 0];let p=t[u.repo];if(!p)return console.warn(`[populate] Repository "${u.repo}" not found in mapping`),[c,void 0];let f=u.sourceKey||c,b=n[f];if(b==null)return [c,u.type==="one"?null:[]];let h=s[c],w=h?{select:h}:void 0;try{if(u.type==="one"){let T=`by${He(u.key)}`,S=typeof p.get?.[T]=="function"?await p.get[T](b,w):null;return [c,S]}else {let T=`by${He(u.key)}`,S=typeof p.query?.[T]=="function"?await p.query[T](b,w):[];return [c,S]}}catch(T){return console.error(`[populate] Error populating "${c}":`,T),[c,u.type==="one"?null:[]]}})),l={};for(let[c,u]of a)u!==void 0&&(l[c]=u);return {...n,populated:l}}}}var Ro=new Set([4,8,10,13,14]),Ha=5,_a=3,Ma=100,Fa=500;async function Na(e){let t=0;for(;;){t++;try{return await e.get()}catch(n){let r=n?.code;if(!(typeof r=="number"&&Ro.has(r))||t>=_a)throw n;let s=Ma*2**(t-1);await new Promise(a=>setTimeout(a,s));}}}function So(e,t,n,r,o,s){let a=()=>new Date;return {backfillKeys:async(c={})=>{let{overwriteCreated:u=false,touchUpdated:p=true,overwritePath:f=false,pageSize:b=300,dryRun:h=false,maxAttempts:w=5,flushThreshold:T=Fa,onError:S,onSuccess:I}=c,A=Math.max(1,T),O=Array.from(new Set([n,r,o,s].filter(C=>typeof C=="string"&&C.length>0))),x=[],d=0,y=0,i=0,g=0,m=h?null:e.bulkWriter();try{m&&(m.onWriteError(k=>{let R=k?.code;if(R===Ha)return i++,!1;if(k.failedAttempts<w&&R!==void 0&&Ro.has(R))return !0;let P={path:k?.documentRef?.path??"(unknown)",error:k};return x.push(P),S?.(P),!1}),m.onWriteResult(k=>{y++,I?.(k.path);}));let C;for(;;){let k=t.orderBy(FieldPath.documentId());O.length>0&&typeof k.select=="function"&&(k=k.select(...O)),C&&(k=k.startAfter(C)),k=k.limit(b);let R=await Na(k);if(R.empty)break;for(let P of R.docs){d++;let _=P.data(),$={};if(n&&(_[n]==null||_[n]==="")&&($[n]=P.id),r&&(f||_[r]==null||_[r]==="")&&_[r]!==P.ref.path&&($[r]=P.ref.path),o&&(u||_[o]==null)&&($[o]=P.createTime?.toDate?.()??a()),p&&s&&_[s]==null&&($[s]=P.updateTime?.toDate?.()??P.createTime?.toDate?.()??a()),Object.keys($).length===0){i++;continue}m?(Promise.resolve(m.update(P.ref,$)).catch(()=>{}),g++,g>=A&&typeof m.flush=="function"&&(await m.flush(),g=0)):y++;}if(R.size<b)break;C=R.docs[R.docs.length-1];}}finally{m&&await m.close();}return {scanned:d,written:y,skipped:i,failures:x}}}}function vo(e,t,n,r,o,s,a){let l=()=>new Date,c=ve(a);return {run:async u=>e.runTransaction(async p=>u({get:async(...b)=>{let h=t(...b),w=await p.get(h);return w.exists?ue(ce({...w.data(),docId:w.id}),c):null},set:(...b)=>{let h=b[b.length-1],w=typeof h=="object"&&h!==null&&"merge"in h,T=w?b[b.length-2]:b[b.length-1],S=w?b.slice(0,-2):b.slice(0,-1),I=w?h:{merge:true},A=t(...S),O={...T},x=S[S.length-1];n&&x&&(O[n]=x),r&&(O[r]=A.path),o&&O[o]===void 0&&(O[o]=l()),s&&(O[s]=l()),xe(O,a),p.set(A,O,I);},update:(...b)=>{let h=b[b.length-1],w=b.slice(0,-1),T=t(...w),S={...h};s&&(S[s]=l()),xe(S,a),p.update(T,S);},delete:(...b)=>{let h=t(...b);p.delete(h);},raw:p}))}}function To(e){if(typeof e!="function")return [];let n=e.toString().match(/^\s*(?:function\s*\w*\s*)?\(([^)]*)\)/);if(!n?.[1])return [];let r=n[1].split(",").map(o=>o.trim().replace(/\s*[:=].*$/,"").trim()).filter(Boolean);return r.length<=2?[]:r.slice(1,-1)}function ja(e){let t=e?.documentKey??"docId",n=!!e?.isGroup,r=_e(typeof e?.path=="string"?e.path:"",t,n),o=r.parentKeys.length>0?r.parentKeys:n?To(e?.refCb):[],s=[e?.documentKey,e?.pathKey,e?.createdKey,e?.updatedKey].filter(l=>typeof l=="string"),a=e?.history&&typeof e.history=="object"?e.history:void 0;return {schema:e?.schema,_systemKeys:s,_pathKey:e?.pathKey??null,_isGroup:n,_createdKey:e?.createdKey??null,_parentKeys:o,_documentPathTemplate:r.documentPathTemplate,_collectionId:typeof e?.path=="string"?r.collectionId:null,relationalKeys:e?.relationalKeys,_historyConfig:a,_historyShadowKey:ve(a),_historyIdentityKeys:Vn(a),_historySubcollection:a?.enabled?a.subcollection??"history":void 0,_collectionPath:typeof e?.path=="string"?r.collectionPath:null}}function dn(e,t){let n=ja(e),r,o=()=>{let s=r??(r=t());if(!s){let a=n._collectionPath||"unknown";throw new Error(`[makeLazyRepo] Failed to resolve repository for path "${a}". The repository mapping resolved to undefined. This almost always indicates a circular import where the repository was exported as undefined.`)}return s};return new Proxy(n,{get(s,a){return typeof a=="string"&&a in n?n[a]:o()[a]},has(s,a){return typeof a=="string"&&a in n?true:a in o()}})}function nr(e,t,n={}){let r=t.documentKey,o=_e(t.path,r,!!t.isGroup),s=o.parentKeys.length>0?o.parentKeys:t.isGroup?To(t.refCb):[],a=t.isGroup?e.collectionGroup(o.collectionId):e.collection(o.collectionPath),l=t.isGroup?null:e.collection(o.collectionPath),c=typeof t.refCb=="function"?(...y)=>t.refCb(e,...y):(...y)=>ho(e,o.documentPathTemplate??`${o.collectionPath}/{${r}}`,y),u=t.history,p=ve(u),f=Vn(u),b=bo(a,t.foreignKeys,l,c,r,p),h=wo(a,t.queryKeys,t.relationalKeys,n,p),w=fo(a),T=go(l,c,r,t.pathKey,t.createdKey,t.updatedKey,s,o.documentPathTemplate,u),S=yo(e,c,t.documentKey,t.pathKey,t.createdKey,t.updatedKey,u),I=vo(e,c,t.documentKey,t.pathKey,t.createdKey,t.updatedKey,u),A=mo(e,t.createdKey,t.updatedKey,u),O=So(e,a,t.documentKey,t.pathKey,t.createdKey,t.updatedKey),x=xo(t,n),d=u?.enabled?po(c,[t.documentKey,t.pathKey,t.createdKey,t.updatedKey].filter(y=>typeof y=="string"),t.path??"(unknown)",u):null;return {ref:a,documentRef:c,get:b,query:h,aggregate:w,...T,batch:S,transaction:I,bulk:A,system:O,...x,...d?{history:d}:{},_historySubcollection:d?u?.subcollection??"history":void 0,_historyConfig:u,_historyShadowKey:p,_historyIdentityKeys:f,schema:t.schema,relationalKeys:t.relationalKeys,_systemKeys:[t.documentKey,t.pathKey,t.createdKey,t.updatedKey].filter(y=>typeof y=="string"),_pathKey:t.pathKey??null,_isGroup:!!t.isGroup,_parentKeys:s,_documentPathTemplate:o.documentPathTemplate,_collectionId:o.collectionId,_collectionPath:o.collectionPath,_createdKey:t.createdKey??null}}var Ba="history";function za(e){let t=e&&typeof e.history=="object"&&e.history!==null?e.history:void 0,n=[e?.documentKey,e?.pathKey,e?.createdKey,e?.updatedKey].filter(s=>typeof s=="string"),r=typeof e?.path=="string"?e.path:null,o=r?_e(r,e?.documentKey??"docId"):null;return {historyConfig:t,systemKeys:n,isGroup:!!e?.isGroup,collectionPath:o?o.collectionPath:null,documentPathTemplate:o&&(!e?.isGroup||o.collectionPath.includes("/"))?o.documentPathTemplate:null}}function qa(e){let t=e._historyConfig??(typeof e.history=="object"&&e.history!==null&&"enabled"in e.history?e.history:void 0),n=e._collectionPath??e.ref?.path??null,r=typeof e._documentPathTemplate=="string"?e._documentPathTemplate:null;return {historyConfig:t,systemKeys:e._systemKeys??[],isGroup:!!e._isGroup,collectionPath:n,documentPathTemplate:r&&(!e._isGroup||n&&n.includes("/"))?r:null}}function Ua(e,t){return t?`${t}/{docId}`:(console.warn(`[HistoryTriggers] Cannot determine collection path for "${e}". Skipping.`),null)}function ko(e,t){let{onDocumentWritten:n}=t.deps,r={},o=e?.rawMapping,s=o?Object.entries(o).map(([a,l])=>[a,za(l)]):Object.entries(e).map(([a,l])=>[a,qa(l)]);for(let[a,l]of s){let c=l.historyConfig;if(!c?.enabled)continue;let u=c.subcollection??Ba,p=c.ttl??t.defaults?.ttl,f=t.repos?.[a],b;if(l.isGroup){let O=f?.triggerPath??l.documentPathTemplate;if(!O){console.warn(`[HistoryTriggers] Skipping collection-group repo "${a}". Provide a triggerPath in the history triggers repos override or use a full path template.`);continue}b=O;}else b=f?.triggerPath??l.documentPathTemplate??Ua(a,l.collectionPath);if(!b)continue;let h=l.systemKeys,w=h[0]??"docId",T=cn(c),S={...t.triggerOptions,...c?.triggerOptions,...f?.triggerOptions},I=Object.keys(S).length>0,A=async O=>{try{let x=O.data?.before?.data(),d=O.data?.after?.data(),y;if(!x&&d)y="create";else if(x&&!d)y="delete";else if(x&&d)y="update";else return;let i=String(d?.[w]??x?.[w]??O.params?.docId??O.data?.after?.id??O.data?.before?.id??"");if(!i)return;let g=sn(x??{},d??{},{include:c.include,exclude:c.exclude,metaFields:T,systemKeys:h});if(y==="update"&&Object.keys(g).length===0)return;let m=an(d??x??null,c),C=Et({entityId:i,operation:y,changes:g,meta:m,config:c,ttlOverride:p}),k=O.data?.after?.ref??O.data?.before?.ref;if(!k)return;let R=k.collection(u);await Ot(R,C,c,{repoName:a,docId:i,before:x??null,after:d??null});}catch(x){console.error(`[HistoryTriggers] Failed to record history for "${a}":`,x);}};r[`${a}_onHistory`]=n(I?{document:b,...S}:b,A);}return r}function La(e){let t=[],n=e.replace(/[.*+?^${}()|[\]\\]/g,r=>r===":"?r:`\\${r}`).replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,(r,o)=>(t.push(o),"([^/]+)"));return {pattern:new RegExp(`^${n}$`),paramNames:t}}function Ka(e){let t=e.path??e.url??"/",n=t.indexOf("?");return n===-1?t:t.slice(0,n)}var Me=class{constructor(){this.routes=[];this.middlewares=[];this.notFoundHandler=(t,n)=>{n.status(404).send("Not Found");};this.errorHandler=(t,n,r)=>{console.error("[MiniRouter]",t),r.status(500).send("Internal Server Error");};}use(t){return this.middlewares.push(t),this}get(t,n){return this.addRoute("GET",t,n)}post(t,n){return this.addRoute("POST",t,n)}put(t,n){return this.addRoute("PUT",t,n)}patch(t,n){return this.addRoute("PATCH",t,n)}delete(t,n){return this.addRoute("DELETE",t,n)}onNotFound(t){return this.notFoundHandler=t,this}onError(t){return this.errorHandler=t,this}addRoute(t,n,r){let{pattern:o,paramNames:s}=La(n);return this.routes.push({method:t.toUpperCase(),pattern:o,paramNames:s,handler:r}),this}async handle(t,n){let r=(t.method??"GET").toUpperCase(),o=Ka(t),s=null,a={};for(let u of this.routes){if(u.method!==r)continue;let p=o.match(u.pattern);if(p){s=u,a={},u.paramNames.forEach((f,b)=>{a[f]=decodeURIComponent(p[b+1]??"");});break}}let l=Object.assign(t,{params:a}),c=s?s.handler:this.notFoundHandler;try{await this.runMiddlewareChain(l,n,c);}catch(u){this.errorHandler(u,t,n);}}async runMiddlewareChain(t,n,r){let o=0,s=async()=>{if(o<this.middlewares.length){let a=this.middlewares[o++];await a(t,n,s);}else await r(t,n);};await s();}};function Oe(e,t,n){let r=t==="/"?"":t.replace(/\/$/,"");if(process.env.FUNCTIONS_EMULATOR==="true"){let a=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??"demo-project",l=n??process.env.FUNCTION_REGION??"us-central1",c=(process.env.FUNCTION_TARGET??"").replace(/\./g,"-");return `/${a}/${l}/${c}${r}`}let o=process.env.K_SERVICE,s=e?.hostname??e?.headers?.host??"";return o&&typeof s=="string"&&s.includes("cloudfunctions.net")?`/${o.toLowerCase()}${r}`:r}function un(e){if(typeof e=="string")return e;if(Array.isArray(e)){let t=e[0];return typeof t=="string"?t:void 0}}function Pt(e){return !!e&&typeof e=="object"&&e.__authExtension===true}function rr(e,t,n=new WeakSet,r=0){if(e==null)return null;if(typeof e=="object"&&typeof e.toDate=="function")return e.toDate().toISOString();if(e instanceof Date)return e.toISOString();if(Buffer.isBuffer(e))return e.toString("base64");if(e instanceof Uint8Array)return Buffer.from(e).toString("base64");if(typeof e=="object"&&"latitude"in e&&"longitude"in e){let o=e;return t?.stringifyArrays===false?{lat:o.latitude,lng:o.longitude}:JSON.stringify({lat:o.latitude,lng:o.longitude})}if(Array.isArray(e)){let o=e.map(s=>rr(s,t,n,r+1));return t?.stringifyArrays===false?o:JSON.stringify(o)}return typeof e=="object"&&e!==null&&t?.stringifyArrays===false?or(e,new Set,{},n,r+1):e}var Ao=32,Qa=5e3;function Eo(e,t,n,r=new WeakSet,o=0){if(o>Ao){n[t||"_truncated"]=JSON.stringify({__truncated:true});return}if(r.has(e)){n[t||"_cycle"]=JSON.stringify({__cycle:true});return}r.add(e);for(let[s,a]of Object.entries(e)){if(Object.keys(n).length>=Qa)break;let l=t?`${t}__${s}`:s;a!=null&&typeof a=="object"&&!Array.isArray(a)&&!(a instanceof Date)&&!Buffer.isBuffer(a)&&!(a instanceof Uint8Array)&&typeof a.toDate!="function"&&!("latitude"in a&&"longitude"in a)?Eo(a,l,n,r,o+1):n[l]=rr(a);}r.delete(e);}function or(e,t,n,r=new WeakSet,o=0){if(o>Ao)return {__truncated:true};if(r.has(e))return {__cycle:true};r.add(e);let s={};for(let[a,l]of Object.entries(e)){if(t.has(a))continue;let c=n[a]??a;l!=null&&typeof l=="object"&&!Array.isArray(l)&&!(l instanceof Date)&&!Buffer.isBuffer(l)&&!(l instanceof Uint8Array)&&typeof l.toDate!="function"&&!("latitude"in l&&"longitude"in l)?s[c]=or(l,new Set,{},r,o+1):s[c]=rr(l,{stringifyArrays:false},r,o+1);}return r.delete(e),s}function Oo(e){let t={};for(let[n,r]of Object.entries(e)){let o=r;if(typeof o=="string"){let l=o.trim();if(l.startsWith("[")&&l.endsWith("]")||l.startsWith("{")&&l.endsWith("}"))try{o=JSON.parse(l);}catch{}}if(n.startsWith("__")||!n.includes("__")){t[n]=o;continue}let s=n.split("__").filter(Boolean),a=t;for(let l=0;l<s.length-1;l++){let c=s[l];(!a[c]||typeof a[c]!="object"||Array.isArray(a[c]))&&(a[c]={}),a=a[c];}a[s[s.length-1]]=o;}return t}function It(e,t){let n=t?.flat!==false,r;if(n){let o=new Set(t?.exclude),s=t?.columnMap??{},a=e;if(o.size>0){let c=false,u={};for(let[p,f]of Object.entries(e)){if(o.has(p)){c=true;continue}u[p]=f;}c&&(a=u);}let l={};Eo(a,"",l),r={};for(let[c,u]of Object.entries(l)){if(o.has(c))continue;let p=c.split("__")[0];if(p!==c&&o.has(p))continue;let f=s[c]??(c.includes("__")?s[c.split("__").pop()]:void 0)??c;r[f]=u;}}else {let o=new Set(t?.exclude),s=t?.columnMap??{};r=or(e,o,s);}return typeof t?.transformDoc=="function"&&(r=t.transformDoc(r)),r}function G(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Fe(e,t,n){let r=G(e),o=G(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>${r} \u2014 Sync Admin</title>
@@ -28,41 +28,41 @@ import {jsx,jsxs,Fragment}from'hono/jsx/jsx-runtime';import {Timestamp,FieldPath
28
28
  <nav><a href="${o}/">\u2190 Dashboard</a></nav>
29
29
  <h1>${r}</h1>
30
30
  ${n}
31
- </body></html>`}function Fe(e,t,n=200){e.status(n).set("Content-Type","text/html; charset=utf-8").send(t);}function Je(e,t,n=200){e.status(n).set("Content-Type","application/json").send(JSON.stringify(t,null,2));}function It(e){return (e.headers?.accept??"").includes("application/json")}function dt(e){if(e===true||e===1)return true;if(Array.isArray(e))return e.some(dt);if(typeof e=="string"){let t=e.trim().toLowerCase();return t==="true"||t==="1"||t==="yes"||t==="on"}return false}function za(e){if(e.query&&dt(e.query.dryRun))return true;let t=e.url??e.originalUrl??"",n=t.indexOf("?");if(n!==-1){let o=new URLSearchParams(t.slice(n+1));if(dt(o.get("dryRun")))return true}let r=e.body;if(r&&typeof r=="object"){if(dt(r.dryRun))return true}else if(typeof r=="string"&&r.trim().length>0){let o=r.trim();if(o.startsWith("{"))try{let s=JSON.parse(o);if(s&&typeof s=="object"&&dt(s.dryRun))return !0}catch{}else {let s=new URLSearchParams(o);if(dt(s.get("dryRun")))return true}}return false}var qa=new Set([4,8,10,13,14,"4","8","10","13","14","DEADLINE_EXCEEDED","RESOURCE_EXHAUSTED","ABORTED","INTERNAL","UNAVAILABLE"]);function Ua(e){if(!e||typeof e!="object")return false;let t=e.code;return (typeof t=="number"||typeof t=="string")&&qa.has(t)}async function La(e,t=3,n=100){let r=0;for(;;){r++;try{return await e()}catch(o){if(r>=t||!Ua(o))throw o;let s=n*2**(r-1);await new Promise(a=>setTimeout(a,s));}}}function or(e,t){let n=new Set,r=[];for(let o of e.adapters){let s=`${e.name}:${o.name}`,a=t.get(s);a&&!n.has(a)&&(n.add(a),r.push({adapterName:o.name??"default",queue:a}));}if(r.length===0){let o=t.get(e.name);o&&!n.has(o)&&(n.add(o),r.push({adapterName:e.adapters[0]?.name??"default",queue:o}));}return r}function Co(e,t,n,r,o,s,a,l){let c=(o.basePath??"/").replace(/\/$/,"")||"",u=o.featuresFlag??{},p=dn(o.httpsOptions?.region),f=Array.isArray(t)?t:[t],w=e?.rawMapping,h=[],b=Object.keys(s??{}),T=b.length>0,S=Object.keys(w||e),I=T?b.filter(x=>S.includes(x)||x in e):S;for(let x of I){let d=s[x],y=w?ln(w[x],()=>e[x]):e[x],i=!!y._isGroup,g=y._collectionPath,m=typeof g=="string"&&g.includes("/");if(!T&&i&&!d?.triggerPath&&!m)continue;let A=d?.adapters&&d.adapters.length>0?f.filter(R=>d.adapters.includes(R.name)):f,k=typeof y._historyShadowKey=="string"?y._historyShadowKey:ve(y._historyConfig);h.push({name:x,schema:y.schema??null,documentKey:y._systemKeys?.[0]??y.documentKey??"docId",tableName:d?.tableName??x,isGroup:i,repoCfg:d,repo:y,adapters:A,historyShadowKey:k});}let C=new _e,O=new Set;if(o.auth)if(Ot(o.auth)){let x=o.auth;for(let d of x.routes){let y=`${c}${d.path}`;d.method==="GET"?C.get(y,d.handler):C.post(y,d.handler);}C.use(x.middleware);}else if(typeof o.auth=="function")C.use(o.auth);else {let x=o.auth.realm??"Sync Admin",d="Basic "+Buffer.from(`${o.auth.username}:${o.auth.password}`).toString("base64");C.use((y,i,g)=>{if((y.headers?.authorization??"")!==d){i.status(401).set("WWW-Authenticate",`Basic realm="${x}"`).set("Content-Type","text/plain").send("Unauthorized");return}g();});}return C.get(`${c}/`,(x,d)=>{let y=Ee(x,c,p),i=G(y),g=h.map(k=>{let R=G(k.name),P=encodeURIComponent(k.name),M=[];u.healthCheck&&M.push(`<a class="btn" href="${i}/${P}/health">Health</a>`),u.manualSync&&M.push(`<a class="btn btn-primary" href="${i}/${P}/force-sync">Force Sync</a>`);let $=k.adapters.map(_=>`<span class="badge badge-ok">${G(_.name)}</span>`).join(" ");return `<tr>
31
+ </body></html>`}function Ne(e,t,n=200){e.status(n).set("Content-Type","text/html; charset=utf-8").send(t);}function Ye(e,t,n=200){e.status(n).set("Content-Type","application/json").send(JSON.stringify(t,null,2));}function Dt(e){return (e.headers?.accept??"").includes("application/json")}function pt(e){if(e===true||e===1)return true;if(Array.isArray(e))return e.some(pt);if(typeof e=="string"){let t=e.trim().toLowerCase();return t==="true"||t==="1"||t==="yes"||t==="on"}return false}function Ga(e){if(e.query&&pt(e.query.dryRun))return true;let t=e.url??e.originalUrl??"",n=t.indexOf("?");if(n!==-1){let o=new URLSearchParams(t.slice(n+1));if(pt(o.get("dryRun")))return true}let r=e.body;if(r&&typeof r=="object"){if(pt(r.dryRun))return true}else if(typeof r=="string"&&r.trim().length>0){let o=r.trim();if(o.startsWith("{"))try{let s=JSON.parse(o);if(s&&typeof s=="object"&&pt(s.dryRun))return !0}catch{}else {let s=new URLSearchParams(o);if(pt(s.get("dryRun")))return true}}return false}var Ja=new Set([4,8,10,13,14,"4","8","10","13","14","DEADLINE_EXCEEDED","RESOURCE_EXHAUSTED","ABORTED","INTERNAL","UNAVAILABLE"]);function Ya(e){if(!e||typeof e!="object")return false;let t=e.code;return (typeof t=="number"||typeof t=="string")&&Ja.has(t)}async function Xa(e,t=3,n=100){let r=0;for(;;){r++;try{return await e()}catch(o){if(r>=t||!Ya(o))throw o;let s=n*2**(r-1);await new Promise(a=>setTimeout(a,s));}}}function sr(e,t){let n=new Set,r=[];for(let o of e.adapters){let s=`${e.name}:${o.name}`,a=t.get(s);a&&!n.has(a)&&(n.add(a),r.push({adapterName:o.name??"default",queue:a}));}if(r.length===0){let o=t.get(e.name);o&&!n.has(o)&&(n.add(o),r.push({adapterName:e.adapters[0]?.name??"default",queue:o}));}return r}function Po(e,t,n,r,o,s,a,l){let c=(o.basePath??"/").replace(/\/$/,"")||"",u=o.featuresFlag??{},p=un(o.httpsOptions?.region),f=Array.isArray(t)?t:[t],b=e?.rawMapping,h=[],w=Object.keys(s??{}),T=w.length>0,S=Object.keys(b||e),I=T?w.filter(x=>S.includes(x)||x in e):S;for(let x of I){let d=s[x],y=b?dn(b[x],()=>e[x]):e[x],i=!!y._isGroup,g=y._collectionPath,m=typeof g=="string"&&g.includes("/");if(!T&&i&&!d?.triggerPath&&!m)continue;let C=d?.adapters&&d.adapters.length>0?f.filter(R=>d.adapters.includes(R.name)):f,k=typeof y._historyShadowKey=="string"?y._historyShadowKey:ve(y._historyConfig);h.push({name:x,schema:y.schema??null,documentKey:y._systemKeys?.[0]??y.documentKey??"docId",tableName:d?.tableName??x,isGroup:i,repoCfg:d,repo:y,adapters:C,historyShadowKey:k});}let A=new Me,O=new Set;if(o.auth)if(Pt(o.auth)){let x=o.auth;for(let d of x.routes){let y=`${c}${d.path}`;d.method==="GET"?A.get(y,d.handler):A.post(y,d.handler);}A.use(x.middleware);}else if(typeof o.auth=="function")A.use(o.auth);else {let x=o.auth.realm??"Sync Admin",d="Basic "+Buffer.from(`${o.auth.username}:${o.auth.password}`).toString("base64");A.use((y,i,g)=>{if((y.headers?.authorization??"")!==d){i.status(401).set("WWW-Authenticate",`Basic realm="${x}"`).set("Content-Type","text/plain").send("Unauthorized");return}g();});}return A.get(`${c}/`,(x,d)=>{let y=Oe(x,c,p),i=G(y),g=h.map(k=>{let R=G(k.name),P=encodeURIComponent(k.name),_=[];u.healthCheck&&_.push(`<a class="btn" href="${i}/${P}/health">Health</a>`),u.manualSync&&_.push(`<a class="btn btn-primary" href="${i}/${P}/force-sync">Force Sync</a>`);let $=k.adapters.map(M=>`<span class="badge badge-ok">${G(M.name)}</span>`).join(" ");return `<tr>
32
32
  <td><strong>${R}</strong></td>
33
33
  <td>${G(k.tableName)}</td>
34
34
  <td>${$||'<span class="badge badge-warn">none</span>'}</td>
35
35
  <td>${k.isGroup?'<span class="badge badge-warn">group</span>':'<span class="badge badge-ok">collection</span>'}</td>
36
36
  <td>${k.schema?"\u2713":"\u2717"}</td>
37
- <td>${M.join(" ")}</td>
37
+ <td>${_.join(" ")}</td>
38
38
  </tr>`}).join(`
39
- `),m=u.configCheck?`<p style="margin-top:.5rem"><a class="btn" href="${i}/config-check">\u2699 Config Check</a></p>`:"",A=Ne("Sync Dashboard",y,`<div class="card">
39
+ `),m=u.configCheck?`<p style="margin-top:.5rem"><a class="btn" href="${i}/config-check">\u2699 Config Check</a></p>`:"",C=Fe("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>${g}</tbody>
43
43
  </table>
44
44
  ${m}
45
- </div>`);Fe(d,A);}),C.get(`${c}`,(x,d)=>{let y=Ee(x,c,p);d.status(302).set("Location",`${y}/`).send("");}),u.healthCheck&&C.get(`${c}/:repoName/health`,async(x,d)=>{let y=Ee(x,c,p),i=h.find(R=>R.name===x.params.repoName);if(!i){Fe(d,Ne("Not Found",y,`<p>Unknown repo: ${G(x.params.repoName)}</p>`),404);return}let g=[];for(let R of i.adapters)if(typeof R.healthCheck=="function"){let P=await R.healthCheck({targetName:i.tableName,primaryKey:i.documentKey,schema:i.schema??void 0,repoConfig:i.repoCfg});g.push({adapterName:R.name,health:P});}else try{let P=await R.targetExists(i.tableName);g.push({adapterName:R.name,health:{healthy:P,targetName:i.tableName,targetExists:P,error:P?null:`Target "${i.tableName}" does not exist`}});}catch(P){g.push({adapterName:R.name,health:{healthy:false,targetName:i.tableName,targetExists:false,error:P?.message??String(P)}});}let m=g.length>0&&g.every(R=>R.health.healthy);if(It(x)){Je(d,{repo:i.name,targetName:i.tableName,healthy:m,adapters:g.map(R=>({name:R.adapterName,...R.health}))});return}let A=R=>{let{adapterName:P,health:M}=R,$=M.healthy?'<span class="badge badge-ok">Healthy</span>':'<span class="badge badge-err">Unhealthy</span>',_="",v=M.details;if(v?.expected&&Array.isArray(v.expected)){let E=v.expected,N=new Set(v.actual??[]),H=v.extra??[],D=E.map(j=>{let z=N.has(j.name)?'<span class="badge badge-ok">OK</span>':'<span class="badge badge-err">MISSING</span>';return `<tr><td>${G(j.name)}</td><td>${G(j.type)}</td><td>${j.nullable?"Yes":"No"}</td><td>${j.isPrimaryKey?"\u2713":""}</td><td>${z}</td></tr>`}).join(`
46
- `),F=H.map(j=>`<tr><td>${G(j)}</td><td colspan="3" class="muted">not in schema</td><td><span class="badge badge-warn">EXTRA</span></td></tr>`).join(`
47
- `);_=`<h2>Columns</h2>
45
+ </div>`);Ne(d,C);}),A.get(`${c}`,(x,d)=>{let y=Oe(x,c,p);d.status(302).set("Location",`${y}/`).send("");}),u.healthCheck&&A.get(`${c}/:repoName/health`,async(x,d)=>{let y=Oe(x,c,p),i=h.find(R=>R.name===x.params.repoName);if(!i){Ne(d,Fe("Not Found",y,`<p>Unknown repo: ${G(x.params.repoName)}</p>`),404);return}let g=[];for(let R of i.adapters)if(typeof R.healthCheck=="function"){let P=await R.healthCheck({targetName:i.tableName,primaryKey:i.documentKey,schema:i.schema??void 0,repoConfig:i.repoCfg});g.push({adapterName:R.name,health:P});}else try{let P=await R.targetExists(i.tableName);g.push({adapterName:R.name,health:{healthy:P,targetName:i.tableName,targetExists:P,error:P?null:`Target "${i.tableName}" does not exist`}});}catch(P){g.push({adapterName:R.name,health:{healthy:false,targetName:i.tableName,targetExists:false,error:P?.message??String(P)}});}let m=g.length>0&&g.every(R=>R.health.healthy);if(Dt(x)){Ye(d,{repo:i.name,targetName:i.tableName,healthy:m,adapters:g.map(R=>({name:R.adapterName,...R.health}))});return}let C=R=>{let{adapterName:P,health:_}=R,$=_.healthy?'<span class="badge badge-ok">Healthy</span>':'<span class="badge badge-err">Unhealthy</span>',M="",v=_.details;if(v?.expected&&Array.isArray(v.expected)){let E=v.expected,F=new Set(v.actual??[]),H=v.extra??[],D=E.map(j=>{let z=F.has(j.name)?'<span class="badge badge-ok">OK</span>':'<span class="badge badge-err">MISSING</span>';return `<tr><td>${G(j.name)}</td><td>${G(j.type)}</td><td>${j.nullable?"Yes":"No"}</td><td>${j.isPrimaryKey?"\u2713":""}</td><td>${z}</td></tr>`}).join(`
46
+ `),N=H.map(j=>`<tr><td>${G(j)}</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>${D}${F}</tbody>
51
- </table>`;}else v?.numberOfDocuments!==void 0&&(_=`<h2>Index Stats</h2>
50
+ <tbody>${D}${N}</tbody>
51
+ </table>`;}else v?.numberOfDocuments!==void 0&&(M=`<h2>Index Stats</h2>
52
52
  <table>
53
53
  <tr><th>Documents Count</th><td>${G(v.numberOfDocuments)}</td></tr>
54
54
  <tr><th>Indexing in Progress</th><td>${v.isIndexing?'<span class="badge badge-warn">Yes</span>':'<span class="badge badge-ok">No</span>'}</td></tr>
55
55
  <tr><th>Primary Key</th><td><code>${G(v.primaryKey??"default")}</code></td></tr>
56
56
  </table>`);return `<div class="card" style="margin-top:1rem">
57
57
  <h2>Adapter: <code>${G(P)}</code> ${$}</h2>
58
- <p>Target: <code>${G(M.targetName)}</code> ${M.targetExists?"":'<span class="badge badge-err">NOT FOUND</span>'}</p>
59
- ${M.error?`<p class="badge badge-err" style="margin-top:.5rem">Error: ${G(M.error)}</p>`:""}
60
- ${_}
61
- </div>`},k=Ne(`Health: ${i.name}`,y,`<div class="card">
58
+ <p>Target: <code>${G(_.targetName)}</code> ${_.targetExists?"":'<span class="badge badge-err">NOT FOUND</span>'}</p>
59
+ ${_.error?`<p class="badge badge-err" style="margin-top:.5rem">Error: ${G(_.error)}</p>`:""}
60
+ ${M}
61
+ </div>`},k=Fe(`Health: ${i.name}`,y,`<div class="card">
62
62
  <p>Overall status for <strong>${G(i.name)}</strong>: ${m?'<span class="badge badge-ok">Healthy</span>':'<span class="badge badge-err">Issues detected</span>'}</p>
63
63
  </div>
64
- ${g.map(A).join(`
65
- `)}`);Fe(d,k);}),u.manualSync&&(C.get(`${c}/:repoName/force-sync`,(x,d)=>{let y=Ee(x,c,p),i=h.find(k=>k.name===x.params.repoName);if(!i){Fe(d,Ne("Not Found",y,`<p>Unknown repo: ${G(x.params.repoName)}</p>`),404);return}let g=G(i.name),m=i.adapters.map(k=>G(k.name)).join(", "),A=Ne(`Force Sync: ${i.name}`,y,`<div class="card">
64
+ ${g.map(C).join(`
65
+ `)}`);Ne(d,k);}),u.manualSync&&(A.get(`${c}/:repoName/force-sync`,(x,d)=>{let y=Oe(x,c,p),i=h.find(k=>k.name===x.params.repoName);if(!i){Ne(d,Fe("Not Found",y,`<p>Unknown repo: ${G(x.params.repoName)}</p>`),404);return}let g=G(i.name),m=i.adapters.map(k=>G(k.name)).join(", "),C=Fe(`Force Sync: ${i.name}`,y,`<div class="card">
66
66
  <p>This will read <strong>all</strong> documents from the <code>${g}</code> Firestore collection
67
67
  and upsert them into all active target storage adapters (${m}).</p>
68
68
  <p class="muted" style="margin:.75rem 0">This may take a while for large collections.</p>
@@ -72,36 +72,36 @@ ${n}
72
72
  </label>
73
73
  <button type="submit" class="btn btn-primary">Start Force Sync</button>
74
74
  </form>
75
- </div>`);Fe(d,A);}),C.post(`${c}/:repoName/force-sync`,async(x,d)=>{let y=Ee(x,c,p),i=h.find(m=>m.name===x.params.repoName);if(!i){Je(d,{error:`Unknown repo: ${x.params.repoName}`},404);return}let g=i.repo.ref;if(!g){Je(d,{error:`No collection reference for "${i.name}"`},400);return}if(O.has(i.name)){if(It(x)){Je(d,{error:`Force sync is already running for "${i.name}"`,repo:i.name},409);return}Fe(d,Ne(`Force Sync: ${i.name}`,y,`<div class="card">
75
+ </div>`);Ne(d,C);}),A.post(`${c}/:repoName/force-sync`,async(x,d)=>{let y=Oe(x,c,p),i=h.find(m=>m.name===x.params.repoName);if(!i){Ye(d,{error:`Unknown repo: ${x.params.repoName}`},404);return}let g=i.repo.ref;if(!g){Ye(d,{error:`No collection reference for "${i.name}"`},400);return}if(O.has(i.name)){if(Dt(x)){Ye(d,{error:`Force sync is already running for "${i.name}"`,repo:i.name},409);return}Ne(d,Fe(`Force Sync: ${i.name}`,y,`<div class="card">
76
76
  <p class="badge badge-warn">Already Running</p>
77
77
  <p>A force sync is already in progress for <strong>${G(i.name)}</strong>. Please wait for it to finish before starting another.</p>
78
- </div>`),409);return}O.add(i.name);try{let m=za(x),A=0,k=0,R=0,P=[],M=500,_=(typeof g.orderBy=="function"?g.orderBy(FieldPath.documentId()):g).limit(M),v=null,E=new Map,N=()=>{for(let[W,X]of E.entries()){if(typeof W.getStats!="function")continue;let oe=W.getStats();for(let se of oe.recentErrors)se.seq>X.lastErrorSeq&&P.length<5&&P.push(`[${X.adapterName}] flush failed (${se.count} event(s)): ${se.message}`);X.lastErrorSeq=oe.errorSeq;}},H=()=>{if(m)return {synced:0,errors:R};let W=Array.from(E.entries()).filter(([se])=>typeof se.getStats=="function");if(W.length===0)return {synced:k,errors:R};let X=k,oe=0;for(let[se,we]of W){let ne=se.getStats(),be=Math.max(0,ne.flushedEvents-we.flushedEvents),re=Math.max(0,ne.failedEvents-we.failedEvents);be<X&&(X=be),oe+=re;}return {synced:X,errors:R+oe}},D=i.historyShadowKey?Array.from(new Set([...i.repoCfg?.exclude??[],i.historyShadowKey])):i.repoCfg?.exclude;try{if(!m){let W=or(i,n);for(let{adapterName:X,queue:oe}of W)if(await oe.flush(),typeof oe.getStats=="function"){let se=oe.getStats();E.set(oe,{adapterName:X,flushedEvents:se.flushedEvents,failedEvents:se.failedEvents,lastErrorSeq:se.errorSeq});}else E.set(oe,{adapterName:X,flushedEvents:0,failedEvents:0,lastErrorSeq:0});}for(;;){let W=v?_.startAfter(v):_,X=Date.now(),oe=await La(()=>(X=Date.now(),W.get()));if(oe.empty||oe.docs.length===0)break;for(let se of oe.docs){A++;let we=String(se.id??"unknown");try{let ne=se.data();we=String(ne?.[i.documentKey]??se.id);let be=Pt(ne,{exclude:D,columnMap:i.repoCfg?.columnMap,flat:i.repoCfg?.flat,transformDoc:i.repoCfg?.transformDoc});m||(await r({operation:"UPSERT",repoName:i.name,docId:we,data:be,timestamp:new Date(X).toISOString(),version:X}),k++);}catch(ne){R++;let be=ne?.message??String(ne);console.error(`[ForceSync:${i.name}] doc=${we} failed:`,ne),P.length<5&&P.push(`${we}: ${be}`);}}if(!m){let se=or(i,n);for(let{adapterName:we,queue:ne}of se)E.has(ne)||E.set(ne,{adapterName:we,flushedEvents:0,failedEvents:0,lastErrorSeq:0}),await ne.flush();N();}if(v=oe.docs[oe.docs.length-1],oe.docs.length<M)break}}catch(W){if(!m){for(let{adapterName:we,queue:ne}of or(i,n))E.has(ne)||E.set(ne,{adapterName:we,flushedEvents:0,failedEvents:0,lastErrorSeq:0});N();}let{synced:X,errors:oe}=H(),se=W?.message??String(W);if(It(x)){Je(d,{error:se,...m&&{dryRun:!0},scanned:A,synced:X,errors:oe,...P.length>0&&{errorSamples:P}},500);return}Fe(d,Ne(`Force Sync: ${i.name}`,y,`<div class="card">
78
+ </div>`),409);return}O.add(i.name);try{let m=Ga(x),C=0,k=0,R=0,P=[],_=500,M=(typeof g.orderBy=="function"?g.orderBy(FieldPath.documentId()):g).limit(_),v=null,E=new Map,F=()=>{for(let[W,X]of E.entries()){if(typeof W.getStats!="function")continue;let oe=W.getStats();for(let se of oe.recentErrors)se.seq>X.lastErrorSeq&&P.length<5&&P.push(`[${X.adapterName}] flush failed (${se.count} event(s)): ${se.message}`);X.lastErrorSeq=oe.errorSeq;}},H=()=>{if(m)return {synced:0,errors:R};let W=Array.from(E.entries()).filter(([se])=>typeof se.getStats=="function");if(W.length===0)return {synced:k,errors:R};let X=k,oe=0;for(let[se,we]of W){let ne=se.getStats(),be=Math.max(0,ne.flushedEvents-we.flushedEvents),re=Math.max(0,ne.failedEvents-we.failedEvents);be<X&&(X=be),oe+=re;}return {synced:X,errors:R+oe}},D=i.historyShadowKey?Array.from(new Set([...i.repoCfg?.exclude??[],i.historyShadowKey])):i.repoCfg?.exclude;try{if(!m){let W=sr(i,n);for(let{adapterName:X,queue:oe}of W)if(await oe.flush(),typeof oe.getStats=="function"){let se=oe.getStats();E.set(oe,{adapterName:X,flushedEvents:se.flushedEvents,failedEvents:se.failedEvents,lastErrorSeq:se.errorSeq});}else E.set(oe,{adapterName:X,flushedEvents:0,failedEvents:0,lastErrorSeq:0});}for(;;){let W=v?M.startAfter(v):M,X=Date.now(),oe=await Xa(()=>(X=Date.now(),W.get()));if(oe.empty||oe.docs.length===0)break;for(let se of oe.docs){C++;let we=String(se.id??"unknown");try{let ne=se.data();we=String(ne?.[i.documentKey]??se.id);let be=It(ne,{exclude:D,columnMap:i.repoCfg?.columnMap,flat:i.repoCfg?.flat,transformDoc:i.repoCfg?.transformDoc});m||(await r({operation:"UPSERT",repoName:i.name,docId:we,data:be,timestamp:new Date(X).toISOString(),version:X}),k++);}catch(ne){R++;let be=ne?.message??String(ne);console.error(`[ForceSync:${i.name}] doc=${we} failed:`,ne),P.length<5&&P.push(`${we}: ${be}`);}}if(!m){let se=sr(i,n);for(let{adapterName:we,queue:ne}of se)E.has(ne)||E.set(ne,{adapterName:we,flushedEvents:0,failedEvents:0,lastErrorSeq:0}),await ne.flush();F();}if(v=oe.docs[oe.docs.length-1],oe.docs.length<_)break}}catch(W){if(!m){for(let{adapterName:we,queue:ne}of sr(i,n))E.has(ne)||E.set(ne,{adapterName:we,flushedEvents:0,failedEvents:0,lastErrorSeq:0});F();}let{synced:X,errors:oe}=H(),se=W?.message??String(W);if(Dt(x)){Ye(d,{error:se,...m&&{dryRun:!0},scanned:C,synced:X,errors:oe,...P.length>0&&{errorSamples:P}},500);return}Ne(d,Fe(`Force Sync: ${i.name}`,y,`<div class="card">
79
79
  <p class="badge badge-err">Error: ${G(se)}</p>
80
- <p>Scanned ${A} docs, synced ${X} docs before failure (${oe} errors).</p>
81
- </div>`),500);return}let{synced:F,errors:j}=H();if(It(x)){Je(d,{...m&&{dryRun:!0},repo:i.name,table:i.tableName,scanned:A,synced:F,errors:j,...P.length>0&&{errorSamples:P}});return}let z=P.length>0?`<details style="margin-top:1rem"><summary>First ${P.length} error(s)</summary>
80
+ <p>Scanned ${C} docs, synced ${X} docs before failure (${oe} errors).</p>
81
+ </div>`),500);return}let{synced:N,errors:j}=H();if(Dt(x)){Ye(d,{...m&&{dryRun:!0},repo:i.name,table:i.tableName,scanned:C,synced:N,errors:j,...P.length>0&&{errorSamples:P}});return}let z=P.length>0?`<details style="margin-top:1rem"><summary>First ${P.length} error(s)</summary>
82
82
  <pre style="white-space:pre-wrap">${P.map(W=>G(W)).join(`
83
83
 
84
- `)}</pre></details>`:"",te=i.adapters.map(W=>G(W.name)).join(", "),K=m?`<p class="badge ${j>0?"badge-warn":"badge-ok"}">${j>0?"Dry run completed with errors":"Dry run complete"}</p>`:`<p class="badge ${j>0?"badge-warn":"badge-ok"}">${j>0?"Completed with errors":"Complete"}</p>`,De=m?`<p>Dry run scanned <strong>${A}</strong> documents (0 synced, no writes performed).</p>`:`<p>Scanned <strong>${A}</strong> documents, synced <strong>${F}</strong> documents to targets (${te}).</p>`,Se=Ne(`Force Sync: ${i.name}`,y,`<div class="card">
84
+ `)}</pre></details>`:"",te=i.adapters.map(W=>G(W.name)).join(", "),K=m?`<p class="badge ${j>0?"badge-warn":"badge-ok"}">${j>0?"Dry run completed with errors":"Dry run complete"}</p>`:`<p class="badge ${j>0?"badge-warn":"badge-ok"}">${j>0?"Completed with errors":"Complete"}</p>`,$e=m?`<p>Dry run scanned <strong>${C}</strong> documents (0 synced, no writes performed).</p>`:`<p>Scanned <strong>${C}</strong> documents, synced <strong>${N}</strong> documents to targets (${te}).</p>`,Se=Fe(`Force Sync: ${i.name}`,y,`<div class="card">
85
85
  ${K}
86
- ${De}
86
+ ${$e}
87
87
  ${j>0?`<p class="badge badge-warn">${j} error(s)</p>`:""}
88
88
  ${z}
89
- </div>`);Fe(d,Se);}finally{O.delete(i.name);}})),u.configCheck&&C.get(`${c}/config-check`,async(x,d)=>{let y=Ee(x,c,p),i=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??process.env.GCP_PROJECT??"unknown",g="https://console.cloud.google.com",m=l??"firestore-sync",A=[];for(let v of f)if(v.name==="bigquery")try{await v.targetExists("__nonexistent_health_check__"),A.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable"});}catch(E){let N=E?.message??String(E),H=N.toLowerCase(),D=H.includes("disabled")||H.includes("has not been used")||H.includes("accessnotconfigured"),F=H.includes("permission")||N.includes("403")||H.includes("access denied"),j=H.includes("project")&&H.includes("not found"),z=H.includes("not found")||N.includes("404");D?A.push({name:"BigQuery API",category:"bigquery",status:"error",message:"BigQuery API is not enabled",fix:{gcloud:`gcloud services enable bigquery.googleapis.com --project=${i}`,console:`${g}/apis/library/bigquery.googleapis.com?project=${i}`}}):j?A.push({name:"BigQuery Project",category:"bigquery",status:"error",message:N,fix:{hint:"The GCP project does not exist or the credentials don't have access to it.",console:`${g}/home/dashboard`}}):F?A.push({name:"BigQuery API",category:"bigquery",status:"error",message:`Permission denied: ${N}`,fix:{hint:"Grant the service account BigQuery Data Editor + BigQuery Job User roles",console:`${g}/iam-admin/iam?project=${i}`}}):z?A.push({name:"BigQuery Dataset",category:"bigquery",status:"error",message:`Dataset not found: ${N}`,fix:{hint:"Create the dataset first",gcloud:`bq mk --dataset ${i}:YOUR_DATASET_ID`,console:`${g}/bigquery?project=${i}`}}):A.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable (table lookup returned expected error)"});}else if(v.name==="meilisearch"||typeof v.checkConnection=="function")try{let E=typeof v.checkConnection=="function"?await v.checkConnection():{healthy:await v.targetExists("__nonexistent__")};A.push({name:"Meilisearch API",category:"meilisearch",status:E.healthy?"ok":"error",message:E.healthy?`Meilisearch is reachable${E.version?` (v${E.version})`:""}`:`Meilisearch connection error: ${E.error??"unknown"}`,...E.error&&{fix:{hint:"Ensure Meilisearch is running and host/apiKey options are valid."}}});}catch(E){A.push({name:"Meilisearch API",category:"meilisearch",status:"error",message:`Meilisearch error: ${E?.message??String(E)}`});}for(let v of h)for(let E of v.adapters){let N=E.name==="bigquery"?"bigquery":E.name==="meilisearch"?"meilisearch":"storage";try{let H=await E.targetExists(v.tableName);A.push({name:`[${E.name}] Target: ${v.tableName}`,category:N,status:H?"ok":"warn",message:H?`Target \`${v.tableName}\` exists`:`Target \`${v.tableName}\` does not exist yet`,...!H&&{fix:{hint:"Target will be auto-created on first sync if autoMigrate is enabled."}}});}catch(H){A.push({name:`[${E.name}] Target: ${v.tableName}`,category:N,status:"error",message:H?.message??String(H)});}}if(a)for(let v of h){let E=`${m}-${v.name}`;try{let N=a.topic(E);if(typeof N.exists=="function"){let[H]=await N.exists();A.push({name:`Topic: ${E}`,category:"pubsub",status:H?"ok":"error",message:H?`Topic \`${E}\` exists`:`Topic \`${E}\` does not exist`,...!H&&{fix:{gcloud:`gcloud pubsub topics create ${E} --project=${i}`,console:`${g}/cloudpubsub/topic/list?project=${i}`}}});}else A.push({name:`Topic: ${E}`,category:"pubsub",status:"warn",message:"Cannot verify topic existence (PubSub client doesn't expose .exists())",fix:{gcloud:`gcloud pubsub topics create ${E} --project=${i}`,console:`${g}/cloudpubsub/topic/list?project=${i}`}});}catch(N){let H=N?.message??String(N),D=H.includes("disabled")||H.includes("has not been used");if(A.push({name:D?"Pub/Sub API":`Topic: ${E}`,category:"pubsub",status:"error",message:D?"Pub/Sub API is not enabled":H,fix:D?{gcloud:`gcloud services enable pubsub.googleapis.com --project=${i}`,console:`${g}/apis/library/pubsub.googleapis.com?project=${i}`}:{gcloud:`gcloud pubsub topics create ${E} --project=${i}`,console:`${g}/cloudpubsub/topic/list?project=${i}`}}),D)break}}else A.push({name:"Pub/Sub Client",category:"pubsub",status:"warn",message:"PubSub client not available for config check"});if(It(x)){let v=A.every(E=>E.status==="ok");Je(d,{project:i,healthy:v,checks:A});return}let k=v=>v==="ok"?'<span class="badge badge-ok">OK</span>':v==="warn"?'<span class="badge badge-warn">WARN</span>':'<span class="badge badge-err">ERROR</span>',R={bigquery:A.filter(v=>v.category==="bigquery"),meilisearch:A.filter(v=>v.category==="meilisearch"),pubsub:A.filter(v=>v.category==="pubsub"),firestore:A.filter(v=>v.category==="firestore"),storage:A.filter(v=>v.category==="storage")},P=(v,E)=>{if(E.length===0)return "";let N=E.map(H=>{let D="";if(H.fix){let F=[];H.fix.hint&&F.push(`<p class="muted">${G(H.fix.hint)}</p>`),H.fix.gcloud&&F.push(`<pre>$ ${G(H.fix.gcloud)}</pre>`),H.fix.console&&F.push(`<p><a href="${G(H.fix.console)}" target="_blank">Open GCP Console \u2192</a></p>`),D=`<div style="margin-top:.5rem">${F.join("")}</div>`;}return `<tr>
89
+ </div>`);Ne(d,Se);}finally{O.delete(i.name);}})),u.configCheck&&A.get(`${c}/config-check`,async(x,d)=>{let y=Oe(x,c,p),i=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??process.env.GCP_PROJECT??"unknown",g="https://console.cloud.google.com",m=l??"firestore-sync",C=[];for(let v of f)if(v.name==="bigquery")try{await v.targetExists("__nonexistent_health_check__"),C.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable"});}catch(E){let F=E?.message??String(E),H=F.toLowerCase(),D=H.includes("disabled")||H.includes("has not been used")||H.includes("accessnotconfigured"),N=H.includes("permission")||F.includes("403")||H.includes("access denied"),j=H.includes("project")&&H.includes("not found"),z=H.includes("not found")||F.includes("404");D?C.push({name:"BigQuery API",category:"bigquery",status:"error",message:"BigQuery API is not enabled",fix:{gcloud:`gcloud services enable bigquery.googleapis.com --project=${i}`,console:`${g}/apis/library/bigquery.googleapis.com?project=${i}`}}):j?C.push({name:"BigQuery Project",category:"bigquery",status:"error",message:F,fix:{hint:"The GCP project does not exist or the credentials don't have access to it.",console:`${g}/home/dashboard`}}):N?C.push({name:"BigQuery API",category:"bigquery",status:"error",message:`Permission denied: ${F}`,fix:{hint:"Grant the service account BigQuery Data Editor + BigQuery Job User roles",console:`${g}/iam-admin/iam?project=${i}`}}):z?C.push({name:"BigQuery Dataset",category:"bigquery",status:"error",message:`Dataset not found: ${F}`,fix:{hint:"Create the dataset first",gcloud:`bq mk --dataset ${i}:YOUR_DATASET_ID`,console:`${g}/bigquery?project=${i}`}}):C.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable (table lookup returned expected error)"});}else if(v.name==="meilisearch"||typeof v.checkConnection=="function")try{let E=typeof v.checkConnection=="function"?await v.checkConnection():{healthy:await v.targetExists("__nonexistent__")};C.push({name:"Meilisearch API",category:"meilisearch",status:E.healthy?"ok":"error",message:E.healthy?`Meilisearch is reachable${E.version?` (v${E.version})`:""}`:`Meilisearch connection error: ${E.error??"unknown"}`,...E.error&&{fix:{hint:"Ensure Meilisearch is running and host/apiKey options are valid."}}});}catch(E){C.push({name:"Meilisearch API",category:"meilisearch",status:"error",message:`Meilisearch error: ${E?.message??String(E)}`});}for(let v of h)for(let E of v.adapters){let F=E.name==="bigquery"?"bigquery":E.name==="meilisearch"?"meilisearch":"storage";try{let H=await E.targetExists(v.tableName);C.push({name:`[${E.name}] Target: ${v.tableName}`,category:F,status:H?"ok":"warn",message:H?`Target \`${v.tableName}\` exists`:`Target \`${v.tableName}\` does not exist yet`,...!H&&{fix:{hint:"Target will be auto-created on first sync if autoMigrate is enabled."}}});}catch(H){C.push({name:`[${E.name}] Target: ${v.tableName}`,category:F,status:"error",message:H?.message??String(H)});}}if(a)for(let v of h){let E=`${m}-${v.name}`;try{let F=a.topic(E);if(typeof F.exists=="function"){let[H]=await F.exists();C.push({name:`Topic: ${E}`,category:"pubsub",status:H?"ok":"error",message:H?`Topic \`${E}\` exists`:`Topic \`${E}\` does not exist`,...!H&&{fix:{gcloud:`gcloud pubsub topics create ${E} --project=${i}`,console:`${g}/cloudpubsub/topic/list?project=${i}`}}});}else C.push({name:`Topic: ${E}`,category:"pubsub",status:"warn",message:"Cannot verify topic existence (PubSub client doesn't expose .exists())",fix:{gcloud:`gcloud pubsub topics create ${E} --project=${i}`,console:`${g}/cloudpubsub/topic/list?project=${i}`}});}catch(F){let H=F?.message??String(F),D=H.includes("disabled")||H.includes("has not been used");if(C.push({name:D?"Pub/Sub API":`Topic: ${E}`,category:"pubsub",status:"error",message:D?"Pub/Sub API is not enabled":H,fix:D?{gcloud:`gcloud services enable pubsub.googleapis.com --project=${i}`,console:`${g}/apis/library/pubsub.googleapis.com?project=${i}`}:{gcloud:`gcloud pubsub topics create ${E} --project=${i}`,console:`${g}/cloudpubsub/topic/list?project=${i}`}}),D)break}}else C.push({name:"Pub/Sub Client",category:"pubsub",status:"warn",message:"PubSub client not available for config check"});if(Dt(x)){let v=C.every(E=>E.status==="ok");Ye(d,{project:i,healthy:v,checks:C});return}let k=v=>v==="ok"?'<span class="badge badge-ok">OK</span>':v==="warn"?'<span class="badge badge-warn">WARN</span>':'<span class="badge badge-err">ERROR</span>',R={bigquery:C.filter(v=>v.category==="bigquery"),meilisearch:C.filter(v=>v.category==="meilisearch"),pubsub:C.filter(v=>v.category==="pubsub"),firestore:C.filter(v=>v.category==="firestore"),storage:C.filter(v=>v.category==="storage")},P=(v,E)=>{if(E.length===0)return "";let F=E.map(H=>{let D="";if(H.fix){let N=[];H.fix.hint&&N.push(`<p class="muted">${G(H.fix.hint)}</p>`),H.fix.gcloud&&N.push(`<pre>$ ${G(H.fix.gcloud)}</pre>`),H.fix.console&&N.push(`<p><a href="${G(H.fix.console)}" target="_blank">Open GCP Console \u2192</a></p>`),D=`<div style="margin-top:.5rem">${N.join("")}</div>`;}return `<tr>
90
90
  <td>${k(H.status)}</td>
91
91
  <td><strong>${G(H.name)}</strong><br><span class="muted">${G(H.message)}</span>${D}</td>
92
92
  </tr>`}).join(`
93
93
  `);return `<h2>${G(v)}</h2>
94
94
  <table><thead><tr><th style="width:80px">Status</th><th>Check</th></tr></thead>
95
- <tbody>${N}</tbody></table>`},$=A.every(v=>v.status==="ok")?'<span class="badge badge-ok">All checks passed</span>':'<span class="badge badge-warn">Some issues found</span>',_=Ne("Config Check",y,`<div class="card">
95
+ <tbody>${F}</tbody></table>`},$=C.every(v=>v.status==="ok")?'<span class="badge badge-ok">All checks passed</span>':'<span class="badge badge-warn">Some issues found</span>',M=Fe("Config Check",y,`<div class="card">
96
96
  <p>Project: <code>${G(i)}</code> ${$}</p>
97
97
  ${P("BigQuery",R.bigquery)}
98
98
  ${P("Meilisearch",R.meilisearch)}
99
99
  ${P("Pub/Sub",R.pubsub)}
100
100
  ${P("Other Targets",R.storage)}
101
101
  ${P("Firestore",R.firestore)}
102
- </div>`);Fe(d,_);}),async(x,d)=>{await C.handle(x,d);}}var Ka="firestore-sync";function Za(e,t){return t?`${t}/{docId}`:(console.warn(`[SyncTriggers] Cannot determine collection path for "${e}". Skipping.`),null)}function Wa(e){let t=[e?.documentKey,e?.pathKey,e?.createdKey,e?.updatedKey].filter(o=>typeof o=="string"),n=typeof e?.path=="string"?e.path:null,r=n?Me(n,e?.documentKey??"docId"):null;return {isGroup:!!e?.isGroup,documentKey:t[0]??"docId",collectionPath:r?r.collectionPath:null,documentPathTemplate:r&&(!e?.isGroup||r.collectionPath.includes("/"))?r.documentPathTemplate:null,historyShadowKey:ve(e?.history)}}function Qa(e){let t=e?._collectionPath??e?.ref?.path??null,n=typeof e?._documentPathTemplate=="string"?e._documentPathTemplate:null;return {isGroup:!!e?._isGroup,documentKey:e?._systemKeys?.[0]??"docId",collectionPath:t,documentPathTemplate:n&&(!e?._isGroup||t&&t.includes("/"))?n:null,historyShadowKey:typeof e?._historyShadowKey=="string"?e._historyShadowKey:ve(e?._historyConfig)}}function Eo(e,t){let{onDocumentWritten:n}=t.deps.firestoreTriggers,r=t.deps.pubsub,o=t?.topicPrefix??Ka,s={},a=new Map;function l(b){let T=a.get(b);return T||(T=r.topic(b),a.set(b,T),T)}async function c(b,T){await l(b).publishMessage({json:T});}let u=e?.rawMapping,p=u?Object.entries(u).map(([b,T])=>[b,Wa(T)]):Object.entries(e).map(([b,T])=>[b,Qa(T)]),f=t?.repos,h=Object.keys(f??{}).length>0;for(let[b,T]of p){if(h&&(!f||!(b in f)))continue;let S=f?.[b],I;if(T.isGroup){let g=S?.triggerPath??T.documentPathTemplate;if(!g){console.warn(`[SyncTriggers] Skipping collection-group repo "${b}". Provide a triggerPath in the sync repos config for group collections or use a full path template.`);continue}I=g;}else I=S?.triggerPath??T.documentPathTemplate??Za(b,T.collectionPath);if(!I)continue;let C=T.documentKey,O=T.historyShadowKey?Array.from(new Set([...S?.exclude??[],T.historyShadowKey])):S?.exclude,x=`${o}-${b}`,d={...t?.triggerOptions,...S?.triggerOptions},y=Object.keys(d).length>0,i=async g=>{let m=g.data?.before,A=g.data?.after;if(!m&&!A)return;let k=!!m?.exists,R=!!A?.exists;if(!k&&R){let P=A.data();if(!P)return;let M=String(P[C]??A.id),$=Pt(P,{exclude:O,columnMap:S?.columnMap,flat:S?.flat,transformDoc:S?.transformDoc}),_={operation:"INSERT",repoName:b,docId:M,data:$,timestamp:new Date().toISOString(),version:Date.now()};await c(x,_);}else if(k&&R){let P=A.data();if(!P)return;let M=String(P[C]??A.id),$=Pt(P,{exclude:O,columnMap:S?.columnMap,flat:S?.flat,transformDoc:S?.transformDoc}),_={operation:"UPSERT",repoName:b,docId:M,data:$,timestamp:new Date().toISOString(),version:Date.now()};await c(x,_);}else if(k&&!R){let P=m.data(),M=String(P?.[C]??m.id),$={operation:"DELETE",repoName:b,docId:M,data:null,timestamp:new Date().toISOString(),version:Date.now()};await c(x,$);}};s[`${b}_onSync`]=n(y?{document:I,...d}:I,i);}return s}var ke="__sync_version";ut();var Ga=new Set(["ZodOptional","ZodNullable","ZodDefault"]);function Ja(e){let t=e,n=false;for(;;){let r=J(t);if(!Ga.has(r))break;(r==="ZodOptional"||r==="ZodNullable")&&(n=true);let o=ye(t);if(!o)break;t=o;}return {inner:t,nullable:n}}var Ya={ZodString:"string",ZodNumber:"number",ZodBigInt:"bigint",ZodBoolean:"boolean",ZodDate:"timestamp",ZodEnum:"string",ZodNativeEnum:"string",ZodLiteral:"string"};function Io(e,t,n,r,o,s,a,l){for(let[c,u]of Object.entries(e)){let p=n?`${n}__${c}`:c;if(o.has(c)||o.has(p))continue;let{inner:f,nullable:w}=Ja(u),h=J(f),b=r||w;if(h==="ZodObject"){let C=me(f);Io(C,t,p,b,o,s,a,l);continue}let T=Ya[h]??"json",S=p===a||c===a,I=s[p]??s[c]??p;l.push({name:I,sqlType:t.mapType(T),nullable:S?false:b,isPrimaryKey:S});}}function Nt(e,t,n={}){let{primaryKey:r,exclude:o=[],columnMap:s={}}=n,a=new Set(o),l=me(e),c=[];return Io(l,t,"",false,a,s,r,c),c.some(u=>u.name===ke)||c.push({name:ke,sqlType:t.mapType("bigint"),nullable:true,isPrimaryKey:false,description:"Monotonic publish version (Date.now() ms). Internal."}),c}var hn=class hn{constructor(t){this.buffer=[];this.flushing=false;this.lastFlushFailed=false;this.flushPromise=null;this.timer=null;this.flushedEvents=0;this.failedEvents=0;this.flushedBatches=0;this.failedBatches=0;this.errorSeq=0;this.recentErrors=[];this.adapter=t.adapter,this.tableName=t.tableName,this.primaryKey=t.primaryKey,this.batchSize=t.batchSize??100,this.onFlushError=t.onFlushError;let n=t.flushIntervalMs??5e3;n>0&&(this.timer=setInterval(()=>{this.flush().catch(r=>{console.error(`[SyncQueue] Scheduled flush failed for ${this.tableName}:`,r);});},n),typeof this.timer=="object"&&"unref"in this.timer&&this.timer.unref());}get size(){return this.buffer.length}getStats(){return {flushedEvents:this.flushedEvents,failedEvents:this.failedEvents,flushedBatches:this.flushedBatches,failedBatches:this.failedBatches,errorSeq:this.errorSeq,recentErrors:this.recentErrors.map(t=>({...t}))}}enqueue(...t){this.buffer.push(...t),this.buffer.length>=this.batchSize&&!this.flushing&&!this.lastFlushFailed&&this._autoFlush().catch(n=>{console.error(`[SyncQueue] Auto-flush failed for ${this.tableName}:`,n);});}async _autoFlush(){for(;this.flushPromise;)await this.flushPromise;this.buffer.length<this.batchSize||this.lastFlushFailed||(this.flushing=true,this.flushPromise=this._drain(true).finally(()=>{this.flushing=false,this.flushPromise=null;}),await this.flushPromise);}async flush(){for(;this.flushPromise;)await this.flushPromise;this.buffer.length!==0&&(this.flushing=true,this.flushPromise=this._drain(false).finally(()=>{this.flushing=false,this.flushPromise=null;}),await this.flushPromise);}async flushWithReport(){let t=this.getStats();await this.flush();let n=this.getStats();return {flushed:n.flushedEvents-t.flushedEvents,failed:n.failedEvents-t.failedEvents,errors:n.recentErrors.filter(r=>r.seq>t.errorSeq).map(r=>r.message)}}async _drain(t){try{for(;(t?this.buffer.length>=this.batchSize:this.buffer.length>0)&&await this._doFlush(););}finally{this.flushing=false;}}async _doFlush(){let t=this.buffer.splice(0,this.batchSize);if(t.length===0)return false;try{let n=new Map,r=[];for(let s of t)if(s.operation==="DELETE")r.push(s.docId),n.delete(s.docId);else if(s.data){let a=n.get(s.docId);if(!a)n.set(s.docId,s.data);else {let l=Number(a[ke]??0);Number(s.data[ke]??0)>=l&&n.set(s.docId,s.data);}}let o=Array.from(n.values());o.length>0&&(typeof this.adapter.upsert=="function"?await this.adapter.upsert(this.tableName,o,this.primaryKey):typeof this.adapter.upsertRows=="function"&&await this.adapter.upsertRows(this.tableName,o,this.primaryKey)),r.length>0&&(typeof this.adapter.delete=="function"?await this.adapter.delete(this.tableName,this.primaryKey,r):typeof this.adapter.deleteRows=="function"&&await this.adapter.deleteRows(this.tableName,this.primaryKey,r)),this.flushedEvents+=t.length,this.flushedBatches++,this.lastFlushFailed=!1;}catch(n){let r=n instanceof Error?n.message:String(n);if(this.failedEvents+=t.length,this.failedBatches++,this.errorSeq++,this.recentErrors.push({seq:this.errorSeq,message:r,count:t.length,timestamp:Date.now()}),this.recentErrors.length>hn.MAX_RECENT_ERRORS&&this.recentErrors.shift(),this.onFlushError)await this.onFlushError(t,n);else return this.buffer.unshift(...t),this.lastFlushFailed=true,console.error(`[SyncQueue] Flush failed for ${this.tableName}:`,n),false}return true}async shutdown(){this.timer&&(clearInterval(this.timer),this.timer=null),await this.flush();}};hn.MAX_RECENT_ERRORS=50;var mn=hn;var Mo=new Set;async function ri(e,t,n,r,o,s,a){let l=`${e}:${t.name}`;if(!Mo.has(l)){if(typeof t.ensureTarget=="function")await t.ensureTarget({targetName:r,primaryKey:o,schema:n,exclude:s,columnMap:a});else if("dialect"in t&&typeof t.createTable=="function"){let c=t,u=Nt(n,c.dialect,{primaryKey:o,exclude:s,columnMap:a});if(!await c.tableExists(r))await c.createTable({tableName:r,columns:u});else {let f=new Set(await c.getTableColumns(r)),w=u.filter(h=>!f.has(h.name));w.length>0&&(await c.addColumns(r,w),await c.onSchemaChange?.(r));}}Mo.add(l);}}function _o(e,t){let{deps:n,adapter:r,adapters:o,batchSize:s=100,flushIntervalMs:a=5e3,autoMigrate:l=false,topicPrefix:c="firestore-sync",maxDlqAttempts:u=5,workerOptions:p,repos:f={}}=t,h=(o||(Array.isArray(r)?r:r?[r]:[])).map(O=>typeof O=="function"?O():O);function b(O){let x=f[O];if(x?.adapters&&x.adapters.length>0){let d=new Set(x.adapters);return h.filter(y=>d.has(y.name))}return h}let T=new Map;function S(O,x,d){let y=`${O}:${x.name}`,i=T.get(y);if(i)return i;let m=f[O]?.tableName??O,A=`${c}-${O}-${x.name}-dlq`,k=n.pubsub.topic(A),R=false,P=async()=>{if(!R){try{await k.create(),console.info(`[SyncWorker:${x.name}] Created DLQ topic "${A}"`);}catch($){if($?.code!==6)throw $}R=true;}},M=async($,_)=>{console.error(`[SyncWorker:${x.name}] Flush failed for "${O}" (${$.length} events):`,_),await P(),await Promise.all($.map(v=>{let E=(v.attempts??0)+1;if(u>0&&E>u)return console.error(`[SyncWorker:${x.name}] Dropping event for "${O}" after ${E-1} DLQ attempts:`,{docId:v.docId,operation:v.operation}),Promise.resolve();let N={...v,attempts:E,firstFailedAt:v.firstFailedAt??Date.now()};return k.publishMessage({json:N})}));};return i=new mn({adapter:x,tableName:m,primaryKey:d,batchSize:s,flushIntervalMs:a,onFlushError:M}),T.set(y,i),T.has(O)||T.set(O,i),i}async function I(O){let{repoName:x}=O,d=e[x];if(!d){console.warn(`[SyncWorker] Unknown repo "${x}", skipping event`);return}let y=d._systemKeys?.[0]??d.documentKey??"docId",i=f[x],g=i?.columnMap,m=g?.[y]??y;O.data&&(O.data[ke]=O.version??Date.now());let A=b(x);for(let k of A){if(l){let P=d.schema??void 0;if(P){let M=i?.tableName??x;await ri(x,k,P,M,m,i?.exclude,g);}}S(x,k,m).enqueue(O);}}function C(O){let x=async d=>{let y=d.data?.message?.json??d.data?.json;if(!y){console.warn("[SyncWorker] Received empty PubSub message");return}await I(y);let i=b(y.repoName);for(let g of i){let m=`${y.repoName}:${g.name}`,A=T.get(m);A&&await A.flush();}};return p?n.pubsubHandler.onMessagePublished({topic:O,...p},x):n.pubsubHandler.onMessagePublished(O,x)}return {handleMessage:I,createHandler:C,queues:T,async shutdown(){let O=[],x=new Set;for(let d of T.values())x.has(d)||(x.add(d),O.push(d.shutdown()));await Promise.all(O);}}}var oi="firestore-sync";function No(e){if(typeof e!="function")return e;let t=e,n;return new Proxy({},{get(r,o){return n||(n=t()),n[o]},has(r,o){return n||(n=t()),o in n}})}function Fo(e,t){let{deps:n,adapter:r,adapters:o,topicPrefix:s=oi,batchSize:a,flushIntervalMs:l,autoMigrate:c,admin:u,workerOptions:p,triggerOptions:f,repos:w}=t,h=No(n.pubsub),T=(o||(Array.isArray(r)?r:r?[r]:[])).map(k=>No(k)),S=Eo(e,{deps:{firestoreTriggers:n.firestoreTriggers,pubsub:h},topicPrefix:s,triggerOptions:f,repos:w}),I=_o(e,{deps:{pubsubHandler:n.pubsubHandler,pubsub:h},adapters:T,batchSize:a,flushIntervalMs:l,autoMigrate:c,topicPrefix:s,workerOptions:p,repos:w}),C={},O=w,x=e?.rawMapping,d=Object.keys(O??{}),y=d.length>0,i=Object.keys(x||e),g=y?d.filter(k=>i.includes(k)||k in e):i;for(let k of g){let R=e?.rawMapping,P=R?!!R[k]?.isGroup:!!e[k]?._isGroup,M=R?R[k]?.path:e[k]?._collectionPath,$=typeof M=="string"&&M.includes("/");!y&&P&&!O?.[k]?.triggerPath&&!$||(C[`sync_${k}`]=I.createHandler(`${s}-${k}`));}let m=null;u&&(m=Co(e,T,I.queues,I.handleMessage,u,w??{},h,s),C.adminsync=u.onRequest?u.httpsOptions?u.onRequest(u.httpsOptions,m):u.onRequest(m):m);let A={functions:{...S,...C},adminHandler:m,handleMessage:I.handleMessage,queues:I.queues,shutdown:I.shutdown};for(let k of ["adminHandler","handleMessage","queues","shutdown"])Object.defineProperty(A,k,{enumerable:false});return A}function si(e){if(e.client)return e.client;if(!e.host)throw new Error("MeilisearchAdapter requires either a `client` instance or a `host` option.");try{let{MeiliSearch:t}=Lr("meilisearch");return new t({host:e.host,apiKey:e.apiKey})}catch(t){throw new Error(`Failed to load the "meilisearch" package. Please install it with:
102
+ </div>`);Ne(d,M);}),async(x,d)=>{await A.handle(x,d);}}var ei="firestore-sync";function ti(e,t){return t?`${t}/{docId}`:(console.warn(`[SyncTriggers] Cannot determine collection path for "${e}". Skipping.`),null)}function ni(e){let t=[e?.documentKey,e?.pathKey,e?.createdKey,e?.updatedKey].filter(o=>typeof o=="string"),n=typeof e?.path=="string"?e.path:null,r=n?_e(n,e?.documentKey??"docId"):null;return {isGroup:!!e?.isGroup,documentKey:t[0]??"docId",collectionPath:r?r.collectionPath:null,documentPathTemplate:r&&(!e?.isGroup||r.collectionPath.includes("/"))?r.documentPathTemplate:null,historyShadowKey:ve(e?.history)}}function ri(e){let t=e?._collectionPath??e?.ref?.path??null,n=typeof e?._documentPathTemplate=="string"?e._documentPathTemplate:null;return {isGroup:!!e?._isGroup,documentKey:e?._systemKeys?.[0]??"docId",collectionPath:t,documentPathTemplate:n&&(!e?._isGroup||t&&t.includes("/"))?n:null,historyShadowKey:typeof e?._historyShadowKey=="string"?e._historyShadowKey:ve(e?._historyConfig)}}function Io(e,t){let{onDocumentWritten:n}=t.deps.firestoreTriggers,r=t.deps.pubsub,o=t?.topicPrefix??ei,s={},a=new Map;function l(w){let T=a.get(w);return T||(T=r.topic(w),a.set(w,T),T)}async function c(w,T){await l(w).publishMessage({json:T});}let u=e?.rawMapping,p=u?Object.entries(u).map(([w,T])=>[w,ni(T)]):Object.entries(e).map(([w,T])=>[w,ri(T)]),f=t?.repos,h=Object.keys(f??{}).length>0;for(let[w,T]of p){if(h&&(!f||!(w in f)))continue;let S=f?.[w],I;if(T.isGroup){let g=S?.triggerPath??T.documentPathTemplate;if(!g){console.warn(`[SyncTriggers] Skipping collection-group repo "${w}". Provide a triggerPath in the sync repos config for group collections or use a full path template.`);continue}I=g;}else I=S?.triggerPath??T.documentPathTemplate??ti(w,T.collectionPath);if(!I)continue;let A=T.documentKey,O=T.historyShadowKey?Array.from(new Set([...S?.exclude??[],T.historyShadowKey])):S?.exclude,x=`${o}-${w}`,d={...t?.triggerOptions,...S?.triggerOptions},y=Object.keys(d).length>0,i=async g=>{let m=g.data?.before,C=g.data?.after;if(!m&&!C)return;let k=!!m?.exists,R=!!C?.exists;if(!k&&R){let P=C.data();if(!P)return;let _=String(P[A]??C.id),$=It(P,{exclude:O,columnMap:S?.columnMap,flat:S?.flat,transformDoc:S?.transformDoc}),M={operation:"INSERT",repoName:w,docId:_,data:$,timestamp:new Date().toISOString(),version:Date.now()};await c(x,M);}else if(k&&R){let P=C.data();if(!P)return;let _=String(P[A]??C.id),$=It(P,{exclude:O,columnMap:S?.columnMap,flat:S?.flat,transformDoc:S?.transformDoc}),M={operation:"UPSERT",repoName:w,docId:_,data:$,timestamp:new Date().toISOString(),version:Date.now()};await c(x,M);}else if(k&&!R){let P=m.data(),_=String(P?.[A]??m.id),$={operation:"DELETE",repoName:w,docId:_,data:null,timestamp:new Date().toISOString(),version:Date.now()};await c(x,$);}};s[`${w}_onSync`]=n(y?{document:I,...d}:I,i);}return s}var ke="__sync_version";ft();var si=new Set(["ZodOptional","ZodNullable","ZodDefault"]);function ai(e){let t=e,n=false;for(;;){let r=J(t);if(!si.has(r))break;(r==="ZodOptional"||r==="ZodNullable")&&(n=true);let o=ye(t);if(!o)break;t=o;}return {inner:t,nullable:n}}var ii={ZodString:"string",ZodNumber:"number",ZodBigInt:"bigint",ZodBoolean:"boolean",ZodDate:"timestamp",ZodEnum:"string",ZodNativeEnum:"string",ZodLiteral:"string"};function Ho(e,t,n,r,o,s,a,l){for(let[c,u]of Object.entries(e)){let p=n?`${n}__${c}`:c;if(o.has(c)||o.has(p))continue;let{inner:f,nullable:b}=ai(u),h=J(f),w=r||b;if(h==="ZodObject"){let A=me(f);Ho(A,t,p,w,o,s,a,l);continue}let T=ii[h]??"json",S=p===a||c===a,I=s[p]??s[c]??p;l.push({name:I,sqlType:t.mapType(T),nullable:S?false:w,isPrimaryKey:S});}}function Nt(e,t,n={}){let{primaryKey:r,exclude:o=[],columnMap:s={}}=n,a=new Set(o),l=me(e),c=[];return Ho(l,t,"",false,a,s,r,c),c.some(u=>u.name===ke)||c.push({name:ke,sqlType:t.mapType("bigint"),nullable:true,isPrimaryKey:false,description:"Monotonic publish version (Date.now() ms). Internal."}),c}var gn=class gn{constructor(t){this.buffer=[];this.flushing=false;this.lastFlushFailed=false;this.flushPromise=null;this.timer=null;this.flushedEvents=0;this.failedEvents=0;this.flushedBatches=0;this.failedBatches=0;this.errorSeq=0;this.recentErrors=[];this.adapter=t.adapter,this.tableName=t.tableName,this.primaryKey=t.primaryKey,this.batchSize=t.batchSize??100,this.onFlushError=t.onFlushError;let n=t.flushIntervalMs??5e3;n>0&&(this.timer=setInterval(()=>{this.flush().catch(r=>{console.error(`[SyncQueue] Scheduled flush failed for ${this.tableName}:`,r);});},n),typeof this.timer=="object"&&"unref"in this.timer&&this.timer.unref());}get size(){return this.buffer.length}getStats(){return {flushedEvents:this.flushedEvents,failedEvents:this.failedEvents,flushedBatches:this.flushedBatches,failedBatches:this.failedBatches,errorSeq:this.errorSeq,recentErrors:this.recentErrors.map(t=>({...t}))}}enqueue(...t){this.buffer.push(...t),this.buffer.length>=this.batchSize&&!this.flushing&&!this.lastFlushFailed&&this._autoFlush().catch(n=>{console.error(`[SyncQueue] Auto-flush failed for ${this.tableName}:`,n);});}async _autoFlush(){for(;this.flushPromise;)await this.flushPromise;this.buffer.length<this.batchSize||this.lastFlushFailed||(this.flushing=true,this.flushPromise=this._drain(true).finally(()=>{this.flushing=false,this.flushPromise=null;}),await this.flushPromise);}async flush(){for(;this.flushPromise;)await this.flushPromise;this.buffer.length!==0&&(this.flushing=true,this.flushPromise=this._drain(false).finally(()=>{this.flushing=false,this.flushPromise=null;}),await this.flushPromise);}async flushWithReport(){let t=this.getStats();await this.flush();let n=this.getStats();return {flushed:n.flushedEvents-t.flushedEvents,failed:n.failedEvents-t.failedEvents,errors:n.recentErrors.filter(r=>r.seq>t.errorSeq).map(r=>r.message)}}async _drain(t){try{for(;(t?this.buffer.length>=this.batchSize:this.buffer.length>0)&&await this._doFlush(););}finally{this.flushing=false;}}async _doFlush(){let t=this.buffer.splice(0,this.batchSize);if(t.length===0)return false;try{let n=new Map,r=[];for(let s of t)if(s.operation==="DELETE")r.push(s.docId),n.delete(s.docId);else if(s.data){let a=n.get(s.docId);if(!a)n.set(s.docId,s.data);else {let l=Number(a[ke]??0);Number(s.data[ke]??0)>=l&&n.set(s.docId,s.data);}}let o=Array.from(n.values());o.length>0&&(typeof this.adapter.upsert=="function"?await this.adapter.upsert(this.tableName,o,this.primaryKey):typeof this.adapter.upsertRows=="function"&&await this.adapter.upsertRows(this.tableName,o,this.primaryKey)),r.length>0&&(typeof this.adapter.delete=="function"?await this.adapter.delete(this.tableName,this.primaryKey,r):typeof this.adapter.deleteRows=="function"&&await this.adapter.deleteRows(this.tableName,this.primaryKey,r)),this.flushedEvents+=t.length,this.flushedBatches++,this.lastFlushFailed=!1;}catch(n){let r=n instanceof Error?n.message:String(n);if(this.failedEvents+=t.length,this.failedBatches++,this.errorSeq++,this.recentErrors.push({seq:this.errorSeq,message:r,count:t.length,timestamp:Date.now()}),this.recentErrors.length>gn.MAX_RECENT_ERRORS&&this.recentErrors.shift(),this.onFlushError)await this.onFlushError(t,n);else return this.buffer.unshift(...t),this.lastFlushFailed=true,console.error(`[SyncQueue] Flush failed for ${this.tableName}:`,n),false}return true}async shutdown(){this.timer&&(clearInterval(this.timer),this.timer=null),await this.flush();}};gn.MAX_RECENT_ERRORS=50;var hn=gn;var No=new Set;async function pi(e,t,n,r,o,s,a){let l=`${e}:${t.name}`;if(!No.has(l)){if(typeof t.ensureTarget=="function")await t.ensureTarget({targetName:r,primaryKey:o,schema:n,exclude:s,columnMap:a});else if("dialect"in t&&typeof t.createTable=="function"){let c=t,u=Nt(n,c.dialect,{primaryKey:o,exclude:s,columnMap:a});if(!await c.tableExists(r))await c.createTable({tableName:r,columns:u});else {let f=new Set(await c.getTableColumns(r)),b=u.filter(h=>!f.has(h.name));b.length>0&&(await c.addColumns(r,b),await c.onSchemaChange?.(r));}}No.add(l);}}function jo(e,t){let{deps:n,adapter:r,adapters:o,batchSize:s=100,flushIntervalMs:a=5e3,autoMigrate:l=false,topicPrefix:c="firestore-sync",maxDlqAttempts:u=5,workerOptions:p,repos:f={}}=t,h=(o||(Array.isArray(r)?r:r?[r]:[])).map(O=>typeof O=="function"?O():O);function w(O){let x=f[O];if(x?.adapters&&x.adapters.length>0){let d=new Set(x.adapters);return h.filter(y=>d.has(y.name))}return h}let T=new Map;function S(O,x,d){let y=`${O}:${x.name}`,i=T.get(y);if(i)return i;let m=f[O]?.tableName??O,C=`${c}-${O}-${x.name}-dlq`,k=n.pubsub.topic(C),R=false,P=async()=>{if(!R){try{await k.create(),console.info(`[SyncWorker:${x.name}] Created DLQ topic "${C}"`);}catch($){if($?.code!==6)throw $}R=true;}},_=async($,M)=>{console.error(`[SyncWorker:${x.name}] Flush failed for "${O}" (${$.length} events):`,M),await P(),await Promise.all($.map(v=>{let E=(v.attempts??0)+1;if(u>0&&E>u)return console.error(`[SyncWorker:${x.name}] Dropping event for "${O}" after ${E-1} DLQ attempts:`,{docId:v.docId,operation:v.operation}),Promise.resolve();let F={...v,attempts:E,firstFailedAt:v.firstFailedAt??Date.now()};return k.publishMessage({json:F})}));};return i=new hn({adapter:x,tableName:m,primaryKey:d,batchSize:s,flushIntervalMs:a,onFlushError:_}),T.set(y,i),T.has(O)||T.set(O,i),i}async function I(O){let{repoName:x}=O,d=e[x];if(!d){console.warn(`[SyncWorker] Unknown repo "${x}", skipping event`);return}let y=d._systemKeys?.[0]??d.documentKey??"docId",i=f[x],g=i?.columnMap,m=g?.[y]??y;O.data&&(O.data[ke]=O.version??Date.now());let C=w(x);for(let k of C){if(l){let P=d.schema??void 0;if(P){let _=i?.tableName??x;await pi(x,k,P,_,m,i?.exclude,g);}}S(x,k,m).enqueue(O);}}function A(O){let x=async d=>{let y=d.data?.message?.json??d.data?.json;if(!y){console.warn("[SyncWorker] Received empty PubSub message");return}await I(y);let i=w(y.repoName);for(let g of i){let m=`${y.repoName}:${g.name}`,C=T.get(m);C&&await C.flush();}};return p?n.pubsubHandler.onMessagePublished({topic:O,...p},x):n.pubsubHandler.onMessagePublished(O,x)}return {handleMessage:I,createHandler:A,queues:T,async shutdown(){let O=[],x=new Set;for(let d of T.values())x.has(d)||(x.add(d),O.push(d.shutdown()));await Promise.all(O);}}}var fi="firestore-sync";function Bo(e){if(typeof e!="function")return e;let t=e,n;return new Proxy({},{get(r,o){return n||(n=t()),n[o]},has(r,o){return n||(n=t()),o in n}})}function zo(e,t){let{deps:n,adapter:r,adapters:o,topicPrefix:s=fi,batchSize:a,flushIntervalMs:l,autoMigrate:c,admin:u,workerOptions:p,triggerOptions:f,repos:b}=t,h=Bo(n.pubsub),T=(o||(Array.isArray(r)?r:r?[r]:[])).map(k=>Bo(k)),S=Io(e,{deps:{firestoreTriggers:n.firestoreTriggers,pubsub:h},topicPrefix:s,triggerOptions:f,repos:b}),I=jo(e,{deps:{pubsubHandler:n.pubsubHandler,pubsub:h},adapters:T,batchSize:a,flushIntervalMs:l,autoMigrate:c,topicPrefix:s,workerOptions:p,repos:b}),A={},O=b,x=e?.rawMapping,d=Object.keys(O??{}),y=d.length>0,i=Object.keys(x||e),g=y?d.filter(k=>i.includes(k)||k in e):i;for(let k of g){let R=e?.rawMapping,P=R?!!R[k]?.isGroup:!!e[k]?._isGroup,_=R?R[k]?.path:e[k]?._collectionPath,$=typeof _=="string"&&_.includes("/");!y&&P&&!O?.[k]?.triggerPath&&!$||(A[`sync_${k}`]=I.createHandler(`${s}-${k}`));}let m=null;u&&(m=Po(e,T,I.queues,I.handleMessage,u,b??{},h,s),A.adminsync=u.onRequest?u.httpsOptions?u.onRequest(u.httpsOptions,m):u.onRequest(m):m);let C={functions:{...S,...A},adminHandler:m,handleMessage:I.handleMessage,queues:I.queues,shutdown:I.shutdown};for(let k of ["adminHandler","handleMessage","queues","shutdown"])Object.defineProperty(C,k,{enumerable:false});return C}function yi(e){if(e.client)return e.client;if(!e.host)throw new Error("MeilisearchAdapter requires either a `client` instance or a `host` option.");try{let{MeiliSearch:t}=Kr("meilisearch");return new t({host:e.host,apiKey:e.apiKey})}catch(t){throw new Error(`Failed to load the "meilisearch" package. Please install it with:
103
103
  bun add meilisearch # or npm install meilisearch
104
- Original error: ${t?.message??String(t)}`)}}function ai(e,t){if(!e||!t)return false;for(let[n,r]of Object.entries(t)){if(r===void 0)continue;let o=e[n];if(Array.isArray(r)){if(!Array.isArray(o)||r.length!==o.length)return false;for(let s=0;s<r.length;s++)if(r[s]!==o[s])return false}else if(typeof r=="object"&&r!==null){if(JSON.stringify(r)!==JSON.stringify(o))return false}else if(r!==o)return false}return true}var gn=class{constructor(t){this.name="meilisearch";this._client=null;this.options=t,t.client&&(this._client=t.client);}get indexesSettings(){return this.options.indexesSettings}get client(){return this._client||(this._client=si(this.options)),this._client}async targetExists(t){try{return await this.client.getIndex(t),!0}catch(n){if(n?.code==="index_not_found"||n?.cause?.code==="index_not_found"||n?.statusCode===404||n?.status===404||n?.response?.status===404||n?.cause?.status===404||n?.cause?.statusCode===404||n?.cause?.response?.status===404)return false;throw n}}async upsert(t,n,r){if(n.length===0)return;let o=this.options.unflatten!==false,s=n.map(l=>{let c=o?Ao(l):l;return typeof this.options.transformDoc=="function"&&(c=this.options.transformDoc(c)),c});await this.client.index(t).addDocuments(s,{primaryKey:r});}async delete(t,n,r){if(r.length===0)return;await this.client.index(t).deleteDocuments(r);}async ensureTarget(t){let{targetName:n,primaryKey:r}=t;await this.targetExists(n)||await this.client.createIndex(n,{primaryKey:r});let s=this.options.indexesSettings?.[n];if(s){let{retrievableAttributes:a,attributesToRetrieve:l,...c}=s,u={...c,displayedAttributes:c.displayedAttributes??a??l};u.displayedAttributes===void 0&&delete u.displayedAttributes;let p=this.client.index(n);if(typeof p.getSettings=="function")try{let f=await p.getSettings();if(ai(f,u))return}catch{}await p.updateSettings(u);}}async healthCheck(t){let{targetName:n}=t;try{if(!await this.targetExists(n))return {healthy:!1,targetName:n,targetExists:!1,error:`Meilisearch index "${n}" does not exist`};let o=this.client.index(n),s=await o.getStats(),a=typeof o.getRawInfo=="function"?await o.getRawInfo():{};return {healthy:!0,targetName:n,targetExists:!0,error:null,details:{numberOfDocuments:s?.numberOfDocuments??0,isIndexing:s?.isIndexing??!1,fieldDistribution:s?.fieldDistribution??{},primaryKey:a?.primaryKey??t.primaryKey}}}catch(r){return {healthy:false,targetName:n,targetExists:false,error:r?.message??String(r)}}}async checkConnection(){try{let t=!0;if(typeof this.client.isHealthy=="function"){let r=await this.client.isHealthy();t=r?.status==="available"||r===!0;}else if(typeof this.client.health=="function"){let r=await this.client.health();t=r?.status==="available"||r===!0;}let n;return typeof this.client.getVersion=="function"&&(n=(await this.client.getVersion())?.pkgVersion),{healthy:t,version:n}}catch(t){return {healthy:false,error:t?.message??String(t)}}}};ut();ut();function ii(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/^\s/,"").replace(/^./,t=>t.toUpperCase())}function jo(e){let t=e,n=true,r=false,o;for(;;){let s=J(t);if(s==="ZodOptional")n=false,t=ye(t);else if(s==="ZodNullable")n=false,r=true,t=ye(t);else if(s==="ZodDefault")n=false,o=Oo(t),t=ye(t);else if(s==="ZodEffects"||s==="ZodPipe"||s==="ZodTransform"){let a=Dt(t);if(!a)break;t=a;}else break}return {inner:t,required:n,nullable:r,defaultValue:o}}function Re(e,t=""){if(J(e)==="ZodObject"){let r=me(e);return Object.entries(r).map(([o,s])=>Bo(t?`${t}.${o}`:o,o,s))}return [Bo(t||"value",t||"value",e)]}function Bo(e,t,n){let{inner:r,required:o,nullable:s,defaultValue:a}=jo(n),l=J(r),c=ii(t.split(".").pop()??t);switch(l){case "ZodString":{let u=Po(r),p=u.includes("email"),f=u.includes("url");return {name:e,label:c,type:"text",required:o,nullable:s,defaultValue:a,hint:p?"email":f?"url":void 0}}case "ZodNumber":case "ZodBigInt":return {name:e,label:c,type:"number",required:o,nullable:s,defaultValue:a};case "ZodBoolean":return {name:e,label:c,type:"checkbox",required:o,nullable:s,defaultValue:a};case "ZodDate":case "ZodCoerce":return {name:e,label:c,type:"datetime-local",required:o,nullable:s,defaultValue:a};case "ZodEnum":{let u=$t(r);return {name:e,label:c,type:"select",required:o,nullable:s,defaultValue:a,options:u}}case "ZodNativeEnum":{let u=Ht(r),p=Object.values(u).filter(f=>typeof f=="string");return {name:e,label:c,type:"select",required:o,nullable:s,defaultValue:a,options:p}}case "ZodLiteral":{let u=String(Mt(r)??"");return {name:e,label:c,type:"select",required:o,nullable:s,defaultValue:a,options:[u]}}case "ZodUnion":{let u=_t(r);if(u.length>0&&u.every(h=>J(h)==="ZodLiteral")){let h=u.map(b=>String(Mt(b)??""));return {name:e,label:c,type:"select",required:o,nullable:s,defaultValue:a,options:h}}if(u.some(h=>J(h)==="ZodDate"))return {name:e,label:c,type:"datetime-local",required:o,nullable:s,defaultValue:a};let w=u.find(h=>{if(J(h)==="ZodObject"){let b=me(h);return "_latitude"in b&&"_longitude"in b||"latitude"in b&&"longitude"in b}return false});return w?{name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,nested:Re(w,e),hint:"GeoPoint"}:{name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON"}}case "ZodObject":{let u=Re(r,e);return {name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,nested:u,hint:"JSON object"}}case "ZodArray":{let u=un(r);if(!u)return {name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON array"};let{inner:p}=jo(u),f=J(p),w,h,b;switch(f){case "ZodString":w="text";break;case "ZodNumber":case "ZodBigInt":w="number";break;case "ZodBoolean":w="checkbox";break;case "ZodDate":w="datetime-local";break;case "ZodEnum":w="select",h=$t(p);break;case "ZodNativeEnum":w="select",h=Object.values(Ht(p)).filter(T=>typeof T=="string");break;case "ZodObject":w="object",b=Re(p);break;default:return {name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON array"}}return {name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,arrayElementType:w,arrayElementOptions:h,arrayElementFields:b}}default:return {name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON"}}}function Ft(e,t=0){let n=t>0?`ml-${t*4}`:"",r=`field_${e.name.replace(/\./g,"__")}`,o=e.name,s=e.required?" required":"",a=e.defaultValue==="__null__",l=!a&&e.defaultValue!=null?String(e.defaultValue):"",c=e.nullable&&e.type!=="checkbox"?`<span class="flex items-center gap-1 shrink-0">
104
+ Original error: ${t?.message??String(t)}`)}}function mi(e,t){if(!e||!t)return false;for(let[n,r]of Object.entries(t)){if(r===void 0)continue;let o=e[n];if(Array.isArray(r)){if(!Array.isArray(o)||r.length!==o.length)return false;for(let s=0;s<r.length;s++)if(r[s]!==o[s])return false}else if(typeof r=="object"&&r!==null){if(JSON.stringify(r)!==JSON.stringify(o))return false}else if(r!==o)return false}return true}var bn=class{constructor(t){this.name="meilisearch";this._client=null;this.options=t,t.client&&(this._client=t.client);}get indexesSettings(){return this.options.indexesSettings}get client(){return this._client||(this._client=yi(this.options)),this._client}async targetExists(t){try{return await this.client.getIndex(t),!0}catch(n){if(n?.code==="index_not_found"||n?.cause?.code==="index_not_found"||n?.statusCode===404||n?.status===404||n?.response?.status===404||n?.cause?.status===404||n?.cause?.statusCode===404||n?.cause?.response?.status===404)return false;throw n}}async upsert(t,n,r){if(n.length===0)return;let o=this.options.unflatten!==false,s=n.map(l=>{let c=o?Oo(l):l;return typeof this.options.transformDoc=="function"&&(c=this.options.transformDoc(c)),c});await this.client.index(t).addDocuments(s,{primaryKey:r});}async delete(t,n,r){if(r.length===0)return;await this.client.index(t).deleteDocuments(r);}async ensureTarget(t){let{targetName:n,primaryKey:r}=t;await this.targetExists(n)||await this.client.createIndex(n,{primaryKey:r});let s=this.options.indexesSettings?.[n];if(s){let{retrievableAttributes:a,attributesToRetrieve:l,...c}=s,u={...c,displayedAttributes:c.displayedAttributes??a??l};u.displayedAttributes===void 0&&delete u.displayedAttributes;let p=this.client.index(n);if(typeof p.getSettings=="function")try{let f=await p.getSettings();if(mi(f,u))return}catch{}await p.updateSettings(u);}}async healthCheck(t){let{targetName:n}=t;try{if(!await this.targetExists(n))return {healthy:!1,targetName:n,targetExists:!1,error:`Meilisearch index "${n}" does not exist`};let o=this.client.index(n),s=await o.getStats(),a=typeof o.getRawInfo=="function"?await o.getRawInfo():{};return {healthy:!0,targetName:n,targetExists:!0,error:null,details:{numberOfDocuments:s?.numberOfDocuments??0,isIndexing:s?.isIndexing??!1,fieldDistribution:s?.fieldDistribution??{},primaryKey:a?.primaryKey??t.primaryKey}}}catch(r){return {healthy:false,targetName:n,targetExists:false,error:r?.message??String(r)}}}async checkConnection(){try{let t=!0;if(typeof this.client.isHealthy=="function"){let r=await this.client.isHealthy();t=r?.status==="available"||r===!0;}else if(typeof this.client.health=="function"){let r=await this.client.health();t=r?.status==="available"||r===!0;}let n;return typeof this.client.getVersion=="function"&&(n=(await this.client.getVersion())?.pkgVersion),{healthy:t,version:n}}catch(t){return {healthy:false,error:t?.message??String(t)}}}};ft();ft();function hi(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/^\s/,"").replace(/^./,t=>t.toUpperCase())}function qo(e){let t=e,n=true,r=false,o;for(;;){let s=J(t);if(s==="ZodOptional")n=false,t=ye(t);else if(s==="ZodNullable")n=false,r=true,t=ye(t);else if(s==="ZodDefault")n=false,o=Do(t),t=ye(t);else if(s==="ZodEffects"||s==="ZodPipe"||s==="ZodTransform"){let a=$t(t);if(!a)break;t=a;}else break}return {inner:t,required:n,nullable:r,defaultValue:o}}function Re(e,t=""){if(J(e)==="ZodObject"){let r=me(e);return Object.entries(r).map(([o,s])=>Uo(t?`${t}.${o}`:o,o,s))}return [Uo(t||"value",t||"value",e)]}function Uo(e,t,n){let{inner:r,required:o,nullable:s,defaultValue:a}=qo(n),l=J(r),c=hi(t.split(".").pop()??t);switch(l){case "ZodString":{let u=$o(r),p=u.includes("email"),f=u.includes("url");return {name:e,label:c,type:"text",required:o,nullable:s,defaultValue:a,hint:p?"email":f?"url":void 0}}case "ZodNumber":case "ZodBigInt":return {name:e,label:c,type:"number",required:o,nullable:s,defaultValue:a};case "ZodBoolean":return {name:e,label:c,type:"checkbox",required:o,nullable:s,defaultValue:a};case "ZodDate":case "ZodCoerce":return {name:e,label:c,type:"datetime-local",required:o,nullable:s,defaultValue:a};case "ZodEnum":{let u=Ht(r);return {name:e,label:c,type:"select",required:o,nullable:s,defaultValue:a,options:u}}case "ZodNativeEnum":{let u=_t(r),p=Object.values(u).filter(f=>typeof f=="string");return {name:e,label:c,type:"select",required:o,nullable:s,defaultValue:a,options:p}}case "ZodLiteral":{let u=String(Mt(r)??"");return {name:e,label:c,type:"select",required:o,nullable:s,defaultValue:a,options:[u]}}case "ZodUnion":{let u=Ft(r);if(u.length>0&&u.every(h=>J(h)==="ZodLiteral")){let h=u.map(w=>String(Mt(w)??""));return {name:e,label:c,type:"select",required:o,nullable:s,defaultValue:a,options:h}}if(u.some(h=>J(h)==="ZodDate"))return {name:e,label:c,type:"datetime-local",required:o,nullable:s,defaultValue:a};let b=u.find(h=>{if(J(h)==="ZodObject"){let w=me(h);return "_latitude"in w&&"_longitude"in w||"latitude"in w&&"longitude"in w}return false});return b?{name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,nested:Re(b,e),hint:"GeoPoint"}:{name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON"}}case "ZodObject":{let u=Re(r,e);return {name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,nested:u,hint:"JSON object"}}case "ZodArray":{let u=pn(r);if(!u)return {name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON array"};let{inner:p}=qo(u),f=J(p),b,h,w;switch(f){case "ZodString":b="text";break;case "ZodNumber":case "ZodBigInt":b="number";break;case "ZodBoolean":b="checkbox";break;case "ZodDate":b="datetime-local";break;case "ZodEnum":b="select",h=Ht(p);break;case "ZodNativeEnum":b="select",h=Object.values(_t(p)).filter(T=>typeof T=="string");break;case "ZodObject":b="object",w=Re(p);break;default:return {name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON array"}}return {name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,arrayElementType:b,arrayElementOptions:h,arrayElementFields:w}}default:return {name:e,label:c,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON"}}}function jt(e,t=0){let n=t>0?`ml-${t*4}`:"",r=`field_${e.name.replace(/\./g,"__")}`,o=e.name,s=e.required?" required":"",a=e.defaultValue==="__null__",l=!a&&e.defaultValue!=null?String(e.defaultValue):"",c=e.nullable&&e.type!=="checkbox"?`<span class="flex items-center gap-1 shrink-0">
105
105
  <input type="hidden" id="${r}__isnull" name="${o}__isnull" value="${a?"1":""}">
106
106
  <label class="flex items-center gap-1 cursor-pointer select-none text-xs text-base-content/40 hover:text-base-content/70 border border-base-300 rounded px-2 py-1">
107
107
  <input type="checkbox" class="checkbox checkbox-xs" ${a?"checked":""}
@@ -138,7 +138,7 @@ Original error: ${t?.message??String(t)}`)}}function ai(e,t){if(!e||!t)return f
138
138
  ${e.required&&!e.nullable?"":'<option value="">\u2014 optional \u2014</option>'}
139
139
  ${(e.options??[]).map(p=>`<option value="${U(p)}"${l===p?" selected":""}>${U(p)}</option>`).join(`
140
140
  `)}
141
- </select>`;break;case "textarea":if(e.arrayElementType)return ci(e,t);if(e.nested&&e.nested.length>0){let p=e.nested.map(f=>Ft(f,t+1)).join(`
141
+ </select>`;break;case "textarea":if(e.arrayElementType)return gi(e,t);if(e.nested&&e.nested.length>0){let p=e.nested.map(f=>jt(f,t+1)).join(`
142
142
  `);return `
143
143
  <fieldset class="fieldset border border-base-300 rounded-box p-3 mb-3 ${n}">
144
144
  <legend class="fieldset-legend text-xs font-semibold text-base-content/60 px-1">
@@ -162,9 +162,9 @@ Original error: ${t?.message??String(t)}`)}}function ai(e,t){if(!e||!t)return f
162
162
  <div class="flex-1 min-w-0">${u}</div>
163
163
  ${c}
164
164
  </div>
165
- </div>`}function U(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function ci(e,t){let n=t>0?`ml-${t*4}`:"",r=`field_${e.name.replace(/\./g,"__")}`,o=e.defaultValue==="__null__",s=e.arrayElementType==="object",a=[];if(e.defaultValue!=null&&e.defaultValue!==""&&e.defaultValue!=="__null__")try{a=JSON.parse(String(e.defaultValue));}catch{}Array.isArray(a)||(a=[]);let l=s?a.map(p=>qo(e,p??{})).join(`
166
- `):a.map(p=>zo(e,p)).join(`
167
- `),c=s?qo(e,{}):zo(e,""),u=e.nullable?`<span class="flex items-center gap-1 mt-2">
165
+ </div>`}function U(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function gi(e,t){let n=t>0?`ml-${t*4}`:"",r=`field_${e.name.replace(/\./g,"__")}`,o=e.defaultValue==="__null__",s=e.arrayElementType==="object",a=[];if(e.defaultValue!=null&&e.defaultValue!==""&&e.defaultValue!=="__null__")try{a=JSON.parse(String(e.defaultValue));}catch{}Array.isArray(a)||(a=[]);let l=s?a.map(p=>Ko(e,p??{})).join(`
166
+ `):a.map(p=>Lo(e,p)).join(`
167
+ `),c=s?Ko(e,{}):Lo(e,""),u=e.nullable?`<span class="flex items-center gap-1 mt-2">
168
168
  <input type="hidden" id="${r}__isnull" name="${U(e.name)}__isnull" value="${o?"1":""}">
169
169
  <label class="flex items-center gap-1 cursor-pointer select-none text-xs text-base-content/40 hover:text-base-content/70 border border-base-300 rounded px-2 py-1">
170
170
  <input type="checkbox" class="checkbox checkbox-xs" ${o?"checked":""}
@@ -190,7 +190,7 @@ Original error: ${t?.message??String(t)}`)}}function ai(e,t){if(!e||!t)return f
190
190
  <template data-frs-array-tpl>${c}</template>
191
191
  <button type="button" class="btn btn-xs btn-outline mt-1" data-frs-array-add>+ Add</button>
192
192
  ${u}
193
- </fieldset>`}function zo(e,t){let n=t!=null?String(t):"",r;switch(e.arrayElementType){case "select":r=`<select data-frs-val class="select select-bordered select-sm flex-1">
193
+ </fieldset>`}function Lo(e,t){let n=t!=null?String(t):"",r;switch(e.arrayElementType){case "select":r=`<select data-frs-val class="select select-bordered select-sm flex-1">
194
194
  <option value="">\u2014</option>
195
195
  ${(e.arrayElementOptions??[]).map(o=>`<option value="${U(o)}"${n===o?" selected":""}>${U(o)}</option>`).join("")}
196
196
  </select>`;break;case "checkbox":r=`<label class="flex items-center gap-2 flex-1 cursor-pointer">
@@ -199,7 +199,7 @@ Original error: ${t?.message??String(t)}`)}}function ai(e,t){if(!e||!t)return f
199
199
  </label>`;break;case "number":r=`<input type="number" data-frs-val value="${U(n)}" class="input input-bordered input-sm flex-1">`;break;case "datetime-local":r=`<input type="datetime-local" data-frs-val value="${U(n)}" class="input input-bordered input-sm flex-1">`;break;default:r=`<input type="text" data-frs-val value="${U(n)}" class="input input-bordered input-sm flex-1">`;}return `<div class="flex items-center gap-2 mb-2" data-frs-array-item>
200
200
  ${r}
201
201
  <button type="button" class="btn btn-xs btn-ghost text-error" data-frs-array-rm>&times;</button>
202
- </div>`}function qo(e,t){return `<div class="border border-base-200 rounded p-3 mb-2" data-frs-array-item>
202
+ </div>`}function Ko(e,t){return `<div class="border border-base-200 rounded p-3 mb-2" data-frs-array-item>
203
203
  <div class="flex justify-end mb-1">
204
204
  <button type="button" class="btn btn-xs btn-ghost text-error" data-frs-array-rm>&times;</button>
205
205
  </div>
@@ -228,7 +228,7 @@ Original error: ${t?.message??String(t)}`)}}function ai(e,t){if(!e||!t)return f
228
228
  <input type="text" data-frs-key="${U(o.name)}" value="${U(a)}" class="input input-bordered input-sm w-full">
229
229
  </div>`}}).join(`
230
230
  `)}
231
- </div>`}function ze(e,t,n,r="Save"){let o=e.map(s=>Ft(s)).join(`
231
+ </div>`}function ze(e,t,n,r="Save"){let o=e.map(s=>jt(s)).join(`
232
232
  `);return `
233
233
  <form action="${U(t)}" method="${n}" novalidate data-frs-form>
234
234
  ${o}
@@ -236,7 +236,7 @@ Original error: ${t?.message??String(t)}`)}}function ai(e,t){if(!e||!t)return f
236
236
  <button type="submit" class="btn btn-primary btn-sm">${U(r)}</button>
237
237
  <button type="button" class="btn btn-ghost btn-sm" onclick="history.back()">Cancel</button>
238
238
  </div>
239
- </form>`}var li=new Set(["<","<=",">",">=","!="]),di=new Set(["array-contains","array-contains-any"]);function ar(e){return e==="desc"?"DESCENDING":"ASCENDING"}function ui(e){return Me(e).collectionId||e}function pi(e,t,n,r,o){let s=[],a=new Set;for(let c of r)if(c.op==="=="||c.op==="in"||c.op==="not-in"){if(a.has(c.field))continue;a.add(c.field),s.push({fieldPath:c.field,order:"ASCENDING"});}for(let c of r)if(di.has(c.op)){if(a.has(c.field))continue;a.add(c.field),s.push({fieldPath:c.field,arrayConfig:"CONTAINS"});}for(let c of r)if(li.has(c.op)){if(a.has(c.field))continue;a.add(c.field);let u=o?.field===c.field?ar(o.dir):"ASCENDING";s.push({fieldPath:c.field,order:u});}if(o&&!a.has(o.field)&&s.push({fieldPath:o.field,order:ar(o.dir)}),s.length===1&&n)return mi(e,t,s[0]);let l=o&&s.some(c=>c.fieldPath===o.field)?ar(o.dir):"ASCENDING";return s.push({fieldPath:"__name__",order:l}),fi(e,t,n,s)}function fi(e,t,n,r,o="(default)"){let s=`projects/${e}/databases/${o}/collectionGroups/${t}/indexes/_`,a=[...lr(1,s),...bn(2,n?2:1)];for(let u of r)a.push(...Uo(3,Lo(u)));let l=o==="(default)"?"-default-":o,c=encodeURIComponent(Ko(a));return `https://console.firebase.google.com/project/${e}/firestore/databases/${l}/indexes?create_composite=${c}`}function yi(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function ir(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function cr(e,t){return e<<3|t}function lr(e,t){let n=Array.from(new TextEncoder().encode(t));return [cr(e,2),...ir(n.length),...n]}function bn(e,t){return [cr(e,0),...ir(t)]}function Uo(e,t){return [cr(e,2),...ir(t.length),...t]}function Lo(e){let t=[...lr(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...bn(3,1)):t.push(...bn(2,e.order==="DESCENDING"?2:1)),t}function Ko(e){let t=String.fromCharCode(...e),n;if(typeof Buffer<"u")n=Buffer.from(e).toString("base64");else if(typeof btoa<"u")n=btoa(t);else throw new Error("No base64 encoder available");return n.replace(/=+$/,"")}function mi(e,t,n,r="(default)"){let o=`projects/${e}/databases/${r}/collectionGroups/${t}/fields/${n.fieldPath}`,s=[...lr(1,o),...bn(2,2),...Uo(3,Lo(n))],a=r==="(default)"?"-default-":r,l=encodeURIComponent(Ko(s));return `https://console.firebase.google.com/project/${e}/firestore/databases/${a}/indexes/automatic?create_exemption=${l}`}function hi(e){let t=e,n=[t?.firestore?.projectId,t?.firestore?.app?.options?.projectId,t?.firestore?._settings?.projectId,t?.firestore?.databaseId?.projectId,t?._firestore?.projectId];for(let o of n)if(typeof o=="string"&&o.length>0)return o;return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.FIREBASE_PROJECT_ID||void 0}function Ye(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function jt(e,t){let n=e??{},r=Ye(e),o;if(r&&(o=n.message?yi(n.message):void 0,!o)){let s=hi(t.ref);if(s){let a=ui(t.path);o=pi(s,a,t.isGroup,t.filters,t.sort);}}return {type:r?"index":"error",message:r?"This query requires a composite index that does not exist yet.":n.message??"Query failed",indexUrl:o}}wn();var Wo=`// \u2500\u2500 Shared helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
239
+ </form>`}var bi=new Set(["<","<=",">",">=","!="]),wi=new Set(["array-contains","array-contains-any"]);function ir(e){return e==="desc"?"DESCENDING":"ASCENDING"}function xi(e){return _e(e).collectionId||e}function Ri(e,t,n,r,o){let s=[],a=new Set;for(let c of r)if(c.op==="=="||c.op==="in"||c.op==="not-in"){if(a.has(c.field))continue;a.add(c.field),s.push({fieldPath:c.field,order:"ASCENDING"});}for(let c of r)if(wi.has(c.op)){if(a.has(c.field))continue;a.add(c.field),s.push({fieldPath:c.field,arrayConfig:"CONTAINS"});}for(let c of r)if(bi.has(c.op)){if(a.has(c.field))continue;a.add(c.field);let u=o?.field===c.field?ir(o.dir):"ASCENDING";s.push({fieldPath:c.field,order:u});}if(o&&!a.has(o.field)&&s.push({fieldPath:o.field,order:ir(o.dir)}),s.length===1&&n)return Ti(e,t,s[0]);let l=o&&s.some(c=>c.fieldPath===o.field)?ir(o.dir):"ASCENDING";return s.push({fieldPath:"__name__",order:l}),Si(e,t,n,s)}function Si(e,t,n,r,o="(default)"){let s=`projects/${e}/databases/${o}/collectionGroups/${t}/indexes/_`,a=[...dr(1,s),...wn(2,n?2:1)];for(let u of r)a.push(...Zo(3,Wo(u)));let l=o==="(default)"?"-default-":o,c=encodeURIComponent(Qo(a));return `https://console.firebase.google.com/project/${e}/firestore/databases/${l}/indexes?create_composite=${c}`}function vi(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function cr(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function lr(e,t){return e<<3|t}function dr(e,t){let n=Array.from(new TextEncoder().encode(t));return [lr(e,2),...cr(n.length),...n]}function wn(e,t){return [lr(e,0),...cr(t)]}function Zo(e,t){return [lr(e,2),...cr(t.length),...t]}function Wo(e){let t=[...dr(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...wn(3,1)):t.push(...wn(2,e.order==="DESCENDING"?2:1)),t}function Qo(e){let t=String.fromCharCode(...e),n;if(typeof Buffer<"u")n=Buffer.from(e).toString("base64");else if(typeof btoa<"u")n=btoa(t);else throw new Error("No base64 encoder available");return n.replace(/=+$/,"")}function Ti(e,t,n,r="(default)"){let o=`projects/${e}/databases/${r}/collectionGroups/${t}/fields/${n.fieldPath}`,s=[...dr(1,o),...wn(2,2),...Zo(3,Wo(n))],a=r==="(default)"?"-default-":r,l=encodeURIComponent(Qo(s));return `https://console.firebase.google.com/project/${e}/firestore/databases/${a}/indexes/automatic?create_exemption=${l}`}function ki(e){let t=e,n=[t?.firestore?.projectId,t?.firestore?.app?.options?.projectId,t?.firestore?._settings?.projectId,t?.firestore?.databaseId?.projectId,t?._firestore?.projectId];for(let o of n)if(typeof o=="string"&&o.length>0)return o;return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.FIREBASE_PROJECT_ID||void 0}function Xe(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function Bt(e,t){let n=e??{},r=Xe(e),o;if(r&&(o=n.message?vi(n.message):void 0,!o)){let s=ki(t.ref);if(s){let a=xi(t.path);o=Ri(s,a,t.isGroup,t.filters,t.sort);}}return {type:r?"index":"error",message:r?"This query requires a composite index that does not exist yet.":n.message??"Query failed",indexUrl:o}}xn();var Go=`// \u2500\u2500 Shared helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
240
240
  function frsGetBasePath() {
241
241
  var root = document.querySelector("[data-frs-panel-root]");
242
242
  var bp = root && root.getAttribute("data-frs-base-path");
@@ -1158,7 +1158,7 @@ function initColumnReorder(table) {
1158
1158
  });
1159
1159
  });
1160
1160
  }
1161
- `;function Bt(){return jsx("script",{dangerouslySetInnerHTML:{__html:Wo}})}yr();function qe(e){return "<!DOCTYPE html>"+renderToString(e)}var Ai=["corporate","silk","dark"],Ci=()=>jsxs("div",{class:"dropdown dropdown-end","data-frs-theme-switcher":true,children:[jsxs("button",{type:"button",tabIndex:0,class:"btn btn-sm btn-ghost text-neutral-content gap-1.5","aria-label":"Switch theme",children:[jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2",class:"size-4",children:[jsx("circle",{cx:"12",cy:"12",r:"4"}),jsx("path",{d:"M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"})]}),jsx("span",{class:"text-xs hidden sm:inline","data-frs-theme-current":true,children:"Theme"})]}),jsx("ul",{tabIndex:0,class:"dropdown-content menu menu-sm bg-base-100 text-base-content rounded-box z-50 mt-2 w-40 p-1 shadow-lg border border-base-300",children:Ai.map(e=>jsx("li",{children:jsxs("button",{type:"button","data-frs-theme":e,class:"capitalize justify-between",children:[jsx("span",{children:e}),jsx("span",{class:"hidden text-primary","data-frs-theme-check":e,children:"\u2713"})]})},e))})]}),Ue=({opts:e,children:t})=>{let{title:n,breadcrumb:r,flash:o,basePath:s="/"}=e;return jsxs("html",{lang:"en","data-theme":"corporate",children:[jsxs("head",{children:[jsx("meta",{charset:"UTF-8"}),jsx("meta",{name:"viewport",content:"width=device-width, initial-scale=1"}),jsxs("title",{children:[n," \u2014 FRS Admin"]}),jsx("script",{dangerouslySetInnerHTML:{__html:"(function(){try{var t=localStorage.getItem('frs-admin-theme');if(t){document.documentElement.setAttribute('data-theme',t);}}catch(_){}})();"}}),jsx("link",{href:"https://cdn.jsdelivr.net/npm/daisyui@5/themes.css",rel:"stylesheet",type:"text/css"}),jsx("link",{href:"https://cdn.jsdelivr.net/npm/daisyui@5/daisyui.css",rel:"stylesheet",type:"text/css"}),jsx("script",{src:"https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"})]}),jsxs("body",{class:"bg-base-200/50 min-h-screen flex flex-col",children:[jsxs("div",{class:"navbar bg-neutral text-neutral-content shadow-sm sticky top-0 z-50 px-6",children:[jsx("div",{class:"flex-1",children:jsx("a",{href:s,class:"font-bold text-lg tracking-tight hover:opacity-80 transition-opacity",children:"FRS Admin"})}),jsx("div",{class:"flex-none",children:jsx(Ci,{})})]}),jsxs("main",{class:"px-6 py-8 w-full flex-1",children:[r&&r.length>0&&jsx("div",{class:"text-sm breadcrumbs mb-4",children:jsx("ul",{children:r.map((a,l)=>a.href?jsx("li",{children:jsx("a",{href:a.href,children:a.label})},l):jsx("li",{class:"text-base-content/60",children:a.label},l))})}),jsx("h1",{class:"text-2xl font-bold mb-6",children:n}),o&&jsxs("div",{role:"alert",class:`alert ${o.type==="success"?"alert-success":o.type==="warning"?"alert-warning":"alert-error"} mb-6`,children:[jsx("span",{class:"flex-1",children:o.message}),o.action&&jsx("a",{href:o.action.href,...o.action.external?{target:"_blank",rel:"noopener noreferrer"}:{},class:"btn btn-sm btn-outline",children:o.action.label})]}),t]}),jsx(fr,{basePath:s}),jsx(Bt,{})]})]})};function mr(e,t){return qe(jsx(Ue,{opts:t,children:jsx("div",{dangerouslySetInnerHTML:{__html:e}})}))}function hr(e,t){return qe(jsx(Ue,{opts:{title:"Repositories",basePath:t},children:e.length===0?jsxs("div",{class:"text-center py-20 text-base-content/50",children:[jsx("p",{class:"text-lg font-medium mb-1",children:"No repositories configured"}),jsx("p",{class:"text-sm",children:"Add a repository to your FRS config to get started."})]}):jsx("div",{class:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:e.map(n=>jsx("a",{href:`${t}/${n.name}`,class:"card bg-base-100 border border-base-300 hover:shadow-md no-underline transition-shadow",children:jsxs("div",{class:"card-body p-5",children:[jsx("h2",{class:"card-title text-sm font-semibold",children:n.name}),jsx("p",{class:"text-xs text-base-content/50 font-mono",children:n.path})]})},n.name))})}))}var Jo=[{value:"==",label:"="},{value:"!=",label:"\u2260"},{value:"in",label:"in"},{value:"not-in",label:"not in"}],Ei=[{value:"==",label:"="},{value:"!=",label:"\u2260"},{value:"<",label:"<"},{value:"<=",label:"\u2264"},{value:">",label:">"},{value:">=",label:"\u2265"},{value:"in",label:"in"},{value:"not-in",label:"not in"}],Oi=[{value:"array-contains",label:"contains"},{value:"array-contains-any",label:"contains any"}];function Pi(e){switch(e){case "ZodNumber":case "ZodBigInt":case "ZodDate":return Ei;case "ZodBoolean":return Jo;case "ZodArray":return Oi;default:return Jo}}var Le="__null__";function Ii(e){return `(function(cb){var i=document.getElementById('${e}');if(!i)return;if(cb.checked){i.dataset._prev=i.value;if(i.tagName==='SELECT'){var o=i.querySelector('option[value="${Le}"]');if(!o){o=document.createElement('option');o.value='${Le}';o.textContent='\u2205 null';o.dataset._auto='1';i.appendChild(o);}o.selected=true;}else{if(i.type==='number'||i.type==='datetime-local'){i.dataset._type=i.type;i.type='text';}i.value='${Le}';i.readOnly=true;}i.style.opacity='0.55';}else{i.style.opacity='';if(i.tagName==='SELECT'){var o2=i.querySelector('option[value="${Le}"][data-_auto="1"]');if(o2)o2.remove();var prev=i.dataset._prev||'';for(var k=0;k<i.options.length;k++)i.options[k].selected=(i.options[k].value===prev);}else{if(i.dataset._type){i.type=i.dataset._type;delete i.dataset._type;}i.readOnly=false;i.value=(i.dataset._prev&&i.dataset._prev!=='${Le}')?i.dataset._prev:'';}}})(this)`}function Di(e,t){return `(function(){var h=document.getElementById('${e}');var boxes=document.querySelectorAll('input[data-enum-group="${t}"]');h.value=Array.from(boxes).filter(function(b){return b.checked;}).map(function(b){return b.value;}).join(',');})()`}function Lt({inputId:e,active:t}){return jsxs("label",{class:"flex items-center gap-1 cursor-pointer select-none text-xs text-base-content/60 hover:text-base-content border border-base-300 rounded-md px-1.5 py-1 shrink-0 leading-none h-8",title:"Filter where field IS NULL",children:[jsx("input",{type:"checkbox",class:"checkbox checkbox-xs",checked:t,onchange:Ii(e)}),jsx("span",{children:"\u2205"})]})}function $i({col:e,active:t}){let n=t?.value??"",r=n===Le,o=`fv_input_${e.name.replace(/\./g,"__")}`,s=t?.op,a=s==="in"||s==="not-in";if(e.enumValues&&e.enumValues.length>0){if(a){let l=new Set(n.split(",").map(u=>u.trim()).filter(Boolean)),c=`eg_${e.name.replace(/\./g,"__")}`;return jsxs("div",{class:"flex flex-wrap items-center gap-1 w-full",children:[jsx("input",{type:"hidden",id:o,name:`fv_${e.name}`,value:n}),e.enumValues.map(u=>jsxs("label",{class:"flex items-center gap-1 text-xs border border-base-300 rounded px-2 cursor-pointer hover:bg-base-200",children:[jsx("input",{type:"checkbox",class:"checkbox checkbox-xs",value:u,checked:l.has(u),"data-enum-group":c,onchange:Di(o,c)}),jsx("span",{children:u})]},u))]})}return jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxs("select",{id:o,name:`fv_${e.name}`,class:"select select-sm select-bordered w-full",style:r?"opacity:0.55":void 0,children:[jsx("option",{value:"",selected:n===""&&!r,children:"\u2014"}),e.enumValues.map(l=>jsx("option",{value:l,selected:n===l,children:l},l)),e.nullable&&jsx("option",{value:Le,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsx(Lt,{inputId:o,active:r})]})}if(e.zodType==="ZodBoolean")return jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxs("select",{id:o,name:`fv_${e.name}`,class:"select select-sm select-bordered w-full",style:r?"opacity:0.55":void 0,children:[jsx("option",{value:"",selected:n===""&&!r,children:"\u2014"}),jsx("option",{value:"true",selected:n==="true",children:"true"}),jsx("option",{value:"false",selected:n==="false",children:"false"}),e.nullable&&jsx("option",{value:Le,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsx(Lt,{inputId:o,active:r})]});if(e.zodType==="ZodArray"){let l=t?.op==="array-contains-any";return jsx("input",{id:o,type:"text",name:`fv_${e.name}`,value:n,placeholder:l?"val1, val2, \u2026":"value",class:"input input-sm input-bordered w-full"})}return e.zodType==="ZodNumber"||e.zodType==="ZodBigInt"?jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsx("input",{id:o,type:r?"text":"number",name:`fv_${e.name}`,value:n,placeholder:"value",class:"input input-sm input-bordered w-full",readOnly:r||void 0,style:r?"opacity:0.55":void 0,"data-_type":r?"number":void 0}),e.nullable&&jsx(Lt,{inputId:o,active:r})]}):e.zodType==="ZodDate"?jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsx("input",{id:o,type:r?"text":"datetime-local",name:`fv_${e.name}`,value:n,class:"input input-sm input-bordered w-full",readOnly:r||void 0,style:r?"opacity:0.55":void 0,"data-_type":r?"datetime-local":void 0}),e.nullable&&jsx(Lt,{inputId:o,active:r})]}):jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsx("input",{id:o,type:"text",name:`fv_${e.name}`,value:n,placeholder:"value",class:"input input-sm input-bordered w-full",readOnly:r||void 0,style:r?"opacity:0.55":void 0}),e.nullable&&jsx(Lt,{inputId:o,active:r})]})}function gr({action:e,columnMeta:t,activeFilters:n,isGroup:r}){let o=Object.fromEntries(n.map(c=>[c.field,c])),s=n.length>0,a=n.length>=2||r&&s,l=t.filter(c=>c.zodType!=="ZodObject"&&c.zodType!=="ZodRecord");return jsxs("details",{class:"collapse collapse-arrow bg-base-100 border border-base-300 rounded-box mb-6 shadow-sm",open:s?true:void 0,children:[jsxs("summary",{class:"collapse-title text-sm font-medium py-2 min-h-0",children:["Filters",s&&jsxs("span",{class:"badge badge-primary badge-sm ml-2",children:[n.length," active"]})]}),jsx("div",{class:"collapse-content pb-4 pt-2",children:jsxs("form",{method:"get",action:e,children:[jsx("div",{class:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:l.map(c=>{let u=Pi(c.zodType),p=o[c.name],f=p?.op??u[0].value;return jsxs("div",{class:"flex flex-col gap-1.5",children:[jsx("label",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:c.name}),jsxs("div",{class:"flex gap-1.5",children:[u.length>1?jsx("select",{name:`fo_${c.name}`,class:"select select-sm select-bordered w-20 shrink-0",children:u.map(w=>jsx("option",{value:w.value,selected:w.value===f,children:w.label},w.value))}):jsx("input",{type:"hidden",name:`fo_${c.name}`,value:u[0].value}),jsx($i,{col:c,active:p})]})]},c.name)})}),jsxs("div",{class:"flex flex-wrap gap-2 mt-4 pt-3 border-t border-base-200 items-center",children:[jsx("button",{type:"submit",class:"btn btn-sm btn-primary",children:"Apply"}),s&&jsx("a",{href:e,class:"btn btn-sm btn-ghost",children:"Clear"}),a&&jsxs("span",{class:"text-xs text-warning ml-auto flex items-center gap-1",children:[jsx("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-4 w-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:jsx("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),r?"Collection group queries require a composite index":"Multiple filters may require a composite index"]})]})]})})]})}function br(e,t,n,r,o,s){let a=n==="create"?`Create ${e}`:`Edit ${e} / ${r??""}`,l=n==="create"?[{label:"Repositories",href:o},{label:e,href:`${o}/${e}`},{label:"New document"}]:[{label:"Repositories",href:o},{label:e,href:`${o}/${e}`},{label:`Edit ${r??""}`}];return qe(jsx(Ue,{opts:{title:a,breadcrumb:l,basePath:o,flash:s},children:jsx("div",{class:"card bg-base-100 border border-base-300",children:jsx("div",{class:"card-body p-6",children:jsx("div",{dangerouslySetInnerHTML:{__html:t}})})})}))}wn();pr();function wr(e,t,n){let r=new URLSearchParams;for(let o of e)r.set(`fv_${o.field}`,o.value),r.set(`fo_${o.field}`,o.op);return t&&(r.set("ob",t.field),r.set("od",t.dir)),n&&r.set("ps",String(n)),r}function Yo(e,t,n,r,o){let s=wr(e,r,o);return s.set("cursor",t),s.set("dir",n),`?${s.toString()}`}function Hi(e,t,n,r){let o=wr(n,void 0,r);return t?.field===e?t.dir==="asc"&&(o.set("ob",e),o.set("od","desc")):(o.set("ob",e),o.set("od","asc")),`?${o.toString()}`}function Mi(e,t,n){return `?${wr(t,n,e).toString()}`}function xr(e,t,n,r,o,s,a=[],l=[],c=false,u=[],p,f,w,h,b,T,S,I=false,C=true){let O=`${r}/${e}`,x=`${O}/create`,d={};if(S)for(let R of n)d[R]=zt(qt(S,R));let y=(T??[]).filter(R=>true),i=y.length>0,g=c,m=g||i,A=y.map(R=>{let P=qt(S,R),M=zt(P),$=a.find(_=>_.name===R);return {name:R,type:M,enumValues:$?.enumValues??null,nullable:$?.nullable??false}}),k=[];return S&&(k=Re(S).filter(P=>y.includes(P.name))),qe(jsxs(Ue,{opts:{title:e,breadcrumb:[{label:"Repositories",href:r},{label:e}],basePath:r,flash:s},children:[a.length>0&&jsx(gr,{action:O,columnMeta:a,activeFilters:l,isGroup:h}),w&&jsxs("div",{role:"alert",class:`alert ${w.type==="index"?"alert-warning":"alert-error"} mb-6 shadow-sm`,children:[jsx("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-6 w-6 shrink-0 stroke-current",fill:"none",viewBox:"0 0 24 24",children:w.type==="index"?jsx("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"}):jsx("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"})}),jsxs("div",{class:"flex-1",children:[jsx("h3",{class:"font-bold",children:w.type==="index"?"Composite index required":"Query failed"}),jsx("div",{class:"text-sm",children:w.message})]}),w.indexUrl&&jsx("a",{href:w.indexUrl,target:"_blank",rel:"noopener noreferrer",class:"btn btn-sm btn-outline",children:"Create Index \u2192"})]}),jsxs("div",{class:"flex flex-wrap justify-between items-center mb-4 gap-3","data-frs-toolbar":true,children:[jsxs("div",{class:"flex items-center gap-3",children:[jsxs("span",{class:"text-sm text-base-content/60",children:[t.length,typeof b=="number"&&jsxs(Fragment,{children:[" ","of"," ",jsx("span",{class:"font-semibold text-base-content/80",children:b})]})," ","document",(typeof b=="number"?b:t.length)!==1&&"s"]}),jsxs("div",{class:"flex items-center gap-1.5 text-sm text-base-content/60",children:[jsx("span",{children:"Rows"}),jsx("div",{class:"join",children:[10,25,50,100].map(R=>jsx("a",{href:Mi(R,l,p),class:`join-item btn btn-xs ${f===R?"btn-active btn-primary":"btn-outline"}`,children:R},R))})]})]}),jsxs("div",{class:"flex gap-2",children:[C&&jsxs("div",{class:"dropdown dropdown-end","data-frs-backfill-menu":true,children:[jsxs("button",{type:"button",tabIndex:0,class:"btn btn-outline btn-sm gap-1",children:["Backfill",jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",class:"size-4 opacity-70",children:jsx("path",{"fill-rule":"evenodd",d:"M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z","clip-rule":"evenodd"})})]}),jsxs("ul",{tabIndex:0,class:"dropdown-content menu menu-sm bg-base-100 text-base-content rounded-box z-50 mt-1 w-52 p-1 shadow-lg border border-base-300",children:[jsx("li",{children:jsxs("form",{method:"post",action:`${O}/_bulk/backfill?dryRun=true`,class:"p-0 block",children:[jsx("input",{type:"hidden",name:"dryRun",value:"1"}),jsx("button",{type:"submit",class:"w-full text-left px-3 py-1.5 rounded",children:"Dry-run backfill"})]})}),jsx("li",{children:jsx("form",{method:"post",action:`${O}/_bulk/backfill`,onsubmit:"return confirm('Backfill entire repository? This will scan all documents and fill missing system keys.')",class:"p-0 block",children:jsx("button",{type:"submit",class:"w-full text-left px-3 py-1.5 rounded text-warning",children:"Run backfill"})})})]})]}),jsx("a",{href:x,class:"btn btn-primary btn-sm",children:"+ New"})]})]}),m&&jsxs("div",{class:"hidden mb-3 alert alert-info py-2 px-3","data-frs-bulk-bar":true,"data-frs-repo":e,"data-frs-total":typeof b=="number"?String(b):"","data-frs-page-size":String(f??t.length),"data-frs-allow-delete":g?"1":"0","data-frs-allow-update":i?"1":"0","data-frs-fields":JSON.stringify(A),"data-frs-filters":JSON.stringify(l),children:[jsxs("div",{class:"flex-1 text-sm",children:[jsx("span",{"data-frs-bulk-summary":true,children:"0 selected"}),typeof b=="number"&&b>t.length&&jsxs("button",{type:"button",class:"ml-3 link text-sm hidden","data-frs-bulk-select-all":true,children:["Select all ",b," matching documents"]}),jsxs("span",{class:"hidden ml-3 italic","data-frs-bulk-all-active":true,children:["All ",b??"?"," matching documents are selected."," ",jsx("button",{type:"button",class:"link","data-frs-bulk-clear":true,children:"Clear selection"})]})]}),jsxs("div",{class:"flex gap-2",children:[i&&jsx("button",{type:"button",class:"btn btn-sm btn-outline","data-frs-bulk-action":"update",children:"Update field\u2026"}),g&&jsx("button",{type:"button",class:"btn btn-sm btn-error btn-outline","data-frs-bulk-action":"delete",children:"Delete"})]})]}),jsx("div",{class:"overflow-x-auto rounded-box border border-base-300 bg-base-100","data-frs-table-wrap":true,children:jsxs("table",{class:"table table-sm w-full","data-frs-table":true,"data-frs-repo":e,"data-frs-colcount":n.length,children:[jsx("thead",{children:jsxs("tr",{class:"bg-base-200/50",children:[m&&jsx("th",{class:"w-8",children:jsx("input",{type:"checkbox",class:"checkbox checkbox-xs checkbox-primary","data-frs-select-page":true,"aria-label":"Select all on this page"})}),[...n].map((R,P)=>{let M=p?.field===R,$=M?p.dir==="asc"?" \u25B2":" \u25BC":"";return jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:jsxs("a",{href:Hi(R,p,l,f),class:`hover:text-base-content inline-flex items-center gap-0.5${M?" text-primary font-bold":""}`,children:[R,$]})},P)}),u.map((R,P)=>jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:R.column},`rel-${P}`)),jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide text-right",children:"Actions"})]})}),jsx("tbody",{children:t.length===0?jsx("tr",{children:jsx("td",{colspan:n.length+u.length+1+(m?1:0),class:"text-center py-16 text-base-content/40",children:"No documents found"})}):t.map((R,P)=>{let M=String(R.docId??R.id??""),$=`${r}/${e}/${encodeURIComponent(M)}/edit`,_=`${r}/${e}/${encodeURIComponent(M)}/delete`;return jsxs("tr",{class:"hover","data-frs-row-id":M,children:[m&&jsx("td",{class:"align-middle py-2",children:jsx("input",{type:"checkbox",class:"checkbox checkbox-xs checkbox-primary","data-frs-select-row":true,value:M,"aria-label":`Select ${M}`})}),n.map((v,E)=>{let N=R[v],H=d[v],D=H?Ut(H,N):null;return jsx("td",{class:"align-top py-2",children:jsx(yt,{val:N,mismatch:D})},E)}),u.map((v,E)=>{let N=R[v.key];if(N==null||N==="")return jsx("td",{class:"py-2"},`rel-${E}`);let H=v.type==="one"?`${r}/${v.targetRepo}/${encodeURIComponent(String(N))}/edit`:`${r}/${v.targetRepo}?fv_${v.targetKey}=${encodeURIComponent(String(N))}`;return jsx("td",{class:"align-middle py-2",children:jsx("a",{href:H,class:"btn btn-xs btn-ghost btn-outline","data-frs-relation":true,"data-frs-rel-type":v.type,"data-frs-rel-repo":v.targetRepo,"data-frs-rel-fk":v.targetKey,"data-frs-rel-val":String(N),"data-frs-rel-label":v.column,children:v.column})},`rel-${E}`)}),jsx("td",{class:"align-middle text-right whitespace-nowrap py-2",children:jsxs("div",{class:"flex gap-1 justify-end",children:[jsx("a",{href:$,class:"btn btn-xs btn-outline",children:"Edit"}),I&&jsx("a",{href:`${r}/${e}/${encodeURIComponent(M)}/history`,class:"btn btn-xs btn-outline",title:"View change history",children:"History"}),c&&jsx("form",{method:"post",action:_,onsubmit:"return confirm('Delete this document?')",children:jsx("button",{type:"submit",class:"btn btn-xs btn-error btn-outline",children:"Delete"})})]})})]},P)})})]})}),(o.hasPrev||o.hasNext)&&jsxs("div",{class:"flex flex-col items-center mt-6 gap-2",children:[jsxs("div",{class:"flex justify-center items-center gap-2",children:[o.hasPrev?jsx("a",{href:Yo(l,o.prevCursor,"prev",p,f),class:"btn btn-sm btn-outline",children:"\u2190 Previous"}):jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"\u2190 Previous"}),o.hasNext?jsx("a",{href:Yo(l,o.nextCursor,"next",p,f),class:"btn btn-sm btn-outline",children:"Next \u2192"}):jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"Next \u2192"})]}),typeof b=="number"&&jsxs("div",{class:"text-xs text-base-content/50",children:[b," total document",b!==1?"s":"",l.length>0?" matching filters":""]})]}),m&&i&&jsxs("dialog",{id:"frs-bulk-update-modal",class:"modal",children:[jsxs("div",{class:"modal-box",children:[jsx("h3",{class:"font-bold text-lg mb-3",children:"Bulk update field"}),jsx("p",{class:"text-sm text-base-content/60 mb-4","data-frs-bulk-update-summary":true,children:"Update one field on the selected documents."}),jsxs("form",{method:"dialog","data-frs-bulk-update-form":true,"data-frs-form":true,children:[jsxs("label",{class:"form-control w-full mb-3",children:[jsx("div",{class:"label",children:jsx("span",{class:"label-text text-xs uppercase tracking-wide",children:"Field"})}),jsxs("select",{class:"select select-bordered select-sm w-full",name:"field",required:true,"data-frs-bulk-field-select":true,children:[jsx("option",{value:"",children:"\u2014 Select a field \u2014"}),y.map(R=>jsx("option",{value:R,children:R},R))]})]}),jsx("div",{class:"mb-4","data-frs-bulk-value-container":true}),jsxs("div",{class:"modal-action",children:[jsx("button",{type:"button",class:"btn btn-sm btn-ghost","data-frs-bulk-update-cancel":true,children:"Cancel"}),jsx("button",{type:"submit",class:"btn btn-sm btn-primary","data-frs-bulk-update-submit":true,children:"Apply"})]})]})]}),jsx("form",{method:"dialog",class:"modal-backdrop",children:jsx("button",{children:"close"})})]}),jsx("div",{class:"hidden","data-frs-bulk-templates":true,children:k.map(R=>jsx("div",{"data-frs-bulk-template-for":R.name,dangerouslySetInnerHTML:{__html:Ft(R)}},R.name))})]}))}function Kt(e,t){return mr(e,t)}function Rr(e,t){return hr(e,t)}function Sr(e,t,n,r,o,s,a,l,c,u,p,f,w,h,b,T,S,I,C){return xr(e,t,n,r,o,s,a,l,c,u,p,f,w,h,b,T,S,I,C)}function Ke(e,t,n,r,o,s){return br(e,t,n,r,o,s)}async function Xo(e,t){if(t)try{let n=e.repo.ref,r=n?.firestore;if(t.startsWith("{"))try{let o=JSON.parse(t);if(o.docPath&&r&&typeof r.doc=="function"){let s=await r.doc(o.docPath).get();if(s.exists)return s}o.docId&&(t=o.docId);}catch{}if(t.includes("/")&&r&&typeof r.doc=="function"){let o=await r.doc(t).get();if(o.exists)return o}if(typeof n.doc=="function"){let o=await n.doc(t).get();if(o.exists)return o}}catch{}}function Rn(e,t){return Ge(e,{pathKey:t.pathKey,documentKey:t.documentKey??"docId",parentKeys:t.parentKeys,documentPathTemplate:t.documentPathTemplate,isGroup:t.isGroup})}async function mt(e,t){let n=e.documentKey??"docId",r=`by${n.charAt(0).toUpperCase()}${n.slice(1)}`;if(typeof e.repo.get[r]=="function")try{let s=await e.repo.get[r](t);if(s)return s}catch{}return (await e.repo.query.by({where:[[n,"==",t]],limit:1}))[0]??null}function vr(e,t,n){let r=e.documentKey??"docId",o=jt(n,{ref:e.repo.ref,path:e.path,isGroup:!!e.isGroup,filters:[{field:r,op:"==",value:t}]});return o.type==="index"?{type:"warning",message:"Loading this document requires a composite index that does not exist yet.",...o.indexUrl?{action:{href:o.indexUrl,label:"Create Index \u2192",external:true}}:{}}:{type:"error",message:o.message}}function L(e,t,n=200){e.status(n).set("Content-Type","text/html; charset=utf-8").send(t);}function et(e,t){e.status(302).set("Location",t).send("");}function Sn(e,t){let n=t.shape,r={};for(let[o,s]of Object.entries(n)){let a=Ar(s),l=J(a),c=l==="ZodObject",u=a,p=false;if(l==="ZodUnion"){let h=_t(a);h.some(T=>J(T)==="ZodDate")&&(p=true);let b=h.find(T=>{if(J(T)==="ZodObject"){let S=me(T);return "latitude"in S&&"longitude"in S}return false});b&&(c=true,u=b);}if(e[o+"__isnull"]==="1"){r[o]=null;continue}if(c){let h={},b=false;for(let[I,C]of Object.entries(e))I.startsWith(`${o}.`)&&(h[I.slice(o.length+1)]=C,b=true);if(b){r[o]=Sn(h,u);continue}let T=e[o],S=Array.isArray(T)?T[T.length-1]:T;if(S)try{r[o]=JSON.parse(S);}catch{r[o]=S;}continue}let f=e[o],w=Array.isArray(f)?f[f.length-1]:f;if(w===void 0||w===""){l==="ZodBoolean"&&(r[o]=false);continue}if(p){r[o]=new Date(w);continue}switch(l){case "ZodBoolean":w==="__null__"?r[o]=null:r[o]=w==="true"||w==="on"||w==="1";break;case "ZodNumber":case "ZodBigInt":r[o]=Number(w);break;case "ZodDate":r[o]=new Date(w);break;case "ZodArray":try{r[o]=JSON.parse(w);}catch{r[o]=w;}break;default:if(w.startsWith("{")||w.startsWith("["))try{r[o]=JSON.parse(w);break}catch{}r[o]=w;}}return r}function es(e){let t=null;if(e instanceof Date)t=e;else if(typeof e=="object"&&e!==null&&typeof e.toDate=="function")t=e.toDate();else if(typeof e=="object"&&e!==null&&"_seconds"in e&&"_nanoseconds"in e)t=new Date(e._seconds*1e3+Math.floor(e._nanoseconds/1e6));else if(typeof e=="string"||typeof e=="number"){let r=new Date(e);isNaN(r.getTime())||(t=r);}if(!t||isNaN(t.getTime()))return null;let n=r=>String(r).padStart(2,"0");return `${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`}function ns(e){let t=e;for(;;){let n=J(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=ye(t);else if(n==="ZodEffects"||n==="ZodPipe"||n==="ZodTransform"){let r=Dt(t);if(!r)return n;t=r;}else return n}}function Ar(e){let t=e;for(;;){let n=J(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=ye(t);else if(n==="ZodEffects"||n==="ZodPipe"||n==="ZodTransform"){let r=Dt(t);if(!r)return t;t=r;}else return t}}function rs(e){let t=e;for(;;){let n=J(t);if(n==="ZodOptional"||n==="ZodNullable")return true;if(n==="ZodDefault"){t=ye(t);continue}return false}}function os(e){let t=Ar(e),n=J(t);if(n==="ZodEnum"){let r=$t(t);return r.length>0?r:void 0}if(n==="ZodNativeEnum"){let r=Ht(t),o=Object.values(r).filter(s=>typeof s=="string");return o.length>0?o:void 0}if(n==="ZodLiteral"){let r=Mt(t);return typeof r=="string"?[r]:void 0}}function ss(e,t,n=""){let r={};for(let o of Object.keys(t.shape)){let s=n?`${n}.${o}`:o,a=e[o];if(a===null){r[s]="__null__";continue}if(a===void 0)continue;let l=Ar(t.shape[o]),c=J(l),u=c==="ZodObject",p=l,f=false;if(c==="ZodUnion"){let w=_t(l);w.some(b=>J(b)==="ZodDate")&&(f=true);let h=w.find(b=>{if(J(b)==="ZodObject"){let T=me(b);return "latitude"in T&&"longitude"in T}return false});h&&(u=true,p=h);}if(u&&typeof a=="object"&&a!==null&&!Array.isArray(a)&&!("_seconds"in a)&&typeof a.toDate!="function"){let w=ss(a,p,s);Object.assign(r,w);}else if(c==="ZodDate"||f){let w=es(a);w!==null&&(r[s]=w);}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)&&("_seconds"in a||typeof a.toDate=="function")){let w=es(a);r[s]=w??JSON.stringify(a,null,2);}else typeof a=="object"?r[s]=JSON.stringify(a,null,2):r[s]=String(a);}return r}function kr(e,t){return e.map(n=>({...n,defaultValue:t[n.name]??n.defaultValue,nested:n.nested?kr(n.nested,t):void 0}))}function Fi(e,t){let n=new Set(["==","!=","<","<=",">",">=","in","not-in","array-contains","array-contains-any"]),r=[];for(let[o,s]of Object.entries(e)){if(!o.startsWith("fv_"))continue;let a=o.slice(3);if(!t.has(a))continue;let l=(s??"").trim();if(!l)continue;let c=e[`fo_${a}`]??"==",u=n.has(c)?c:"==";r.push({field:a,op:u,value:l});}return r}function ts(e){let t="__null__",n=r=>r===t?null:r==="true"?true:r==="false"?false:r!==""&&!isNaN(Number(r))?Number(r):r;return e.map(r=>{if(r.op==="array-contains-any"||r.op==="in"||r.op==="not-in"){let o=r.value.split(",").map(s=>s.trim()).filter(s=>s!==""&&s!==t).map(s=>n(s));return [r.field,r.op,o]}return [r.field,r.op,n(r.value)]})}function as(e,t,n=""){let r=[];for(let o of e){let s=n?`${n}.${o}`:o,a=t.shape[o];if(!a){r.push({name:s,zodType:"ZodString"});continue}let l=ns(a);if(l==="ZodObject"){let c=a;for(;;){let p=J(c);if(p==="ZodOptional"||p==="ZodNullable"||p==="ZodDefault")c=ye(c);else break}let u=me(c);r.push(...as(Object.keys(u),c,s));}else r.push({name:s,zodType:l,nullable:rs(a),enumValues:os(a)});}return r}function ji(e,t){let n=t.split("."),r=e;for(let o of n){for(;;){let a=J(r);if(a==="ZodOptional"||a==="ZodNullable"||a==="ZodDefault")r=ye(r);else break}let s=me(r);if(!(o in s))return null;r=s[o];}return r}function tt(e,t){if(!t||t.length===0)return e;let n=[],r=new Map;for(let s of t){let a=s.indexOf(".");if(a===-1)n.push(s);else {let l=s.slice(0,a),c=s.slice(a+1);r.has(l)||r.set(l,[]),r.get(l).push(c);}}let o={};for(let s of n)s in e.shape&&(o[s]=e.shape[s]);for(let[s,a]of r){if(!(s in e.shape))continue;let l=e.shape[s];for(;;){let c=J(l);if(c==="ZodOptional"||c==="ZodNullable"||c==="ZodDefault")l=ye(l);else break}if(J(l)!=="ZodObject"){o[s]=e.shape[s];continue}o[s]=tt(l,a);}return z.object(o)}function Oe(e,t,n){return Ee(e,t,n)}function is(e,t,n){let r=new Set,o=(x,d)=>{let y=Oe(x,t,n),i=Object.values(e).map(g=>({name:g.name,path:g.path}));L(d,Rr(i,y));},s=async(x,d)=>{let y=x.params.repoName;if(!y){L(d,"Bad request",400);return}let i=e[y];if(!i){L(d,"Repository not found",404);return}let g=i.pageSize??25,m=x.query??{},A=m.cursor,k=m.dir==="prev"?"prev":"next",R=m.ob??"",P=m.od==="desc"?"desc":"asc",M=R?{field:R,dir:P}:void 0,$=parseInt(m.ps??""),_=Number.isFinite($)&&$>0?Math.min($,200):g,v=i.listColumns??Object.keys(i.schema.shape),E=i.documentKey??"docId",N=[E,...v.filter(re=>re!==E)];M&&(new Set([E,...v]).has(M.field)||(M=void 0));let H=i.filterableFields?(()=>{let re=[];for(let ie of i.filterableFields)(ie.includes(".")||v.includes(ie))&&re.push(ie);return re})():v,D=(()=>{let re=[];for(let ie of H)if(ie.includes(".")){let fe=ji(i.schema,ie);re.push({name:ie,zodType:fe?ns(fe):"ZodString",nullable:fe?rs(fe):false,enumValues:fe?os(fe):void 0});}else re.push(...as([ie],i.schema));return re})(),F=new Set(D.map(re=>re.name)),j=Fi(m,F),z=ts(j),te;A&&(te=await Xo(i,A));let[K,De]=await Promise.all([i.repo.query.paginate({pageSize:_,cursor:te,direction:k,...z.length>0?{where:z}:{},...M?{orderBy:[{field:M.field,direction:M.dir}]}:{}}).catch(re=>({queryError:jt(re,{ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:j,sort:M})})),i.repo.aggregate.count(z.length>0?{where:z}:{}).catch(()=>{})]),Se="queryError"in K,W=Se?[]:K.data,X=Se?"":K.nextCursor?.ref?.path??K.nextCursor?.id??"",oe=Se?"":K.prevCursor?.ref?.path??K.prevCursor?.id??"",se=Se?K.queryError:void 0,we=Oe(x,t,n),ne,be=m.flash;if(be==="created")ne={type:"success",message:"Document created successfully."};else if(be==="updated")ne={type:"success",message:"Document updated successfully."};else if(be==="deleted")ne={type:"success",message:"Document deleted successfully."};else if(be==="backfilled"){let re=Pe(m.scanned),ie=Pe(m.written),fe=Pe(m.skipped);ne={type:"success",message:re!==void 0&&ie!==void 0&&fe!==void 0?`Backfill complete: scanned ${re}, updated ${ie}, skipped ${fe}.`:"Repository backfilled successfully."};}else if(be==="backfill_dryrun"){let re=Pe(m.scanned),ie=Pe(m.written),fe=Pe(m.skipped);ne={type:"success",message:re!==void 0&&ie!==void 0&&fe!==void 0?`Dry run complete: scanned ${re}, would update ${ie}, skipped ${fe}.`:"Dry run complete."};}else if(be==="backfill_partial"){let re=Pe(m.scanned),ie=Pe(m.written),fe=Pe(m.skipped),$n=Pe(m.failed),js=re!==void 0&&ie!==void 0&&fe!==void 0&&$n!==void 0;ne={type:ie!==void 0&&ie>0?"warning":"error",message:js?`Backfill finished with ${$n} failure${$n===1?"":"s"} (scanned ${re}, updated ${ie}, skipped ${fe}). Check server logs for details.`:"Backfill finished with failures. Check server logs for details."};}else be==="backfill_busy"&&(ne={type:"warning",message:"A backfill is already running for this repository. Please wait for it to finish."});L(d,Sr(i.name,W,N,we,{hasPrev:Se?false:K.hasPrevPage,hasNext:Se?false:K.hasNextPage,prevCursor:oe,nextCursor:X},ne,D,j,i.allowDelete??false,i.relationalMeta,M,_,se,i.isGroup,De,i.mutableFields,i.schema,i.historyEnabled,i.allowBackfill!==false));},a=(x,d)=>{let y=x.params.repoName;if(!y){L(d,"Bad request",400);return}let i=e[y];if(!i){L(d,"Repository not found",404);return}let g=Oe(x,t,n),m=tt(i.schema,i.createFields),A=Re(m),k=`${g}/${i.name}/create`,R=ze(A,k,"POST","Create document");L(d,Ke(i.name,R,"create",null,g));},l=async(x,d)=>{let y=x.params.repoName;if(!y){L(d,"Bad request",400);return}let i=e[y];if(!i){L(d,"Repository not found",404);return}let g=Oe(x,t,n),m=x.body??{},A=Sn(m,i.schema),k=tt(i.schema,i.createFields),R=k.safeParse(A);if(!R.success){let P=Re(k),M=`${g}/${i.name}/create`,$=ze(P,M,"POST","Create document"),_=R.error.issues.map(v=>`${v.path.join(".")}: ${v.message}`).join(", ");L(d,Ke(i.name,$,"create",null,g,{type:"error",message:`Validation error: ${_}`}),422);return}try{if(i.isGroup&&i.parentKeys&&i.parentKeys.length>0){let P={...R.data},M=i.parentKeys.filter($=>P[$]===void 0||P[$]===null||typeof P[$]=="string"&&P[$].trim()==="");if(M.length>0)throw new Error(`Missing parent key(s) for subcollection create: ${M.join(", ")}`);if(typeof i.repo.create=="function")await i.repo.create(P);else {let $=i.parentKeys.map(E=>String(P[E])),_=i.documentKey??"docId",v=P[_]||Be();await i.repo.set(...$,v,P);}}else await i.repo.create(R.data);et(d,`${g}/${i.name}?flash=created`);}catch(P){let M=tt(i.schema,i.createFields),$=Re(M),_=`${g}/${i.name}/create`,v=ze($,_,"POST","Create document");L(d,Ke(i.name,v,"create",null,g,{type:"error",message:`Save error: ${P.message}`}),500);}},c=async(x,d)=>{let y=x.params.repoName,i=x.params.id;if(!y||!i){L(d,"Bad request",400);return}let g=e[y];if(!g){L(d,"Repository not found",404);return}let m=Oe(x,t,n),A=null;try{A=await mt(g,i);}catch(_){let v=vr(g,i,_),E=Ye(_)?424:500;L(d,Kt("",{title:`Edit ${g.name} / ${i}`,basePath:m,breadcrumb:[{label:"Repositories",href:m},{label:g.name,href:`${m}/${g.name}`},{label:`Edit ${i}`}],flash:v}),E);return}if(!A){L(d,"Document not found",404);return}let k=ss(A,g.schema),R=tt(g.schema,g.mutableFields),P=kr(Re(R),k),M=`${m}/${g.name}/${encodeURIComponent(i)}/edit`,$=ze(P,M,"POST","Save changes");L(d,Ke(g.name,$,"edit",i,m));},u=async(x,d)=>{let y=x.params.repoName,i=x.params.id;if(!y||!i){L(d,"Bad request",400);return}let g=e[y];if(!g){L(d,"Repository not found",404);return}let m=Oe(x,t,n),A=x.body??{},k=Sn(A,g.schema),R=tt(g.schema,g.mutableFields),M=R.partial().safeParse(k);if(!M.success){let $=Object.fromEntries(Object.entries(A).map(([H,D])=>[H,Array.isArray(D)?D.join(","):D??""])),_=kr(Re(R),$),v=`${m}/${g.name}/${encodeURIComponent(i)}/edit`,E=ze(_,v,"POST","Save changes"),N=M.error.issues.map(H=>`${H.path.join(".")}: ${H.message}`).join(", ");L(d,Ke(g.name,E,"edit",i,m,{type:"error",message:`Validation error: ${N}`}),422);return}try{let $=await mt(g,i),_=($&&Rn($,g))??[i];await g.repo.update(..._,M.data),et(d,`${m}/${g.name}?flash=updated`);}catch($){let _=tt(g.schema,g.mutableFields),v=Re(_),E=`${m}/${g.name}/${encodeURIComponent(i)}/edit`,N=ze(v,E,"POST","Save changes"),H=Ye($)?vr(g,i,$):{type:"error",message:`Save error: ${$.message}`},D=Ye($)?424:500;L(d,Ke(g.name,N,"edit",i,m,H),D);}},p=async(x,d)=>{let y=x.params.repoName,i=x.params.id;if(!y||!i){L(d,"Bad request",400);return}let g=e[y];if(!g){L(d,"Repository not found",404);return}if(!g.allowDelete){L(d,"Delete is not allowed for this repository",403);return}let m=Oe(x,t,n);try{let A=await mt(g,i),k=(A&&Rn(A,g))??[i];await g.repo.delete(...k),et(d,`${m}/${g.name}?flash=deleted`);}catch(A){let k=Ye(A)?vr(g,i,A):{type:"error",message:`Delete error: ${A.message}`},R=Ye(A)?424:500;L(d,Kt("",{title:`Delete ${g.name} / ${i}`,basePath:m,breadcrumb:[{label:"Repositories",href:m},{label:g.name,href:`${m}/${g.name}`},{label:`Delete ${i}`}],flash:k}),R);}},f=async(x,d)=>{let y=x.params.repoName;if(!y){L(d,"Bad request",400);return}let i=e[y];if(!i){L(d,"Repository not found",404);return}let g=Oe(x,t,n),m=x.query,A=m?.type==="many"?"many":"one",k=Math.max(1,Math.min(100,Number(m?.ps??25)||25)),R=i.listColumns??Object.keys(me(i.schema)),{PanelOne:P,PanelMany:M}=await Promise.resolve().then(()=>(yr(),Vo)),{renderToString:$}=await import('hono/jsx/dom/server');if(A==="one"){let D=String(m?.id??"");if(!D){L(d,"<div class='p-6 text-error'>Missing id parameter.</div>",400);return}try{let F=await mt(i,D),j=$(P({doc:F,repoName:i.name,basePath:g,schema:i.schema,columns:R}));L(d,j);}catch(F){L(d,`<div class='p-6 text-error text-sm'>Error: ${F.message}</div>`,500);}return}let _=String(m?.fk??""),v=String(m?.fv??"");if(!_||!v){L(d,"<div class='p-6 text-error'>Missing fk/fv parameters.</div>",400);return}let E=m?.cursor??"",N=m?.dir==="prev"?"prev":"next",H;E&&(H=await Xo(i,E));try{let D=await i.repo.query.paginate({pageSize:k,cursor:H,direction:N,where:[[_,"==",Ui(v)]]}),F=$(M({docs:D.data,repoName:i.name,basePath:g,fk:_,fv:v,columns:R,schema:i.schema,pagination:{hasPrev:D.hasPrevPage,hasNext:D.hasNextPage,prevCursor:D.prevCursor?.ref?.path??D.prevCursor?.id??"",nextCursor:D.nextCursor?.ref?.path??D.nextCursor?.id??"",pageSize:k}}));L(d,F);}catch(D){L(d,`<div class='p-6 text-error text-sm'>Error: ${D.message}</div>`,500);}},w=async(x,d)=>{let y=zi(x),i=x.params.repoName;if(!i){y?ae(d,{error:"Bad request"},400):L(d,"Bad request",400);return}let g=e[i];if(!g){y?ae(d,{error:"Repository not found"},404):L(d,"Repository not found",404);return}if(g.allowBackfill===false){let k="Backfill is not allowed for this repository";y?ae(d,{error:k},403):L(d,k,403);return}let m=Oe(x,t,n);if(r.has(i)){y?ae(d,{error:`Backfill is already running for "${i}"`},409):et(d,`${m}/${g.name}?flash=backfill_busy`);return}let A=qi(x);r.add(i);try{let k=await g.repo.system.backfillKeys({dryRun:A}),R=k?.scanned??0,P=k?.written??0,M=k?.skipped??0,$=Array.isArray(k?.failures)?k.failures:[];if($.length>0&&console.error(`[admin] Backfill for "${i}" finished with ${$.length} failure(s) (scanned=${R}, written=${P}, skipped=${M}):`,$.map(v=>({path:v.path,error:Tr(v.error)}))),y){let v=$.length===0?200:P>0?207:500;ae(d,{dryRun:A,scanned:R,written:P,skipped:M,failures:$.map(E=>({path:E.path,error:Tr(E.error)}))},v);return}let _=new URLSearchParams({scanned:String(R),written:String(P),skipped:String(M)});$.length>0?(_.set("failed",String($.length)),et(d,`${m}/${g.name}?flash=backfill_partial&${_.toString()}`)):A?et(d,`${m}/${g.name}?flash=backfill_dryrun&${_.toString()}`):et(d,`${m}/${g.name}?flash=backfilled&${_.toString()}`);}catch(k){let R=Tr(k);console.error(`[admin] Backfill failed for "${i}":`,k),y?ae(d,{error:R},500):L(d,`<div class="p-6 text-error">Backfill failed: ${Bi(R)}</div>`,500);}finally{r.delete(i);}},h=async(x,d)=>{let y=[];for(let i of d){let g;if(x.isGroup||x.parentKeys?.length){let m=await mt(x,i);g=m?Rn(m,x):void 0;}g||(g=[i]);try{let m=x.repo.documentRef(...g);m&&y.push(m);}catch{}}return y},b=async(x,d)=>{let y=ts(d),i=x.documentKey??"docId",g=[],m;for(;;){let A=await x.repo.query.paginate({pageSize:500,cursor:m,direction:"next",...y.length>0?{where:y}:{}});for(let k of A.data){let R=String(k[i]??k.id??"");R&&g.push(R);}if(!A.hasNextPage||!A.nextCursor)break;m=A.nextCursor;}return g},T=async(x,d)=>{let y=x.params.repoName;if(!y){ae(d,{error:"Bad request"},400);return}let i=e[y];if(!i){ae(d,{error:"Repository not found"},404);return}if(!i.allowDelete){ae(d,{error:"Delete is not allowed for this repository"},403);return}let g=x.body??{};try{let m=await I(i,g);if(m.length===0){ae(d,{deleted:0});return}let A=await h(i,m);for(let k=0;k<A.length;k+=500)await i.repo.bulk.delete(A.slice(k,k+500));ae(d,{deleted:A.length});}catch(m){ae(d,{error:m.message},500);}},S=async(x,d)=>{let y=x.params.repoName;if(!y){ae(d,{error:"Bad request"},400);return}let i=e[y];if(!i){ae(d,{error:"Repository not found"},404);return}let g=x.body??{},m=String(g.field??"");if(!m){ae(d,{error:"Missing 'field'"},400);return}if(!i.mutableFields||!i.mutableFields.includes(m)){ae(d,{error:`Field '${m}' is not bulk-updatable`},403);return}let A=i.schema.shape?.[m],k;if(A){let R=typeof i.schema=="object"&&i.schema&&"constructor"in i.schema&&i.schema.constructor.name.includes("Zod")?i.schema.pick({[m]:true}):void 0;if(!R){ae(d,{error:"Invalid schema structure"},500);return}k=Sn(g.formPayload??{},R)[m];let M=A.safeParse(k);if(!M.success){ae(d,{error:`Invalid value for '${m}': ${M.error.message}`},400);return}k=M.data;}try{let R=await I(i,g);if(R.length===0){ae(d,{updated:0});return}let M=(await h(i,R)).map($=>({docRef:$,data:{[m]:k}}));for(let $=0;$<M.length;$+=500)await i.repo.bulk.update(M.slice($,$+500));ae(d,{updated:M.length});}catch(R){ae(d,{error:R.message},500);}};async function I(x,d){if(d.selectAll){let y=C(d.filters,x);return await b(x,y)}return Array.isArray(d.ids)?d.ids.filter(y=>typeof y=="string"&&!!y):[]}function C(x,d){if(!Array.isArray(x))return [];let y=new Set((d.filterableFields??Object.keys(me(d.schema))).map(m=>String(m))),i=new Set(["==","!=","<","<=",">",">=","in","not-in","array-contains","array-contains-any"]),g=[];for(let m of x)m&&typeof m=="object"&&typeof m.field=="string"&&y.has(m.field)&&typeof m.value=="string"&&i.has(String(m.op))&&g.push({field:m.field,op:m.op,value:m.value});return g}return {handleDashboard:o,handleList:s,handleCreateForm:a,handleCreateSubmit:l,handleEditForm:c,handleEditSubmit:u,handleDelete:p,handlePanel:f,handleBulkDelete:T,handleBulkUpdate:S,handleBulkBackfill:w,handleHistory:async(x,d)=>{let y=x.params.repoName,i=x.params.id;if(!y||!i){L(d,"Bad request",400);return}let g=e[y];if(!g){L(d,"Repository not found",404);return}if(!g.historyEnabled||!g.repo.history){L(d,"History not enabled for this repository",404);return}let m=Oe(x,t,n),A=g.historySubcollection??"history",k=[i];try{let D=await mt(g,i),F=D?Rn(D,g):void 0;F&&F.length>0&&(k=F);}catch{}let R=parseInt(String(x.query?.limit??"")),P=Number.isFinite(R)&&R>0?Math.min(R,500):100,M=[],$;try{M=await g.repo.history.list(...k,{limit:P});}catch(D){$=D.message;}let _=D=>String(D??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),v=D=>{if(D===void 0)return '<span class="opacity-40">undefined</span>';if(D===null)return '<span class="opacity-40">null</span>';if(typeof D=="object")try{return `<code class="text-xs">${_(JSON.stringify(D))}</code>`}catch{return _(String(D))}return _(String(D))},E=D=>D?typeof D.toDate=="function"?D.toDate().toISOString():D instanceof Date?D.toISOString():_(String(D)):"",N=D=>`<span class="badge badge-sm ${D==="create"?"badge-success":D==="delete"?"badge-error":D==="custom"?"badge-secondary":"badge-info"}">${_(D)}</span>`,H="";if(H+='<div class="flex items-center justify-between mb-4">',H+=`<a href="${m}/${g.name}/${encodeURIComponent(i)}/edit" class="btn btn-sm btn-outline">\u2190 Back to edit</a>`,H+=`<a href="${m}/${g.name}" class="btn btn-sm btn-outline">\u2190 Back to list</a>`,H+="</div>",H+=`<p class="text-sm text-base-content/60 mb-4">Subcollection: <code>${_(A)}</code> \xB7 Showing up to ${P} entries.</p>`,$)H+=`<div class="alert alert-error mb-4">${_($)}</div>`;else if(M.length===0)H+='<div class="alert">No history entries found.</div>';else {H+='<div class="overflow-x-auto"><table class="table table-zebra table-sm">',H+="<thead><tr><th>When</th><th>Op</th><th>User</th><th>Reason / Comment</th><th>Changes</th></tr></thead><tbody>";for(let D of M){let F=D.meta??{},j=[F.reason,F.comment].filter(K=>K!=null&&K!=="").map(K=>_(String(K))).join(" \u2014 "),z="",te=Object.keys(D.changes??{});if(D.custom){let K=`<strong>${_(D.custom.title)}</strong>`,De=D.custom.key?` <code class="text-xs opacity-60">${_(D.custom.key)}</code>`:"",Se=D.custom.description?`<div class="text-xs opacity-80 mt-0.5">${_(D.custom.description)}</div>`:"";z=`<div>${K}${De}${Se}</div>`;}else te.length===0?z='<span class="opacity-40">\u2014</span>':z='<ul class="space-y-1">'+te.map(K=>{let De=D.changes[K];return `<li><strong>${_(K)}</strong>: ${v(De.oldValue)} \u2192 ${v(De.newValue)}</li>`}).join("")+"</ul>";H+="<tr>",H+=`<td class="whitespace-nowrap text-xs font-mono">${_(E(D.historySetAt))}</td>`,H+=`<td>${N(D.operation??"update")}</td>`,H+=`<td class="text-xs">${_(F.userEmail??F.userId??"")}</td>`,H+=`<td class="text-xs">${j}</td>`,H+=`<td>${z}</td>`,H+="</tr>";}H+="</tbody></table></div>";}L(d,Kt(H,{title:`History \u2014 ${g.name} / ${i}`,basePath:m,breadcrumb:[{label:"Repositories",href:m},{label:g.name,href:`${m}/${g.name}`},{label:`History ${i}`}]}));}}}function ae(e,t,n=200){e.status(n).set("Content-Type","application/json; charset=utf-8").send(JSON.stringify(t));}function Bi(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Tr(e){return e instanceof Error||e&&typeof e=="object"&&typeof e.message=="string"?e.message:String(e)}function zi(e){let t=e.headers??{},n="",r="";for(let[o,s]of Object.entries(t)){let a=o.toLowerCase(),l=Array.isArray(s)?s.join(","):String(s??"");a==="accept"?n=l.toLowerCase():a==="content-type"&&(r=l.toLowerCase());}return n.includes("application/json")||r.includes("application/json")}function ht(e){if(e===true||e===1)return true;if(typeof e=="string"){let t=e.trim().toLowerCase();return t==="true"||t==="1"}return Array.isArray(e)&&e.length>0?ht(e[e.length-1]):false}function qi(e){let t=e.query??{};if(t.dryRun!==void 0)return ht(t.dryRun);if(typeof e.url=="string"){let r=e.url.indexOf("?");if(r!==-1){let s=new URLSearchParams(e.url.slice(r+1)).get("dryRun");if(s!==null)return ht(s)}}let n=e.body;if(n&&typeof n=="object"&&!Array.isArray(n)){let r=n.dryRun;if(r!==void 0)return ht(r)}else if(typeof n=="string"&&n.trim()!==""){let r=n.trim();if(r.startsWith("{"))try{let o=JSON.parse(r);if(o&&typeof o=="object"&&!Array.isArray(o)){let s=o.dryRun;if(s!==void 0)return ht(s)}}catch{}else {let s=new URLSearchParams(r).get("dryRun");if(s!==null)return ht(s)}}return false}function Pe(e){if(e===void 0||e==="")return;let t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}function Ui(e){return e==="true"?true:e==="false"?false:e!==""&&!isNaN(Number(e))?Number(e):e}Tn();async function us(e){return typeof e.rawBody=="string"?e.rawBody:Buffer.isBuffer(e.rawBody)?e.rawBody.toString("utf8"):""}function Li(e){let t={};if(!e)return t;for(let n of e.split("&")){let r=n.indexOf("=");if(r===-1)continue;let o=decodeURIComponent(n.slice(0,r).replace(/\+/g," ")),s=decodeURIComponent(n.slice(r+1).replace(/\+/g," ")),a=t[o];a===void 0?t[o]=s:Array.isArray(a)?a.push(s):t[o]=[a,s];}return t}function ps(e){let{basePath:t="/",repos:n,parseBody:r=true,securityHeaders:o,auth:s,middleware:a=[],httpsOptions:l}=e,c=t==="/"?"":t.replace(/\/$/,""),u={};for(let[h,b]of Object.entries(n)){if(!b.repo)throw new Error(`[createAdminServer] Repository "${h}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let T=b.schema??b.repo.schema??null;if(!T)throw new Error(`[createAdminServer] Repository "${h}" has no Zod schema. Either use createRepositoryConfig(schema)(config) or pass schema: explicitly.`);let S,I,C;if(b.fieldsConfig){let d=b.fieldsConfig;S=[],I=[],C=[];for(let[y,i]of Object.entries(d))for(let g of i)g==="filterable"?S.push(y):g==="mutable"?I.push(y):g==="create"&&C.push(y);S.length===0&&(S=void 0),I.length===0&&(I=void 0),C.length===0&&(C=void 0);}let O=(()=>{let d=b.repo._parentKeys;return d&&d.length>0?d:void 0})();if(O&&C)for(let d of O)C.includes(d)||C.push(d);let x={name:h,path:b.path,repo:b.repo,schema:T,documentKey:b.documentKey??"docId",pathKey:b.repo._pathKey??void 0,isGroup:!!b.repo._isGroup,parentKeys:O,documentPathTemplate:b.repo._documentPathTemplate??void 0,createdKey:b.repo._createdKey??void 0,listColumns:b.listColumns,pageSize:b.pageSize,filterableFields:S,mutableFields:I,createFields:C,allowDelete:b.allowDelete??false,allowBackfill:b.allowBackfill??true,historyEnabled:!!b.repo._historyConfig?.enabled,historySubcollection:(b.repo._historyConfig?.enabled&&b.repo._historySubcollection)??void 0,relationalMeta:(()=>{if(!b.relationalFields||b.relationalFields.length===0)return;let d=b.repo.relationalKeys??{},y=[];for(let i of b.relationalFields){let g=d[i.key];g&&y.push({key:g.sourceKey?String(g.sourceKey):i.key,column:i.column,targetRepo:String(g.repo),targetKey:String(g.key),type:g.type});}return y.length>0?y:void 0})()};u[h]=x;}let p=is(u,c,dn(l?.region)),f=new _e;if(o!==false&&f.use(vn(o===void 0?{}:o)),r&&f.use(async(h,b,T)=>{let S=h,I="";if(S.headers){for(let[C,O]of Object.entries(S.headers))if(C.toLowerCase()==="content-type"){I=(Array.isArray(O)?O.join(","):String(O??"")).toLowerCase();break}}if(I.includes("application/x-www-form-urlencoded")){let C=await us(S)||(typeof S.body=="string"?S.body:"");(C!==""||!S.body||typeof S.body!="object")&&(h.body=Li(C));}else if(I.includes("application/json")){let C=typeof S.body=="string"?S.body:S.body===void 0?await us(S):"";if(C)try{h.body=JSON.parse(C);}catch{}}await T();}),s)if(Ot(s)){for(let h of s.routes){let b=`${c}${h.path}`;h.method==="GET"?f.get(b,h.handler):f.post(b,h.handler);}f.use(s.middleware);}else if(typeof s=="function")f.use(s);else {let h=s.realm??"Admin",b="Basic "+Buffer.from(`${s.username}:${s.password}`).toString("base64");f.use((T,S,I)=>{if((T.headers?.authorization??"")!==b){S.status(401).set("WWW-Authenticate",`Basic realm="${h}"`).set("Content-Type","text/plain").send("Unauthorized");return}I();});}for(let h of a)f.use(h);f.get(`${c}/`,p.handleDashboard),f.get(`${c}`,p.handleDashboard),f.get(`${c}/:repoName/_panel`,p.handlePanel),f.post(`${c}/:repoName/_bulk/delete`,p.handleBulkDelete),f.post(`${c}/:repoName/_bulk/update`,p.handleBulkUpdate),f.post(`${c}/:repoName/_bulk/backfill`,p.handleBulkBackfill),f.get(`${c}/:repoName`,p.handleList),f.get(`${c}/:repoName/create`,p.handleCreateForm),f.post(`${c}/:repoName/create`,p.handleCreateSubmit),f.get(`${c}/:repoName/:id/edit`,p.handleEditForm),f.post(`${c}/:repoName/:id/edit`,p.handleEditSubmit),f.get(`${c}/:repoName/:id/history`,p.handleHistory),f.post(`${c}/:repoName/:id/delete`,p.handleDelete);let w=async(h,b)=>{await f.handle(h,b);};return l&&(w.httpsOptions=l),w}ut();function Te(e,t){let n=e||{},r={},o={...n};for(let[s,a]of Object.entries(t||{})){let l=n[s];At(l,a)||(r[s]=a,o[s]=a);}return {before:n,after:o,changes:r}}function Er(e){return e}async function kn(e,t,n){let r=e.changes||{};for(let o of Object.keys(r)){let s=t[o];if(s&&s.length>0){for(let a of s)if(await a.rule({diff:e,key:o,user:n,authenticatedUser:n})===false)return {allowed:false,reason:a.description}}}return {allowed:true}}function Or(e){return async t=>kn(t.diff,e,t.user)}var Pr=1e3;function fs(e,t){if(e===void 0)return {success:true,value:Math.min(Math.max(1,t),Pr)};let n=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):NaN;return !Number.isInteger(n)||n<=0||n>Pr?{success:false,error:`Invalid pageSize: must be an integer between 1 and ${Pr}`}:{success:true,value:n}}function $r(e,t,n=200){let r=ce(t);return e.json(r,n)}function nt(e,t,n,r=200){return $r(e,{success:true,data:t,meta:n},r)}function q(e,t,n=400){return $r(e,{success:false,error:t},n)}async function Ir(e,t,n,r,o,s){let a=jt(t,n),l=a.type==="index",c=l?424:500,p={success:false,error:l?a.message:o&&t instanceof Error?t.message:r};if(l&&(p.errorType="index",a.indexUrl&&(p.indexUrl=a.indexUrl,s)))try{let f=s({indexUrl:a.indexUrl,repoName:n.repoName??"",path:n.path,isGroup:n.isGroup,filters:n.filters,sort:n.sort,error:t,c:e});f instanceof Promise&&await f;}catch(f){o&&console.error("[crudServer] Error in indexesError callback:",f);}return $r(e,p,c)}function rt(e){let t=e._def??e.def;if(!t)return e;let n=t.typeName??t.type;if(n==="ZodDate"||n==="date")return z.preprocess(r=>Bn(r)??r,e);if(n==="ZodObject"||n==="object"){let r=e.shape,o={};for(let[s,a]of Object.entries(r))o[s]=rt(a);return z.object(o)}if(n==="ZodArray"||n==="array"){let r=t.element??t.type;if(r)return z.array(rt(r))}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(r)return rt(r).optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(r)return rt(r).nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType,o=t.defaultValue;if(r){let s=rt(r);return typeof o=="function"?s.default(o()):s.default(o)}}return e}function Ki(e,t,n=[]){let r=e.shape,o={},s=t&&t.length>0?t:Object.keys(r);for(let a of s){if(n.includes(a))continue;let l=a.split(".")[0];l&&r[l]&&(o[l]=r[l]);}return z.object(o)}function Dr(e){let t=e;for(;t;){let n=t._zod?.def??t._def;if(!n)break;if(n.innerType)t=n.innerType;else if(n.schema)t=n.schema;else if(n.type==="optional"||n.type==="nullable"||n.type==="default"||n.type==="catch"||n.type==="effects")t=n.innerType??n.schema;else break}return t}function hs(e,t){let n=t.split("."),r=Dr(e);for(let o=0;o<n.length;o++){let s=n[o];if(!s)continue;let a=r?.shape;if(!a||!a[s])return;let l=a[s];if(o===n.length-1)return l;r=Dr(l);}return r}function ot(e){let t=e?._zod?.def??e?._def,n=t?.typeName??t?.type;if(n==="ZodObject"||n==="object"){let r=e.shape,o={};for(let[s,a]of Object.entries(r))o[s]=ot(a);return z.object(o).partial()}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(!r)return e;let o=ot(r);return o===r?e:o.optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(!r)return e;let o=ot(r);return o===r?e:o.nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType;return r?ot(r).optional():e}if(n==="ZodUnion"||n==="union"){let r=t.options;if(!r||r.length<2)return e;let o=r.map(a=>ot(a));return o.some((a,l)=>a!==r[l])?z.union(o):e}return e}function An(e,t,n,r=false,o=[]){if(typeof t!="object"||t===null||Array.isArray(t))return {success:false,error:"Data payload must be an object"};try{let s=t,a={},l={};for(let[c,u]of Object.entries(s))if(c.includes(".")){let p=c.split(".")[0];if(o.includes(c)||o.includes(p))continue;if(n&&n.length>0&&!n.includes(c)&&!n.includes(p))return {success:!1,error:`Field '${c}' is not allowed for this operation`};let f=hs(e,c);if(!f)return {success:!1,error:`Field '${c}' does not exist in schema`};let w=r?ot(f):f,b=(tn()==="normalize"?rt(w):w).parse(u);a[c]=b;}else l[c]=u;if(Object.keys(l).length>0||Object.keys(a).length===0){let c=Ki(e,n,o),u=r?ot(c):c,f=(tn()==="normalize"?rt(u):u).parse(l);Object.assign(a,f);}return {success:!0,data:a}}catch(s){return s instanceof z.ZodError?{success:false,error:`Validation failed: ${s.issues.map(l=>`${l.path.join(".")}: ${l.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}var gs={eq:"==","==":"==",ne:"!=","!=":"!=",lt:"<","<":"<",lte:"<=","<=":"<=",gt:">",">":">",gte:">=",">=":">=",in:"in",nin:"not-in","not-in":"not-in",not_in:"not-in",contains:"array-contains","array-contains":"array-contains",array_contains:"array-contains",arrayContains:"array-contains",containsAny:"array-contains-any","array-contains-any":"array-contains-any",array_contains_any:"array-contains-any",arrayContainsAny:"array-contains-any"};function Zt(e){return gs[e]??e}function Zi(e){return e in gs}function Cn(e,t,n,r){let o=hs(e,t);if(!o||typeof o.safeParse!="function")return {success:true,data:n};let s=r?Zt(r):void 0,a=Dr(o),l=un(a);if(s==="array-contains"){let p=l??o;if(typeof p.safeParse=="function"){let f=p.safeParse(n);return f.success?{success:true,data:f.data}:{success:false,error:f.error.issues.map(h=>h.message).join(", ")}}return {success:true,data:n}}if(s==="array-contains-any"){if(!Array.isArray(n))return {success:false,error:"Expected array value for array-contains-any"};let p=l??o,f=[];for(let w of n)if(typeof p.safeParse=="function"){let h=p.safeParse(w);if(h.success)f.push(h.data);else return {success:false,error:h.error.issues.map(T=>T.message).join(", ")}}else f.push(w);return {success:true,data:f}}let c=o.safeParse(n);if(c.success)return {success:true,data:c.data};if(Array.isArray(n)){let p=l??o,f=[];for(let w of n)if(typeof p.safeParse=="function"){let h=p.safeParse(w);if(h.success)f.push(h.data);else return {success:false,error:h.error.issues.map(T=>T.message).join(", ")}}else f.push(w);return {success:true,data:f}}return {success:false,error:c.error.issues.map(p=>p.message).join(", ")}}function Wi(e,t){let n=[],r=t?new Set(t):null;for(let[o,s]of Object.entries(e)){if(s===void 0||["cursor","direction","limit","pageSize","orderBy","orderDir","select","includes","withTotal"].includes(o))continue;let a=Array.isArray(s)?s[0]:s;if(a===void 0||a==="")continue;let l=o.lastIndexOf("__"),c,u="==";if(l!==-1){let f=o.slice(0,l),w=o.slice(l+2);Zi(w)?(c=f,u=Zt(w)):(c=o,u="==");}else c=o;if(r&&!r.has(c))continue;let p=a;u==="in"||u==="not-in"||u==="array-contains-any"?p=a.split(",").map(f=>ys(f.trim())):p=ys(a),n.push({field:c,op:u,value:p});}return n}function ys(e){if(e==="true")return true;if(e==="false")return false;if(e==="null"||e==="__null__")return null;let t=Number(e);return !isNaN(t)&&e!==""?t:e}function En(e){return e?{docId:e.id,docPath:e.ref?.path??void 0}:null}async function ms(e,t){if(!t)return;let n;if(typeof t=="string")try{n=JSON.parse(t);}catch{n=t.includes("/")?{docPath:t}:{docId:t};}else typeof t=="object"&&(n=t);if(!n)return;let r=typeof n.docPath=="string"?n.docPath:void 0,o=typeof n.docId=="string"?n.docId:void 0;try{let s=e.repo.ref,a=s?.firestore;if(r&&a&&typeof a.doc=="function"){let l=await a.doc(r).get();if(l.exists)return l}if(o&&o.includes("/")&&a&&typeof a.doc=="function"){let l=await a.doc(o).get();if(l.exists)return l}if(o&&typeof s.doc=="function"){let l=await s.doc(o).get();if(l.exists)return l}return}catch{return}}function On(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t={},n=0;for(let[r,o]of Object.entries(e))o!==void 0&&(t[r]=o,n++);return n>0?t:null}function bs(e,t,n,r,o){async function s(x,d,y,i){let g=false;if(x.hooks?.onAfterError){g=true;try{let m=x.hooks.onAfterError(i,y.hook);m instanceof Promise&&await m;}catch(m){console.error("[crudServer] Error in hooks.onAfterError callback:",m);}}if(o){g=true;try{let m=o({...y,error:i});m instanceof Promise&&await m;}catch(m){console.error("[crudServer] Error in onHookError callback:",m);}}if(!g){if(d&&typeof d.error=="function"){d.error(i,{hook:y.hook,repoName:y.repoName,path:y.path,...y.id!==void 0?{id:y.id}:{},...y.pathArgs!==void 0?{pathArgs:y.pathArgs}:{}});return}console.error(`[crudServer] Hook "${y.hook}" failed on repo "${y.repoName}":`,{hook:y.hook,repoName:y.repoName,path:y.path,...y.id!==void 0?{id:y.id}:{},...y.pathArgs!==void 0?{pathArgs:y.pathArgs}:{},error:i});}}async function a(x,d,y,i){if(!d.rules)return {allowed:true};let g=d.rules?.[y];if(!g)return {allowed:false,errorResponse:q(x,`Operation "${y}" is not allowed for this repository`,403)};try{let m=await g(i);return m===!1?{allowed:!1,errorResponse:q(x,"Forbidden",403)}:typeof m=="string"?{allowed:!1,errorResponse:q(x,m,403)}:typeof m=="object"&&m!==null&&!m.allowed?{allowed:!1,errorResponse:q(x,m.reason||"Forbidden",403)}:{allowed:!0}}catch(m){let A=n&&m instanceof Error?m.message:"Forbidden";return {allowed:false,errorResponse:q(x,A,403)}}}async function l(x,d,y,i){if(!x.rules)return i;let g=x.rules?.filter;if(!g)return i;let m=[];for(let A of i)try{await g({user:d,doc:A,params:y})&&m.push(A);}catch{}return m}function c(x){return x.get("user")??x.get("docsUser")??null}function u(x,d){if(!x){let y=d.req.path.split("/");for(let i of y)if(e[i]){x=i;break}}return !x||!e[x]?null:e[x]??null}function p(x,d){return Ge(x,{pathKey:d.pathKey,documentKey:d.documentKey,parentKeys:d.parentKeys,documentPathTemplate:d.documentPathTemplate,isGroup:d.isGroup})}async function f(x,d){let y=`by${x.documentKey.charAt(0).toUpperCase()}${x.documentKey.slice(1)}`,i=x.repo.get[y];if(typeof i=="function")try{let m=await i(d);if(m)return m}catch{}return (await x.repo.query.by({where:[[x.documentKey,"==",d]],limit:1}))[0]??null}async function w(x){let d=x.c,y=d.req.param(),i=u(y.repoName,d);if(!i)return q(d,"Repository not found",404);let g=c(d),m=await a(d,i,"list",{user:g,query:d.req.query(),params:y});if(!m.allowed)return m.errorResponse;let A=[],k;try{let R=d.req.query(),P=fs(R.pageSize,i.pageSize);if(!P.success)return q(d,P.error,400);let M=P.value,$=R.cursor,_=R.direction?.toLowerCase()==="prev"?"prev":"next",v=R.orderBy,E=R.orderDir?.toLowerCase()==="desc"?"desc":"asc",N=R.select,H=N?N.split(",").map(W=>W.trim()):void 0,D=R.withTotal,F=D==="true"||D==="1"||D===!0,j;i.allowedIncludes&&R.includes&&(j=(typeof R.includes=="string"?R.includes.split(",").map(X=>X.trim()):Array.isArray(R.includes)?R.includes:[]).filter(X=>typeof X=="string"&&i.allowedIncludes.includes(X)),j?.length===0&&(j=void 0));let z=Wi(R,i.filterableFields);A=z.map(W=>({field:W.field,op:W.op,value:String(W.value??"")})),v&&(k={field:v,dir:E});let te={pageSize:M,direction:_,...F?{withTotal:!0}:{}};if($)try{let W=typeof $=="string"?JSON.parse($):$;te.cursor=await ms(i,W);}catch{}if(v){if(i.orderableFields&&!i.orderableFields.includes(v))return q(d,`Field not orderable: ${v}`,400);te.orderBy=[{field:v,direction:E}];}if(z.length>0){te.where=[];for(let W of z){let X=Cn(i.schema,W.field,W.value,W.op);if(!X.success)return q(d,`Invalid filter value for '${W.field}': ${X.error}`,400);te.where.push([W.field,W.op,X.data]);}}H&&(te.select=H),j&&(te.include=j);let K=await i.repo.query.paginate(te),Se={items:await l(i,c(d),y,K.data),hasNextPage:K.hasNextPage,hasPrevPage:K.hasPrevPage,nextCursor:En(K.nextCursor),prevCursor:En(K.prevCursor),...K.totalCount!==void 0?{totalCount:K.totalCount,totalCountIsExact:K.totalCountIsExact}:{}};return nt(d,Se,{pageSize:M,hasMore:K.hasNextPage,...K.totalCount!==void 0?{totalCount:K.totalCount,totalCountIsExact:K.totalCountIsExact}:{}})}catch(R){return await Ir(d,R,{repoName:y.repoName||i.name,ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:A,sort:k},"Failed to fetch documents",n,r)}}async function h(x){let d=x.c,y=d.req.param(),i=u(y.repoName,d);if(!i)return q(d,"Repository not found",404);let g=c(d),m=await a(d,i,"list",{user:g,query:x.input||{},params:y});if(!m.allowed)return m.errorResponse;let A=[],k;try{let R=x.input||{},P=fs(R.pageSize,i.pageSize);if(!P.success)return q(d,P.error,400);let M=P.value,$=R.direction==="prev"?"prev":"next";R.where&&(A=R.where.map(D=>({field:String(D[0]),op:D[1],value:String(D[2]??"")}))),R.orderBy&&R.orderBy[0]&&(k={field:R.orderBy[0].field,dir:R.orderBy[0].direction==="desc"?"desc":"asc"});let _=R.withTotal===!0||String(R.withTotal)==="true",v={pageSize:M,direction:$,..._?{withTotal:!0}:{}};if(R.cursor)try{let D=typeof R.cursor=="string"?JSON.parse(R.cursor):R.cursor;v.cursor=await ms(i,D);}catch{}if(i.allowedIncludes&&R.includes&&R.includes.length>0){let D=R.includes.filter(F=>typeof F=="string"?i.allowedIncludes.includes(F):typeof F=="object"&&F!==null&&"relation"in F&&typeof F.relation=="string"?i.allowedIncludes.includes(F.relation):!1);D.length>0&&(v.include=D);}if(R.where&&R.where.length>0){if(i.filterableFields){let F=new Set(i.filterableFields),j=R.where.filter(z=>!F.has(z[0]));if(j.length>0){q(d,`Fields not filterable: ${j.map(z=>z[0]).join(", ")}`,400);return}}let D=[];for(let F of R.where){let j=Zt(F[1]),z=Cn(i.schema,F[0],F[2],j);if(!z.success){q(d,`Invalid filter value for '${F[0]}': ${z.error}`,400);return}D.push([F[0],j,z.data]);}v.where=D;}if(R.orWhere&&R.orWhere.length>0){if(i.filterableFields){let F=new Set(i.filterableFields),j=R.orWhere.filter(z=>!F.has(z[0]));if(j.length>0){q(d,`Fields not filterable: ${j.map(z=>z[0]).join(", ")}`,400);return}}let D=[];for(let F of R.orWhere){let j=Zt(F[1]),z=Cn(i.schema,F[0],F[2],j);if(!z.success){q(d,`Invalid filter value for '${F[0]}': ${z.error}`,400);return}D.push([F[0],j,z.data]);}v.orWhere=D;}if(R.orWhereGroups&&R.orWhereGroups.length>0){if(i.filterableFields){let F=new Set(i.filterableFields);for(let j of R.orWhereGroups){let z=j.filter(te=>!F.has(te[0]));if(z.length>0){q(d,`Fields not filterable: ${z.map(te=>te[0]).join(", ")}`,400);return}}}let D=[];for(let F of R.orWhereGroups){let j=[];for(let z of F){let te=Zt(z[1]),K=Cn(i.schema,z[0],z[2],te);if(!K.success){q(d,`Invalid filter value for '${z[0]}': ${K.error}`,400);return}j.push([z[0],te,K.data]);}D.push(j);}v.orWhereGroups=D;}if(R.orderBy&&R.orderBy.length>0){if(i.orderableFields){let D=new Set(i.orderableFields),F=R.orderBy.filter(j=>!D.has(j.field));if(F.length>0){q(d,`Fields not orderable: ${F.map(j=>j.field).join(", ")}`,400);return}}v.orderBy=R.orderBy;}R.select&&R.select.length>0&&(v.select=R.select);let E=await i.repo.query.paginate(v),H={items:await l(i,c(d),y,E.data),hasNextPage:E.hasNextPage,hasPrevPage:E.hasPrevPage,nextCursor:En(E.nextCursor),prevCursor:En(E.prevCursor),...E.totalCount!==void 0?{totalCount:E.totalCount,totalCountIsExact:E.totalCountIsExact}:{}};return nt(d,H,{pageSize:M,hasMore:E.hasNextPage,...E.totalCount!==void 0?{totalCount:E.totalCount,totalCountIsExact:E.totalCountIsExact}:{}})}catch(R){return await Ir(d,R,{repoName:y.repoName||i.name,ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:A,sort:k},"Failed to query documents",n,r)}}async function b(x){let d=x.c,y=d.req.param(),i=u(y.repoName,d);if(!i)return q(d,"Repository not found",404);let g=y.id;if(!g)return q(d,"Document ID required",400);try{let m=await f(i,g);if(!m)return q(d,"Document not found",404);let A=c(d),k=await a(d,i,"get",{user:A,doc:m,params:y});if(!k.allowed)return k.errorResponse;if(i.rules?.filter)try{if(!await i.rules.filter({user:A,doc:m,params:y}))return q(d,"Document not found",404)}catch{return q(d,"Document not found",404)}return nt(d,m)}catch(m){return await Ir(d,m,{repoName:y.repoName||i.name,ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:[{field:i.documentKey,op:"==",value:g}]},"Failed to fetch document",n,r)}}async function T(x){let d=x.c,y=d.req.param(),i=u(y.repoName,d);if(!i)return q(d,"Repository not found",404);try{let g=x.input||{},m=c(d),A=await a(d,i,"create",{user:m,body:g,params:y});if(!A.allowed)return A.errorResponse;let k=An(i.schema,g,i.createFields,!1,i.systemKeys);if(!k.success)return q(d,k.error,400);if(i.validate){let $=await i.validate(k.data,"create");if($)return q(d,$,400)}i.hooks?.beforeCreate&&await i.hooks.beforeCreate({user:m,body:k.data,params:y,c:d});let R,P;if(i.isGroup&&i.parentKeys&&i.parentKeys.length>0){let $={...k.data},_=i.parentKeys.filter(v=>$[v]===void 0||$[v]===null||typeof $[v]=="string"&&$[v].trim()==="");if(_.length>0)return q(d,`Missing parent key(s) for subcollection create: ${_.join(", ")}`,400);if(typeof i.repo.create=="function")R=await i.repo.create($);else {let v=i.parentKeys.map(N=>String($[N])),E=$[i.documentKey]||Be();P=[...v,E],R=await i.repo.set(...v,E,$);}}else R=await i.repo.create(k.data);let M=R;if(i.hooks?.afterCreate){let $=R?.[i.documentKey]??P?.[P.length-1]??"",_=String($),v=P??p(R,i)??p({...k.data,..._?{[i.documentKey]:_}:{}},i)??(_?[_]:[]);try{let E=await i.hooks.afterCreate({user:m,doc:R,id:_,pathArgs:v,params:y,c:d}),N=On(E);N&&v.length>0&&(M=await i.repo.update(...v,N));}catch(E){await s(i,x.logger,{hook:"afterCreate",repoName:i.name,path:i.path,id:_,pathArgs:v,user:m,c:d},E);}}return nt(d,M,void 0,201)}catch(g){let m=n&&g instanceof Error?g.message:"Failed to create document";return q(d,m,500)}}async function S(x,d){let y=x.c,i=y.req.param(),g=u(i.repoName,y);if(!g)return q(y,"Repository not found",404);let m=i.id;if(!m)return q(y,"Document ID required",400);try{let A=x.input||{},k=await f(g,m);if(!k)return q(y,"Document not found",404);let R=An(g.schema,A,g.mutableFields,d,g.systemKeys);if(!R.success)return q(y,R.error,400);if(g.validate){let D=await g.validate(R.data,"update");if(D)return q(y,D,400)}let P=Te(k,R.data),M=c(y),$=await a(y,g,"update",{user:M,doc:k,body:R.data,diff:P,params:i});if(!$.allowed)return $.errorResponse;if(g.hooks?.beforeUpdate){let D=g.rules?.update?Te(k,R.data):P;await g.hooks.beforeUpdate({user:M,doc:k,body:R.data,diff:D,params:i,c:y});}let _={...R.data},v=g.hooks?.afterUpdate?Te(k,_):P,E=p(k,g)??[m],N=await g.repo.update(...E,R.data),H=N;if(g.hooks?.afterUpdate)try{let D=await g.hooks.afterUpdate({user:M,before:k,after:N,body:_,diff:v,id:m,pathArgs:E,params:i,c:y}),F=On(D);F&&(H=await g.repo.update(...E,F));}catch(D){await s(g,x.logger,{hook:"afterUpdate",repoName:g.name,path:g.path,id:m,pathArgs:E,user:M,c:y},D);}return nt(y,H)}catch(A){let k=n&&A instanceof Error?A.message:"Failed to update document";return q(y,k,500)}}async function I(x){let d=x.c,y=d.req.param(),i=u(y.repoName,d);if(!i)return q(d,"Repository not found",404);if(!i.allowDelete)return q(d,"Delete not allowed for this repository",403);let g=y.id;if(!g)return q(d,"Document ID required",400);try{let m=await f(i,g);if(!m)return q(d,"Document not found",404);let A=c(d),k=await a(d,i,"delete",{user:A,doc:m,params:y});if(!k.allowed)return k.errorResponse;let R=p(m,i)??[g];if(await i.repo.delete(...R),i.hooks?.afterDelete)try{await i.hooks.afterDelete({user:A,doc:m,id:g,pathArgs:R,params:y,c:d});}catch(P){await s(i,x.logger,{hook:"afterDelete",repoName:i.name,path:i.path,id:g,pathArgs:R,user:A,c:d},P);}return nt(d,{deleted:!0})}catch(m){let A=n&&m instanceof Error?m.message:"Failed to delete document";return q(d,A,500)}}function C(x){return x.c.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-History-Reason, X-History-Comment","Access-Control-Max-Age":"86400"})}async function O(x){let d=x.c,y=d.req.param(),i=u(y.repoName,d);if(!i)return q(d,"Repository not found",404);try{let g=x.input||{};if(!Array.isArray(g.operations))return q(d,"operations array is required",400);let m=c(d),A=i.repo.batch.create(),k=[],R=!!i.hooks,P=[],M=[],$=[];for(let v of g.operations){if(!v.type||!["create","update","delete"].includes(v.type))return q(d,"Invalid operation type",400);if(v.type==="create"){let E=await a(d,i,"create",{user:m,body:v.data,params:y});if(!E.allowed)return E.errorResponse;let N=An(i.schema,v.data,i.createFields,!1,i.systemKeys);if(!N.success)return q(d,N.error,400);i.hooks?.beforeCreate&&await i.hooks.beforeCreate({user:m,body:N.data,params:y,c:d});let H=v.data[i.documentKey]||N.data[i.documentKey]||Be(),D={...N.data};i.createdKey&&D[i.createdKey]===void 0&&(D[i.createdKey]=new Date);let F;if(i.isGroup&&i.parentKeys){let j=i.parentKeys.map(z=>String(D[z]));F=[...j,H],A.set(...j,H,D);}else F=[H],A.set(H,D);if(k.push({op:"create",id:H}),R){let j={...D,[i.documentKey]:H};if(i.pathKey&&typeof i.repo.documentRef=="function")try{let z=i.repo.documentRef(...F);z?.path&&(j[i.pathKey]=z.path);}catch{}P.push({id:H,pathArgs:F,doc:j});}}else if(v.type==="update"){if(!v.id)return q(d,"id required for update",400);let E=await f(i,v.id);if(!E)return q(d,`Document ${v.id} not found`,404);let N=An(i.schema,v.data,i.mutableFields,!0,i.systemKeys);if(!N.success)return q(d,N.error,400);if(i.validate){let te=await i.validate(N.data,"update");if(te)return q(d,te,400)}let H=Te(E,N.data),D=await a(d,i,"update",{user:m,doc:E,body:N.data,diff:H,params:y});if(!D.allowed)return D.errorResponse;if(i.hooks?.beforeUpdate){let te=i.rules?.update?Te(E,N.data):H;await i.hooks.beforeUpdate({user:m,doc:E,body:N.data,diff:te,params:y,c:d});}let F={...N.data},j=R?Te(E,F):H,z=p(E,i)??[v.id];A.update(...z,N.data),k.push({op:"update",id:v.id}),R&&M.push({id:v.id,pathArgs:z,before:E,after:j.after,body:F,diff:j});}else if(v.type==="delete"){if(!i.allowDelete)return q(d,"Delete not allowed",403);if(!v.id)return q(d,"id required for delete",400);let E=await f(i,v.id);if(!E)return q(d,`Document ${v.id} not found`,404);let N=await a(d,i,"delete",{user:m,doc:E,params:y});if(!N.allowed)return N.errorResponse;let H=p(E,i)??[v.id];A.delete(...H),k.push({op:"delete",id:v.id}),R&&$.push({id:v.id,pathArgs:H,doc:E});}}await A.commit();let _=P.length>0||M.length>0||$.length>0;if(i.hooks&&_)if(i.hooks.afterBatch)try{await i.hooks.afterBatch({user:m,created:P,updated:M,deleted:$,params:y,c:d});}catch(v){await s(i,x.logger,{hook:"afterBatch",repoName:i.name,path:i.path,user:m,c:d},v);}else {if(i.hooks.afterCreate)for(let v of P)try{let E=await i.hooks.afterCreate({user:m,doc:v.doc,id:v.id,pathArgs:v.pathArgs,params:y,c:d}),N=On(E);N&&v.pathArgs.length>0&&await i.repo.update(...v.pathArgs,N);}catch(E){await s(i,x.logger,{hook:"afterCreate",repoName:i.name,path:i.path,id:v.id,pathArgs:v.pathArgs,user:m,c:d},E);}if(i.hooks.afterUpdate)for(let v of M)try{let E=await i.hooks.afterUpdate({user:m,before:v.before,after:v.after,body:v.body,diff:v.diff,id:v.id,pathArgs:v.pathArgs,params:y,c:d}),N=On(E);N&&v.pathArgs.length>0&&await i.repo.update(...v.pathArgs,N);}catch(E){await s(i,x.logger,{hook:"afterUpdate",repoName:i.name,path:i.path,id:v.id,pathArgs:v.pathArgs,user:m,c:d},E);}if(i.hooks.afterDelete)for(let v of $)try{await i.hooks.afterDelete({user:m,doc:v.doc,id:v.id,pathArgs:v.pathArgs,params:y,c:d});}catch(E){await s(i,x.logger,{hook:"afterDelete",repoName:i.name,path:i.path,id:v.id,pathArgs:v.pathArgs,user:m,c:d},E);}}return nt(d,{results:k})}catch(g){let m=n&&g instanceof Error?g.message:"Batch operation failed";return q(d,m,500)}}return {handleList:w,handleQuery:h,handleGet:b,handleCreate:T,handleUpdate:S,handleDelete:I,handleBatch:O,handleOptions:C}}function bt(e){try{return z.toJSONSchema(e,{target:"openapi-3.1",unrepresentable:"any",override:t=>{let n=getOpenApiMetadata(t.zodSchema);n&&(Object.assign(t.jsonSchema,n),(t.jsonSchema.anyOf||t.jsonSchema.oneOf)&&delete t.jsonSchema.type);let r=t.zodSchema?._zod?.def;r&&(r.type==="date"&&!t.jsonSchema.type&&!t.jsonSchema.anyOf?(t.jsonSchema.type="string",t.jsonSchema.format="date-time"):r.type==="bigint"&&!t.jsonSchema.type&&!t.jsonSchema.anyOf&&(t.jsonSchema.type="string",t.jsonSchema.format="int64"));}})}catch(t){return typeof console<"u"&&console.warn&&console.warn("[generateOpenAPISpec] Failed to convert Zod schema to JSON Schema; falling back to {type:object}.",t),{type:"object"}}}function pe(e){return {$ref:`#/components/schemas/${e}`}}function ee(e){return {description:e,content:{"application/json":{schema:pe("ErrorResponse")}}}}function gt(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function Qi(e){return {description:"Paginated list of documents",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:{type:"object",properties:{items:{type:"array",items:e},nextCursor:{oneOf:[{type:"object"},{type:"null"}]},prevCursor:{oneOf:[{type:"object"},{type:"null"}]},hasNextPage:{type:"boolean"},hasPrevPage:{type:"boolean"},totalCount:{type:"integer",description:"Total count of matching documents (when requested with withTotal=true)"},totalCountIsExact:{type:"boolean",description:"Whether totalCount is exact (true) or estimated due to OR conditions (false)"}},required:["items","hasNextPage","hasPrevPage"]},meta:{type:"object",properties:{pageSize:{type:"integer"},hasMore:{type:"boolean"},totalCount:{type:"integer"},totalCountIsExact:{type:"boolean"},cursor:{oneOf:[{type:"string"},{type:"null"}]}}}},required:["success","data"]}}}}}function Qt(e){let t=e;for(;t;){let n=t._zod?.def??t._def;if(!n)break;if(n.innerType)t=n.innerType;else if(n.schema)t=n.schema;else if(n.type==="optional"||n.type==="nullable"||n.type==="default"||n.type==="catch"||n.type==="effects")t=n.innerType??n.schema;else break}return t}function Vi(e,t){let n=t.split("."),r=Qt(e);for(let o=0;o<n.length;o++){let s=n[o];if(!s)continue;let a=r?.shape;if(!a||!a[s])return;let l=a[s];if(o===n.length-1)return l;r=Qt(l);}return r}function at(e){let t=e?._zod?.def??e?._def,n=t?.typeName??t?.type,r=o=>{let s=getOpenApiMetadata(e);return s&&typeof o.openapi=="function"?o.openapi(s):o};if(n==="ZodObject"||n==="object"){let o=e.shape,s={};for(let[a,l]of Object.entries(o))s[a]=at(l);return r(z.object(s).partial())}if(n==="ZodOptional"||n==="optional"){let o=t.innerType;if(!o)return e;let s=at(o);return s===o?e:r(s.optional())}if(n==="ZodNullable"||n==="nullable"){let o=t.innerType;if(!o)return e;let s=at(o);return s===o?e:r(s.nullable())}if(n==="ZodDefault"||n==="default"){let o=t.innerType;return o?r(at(o).optional()):e}if(n==="ZodUnion"||n==="union"){let o=t.options;if(!o||o.length<2)return e;let s=o.map(l=>at(l));return s.some((l,c)=>l!==o[c])?r(z.union(s)):e}return e}function Hr(e,t="",n=0){if(n>5)return [];let o=Qt(e)?.shape;if(!o)return [];let s=[];for(let[a,l]of Object.entries(o)){let c=t?`${t}.${a}`:a,u=Qt(l);u?.shape&&typeof u.shape=="object"?(s.push({path:c,zodSchema:l}),s.push(...Hr(u,c,n+1))):s.push({path:c,zodSchema:l});}return s}function Gi(e){return e.filterableFields&&e.filterableFields.length>0?e.filterableFields.map(t=>({path:t,zodSchema:Vi(e.schema,t)})):Hr(e.schema)}function ws(e){if(!e)return {type:"string"};let t=bt(e);return delete t.$schema,delete t.title,t}function Rs(){return {type:"object",properties:{where:{type:"array",items:{type:"array",items:{},minItems:3,maxItems:3},description:"AND conditions: [field, operator, value][]"},orWhere:{type:"array",items:{type:"array",items:{},minItems:3,maxItems:3},description:"Simple OR conditions (each independently OR'd)"},orWhereGroups:{type:"array",items:{type:"array",items:{type:"array",items:{},minItems:3,maxItems:3}},description:"Advanced OR groups (AND within, OR across groups)"},orderBy:{type:"array",items:{type:"object",properties:{field:{type:"string"},direction:{type:"string",enum:["asc","desc"]}},required:["field"]}},select:{type:"array",items:{type:"string"},description:"Fields to select (projection)"},pageSize:{type:"integer",minimum:1,maximum:1e3,description:"Number of items per page"},cursor:{oneOf:[{type:"string"},{type:"object"}],description:"Pagination cursor"},direction:{type:"string",enum:["next","prev"],description:"Pagination direction"},includes:{type:"array",items:{oneOf:[{type:"string"},{type:"object",properties:{relation:{type:"string"},select:{type:"array",items:{type:"string"}}},required:["relation"]}]},description:"Relations to include (populate)"},withTotal:{type:"boolean",description:"Include total document count (totalCount and totalCountIsExact) in response"}}}}function Ji(e){let t=Gi(e),n=e.orderableFields??t.map(a=>a.path),r=t.map(a=>a.path);if(t.length===0)return Rs();let o=[];for(let{path:a,zodSchema:l}of t){let c=ws(l),u=Qt(l),f=u?._zod?.def?.type==="array"||u?._def?.typeName==="ZodArray"||u?._def?.type==="array"?ws(u?._zod?.def?.element??u?._def?.type??u?._def?.element):c;o.push({type:"array",description:`Condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["==","!=","<","<=",">",">=","eq","ne","lt","lte","gt","gte"]},c],minItems:3,maxItems:3}),o.push({type:"array",description:`List condition on '${a}' (in, not-in)`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["in","not-in","nin"]},{type:"array",items:c}],minItems:3,maxItems:3}),o.push({type:"array",description:`Array contains condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["array-contains","contains"]},f],minItems:3,maxItems:3}),o.push({type:"array",description:`Array contains-any condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["array-contains-any","containsAny"]},{type:"array",items:f}],minItems:3,maxItems:3});}let s={oneOf:o};return {type:"object",properties:{where:{type:"array",items:s,description:"AND conditions: [field, operator, value][]"},orWhere:{type:"array",items:s,description:"Simple OR conditions (each independently OR'd)"},orWhereGroups:{type:"array",items:{type:"array",items:s},description:"Advanced OR groups (AND within, OR across groups)"},orderBy:{type:"array",items:{type:"object",properties:{field:{type:"string",enum:n},direction:{type:"string",enum:["asc","desc"]}},required:["field"]}},select:{type:"array",items:{type:"string",enum:r},description:"Fields to select (projection)"},pageSize:{type:"integer",minimum:1,maximum:1e3,description:"Number of items per page"},cursor:{oneOf:[{type:"string"},{type:"object"}],description:"Pagination cursor"},direction:{type:"string",enum:["next","prev"],description:"Pagination direction"},includes:{type:"array",items:e.allowedIncludes&&e.allowedIncludes.length>0?{oneOf:[{type:"string",enum:e.allowedIncludes},{type:"object",properties:{relation:{type:"string",enum:e.allowedIncludes},select:{type:"array",items:{type:"string"}}},required:["relation"]}]}:{oneOf:[{type:"string"},{type:"object",properties:{relation:{type:"string"},select:{type:"array",items:{type:"string"}}},required:["relation"]}]},description:"Relations to include (populate)"},withTotal:{type:"boolean",description:"Include total document count (totalCount and totalCountIsExact) in response"}}}}function Yi(e){if(e.historyHeaders)return e.historyHeaders;let t=e.repo?._historyConfig;if(!t?.enabled||t.autoInjectMeta===false)return null;let n=Ce(t);return n?{reason:n.fields.reason!==false,comment:n.fields.comment!==false}:null}function Xi(e,t){if(t===false)return [];let n=Yi(e);if(!n)return [];let r=t?.reasonHeader===void 0?Qe:t.reasonHeader,o=t?.commentHeader===void 0?Ve:t.commentHeader,s=[],a=new Set;if(n.reason&&typeof r=="string"&&r.trim()){let l=r.trim();a.add(l.toLowerCase()),s.push({name:l,in:"header",required:false,schema:{type:"string"},description:"Optional reason recorded in the document's change history"});}if(n.comment&&typeof o=="string"&&o.trim()){let l=o.trim();a.has(l.toLowerCase())||(a.add(l.toLowerCase()),s.push({name:l,in:"header",required:false,schema:{type:"string"},description:"Optional comment recorded in the document's change history"}));}if(t?.extraHeaders?.length)for(let l of t.extraHeaders){let c=typeof l=="string"?{name:l}:l,u=c?.name?.trim();!u||a.has(u.toLowerCase())||(a.add(u.toLowerCase()),s.push({name:u,in:"header",required:c.required??false,schema:c.schema??{type:"string"},...c.description?{description:c.description}:{}}));}return s}function ec(e,t,n,r,o,s=null,a="QueryRequestBody",l=[]){let c={},u=e.name,p=`${t}/${e.name}`,f=`${p}/{${e.documentKey}}`,w={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};c[p]={post:{operationId:`create${Ze(e.name)}`,summary:`Create a ${Ie(e.name)}`,tags:[u],...l.length>0?{parameters:[...l]}:{},requestBody:{required:true,content:{"application/json":{schema:pe(r??n)}}},responses:{201:gt("Document created",pe(n)),400:ee("Validation error"),403:ee("Forbidden"),500:ee("Internal server error")}}},c[`${p}/query`]={post:{operationId:`query${Ze(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[u],requestBody:{required:true,content:{"application/json":{schema:pe(a)}}},responses:{200:Qi(pe(n)),400:ee("Invalid query"),403:ee("Forbidden"),424:ee("Missing composite index (includes indexUrl in response)"),500:ee("Internal server error")}}},c[`${p}/batch`]={post:{operationId:`batch${Ze(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[u],...l.length>0?{parameters:[...l]}:{},requestBody:{required:true,content:{"application/json":{schema:pe(`${n}BatchRequest`)}}},responses:{200:gt("Batch operations completed",{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{op:{type:"string"},id:{type:"string"}}}}}}),400:ee("Validation error"),403:ee("Forbidden"),404:ee("Document not found"),500:ee("Internal server error")}}};let h={};return h.get={operationId:`get${Ze(Ie(e.name))}`,summary:`Get a single ${Ie(e.name)}`,tags:[u],parameters:[w],responses:{200:gt("Document found",pe(n)),400:ee("Document ID required"),403:ee("Forbidden"),404:ee("Document not found"),424:ee("Missing composite index (includes indexUrl in response)"),500:ee("Internal server error")}},h.put={operationId:`update${Ze(Ie(e.name))}`,summary:`Update a ${Ie(e.name)} (full replace)`,tags:[u],parameters:[w,...l],requestBody:{required:true,content:{"application/json":{schema:pe(o??n)}}},responses:{200:gt("Document updated",pe(n)),400:ee("Validation error"),403:ee("Forbidden"),404:ee("Document not found"),500:ee("Internal server error")}},h.patch={operationId:`patch${Ze(Ie(e.name))}`,summary:`Partially update a ${Ie(e.name)}`,tags:[u],parameters:[w,...l],requestBody:{required:true,content:{"application/json":{schema:pe(s??o??n)}}},responses:{200:gt("Document patched",pe(n)),400:ee("Validation error"),403:ee("Forbidden"),404:ee("Document not found"),500:ee("Internal server error")}},e.allowDelete&&(h.delete={operationId:`delete${Ze(Ie(e.name))}`,summary:`Delete a ${Ie(e.name)}`,tags:[u],parameters:[w],responses:{200:gt("Document deleted",{type:"object",properties:{id:{type:"string"}}}),400:ee("Document ID required"),403:ee("Forbidden"),404:ee("Document not found"),500:ee("Internal server error")}}),c[f]=h,c}function Mr(e,t,n={}){let{title:r="CRUD API",version:o="1.0.0",description:s,servers:a,auth:l=false}=n,c=t==="/"?"":t.replace(/\/$/,""),u={},p={},f=[];u.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string",description:"Human-readable error description"},errorType:{type:"string",enum:["index"],description:"Error category discriminator. Set to 'index' when a Firestore composite index is missing."},indexUrl:{type:"string",format:"uri",description:"Direct Firebase Console URL to create the required composite index (when errorType is 'index')."}},required:["success","error"]},u.QueryRequestBody=Rs();for(let[T,S]of Object.entries(e)){let I=Ze(Ie(T)),C=`${I}Create`,O=`${I}Update`,x=`${I}Patch`,d=`${I}QueryRequestBody`;u[I]=bt(S.schema),u[d]=Ji(S);let y=v=>{let E={},N=Hr(S.schema);for(let{path:H,zodSchema:D}of N){let F=H.split(".")[0];S.systemKeys.includes(F)||S.systemKeys.includes(H)||v&&v.length>0&&!v.includes(H)&&!v.includes(F)||(H.includes(".")?E[H]=D.optional():E[H]=D);}return E},i=null,g=y(S.createFields);if(S.isGroup&&S.parentKeys&&S.parentKeys.length>0){let v=S.schema?.shape??{};for(let E of S.parentKeys)!g[E]&&v[E]&&(g[E]=v[E]);}if(Object.keys(g).length>0){let v=bt(z.object(g));if(S.isGroup&&S.parentKeys&&S.parentKeys.length>0){let E=new Set(Array.isArray(v.required)?v.required:[]);for(let N of S.parentKeys)v.properties?.[N]&&E.add(N);E.size>0&&(v.required=Array.from(E));}u[C]=v,i=C;}let m=null,A=null,k=y(S.mutableFields);if(Object.keys(k).length>0){let v=z.object(k);u[O]=bt(v),m=O,u[x]=bt(at(v)),A=x;}else u[x]=bt(at(S.schema)),A=x;let R=`${I}BatchCreateOperation`,P=`${I}BatchUpdateOperation`,M=`${I}BatchDeleteOperation`;u[R]={type:"object",title:`${I} Create Operation`,properties:{type:{type:"string",enum:["create"],const:"create"},data:pe(i??I)},required:["type","data"]},u[P]={type:"object",title:`${I} Update Operation`,properties:{type:{type:"string",enum:["update"],const:"update"},id:{type:"string"},data:pe(A??m??I)},required:["type","id","data"]},S.allowDelete&&(u[M]={type:"object",title:`${I} Delete Operation`,properties:{type:{type:"string",enum:["delete"],const:"delete"},id:{type:"string"}},required:["type","id"]}),u[`${I}BatchRequest`]={type:"object",properties:{operations:{type:"array",items:{oneOf:[pe(R),pe(P),...S.allowDelete?[pe(M)]:[]],discriminator:{propertyName:"type"}}}},required:["operations"]};let $=Xi(S,n.historyHeaders),_=ec(S,c,I,i,m,A,d,$);Object.assign(p,_),f.push({name:T,description:`Operations on ${T} (collection: ${S.path})`});}let w={},h;return l==="basic"?(w.basicAuth={type:"http",scheme:"basic"},h=[{basicAuth:[]}]):l==="bearer"&&(w.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},h=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:r,version:o,...s?{description:s}:{}},...a&&a.length>0?{servers:a}:{},paths:p,components:{schemas:u,...Object.keys(w).length>0?{securitySchemes:w}:{}},...h?{security:h}:{},tags:f}}function Ze(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Ie(e){return e.endsWith("ies")?e.slice(0,-3)+"y":e.endsWith("ses")||e.endsWith("xes")||e.endsWith("zes")?e.slice(0,-2):e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e}var wt=class extends Error{constructor(n,r){super("Request validation failed");this.zodError=n;this.source=r;this.statusCode=400;this.name="ValidationError";}};var Vt=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},Gt=class extends Error{constructor(n){super("Output validation failed");this.zodError=n;this.statusCode=500;this.name="OutputValidationError";}};function Ss(e){return e.issues.map(t=>({path:t.path.join("."),code:t.code,message:t.message}))}function vs(e,t){return t instanceof wt?e.json({success:false,error:"Validation failed",issues:Ss(t.zodError)},400):t instanceof Vt?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof Gt?e.json({success:false,error:"Output validation failed",issues:Ss(t.zodError)},500):null}extendZodWithOpenApi(z);var Ts="Successful response",ks="Error response";function ge(e,t=new Set){if(!e||typeof e!="object"||t.has(e))return;t.add(e);let n=e,r=n._zod?.def??n.def;if(!r)return;if(r.type==="custom"){let s=getOpenApiMetadata(n);s?.type||z.globalRegistry.add(n,{...s??{},type:"object"});return}if(r.innerType&&ge(r.innerType,t),r.element&&ge(r.element,t),r.valueType&&ge(r.valueType,t),r.keyType&&ge(r.keyType,t),r.left&&ge(r.left,t),r.right&&ge(r.right,t),r.in&&ge(r.in,t),r.out&&ge(r.out,t),typeof r.getter=="function")try{ge(r.getter(),t);}catch{}if(Array.isArray(r.options))for(let s of r.options)ge(s,t);if(Array.isArray(r.items))for(let s of r.items)ge(s,t);let o=typeof r.shape=="function"?r.shape():r.shape;if(o&&typeof o=="object")for(let s of Object.values(o))ge(s,t);}function _r(e){if(!e||typeof e!="object")return;if(Array.isArray(e)){for(let n of e)_r(n);return}let t=e;(Array.isArray(t.anyOf)||Array.isArray(t.oneOf))&&"type"in t&&delete t.type;for(let n of Object.values(t))_r(n);}function sc(e){return e==="get"?"query":"json"}function ac(e,t){let n=t?.output;return n?typeof n=="function"?n(e):n:e}function ic(e){if(typeof e.safeParse=="function")return {description:ks,schema:e};let t=e;return {description:t.description??ks,schema:t.schema}}function Es(e,t,n,r){let o=new OpenAPIRegistry;if(n.securitySchemes)for(let[l,c]of Object.entries(n.securitySchemes))o.registerComponent("securitySchemes",l,c);for(let l of e){let c=l.method,u=l.source??sc(c),p=dc(t,l.path??"/"),f=l.status??200;l.input&&ge(l.input);let w=cc(c,u,l.input),h=As(u,l.input,"query"),b=As(u,l.input,"param"),T=uc(c,p),S=ac(l.output,r);S&&ge(S);let I={[f]:S?{description:Ts,content:{"application/json":{schema:S}}}:{description:Ts}};if(r?.errors)for(let[C,O]of Object.entries(r.errors)){let{description:x,schema:d}=ic(O);d&&ge(d),I[C]=d?{description:x,content:{"application/json":{schema:d}}}:{description:x};}o.registerPath({method:c,path:lc(p),operationId:T,summary:l.summary,description:l.description,tags:l.tags,deprecated:l.deprecated,security:l.security,request:{...h?{query:h}:{},...b?{params:b}:{},...w?{body:w}:{}},responses:I});}let a=new OpenApiGeneratorV31(o.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security});return _r(a),a}function cc(e,t,n){return !n||e==="get"?null:t==="json"?{content:{"application/json":{schema:n}}}:t==="form"?{content:{"application/x-www-form-urlencoded":{schema:n}}}:null}function As(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function lc(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function dc(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,o=`${n}${r}`;return o===""?"/":o}function uc(e,t){let n=t.replace(/[{}]/g,"").replace(/\/+/g,"_").replace(/[^A-Za-z0-9_]/g,"").replace(/^_+|_+$/g,"");return `${e}_${n||"root"}`}function Os(e,t){let n=e.replace(/"/g,"&quot;");return `<!doctype html>
1161
+ `;function zt(){return jsx("script",{dangerouslySetInnerHTML:{__html:Go}})}mr();function qe(e){return "<!DOCTYPE html>"+renderToString(e)}var _i=["corporate","silk","dark"],Mi=()=>jsxs("div",{class:"dropdown dropdown-end","data-frs-theme-switcher":true,children:[jsxs("button",{type:"button",tabIndex:0,class:"btn btn-sm btn-ghost text-neutral-content gap-1.5","aria-label":"Switch theme",children:[jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2",class:"size-4",children:[jsx("circle",{cx:"12",cy:"12",r:"4"}),jsx("path",{d:"M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"})]}),jsx("span",{class:"text-xs hidden sm:inline","data-frs-theme-current":true,children:"Theme"})]}),jsx("ul",{tabIndex:0,class:"dropdown-content menu menu-sm bg-base-100 text-base-content rounded-box z-50 mt-2 w-40 p-1 shadow-lg border border-base-300",children:_i.map(e=>jsx("li",{children:jsxs("button",{type:"button","data-frs-theme":e,class:"capitalize justify-between",children:[jsx("span",{children:e}),jsx("span",{class:"hidden text-primary","data-frs-theme-check":e,children:"\u2713"})]})},e))})]}),Ue=({opts:e,children:t})=>{let{title:n,breadcrumb:r,flash:o,basePath:s="/"}=e;return jsxs("html",{lang:"en","data-theme":"corporate",children:[jsxs("head",{children:[jsx("meta",{charset:"UTF-8"}),jsx("meta",{name:"viewport",content:"width=device-width, initial-scale=1"}),jsxs("title",{children:[n," \u2014 FRS Admin"]}),jsx("script",{dangerouslySetInnerHTML:{__html:"(function(){try{var t=localStorage.getItem('frs-admin-theme');if(t){document.documentElement.setAttribute('data-theme',t);}}catch(_){}})();"}}),jsx("link",{href:"https://cdn.jsdelivr.net/npm/daisyui@5/themes.css",rel:"stylesheet",type:"text/css"}),jsx("link",{href:"https://cdn.jsdelivr.net/npm/daisyui@5/daisyui.css",rel:"stylesheet",type:"text/css"}),jsx("script",{src:"https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"})]}),jsxs("body",{class:"bg-base-200/50 min-h-screen flex flex-col",children:[jsxs("div",{class:"navbar bg-neutral text-neutral-content shadow-sm sticky top-0 z-50 px-6",children:[jsx("div",{class:"flex-1",children:jsx("a",{href:s,class:"font-bold text-lg tracking-tight hover:opacity-80 transition-opacity",children:"FRS Admin"})}),jsx("div",{class:"flex-none",children:jsx(Mi,{})})]}),jsxs("main",{class:"px-6 py-8 w-full flex-1",children:[r&&r.length>0&&jsx("div",{class:"text-sm breadcrumbs mb-4",children:jsx("ul",{children:r.map((a,l)=>a.href?jsx("li",{children:jsx("a",{href:a.href,children:a.label})},l):jsx("li",{class:"text-base-content/60",children:a.label},l))})}),jsx("h1",{class:"text-2xl font-bold mb-6",children:n}),o&&jsxs("div",{role:"alert",class:`alert ${o.type==="success"?"alert-success":o.type==="warning"?"alert-warning":"alert-error"} mb-6`,children:[jsx("span",{class:"flex-1",children:o.message}),o.action&&jsx("a",{href:o.action.href,...o.action.external?{target:"_blank",rel:"noopener noreferrer"}:{},class:"btn btn-sm btn-outline",children:o.action.label})]}),t]}),jsx(yr,{basePath:s}),jsx(zt,{})]})]})};function hr(e,t){return qe(jsx(Ue,{opts:t,children:jsx("div",{dangerouslySetInnerHTML:{__html:e}})}))}function gr(e,t){return qe(jsx(Ue,{opts:{title:"Repositories",basePath:t},children:e.length===0?jsxs("div",{class:"text-center py-20 text-base-content/50",children:[jsx("p",{class:"text-lg font-medium mb-1",children:"No repositories configured"}),jsx("p",{class:"text-sm",children:"Add a repository to your FRS config to get started."})]}):jsx("div",{class:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:e.map(n=>jsx("a",{href:`${t}/${n.name}`,class:"card bg-base-100 border border-base-300 hover:shadow-md no-underline transition-shadow",children:jsxs("div",{class:"card-body p-5",children:[jsx("h2",{class:"card-title text-sm font-semibold",children:n.name}),jsx("p",{class:"text-xs text-base-content/50 font-mono",children:n.path})]})},n.name))})}))}var es=[{value:"==",label:"="},{value:"!=",label:"\u2260"},{value:"in",label:"in"},{value:"not-in",label:"not in"}],Fi=[{value:"==",label:"="},{value:"!=",label:"\u2260"},{value:"<",label:"<"},{value:"<=",label:"\u2264"},{value:">",label:">"},{value:">=",label:"\u2265"},{value:"in",label:"in"},{value:"not-in",label:"not in"}],Ni=[{value:"array-contains",label:"contains"},{value:"array-contains-any",label:"contains any"}];function ji(e){switch(e){case "ZodNumber":case "ZodBigInt":case "ZodDate":return Fi;case "ZodBoolean":return es;case "ZodArray":return Ni;default:return es}}var Le="__null__";function Bi(e){return `(function(cb){var i=document.getElementById('${e}');if(!i)return;if(cb.checked){i.dataset._prev=i.value;if(i.tagName==='SELECT'){var o=i.querySelector('option[value="${Le}"]');if(!o){o=document.createElement('option');o.value='${Le}';o.textContent='\u2205 null';o.dataset._auto='1';i.appendChild(o);}o.selected=true;}else{if(i.type==='number'||i.type==='datetime-local'){i.dataset._type=i.type;i.type='text';}i.value='${Le}';i.readOnly=true;}i.style.opacity='0.55';}else{i.style.opacity='';if(i.tagName==='SELECT'){var o2=i.querySelector('option[value="${Le}"][data-_auto="1"]');if(o2)o2.remove();var prev=i.dataset._prev||'';for(var k=0;k<i.options.length;k++)i.options[k].selected=(i.options[k].value===prev);}else{if(i.dataset._type){i.type=i.dataset._type;delete i.dataset._type;}i.readOnly=false;i.value=(i.dataset._prev&&i.dataset._prev!=='${Le}')?i.dataset._prev:'';}}})(this)`}function zi(e,t){return `(function(){var h=document.getElementById('${e}');var boxes=document.querySelectorAll('input[data-enum-group="${t}"]');h.value=Array.from(boxes).filter(function(b){return b.checked;}).map(function(b){return b.value;}).join(',');})()`}function Kt({inputId:e,active:t}){return jsxs("label",{class:"flex items-center gap-1 cursor-pointer select-none text-xs text-base-content/60 hover:text-base-content border border-base-300 rounded-md px-1.5 py-1 shrink-0 leading-none h-8",title:"Filter where field IS NULL",children:[jsx("input",{type:"checkbox",class:"checkbox checkbox-xs",checked:t,onchange:Bi(e)}),jsx("span",{children:"\u2205"})]})}function qi({col:e,active:t}){let n=t?.value??"",r=n===Le,o=`fv_input_${e.name.replace(/\./g,"__")}`,s=t?.op,a=s==="in"||s==="not-in";if(e.enumValues&&e.enumValues.length>0){if(a){let l=new Set(n.split(",").map(u=>u.trim()).filter(Boolean)),c=`eg_${e.name.replace(/\./g,"__")}`;return jsxs("div",{class:"flex flex-wrap items-center gap-1 w-full",children:[jsx("input",{type:"hidden",id:o,name:`fv_${e.name}`,value:n}),e.enumValues.map(u=>jsxs("label",{class:"flex items-center gap-1 text-xs border border-base-300 rounded px-2 cursor-pointer hover:bg-base-200",children:[jsx("input",{type:"checkbox",class:"checkbox checkbox-xs",value:u,checked:l.has(u),"data-enum-group":c,onchange:zi(o,c)}),jsx("span",{children:u})]},u))]})}return jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxs("select",{id:o,name:`fv_${e.name}`,class:"select select-sm select-bordered w-full",style:r?"opacity:0.55":void 0,children:[jsx("option",{value:"",selected:n===""&&!r,children:"\u2014"}),e.enumValues.map(l=>jsx("option",{value:l,selected:n===l,children:l},l)),e.nullable&&jsx("option",{value:Le,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsx(Kt,{inputId:o,active:r})]})}if(e.zodType==="ZodBoolean")return jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxs("select",{id:o,name:`fv_${e.name}`,class:"select select-sm select-bordered w-full",style:r?"opacity:0.55":void 0,children:[jsx("option",{value:"",selected:n===""&&!r,children:"\u2014"}),jsx("option",{value:"true",selected:n==="true",children:"true"}),jsx("option",{value:"false",selected:n==="false",children:"false"}),e.nullable&&jsx("option",{value:Le,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsx(Kt,{inputId:o,active:r})]});if(e.zodType==="ZodArray"){let l=t?.op==="array-contains-any";return jsx("input",{id:o,type:"text",name:`fv_${e.name}`,value:n,placeholder:l?"val1, val2, \u2026":"value",class:"input input-sm input-bordered w-full"})}return e.zodType==="ZodNumber"||e.zodType==="ZodBigInt"?jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsx("input",{id:o,type:r?"text":"number",name:`fv_${e.name}`,value:n,placeholder:"value",class:"input input-sm input-bordered w-full",readOnly:r||void 0,style:r?"opacity:0.55":void 0,"data-_type":r?"number":void 0}),e.nullable&&jsx(Kt,{inputId:o,active:r})]}):e.zodType==="ZodDate"?jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsx("input",{id:o,type:r?"text":"datetime-local",name:`fv_${e.name}`,value:n,class:"input input-sm input-bordered w-full",readOnly:r||void 0,style:r?"opacity:0.55":void 0,"data-_type":r?"datetime-local":void 0}),e.nullable&&jsx(Kt,{inputId:o,active:r})]}):jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsx("input",{id:o,type:"text",name:`fv_${e.name}`,value:n,placeholder:"value",class:"input input-sm input-bordered w-full",readOnly:r||void 0,style:r?"opacity:0.55":void 0}),e.nullable&&jsx(Kt,{inputId:o,active:r})]})}function br({action:e,columnMeta:t,activeFilters:n,isGroup:r}){let o=Object.fromEntries(n.map(c=>[c.field,c])),s=n.length>0,a=n.length>=2||r&&s,l=t.filter(c=>c.zodType!=="ZodObject"&&c.zodType!=="ZodRecord");return jsxs("details",{class:"collapse collapse-arrow bg-base-100 border border-base-300 rounded-box mb-6 shadow-sm",open:s?true:void 0,children:[jsxs("summary",{class:"collapse-title text-sm font-medium py-2 min-h-0",children:["Filters",s&&jsxs("span",{class:"badge badge-primary badge-sm ml-2",children:[n.length," active"]})]}),jsx("div",{class:"collapse-content pb-4 pt-2",children:jsxs("form",{method:"get",action:e,children:[jsx("div",{class:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:l.map(c=>{let u=ji(c.zodType),p=o[c.name],f=p?.op??u[0].value;return jsxs("div",{class:"flex flex-col gap-1.5",children:[jsx("label",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:c.name}),jsxs("div",{class:"flex gap-1.5",children:[u.length>1?jsx("select",{name:`fo_${c.name}`,class:"select select-sm select-bordered w-20 shrink-0",children:u.map(b=>jsx("option",{value:b.value,selected:b.value===f,children:b.label},b.value))}):jsx("input",{type:"hidden",name:`fo_${c.name}`,value:u[0].value}),jsx(qi,{col:c,active:p})]})]},c.name)})}),jsxs("div",{class:"flex flex-wrap gap-2 mt-4 pt-3 border-t border-base-200 items-center",children:[jsx("button",{type:"submit",class:"btn btn-sm btn-primary",children:"Apply"}),s&&jsx("a",{href:e,class:"btn btn-sm btn-ghost",children:"Clear"}),a&&jsxs("span",{class:"text-xs text-warning ml-auto flex items-center gap-1",children:[jsx("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-4 w-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:jsx("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),r?"Collection group queries require a composite index":"Multiple filters may require a composite index"]})]})]})})]})}function wr(e,t,n,r,o,s){let a=n==="create"?`Create ${e}`:`Edit ${e} / ${r??""}`,l=n==="create"?[{label:"Repositories",href:o},{label:e,href:`${o}/${e}`},{label:"New document"}]:[{label:"Repositories",href:o},{label:e,href:`${o}/${e}`},{label:`Edit ${r??""}`}];return qe(jsx(Ue,{opts:{title:a,breadcrumb:l,basePath:o,flash:s},children:jsx("div",{class:"card bg-base-100 border border-base-300",children:jsx("div",{class:"card-body p-6",children:jsx("div",{dangerouslySetInnerHTML:{__html:t}})})})}))}xn();fr();function xr(e,t,n){let r=new URLSearchParams;for(let o of e)r.set(`fv_${o.field}`,o.value),r.set(`fo_${o.field}`,o.op);return t&&(r.set("ob",t.field),r.set("od",t.dir)),n&&r.set("ps",String(n)),r}function ts(e,t,n,r,o){let s=xr(e,r,o);return s.set("cursor",t),s.set("dir",n),`?${s.toString()}`}function Ui(e,t,n,r){let o=xr(n,void 0,r);return t?.field===e?t.dir==="asc"&&(o.set("ob",e),o.set("od","desc")):(o.set("ob",e),o.set("od","asc")),`?${o.toString()}`}function Li(e,t,n){return `?${xr(t,n,e).toString()}`}function Rr(e,t,n,r,o,s,a=[],l=[],c=false,u=[],p,f,b,h,w,T,S,I=false,A=true){let O=`${r}/${e}`,x=`${O}/create`,d={};if(S)for(let R of n)d[R]=qt(Ut(S,R));let y=(T??[]).filter(R=>true),i=y.length>0,g=c,m=g||i,C=y.map(R=>{let P=Ut(S,R),_=qt(P),$=a.find(M=>M.name===R);return {name:R,type:_,enumValues:$?.enumValues??null,nullable:$?.nullable??false}}),k=[];return S&&(k=Re(S).filter(P=>y.includes(P.name))),qe(jsxs(Ue,{opts:{title:e,breadcrumb:[{label:"Repositories",href:r},{label:e}],basePath:r,flash:s},children:[a.length>0&&jsx(br,{action:O,columnMeta:a,activeFilters:l,isGroup:h}),b&&jsxs("div",{role:"alert",class:`alert ${b.type==="index"?"alert-warning":"alert-error"} mb-6 shadow-sm`,children:[jsx("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-6 w-6 shrink-0 stroke-current",fill:"none",viewBox:"0 0 24 24",children:b.type==="index"?jsx("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"}):jsx("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"})}),jsxs("div",{class:"flex-1",children:[jsx("h3",{class:"font-bold",children:b.type==="index"?"Composite index required":"Query failed"}),jsx("div",{class:"text-sm",children:b.message})]}),b.indexUrl&&jsx("a",{href:b.indexUrl,target:"_blank",rel:"noopener noreferrer",class:"btn btn-sm btn-outline",children:"Create Index \u2192"})]}),jsxs("div",{class:"flex flex-wrap justify-between items-center mb-4 gap-3","data-frs-toolbar":true,children:[jsxs("div",{class:"flex items-center gap-3",children:[jsxs("span",{class:"text-sm text-base-content/60",children:[t.length,typeof w=="number"&&jsxs(Fragment,{children:[" ","of"," ",jsx("span",{class:"font-semibold text-base-content/80",children:w})]})," ","document",(typeof w=="number"?w:t.length)!==1&&"s"]}),jsxs("div",{class:"flex items-center gap-1.5 text-sm text-base-content/60",children:[jsx("span",{children:"Rows"}),jsx("div",{class:"join",children:[10,25,50,100].map(R=>jsx("a",{href:Li(R,l,p),class:`join-item btn btn-xs ${f===R?"btn-active btn-primary":"btn-outline"}`,children:R},R))})]})]}),jsxs("div",{class:"flex gap-2",children:[A&&jsxs("div",{class:"dropdown dropdown-end","data-frs-backfill-menu":true,children:[jsxs("button",{type:"button",tabIndex:0,class:"btn btn-outline btn-sm gap-1",children:["Backfill",jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",class:"size-4 opacity-70",children:jsx("path",{"fill-rule":"evenodd",d:"M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z","clip-rule":"evenodd"})})]}),jsxs("ul",{tabIndex:0,class:"dropdown-content menu menu-sm bg-base-100 text-base-content rounded-box z-50 mt-1 w-52 p-1 shadow-lg border border-base-300",children:[jsx("li",{children:jsxs("form",{method:"post",action:`${O}/_bulk/backfill?dryRun=true`,class:"p-0 block",children:[jsx("input",{type:"hidden",name:"dryRun",value:"1"}),jsx("button",{type:"submit",class:"w-full text-left px-3 py-1.5 rounded",children:"Dry-run backfill"})]})}),jsx("li",{children:jsx("form",{method:"post",action:`${O}/_bulk/backfill`,onsubmit:"return confirm('Backfill entire repository? This will scan all documents and fill missing system keys.')",class:"p-0 block",children:jsx("button",{type:"submit",class:"w-full text-left px-3 py-1.5 rounded text-warning",children:"Run backfill"})})})]})]}),jsx("a",{href:x,class:"btn btn-primary btn-sm",children:"+ New"})]})]}),m&&jsxs("div",{class:"hidden mb-3 alert alert-info py-2 px-3","data-frs-bulk-bar":true,"data-frs-repo":e,"data-frs-total":typeof w=="number"?String(w):"","data-frs-page-size":String(f??t.length),"data-frs-allow-delete":g?"1":"0","data-frs-allow-update":i?"1":"0","data-frs-fields":JSON.stringify(C),"data-frs-filters":JSON.stringify(l),children:[jsxs("div",{class:"flex-1 text-sm",children:[jsx("span",{"data-frs-bulk-summary":true,children:"0 selected"}),typeof w=="number"&&w>t.length&&jsxs("button",{type:"button",class:"ml-3 link text-sm hidden","data-frs-bulk-select-all":true,children:["Select all ",w," matching documents"]}),jsxs("span",{class:"hidden ml-3 italic","data-frs-bulk-all-active":true,children:["All ",w??"?"," matching documents are selected."," ",jsx("button",{type:"button",class:"link","data-frs-bulk-clear":true,children:"Clear selection"})]})]}),jsxs("div",{class:"flex gap-2",children:[i&&jsx("button",{type:"button",class:"btn btn-sm btn-outline","data-frs-bulk-action":"update",children:"Update field\u2026"}),g&&jsx("button",{type:"button",class:"btn btn-sm btn-error btn-outline","data-frs-bulk-action":"delete",children:"Delete"})]})]}),jsx("div",{class:"overflow-x-auto rounded-box border border-base-300 bg-base-100","data-frs-table-wrap":true,children:jsxs("table",{class:"table table-sm w-full","data-frs-table":true,"data-frs-repo":e,"data-frs-colcount":n.length,children:[jsx("thead",{children:jsxs("tr",{class:"bg-base-200/50",children:[m&&jsx("th",{class:"w-8",children:jsx("input",{type:"checkbox",class:"checkbox checkbox-xs checkbox-primary","data-frs-select-page":true,"aria-label":"Select all on this page"})}),[...n].map((R,P)=>{let _=p?.field===R,$=_?p.dir==="asc"?" \u25B2":" \u25BC":"";return jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:jsxs("a",{href:Ui(R,p,l,f),class:`hover:text-base-content inline-flex items-center gap-0.5${_?" text-primary font-bold":""}`,children:[R,$]})},P)}),u.map((R,P)=>jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:R.column},`rel-${P}`)),jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide text-right",children:"Actions"})]})}),jsx("tbody",{children:t.length===0?jsx("tr",{children:jsx("td",{colspan:n.length+u.length+1+(m?1:0),class:"text-center py-16 text-base-content/40",children:"No documents found"})}):t.map((R,P)=>{let _=String(R.docId??R.id??""),$=`${r}/${e}/${encodeURIComponent(_)}/edit`,M=`${r}/${e}/${encodeURIComponent(_)}/delete`;return jsxs("tr",{class:"hover","data-frs-row-id":_,children:[m&&jsx("td",{class:"align-middle py-2",children:jsx("input",{type:"checkbox",class:"checkbox checkbox-xs checkbox-primary","data-frs-select-row":true,value:_,"aria-label":`Select ${_}`})}),n.map((v,E)=>{let F=R[v],H=d[v],D=H?Lt(H,F):null;return jsx("td",{class:"align-top py-2",children:jsx(ht,{val:F,mismatch:D})},E)}),u.map((v,E)=>{let F=R[v.key];if(F==null||F==="")return jsx("td",{class:"py-2"},`rel-${E}`);let H=v.type==="one"?`${r}/${v.targetRepo}/${encodeURIComponent(String(F))}/edit`:`${r}/${v.targetRepo}?fv_${v.targetKey}=${encodeURIComponent(String(F))}`;return jsx("td",{class:"align-middle py-2",children:jsx("a",{href:H,class:"btn btn-xs btn-ghost btn-outline","data-frs-relation":true,"data-frs-rel-type":v.type,"data-frs-rel-repo":v.targetRepo,"data-frs-rel-fk":v.targetKey,"data-frs-rel-val":String(F),"data-frs-rel-label":v.column,children:v.column})},`rel-${E}`)}),jsx("td",{class:"align-middle text-right whitespace-nowrap py-2",children:jsxs("div",{class:"flex gap-1 justify-end",children:[jsx("a",{href:$,class:"btn btn-xs btn-outline",children:"Edit"}),I&&jsx("a",{href:`${r}/${e}/${encodeURIComponent(_)}/history`,class:"btn btn-xs btn-outline",title:"View change history",children:"History"}),c&&jsx("form",{method:"post",action:M,onsubmit:"return confirm('Delete this document?')",children:jsx("button",{type:"submit",class:"btn btn-xs btn-error btn-outline",children:"Delete"})})]})})]},P)})})]})}),(o.hasPrev||o.hasNext)&&jsxs("div",{class:"flex flex-col items-center mt-6 gap-2",children:[jsxs("div",{class:"flex justify-center items-center gap-2",children:[o.hasPrev?jsx("a",{href:ts(l,o.prevCursor,"prev",p,f),class:"btn btn-sm btn-outline",children:"\u2190 Previous"}):jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"\u2190 Previous"}),o.hasNext?jsx("a",{href:ts(l,o.nextCursor,"next",p,f),class:"btn btn-sm btn-outline",children:"Next \u2192"}):jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"Next \u2192"})]}),typeof w=="number"&&jsxs("div",{class:"text-xs text-base-content/50",children:[w," total document",w!==1?"s":"",l.length>0?" matching filters":""]})]}),m&&i&&jsxs("dialog",{id:"frs-bulk-update-modal",class:"modal",children:[jsxs("div",{class:"modal-box",children:[jsx("h3",{class:"font-bold text-lg mb-3",children:"Bulk update field"}),jsx("p",{class:"text-sm text-base-content/60 mb-4","data-frs-bulk-update-summary":true,children:"Update one field on the selected documents."}),jsxs("form",{method:"dialog","data-frs-bulk-update-form":true,"data-frs-form":true,children:[jsxs("label",{class:"form-control w-full mb-3",children:[jsx("div",{class:"label",children:jsx("span",{class:"label-text text-xs uppercase tracking-wide",children:"Field"})}),jsxs("select",{class:"select select-bordered select-sm w-full",name:"field",required:true,"data-frs-bulk-field-select":true,children:[jsx("option",{value:"",children:"\u2014 Select a field \u2014"}),y.map(R=>jsx("option",{value:R,children:R},R))]})]}),jsx("div",{class:"mb-4","data-frs-bulk-value-container":true}),jsxs("div",{class:"modal-action",children:[jsx("button",{type:"button",class:"btn btn-sm btn-ghost","data-frs-bulk-update-cancel":true,children:"Cancel"}),jsx("button",{type:"submit",class:"btn btn-sm btn-primary","data-frs-bulk-update-submit":true,children:"Apply"})]})]})]}),jsx("form",{method:"dialog",class:"modal-backdrop",children:jsx("button",{children:"close"})})]}),jsx("div",{class:"hidden","data-frs-bulk-templates":true,children:k.map(R=>jsx("div",{"data-frs-bulk-template-for":R.name,dangerouslySetInnerHTML:{__html:jt(R)}},R.name))})]}))}function Zt(e,t){return hr(e,t)}function Sr(e,t){return gr(e,t)}function vr(e,t,n,r,o,s,a,l,c,u,p,f,b,h,w,T,S,I,A){return Rr(e,t,n,r,o,s,a,l,c,u,p,f,b,h,w,T,S,I,A)}function Ke(e,t,n,r,o,s){return wr(e,t,n,r,o,s)}async function ns(e,t){if(t)try{let n=e.repo.ref,r=n?.firestore;if(t.startsWith("{"))try{let o=JSON.parse(t);if(o.docPath&&r&&typeof r.doc=="function"){let s=await r.doc(o.docPath).get();if(s.exists)return s}o.docId&&(t=o.docId);}catch{}if(t.includes("/")&&r&&typeof r.doc=="function"){let o=await r.doc(t).get();if(o.exists)return o}if(typeof n.doc=="function"){let o=await n.doc(t).get();if(o.exists)return o}}catch{}}function Sn(e,t){return Je(e,{pathKey:t.pathKey,documentKey:t.documentKey??"docId",parentKeys:t.parentKeys,documentPathTemplate:t.documentPathTemplate,isGroup:t.isGroup})}async function gt(e,t){let n=e.documentKey??"docId",r=`by${n.charAt(0).toUpperCase()}${n.slice(1)}`;if(typeof e.repo.get[r]=="function")try{let s=await e.repo.get[r](t);if(s)return s}catch{}return (await e.repo.query.by({where:[[n,"==",t]],limit:1}))[0]??null}function Tr(e,t,n){let r=e.documentKey??"docId",o=Bt(n,{ref:e.repo.ref,path:e.path,isGroup:!!e.isGroup,filters:[{field:r,op:"==",value:t}]});return o.type==="index"?{type:"warning",message:"Loading this document requires a composite index that does not exist yet.",...o.indexUrl?{action:{href:o.indexUrl,label:"Create Index \u2192",external:true}}:{}}:{type:"error",message:o.message}}function L(e,t,n=200){e.status(n).set("Content-Type","text/html; charset=utf-8").send(t);}function tt(e,t){e.status(302).set("Location",t).send("");}function vn(e,t){let n=t.shape,r={};for(let[o,s]of Object.entries(n)){let a=Ar(s),l=J(a),c=l==="ZodObject",u=a,p=false;if(l==="ZodUnion"){let h=Ft(a);h.some(T=>J(T)==="ZodDate")&&(p=true);let w=h.find(T=>{if(J(T)==="ZodObject"){let S=me(T);return "latitude"in S&&"longitude"in S}return false});w&&(c=true,u=w);}if(e[o+"__isnull"]==="1"){r[o]=null;continue}if(c){let h={},w=false;for(let[I,A]of Object.entries(e))I.startsWith(`${o}.`)&&(h[I.slice(o.length+1)]=A,w=true);if(w){r[o]=vn(h,u);continue}let T=e[o],S=Array.isArray(T)?T[T.length-1]:T;if(S)try{r[o]=JSON.parse(S);}catch{r[o]=S;}continue}let f=e[o],b=Array.isArray(f)?f[f.length-1]:f;if(b===void 0||b===""){l==="ZodBoolean"&&(r[o]=false);continue}if(p){r[o]=new Date(b);continue}switch(l){case "ZodBoolean":b==="__null__"?r[o]=null:r[o]=b==="true"||b==="on"||b==="1";break;case "ZodNumber":case "ZodBigInt":r[o]=Number(b);break;case "ZodDate":r[o]=new Date(b);break;case "ZodArray":try{r[o]=JSON.parse(b);}catch{r[o]=b;}break;default:if(b.startsWith("{")||b.startsWith("["))try{r[o]=JSON.parse(b);break}catch{}r[o]=b;}}return r}function rs(e){let t=null;if(e instanceof Date)t=e;else if(typeof e=="object"&&e!==null&&typeof e.toDate=="function")t=e.toDate();else if(typeof e=="object"&&e!==null&&"_seconds"in e&&"_nanoseconds"in e)t=new Date(e._seconds*1e3+Math.floor(e._nanoseconds/1e6));else if(typeof e=="string"||typeof e=="number"){let r=new Date(e);isNaN(r.getTime())||(t=r);}if(!t||isNaN(t.getTime()))return null;let n=r=>String(r).padStart(2,"0");return `${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`}function ss(e){let t=e;for(;;){let n=J(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=ye(t);else if(n==="ZodEffects"||n==="ZodPipe"||n==="ZodTransform"){let r=$t(t);if(!r)return n;t=r;}else return n}}function Ar(e){let t=e;for(;;){let n=J(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=ye(t);else if(n==="ZodEffects"||n==="ZodPipe"||n==="ZodTransform"){let r=$t(t);if(!r)return t;t=r;}else return t}}function as(e){let t=e;for(;;){let n=J(t);if(n==="ZodOptional"||n==="ZodNullable")return true;if(n==="ZodDefault"){t=ye(t);continue}return false}}function is(e){let t=Ar(e),n=J(t);if(n==="ZodEnum"){let r=Ht(t);return r.length>0?r:void 0}if(n==="ZodNativeEnum"){let r=_t(t),o=Object.values(r).filter(s=>typeof s=="string");return o.length>0?o:void 0}if(n==="ZodLiteral"){let r=Mt(t);return typeof r=="string"?[r]:void 0}}function cs(e,t,n=""){let r={};for(let o of Object.keys(t.shape)){let s=n?`${n}.${o}`:o,a=e[o];if(a===null){r[s]="__null__";continue}if(a===void 0)continue;let l=Ar(t.shape[o]),c=J(l),u=c==="ZodObject",p=l,f=false;if(c==="ZodUnion"){let b=Ft(l);b.some(w=>J(w)==="ZodDate")&&(f=true);let h=b.find(w=>{if(J(w)==="ZodObject"){let T=me(w);return "latitude"in T&&"longitude"in T}return false});h&&(u=true,p=h);}if(u&&typeof a=="object"&&a!==null&&!Array.isArray(a)&&!("_seconds"in a)&&typeof a.toDate!="function"){let b=cs(a,p,s);Object.assign(r,b);}else if(c==="ZodDate"||f){let b=rs(a);b!==null&&(r[s]=b);}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)&&("_seconds"in a||typeof a.toDate=="function")){let b=rs(a);r[s]=b??JSON.stringify(a,null,2);}else typeof a=="object"?r[s]=JSON.stringify(a,null,2):r[s]=String(a);}return r}function Cr(e,t){return e.map(n=>({...n,defaultValue:t[n.name]??n.defaultValue,nested:n.nested?Cr(n.nested,t):void 0}))}function Wi(e,t){let n=new Set(["==","!=","<","<=",">",">=","in","not-in","array-contains","array-contains-any"]),r=[];for(let[o,s]of Object.entries(e)){if(!o.startsWith("fv_"))continue;let a=o.slice(3);if(!t.has(a))continue;let l=(s??"").trim();if(!l)continue;let c=e[`fo_${a}`]??"==",u=n.has(c)?c:"==";r.push({field:a,op:u,value:l});}return r}function os(e){let t="__null__",n=r=>r===t?null:r==="true"?true:r==="false"?false:r!==""&&!isNaN(Number(r))?Number(r):r;return e.map(r=>{if(r.op==="array-contains-any"||r.op==="in"||r.op==="not-in"){let o=r.value.split(",").map(s=>s.trim()).filter(s=>s!==""&&s!==t).map(s=>n(s));return [r.field,r.op,o]}return [r.field,r.op,n(r.value)]})}function ls(e,t,n=""){let r=[];for(let o of e){let s=n?`${n}.${o}`:o,a=t.shape[o];if(!a){r.push({name:s,zodType:"ZodString"});continue}let l=ss(a);if(l==="ZodObject"){let c=a;for(;;){let p=J(c);if(p==="ZodOptional"||p==="ZodNullable"||p==="ZodDefault")c=ye(c);else break}let u=me(c);r.push(...ls(Object.keys(u),c,s));}else r.push({name:s,zodType:l,nullable:as(a),enumValues:is(a)});}return r}function Qi(e,t){let n=t.split("."),r=e;for(let o of n){for(;;){let a=J(r);if(a==="ZodOptional"||a==="ZodNullable"||a==="ZodDefault")r=ye(r);else break}let s=me(r);if(!(o in s))return null;r=s[o];}return r}function nt(e,t){if(!t||t.length===0)return e;let n=[],r=new Map;for(let s of t){let a=s.indexOf(".");if(a===-1)n.push(s);else {let l=s.slice(0,a),c=s.slice(a+1);r.has(l)||r.set(l,[]),r.get(l).push(c);}}let o={};for(let s of n)s in e.shape&&(o[s]=e.shape[s]);for(let[s,a]of r){if(!(s in e.shape))continue;let l=e.shape[s];for(;;){let c=J(l);if(c==="ZodOptional"||c==="ZodNullable"||c==="ZodDefault")l=ye(l);else break}if(J(l)!=="ZodObject"){o[s]=e.shape[s];continue}o[s]=nt(l,a);}return z.object(o)}function Pe(e,t,n){return Oe(e,t,n)}function ds(e,t,n){let r=new Set,o=(x,d)=>{let y=Pe(x,t,n),i=Object.values(e).map(g=>({name:g.name,path:g.path}));L(d,Sr(i,y));},s=async(x,d)=>{let y=x.params.repoName;if(!y){L(d,"Bad request",400);return}let i=e[y];if(!i){L(d,"Repository not found",404);return}let g=i.pageSize??25,m=x.query??{},C=m.cursor,k=m.dir==="prev"?"prev":"next",R=m.ob??"",P=m.od==="desc"?"desc":"asc",_=R?{field:R,dir:P}:void 0,$=parseInt(m.ps??""),M=Number.isFinite($)&&$>0?Math.min($,200):g,v=i.listColumns??Object.keys(i.schema.shape),E=i.documentKey??"docId",F=[E,...v.filter(re=>re!==E)];_&&(new Set([E,...v]).has(_.field)||(_=void 0));let H=i.filterableFields?(()=>{let re=[];for(let ie of i.filterableFields)(ie.includes(".")||v.includes(ie))&&re.push(ie);return re})():v,D=(()=>{let re=[];for(let ie of H)if(ie.includes(".")){let fe=Qi(i.schema,ie);re.push({name:ie,zodType:fe?ss(fe):"ZodString",nullable:fe?as(fe):false,enumValues:fe?is(fe):void 0});}else re.push(...ls([ie],i.schema));return re})(),N=new Set(D.map(re=>re.name)),j=Wi(m,N),z=os(j),te;C&&(te=await ns(i,C));let[K,$e]=await Promise.all([i.repo.query.paginate({pageSize:M,cursor:te,direction:k,...z.length>0?{where:z}:{},..._?{orderBy:[{field:_.field,direction:_.dir}]}:{}}).catch(re=>({queryError:Bt(re,{ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:j,sort:_})})),i.repo.aggregate.count(z.length>0?{where:z}:{}).catch(()=>{})]),Se="queryError"in K,W=Se?[]:K.data,X=Se?"":K.nextCursor?.ref?.path??K.nextCursor?.id??"",oe=Se?"":K.prevCursor?.ref?.path??K.prevCursor?.id??"",se=Se?K.queryError:void 0,we=Pe(x,t,n),ne,be=m.flash;if(be==="created")ne={type:"success",message:"Document created successfully."};else if(be==="updated")ne={type:"success",message:"Document updated successfully."};else if(be==="deleted")ne={type:"success",message:"Document deleted successfully."};else if(be==="backfilled"){let re=Ie(m.scanned),ie=Ie(m.written),fe=Ie(m.skipped);ne={type:"success",message:re!==void 0&&ie!==void 0&&fe!==void 0?`Backfill complete: scanned ${re}, updated ${ie}, skipped ${fe}.`:"Repository backfilled successfully."};}else if(be==="backfill_dryrun"){let re=Ie(m.scanned),ie=Ie(m.written),fe=Ie(m.skipped);ne={type:"success",message:re!==void 0&&ie!==void 0&&fe!==void 0?`Dry run complete: scanned ${re}, would update ${ie}, skipped ${fe}.`:"Dry run complete."};}else if(be==="backfill_partial"){let re=Ie(m.scanned),ie=Ie(m.written),fe=Ie(m.skipped),Hn=Ie(m.failed),qs=re!==void 0&&ie!==void 0&&fe!==void 0&&Hn!==void 0;ne={type:ie!==void 0&&ie>0?"warning":"error",message:qs?`Backfill finished with ${Hn} failure${Hn===1?"":"s"} (scanned ${re}, updated ${ie}, skipped ${fe}). Check server logs for details.`:"Backfill finished with failures. Check server logs for details."};}else be==="backfill_busy"&&(ne={type:"warning",message:"A backfill is already running for this repository. Please wait for it to finish."});L(d,vr(i.name,W,F,we,{hasPrev:Se?false:K.hasPrevPage,hasNext:Se?false:K.hasNextPage,prevCursor:oe,nextCursor:X},ne,D,j,i.allowDelete??false,i.relationalMeta,_,M,se,i.isGroup,$e,i.mutableFields,i.schema,i.historyEnabled,i.allowBackfill!==false));},a=(x,d)=>{let y=x.params.repoName;if(!y){L(d,"Bad request",400);return}let i=e[y];if(!i){L(d,"Repository not found",404);return}let g=Pe(x,t,n),m=nt(i.schema,i.createFields),C=Re(m),k=`${g}/${i.name}/create`,R=ze(C,k,"POST","Create document");L(d,Ke(i.name,R,"create",null,g));},l=async(x,d)=>{let y=x.params.repoName;if(!y){L(d,"Bad request",400);return}let i=e[y];if(!i){L(d,"Repository not found",404);return}let g=Pe(x,t,n),m=x.body??{},C=vn(m,i.schema),k=nt(i.schema,i.createFields),R=k.safeParse(C);if(!R.success){let P=Re(k),_=`${g}/${i.name}/create`,$=ze(P,_,"POST","Create document"),M=R.error.issues.map(v=>`${v.path.join(".")}: ${v.message}`).join(", ");L(d,Ke(i.name,$,"create",null,g,{type:"error",message:`Validation error: ${M}`}),422);return}try{if(i.isGroup&&i.parentKeys&&i.parentKeys.length>0){let P={...R.data},_=i.parentKeys.filter($=>P[$]===void 0||P[$]===null||typeof P[$]=="string"&&P[$].trim()==="");if(_.length>0)throw new Error(`Missing parent key(s) for subcollection create: ${_.join(", ")}`);if(typeof i.repo.create=="function")await i.repo.create(P);else {let $=i.parentKeys.map(E=>String(P[E])),M=i.documentKey??"docId",v=P[M]||Be();await i.repo.set(...$,v,P);}}else await i.repo.create(R.data);tt(d,`${g}/${i.name}?flash=created`);}catch(P){let _=nt(i.schema,i.createFields),$=Re(_),M=`${g}/${i.name}/create`,v=ze($,M,"POST","Create document");L(d,Ke(i.name,v,"create",null,g,{type:"error",message:`Save error: ${P.message}`}),500);}},c=async(x,d)=>{let y=x.params.repoName,i=x.params.id;if(!y||!i){L(d,"Bad request",400);return}let g=e[y];if(!g){L(d,"Repository not found",404);return}let m=Pe(x,t,n),C=null;try{C=await gt(g,i);}catch(M){let v=Tr(g,i,M),E=Xe(M)?424:500;L(d,Zt("",{title:`Edit ${g.name} / ${i}`,basePath:m,breadcrumb:[{label:"Repositories",href:m},{label:g.name,href:`${m}/${g.name}`},{label:`Edit ${i}`}],flash:v}),E);return}if(!C){L(d,"Document not found",404);return}let k=cs(C,g.schema),R=nt(g.schema,g.mutableFields),P=Cr(Re(R),k),_=`${m}/${g.name}/${encodeURIComponent(i)}/edit`,$=ze(P,_,"POST","Save changes");L(d,Ke(g.name,$,"edit",i,m));},u=async(x,d)=>{let y=x.params.repoName,i=x.params.id;if(!y||!i){L(d,"Bad request",400);return}let g=e[y];if(!g){L(d,"Repository not found",404);return}let m=Pe(x,t,n),C=x.body??{},k=vn(C,g.schema),R=nt(g.schema,g.mutableFields),_=R.partial().safeParse(k);if(!_.success){let $=Object.fromEntries(Object.entries(C).map(([H,D])=>[H,Array.isArray(D)?D.join(","):D??""])),M=Cr(Re(R),$),v=`${m}/${g.name}/${encodeURIComponent(i)}/edit`,E=ze(M,v,"POST","Save changes"),F=_.error.issues.map(H=>`${H.path.join(".")}: ${H.message}`).join(", ");L(d,Ke(g.name,E,"edit",i,m,{type:"error",message:`Validation error: ${F}`}),422);return}try{let $=await gt(g,i),M=($&&Sn($,g))??[i];await g.repo.update(...M,_.data),tt(d,`${m}/${g.name}?flash=updated`);}catch($){let M=nt(g.schema,g.mutableFields),v=Re(M),E=`${m}/${g.name}/${encodeURIComponent(i)}/edit`,F=ze(v,E,"POST","Save changes"),H=Xe($)?Tr(g,i,$):{type:"error",message:`Save error: ${$.message}`},D=Xe($)?424:500;L(d,Ke(g.name,F,"edit",i,m,H),D);}},p=async(x,d)=>{let y=x.params.repoName,i=x.params.id;if(!y||!i){L(d,"Bad request",400);return}let g=e[y];if(!g){L(d,"Repository not found",404);return}if(!g.allowDelete){L(d,"Delete is not allowed for this repository",403);return}let m=Pe(x,t,n);try{let C=await gt(g,i),k=(C&&Sn(C,g))??[i];await g.repo.delete(...k),tt(d,`${m}/${g.name}?flash=deleted`);}catch(C){let k=Xe(C)?Tr(g,i,C):{type:"error",message:`Delete error: ${C.message}`},R=Xe(C)?424:500;L(d,Zt("",{title:`Delete ${g.name} / ${i}`,basePath:m,breadcrumb:[{label:"Repositories",href:m},{label:g.name,href:`${m}/${g.name}`},{label:`Delete ${i}`}],flash:k}),R);}},f=async(x,d)=>{let y=x.params.repoName;if(!y){L(d,"Bad request",400);return}let i=e[y];if(!i){L(d,"Repository not found",404);return}let g=Pe(x,t,n),m=x.query,C=m?.type==="many"?"many":"one",k=Math.max(1,Math.min(100,Number(m?.ps??25)||25)),R=i.listColumns??Object.keys(me(i.schema)),{PanelOne:P,PanelMany:_}=await Promise.resolve().then(()=>(mr(),Yo)),{renderToString:$}=await import('hono/jsx/dom/server');if(C==="one"){let D=String(m?.id??"");if(!D){L(d,"<div class='p-6 text-error'>Missing id parameter.</div>",400);return}try{let N=await gt(i,D),j=$(P({doc:N,repoName:i.name,basePath:g,schema:i.schema,columns:R}));L(d,j);}catch(N){L(d,`<div class='p-6 text-error text-sm'>Error: ${N.message}</div>`,500);}return}let M=String(m?.fk??""),v=String(m?.fv??"");if(!M||!v){L(d,"<div class='p-6 text-error'>Missing fk/fv parameters.</div>",400);return}let E=m?.cursor??"",F=m?.dir==="prev"?"prev":"next",H;E&&(H=await ns(i,E));try{let D=await i.repo.query.paginate({pageSize:k,cursor:H,direction:F,where:[[M,"==",Yi(v)]]}),N=$(_({docs:D.data,repoName:i.name,basePath:g,fk:M,fv:v,columns:R,schema:i.schema,pagination:{hasPrev:D.hasPrevPage,hasNext:D.hasNextPage,prevCursor:D.prevCursor?.ref?.path??D.prevCursor?.id??"",nextCursor:D.nextCursor?.ref?.path??D.nextCursor?.id??"",pageSize:k}}));L(d,N);}catch(D){L(d,`<div class='p-6 text-error text-sm'>Error: ${D.message}</div>`,500);}},b=async(x,d)=>{let y=Gi(x),i=x.params.repoName;if(!i){y?ae(d,{error:"Bad request"},400):L(d,"Bad request",400);return}let g=e[i];if(!g){y?ae(d,{error:"Repository not found"},404):L(d,"Repository not found",404);return}if(g.allowBackfill===false){let k="Backfill is not allowed for this repository";y?ae(d,{error:k},403):L(d,k,403);return}let m=Pe(x,t,n);if(r.has(i)){y?ae(d,{error:`Backfill is already running for "${i}"`},409):tt(d,`${m}/${g.name}?flash=backfill_busy`);return}let C=Ji(x);r.add(i);try{let k=await g.repo.system.backfillKeys({dryRun:C}),R=k?.scanned??0,P=k?.written??0,_=k?.skipped??0,$=Array.isArray(k?.failures)?k.failures:[];if($.length>0&&console.error(`[admin] Backfill for "${i}" finished with ${$.length} failure(s) (scanned=${R}, written=${P}, skipped=${_}):`,$.map(v=>({path:v.path,error:kr(v.error)}))),y){let v=$.length===0?200:P>0?207:500;ae(d,{dryRun:C,scanned:R,written:P,skipped:_,failures:$.map(E=>({path:E.path,error:kr(E.error)}))},v);return}let M=new URLSearchParams({scanned:String(R),written:String(P),skipped:String(_)});$.length>0?(M.set("failed",String($.length)),tt(d,`${m}/${g.name}?flash=backfill_partial&${M.toString()}`)):C?tt(d,`${m}/${g.name}?flash=backfill_dryrun&${M.toString()}`):tt(d,`${m}/${g.name}?flash=backfilled&${M.toString()}`);}catch(k){let R=kr(k);console.error(`[admin] Backfill failed for "${i}":`,k),y?ae(d,{error:R},500):L(d,`<div class="p-6 text-error">Backfill failed: ${Vi(R)}</div>`,500);}finally{r.delete(i);}},h=async(x,d)=>{let y=[];for(let i of d){let g;if(x.isGroup||x.parentKeys?.length){let m=await gt(x,i);g=m?Sn(m,x):void 0;}g||(g=[i]);try{let m=x.repo.documentRef(...g);m&&y.push(m);}catch{}}return y},w=async(x,d)=>{let y=os(d),i=x.documentKey??"docId",g=[],m;for(;;){let C=await x.repo.query.paginate({pageSize:500,cursor:m,direction:"next",...y.length>0?{where:y}:{}});for(let k of C.data){let R=String(k[i]??k.id??"");R&&g.push(R);}if(!C.hasNextPage||!C.nextCursor)break;m=C.nextCursor;}return g},T=async(x,d)=>{let y=x.params.repoName;if(!y){ae(d,{error:"Bad request"},400);return}let i=e[y];if(!i){ae(d,{error:"Repository not found"},404);return}if(!i.allowDelete){ae(d,{error:"Delete is not allowed for this repository"},403);return}let g=x.body??{};try{let m=await I(i,g);if(m.length===0){ae(d,{deleted:0});return}let C=await h(i,m);for(let k=0;k<C.length;k+=500)await i.repo.bulk.delete(C.slice(k,k+500));ae(d,{deleted:C.length});}catch(m){ae(d,{error:m.message},500);}},S=async(x,d)=>{let y=x.params.repoName;if(!y){ae(d,{error:"Bad request"},400);return}let i=e[y];if(!i){ae(d,{error:"Repository not found"},404);return}let g=x.body??{},m=String(g.field??"");if(!m){ae(d,{error:"Missing 'field'"},400);return}if(!i.mutableFields||!i.mutableFields.includes(m)){ae(d,{error:`Field '${m}' is not bulk-updatable`},403);return}let C=i.schema.shape?.[m],k;if(C){let R=typeof i.schema=="object"&&i.schema&&"constructor"in i.schema&&i.schema.constructor.name.includes("Zod")?i.schema.pick({[m]:true}):void 0;if(!R){ae(d,{error:"Invalid schema structure"},500);return}k=vn(g.formPayload??{},R)[m];let _=C.safeParse(k);if(!_.success){ae(d,{error:`Invalid value for '${m}': ${_.error.message}`},400);return}k=_.data;}try{let R=await I(i,g);if(R.length===0){ae(d,{updated:0});return}let _=(await h(i,R)).map($=>({docRef:$,data:{[m]:k}}));for(let $=0;$<_.length;$+=500)await i.repo.bulk.update(_.slice($,$+500));ae(d,{updated:_.length});}catch(R){ae(d,{error:R.message},500);}};async function I(x,d){if(d.selectAll){let y=A(d.filters,x);return await w(x,y)}return Array.isArray(d.ids)?d.ids.filter(y=>typeof y=="string"&&!!y):[]}function A(x,d){if(!Array.isArray(x))return [];let y=new Set((d.filterableFields??Object.keys(me(d.schema))).map(m=>String(m))),i=new Set(["==","!=","<","<=",">",">=","in","not-in","array-contains","array-contains-any"]),g=[];for(let m of x)m&&typeof m=="object"&&typeof m.field=="string"&&y.has(m.field)&&typeof m.value=="string"&&i.has(String(m.op))&&g.push({field:m.field,op:m.op,value:m.value});return g}return {handleDashboard:o,handleList:s,handleCreateForm:a,handleCreateSubmit:l,handleEditForm:c,handleEditSubmit:u,handleDelete:p,handlePanel:f,handleBulkDelete:T,handleBulkUpdate:S,handleBulkBackfill:b,handleHistory:async(x,d)=>{let y=x.params.repoName,i=x.params.id;if(!y||!i){L(d,"Bad request",400);return}let g=e[y];if(!g){L(d,"Repository not found",404);return}if(!g.historyEnabled||!g.repo.history){L(d,"History not enabled for this repository",404);return}let m=Pe(x,t,n),C=g.historySubcollection??"history",k=[i];try{let D=await gt(g,i),N=D?Sn(D,g):void 0;N&&N.length>0&&(k=N);}catch{}let R=parseInt(String(x.query?.limit??"")),P=Number.isFinite(R)&&R>0?Math.min(R,500):100,_=[],$;try{_=await g.repo.history.list(...k,{limit:P});}catch(D){$=D.message;}let M=D=>String(D??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),v=D=>{if(D===void 0)return '<span class="opacity-40">undefined</span>';if(D===null)return '<span class="opacity-40">null</span>';if(typeof D=="object")try{return `<code class="text-xs">${M(JSON.stringify(D))}</code>`}catch{return M(String(D))}return M(String(D))},E=D=>D?typeof D.toDate=="function"?D.toDate().toISOString():D instanceof Date?D.toISOString():M(String(D)):"",F=D=>`<span class="badge badge-sm ${D==="create"?"badge-success":D==="delete"?"badge-error":D==="custom"?"badge-secondary":"badge-info"}">${M(D)}</span>`,H="";if(H+='<div class="flex items-center justify-between mb-4">',H+=`<a href="${m}/${g.name}/${encodeURIComponent(i)}/edit" class="btn btn-sm btn-outline">\u2190 Back to edit</a>`,H+=`<a href="${m}/${g.name}" class="btn btn-sm btn-outline">\u2190 Back to list</a>`,H+="</div>",H+=`<p class="text-sm text-base-content/60 mb-4">Subcollection: <code>${M(C)}</code> \xB7 Showing up to ${P} entries.</p>`,$)H+=`<div class="alert alert-error mb-4">${M($)}</div>`;else if(_.length===0)H+='<div class="alert">No history entries found.</div>';else {H+='<div class="overflow-x-auto"><table class="table table-zebra table-sm">',H+="<thead><tr><th>When</th><th>Op</th><th>User</th><th>Reason / Comment</th><th>Changes</th></tr></thead><tbody>";for(let D of _){let N=D.meta??{},j=[N.reason,N.comment].filter(K=>K!=null&&K!=="").map(K=>M(String(K))).join(" \u2014 "),z="",te=Object.keys(D.changes??{});if(D.custom){let K=`<strong>${M(D.custom.title)}</strong>`,$e=D.custom.key?` <code class="text-xs opacity-60">${M(D.custom.key)}</code>`:"",Se=D.custom.description?`<div class="text-xs opacity-80 mt-0.5">${M(D.custom.description)}</div>`:"";z=`<div>${K}${$e}${Se}</div>`;}else te.length===0?z='<span class="opacity-40">\u2014</span>':z='<ul class="space-y-1">'+te.map(K=>{let $e=D.changes[K];return `<li><strong>${M(K)}</strong>: ${v($e.oldValue)} \u2192 ${v($e.newValue)}</li>`}).join("")+"</ul>";H+="<tr>",H+=`<td class="whitespace-nowrap text-xs font-mono">${M(E(D.historySetAt))}</td>`,H+=`<td>${F(D.operation??"update")}</td>`,H+=`<td class="text-xs">${M(N.userEmail??N.userId??"")}</td>`,H+=`<td class="text-xs">${j}</td>`,H+=`<td>${z}</td>`,H+="</tr>";}H+="</tbody></table></div>";}L(d,Zt(H,{title:`History \u2014 ${g.name} / ${i}`,basePath:m,breadcrumb:[{label:"Repositories",href:m},{label:g.name,href:`${m}/${g.name}`},{label:`History ${i}`}]}));}}}function ae(e,t,n=200){e.status(n).set("Content-Type","application/json; charset=utf-8").send(JSON.stringify(t));}function Vi(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function kr(e){return e instanceof Error||e&&typeof e=="object"&&typeof e.message=="string"?e.message:String(e)}function Gi(e){let t=e.headers??{},n="",r="";for(let[o,s]of Object.entries(t)){let a=o.toLowerCase(),l=Array.isArray(s)?s.join(","):String(s??"");a==="accept"?n=l.toLowerCase():a==="content-type"&&(r=l.toLowerCase());}return n.includes("application/json")||r.includes("application/json")}function bt(e){if(e===true||e===1)return true;if(typeof e=="string"){let t=e.trim().toLowerCase();return t==="true"||t==="1"}return Array.isArray(e)&&e.length>0?bt(e[e.length-1]):false}function Ji(e){let t=e.query??{};if(t.dryRun!==void 0)return bt(t.dryRun);if(typeof e.url=="string"){let r=e.url.indexOf("?");if(r!==-1){let s=new URLSearchParams(e.url.slice(r+1)).get("dryRun");if(s!==null)return bt(s)}}let n=e.body;if(n&&typeof n=="object"&&!Array.isArray(n)){let r=n.dryRun;if(r!==void 0)return bt(r)}else if(typeof n=="string"&&n.trim()!==""){let r=n.trim();if(r.startsWith("{"))try{let o=JSON.parse(r);if(o&&typeof o=="object"&&!Array.isArray(o)){let s=o.dryRun;if(s!==void 0)return bt(s)}}catch{}else {let s=new URLSearchParams(r).get("dryRun");if(s!==null)return bt(s)}}return false}function Ie(e){if(e===void 0||e==="")return;let t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}function Yi(e){return e==="true"?true:e==="false"?false:e!==""&&!isNaN(Number(e))?Number(e):e}kn();async function ys(e){return typeof e.rawBody=="string"?e.rawBody:Buffer.isBuffer(e.rawBody)?e.rawBody.toString("utf8"):""}function Xi(e){let t={};if(!e)return t;for(let n of e.split("&")){let r=n.indexOf("=");if(r===-1)continue;let o=decodeURIComponent(n.slice(0,r).replace(/\+/g," ")),s=decodeURIComponent(n.slice(r+1).replace(/\+/g," ")),a=t[o];a===void 0?t[o]=s:Array.isArray(a)?a.push(s):t[o]=[a,s];}return t}function ms(e){let{basePath:t="/",repos:n,parseBody:r=true,securityHeaders:o,auth:s,middleware:a=[],httpsOptions:l}=e,c=t==="/"?"":t.replace(/\/$/,""),u={};for(let[h,w]of Object.entries(n)){if(!w.repo)throw new Error(`[createAdminServer] Repository "${h}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let T=w.schema??w.repo.schema??null;if(!T)throw new Error(`[createAdminServer] Repository "${h}" has no Zod schema. Either use createRepositoryConfig(schema)(config) or pass schema: explicitly.`);let S,I,A;if(w.fieldsConfig){let d=w.fieldsConfig;S=[],I=[],A=[];for(let[y,i]of Object.entries(d))for(let g of i)g==="filterable"?S.push(y):g==="mutable"?I.push(y):g==="create"&&A.push(y);S.length===0&&(S=void 0),I.length===0&&(I=void 0),A.length===0&&(A=void 0);}let O=(()=>{let d=w.repo._parentKeys;return d&&d.length>0?d:void 0})();if(O&&A)for(let d of O)A.includes(d)||A.push(d);let x={name:h,path:w.path,repo:w.repo,schema:T,documentKey:w.documentKey??"docId",pathKey:w.repo._pathKey??void 0,isGroup:!!w.repo._isGroup,parentKeys:O,documentPathTemplate:w.repo._documentPathTemplate??void 0,createdKey:w.repo._createdKey??void 0,listColumns:w.listColumns,pageSize:w.pageSize,filterableFields:S,mutableFields:I,createFields:A,allowDelete:w.allowDelete??false,allowBackfill:w.allowBackfill??true,historyEnabled:!!w.repo._historyConfig?.enabled,historySubcollection:(w.repo._historyConfig?.enabled&&w.repo._historySubcollection)??void 0,relationalMeta:(()=>{if(!w.relationalFields||w.relationalFields.length===0)return;let d=w.repo.relationalKeys??{},y=[];for(let i of w.relationalFields){let g=d[i.key];g&&y.push({key:g.sourceKey?String(g.sourceKey):i.key,column:i.column,targetRepo:String(g.repo),targetKey:String(g.key),type:g.type});}return y.length>0?y:void 0})()};u[h]=x;}let p=ds(u,c,un(l?.region)),f=new Me;if(o!==false&&f.use(Tn(o===void 0?{}:o)),r&&f.use(async(h,w,T)=>{let S=h,I="";if(S.headers){for(let[A,O]of Object.entries(S.headers))if(A.toLowerCase()==="content-type"){I=(Array.isArray(O)?O.join(","):String(O??"")).toLowerCase();break}}if(I.includes("application/x-www-form-urlencoded")){let A=await ys(S)||(typeof S.body=="string"?S.body:"");(A!==""||!S.body||typeof S.body!="object")&&(h.body=Xi(A));}else if(I.includes("application/json")){let A=typeof S.body=="string"?S.body:S.body===void 0?await ys(S):"";if(A)try{h.body=JSON.parse(A);}catch{}}await T();}),s)if(Pt(s)){for(let h of s.routes){let w=`${c}${h.path}`;h.method==="GET"?f.get(w,h.handler):f.post(w,h.handler);}f.use(s.middleware);}else if(typeof s=="function")f.use(s);else {let h=s.realm??"Admin",w="Basic "+Buffer.from(`${s.username}:${s.password}`).toString("base64");f.use((T,S,I)=>{if((T.headers?.authorization??"")!==w){S.status(401).set("WWW-Authenticate",`Basic realm="${h}"`).set("Content-Type","text/plain").send("Unauthorized");return}I();});}for(let h of a)f.use(h);f.get(`${c}/`,p.handleDashboard),f.get(`${c}`,p.handleDashboard),f.get(`${c}/:repoName/_panel`,p.handlePanel),f.post(`${c}/:repoName/_bulk/delete`,p.handleBulkDelete),f.post(`${c}/:repoName/_bulk/update`,p.handleBulkUpdate),f.post(`${c}/:repoName/_bulk/backfill`,p.handleBulkBackfill),f.get(`${c}/:repoName`,p.handleList),f.get(`${c}/:repoName/create`,p.handleCreateForm),f.post(`${c}/:repoName/create`,p.handleCreateSubmit),f.get(`${c}/:repoName/:id/edit`,p.handleEditForm),f.post(`${c}/:repoName/:id/edit`,p.handleEditSubmit),f.get(`${c}/:repoName/:id/history`,p.handleHistory),f.post(`${c}/:repoName/:id/delete`,p.handleDelete);let b=async(h,w)=>{await f.handle(h,w);};return l&&(b.httpsOptions=l),b}ft();function Te(e,t){let n=e||{},r={},o={...n};for(let[s,a]of Object.entries(t||{})){let l=n[s];At(l,a)||(r[s]=a,o[s]=a);}return {before:n,after:o,changes:r}}function Or(e){return e}async function Cn(e,t,n){let r=e.changes||{};for(let o of Object.keys(r)){let s=t[o];if(s&&s.length>0){for(let a of s)if(await a.rule({diff:e,key:o,user:n,authenticatedUser:n})===false)return {allowed:false,reason:a.description}}}return {allowed:true}}function Pr(e){return async t=>Cn(t.diff,e,t.user)}var Ir=1e3;function hs(e,t){if(e===void 0)return {success:true,value:Math.min(Math.max(1,t),Ir)};let n=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):NaN;return !Number.isInteger(n)||n<=0||n>Ir?{success:false,error:`Invalid pageSize: must be an integer between 1 and ${Ir}`}:{success:true,value:n}}function Hr(e,t,n=200){let r=ce(t);return e.json(r,n)}function rt(e,t,n,r=200){return Hr(e,{success:true,data:t,meta:n},r)}function q(e,t,n=400){return Hr(e,{success:false,error:t},n)}async function Dr(e,t,n,r,o,s){let a=Bt(t,n),l=a.type==="index",c=l?424:500,p={success:false,error:l?a.message:o&&t instanceof Error?t.message:r};if(l&&(p.errorType="index",a.indexUrl&&(p.indexUrl=a.indexUrl,s)))try{let f=s({indexUrl:a.indexUrl,repoName:n.repoName??"",path:n.path,isGroup:n.isGroup,filters:n.filters,sort:n.sort,error:t,c:e});f instanceof Promise&&await f;}catch(f){o&&console.error("[crudServer] Error in indexesError callback:",f);}return Hr(e,p,c)}function ot(e){let t=e._def??e.def;if(!t)return e;let n=t.typeName??t.type;if(n==="ZodDate"||n==="date")return z.preprocess(r=>zn(r)??r,e);if(n==="ZodObject"||n==="object"){let r=e.shape,o={};for(let[s,a]of Object.entries(r))o[s]=ot(a);return z.object(o)}if(n==="ZodArray"||n==="array"){let r=t.element??t.type;if(r)return z.array(ot(r))}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(r)return ot(r).optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(r)return ot(r).nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType,o=t.defaultValue;if(r){let s=ot(r);return typeof o=="function"?s.default(o()):s.default(o)}}return e}function ec(e,t,n=[]){let r=e.shape,o={},s=t&&t.length>0?t:Object.keys(r);for(let a of s){if(n.includes(a))continue;let l=a.split(".")[0];l&&r[l]&&(o[l]=r[l]);}return z.object(o)}function $r(e){let t=e;for(;t;){let n=t._zod?.def??t._def;if(!n)break;if(n.innerType)t=n.innerType;else if(n.schema)t=n.schema;else if(n.type==="optional"||n.type==="nullable"||n.type==="default"||n.type==="catch"||n.type==="effects")t=n.innerType??n.schema;else break}return t}function ws(e,t){let n=t.split("."),r=$r(e);for(let o=0;o<n.length;o++){let s=n[o];if(!s)continue;let a=r?.shape;if(!a||!a[s])return;let l=a[s];if(o===n.length-1)return l;r=$r(l);}return r}function st(e){let t=e?._zod?.def??e?._def,n=t?.typeName??t?.type;if(n==="ZodObject"||n==="object"){let r=e.shape,o={};for(let[s,a]of Object.entries(r))o[s]=st(a);return z.object(o).partial()}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(!r)return e;let o=st(r);return o===r?e:o.optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(!r)return e;let o=st(r);return o===r?e:o.nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType;return r?st(r).optional():e}if(n==="ZodUnion"||n==="union"){let r=t.options;if(!r||r.length<2)return e;let o=r.map(a=>st(a));return o.some((a,l)=>a!==r[l])?z.union(o):e}return e}function An(e,t,n,r=false,o=[]){if(typeof t!="object"||t===null||Array.isArray(t))return {success:false,error:"Data payload must be an object"};try{let s=t,a={},l={};for(let[c,u]of Object.entries(s))if(c.includes(".")){let p=c.split(".")[0];if(o.includes(c)||o.includes(p))continue;if(n&&n.length>0&&!n.includes(c)&&!n.includes(p))return {success:!1,error:`Field '${c}' is not allowed for this operation`};let f=ws(e,c);if(!f)return {success:!1,error:`Field '${c}' does not exist in schema`};let b=r?st(f):f,w=(nn()==="normalize"?ot(b):b).parse(u);a[c]=w;}else l[c]=u;if(Object.keys(l).length>0||Object.keys(a).length===0){let c=ec(e,n,o),u=r?st(c):c,f=(nn()==="normalize"?ot(u):u).parse(l);Object.assign(a,f);}return {success:!0,data:a}}catch(s){return s instanceof z.ZodError?{success:false,error:`Validation failed: ${s.issues.map(l=>`${l.path.join(".")}: ${l.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}var xs={eq:"==","==":"==",ne:"!=","!=":"!=",lt:"<","<":"<",lte:"<=","<=":"<=",gt:">",">":">",gte:">=",">=":">=",in:"in",nin:"not-in","not-in":"not-in",not_in:"not-in",contains:"array-contains","array-contains":"array-contains",array_contains:"array-contains",arrayContains:"array-contains",containsAny:"array-contains-any","array-contains-any":"array-contains-any",array_contains_any:"array-contains-any",arrayContainsAny:"array-contains-any"};function Wt(e){return xs[e]??e}function tc(e){return e in xs}function En(e,t,n,r){let o=ws(e,t);if(!o||typeof o.safeParse!="function")return {success:true,data:n};let s=r?Wt(r):void 0,a=$r(o),l=pn(a);if(s==="array-contains"){let p=l??o;if(typeof p.safeParse=="function"){let f=p.safeParse(n);return f.success?{success:true,data:f.data}:{success:false,error:f.error.issues.map(h=>h.message).join(", ")}}return {success:true,data:n}}if(s==="array-contains-any"){if(!Array.isArray(n))return {success:false,error:"Expected array value for array-contains-any"};let p=l??o,f=[];for(let b of n)if(typeof p.safeParse=="function"){let h=p.safeParse(b);if(h.success)f.push(h.data);else return {success:false,error:h.error.issues.map(T=>T.message).join(", ")}}else f.push(b);return {success:true,data:f}}let c=o.safeParse(n);if(c.success)return {success:true,data:c.data};if(Array.isArray(n)){let p=l??o,f=[];for(let b of n)if(typeof p.safeParse=="function"){let h=p.safeParse(b);if(h.success)f.push(h.data);else return {success:false,error:h.error.issues.map(T=>T.message).join(", ")}}else f.push(b);return {success:true,data:f}}return {success:false,error:c.error.issues.map(p=>p.message).join(", ")}}function nc(e,t){let n=[],r=t?new Set(t):null;for(let[o,s]of Object.entries(e)){if(s===void 0||["cursor","direction","limit","pageSize","orderBy","orderDir","select","includes","withTotal"].includes(o))continue;let a=Array.isArray(s)?s[0]:s;if(a===void 0||a==="")continue;let l=o.lastIndexOf("__"),c,u="==";if(l!==-1){let f=o.slice(0,l),b=o.slice(l+2);tc(b)?(c=f,u=Wt(b)):(c=o,u="==");}else c=o;if(r&&!r.has(c))continue;let p=a;u==="in"||u==="not-in"||u==="array-contains-any"?p=a.split(",").map(f=>gs(f.trim())):p=gs(a),n.push({field:c,op:u,value:p});}return n}function gs(e){if(e==="true")return true;if(e==="false")return false;if(e==="null"||e==="__null__")return null;let t=Number(e);return !isNaN(t)&&e!==""?t:e}function On(e){return e?{docId:e.id,docPath:e.ref?.path??void 0}:null}async function bs(e,t){if(!t)return;let n;if(typeof t=="string")try{n=JSON.parse(t);}catch{n=t.includes("/")?{docPath:t}:{docId:t};}else typeof t=="object"&&(n=t);if(!n)return;let r=typeof n.docPath=="string"?n.docPath:void 0,o=typeof n.docId=="string"?n.docId:void 0;try{let s=e.repo.ref,a=s?.firestore;if(r&&a&&typeof a.doc=="function"){let l=await a.doc(r).get();if(l.exists)return l}if(o&&o.includes("/")&&a&&typeof a.doc=="function"){let l=await a.doc(o).get();if(l.exists)return l}if(o&&typeof s.doc=="function"){let l=await s.doc(o).get();if(l.exists)return l}return}catch{return}}function Pn(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t={},n=0;for(let[r,o]of Object.entries(e))o!==void 0&&(t[r]=o,n++);return n>0?t:null}function Rs(e,t,n,r,o){async function s(x,d,y,i){let g=false;if(x.hooks?.onAfterError){g=true;try{let m=x.hooks.onAfterError(i,y.hook);m instanceof Promise&&await m;}catch(m){console.error("[crudServer] Error in hooks.onAfterError callback:",m);}}if(o){g=true;try{let m=o({...y,error:i});m instanceof Promise&&await m;}catch(m){console.error("[crudServer] Error in onHookError callback:",m);}}if(!g){if(d&&typeof d.error=="function"){d.error(i,{hook:y.hook,repoName:y.repoName,path:y.path,...y.id!==void 0?{id:y.id}:{},...y.pathArgs!==void 0?{pathArgs:y.pathArgs}:{}});return}console.error(`[crudServer] Hook "${y.hook}" failed on repo "${y.repoName}":`,{hook:y.hook,repoName:y.repoName,path:y.path,...y.id!==void 0?{id:y.id}:{},...y.pathArgs!==void 0?{pathArgs:y.pathArgs}:{},error:i});}}async function a(x,d,y,i){if(!d.rules)return {allowed:true};let g=d.rules?.[y];if(!g)return {allowed:false,errorResponse:q(x,`Operation "${y}" is not allowed for this repository`,403)};try{let m=await g(i);return m===!1?{allowed:!1,errorResponse:q(x,"Forbidden",403)}:typeof m=="string"?{allowed:!1,errorResponse:q(x,m,403)}:typeof m=="object"&&m!==null&&!m.allowed?{allowed:!1,errorResponse:q(x,m.reason||"Forbidden",403)}:{allowed:!0}}catch(m){let C=n&&m instanceof Error?m.message:"Forbidden";return {allowed:false,errorResponse:q(x,C,403)}}}async function l(x,d,y,i){if(!x.rules)return i;let g=x.rules?.filter;if(!g)return i;let m=[];for(let C of i)try{await g({user:d,doc:C,params:y})&&m.push(C);}catch{}return m}function c(x){return x.get("user")??x.get("docsUser")??null}function u(x,d){if(!x){let y=d.req.path.split("/");for(let i of y)if(e[i]){x=i;break}}return !x||!e[x]?null:e[x]??null}function p(x,d){return Je(x,{pathKey:d.pathKey,documentKey:d.documentKey,parentKeys:d.parentKeys,documentPathTemplate:d.documentPathTemplate,isGroup:d.isGroup})}async function f(x,d){let y=`by${x.documentKey.charAt(0).toUpperCase()}${x.documentKey.slice(1)}`,i=x.repo.get[y];if(typeof i=="function")try{let m=await i(d);if(m)return m}catch{}return (await x.repo.query.by({where:[[x.documentKey,"==",d]],limit:1}))[0]??null}async function b(x){let d=x.c,y=d.req.param(),i=u(y.repoName,d);if(!i)return q(d,"Repository not found",404);let g=c(d),m=await a(d,i,"list",{user:g,query:d.req.query(),params:y});if(!m.allowed)return m.errorResponse;let C=[],k;try{let R=d.req.query(),P=hs(R.pageSize,i.pageSize);if(!P.success)return q(d,P.error,400);let _=P.value,$=R.cursor,M=R.direction?.toLowerCase()==="prev"?"prev":"next",v=R.orderBy,E=R.orderDir?.toLowerCase()==="desc"?"desc":"asc",F=R.select,H=F?F.split(",").map(W=>W.trim()):void 0,D=R.withTotal,N=D==="true"||D==="1"||D===!0,j;i.allowedIncludes&&R.includes&&(j=(typeof R.includes=="string"?R.includes.split(",").map(X=>X.trim()):Array.isArray(R.includes)?R.includes:[]).filter(X=>typeof X=="string"&&i.allowedIncludes.includes(X)),j?.length===0&&(j=void 0));let z=nc(R,i.filterableFields);C=z.map(W=>({field:W.field,op:W.op,value:String(W.value??"")})),v&&(k={field:v,dir:E});let te={pageSize:_,direction:M,...N?{withTotal:!0}:{}};if($)try{let W=typeof $=="string"?JSON.parse($):$;te.cursor=await bs(i,W);}catch{}if(v){if(i.orderableFields&&!i.orderableFields.includes(v))return q(d,`Field not orderable: ${v}`,400);te.orderBy=[{field:v,direction:E}];}if(z.length>0){te.where=[];for(let W of z){let X=En(i.schema,W.field,W.value,W.op);if(!X.success)return q(d,`Invalid filter value for '${W.field}': ${X.error}`,400);te.where.push([W.field,W.op,X.data]);}}H&&(te.select=H),j&&(te.include=j);let K=await i.repo.query.paginate(te),Se={items:await l(i,c(d),y,K.data),hasNextPage:K.hasNextPage,hasPrevPage:K.hasPrevPage,nextCursor:On(K.nextCursor),prevCursor:On(K.prevCursor),...K.totalCount!==void 0?{totalCount:K.totalCount,totalCountIsExact:K.totalCountIsExact}:{}};return rt(d,Se,{pageSize:_,hasMore:K.hasNextPage,...K.totalCount!==void 0?{totalCount:K.totalCount,totalCountIsExact:K.totalCountIsExact}:{}})}catch(R){return await Dr(d,R,{repoName:y.repoName||i.name,ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:C,sort:k},"Failed to fetch documents",n,r)}}async function h(x){let d=x.c,y=d.req.param(),i=u(y.repoName,d);if(!i)return q(d,"Repository not found",404);let g=c(d),m=await a(d,i,"list",{user:g,query:x.input||{},params:y});if(!m.allowed)return m.errorResponse;let C=[],k;try{let R=x.input||{},P=hs(R.pageSize,i.pageSize);if(!P.success)return q(d,P.error,400);let _=P.value,$=R.direction==="prev"?"prev":"next";R.where&&(C=R.where.map(D=>({field:String(D[0]),op:D[1],value:String(D[2]??"")}))),R.orderBy&&R.orderBy[0]&&(k={field:R.orderBy[0].field,dir:R.orderBy[0].direction==="desc"?"desc":"asc"});let M=R.withTotal===!0||String(R.withTotal)==="true",v={pageSize:_,direction:$,...M?{withTotal:!0}:{}};if(R.cursor)try{let D=typeof R.cursor=="string"?JSON.parse(R.cursor):R.cursor;v.cursor=await bs(i,D);}catch{}if(i.allowedIncludes&&R.includes&&R.includes.length>0){let D=R.includes.filter(N=>typeof N=="string"?i.allowedIncludes.includes(N):typeof N=="object"&&N!==null&&"relation"in N&&typeof N.relation=="string"?i.allowedIncludes.includes(N.relation):!1);D.length>0&&(v.include=D);}if(R.where&&R.where.length>0){if(i.filterableFields){let N=new Set(i.filterableFields),j=R.where.filter(z=>!N.has(z[0]));if(j.length>0){q(d,`Fields not filterable: ${j.map(z=>z[0]).join(", ")}`,400);return}}let D=[];for(let N of R.where){let j=Wt(N[1]),z=En(i.schema,N[0],N[2],j);if(!z.success){q(d,`Invalid filter value for '${N[0]}': ${z.error}`,400);return}D.push([N[0],j,z.data]);}v.where=D;}if(R.orWhere&&R.orWhere.length>0){if(i.filterableFields){let N=new Set(i.filterableFields),j=R.orWhere.filter(z=>!N.has(z[0]));if(j.length>0){q(d,`Fields not filterable: ${j.map(z=>z[0]).join(", ")}`,400);return}}let D=[];for(let N of R.orWhere){let j=Wt(N[1]),z=En(i.schema,N[0],N[2],j);if(!z.success){q(d,`Invalid filter value for '${N[0]}': ${z.error}`,400);return}D.push([N[0],j,z.data]);}v.orWhere=D;}if(R.orWhereGroups&&R.orWhereGroups.length>0){if(i.filterableFields){let N=new Set(i.filterableFields);for(let j of R.orWhereGroups){let z=j.filter(te=>!N.has(te[0]));if(z.length>0){q(d,`Fields not filterable: ${z.map(te=>te[0]).join(", ")}`,400);return}}}let D=[];for(let N of R.orWhereGroups){let j=[];for(let z of N){let te=Wt(z[1]),K=En(i.schema,z[0],z[2],te);if(!K.success){q(d,`Invalid filter value for '${z[0]}': ${K.error}`,400);return}j.push([z[0],te,K.data]);}D.push(j);}v.orWhereGroups=D;}if(R.orderBy&&R.orderBy.length>0){if(i.orderableFields){let D=new Set(i.orderableFields),N=R.orderBy.filter(j=>!D.has(j.field));if(N.length>0){q(d,`Fields not orderable: ${N.map(j=>j.field).join(", ")}`,400);return}}v.orderBy=R.orderBy;}R.select&&R.select.length>0&&(v.select=R.select);let E=await i.repo.query.paginate(v),H={items:await l(i,c(d),y,E.data),hasNextPage:E.hasNextPage,hasPrevPage:E.hasPrevPage,nextCursor:On(E.nextCursor),prevCursor:On(E.prevCursor),...E.totalCount!==void 0?{totalCount:E.totalCount,totalCountIsExact:E.totalCountIsExact}:{}};return rt(d,H,{pageSize:_,hasMore:E.hasNextPage,...E.totalCount!==void 0?{totalCount:E.totalCount,totalCountIsExact:E.totalCountIsExact}:{}})}catch(R){return await Dr(d,R,{repoName:y.repoName||i.name,ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:C,sort:k},"Failed to query documents",n,r)}}async function w(x){let d=x.c,y=d.req.param(),i=u(y.repoName,d);if(!i)return q(d,"Repository not found",404);let g=y.id;if(!g)return q(d,"Document ID required",400);try{let m=await f(i,g);if(!m)return q(d,"Document not found",404);let C=c(d),k=await a(d,i,"get",{user:C,doc:m,params:y});if(!k.allowed)return k.errorResponse;if(i.rules?.filter)try{if(!await i.rules.filter({user:C,doc:m,params:y}))return q(d,"Document not found",404)}catch{return q(d,"Document not found",404)}return rt(d,m)}catch(m){return await Dr(d,m,{repoName:y.repoName||i.name,ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:[{field:i.documentKey,op:"==",value:g}]},"Failed to fetch document",n,r)}}async function T(x){let d=x.c,y=d.req.param(),i=u(y.repoName,d);if(!i)return q(d,"Repository not found",404);try{let g=x.input||{},m=c(d),C=await a(d,i,"create",{user:m,body:g,params:y});if(!C.allowed)return C.errorResponse;let k=An(i.schema,g,i.createFields,!1,i.systemKeys);if(!k.success)return q(d,k.error,400);if(i.validate){let $=await i.validate(k.data,"create");if($)return q(d,$,400)}i.hooks?.beforeCreate&&await i.hooks.beforeCreate({user:m,body:k.data,params:y,c:d});let R,P;if(i.isGroup&&i.parentKeys&&i.parentKeys.length>0){let $={...k.data},M=i.parentKeys.filter(v=>$[v]===void 0||$[v]===null||typeof $[v]=="string"&&$[v].trim()==="");if(M.length>0)return q(d,`Missing parent key(s) for subcollection create: ${M.join(", ")}`,400);if(typeof i.repo.create=="function")R=await i.repo.create($);else {let v=i.parentKeys.map(F=>String($[F])),E=$[i.documentKey]||Be();P=[...v,E],R=await i.repo.set(...v,E,$);}}else R=await i.repo.create(k.data);let _=R;if(i.hooks?.afterCreate){let $=R?.[i.documentKey]??P?.[P.length-1]??"",M=String($),v=P??p(R,i)??p({...k.data,...M?{[i.documentKey]:M}:{}},i)??(M?[M]:[]);try{let E=await i.hooks.afterCreate({user:m,doc:R,id:M,pathArgs:v,params:y,c:d}),F=Pn(E);F&&v.length>0&&(_=await i.repo.update(...v,F));}catch(E){await s(i,x.logger,{hook:"afterCreate",repoName:i.name,path:i.path,id:M,pathArgs:v,user:m,c:d},E);}}return rt(d,_,void 0,201)}catch(g){let m=n&&g instanceof Error?g.message:"Failed to create document";return q(d,m,500)}}async function S(x,d){let y=x.c,i=y.req.param(),g=u(i.repoName,y);if(!g)return q(y,"Repository not found",404);let m=i.id;if(!m)return q(y,"Document ID required",400);try{let C=x.input||{},k=await f(g,m);if(!k)return q(y,"Document not found",404);let R=An(g.schema,C,g.mutableFields,d,g.systemKeys);if(!R.success)return q(y,R.error,400);if(g.validate){let D=await g.validate(R.data,"update");if(D)return q(y,D,400)}let P=Te(k,R.data),_=c(y),$=await a(y,g,"update",{user:_,doc:k,body:R.data,diff:P,params:i});if(!$.allowed)return $.errorResponse;if(g.hooks?.beforeUpdate){let D=g.rules?.update?Te(k,R.data):P;await g.hooks.beforeUpdate({user:_,doc:k,body:R.data,diff:D,params:i,c:y});}let M={...R.data},v=g.hooks?.afterUpdate?Te(k,M):P,E=p(k,g)??[m],F=await g.repo.update(...E,R.data),H=F;if(g.hooks?.afterUpdate)try{let D=await g.hooks.afterUpdate({user:_,before:k,after:F,body:M,diff:v,id:m,pathArgs:E,params:i,c:y}),N=Pn(D);N&&(H=await g.repo.update(...E,N));}catch(D){await s(g,x.logger,{hook:"afterUpdate",repoName:g.name,path:g.path,id:m,pathArgs:E,user:_,c:y},D);}return rt(y,H)}catch(C){let k=n&&C instanceof Error?C.message:"Failed to update document";return q(y,k,500)}}async function I(x){let d=x.c,y=d.req.param(),i=u(y.repoName,d);if(!i)return q(d,"Repository not found",404);if(!i.allowDelete)return q(d,"Delete not allowed for this repository",403);let g=y.id;if(!g)return q(d,"Document ID required",400);try{let m=await f(i,g);if(!m)return q(d,"Document not found",404);let C=c(d),k=await a(d,i,"delete",{user:C,doc:m,params:y});if(!k.allowed)return k.errorResponse;let R=p(m,i)??[g];if(await i.repo.delete(...R),i.hooks?.afterDelete)try{await i.hooks.afterDelete({user:C,doc:m,id:g,pathArgs:R,params:y,c:d});}catch(P){await s(i,x.logger,{hook:"afterDelete",repoName:i.name,path:i.path,id:g,pathArgs:R,user:C,c:d},P);}return rt(d,{deleted:!0})}catch(m){let C=n&&m instanceof Error?m.message:"Failed to delete document";return q(d,C,500)}}function A(x){return x.c.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-History-Reason, X-History-Comment","Access-Control-Max-Age":"86400"})}async function O(x){let d=x.c,y=d.req.param(),i=u(y.repoName,d);if(!i)return q(d,"Repository not found",404);try{let g=x.input||{};if(!Array.isArray(g.operations))return q(d,"operations array is required",400);let m=c(d),C=i.repo.batch.create(),k=[],R=!!i.hooks,P=[],_=[],$=[];for(let v of g.operations){if(!v.type||!["create","update","delete"].includes(v.type))return q(d,"Invalid operation type",400);if(v.type==="create"){let E=await a(d,i,"create",{user:m,body:v.data,params:y});if(!E.allowed)return E.errorResponse;let F=An(i.schema,v.data,i.createFields,!1,i.systemKeys);if(!F.success)return q(d,F.error,400);i.hooks?.beforeCreate&&await i.hooks.beforeCreate({user:m,body:F.data,params:y,c:d});let H=v.data[i.documentKey]||F.data[i.documentKey]||Be(),D={...F.data};i.createdKey&&D[i.createdKey]===void 0&&(D[i.createdKey]=new Date);let N;if(i.isGroup&&i.parentKeys){let j=i.parentKeys.map(z=>String(D[z]));N=[...j,H],C.set(...j,H,D);}else N=[H],C.set(H,D);if(k.push({op:"create",id:H}),R){let j={...D,[i.documentKey]:H};if(i.pathKey&&typeof i.repo.documentRef=="function")try{let z=i.repo.documentRef(...N);z?.path&&(j[i.pathKey]=z.path);}catch{}P.push({id:H,pathArgs:N,doc:j});}}else if(v.type==="update"){if(!v.id)return q(d,"id required for update",400);let E=await f(i,v.id);if(!E)return q(d,`Document ${v.id} not found`,404);let F=An(i.schema,v.data,i.mutableFields,!0,i.systemKeys);if(!F.success)return q(d,F.error,400);if(i.validate){let te=await i.validate(F.data,"update");if(te)return q(d,te,400)}let H=Te(E,F.data),D=await a(d,i,"update",{user:m,doc:E,body:F.data,diff:H,params:y});if(!D.allowed)return D.errorResponse;if(i.hooks?.beforeUpdate){let te=i.rules?.update?Te(E,F.data):H;await i.hooks.beforeUpdate({user:m,doc:E,body:F.data,diff:te,params:y,c:d});}let N={...F.data},j=R?Te(E,N):H,z=p(E,i)??[v.id];C.update(...z,F.data),k.push({op:"update",id:v.id}),R&&_.push({id:v.id,pathArgs:z,before:E,after:j.after,body:N,diff:j});}else if(v.type==="delete"){if(!i.allowDelete)return q(d,"Delete not allowed",403);if(!v.id)return q(d,"id required for delete",400);let E=await f(i,v.id);if(!E)return q(d,`Document ${v.id} not found`,404);let F=await a(d,i,"delete",{user:m,doc:E,params:y});if(!F.allowed)return F.errorResponse;let H=p(E,i)??[v.id];C.delete(...H),k.push({op:"delete",id:v.id}),R&&$.push({id:v.id,pathArgs:H,doc:E});}}await C.commit();let M=P.length>0||_.length>0||$.length>0;if(i.hooks&&M)if(i.hooks.afterBatch)try{await i.hooks.afterBatch({user:m,created:P,updated:_,deleted:$,params:y,c:d});}catch(v){await s(i,x.logger,{hook:"afterBatch",repoName:i.name,path:i.path,user:m,c:d},v);}else {if(i.hooks.afterCreate)for(let v of P)try{let E=await i.hooks.afterCreate({user:m,doc:v.doc,id:v.id,pathArgs:v.pathArgs,params:y,c:d}),F=Pn(E);F&&v.pathArgs.length>0&&await i.repo.update(...v.pathArgs,F);}catch(E){await s(i,x.logger,{hook:"afterCreate",repoName:i.name,path:i.path,id:v.id,pathArgs:v.pathArgs,user:m,c:d},E);}if(i.hooks.afterUpdate)for(let v of _)try{let E=await i.hooks.afterUpdate({user:m,before:v.before,after:v.after,body:v.body,diff:v.diff,id:v.id,pathArgs:v.pathArgs,params:y,c:d}),F=Pn(E);F&&v.pathArgs.length>0&&await i.repo.update(...v.pathArgs,F);}catch(E){await s(i,x.logger,{hook:"afterUpdate",repoName:i.name,path:i.path,id:v.id,pathArgs:v.pathArgs,user:m,c:d},E);}if(i.hooks.afterDelete)for(let v of $)try{await i.hooks.afterDelete({user:m,doc:v.doc,id:v.id,pathArgs:v.pathArgs,params:y,c:d});}catch(E){await s(i,x.logger,{hook:"afterDelete",repoName:i.name,path:i.path,id:v.id,pathArgs:v.pathArgs,user:m,c:d},E);}}return rt(d,{results:k})}catch(g){let m=n&&g instanceof Error?g.message:"Batch operation failed";return q(d,m,500)}}return {handleList:b,handleQuery:h,handleGet:w,handleCreate:T,handleUpdate:S,handleDelete:I,handleBatch:O,handleOptions:A}}function xt(e){try{return z.toJSONSchema(e,{target:"openapi-3.1",unrepresentable:"any",override:t=>{let n=getOpenApiMetadata(t.zodSchema);n&&(Object.assign(t.jsonSchema,n),(t.jsonSchema.anyOf||t.jsonSchema.oneOf)&&delete t.jsonSchema.type);let r=t.zodSchema?._zod?.def;r&&(r.type==="date"&&!t.jsonSchema.type&&!t.jsonSchema.anyOf?(t.jsonSchema.type="string",t.jsonSchema.format="date-time"):r.type==="bigint"&&!t.jsonSchema.type&&!t.jsonSchema.anyOf&&(t.jsonSchema.type="string",t.jsonSchema.format="int64"));}})}catch(t){return typeof console<"u"&&console.warn&&console.warn("[generateOpenAPISpec] Failed to convert Zod schema to JSON Schema; falling back to {type:object}.",t),{type:"object"}}}function pe(e){return {$ref:`#/components/schemas/${e}`}}function ee(e){return {description:e,content:{"application/json":{schema:pe("ErrorResponse")}}}}function wt(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function rc(e){return {description:"Paginated list of documents",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:{type:"object",properties:{items:{type:"array",items:e},nextCursor:{oneOf:[{type:"object"},{type:"null"}]},prevCursor:{oneOf:[{type:"object"},{type:"null"}]},hasNextPage:{type:"boolean"},hasPrevPage:{type:"boolean"},totalCount:{type:"integer",description:"Total count of matching documents (when requested with withTotal=true)"},totalCountIsExact:{type:"boolean",description:"Whether totalCount is exact (true) or estimated via parallel branch-sum fallback (false)"}},required:["items","hasNextPage","hasPrevPage"]},meta:{type:"object",properties:{pageSize:{type:"integer"},hasMore:{type:"boolean"},totalCount:{type:"integer"},totalCountIsExact:{type:"boolean"},cursor:{oneOf:[{type:"string"},{type:"null"}]}}}},required:["success","data"]}}}}}function Vt(e){let t=e;for(;t;){let n=t._zod?.def??t._def;if(!n)break;if(n.innerType)t=n.innerType;else if(n.schema)t=n.schema;else if(n.type==="optional"||n.type==="nullable"||n.type==="default"||n.type==="catch"||n.type==="effects")t=n.innerType??n.schema;else break}return t}function oc(e,t){let n=t.split("."),r=Vt(e);for(let o=0;o<n.length;o++){let s=n[o];if(!s)continue;let a=r?.shape;if(!a||!a[s])return;let l=a[s];if(o===n.length-1)return l;r=Vt(l);}return r}function it(e){let t=e?._zod?.def??e?._def,n=t?.typeName??t?.type,r=o=>{let s=getOpenApiMetadata(e);return s&&typeof o.openapi=="function"?o.openapi(s):o};if(n==="ZodObject"||n==="object"){let o=e.shape,s={};for(let[a,l]of Object.entries(o))s[a]=it(l);return r(z.object(s).partial())}if(n==="ZodOptional"||n==="optional"){let o=t.innerType;if(!o)return e;let s=it(o);return s===o?e:r(s.optional())}if(n==="ZodNullable"||n==="nullable"){let o=t.innerType;if(!o)return e;let s=it(o);return s===o?e:r(s.nullable())}if(n==="ZodDefault"||n==="default"){let o=t.innerType;return o?r(it(o).optional()):e}if(n==="ZodUnion"||n==="union"){let o=t.options;if(!o||o.length<2)return e;let s=o.map(l=>it(l));return s.some((l,c)=>l!==o[c])?r(z.union(s)):e}return e}function _r(e,t="",n=0){if(n>5)return [];let o=Vt(e)?.shape;if(!o)return [];let s=[];for(let[a,l]of Object.entries(o)){let c=t?`${t}.${a}`:a,u=Vt(l);u?.shape&&typeof u.shape=="object"?(s.push({path:c,zodSchema:l}),s.push(..._r(u,c,n+1))):s.push({path:c,zodSchema:l});}return s}function sc(e){return e.filterableFields&&e.filterableFields.length>0?e.filterableFields.map(t=>({path:t,zodSchema:oc(e.schema,t)})):_r(e.schema)}function Ss(e){if(!e)return {type:"string"};let t=xt(e);return delete t.$schema,delete t.title,t}function Ts(){return {type:"object",properties:{where:{type:"array",items:{type:"array",items:{},minItems:3,maxItems:3},description:"AND conditions: [field, operator, value][]"},orWhere:{type:"array",items:{type:"array",items:{},minItems:3,maxItems:3},description:"Simple OR conditions (each independently OR'd)"},orWhereGroups:{type:"array",items:{type:"array",items:{type:"array",items:{},minItems:3,maxItems:3}},description:"Advanced OR groups (AND within, OR across groups)"},orderBy:{type:"array",items:{type:"object",properties:{field:{type:"string"},direction:{type:"string",enum:["asc","desc"]}},required:["field"]}},select:{type:"array",items:{type:"string"},description:"Fields to select (projection)"},pageSize:{type:"integer",minimum:1,maximum:1e3,description:"Number of items per page"},cursor:{oneOf:[{type:"string"},{type:"object"}],description:"Pagination cursor"},direction:{type:"string",enum:["next","prev"],description:"Pagination direction"},includes:{type:"array",items:{oneOf:[{type:"string"},{type:"object",properties:{relation:{type:"string"},select:{type:"array",items:{type:"string"}}},required:["relation"]}]},description:"Relations to include (populate)"},withTotal:{type:"boolean",description:"Include total document count (totalCount and totalCountIsExact) in response"}}}}function ac(e){let t=sc(e),n=e.orderableFields??t.map(a=>a.path),r=t.map(a=>a.path);if(t.length===0)return Ts();let o=[];for(let{path:a,zodSchema:l}of t){let c=Ss(l),u=Vt(l),f=u?._zod?.def?.type==="array"||u?._def?.typeName==="ZodArray"||u?._def?.type==="array"?Ss(u?._zod?.def?.element??u?._def?.type??u?._def?.element):c;o.push({type:"array",description:`Condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["==","!=","<","<=",">",">=","eq","ne","lt","lte","gt","gte"]},c],minItems:3,maxItems:3}),o.push({type:"array",description:`List condition on '${a}' (in, not-in)`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["in","not-in","nin"]},{type:"array",items:c}],minItems:3,maxItems:3}),o.push({type:"array",description:`Array contains condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["array-contains","contains"]},f],minItems:3,maxItems:3}),o.push({type:"array",description:`Array contains-any condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["array-contains-any","containsAny"]},{type:"array",items:f}],minItems:3,maxItems:3});}let s={oneOf:o};return {type:"object",properties:{where:{type:"array",items:s,description:"AND conditions: [field, operator, value][]"},orWhere:{type:"array",items:s,description:"Simple OR conditions (each independently OR'd)"},orWhereGroups:{type:"array",items:{type:"array",items:s},description:"Advanced OR groups (AND within, OR across groups)"},orderBy:{type:"array",items:{type:"object",properties:{field:{type:"string",enum:n},direction:{type:"string",enum:["asc","desc"]}},required:["field"]}},select:{type:"array",items:{type:"string",enum:r},description:"Fields to select (projection)"},pageSize:{type:"integer",minimum:1,maximum:1e3,description:"Number of items per page"},cursor:{oneOf:[{type:"string"},{type:"object"}],description:"Pagination cursor"},direction:{type:"string",enum:["next","prev"],description:"Pagination direction"},includes:{type:"array",items:e.allowedIncludes&&e.allowedIncludes.length>0?{oneOf:[{type:"string",enum:e.allowedIncludes},{type:"object",properties:{relation:{type:"string",enum:e.allowedIncludes},select:{type:"array",items:{type:"string"}}},required:["relation"]}]}:{oneOf:[{type:"string"},{type:"object",properties:{relation:{type:"string"},select:{type:"array",items:{type:"string"}}},required:["relation"]}]},description:"Relations to include (populate)"},withTotal:{type:"boolean",description:"Include total document count (totalCount and totalCountIsExact) in response"}}}}function ic(e){if(e.historyHeaders)return e.historyHeaders;let t=e.repo?._historyConfig;if(!t?.enabled||t.autoInjectMeta===false)return null;let n=Ee(t);return n?{reason:n.fields.reason!==false,comment:n.fields.comment!==false}:null}function cc(e,t){if(t===false)return [];let n=ic(e);if(!n)return [];let r=t?.reasonHeader===void 0?Ve:t.reasonHeader,o=t?.commentHeader===void 0?Ge:t.commentHeader,s=[],a=new Set;if(n.reason&&typeof r=="string"&&r.trim()){let l=r.trim();a.add(l.toLowerCase()),s.push({name:l,in:"header",required:false,schema:{type:"string"},description:"Optional reason recorded in the document's change history"});}if(n.comment&&typeof o=="string"&&o.trim()){let l=o.trim();a.has(l.toLowerCase())||(a.add(l.toLowerCase()),s.push({name:l,in:"header",required:false,schema:{type:"string"},description:"Optional comment recorded in the document's change history"}));}if(t?.extraHeaders?.length)for(let l of t.extraHeaders){let c=typeof l=="string"?{name:l}:l,u=c?.name?.trim();!u||a.has(u.toLowerCase())||(a.add(u.toLowerCase()),s.push({name:u,in:"header",required:c.required??false,schema:c.schema??{type:"string"},...c.description?{description:c.description}:{}}));}return s}function lc(e,t,n,r,o,s=null,a="QueryRequestBody",l=[]){let c={},u=e.name,p=`${t}/${e.name}`,f=`${p}/{${e.documentKey}}`,b={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};c[p]={post:{operationId:`create${Ze(e.name)}`,summary:`Create a ${De(e.name)}`,tags:[u],...l.length>0?{parameters:[...l]}:{},requestBody:{required:true,content:{"application/json":{schema:pe(r??n)}}},responses:{201:wt("Document created",pe(n)),400:ee("Validation error"),403:ee("Forbidden"),500:ee("Internal server error")}}},c[`${p}/query`]={post:{operationId:`query${Ze(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[u],requestBody:{required:true,content:{"application/json":{schema:pe(a)}}},responses:{200:rc(pe(n)),400:ee("Invalid query"),403:ee("Forbidden"),424:ee("Missing composite index (includes indexUrl in response)"),500:ee("Internal server error")}}},c[`${p}/batch`]={post:{operationId:`batch${Ze(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[u],...l.length>0?{parameters:[...l]}:{},requestBody:{required:true,content:{"application/json":{schema:pe(`${n}BatchRequest`)}}},responses:{200:wt("Batch operations completed",{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{op:{type:"string"},id:{type:"string"}}}}}}),400:ee("Validation error"),403:ee("Forbidden"),404:ee("Document not found"),500:ee("Internal server error")}}};let h={};return h.get={operationId:`get${Ze(De(e.name))}`,summary:`Get a single ${De(e.name)}`,tags:[u],parameters:[b],responses:{200:wt("Document found",pe(n)),400:ee("Document ID required"),403:ee("Forbidden"),404:ee("Document not found"),424:ee("Missing composite index (includes indexUrl in response)"),500:ee("Internal server error")}},h.put={operationId:`update${Ze(De(e.name))}`,summary:`Update a ${De(e.name)} (full replace)`,tags:[u],parameters:[b,...l],requestBody:{required:true,content:{"application/json":{schema:pe(o??n)}}},responses:{200:wt("Document updated",pe(n)),400:ee("Validation error"),403:ee("Forbidden"),404:ee("Document not found"),500:ee("Internal server error")}},h.patch={operationId:`patch${Ze(De(e.name))}`,summary:`Partially update a ${De(e.name)}`,tags:[u],parameters:[b,...l],requestBody:{required:true,content:{"application/json":{schema:pe(s??o??n)}}},responses:{200:wt("Document patched",pe(n)),400:ee("Validation error"),403:ee("Forbidden"),404:ee("Document not found"),500:ee("Internal server error")}},e.allowDelete&&(h.delete={operationId:`delete${Ze(De(e.name))}`,summary:`Delete a ${De(e.name)}`,tags:[u],parameters:[b],responses:{200:wt("Document deleted",{type:"object",properties:{id:{type:"string"}}}),400:ee("Document ID required"),403:ee("Forbidden"),404:ee("Document not found"),500:ee("Internal server error")}}),c[f]=h,c}function Mr(e,t,n={}){let{title:r="CRUD API",version:o="1.0.0",description:s,servers:a,auth:l=false}=n,c=t==="/"?"":t.replace(/\/$/,""),u={},p={},f=[];u.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string",description:"Human-readable error description"},errorType:{type:"string",enum:["index"],description:"Error category discriminator. Set to 'index' when a Firestore composite index is missing."},indexUrl:{type:"string",format:"uri",description:"Direct Firebase Console URL to create the required composite index (when errorType is 'index')."}},required:["success","error"]},u.QueryRequestBody=Ts();for(let[T,S]of Object.entries(e)){let I=Ze(De(T)),A=`${I}Create`,O=`${I}Update`,x=`${I}Patch`,d=`${I}QueryRequestBody`;u[I]=xt(S.schema),u[d]=ac(S);let y=v=>{let E={},F=_r(S.schema);for(let{path:H,zodSchema:D}of F){let N=H.split(".")[0];S.systemKeys.includes(N)||S.systemKeys.includes(H)||v&&v.length>0&&!v.includes(H)&&!v.includes(N)||(H.includes(".")?E[H]=D.optional():E[H]=D);}return E},i=null,g=y(S.createFields);if(S.isGroup&&S.parentKeys&&S.parentKeys.length>0){let v=S.schema?.shape??{};for(let E of S.parentKeys)!g[E]&&v[E]&&(g[E]=v[E]);}if(Object.keys(g).length>0){let v=xt(z.object(g));if(S.isGroup&&S.parentKeys&&S.parentKeys.length>0){let E=new Set(Array.isArray(v.required)?v.required:[]);for(let F of S.parentKeys)v.properties?.[F]&&E.add(F);E.size>0&&(v.required=Array.from(E));}u[A]=v,i=A;}let m=null,C=null,k=y(S.mutableFields);if(Object.keys(k).length>0){let v=z.object(k);u[O]=xt(v),m=O,u[x]=xt(it(v)),C=x;}else u[x]=xt(it(S.schema)),C=x;let R=`${I}BatchCreateOperation`,P=`${I}BatchUpdateOperation`,_=`${I}BatchDeleteOperation`;u[R]={type:"object",title:`${I} Create Operation`,properties:{type:{type:"string",enum:["create"],const:"create"},data:pe(i??I)},required:["type","data"]},u[P]={type:"object",title:`${I} Update Operation`,properties:{type:{type:"string",enum:["update"],const:"update"},id:{type:"string"},data:pe(C??m??I)},required:["type","id","data"]},S.allowDelete&&(u[_]={type:"object",title:`${I} Delete Operation`,properties:{type:{type:"string",enum:["delete"],const:"delete"},id:{type:"string"}},required:["type","id"]}),u[`${I}BatchRequest`]={type:"object",properties:{operations:{type:"array",items:{oneOf:[pe(R),pe(P),...S.allowDelete?[pe(_)]:[]],discriminator:{propertyName:"type"}}}},required:["operations"]};let $=cc(S,n.historyHeaders),M=lc(S,c,I,i,m,C,d,$);Object.assign(p,M),f.push({name:T,description:`Operations on ${T} (collection: ${S.path})`});}let b={},h;return l==="basic"?(b.basicAuth={type:"http",scheme:"basic"},h=[{basicAuth:[]}]):l==="bearer"&&(b.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},h=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:r,version:o,...s?{description:s}:{}},...a&&a.length>0?{servers:a}:{},paths:p,components:{schemas:u,...Object.keys(b).length>0?{securitySchemes:b}:{}},...h?{security:h}:{},tags:f}}function Ze(e){return e.charAt(0).toUpperCase()+e.slice(1)}function De(e){return e.endsWith("ies")?e.slice(0,-3)+"y":e.endsWith("ses")||e.endsWith("xes")||e.endsWith("zes")?e.slice(0,-2):e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e}var Rt=class extends Error{constructor(n,r){super("Request validation failed");this.zodError=n;this.source=r;this.statusCode=400;this.name="ValidationError";}};var Gt=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},Jt=class extends Error{constructor(n){super("Output validation failed");this.zodError=n;this.statusCode=500;this.name="OutputValidationError";}};function ks(e){return e.issues.map(t=>({path:t.path.join("."),code:t.code,message:t.message}))}function Cs(e,t){return t instanceof Rt?e.json({success:false,error:"Validation failed",issues:ks(t.zodError)},400):t instanceof Gt?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof Jt?e.json({success:false,error:"Output validation failed",issues:ks(t.zodError)},500):null}extendZodWithOpenApi(z);var As="Successful response",Es="Error response";function ge(e,t=new Set){if(!e||typeof e!="object"||t.has(e))return;t.add(e);let n=e,r=n._zod?.def??n.def;if(!r)return;if(r.type==="custom"){let s=getOpenApiMetadata(n);s?.type||z.globalRegistry.add(n,{...s??{},type:"object"});return}if(r.innerType&&ge(r.innerType,t),r.element&&ge(r.element,t),r.valueType&&ge(r.valueType,t),r.keyType&&ge(r.keyType,t),r.left&&ge(r.left,t),r.right&&ge(r.right,t),r.in&&ge(r.in,t),r.out&&ge(r.out,t),typeof r.getter=="function")try{ge(r.getter(),t);}catch{}if(Array.isArray(r.options))for(let s of r.options)ge(s,t);if(Array.isArray(r.items))for(let s of r.items)ge(s,t);let o=typeof r.shape=="function"?r.shape():r.shape;if(o&&typeof o=="object")for(let s of Object.values(o))ge(s,t);}function Fr(e){if(!e||typeof e!="object")return;if(Array.isArray(e)){for(let n of e)Fr(n);return}let t=e;(Array.isArray(t.anyOf)||Array.isArray(t.oneOf))&&"type"in t&&delete t.type;for(let n of Object.values(t))Fr(n);}function yc(e){return e==="get"?"query":"json"}function mc(e,t){let n=t?.output;return n?typeof n=="function"?n(e):n:e}function hc(e){if(typeof e.safeParse=="function")return {description:Es,schema:e};let t=e;return {description:t.description??Es,schema:t.schema}}function Is(e,t,n,r){let o=new OpenAPIRegistry;if(n.securitySchemes)for(let[l,c]of Object.entries(n.securitySchemes))o.registerComponent("securitySchemes",l,c);for(let l of e){let c=l.method,u=l.source??yc(c),p=wc(t,l.path??"/"),f=l.status??200;l.input&&ge(l.input);let b=gc(c,u,l.input),h=Os(u,l.input,"query"),w=Os(u,l.input,"param"),T=xc(c,p),S=mc(l.output,r);S&&ge(S);let I={[f]:S?{description:As,content:{"application/json":{schema:S}}}:{description:As}};if(r?.errors)for(let[A,O]of Object.entries(r.errors)){let{description:x,schema:d}=hc(O);d&&ge(d),I[A]=d?{description:x,content:{"application/json":{schema:d}}}:{description:x};}o.registerPath({method:c,path:bc(p),operationId:T,summary:l.summary,description:l.description,tags:l.tags,deprecated:l.deprecated,security:l.security,request:{...h?{query:h}:{},...w?{params:w}:{},...b?{body:b}:{}},responses:I});}let a=new OpenApiGeneratorV31(o.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security});return Fr(a),a}function gc(e,t,n){return !n||e==="get"?null:t==="json"?{content:{"application/json":{schema:n}}}:t==="form"?{content:{"application/x-www-form-urlencoded":{schema:n}}}:null}function Os(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function bc(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function wc(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,o=`${n}${r}`;return o===""?"/":o}function xc(e,t){let n=t.replace(/[{}]/g,"").replace(/\/+/g,"_").replace(/[^A-Za-z0-9_]/g,"").replace(/^_+|_+$/g,"");return `${e}_${n||"root"}`}function Ds(e,t){let n=e.replace(/"/g,"&quot;");return `<!doctype html>
1162
1162
  <html lang="en">
1163
1163
  <head>
1164
1164
  <meta charset="utf-8" />
@@ -1169,5 +1169,5 @@ function initColumnReorder(table) {
1169
1169
  <script id="api-reference" data-url="${n}"></script>
1170
1170
  <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
1171
1171
  </body>
1172
- </html>`}function Ps(e){return typeof e=="object"&&e!==null&&e.__docsAuthExtension===true}var Nr=new AsyncLocalStorage;function Is(){return async(e,t)=>{await Nr.run({c:e},async()=>{await t();});}}var mc=Object.freeze({}),In=class{constructor(t){this.cachedSpec=null;this.options=t,this.app=new Hono,this.mountedRoutes=bc(t.routes,t.api),this.app.use("*",Zn(t.actorResolver)),t.services&&this.app.use("*",Is());let n=[...t.middlewares??[],...t.globalMiddlewares??[]];for(let r of n)this.app.use("*",r);this.mountRoutes(),this.mountOpenApi(),t.notFound&&this.app.notFound(t.notFound),t.onError&&this.app.onError(t.onError);}get hono(){return this.app}get nodeHandler(){return getRequestListener(this.app.fetch,{overrideGlobalObjects:false})}toFunction(t,n){let r=this.nodeHandler;return n?t(n,r):t(r)}buildOpenApiSpec(){if(this.cachedSpec)return this.cachedSpec;if(!this.options.openapi)throw new Error("[HonoServer] openapi config not set");return this.cachedSpec=Es(this.mountedRoutes,this.options.basePath??"",this.options.openapi,gc(this.options.interceptor)),this.cachedSpec}mountRoutes(){let t=this.options.basePath??"",n=this.options.validateOutput??false,r=this.options.verbose??false;for(let o of this.mountedRoutes){if(!o.path)throw new Error(`[HonoServer] route "${o.method.toUpperCase()} (no path)" \u2014 missing \`path\`. Run the codegen so the path is derived from the file location, or set it explicitly.`);let s=Pn(t,o.path),a=o.middlewares??[],l=o.source??(o.method==="get"?"query":"json"),c=Rc(o,l,n,hc(this.options.interceptor),this.options.services,this.options.errorHandler,this.options.logger),u=o.method.toUpperCase();this.app.on(u,[s],...a,c),r&&console.log(`[HonoServer] ${o.method.toUpperCase().padEnd(6)} ${s}`);}}mountOpenApi(){let t=this.options.openapi;if(!t)return;let n=t.path??"/openapi.json",r=t.docsPath===void 0?"/docs":t.docsPath,o=Pn(this.options.basePath??"",n),s=r===false?null:Pn(this.options.basePath??"",r),a;if(Ps(t.docsAuth)){let l=t.docsAuth;a=[l.middleware];let c=wc(s??o);for(let u of l.routes)this.app.on(u.method,[Pn(c,u.name)],u.handler);}else a=t.docsAuth?Array.isArray(t.docsAuth)?t.docsAuth:[t.docsAuth]:[];if(this.app.on("GET",[o],...a,l=>l.json(this.buildOpenApiSpec())),s){let l=xc(s,o);this.app.on("GET",[s],...a,c=>c.html(Os(l,t.info.title)));}}};function Ds(e){return typeof e=="object"&&e!==null&&typeof e.handler=="function"}function hc(e){if(e)return Ds(e)?e.handler:e}function gc(e){return Ds(e)?e:void 0}function bc(e,t){return t?e.filter(n=>Array.isArray(n.api)?n.api.includes(t):n.api===t):e.slice()}function Pn(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,o=`${n}${r}`;return o===""?"/":o}function wc(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function xc(e,t){let n=e.split("/").filter(Boolean),r=t.split("/").filter(Boolean);n.pop();let o=0;for(;o<n.length&&o<r.length&&n[o]===r[o];)o++;let s=n.length-o;return [...Array(s).fill(".."),...r.slice(o)].join("/")||"./"}function Rc(e,t,n,r,o,s,a){let l=e.input,c=e.output,u=e.status??200,p=o??mc;return async f=>{let w=async T=>{if(s){let S=await s.handle({error:T,c:f,route:e,services:p,logger:a});if(S)return S}return vs(f,T)},h=async()=>{let T,S;try{S=await Sc(f,t,e.method);}catch(C){throw new Vt(C instanceof Error?C.message:String(C))}if(l){let C=l.safeParse(S);if(!C.success)throw new wt(C.error,t);T=C.data;}else T=S;let I=await e.handler({input:T,c:f,services:p,errorHandler:s,logger:a});if(n&&c&&!(I instanceof Response)){let C=c.safeParse(I);if(!C.success)throw new Gt(C.error);return C.data}return I},b;if(r)try{b=await r({next:h,route:e,c:f,services:p,errorHandler:s,logger:a});}catch(T){let S=await w(T);if(S)return S;throw T}else try{b=await h();}catch(T){let S=await w(T);if(S)return S;throw T}return b instanceof Response?b:f.json(b,u)}}async function Sc(e,t,n){switch(t){case "json":{if(n==="get")return e.req.query();let r=await e.req.text();if(!r)return {};try{return JSON.parse(r)}catch(o){throw new Error(`Invalid JSON body: ${o instanceof Error?o.message:String(o)}`)}}case "query":return e.req.query();case "form":return await e.req.parseBody();case "param":return e.req.param();default:return {}}}function Fr(e){return e}async function $s(e,t){if(e?.length){for(let n of e)if(typeof n=="function")await n(t);else if(n&&typeof n.mutation=="function"){if(n.operations&&!n.operations.includes(t.operation))continue;await n.mutation(t);}}}async function Jt(e,t,n,r,o,s=t?"update":"create"){for(let a of Object.keys(n.changes))await $s(r[a],{body:e,doc:t,diff:n,key:a,operation:s,user:o});await $s(r["*"],{body:e,doc:t,diff:n,key:"*",operation:s,user:o});}function jr(e){return async t=>{await Jt(t.body,t.doc,t.diff,e,t.user,"update");}}function Br(e){return async t=>{let n=Te({},t.body);await Jt(t.body,null,n,e,t.user,"create");}}function zr(e){return e}async function Hs(e,t,n,r,o,s,a,l){if(!e?.length)return s;let c=s;for(let u of e){let p=null,f=false;try{if(f=!!await u.rule({diff:n,key:t,user:a,operation:l}),f){let w=await u.handler(r);w&&(c={...c,...w});}}catch(w){p=w;}o.push({key:String(t),description:u.description,isCalled:f,error:p});}return c}async function Dn(e,t,n,r,o="update"){let s=[],a={};for(let l of Object.keys(e.changes))a=await Hs(t[l],l,e,n,s,a,r,o);return a=await Hs(t["*"],"*",e,n,s,a,r,o),{results:s,changesNeeded:a,hasErrors:s.some(l=>l.error!==null)}}function qr(e,t,n){return async r=>{let o=t(r),{results:s,changesNeeded:a}=await Dn(r.diff,e,o,r.user,"update");if(n?.onRuleError)for(let l of s)l.error&&await n.onRuleError(l,r);return Object.keys(a).length>0?a:void 0}}function Ms(e){let{basePath:t="/",repos:n,parseBody:r=true,securityHeaders:o,verbose:s=false,httpsOptions:a}=e,l=t==="/"?"":t.replace(/\/$/,""),c={};for(let[d,y]of Object.entries(n)){if(!y.repo)throw new Error(`[createCrudServer] Repository "${d}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let i=y.schema??y.repo.schema??null;if(!i)throw new Error(`[createCrudServer] Repository "${d}" has no Zod schema.`);let g,m,A,k;if(y.fieldsConfig){let H=y.fieldsConfig;g=[],m=[],A=[],k=[];for(let[D,F]of Object.entries(H))for(let j of F)j==="filterable"?g.push(D):j==="orderable"?m.push(D):j==="mutable"?A.push(D):j==="create"&&k.push(D);m.length===0&&(m=g),g.length===0&&(g=void 0),m&&m.length===0&&(m=void 0),A.length===0&&(A=void 0),k.length===0&&(k=void 0);}let R=(()=>{let H=y.repo._parentKeys;return H&&H.length>0?H:void 0})();if(R&&k)for(let H of R)k.includes(H)||k.push(H);let P=y.repo._systemKeys??[y.documentKey??"docId"],M=y.repo._historyIdentityKeys??[],$=Array.from(new Set([...P,...M])),_=y.repo._historyConfig,v=_?.enabled&&_.autoInjectMeta!==false?Ce(_):null,E=v?{reason:v.fields.reason!==false,comment:v.fields.comment!==false}:void 0,N={name:d,path:y.path,repo:y.repo,schema:i,systemKeys:$,documentKey:y.documentKey??"docId",pathKey:y.repo._pathKey??void 0,isGroup:!!y.repo._isGroup,parentKeys:R,documentPathTemplate:y.repo._documentPathTemplate??void 0,createdKey:y.repo._createdKey??void 0,pageSize:y.pageSize??25,filterableFields:g,orderableFields:m,mutableFields:A,createFields:k,allowDelete:y.allowDelete??false,allowedIncludes:y.allowedIncludes,validate:y.validate,rules:y.rules,hooks:y.hooks,...E?{historyHeaders:E}:{}};c[d]=N;}let u=e.indexesError??e.onIndexError,p=bs(c,l,s,u,e.onHookError),f=e.openapi,w=f&&typeof f=="object"?f:{},h=Kn(e.actorResolver),b=w.historyHeaders===false?false:{reasonHeader:w.historyHeaders?.reasonHeader!==void 0?w.historyHeaders.reasonHeader:h.reasonHeader,commentHeader:w.historyHeaders?.commentHeader!==void 0?w.historyHeaders.commentHeader:h.commentHeader,...w.historyHeaders?.extraHeaders?{extraHeaders:w.historyHeaders.extraHeaders}:{}},T=(()=>{let d=["Content-Type","Authorization"],y=new Set(d.map(g=>g.toLowerCase())),i=g=>{if(typeof g!="string")return;let m=g.trim();!m||y.has(m.toLowerCase())||(y.add(m.toLowerCase()),d.push(m));};if(i(h.reasonHeader),i(h.commentHeader),w.historyHeaders&&typeof w.historyHeaders=="object"&&(i(w.historyHeaders.reasonHeader),i(w.historyHeaders.commentHeader),w.historyHeaders.extraHeaders))for(let g of w.historyHeaders.extraHeaders)i(typeof g=="string"?g:g?.name);return d.join(", ")})(),S=null;function I(){return S||(S=Mr(c,l,{...w,auth:w.auth??false,historyHeaders:b})),S}let C=[];for(let d of Object.keys(c))C.push({api:"crud",method:"post",path:`/${d}/query`,source:"json",handler:p.handleQuery}),C.push({api:"crud",method:"get",path:`/${d}/:id`,source:"query",handler:p.handleGet}),C.push({api:"crud",method:"post",path:`/${d}`,source:"json",handler:p.handleCreate}),C.push({api:"crud",method:"put",path:`/${d}/:id`,source:"json",handler:y=>p.handleUpdate(y,false)}),C.push({api:"crud",method:"patch",path:`/${d}/:id`,source:"json",handler:y=>p.handleUpdate(y,true)}),C.push({api:"crud",method:"delete",path:`/${d}/:id`,source:"query",handler:p.handleDelete}),C.push({api:"crud",method:"post",path:`/${d}/batch`,source:"json",handler:p.handleBatch});let O=new In({...e,openapi:f!==false?{path:w.path??"/openapi.json",docsPath:w.docsPath??"/docs",info:{title:w.title??"CRUD API",version:w.version??"1.0.0"},docsAuth:w.docsAuth}:void 0,basePath:t,api:"crud",routes:C,middlewares:[async(d,y)=>{if(d.req.method==="OPTIONS")return d.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":T,"Access-Control-Max-Age":"86400","Access-Control-Allow-Origin":"*","Access-Control-Allow-Credentials":"true"});d.header("Access-Control-Allow-Origin","*"),d.header("Access-Control-Allow-Credentials","true"),await y();},...e.middlewares||[]]});if(f!==false&&(O.buildOpenApiSpec=I),o!==false){let{securityHeaders:d}=(Tn(),Ls(ds)),y=o===void 0?{csp:false}:o;O.hono.use("*",async(i,g)=>{let m=d(y);await new Promise(A=>{let k=i.req.raw;m(k,{setHeader:(P,M)=>i.header(P,M),removeHeader:P=>i.res.headers.delete(P)},()=>A());}),await g();});}let x=O.nodeHandler;return x.spec=I,a&&(x.httpsOptions=a),x}function _s(e,t){if(!t.onRequest)return e;let n=e.httpsOptions??t.httpsOptions,r=n?t.onRequest(n,e):t.onRequest(e),o=e.spec;return typeof o=="function"&&(r.spec=o),r}function Ns(e,t,n){let r={},o=e?.rawMapping;for(let[s,a]of Object.entries(t)){if(!a)continue;if(!(o?s in o:!!e[s]))throw new Error(`[createServers.${n}] Unknown repo "${s}" \u2014 not present in the registry passed to createServers().`);let c=o?ln(o[s],()=>e[s]):e[s];r[s]={...a,repo:c};}return r}function Fs(e,t={}){return {admin(n){let r=Ns(e,n.repos,"admin"),o=ps({...n,repos:r,httpsOptions:n.httpsOptions??t.httpsOptions});return _s(o,t)},crud(n){let r=Ns(e,n.repos,"crud"),o=Ms({...n,repos:r,httpsOptions:n.httpsOptions??t.httpsOptions,actorResolver:n.actorResolver??t.actorResolver});return _s(o,t)},sync(n){let r=t.triggerOptions||n.triggerOptions?{...t.triggerOptions,...n.triggerOptions}:void 0,o={...n,...r?{triggerOptions:r}:{}};return t.onRequest&&o.admin&&!o.admin.onRequest&&(o.admin={...o.admin,onRequest:t.onRequest,httpsOptions:o.admin.httpsOptions??t.httpsOptions}),Fo(e,o)},meilisearchAdapter(n){return ()=>new gn(n)},history(n){let r=t.triggerOptions||n.triggerOptions?{...t.triggerOptions,...n.triggerOptions}:void 0,o={...n,...r?{triggerOptions:r}:{}};return So(e,o)}}}Tn();function of(e){return t=>({...t,schema:e,type:null,documentRef:null,update:null})}function sf(e,t){let n={...e};for(let r in t)t[r]&&(n[r]={...e[r],relationalKeys:t[r]});return n}var Ur=class{constructor(t,n){this.allRepositories={};this.initialized=false;this.dbFactory=t,this.mapping=n;}get db(){return this._db??(this._db=this.dbFactory())}get rawMapping(){return this.mapping}ensureInitialized(){this.initialized||(this.initializeRepositories(),this.initialized=true);}initializeRepositories(){let t=this.db;for(let n of Object.keys(this.mapping))this.allRepositories[n]=tr(t,this.mapping[n],{});for(let n of Object.keys(this.mapping))this.allRepositories[n]=tr(t,this.mapping[n],this.allRepositories);}getRepository(t){return this.ensureInitialized(),this.allRepositories[t]}};function af(e,t){let n=new Ur(e,t),r=Object.keys(t);return new Proxy(n,{get(o,s){return typeof s=="string"&&s in t?o.getRepository(s):o[s]},has(o,s){return typeof s=="string"&&s in t?true:s in o},ownKeys(){return r},getOwnPropertyDescriptor(o,s){if(typeof s=="string"&&s in t)return {configurable:true,enumerable:true,writable:false}}})}export{Ve as DEFAULT_HISTORY_COMMENT_HEADER,Qe as DEFAULT_HISTORY_REASON_HEADER,Wn as DEFAULT_HISTORY_SHADOW_KEY,_e as MiniRouter,Ur as RepositoryMapping,Dn as applyEffects,Jt as applyMutations,je as applyPaginationQueryOptions,kn as applyRules,Fn as buildAndCountQuery,We as buildAndExecuteQuery,sf as buildRepositoryRelations,Bn as coerceToDate,Te as computeDeepDiff,Zn as createActorContextMiddleware,Ln as createActorResolver,qr as createAfterUpdateEffects,Br as createBeforeCreateMutations,Or as createBeforeRules,jr as createBeforeUpdateMutations,zr as createEffects,Fr as createMutations,zn as createPaginationIterator,of as createRepositoryConfig,af as createRepositoryMapping,Er as createRules,Fs as createServers,oo as defaultActorResolver,nn as executePaginatedQuery,Kn as getActorResolverHeaders,lt as getCurrentActor,tn as getDateHandling,en as normalizeTimestamps,na as setDateHandling,la as setRequestActorMeta,ca as withActor};//# sourceMappingURL=index.js.map
1172
+ </html>`}function $s(e){return typeof e=="object"&&e!==null&&e.__docsAuthExtension===true}var Nr=new AsyncLocalStorage;function Hs(){return async(e,t)=>{await Nr.run({c:e},async()=>{await t();});}}var Tc=Object.freeze({}),Dn=class{constructor(t){this.cachedSpec=null;this.options=t,this.app=new Hono,this.mountedRoutes=Ac(t.routes,t.api),this.app.use("*",Wn(t.actorResolver)),t.services&&this.app.use("*",Hs());let n=[...t.middlewares??[],...t.globalMiddlewares??[]];for(let r of n)this.app.use("*",r);this.mountRoutes(),this.mountOpenApi(),t.notFound&&this.app.notFound(t.notFound),t.onError&&this.app.onError(t.onError);}get hono(){return this.app}get nodeHandler(){return getRequestListener(this.app.fetch,{overrideGlobalObjects:false})}toFunction(t,n){let r=this.nodeHandler;return n?t(n,r):t(r)}buildOpenApiSpec(){if(this.cachedSpec)return this.cachedSpec;if(!this.options.openapi)throw new Error("[HonoServer] openapi config not set");return this.cachedSpec=Is(this.mountedRoutes,this.options.basePath??"",this.options.openapi,Cc(this.options.interceptor)),this.cachedSpec}mountRoutes(){let t=this.options.basePath??"",n=this.options.validateOutput??false,r=this.options.verbose??false;for(let o of this.mountedRoutes){if(!o.path)throw new Error(`[HonoServer] route "${o.method.toUpperCase()} (no path)" \u2014 missing \`path\`. Run the codegen so the path is derived from the file location, or set it explicitly.`);let s=In(t,o.path),a=o.middlewares??[],l=o.source??(o.method==="get"?"query":"json"),c=Pc(o,l,n,kc(this.options.interceptor),this.options.services,this.options.errorHandler,this.options.logger),u=o.method.toUpperCase();this.app.on(u,[s],...a,c),r&&console.log(`[HonoServer] ${o.method.toUpperCase().padEnd(6)} ${s}`);}}mountOpenApi(){let t=this.options.openapi;if(!t)return;let n=t.path??"/openapi.json",r=t.docsPath===void 0?"/docs":t.docsPath,o=In(this.options.basePath??"",n),s=r===false?null:In(this.options.basePath??"",r),a;if($s(t.docsAuth)){let l=t.docsAuth;a=[l.middleware];let c=Ec(s??o);for(let u of l.routes)this.app.on(u.method,[In(c,u.name)],u.handler);}else a=t.docsAuth?Array.isArray(t.docsAuth)?t.docsAuth:[t.docsAuth]:[];if(this.app.on("GET",[o],...a,l=>l.json(this.buildOpenApiSpec())),s){let l=Oc(s,o);this.app.on("GET",[s],...a,c=>c.html(Ds(l,t.info.title)));}}};function _s(e){return typeof e=="object"&&e!==null&&typeof e.handler=="function"}function kc(e){if(e)return _s(e)?e.handler:e}function Cc(e){return _s(e)?e:void 0}function Ac(e,t){return t?e.filter(n=>Array.isArray(n.api)?n.api.includes(t):n.api===t):e.slice()}function In(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,o=`${n}${r}`;return o===""?"/":o}function Ec(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function Oc(e,t){let n=e.split("/").filter(Boolean),r=t.split("/").filter(Boolean);n.pop();let o=0;for(;o<n.length&&o<r.length&&n[o]===r[o];)o++;let s=n.length-o;return [...Array(s).fill(".."),...r.slice(o)].join("/")||"./"}function Pc(e,t,n,r,o,s,a){let l=e.input,c=e.output,u=e.status??200,p=o??Tc;return async f=>{let b=async T=>{if(s){let S=await s.handle({error:T,c:f,route:e,services:p,logger:a});if(S)return S}return Cs(f,T)},h=async()=>{let T,S;try{S=await Ic(f,t,e.method);}catch(A){throw new Gt(A instanceof Error?A.message:String(A))}if(l){let A=l.safeParse(S);if(!A.success)throw new Rt(A.error,t);T=A.data;}else T=S;let I=await e.handler({input:T,c:f,services:p,errorHandler:s,logger:a});if(n&&c&&!(I instanceof Response)){let A=c.safeParse(I);if(!A.success)throw new Jt(A.error);return A.data}return I},w;if(r)try{w=await r({next:h,route:e,c:f,services:p,errorHandler:s,logger:a});}catch(T){let S=await b(T);if(S)return S;throw T}else try{w=await h();}catch(T){let S=await b(T);if(S)return S;throw T}return w instanceof Response?w:f.json(w,u)}}async function Ic(e,t,n){switch(t){case "json":{if(n==="get")return e.req.query();let r=await e.req.text();if(!r)return {};try{return JSON.parse(r)}catch(o){throw new Error(`Invalid JSON body: ${o instanceof Error?o.message:String(o)}`)}}case "query":return e.req.query();case "form":return await e.req.parseBody();case "param":return e.req.param();default:return {}}}function jr(e){return e}async function Ms(e,t){if(e?.length){for(let n of e)if(typeof n=="function")await n(t);else if(n&&typeof n.mutation=="function"){if(n.operations&&!n.operations.includes(t.operation))continue;await n.mutation(t);}}}async function Yt(e,t,n,r,o,s=t?"update":"create"){for(let a of Object.keys(n.changes))await Ms(r[a],{body:e,doc:t,diff:n,key:a,operation:s,user:o});await Ms(r["*"],{body:e,doc:t,diff:n,key:"*",operation:s,user:o});}function Br(e){return async t=>{await Yt(t.body,t.doc,t.diff,e,t.user,"update");}}function zr(e){return async t=>{let n=Te({},t.body);await Yt(t.body,null,n,e,t.user,"create");}}function qr(e){return e}async function Fs(e,t,n,r,o,s,a,l){if(!e?.length)return s;let c=s;for(let u of e){let p=null,f=false;try{if(f=!!await u.rule({diff:n,key:t,user:a,operation:l}),f){let b=await u.handler(r);b&&(c={...c,...b});}}catch(b){p=b;}o.push({key:String(t),description:u.description,isCalled:f,error:p});}return c}async function $n(e,t,n,r,o="update"){let s=[],a={};for(let l of Object.keys(e.changes))a=await Fs(t[l],l,e,n,s,a,r,o);return a=await Fs(t["*"],"*",e,n,s,a,r,o),{results:s,changesNeeded:a,hasErrors:s.some(l=>l.error!==null)}}function Ur(e,t,n){return async r=>{let o=t(r),{results:s,changesNeeded:a}=await $n(r.diff,e,o,r.user,"update");if(n?.onRuleError)for(let l of s)l.error&&await n.onRuleError(l,r);return Object.keys(a).length>0?a:void 0}}function Ns(e){let{basePath:t="/",repos:n,parseBody:r=true,securityHeaders:o,verbose:s=false,httpsOptions:a}=e,l=t==="/"?"":t.replace(/\/$/,""),c={};for(let[d,y]of Object.entries(n)){if(!y.repo)throw new Error(`[createCrudServer] Repository "${d}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let i=y.schema??y.repo.schema??null;if(!i)throw new Error(`[createCrudServer] Repository "${d}" has no Zod schema.`);let g,m,C,k;if(y.fieldsConfig){let H=y.fieldsConfig;g=[],m=[],C=[],k=[];for(let[D,N]of Object.entries(H))for(let j of N)j==="filterable"?g.push(D):j==="orderable"?m.push(D):j==="mutable"?C.push(D):j==="create"&&k.push(D);m.length===0&&(m=g),g.length===0&&(g=void 0),m&&m.length===0&&(m=void 0),C.length===0&&(C=void 0),k.length===0&&(k=void 0);}let R=(()=>{let H=y.repo._parentKeys;return H&&H.length>0?H:void 0})();if(R&&k)for(let H of R)k.includes(H)||k.push(H);let P=y.repo._systemKeys??[y.documentKey??"docId"],_=y.repo._historyIdentityKeys??[],$=Array.from(new Set([...P,..._])),M=y.repo._historyConfig,v=M?.enabled&&M.autoInjectMeta!==false?Ee(M):null,E=v?{reason:v.fields.reason!==false,comment:v.fields.comment!==false}:void 0,F={name:d,path:y.path,repo:y.repo,schema:i,systemKeys:$,documentKey:y.documentKey??"docId",pathKey:y.repo._pathKey??void 0,isGroup:!!y.repo._isGroup,parentKeys:R,documentPathTemplate:y.repo._documentPathTemplate??void 0,createdKey:y.repo._createdKey??void 0,pageSize:y.pageSize??25,filterableFields:g,orderableFields:m,mutableFields:C,createFields:k,allowDelete:y.allowDelete??false,allowedIncludes:y.allowedIncludes,validate:y.validate,rules:y.rules,hooks:y.hooks,...E?{historyHeaders:E}:{}};c[d]=F;}let u=e.indexesError??e.onIndexError,p=Rs(c,l,s,u,e.onHookError),f=e.openapi,b=f&&typeof f=="object"?f:{},h=Zn(e.actorResolver),w=b.historyHeaders===false?false:{reasonHeader:b.historyHeaders?.reasonHeader!==void 0?b.historyHeaders.reasonHeader:h.reasonHeader,commentHeader:b.historyHeaders?.commentHeader!==void 0?b.historyHeaders.commentHeader:h.commentHeader,...b.historyHeaders?.extraHeaders?{extraHeaders:b.historyHeaders.extraHeaders}:{}},T=(()=>{let d=["Content-Type","Authorization"],y=new Set(d.map(g=>g.toLowerCase())),i=g=>{if(typeof g!="string")return;let m=g.trim();!m||y.has(m.toLowerCase())||(y.add(m.toLowerCase()),d.push(m));};if(i(h.reasonHeader),i(h.commentHeader),b.historyHeaders&&typeof b.historyHeaders=="object"&&(i(b.historyHeaders.reasonHeader),i(b.historyHeaders.commentHeader),b.historyHeaders.extraHeaders))for(let g of b.historyHeaders.extraHeaders)i(typeof g=="string"?g:g?.name);return d.join(", ")})(),S=null;function I(){return S||(S=Mr(c,l,{...b,auth:b.auth??false,historyHeaders:w})),S}let A=[];for(let d of Object.keys(c))A.push({api:"crud",method:"post",path:`/${d}/query`,source:"json",handler:p.handleQuery}),A.push({api:"crud",method:"get",path:`/${d}/:id`,source:"query",handler:p.handleGet}),A.push({api:"crud",method:"post",path:`/${d}`,source:"json",handler:p.handleCreate}),A.push({api:"crud",method:"put",path:`/${d}/:id`,source:"json",handler:y=>p.handleUpdate(y,false)}),A.push({api:"crud",method:"patch",path:`/${d}/:id`,source:"json",handler:y=>p.handleUpdate(y,true)}),A.push({api:"crud",method:"delete",path:`/${d}/:id`,source:"query",handler:p.handleDelete}),A.push({api:"crud",method:"post",path:`/${d}/batch`,source:"json",handler:p.handleBatch});let O=new Dn({...e,openapi:f!==false?{path:b.path??"/openapi.json",docsPath:b.docsPath??"/docs",info:{title:b.title??"CRUD API",version:b.version??"1.0.0"},docsAuth:b.docsAuth}:void 0,basePath:t,api:"crud",routes:A,middlewares:[async(d,y)=>{if(d.req.method==="OPTIONS")return d.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":T,"Access-Control-Max-Age":"86400","Access-Control-Allow-Origin":"*","Access-Control-Allow-Credentials":"true"});d.header("Access-Control-Allow-Origin","*"),d.header("Access-Control-Allow-Credentials","true"),await y();},...e.middlewares||[]]});if(f!==false&&(O.buildOpenApiSpec=I),o!==false){let{securityHeaders:d}=(kn(),Ws(fs)),y=o===void 0?{csp:false}:o;O.hono.use("*",async(i,g)=>{let m=d(y);await new Promise(C=>{let k=i.req.raw;m(k,{setHeader:(P,_)=>i.header(P,_),removeHeader:P=>i.res.headers.delete(P)},()=>C());}),await g();});}let x=O.nodeHandler;return x.spec=I,a&&(x.httpsOptions=a),x}function js(e,t){if(!t.onRequest)return e;let n=e.httpsOptions??t.httpsOptions,r=n?t.onRequest(n,e):t.onRequest(e),o=e.spec;return typeof o=="function"&&(r.spec=o),r}function Bs(e,t,n){let r={},o=e?.rawMapping;for(let[s,a]of Object.entries(t)){if(!a)continue;if(!(o?s in o:!!e[s]))throw new Error(`[createServers.${n}] Unknown repo "${s}" \u2014 not present in the registry passed to createServers().`);let c=o?dn(o[s],()=>e[s]):e[s];r[s]={...a,repo:c};}return r}function zs(e,t={}){return {admin(n){let r=Bs(e,n.repos,"admin"),o=ms({...n,repos:r,httpsOptions:n.httpsOptions??t.httpsOptions});return js(o,t)},crud(n){let r=Bs(e,n.repos,"crud"),o=Ns({...n,repos:r,httpsOptions:n.httpsOptions??t.httpsOptions,actorResolver:n.actorResolver??t.actorResolver});return js(o,t)},sync(n){let r=t.triggerOptions||n.triggerOptions?{...t.triggerOptions,...n.triggerOptions}:void 0,o={...n,...r?{triggerOptions:r}:{}};return t.onRequest&&o.admin&&!o.admin.onRequest&&(o.admin={...o.admin,onRequest:t.onRequest,httpsOptions:o.admin.httpsOptions??t.httpsOptions}),zo(e,o)},meilisearchAdapter(n){return ()=>new bn(n)},history(n){let r=t.triggerOptions||n.triggerOptions?{...t.triggerOptions,...n.triggerOptions}:void 0,o={...n,...r?{triggerOptions:r}:{}};return ko(e,o)}}}kn();function mf(e){return t=>({...t,schema:e,type:null,documentRef:null,update:null})}function hf(e,t){let n={...e};for(let r in t)t[r]&&(n[r]={...e[r],relationalKeys:t[r]});return n}var Lr=class{constructor(t,n){this.allRepositories={};this.initialized=false;this.dbFactory=t,this.mapping=n;}get db(){return this._db??(this._db=this.dbFactory())}get rawMapping(){return this.mapping}ensureInitialized(){this.initialized||(this.initializeRepositories(),this.initialized=true);}initializeRepositories(){let t=this.db;for(let n of Object.keys(this.mapping))this.allRepositories[n]=nr(t,this.mapping[n],{});for(let n of Object.keys(this.mapping))this.allRepositories[n]=nr(t,this.mapping[n],this.allRepositories);}getRepository(t){return this.ensureInitialized(),this.allRepositories[t]}};function gf(e,t){let n=new Lr(e,t),r=Object.keys(t);return new Proxy(n,{get(o,s){return typeof s=="string"&&s in t?o.getRepository(s):o[s]},has(o,s){return typeof s=="string"&&s in t?true:s in o},ownKeys(){return r},getOwnPropertyDescriptor(o,s){if(typeof s=="string"&&s in t)return {configurable:true,enumerable:true,writable:false}}})}export{Ge as DEFAULT_HISTORY_COMMENT_HEADER,Ve as DEFAULT_HISTORY_REASON_HEADER,Qn as DEFAULT_HISTORY_SHADOW_KEY,Me as MiniRouter,Lr as RepositoryMapping,$n as applyEffects,Yt as applyMutations,je as applyPaginationQueryOptions,Cn as applyRules,jn as buildAndCountQuery,Qe as buildAndExecuteQuery,hf as buildRepositoryRelations,zn as coerceToDate,Te as computeDeepDiff,Wn as createActorContextMiddleware,Kn as createActorResolver,Ur as createAfterUpdateEffects,zr as createBeforeCreateMutations,Pr as createBeforeRules,Br as createBeforeUpdateMutations,qr as createEffects,jr as createMutations,qn as createPaginationIterator,mf as createRepositoryConfig,gf as createRepositoryMapping,Or as createRules,zs as createServers,io as defaultActorResolver,rn as executePaginatedQuery,Zn as getActorResolverHeaders,ut as getCurrentActor,nn as getDateHandling,tn as normalizeTimestamps,ua as setDateHandling,ba as setRequestActorMeta,ga as withActor};//# sourceMappingURL=index.js.map
1173
1173
  //# sourceMappingURL=index.js.map