@lpdjs/firestore-repo-service 2.6.37 → 2.6.39

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.
@@ -1,4 +1,4 @@
1
- import {jsx,jsxs,Fragment}from'hono/jsx/jsx-runtime';import {Timestamp}from'firebase-admin/firestore';import {randomUUID,randomBytes}from'crypto';import {z as z$1}from'zod';import {renderToString}from'hono/jsx/dom/server';import {Hono}from'hono';import {getRequestListener}from'@hono/node-server';import {extendZodWithOpenApi,OpenAPIRegistry,OpenApiGeneratorV31}from'@asteasolutions/zod-to-openapi';import {AsyncLocalStorage}from'async_hooks';var bt=Object.defineProperty;var Tr=Object.getOwnPropertyDescriptor;var Ar=Object.getOwnPropertyNames;var Cr=Object.prototype.hasOwnProperty;var je=(e,t)=>()=>(e&&(t=e(e=0)),t);var sn=(e,t)=>{for(var n in t)bt(e,n,{get:t[n],enumerable:true});},Or=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ar(t))!Cr.call(e,o)&&o!==n&&bt(e,o,{get:()=>t[o],enumerable:!(r=Tr(t,o))||r.enumerable});return e};var Er=e=>Or(bt({},"__esModule",{value:true}),e);function q(e){let t=e,n=t._zod?.def?.type;if(n)return Ur[n]??`Zod${n.charAt(0).toUpperCase()}${n.slice(1)}`;let r=t._def?.typeName;return r||""}function X(e){let t=e;if(t._zod?.def?.innerType)return t._zod.def.innerType;if(t._def?.innerType)return t._def.innerType}function He(e){let t=e,n=t._zod?.def?.in;if(n)return n;if(t._def?.schema)return t._def.schema}function gn(e){let t=e;if(t._zod?.def?.element)return t._zod.def.element;if(t._def?.type)return t._def.type}function hn(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 Y(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 Ne(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 ze(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 Be(e){let t=e;return Array.isArray(t._zod?.def?.values)?t._zod.def.values[0]:t._def?.value}function qe(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 bn(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 Ur,Ze=je(()=>{Ur={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 Mn({val:e}){return jsx("span",{class:"text-sm text-base-content/80 font-mono tabular-nums whitespace-nowrap",children:e.toLocaleString()})}function yo({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 Pe({val:e,mismatch:t}){let n=Dt(e);return t?jsxs("span",{class:"inline-flex items-start gap-0.5",children:[n,jsx(yo,{message:t})]}):n}function Dt(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(Mn,{val:e});if(typeof e=="object"&&e!==null&&typeof e.toDate=="function")return jsx(Mn,{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:Dt(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:Dt(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 ct=je(()=>{});function We(e){if(!e)return "unknown";let t=_t(e);switch(q(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 _t(e){let t=q(e);if(t==="ZodOptional"||t==="ZodNullable"||t==="ZodDefault"){let n=X(e);return n?_t(n):e}return e}function Qe(e,t){if(!e)return;let n=t.split("."),r=e;for(let o of n){if(!r)return;let s=_t(r);if(q(s)!=="ZodObject")return;r=Y(s)[o];}return r}function bo(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 Ge(e,t){if(e==="unknown")return null;let n=bo(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 jt=je(()=>{Ze();});var zn={};sn(zn,{PanelMany:()=>vo,PanelOne:()=>wo,RightPanel:()=>Ft});function wo({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`,p=Nn(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(d=>{let b=e[d],v=p[d],x=v?Ge(v,b):null;return jsxs(Fragment,{children:[jsx("dt",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide pt-0.5",children:d}),jsx("dd",{class:"min-w-0",children:jsx(Pe,{val:b,mismatch:x})})]})})})]})}function vo({docs:e,repoName:t,basePath:n,fk:r,fv:o,columns:s,schema:a,pagination:p}){let d=`${n}/${t}?fv_${r}=${encodeURIComponent(o)}`,b=Nn(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:d,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((v,x)=>jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:v},x)),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((v,x)=>{let A=String(v.docId??v.id??""),S=`${n}/${t}/${encodeURIComponent(A)}/edit`;return jsxs("tr",{class:"hover",children:[s.map((g,k)=>{let m=v[g],y=b[g],i=y?Ge(y,m):null;return jsx("td",{class:"align-top py-1.5",children:jsx(Pe,{val:m,mismatch:i})},k)}),jsx("td",{class:"text-right py-1.5",children:jsx("a",{href:S,class:"btn btn-xs btn-ghost",children:"Edit"})})]},x)})})]})}),(p.hasPrev||p.hasNext)&&jsxs("div",{class:"flex justify-center items-center gap-2",children:[p.hasPrev?jsx("button",{type:"button",class:"btn btn-xs btn-outline","data-frs-panel-page":"prev","data-cursor":p.prevCursor,children:"\u2190 Previous"}):jsx("button",{class:"btn btn-xs btn-outline",disabled:true,children:"\u2190 Previous"}),p.hasNext?jsx("button",{type:"button",class:"btn btn-xs btn-outline","data-frs-panel-page":"next","data-cursor":p.nextCursor,children:"Next \u2192"}):jsx("button",{class:"btn btn-xs btn-outline",disabled:true,children:"Next \u2192"})]})]})}function Nn(e,t){if(!e)return {};let n={};for(let r of t)n[r]=We(Qe(e,r));return n}var Ft,Mt=je(()=>{ct();jt();Ft=({basePath:e=""})=>jsxs("div",{class:"fixed inset-0 z-[100] hidden pointer-events-none","data-frs-panel-root":true,"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":true}),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":true,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":true,children:"Relation"}),jsx("button",{type:"button",class:"btn btn-sm btn-ghost btn-circle","data-frs-panel-close":true,"aria-label":"Close panel",children:"\u2715"})]}),jsx("div",{class:"flex-1 overflow-auto p-5 text-sm","data-frs-panel-body":true,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 er={};sn(er,{DEFAULT_HTML_CSP:()=>Jt,securityHeaders:()=>pt});function pt(e={}){let t=e.csp===void 0?Jt: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,p)=>{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 p();}}var Xn,Yn,Jt,ft=je(()=>{Xn="https://cdn.jsdelivr.net",Yn="https://www.gstatic.com",Jt=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${Xn} ${Yn}`,`style-src 'self' 'unsafe-inline' ${Xn}`,`connect-src 'self' ${Yn} 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("; ");});function wt(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 vt(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(!vt(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)||!vt(e[s],t[s],n))return false;return true}return false}function xt(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??{},p=new Set([...Object.keys(s),...Object.keys(a)]),d={};for(let b of p){if(r.has(b)||o&&!o.has(b))continue;let v=s[b],x=a[b];vt(v,x)||(d[b]={oldValue:v===void 0?null:v,newValue:x===void 0?null:x,type:{old:wt(v),new:wt(x)}});}return d}var $r=7e5;function Rt(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,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,p)=>p instanceof Timestamp?p.toMillis():p),"utf8")}catch{return 0}};if(o(r.changes)>$r){let s={};for(let[a,p]of Object.entries(r.changes)){let d=o(p.oldValue),b=o(p.newValue);s[a]={oldValue:d>5e4?"[truncated]":p.oldValue,newValue:b>5e4?"[truncated]":p.newValue,type:p.type};}r.changes=s,r._truncated=true;}return r}async function kt(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 Tt(e,t){let n=e??{},r={},o=t.meta;if(!o)return r;let s=v=>{if(!v)return;let x=n[v];return x===void 0||x===null?null:String(x)},a=s(o.userId);a!==void 0&&(r.userId=a);let p=s(o.userEmail);p!==void 0&&(r.userEmail=p);let d=s(o.reason);d!==void 0&&(r.reason=d);let b=s(o.comment);if(b!==void 0&&(r.comment=b),o.extras&&o.extras.length>0){let v={},x=false;for(let A of o.extras)A in n&&(v[A]=n[A],x=true);x&&(r.extras=v);}return r}function At(e){let t=e.meta;if(!t)return [];let n=[];return t.userId&&n.push(t.userId),t.userEmail&&n.push(t.userEmail),t.reason&&n.push(t.reason),t.comment&&n.push(t.comment),t.extras&&n.push(...t.extras),n}var Ir="history";function Dr(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(r=>typeof r=="string");return {historyConfig:t,systemKeys:n,isGroup:!!e?.isGroup,collectionPath:typeof e?.path=="string"?e.path:null}}function _r(e){return {historyConfig:e._historyConfig??(typeof e.history=="object"&&e.history!==null&&"enabled"in e.history?e.history:void 0),systemKeys:e._systemKeys??[],isGroup:!!e._isGroup,collectionPath:e.ref?.path??null}}function jr(e,t){return t?`${t}/{docId}`:(console.warn(`[HistoryTriggers] Cannot determine collection path for "${e}". Skipping.`),null)}function an(e,t){let{onDocumentWritten:n}=t.deps,r={},o=e?.rawMapping,s=o?Object.entries(o).map(([a,p])=>[a,Dr(p)]):Object.entries(e).map(([a,p])=>[a,_r(p)]);for(let[a,p]of s){let d=p.historyConfig;if(!d?.enabled)continue;let b=d.subcollection??Ir,v=d.ttl??t.defaults?.ttl,x=t.repos?.[a],A;if(p.isGroup){if(!x?.triggerPath){console.warn(`[HistoryTriggers] Skipping collection-group repo "${a}". Provide a triggerPath in the history triggers repos override.`);continue}A=x.triggerPath;}else A=x?.triggerPath??jr(a,p.collectionPath);if(!A)continue;let S=p.systemKeys,g=S[0]??"docId",k=At(d);r[`${a}_onHistory`]=n(A,async m=>{try{let y=m.data?.before?.data(),i=m.data?.after?.data(),u;if(!y&&i)u="create";else if(y&&!i)u="delete";else if(y&&i)u="update";else return;let l=String(i?.[g]??y?.[g]??m.params?.docId??m.data?.after?.id??m.data?.before?.id??"");if(!l)return;let c=xt(y??{},i??{},{include:d.include,exclude:d.exclude,metaFields:k,systemKeys:S});if(u==="update"&&Object.keys(c).length===0)return;let f=Tt(i??y??null,d),h=Rt({entityId:l,operation:u,changes:c,meta:f,config:d,ttlOverride:v}),w=m.data?.after?.ref??m.data?.before?.ref;if(!w)return;let O=w.collection(b);await kt(O,h,d,{repoName:a,docId:l,before:y??null,after:i??null});}catch(y){console.error(`[HistoryTriggers] Failed to record history for "${a}":`,y);}});}return r}var dn="preserve";function un(){return dn}function Fr(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function pn(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(Fr(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 xe(e){return e}function Nr(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 zr(e){let t=[e?.documentKey,e?.pathKey,e?.createdKey,e?.updatedKey].filter(r=>typeof r=="string"),n=e?.history&&typeof e.history=="object"?e.history:void 0;return {schema:e?.schema,_systemKeys:t,_pathKey:e?.pathKey??null,_isGroup:!!e?.isGroup,_createdKey:e?.createdKey??null,_parentKeys:e?.isGroup?Nr(e?.refCb):[],relationalKeys:e?.relationalKeys,_historyConfig:n,_historySubcollection:n?.enabled?n.subcollection??"history":void 0,_collectionPath:typeof e?.path=="string"?e.path:null}}function rt(e,t){let n=zr(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 Br(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 qr(e){let t=e.path??e.url??"/",n=t.indexOf("?");return n===-1?t:t.slice(0,n)}var ye=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}=Br(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=qr(t),s=null,a={};for(let b of this.routes){if(b.method!==r)continue;let v=o.match(b.pattern);if(v){s=b,a={},b.paramNames.forEach((x,A)=>{a[x]=decodeURIComponent(v[A+1]??"");});break}}let p=Object.assign(t,{params:a}),d=s?s.handler:this.notFoundHandler;try{await this.runMiddlewareChain(p,n,d);}catch(b){this.errorHandler(b,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 ae(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",p=n??process.env.FUNCTION_REGION??"us-central1",d=(process.env.FUNCTION_TARGET??"").replace(/\./g,"-");return `/${a}/${p}/${d}${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 yn(e){if(typeof e=="string")return e;if(Array.isArray(e)){let t=e[0];return typeof t=="string"?t:void 0}}function Me(e){return !!e&&typeof e=="object"&&e.__authExtension===true}Ze();var me="__sync_version";var Kr=new Set(["ZodOptional","ZodNullable","ZodDefault"]);function Vr(e){let t=e,n=false;for(;;){let r=q(t);if(!Kr.has(r))break;(r==="ZodOptional"||r==="ZodNullable")&&(n=true);let o=X(t);if(!o)break;t=o;}return {inner:t,nullable:n}}var Wr={ZodString:"string",ZodNumber:"number",ZodBigInt:"bigint",ZodBoolean:"boolean",ZodDate:"timestamp",ZodEnum:"string",ZodNativeEnum:"string",ZodLiteral:"string"};function wn(e,t,n,r,o,s,a,p){for(let[d,b]of Object.entries(e)){let v=n?`${n}__${d}`:d;if(o.has(d)||o.has(v))continue;let{inner:x,nullable:A}=Vr(b),S=q(x),g=r||A;if(S==="ZodObject"){let i=Y(x);wn(i,t,v,g,o,s,a,p);continue}let k=Wr[S]??"json",m=v===a||d===a,y=s[v]??s[d]??v;p.push({name:y,sqlType:t.mapType(k),nullable:m?false:g,isPrimaryKey:m});}}function ot(e,t,n={}){let{primaryKey:r,exclude:o=[],columnMap:s={}}=n,a=new Set(o),p=Y(e),d=[];return wn(p,t,"",false,a,s,r,d),d.some(b=>b.name===me)||d.push({name:me,sqlType:t.mapType("bigint"),nullable:true,isPrimaryKey:false,description:"Monotonic publish version (Date.now() ms). Internal."}),d}function vn(e){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 t=e;return JSON.stringify({lat:t.latitude,lng:t.longitude})}return Array.isArray(e)?JSON.stringify(e.map(vn)):e}var Qr=32,Gr=5e3;function xn(e,t,n,r=new WeakSet,o=0){if(o>Qr){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>=Gr)break;let p=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)?xn(a,p,n,r,o+1):n[p]=vn(a);}r.delete(e);}function Le(e,t){let n=new Set(t?.exclude),r=t?.columnMap??{},o={};xn(e,"",o);let s={};for(let[a,p]of Object.entries(o)){if(n.has(a))continue;let d=a.split("__")[0];if(d!==a&&n.has(d))continue;let b=r[a]??(a.includes("__")?r[a.split("__").pop()]:void 0)??a;s[b]=p;}return s}function de(e,t,n){return `<!DOCTYPE html>
1
+ import {jsx,jsxs,Fragment}from'hono/jsx/jsx-runtime';import {Timestamp}from'firebase-admin/firestore';import {randomUUID,randomBytes}from'crypto';import {z as z$1}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';import {AsyncLocalStorage}from'async_hooks';var bt=Object.defineProperty;var Tr=Object.getOwnPropertyDescriptor;var Ar=Object.getOwnPropertyNames;var Cr=Object.prototype.hasOwnProperty;var je=(e,t)=>()=>(e&&(t=e(e=0)),t);var sn=(e,t)=>{for(var n in t)bt(e,n,{get:t[n],enumerable:true});},Or=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ar(t))!Cr.call(e,o)&&o!==n&&bt(e,o,{get:()=>t[o],enumerable:!(r=Tr(t,o))||r.enumerable});return e};var Er=e=>Or(bt({},"__esModule",{value:true}),e);function q(e){let t=e,n=t._zod?.def?.type;if(n)return Ur[n]??`Zod${n.charAt(0).toUpperCase()}${n.slice(1)}`;let r=t._def?.typeName;return r||""}function X(e){let t=e;if(t._zod?.def?.innerType)return t._zod.def.innerType;if(t._def?.innerType)return t._def.innerType}function He(e){let t=e,n=t._zod?.def?.in;if(n)return n;if(t._def?.schema)return t._def.schema}function gn(e){let t=e;if(t._zod?.def?.element)return t._zod.def.element;if(t._def?.type)return t._def.type}function hn(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 Y(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 Ne(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 ze(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 Be(e){let t=e;return Array.isArray(t._zod?.def?.values)?t._zod.def.values[0]:t._def?.value}function qe(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 bn(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 Ur,Ze=je(()=>{Ur={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 Mn({val:e}){return jsx("span",{class:"text-sm text-base-content/80 font-mono tabular-nums whitespace-nowrap",children:e.toLocaleString()})}function yo({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 Pe({val:e,mismatch:t}){let n=Dt(e);return t?jsxs("span",{class:"inline-flex items-start gap-0.5",children:[n,jsx(yo,{message:t})]}):n}function Dt(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(Mn,{val:e});if(typeof e=="object"&&e!==null&&typeof e.toDate=="function")return jsx(Mn,{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:Dt(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:Dt(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 ct=je(()=>{});function We(e){if(!e)return "unknown";let t=_t(e);switch(q(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 _t(e){let t=q(e);if(t==="ZodOptional"||t==="ZodNullable"||t==="ZodDefault"){let n=X(e);return n?_t(n):e}return e}function Qe(e,t){if(!e)return;let n=t.split("."),r=e;for(let o of n){if(!r)return;let s=_t(r);if(q(s)!=="ZodObject")return;r=Y(s)[o];}return r}function bo(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 Ge(e,t){if(e==="unknown")return null;let n=bo(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 jt=je(()=>{Ze();});var zn={};sn(zn,{PanelMany:()=>vo,PanelOne:()=>wo,RightPanel:()=>Ft});function wo({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`,u=Nn(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(d=>{let b=e[d],v=u[d],x=v?Ge(v,b):null;return jsxs(Fragment,{children:[jsx("dt",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide pt-0.5",children:d}),jsx("dd",{class:"min-w-0",children:jsx(Pe,{val:b,mismatch:x})})]})})})]})}function vo({docs:e,repoName:t,basePath:n,fk:r,fv:o,columns:s,schema:a,pagination:u}){let d=`${n}/${t}?fv_${r}=${encodeURIComponent(o)}`,b=Nn(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:d,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((v,x)=>jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:v},x)),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((v,x)=>{let A=String(v.docId??v.id??""),S=`${n}/${t}/${encodeURIComponent(A)}/edit`;return jsxs("tr",{class:"hover",children:[s.map((m,k)=>{let y=v[m],g=b[m],i=g?Ge(g,y):null;return jsx("td",{class:"align-top py-1.5",children:jsx(Pe,{val:y,mismatch:i})},k)}),jsx("td",{class:"text-right py-1.5",children:jsx("a",{href:S,class:"btn btn-xs btn-ghost",children:"Edit"})})]},x)})})]})}),(u.hasPrev||u.hasNext)&&jsxs("div",{class:"flex justify-center items-center gap-2",children:[u.hasPrev?jsx("button",{type:"button",class:"btn btn-xs btn-outline","data-frs-panel-page":"prev","data-cursor":u.prevCursor,children:"\u2190 Previous"}):jsx("button",{class:"btn btn-xs btn-outline",disabled:true,children:"\u2190 Previous"}),u.hasNext?jsx("button",{type:"button",class:"btn btn-xs btn-outline","data-frs-panel-page":"next","data-cursor":u.nextCursor,children:"Next \u2192"}):jsx("button",{class:"btn btn-xs btn-outline",disabled:true,children:"Next \u2192"})]})]})}function Nn(e,t){if(!e)return {};let n={};for(let r of t)n[r]=We(Qe(e,r));return n}var Ft,Mt=je(()=>{ct();jt();Ft=({basePath:e=""})=>jsxs("div",{class:"fixed inset-0 z-[100] hidden pointer-events-none","data-frs-panel-root":true,"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":true}),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":true,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":true,children:"Relation"}),jsx("button",{type:"button",class:"btn btn-sm btn-ghost btn-circle","data-frs-panel-close":true,"aria-label":"Close panel",children:"\u2715"})]}),jsx("div",{class:"flex-1 overflow-auto p-5 text-sm","data-frs-panel-body":true,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 er={};sn(er,{DEFAULT_HTML_CSP:()=>Jt,securityHeaders:()=>pt});function pt(e={}){let t=e.csp===void 0?Jt: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,u)=>{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 u();}}var Xn,Yn,Jt,ft=je(()=>{Xn="https://cdn.jsdelivr.net",Yn="https://www.gstatic.com",Jt=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${Xn} ${Yn}`,`style-src 'self' 'unsafe-inline' ${Xn}`,`connect-src 'self' ${Yn} 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("; ");});function wt(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 vt(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(!vt(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)||!vt(e[s],t[s],n))return false;return true}return false}function xt(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??{},u=new Set([...Object.keys(s),...Object.keys(a)]),d={};for(let b of u){if(r.has(b)||o&&!o.has(b))continue;let v=s[b],x=a[b];vt(v,x)||(d[b]={oldValue:v===void 0?null:v,newValue:x===void 0?null:x,type:{old:wt(v),new:wt(x)}});}return d}var $r=7e5;function Rt(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,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,u)=>u instanceof Timestamp?u.toMillis():u),"utf8")}catch{return 0}};if(o(r.changes)>$r){let s={};for(let[a,u]of Object.entries(r.changes)){let d=o(u.oldValue),b=o(u.newValue);s[a]={oldValue:d>5e4?"[truncated]":u.oldValue,newValue:b>5e4?"[truncated]":u.newValue,type:u.type};}r.changes=s,r._truncated=true;}return r}async function kt(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 Tt(e,t){let n=e??{},r={},o=t.meta;if(!o)return r;let s=v=>{if(!v)return;let x=n[v];return x===void 0||x===null?null:String(x)},a=s(o.userId);a!==void 0&&(r.userId=a);let u=s(o.userEmail);u!==void 0&&(r.userEmail=u);let d=s(o.reason);d!==void 0&&(r.reason=d);let b=s(o.comment);if(b!==void 0&&(r.comment=b),o.extras&&o.extras.length>0){let v={},x=false;for(let A of o.extras)A in n&&(v[A]=n[A],x=true);x&&(r.extras=v);}return r}function At(e){let t=e.meta;if(!t)return [];let n=[];return t.userId&&n.push(t.userId),t.userEmail&&n.push(t.userEmail),t.reason&&n.push(t.reason),t.comment&&n.push(t.comment),t.extras&&n.push(...t.extras),n}var Ir="history";function Dr(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(r=>typeof r=="string");return {historyConfig:t,systemKeys:n,isGroup:!!e?.isGroup,collectionPath:typeof e?.path=="string"?e.path:null}}function _r(e){return {historyConfig:e._historyConfig??(typeof e.history=="object"&&e.history!==null&&"enabled"in e.history?e.history:void 0),systemKeys:e._systemKeys??[],isGroup:!!e._isGroup,collectionPath:e.ref?.path??null}}function jr(e,t){return t?`${t}/{docId}`:(console.warn(`[HistoryTriggers] Cannot determine collection path for "${e}". Skipping.`),null)}function an(e,t){let{onDocumentWritten:n}=t.deps,r={},o=e?.rawMapping,s=o?Object.entries(o).map(([a,u])=>[a,Dr(u)]):Object.entries(e).map(([a,u])=>[a,_r(u)]);for(let[a,u]of s){let d=u.historyConfig;if(!d?.enabled)continue;let b=d.subcollection??Ir,v=d.ttl??t.defaults?.ttl,x=t.repos?.[a],A;if(u.isGroup){if(!x?.triggerPath){console.warn(`[HistoryTriggers] Skipping collection-group repo "${a}". Provide a triggerPath in the history triggers repos override.`);continue}A=x.triggerPath;}else A=x?.triggerPath??jr(a,u.collectionPath);if(!A)continue;let S=u.systemKeys,m=S[0]??"docId",k=At(d);r[`${a}_onHistory`]=n(A,async y=>{try{let g=y.data?.before?.data(),i=y.data?.after?.data(),p;if(!g&&i)p="create";else if(g&&!i)p="delete";else if(g&&i)p="update";else return;let l=String(i?.[m]??g?.[m]??y.params?.docId??y.data?.after?.id??y.data?.before?.id??"");if(!l)return;let c=xt(g??{},i??{},{include:d.include,exclude:d.exclude,metaFields:k,systemKeys:S});if(p==="update"&&Object.keys(c).length===0)return;let f=Tt(i??g??null,d),h=Rt({entityId:l,operation:p,changes:c,meta:f,config:d,ttlOverride:v}),w=y.data?.after?.ref??y.data?.before?.ref;if(!w)return;let O=w.collection(b);await kt(O,h,d,{repoName:a,docId:l,before:g??null,after:i??null});}catch(g){console.error(`[HistoryTriggers] Failed to record history for "${a}":`,g);}});}return r}var dn="preserve";function un(){return dn}function Fr(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function pn(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(Fr(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 xe(e){return e}function Nr(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 zr(e){let t=[e?.documentKey,e?.pathKey,e?.createdKey,e?.updatedKey].filter(r=>typeof r=="string"),n=e?.history&&typeof e.history=="object"?e.history:void 0;return {schema:e?.schema,_systemKeys:t,_pathKey:e?.pathKey??null,_isGroup:!!e?.isGroup,_createdKey:e?.createdKey??null,_parentKeys:e?.isGroup?Nr(e?.refCb):[],relationalKeys:e?.relationalKeys,_historyConfig:n,_historySubcollection:n?.enabled?n.subcollection??"history":void 0,_collectionPath:typeof e?.path=="string"?e.path:null}}function rt(e,t){let n=zr(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 Br(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 qr(e){let t=e.path??e.url??"/",n=t.indexOf("?");return n===-1?t:t.slice(0,n)}var ye=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}=Br(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=qr(t),s=null,a={};for(let b of this.routes){if(b.method!==r)continue;let v=o.match(b.pattern);if(v){s=b,a={},b.paramNames.forEach((x,A)=>{a[x]=decodeURIComponent(v[A+1]??"");});break}}let u=Object.assign(t,{params:a}),d=s?s.handler:this.notFoundHandler;try{await this.runMiddlewareChain(u,n,d);}catch(b){this.errorHandler(b,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 ae(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",u=n??process.env.FUNCTION_REGION??"us-central1",d=(process.env.FUNCTION_TARGET??"").replace(/\./g,"-");return `/${a}/${u}/${d}${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 yn(e){if(typeof e=="string")return e;if(Array.isArray(e)){let t=e[0];return typeof t=="string"?t:void 0}}function Me(e){return !!e&&typeof e=="object"&&e.__authExtension===true}Ze();var me="__sync_version";var Kr=new Set(["ZodOptional","ZodNullable","ZodDefault"]);function Vr(e){let t=e,n=false;for(;;){let r=q(t);if(!Kr.has(r))break;(r==="ZodOptional"||r==="ZodNullable")&&(n=true);let o=X(t);if(!o)break;t=o;}return {inner:t,nullable:n}}var Wr={ZodString:"string",ZodNumber:"number",ZodBigInt:"bigint",ZodBoolean:"boolean",ZodDate:"timestamp",ZodEnum:"string",ZodNativeEnum:"string",ZodLiteral:"string"};function wn(e,t,n,r,o,s,a,u){for(let[d,b]of Object.entries(e)){let v=n?`${n}__${d}`:d;if(o.has(d)||o.has(v))continue;let{inner:x,nullable:A}=Vr(b),S=q(x),m=r||A;if(S==="ZodObject"){let i=Y(x);wn(i,t,v,m,o,s,a,u);continue}let k=Wr[S]??"json",y=v===a||d===a,g=s[v]??s[d]??v;u.push({name:g,sqlType:t.mapType(k),nullable:y?false:m,isPrimaryKey:y});}}function ot(e,t,n={}){let{primaryKey:r,exclude:o=[],columnMap:s={}}=n,a=new Set(o),u=Y(e),d=[];return wn(u,t,"",false,a,s,r,d),d.some(b=>b.name===me)||d.push({name:me,sqlType:t.mapType("bigint"),nullable:true,isPrimaryKey:false,description:"Monotonic publish version (Date.now() ms). Internal."}),d}function vn(e){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 t=e;return JSON.stringify({lat:t.latitude,lng:t.longitude})}return Array.isArray(e)?JSON.stringify(e.map(vn)):e}var Qr=32,Gr=5e3;function xn(e,t,n,r=new WeakSet,o=0){if(o>Qr){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>=Gr)break;let u=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)?xn(a,u,n,r,o+1):n[u]=vn(a);}r.delete(e);}function Le(e,t){let n=new Set(t?.exclude),r=t?.columnMap??{},o={};xn(e,"",o);let s={};for(let[a,u]of Object.entries(o)){if(n.has(a))continue;let d=a.split("__")[0];if(d!==a&&n.has(d))continue;let b=r[a]??(a.includes("__")?r[a.split("__").pop()]:void 0)??a;s[b]=u;}return s}function de(e,t,n){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>${e} \u2014 Sync Admin</title>
@@ -28,60 +28,60 @@ import {jsx,jsxs,Fragment}from'hono/jsx/jsx-runtime';import {Timestamp}from'fire
28
28
  <nav><a href="${t}/">\u2190 Dashboard</a></nav>
29
29
  <h1>${e}</h1>
30
30
  ${n}
31
- </body></html>`}function ue(e,t,n=200){e.status(n).set("Content-Type","text/html; charset=utf-8").send(t);}function Oe(e,t,n=200){e.status(n).set("Content-Type","application/json").send(JSON.stringify(t,null,2));}function st(e){return (e.headers?.accept??"").includes("application/json")}function Sn(e,t,n,r,o,s,a,p){let d=(o.basePath??"/").replace(/\/$/,"")||"",b=o.featuresFlag??{},v=e?.rawMapping,x=[];for(let S of Object.keys(e)){let g=s[S],k=v?rt(v[S],()=>e[S]):e[S];x.push({name:S,schema:k.schema??null,documentKey:k._systemKeys?.[0]??k.documentKey??"docId",tableName:g?.tableName??S,isGroup:!!k._isGroup,repoCfg:g,repo:k});}let A=new ye;if(o.auth)if(Me(o.auth)){let S=o.auth;for(let g of S.routes){let k=`${d}${g.path}`;g.method==="GET"?A.get(k,g.handler):A.post(k,g.handler);}A.use(S.middleware);}else if(typeof o.auth=="function")A.use(o.auth);else {let S=o.auth.realm??"Sync Admin",g="Basic "+Buffer.from(`${o.auth.username}:${o.auth.password}`).toString("base64");A.use((k,m,y)=>{if((k.headers?.authorization??"")!==g){m.status(401).set("WWW-Authenticate",`Basic realm="${S}"`).set("Content-Type","text/plain").send("Unauthorized");return}y();});}return A.get(`${d}/`,(S,g)=>{let k=ae(S,d),m=x.map(u=>{let l=[];return b.healthCheck&&l.push(`<a class="btn" href="${k}/${u.name}/health">Health</a>`),b.manualSync&&l.push(`<a class="btn btn-primary" href="${k}/${u.name}/force-sync">Force Sync</a>`),`<tr>
32
- <td><strong>${u.name}</strong></td>
33
- <td>${u.tableName}</td>
34
- <td>${u.isGroup?'<span class="badge badge-warn">group</span>':'<span class="badge badge-ok">collection</span>'}</td>
35
- <td>${u.schema?"\u2713":"\u2717"}</td>
31
+ </body></html>`}function ue(e,t,n=200){e.status(n).set("Content-Type","text/html; charset=utf-8").send(t);}function Oe(e,t,n=200){e.status(n).set("Content-Type","application/json").send(JSON.stringify(t,null,2));}function st(e){return (e.headers?.accept??"").includes("application/json")}function Sn(e,t,n,r,o,s,a,u){let d=(o.basePath??"/").replace(/\/$/,"")||"",b=o.featuresFlag??{},v=e?.rawMapping,x=[];for(let S of Object.keys(e)){let m=s[S],k=v?rt(v[S],()=>e[S]):e[S];x.push({name:S,schema:k.schema??null,documentKey:k._systemKeys?.[0]??k.documentKey??"docId",tableName:m?.tableName??S,isGroup:!!k._isGroup,repoCfg:m,repo:k});}let A=new ye;if(o.auth)if(Me(o.auth)){let S=o.auth;for(let m of S.routes){let k=`${d}${m.path}`;m.method==="GET"?A.get(k,m.handler):A.post(k,m.handler);}A.use(S.middleware);}else if(typeof o.auth=="function")A.use(o.auth);else {let S=o.auth.realm??"Sync Admin",m="Basic "+Buffer.from(`${o.auth.username}:${o.auth.password}`).toString("base64");A.use((k,y,g)=>{if((k.headers?.authorization??"")!==m){y.status(401).set("WWW-Authenticate",`Basic realm="${S}"`).set("Content-Type","text/plain").send("Unauthorized");return}g();});}return A.get(`${d}/`,(S,m)=>{let k=ae(S,d),y=x.map(p=>{let l=[];return b.healthCheck&&l.push(`<a class="btn" href="${k}/${p.name}/health">Health</a>`),b.manualSync&&l.push(`<a class="btn btn-primary" href="${k}/${p.name}/force-sync">Force Sync</a>`),`<tr>
32
+ <td><strong>${p.name}</strong></td>
33
+ <td>${p.tableName}</td>
34
+ <td>${p.isGroup?'<span class="badge badge-warn">group</span>':'<span class="badge badge-ok">collection</span>'}</td>
35
+ <td>${p.schema?"\u2713":"\u2717"}</td>
36
36
  <td>${l.join(" ")}</td>
37
37
  </tr>`}).join(`
38
- `),y=b.configCheck?`<p style="margin-top:.5rem"><a class="btn" href="${k}/config-check">\u2699 Config Check</a></p>`:"",i=de("Sync Dashboard",k,`<div class="card">
38
+ `),g=b.configCheck?`<p style="margin-top:.5rem"><a class="btn" href="${k}/config-check">\u2699 Config Check</a></p>`:"",i=de("Sync Dashboard",k,`<div class="card">
39
39
  <table>
40
40
  <thead><tr><th>Repository</th><th>Table</th><th>Type</th><th>Schema</th><th>Actions</th></tr></thead>
41
- <tbody>${m}</tbody>
41
+ <tbody>${y}</tbody>
42
42
  </table>
43
- ${y}
44
- </div>`);ue(g,i);}),A.get(`${d}`,(S,g)=>{let k=ae(S,d);g.status(302).set("Location",`${k}/`).send("");}),b.healthCheck&&A.get(`${d}/:repoName/health`,async(S,g)=>{let k=ae(S,d),m=x.find(P=>P.name===S.params.repoName);if(!m){ue(g,de("Not Found",k,`<p>Unknown repo: ${S.params.repoName}</p>`),404);return}if(!m.schema){ue(g,de("Health Check",k,`<p class="badge badge-warn">No Zod schema attached to "${m.name}"</p>`));return}let y=ot(m.schema,t.dialect,{primaryKey:m.documentKey,exclude:m.repoCfg?.exclude,columnMap:m.repoCfg?.columnMap}),i=[],u=false,l=null;try{u=await t.tableExists(m.tableName),u&&(i=await t.getTableColumns(m.tableName));}catch(P){l=P?.message??String(P);}let c=new Set(i),f=new Set(y.map(P=>P.name)),h=y.filter(P=>!c.has(P.name)),w=i.filter(P=>!f.has(P)),O=y.filter(P=>c.has(P.name)),T=u&&h.length===0&&!l;if(st(S)){Oe(g,{repo:m.name,table:m.tableName,tableExists:u,healthy:T,error:l,columns:{expected:y.map(P=>({name:P.name,type:P.sqlType,nullable:P.nullable,isPrimaryKey:P.isPrimaryKey})),actual:i,matched:O.map(P=>P.name),missing:h.map(P=>({name:P.name,type:P.sqlType})),extra:w}});return}let R=T?'<span class="badge badge-ok">Healthy</span>':'<span class="badge badge-err">Unhealthy</span>',C=y.map(P=>{let D=c.has(P.name)?'<span class="badge badge-ok">OK</span>':'<span class="badge badge-err">MISSING</span>';return `<tr><td>${P.name}</td><td>${P.sqlType}</td><td>${P.nullable?"Yes":"No"}</td><td>${P.isPrimaryKey?"\u2713":""}</td><td>${D}</td></tr>`}).join(`
43
+ ${g}
44
+ </div>`);ue(m,i);}),A.get(`${d}`,(S,m)=>{let k=ae(S,d);m.status(302).set("Location",`${k}/`).send("");}),b.healthCheck&&A.get(`${d}/:repoName/health`,async(S,m)=>{let k=ae(S,d),y=x.find(P=>P.name===S.params.repoName);if(!y){ue(m,de("Not Found",k,`<p>Unknown repo: ${S.params.repoName}</p>`),404);return}if(!y.schema){ue(m,de("Health Check",k,`<p class="badge badge-warn">No Zod schema attached to "${y.name}"</p>`));return}let g=ot(y.schema,t.dialect,{primaryKey:y.documentKey,exclude:y.repoCfg?.exclude,columnMap:y.repoCfg?.columnMap}),i=[],p=false,l=null;try{p=await t.tableExists(y.tableName),p&&(i=await t.getTableColumns(y.tableName));}catch(P){l=P?.message??String(P);}let c=new Set(i),f=new Set(g.map(P=>P.name)),h=g.filter(P=>!c.has(P.name)),w=i.filter(P=>!f.has(P)),O=g.filter(P=>c.has(P.name)),T=p&&h.length===0&&!l;if(st(S)){Oe(m,{repo:y.name,table:y.tableName,tableExists:p,healthy:T,error:l,columns:{expected:g.map(P=>({name:P.name,type:P.sqlType,nullable:P.nullable,isPrimaryKey:P.isPrimaryKey})),actual:i,matched:O.map(P=>P.name),missing:h.map(P=>({name:P.name,type:P.sqlType})),extra:w}});return}let R=T?'<span class="badge badge-ok">Healthy</span>':'<span class="badge badge-err">Unhealthy</span>',C=g.map(P=>{let D=c.has(P.name)?'<span class="badge badge-ok">OK</span>':'<span class="badge badge-err">MISSING</span>';return `<tr><td>${P.name}</td><td>${P.sqlType}</td><td>${P.nullable?"Yes":"No"}</td><td>${P.isPrimaryKey?"\u2713":""}</td><td>${D}</td></tr>`}).join(`
45
45
  `),E=w.map(P=>`<tr><td>${P}</td><td colspan="3" class="muted">not in schema</td><td><span class="badge badge-warn">EXTRA</span></td></tr>`).join(`
46
- `),$=de(`Health: ${m.name}`,k,`<div class="card">
47
- <p>Table: <code>${m.tableName}</code> ${u?R:'<span class="badge badge-err">NOT FOUND</span>'}</p>
46
+ `),$=de(`Health: ${y.name}`,k,`<div class="card">
47
+ <p>Table: <code>${y.tableName}</code> ${p?R:'<span class="badge badge-err">NOT FOUND</span>'}</p>
48
48
  ${l?`<p class="badge badge-err">Error: ${l}</p>`:""}
49
49
  <h2>Columns</h2>
50
50
  <table>
51
51
  <thead><tr><th>Column</th><th>SQL Type</th><th>Nullable</th><th>PK</th><th>Status</th></tr></thead>
52
52
  <tbody>${C}${E}</tbody>
53
53
  </table>
54
- </div>`);ue(g,$);}),b.manualSync&&(A.get(`${d}/:repoName/force-sync`,(S,g)=>{let k=ae(S,d),m=x.find(i=>i.name===S.params.repoName);if(!m){ue(g,de("Not Found",k,`<p>Unknown repo: ${S.params.repoName}</p>`),404);return}let y=de(`Force Sync: ${m.name}`,k,`<div class="card">
55
- <p>This will read <strong>all</strong> documents from the <code>${m.name}</code> Firestore collection
56
- and upsert them into the <code>${m.tableName}</code> SQL table.</p>
54
+ </div>`);ue(m,$);}),b.manualSync&&(A.get(`${d}/:repoName/force-sync`,(S,m)=>{let k=ae(S,d),y=x.find(i=>i.name===S.params.repoName);if(!y){ue(m,de("Not Found",k,`<p>Unknown repo: ${S.params.repoName}</p>`),404);return}let g=de(`Force Sync: ${y.name}`,k,`<div class="card">
55
+ <p>This will read <strong>all</strong> documents from the <code>${y.name}</code> Firestore collection
56
+ and upsert them into the <code>${y.tableName}</code> SQL table.</p>
57
57
  <p class="muted" style="margin:.75rem 0">This may take a while for large collections.</p>
58
- <form method="POST" action="${k}/${m.name}/force-sync">
58
+ <form method="POST" action="${k}/${y.name}/force-sync">
59
59
  <button type="submit" class="btn btn-primary">Start Force Sync</button>
60
60
  </form>
61
- </div>`);ue(g,y);}),A.post(`${d}/:repoName/force-sync`,async(S,g)=>{let k=ae(S,d),m=x.find(T=>T.name===S.params.repoName);if(!m){Oe(g,{error:`Unknown repo: ${S.params.repoName}`},404);return}let y=m.repo.ref;if(!y){Oe(g,{error:`No collection reference for "${m.name}"`},400);return}let i=0,u=0,l=[],c=500,f=y.limit(c),h=null;try{for(;;){let C=await(h?f.startAfter(h):f).get();if(C.empty)break;for(let E of C.docs){let $=E.data(),P=String($[m.documentKey]??E.id),D=Le($,{exclude:m.repoCfg?.exclude,columnMap:m.repoCfg?.columnMap});try{await r({operation:"UPSERT",repoName:m.name,docId:P,data:D,timestamp:new Date().toISOString()}),i++;}catch(H){u++;let j=H?.message??String(H);console.error(`[ForceSync:${m.name}] doc=${P} failed:`,H),l.length<5&&l.push(`${P}: ${j}`);}}if(h=C.docs[C.docs.length-1],C.docs.length<c)break}let T=n.get(m.name);T&&await T.flush();}catch(T){if(st(S)){Oe(g,{error:T?.message??String(T),synced:i,errors:u},500);return}ue(g,de(`Force Sync: ${m.name}`,k,`<div class="card">
61
+ </div>`);ue(m,g);}),A.post(`${d}/:repoName/force-sync`,async(S,m)=>{let k=ae(S,d),y=x.find(T=>T.name===S.params.repoName);if(!y){Oe(m,{error:`Unknown repo: ${S.params.repoName}`},404);return}let g=y.repo.ref;if(!g){Oe(m,{error:`No collection reference for "${y.name}"`},400);return}let i=0,p=0,l=[],c=500,f=g.limit(c),h=null;try{for(;;){let C=await(h?f.startAfter(h):f).get();if(C.empty)break;for(let E of C.docs){let $=E.data(),P=String($[y.documentKey]??E.id),D=Le($,{exclude:y.repoCfg?.exclude,columnMap:y.repoCfg?.columnMap});try{await r({operation:"UPSERT",repoName:y.name,docId:P,data:D,timestamp:new Date().toISOString()}),i++;}catch(H){p++;let j=H?.message??String(H);console.error(`[ForceSync:${y.name}] doc=${P} failed:`,H),l.length<5&&l.push(`${P}: ${j}`);}}if(h=C.docs[C.docs.length-1],C.docs.length<c)break}let T=n.get(y.name);T&&await T.flush();}catch(T){if(st(S)){Oe(m,{error:T?.message??String(T),synced:i,errors:p},500);return}ue(m,de(`Force Sync: ${y.name}`,k,`<div class="card">
62
62
  <p class="badge badge-err">Error: ${T?.message??String(T)}</p>
63
- <p>Synced ${i} docs before failure (${u} errors).</p>
64
- </div>`),500);return}if(st(S)){Oe(g,{repo:m.name,table:m.tableName,synced:i,errors:u,...l.length>0&&{errorSamples:l}});return}let w=l.length>0?`<details style="margin-top:1rem"><summary>First ${l.length} error(s)</summary>
63
+ <p>Synced ${i} docs before failure (${p} errors).</p>
64
+ </div>`),500);return}if(st(S)){Oe(m,{repo:y.name,table:y.tableName,synced:i,errors:p,...l.length>0&&{errorSamples:l}});return}let w=l.length>0?`<details style="margin-top:1rem"><summary>First ${l.length} error(s)</summary>
65
65
  <pre style="white-space:pre-wrap">${l.map(T=>T.replace(/[<>&]/g,R=>`&#${R.charCodeAt(0)};`)).join(`
66
66
 
67
- `)}</pre></details>`:"",O=de(`Force Sync: ${m.name}`,k,`<div class="card">
68
- <p class="badge ${u>0?"badge-warn":"badge-ok"}">${u>0?"Completed with errors":"Complete"}</p>
69
- <p>Synced <strong>${i}</strong> documents to <code>${m.tableName}</code>.</p>
70
- ${u>0?`<p class="badge badge-warn">${u} error(s)</p>`:""}
67
+ `)}</pre></details>`:"",O=de(`Force Sync: ${y.name}`,k,`<div class="card">
68
+ <p class="badge ${p>0?"badge-warn":"badge-ok"}">${p>0?"Completed with errors":"Complete"}</p>
69
+ <p>Synced <strong>${i}</strong> documents to <code>${y.tableName}</code>.</p>
70
+ ${p>0?`<p class="badge badge-warn">${p} error(s)</p>`:""}
71
71
  ${w}
72
- </div>`);ue(g,O);})),b.configCheck&&A.get(`${d}/config-check`,async(S,g)=>{let k=ae(S,d),m=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??process.env.GCP_PROJECT??"unknown",y="https://console.cloud.google.com",i=p??"firestore-sync",u=[];try{await t.tableExists("__nonexistent_health_check__"),u.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable"});}catch(T){let R=T?.message??String(T),C=R.toLowerCase(),E=C.includes("disabled")||C.includes("has not been used")||C.includes("accessnotconfigured"),$=C.includes("permission")||R.includes("403")||C.includes("access denied"),P=C.includes("project")&&C.includes("not found"),D=C.includes("not found")||R.includes("404");E?u.push({name:"BigQuery API",category:"bigquery",status:"error",message:"BigQuery API is not enabled",fix:{gcloud:`gcloud services enable bigquery.googleapis.com --project=${m}`,console:`${y}/apis/library/bigquery.googleapis.com?project=${m}`}}):P?u.push({name:"BigQuery Project",category:"bigquery",status:"error",message:R,fix:{hint:"The GCP project does not exist or the credentials don't have access to it. In the Firebase emulator, GCLOUD_PROJECT may override the configured projectId. Ensure you pass the correct projectId to the BigQuery constructor and have valid credentials.",console:`${y}/home/dashboard`}}):$?u.push({name:"BigQuery API",category:"bigquery",status:"error",message:`Permission denied: ${R}`,fix:{hint:"Grant the service account BigQuery Data Editor + BigQuery Job User roles",gcloud:[`SA=$(gcloud run services describe YOUR_SERVICE --region=YOUR_REGION --format="value(spec.template.spec.serviceAccountName)" --project=${m})`,`gcloud projects add-iam-policy-binding ${m} --member="serviceAccount:$SA" --role="roles/bigquery.dataEditor"`,`gcloud projects add-iam-policy-binding ${m} --member="serviceAccount:$SA" --role="roles/bigquery.jobUser"`].join(`
73
- `),console:`${y}/iam-admin/iam?project=${m}`}}):D?u.push({name:"BigQuery Dataset",category:"bigquery",status:"error",message:`Dataset not found: ${R}`,fix:{hint:"Create the dataset first",gcloud:`bq mk --dataset ${m}:YOUR_DATASET_ID`,console:`${y}/bigquery?project=${m}`}}):u.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable (table lookup returned expected error)"});}for(let T of x)try{let R=await t.tableExists(T.tableName);u.push({name:`Table: ${T.tableName}`,category:"bigquery",status:R?"ok":"warn",message:R?`Table \`${T.tableName}\` exists`:`Table \`${T.tableName}\` does not exist yet`,...!R&&{fix:{hint:"Table will be auto-created on first sync if autoMigrate is enabled. Or create it manually."}}});}catch(R){u.push({name:`Table: ${T.tableName}`,category:"bigquery",status:"error",message:R?.message??String(R)});}if(a)for(let T of x){let R=`${i}-${T.name}`;try{let C=a.topic(R);if(typeof C.exists=="function"){let[E]=await C.exists();u.push({name:`Topic: ${R}`,category:"pubsub",status:E?"ok":"error",message:E?`Topic \`${R}\` exists`:`Topic \`${R}\` does not exist`,...!E&&{fix:{gcloud:`gcloud pubsub topics create ${R} --project=${m}`,console:`${y}/cloudpubsub/topic/list?project=${m}`}}});}else u.push({name:`Topic: ${R}`,category:"pubsub",status:"warn",message:"Cannot verify topic existence (PubSub client doesn't expose .exists())",fix:{gcloud:`gcloud pubsub topics create ${R} --project=${m}`,console:`${y}/cloudpubsub/topic/list?project=${m}`,hint:"Ensure the topic exists. It is auto-created by the Firebase emulator but must exist in production."}});}catch(C){let E=C?.message??String(C),$=E.includes("disabled")||E.includes("has not been used");if(u.push({name:$?"Pub/Sub API":`Topic: ${R}`,category:"pubsub",status:"error",message:$?"Pub/Sub API is not enabled":E,fix:$?{gcloud:`gcloud services enable pubsub.googleapis.com --project=${m}`,console:`${y}/apis/library/pubsub.googleapis.com?project=${m}`}:{gcloud:`gcloud pubsub topics create ${R} --project=${m}`,console:`${y}/cloudpubsub/topic/list?project=${m}`}}),$)break}}else u.push({name:"Pub/Sub Client",category:"pubsub",status:"warn",message:"PubSub client not available for config check"});if(st(S)){let T=u.every(R=>R.status==="ok");Oe(g,{project:m,healthy:T,checks:u});return}let l=T=>T==="ok"?'<span class="badge badge-ok">OK</span>':T==="warn"?'<span class="badge badge-warn">WARN</span>':'<span class="badge badge-err">ERROR</span>',c={bigquery:u.filter(T=>T.category==="bigquery"),pubsub:u.filter(T=>T.category==="pubsub"),firestore:u.filter(T=>T.category==="firestore")},f=(T,R)=>{if(R.length===0)return "";let C=R.map(E=>{let $="";if(E.fix){let P=[];E.fix.hint&&P.push(`<p class="muted">${E.fix.hint}</p>`),E.fix.gcloud&&P.push(`<pre>$ ${E.fix.gcloud}</pre>`),E.fix.console&&P.push(`<p><a href="${E.fix.console}" target="_blank">Open GCP Console \u2192</a></p>`),$=`<div style="margin-top:.5rem">${P.join("")}</div>`;}return `<tr>
72
+ </div>`);ue(m,O);})),b.configCheck&&A.get(`${d}/config-check`,async(S,m)=>{let k=ae(S,d),y=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??process.env.GCP_PROJECT??"unknown",g="https://console.cloud.google.com",i=u??"firestore-sync",p=[];try{await t.tableExists("__nonexistent_health_check__"),p.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable"});}catch(T){let R=T?.message??String(T),C=R.toLowerCase(),E=C.includes("disabled")||C.includes("has not been used")||C.includes("accessnotconfigured"),$=C.includes("permission")||R.includes("403")||C.includes("access denied"),P=C.includes("project")&&C.includes("not found"),D=C.includes("not found")||R.includes("404");E?p.push({name:"BigQuery API",category:"bigquery",status:"error",message:"BigQuery API is not enabled",fix:{gcloud:`gcloud services enable bigquery.googleapis.com --project=${y}`,console:`${g}/apis/library/bigquery.googleapis.com?project=${y}`}}):P?p.push({name:"BigQuery Project",category:"bigquery",status:"error",message:R,fix:{hint:"The GCP project does not exist or the credentials don't have access to it. In the Firebase emulator, GCLOUD_PROJECT may override the configured projectId. Ensure you pass the correct projectId to the BigQuery constructor and have valid credentials.",console:`${g}/home/dashboard`}}):$?p.push({name:"BigQuery API",category:"bigquery",status:"error",message:`Permission denied: ${R}`,fix:{hint:"Grant the service account BigQuery Data Editor + BigQuery Job User roles",gcloud:[`SA=$(gcloud run services describe YOUR_SERVICE --region=YOUR_REGION --format="value(spec.template.spec.serviceAccountName)" --project=${y})`,`gcloud projects add-iam-policy-binding ${y} --member="serviceAccount:$SA" --role="roles/bigquery.dataEditor"`,`gcloud projects add-iam-policy-binding ${y} --member="serviceAccount:$SA" --role="roles/bigquery.jobUser"`].join(`
73
+ `),console:`${g}/iam-admin/iam?project=${y}`}}):D?p.push({name:"BigQuery Dataset",category:"bigquery",status:"error",message:`Dataset not found: ${R}`,fix:{hint:"Create the dataset first",gcloud:`bq mk --dataset ${y}:YOUR_DATASET_ID`,console:`${g}/bigquery?project=${y}`}}):p.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable (table lookup returned expected error)"});}for(let T of x)try{let R=await t.tableExists(T.tableName);p.push({name:`Table: ${T.tableName}`,category:"bigquery",status:R?"ok":"warn",message:R?`Table \`${T.tableName}\` exists`:`Table \`${T.tableName}\` does not exist yet`,...!R&&{fix:{hint:"Table will be auto-created on first sync if autoMigrate is enabled. Or create it manually."}}});}catch(R){p.push({name:`Table: ${T.tableName}`,category:"bigquery",status:"error",message:R?.message??String(R)});}if(a)for(let T of x){let R=`${i}-${T.name}`;try{let C=a.topic(R);if(typeof C.exists=="function"){let[E]=await C.exists();p.push({name:`Topic: ${R}`,category:"pubsub",status:E?"ok":"error",message:E?`Topic \`${R}\` exists`:`Topic \`${R}\` does not exist`,...!E&&{fix:{gcloud:`gcloud pubsub topics create ${R} --project=${y}`,console:`${g}/cloudpubsub/topic/list?project=${y}`}}});}else p.push({name:`Topic: ${R}`,category:"pubsub",status:"warn",message:"Cannot verify topic existence (PubSub client doesn't expose .exists())",fix:{gcloud:`gcloud pubsub topics create ${R} --project=${y}`,console:`${g}/cloudpubsub/topic/list?project=${y}`,hint:"Ensure the topic exists. It is auto-created by the Firebase emulator but must exist in production."}});}catch(C){let E=C?.message??String(C),$=E.includes("disabled")||E.includes("has not been used");if(p.push({name:$?"Pub/Sub API":`Topic: ${R}`,category:"pubsub",status:"error",message:$?"Pub/Sub API is not enabled":E,fix:$?{gcloud:`gcloud services enable pubsub.googleapis.com --project=${y}`,console:`${g}/apis/library/pubsub.googleapis.com?project=${y}`}:{gcloud:`gcloud pubsub topics create ${R} --project=${y}`,console:`${g}/cloudpubsub/topic/list?project=${y}`}}),$)break}}else p.push({name:"Pub/Sub Client",category:"pubsub",status:"warn",message:"PubSub client not available for config check"});if(st(S)){let T=p.every(R=>R.status==="ok");Oe(m,{project:y,healthy:T,checks:p});return}let l=T=>T==="ok"?'<span class="badge badge-ok">OK</span>':T==="warn"?'<span class="badge badge-warn">WARN</span>':'<span class="badge badge-err">ERROR</span>',c={bigquery:p.filter(T=>T.category==="bigquery"),pubsub:p.filter(T=>T.category==="pubsub"),firestore:p.filter(T=>T.category==="firestore")},f=(T,R)=>{if(R.length===0)return "";let C=R.map(E=>{let $="";if(E.fix){let P=[];E.fix.hint&&P.push(`<p class="muted">${E.fix.hint}</p>`),E.fix.gcloud&&P.push(`<pre>$ ${E.fix.gcloud}</pre>`),E.fix.console&&P.push(`<p><a href="${E.fix.console}" target="_blank">Open GCP Console \u2192</a></p>`),$=`<div style="margin-top:.5rem">${P.join("")}</div>`;}return `<tr>
74
74
  <td>${l(E.status)}</td>
75
75
  <td><strong>${E.name}</strong><br><span class="muted">${E.message}</span>${$}</td>
76
76
  </tr>`}).join(`
77
77
  `);return `<h2>${T}</h2>
78
78
  <table><thead><tr><th style="width:80px">Status</th><th>Check</th></tr></thead>
79
- <tbody>${C}</tbody></table>`},w=u.every(T=>T.status==="ok")?'<span class="badge badge-ok">All checks passed</span>':'<span class="badge badge-warn">Some issues found</span>',O=de("Config Check",k,`<div class="card">
80
- <p>Project: <code>${m}</code> ${w}</p>
79
+ <tbody>${C}</tbody></table>`},w=p.every(T=>T.status==="ok")?'<span class="badge badge-ok">All checks passed</span>':'<span class="badge badge-warn">Some issues found</span>',O=de("Config Check",k,`<div class="card">
80
+ <p>Project: <code>${y}</code> ${w}</p>
81
81
  ${f("BigQuery",c.bigquery)}
82
82
  ${f("Pub/Sub",c.pubsub)}
83
83
  ${f("Firestore",c.firestore)}
84
- </div>`);ue(g,O);}),async(S,g)=>{await A.handle(S,g);}}var Jr="firestore-sync";function Xr(e,t){return t?`${t}/{docId}`:(console.warn(`[SyncTriggers] Cannot determine collection path for "${e}". Skipping.`),null)}function Yr(e){let t=[e?.documentKey,e?.pathKey,e?.createdKey,e?.updatedKey].filter(n=>typeof n=="string");return {isGroup:!!e?.isGroup,documentKey:t[0]??"docId",collectionPath:typeof e?.path=="string"?e.path:null}}function eo(e){return {isGroup:!!e?._isGroup,documentKey:e?._systemKeys?.[0]??"docId",collectionPath:e?.ref?.path??null}}function Rn(e,t){let{onDocumentCreated:n,onDocumentUpdated:r,onDocumentDeleted:o}=t.deps.firestoreTriggers,s=t.deps.pubsub,a=t?.topicPrefix??Jr,p={},d=new Map;function b(S){let g=d.get(S);return g||(g=s.topic(S),d.set(S,g),g)}async function v(S,g){await b(S).publishMessage({json:g});}let x=e?.rawMapping,A=x?Object.entries(x).map(([S,g])=>[S,Yr(g)]):Object.entries(e).map(([S,g])=>[S,eo(g)]);for(let[S,g]of A){let k=t?.repos?.[S],m;if(g.isGroup){if(!k?.triggerPath){console.warn(`[SyncTriggers] Skipping collection-group repo "${S}". Provide a triggerPath in the sync repos config for group collections.`);continue}m=k.triggerPath;}else m=k?.triggerPath??Xr(S,g.collectionPath);if(!m)continue;let y=g.documentKey,i=`${a}-${S}`;p[`${S}_onCreate`]=n(m,async u=>{let l=u.data;if(!l)return;let c=l.data();if(!c)return;let f=String(c[y]??l.id),h=Le(c,{exclude:k?.exclude,columnMap:k?.columnMap}),w={operation:"INSERT",repoName:S,docId:f,data:h,timestamp:new Date().toISOString(),version:Date.now()};await v(i,w);}),p[`${S}_onUpdate`]=r(m,async u=>{let l=u.data?.after;if(!l)return;let c=l.data();if(!c)return;let f=String(c[y]??l.id),h=Le(c,{exclude:k?.exclude,columnMap:k?.columnMap}),w={operation:"UPSERT",repoName:S,docId:f,data:h,timestamp:new Date().toISOString(),version:Date.now()};await v(i,w);}),p[`${S}_onDelete`]=o(m,async u=>{let l=u.data;if(!l)return;let c=l.data(),f=String(c?.[y]??l.id),h={operation:"DELETE",repoName:S,docId:f,data:null,timestamp:new Date().toISOString(),version:Date.now()};await v(i,h);});}return p}function kn(e){let t=e.toUpperCase();switch(t){case "INTEGER":return "INT64";case "FLOAT":return "FLOAT64";case "BOOLEAN":return "BOOL";default:return t}}function Tn(e,t){let n=kn(e),r=kn(t);return n===r?true:{INT64:["NUMERIC","BIGNUMERIC","FLOAT64"],NUMERIC:["BIGNUMERIC","FLOAT64"],DATE:["DATETIME","TIMESTAMP"],DATETIME:["TIMESTAMP"]}[n]?.includes(r)??false}var at=class{constructor(t){this.buffer=[];this.flushing=false;this.flushPromise=null;this.timer=null;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();},n),typeof this.timer=="object"&&"unref"in this.timer&&this.timer.unref());}get size(){return this.buffer.length}enqueue(...t){this.buffer.push(...t),this.buffer.length>=this.batchSize&&this.flush();}async flush(){for(;this.flushPromise;)await this.flushPromise;this.buffer.length!==0&&(this.flushing=true,this.flushPromise=this._drain().finally(()=>{this.flushing=false,this.flushPromise=null;}),await this.flushPromise);}async _drain(){for(;this.buffer.length>0&&await this._doFlush(););}async _doFlush(){let t=this.buffer.splice(0,this.batchSize);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 p=Number(a[me]??0);Number(s.data[me]??0)>=p&&n.set(s.docId,s.data);}}let o=Array.from(n.values());o.length>0&&await this.adapter.upsertRows(this.tableName,o,this.primaryKey),r.length>0&&await this.adapter.deleteRows(this.tableName,this.primaryKey,r);}catch(n){if(this.onFlushError)await this.onFlushError(t,n);else return this.buffer.unshift(...t),console.error(`[SyncQueue] Flush failed for ${this.tableName}:`,n),false}return true}async shutdown(){this.timer&&(clearInterval(this.timer),this.timer=null),await this.flush();}};var An=new Set,Ot=class extends Error{constructor(n,r,o,s){super(`Schema drift detected on \`${n}\`: column \`${r}\` has type ${o} in BigQuery but the current Zod schema maps it to ${s}. BigQuery cannot safely convert between these types \u2014 to resolve, either (a) keep the BigQuery type and add a transform in your repo to coerce values, (b) rename the field in your Zod schema (creates a new column), or (c) drop & recreate the table.`);this.tableName=n;this.column=r;this.existingType=o;this.desiredType=s;this.name="SchemaTypeMismatchError";}};async function to(e,t,n,r,o,s,a){if(An.has(e))return;let p=ot(n,t.dialect,{primaryKey:o,exclude:s,columnMap:a});if(!await t.tableExists(r))await t.createTable({tableName:r,columns:p});else if(t.getTableColumnsWithTypes){let b=await t.getTableColumnsWithTypes(r),v=[];for(let x of p){let A=b.get(x.name);if(A===void 0){v.push(x);continue}if(t.dialect.name==="bigquery"&&!Tn(A,x.sqlType))throw new Ot(r,x.name,A,x.sqlType)}v.length>0&&(await t.addColumns(r,v),await t.onSchemaChange?.(r));}else {let b=new Set(await t.getTableColumns(r)),v=p.filter(x=>!b.has(x.name));v.length>0&&(await t.addColumns(r,v),await t.onSchemaChange?.(r));}An.add(e);}function Cn(e,t){let{deps:n,adapter:r,batchSize:o=100,flushIntervalMs:s=5e3,autoMigrate:a=false,topicPrefix:p="firestore-sync",maxDlqAttempts:d=5,workerOptions:b,repos:v={}}=t,x=new Map;function A(k,m){let y=x.get(k);if(y)return y;let u=v[k]?.tableName??k,l=`${p}-${k}-dlq`,c=n.pubsub.topic(l),f=false,h=async()=>{if(!f){try{await c.create(),console.info(`[SyncWorker] Created DLQ topic "${l}"`);}catch(O){if(O?.code!==6)throw O}f=true;}},w=async(O,T)=>{console.error(`[SyncWorker] Flush failed for "${k}" (${O.length} events):`,T),await h(),await Promise.all(O.map(R=>{let C=(R.attempts??0)+1;if(d>0&&C>d)return console.error(`[SyncWorker] Dropping event for "${k}" after ${C-1} DLQ attempts:`,{docId:R.docId,operation:R.operation}),Promise.resolve();let E={...R,attempts:C,firstFailedAt:R.firstFailedAt??Date.now()};return c.publishMessage({json:E})}));};return y=new at({adapter:r,tableName:u,primaryKey:m,batchSize:o,flushIntervalMs:s,onFlushError:w}),x.set(k,y),y}async function S(k){let{repoName:m}=k,y=e[m];if(!y){console.warn(`[SyncWorker] Unknown repo "${m}", skipping event`);return}let i=y._systemKeys?.[0]??y.documentKey??"docId",u=v[m],l=u?.columnMap,c=l?.[i]??i;if(a){let h=y.schema??void 0;if(h){let w=u?.tableName??m;await to(m,r,h,w,i,u?.exclude,l);}}let f=A(m,c);k.data&&(k.data[me]=k.version??Date.now()),f.enqueue(k);}function g(k){let m=async y=>{let i=y.data?.message?.json??y.data?.json;if(!i){console.warn("[SyncWorker] Received empty PubSub message");return}await S(i);let u=x.get(i.repoName);u&&await u.flush();};return b?n.pubsubHandler.onMessagePublished({topic:k,...b},m):n.pubsubHandler.onMessagePublished(k,m)}return {handleMessage:S,createHandler:g,queues:x,async shutdown(){let k=[];for(let m of x.values())k.push(m.shutdown());await Promise.all(k);}}}var no="firestore-sync";function On(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 En(e,t){let{deps:n,adapter:r,topicPrefix:o=no,batchSize:s,flushIntervalMs:a,autoMigrate:p,admin:d,workerOptions:b,repos:v}=t,x=On(n.pubsub),A=On(r),S=Rn(e,{deps:{firestoreTriggers:n.firestoreTriggers,pubsub:x},topicPrefix:o,repos:v}),g=Cn(e,{deps:{pubsubHandler:n.pubsubHandler,pubsub:x},adapter:A,batchSize:s,flushIntervalMs:a,autoMigrate:p,topicPrefix:o,workerOptions:b,repos:v}),k={};for(let i of Object.keys(e))k[`sync_${i}`]=g.createHandler(`${o}-${i}`);let m=null;d&&(m=Sn(e,A,g.queues,g.handleMessage,d,v??{},x,o),k.adminsync=d.onRequest?d.httpsOptions?d.onRequest(d.httpsOptions,m):d.onRequest(m):m);let y={functions:{...S,...k},adminHandler:m,handleMessage:g.handleMessage,queues:g.queues,shutdown:g.shutdown};for(let i of ["adminHandler","handleMessage","queues","shutdown"])Object.defineProperty(y,i,{enumerable:false});return y}Ze();Ze();function ro(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/^\s/,"").replace(/^./,t=>t.toUpperCase())}function Pn(e){let t=e,n=true,r=false,o;for(;;){let s=q(t);if(s==="ZodOptional")n=false,t=X(t);else if(s==="ZodNullable")n=false,r=true,t=X(t);else if(s==="ZodDefault")n=false,o=hn(t),t=X(t);else if(s==="ZodEffects"||s==="ZodPipe"||s==="ZodTransform"){let a=He(t);if(!a)break;t=a;}else break}return {inner:t,required:n,nullable:r,defaultValue:o}}function re(e,t=""){if(q(e)==="ZodObject"){let r=Y(e);return Object.entries(r).map(([o,s])=>$n(t?`${t}.${o}`:o,o,s))}return [$n(t||"value",t||"value",e)]}function $n(e,t,n){let{inner:r,required:o,nullable:s,defaultValue:a}=Pn(n),p=q(r),d=ro(t.split(".").pop()??t);switch(p){case "ZodString":{let b=bn(r),v=b.includes("email"),x=b.includes("url");return {name:e,label:d,type:"text",required:o,nullable:s,defaultValue:a,hint:v?"email":x?"url":void 0}}case "ZodNumber":case "ZodBigInt":return {name:e,label:d,type:"number",required:o,nullable:s,defaultValue:a};case "ZodBoolean":return {name:e,label:d,type:"checkbox",required:o,nullable:s,defaultValue:a};case "ZodDate":case "ZodCoerce":return {name:e,label:d,type:"datetime-local",required:o,nullable:s,defaultValue:a};case "ZodEnum":{let b=Ne(r);return {name:e,label:d,type:"select",required:o,nullable:s,defaultValue:a,options:b}}case "ZodNativeEnum":{let b=ze(r),v=Object.values(b).filter(x=>typeof x=="string");return {name:e,label:d,type:"select",required:o,nullable:s,defaultValue:a,options:v}}case "ZodLiteral":{let b=String(Be(r)??"");return {name:e,label:d,type:"select",required:o,nullable:s,defaultValue:a,options:[b]}}case "ZodUnion":{let b=qe(r);if(b.length>0&&b.every(S=>q(S)==="ZodLiteral")){let S=b.map(g=>String(Be(g)??""));return {name:e,label:d,type:"select",required:o,nullable:s,defaultValue:a,options:S}}if(b.some(S=>q(S)==="ZodDate"))return {name:e,label:d,type:"datetime-local",required:o,nullable:s,defaultValue:a};let A=b.find(S=>{if(q(S)==="ZodObject"){let g=Y(S);return "_latitude"in g&&"_longitude"in g||"latitude"in g&&"longitude"in g}return false});return A?{name:e,label:d,type:"textarea",required:o,nullable:s,defaultValue:a,nested:re(A,e),hint:"GeoPoint"}:{name:e,label:d,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON"}}case "ZodObject":{let b=re(r,e);return {name:e,label:d,type:"textarea",required:o,nullable:s,defaultValue:a,nested:b,hint:"JSON object"}}case "ZodArray":{let b=gn(r);if(!b)return {name:e,label:d,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON array"};let{inner:v}=Pn(b),x=q(v),A,S,g;switch(x){case "ZodString":A="text";break;case "ZodNumber":case "ZodBigInt":A="number";break;case "ZodBoolean":A="checkbox";break;case "ZodDate":A="datetime-local";break;case "ZodEnum":A="select",S=Ne(v);break;case "ZodNativeEnum":A="select",S=Object.values(ze(v)).filter(k=>typeof k=="string");break;case "ZodObject":A="object",g=re(v);break;default:return {name:e,label:d,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON array"}}return {name:e,label:d,type:"textarea",required:o,nullable:s,defaultValue:a,arrayElementType:A,arrayElementOptions:S,arrayElementFields:g}}default:return {name:e,label:d,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON"}}}function Ue(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__",p=!a&&e.defaultValue!=null?String(e.defaultValue):"",d=e.nullable&&e.type!=="checkbox"?`<span class="flex items-center gap-1 shrink-0">
84
+ </div>`);ue(m,O);}),async(S,m)=>{await A.handle(S,m);}}var Jr="firestore-sync";function Xr(e,t){return t?`${t}/{docId}`:(console.warn(`[SyncTriggers] Cannot determine collection path for "${e}". Skipping.`),null)}function Yr(e){let t=[e?.documentKey,e?.pathKey,e?.createdKey,e?.updatedKey].filter(n=>typeof n=="string");return {isGroup:!!e?.isGroup,documentKey:t[0]??"docId",collectionPath:typeof e?.path=="string"?e.path:null}}function eo(e){return {isGroup:!!e?._isGroup,documentKey:e?._systemKeys?.[0]??"docId",collectionPath:e?.ref?.path??null}}function Rn(e,t){let{onDocumentCreated:n,onDocumentUpdated:r,onDocumentDeleted:o}=t.deps.firestoreTriggers,s=t.deps.pubsub,a=t?.topicPrefix??Jr,u={},d=new Map;function b(S){let m=d.get(S);return m||(m=s.topic(S),d.set(S,m),m)}async function v(S,m){await b(S).publishMessage({json:m});}let x=e?.rawMapping,A=x?Object.entries(x).map(([S,m])=>[S,Yr(m)]):Object.entries(e).map(([S,m])=>[S,eo(m)]);for(let[S,m]of A){let k=t?.repos?.[S],y;if(m.isGroup){if(!k?.triggerPath){console.warn(`[SyncTriggers] Skipping collection-group repo "${S}". Provide a triggerPath in the sync repos config for group collections.`);continue}y=k.triggerPath;}else y=k?.triggerPath??Xr(S,m.collectionPath);if(!y)continue;let g=m.documentKey,i=`${a}-${S}`;u[`${S}_onCreate`]=n(y,async p=>{let l=p.data;if(!l)return;let c=l.data();if(!c)return;let f=String(c[g]??l.id),h=Le(c,{exclude:k?.exclude,columnMap:k?.columnMap}),w={operation:"INSERT",repoName:S,docId:f,data:h,timestamp:new Date().toISOString(),version:Date.now()};await v(i,w);}),u[`${S}_onUpdate`]=r(y,async p=>{let l=p.data?.after;if(!l)return;let c=l.data();if(!c)return;let f=String(c[g]??l.id),h=Le(c,{exclude:k?.exclude,columnMap:k?.columnMap}),w={operation:"UPSERT",repoName:S,docId:f,data:h,timestamp:new Date().toISOString(),version:Date.now()};await v(i,w);}),u[`${S}_onDelete`]=o(y,async p=>{let l=p.data;if(!l)return;let c=l.data(),f=String(c?.[g]??l.id),h={operation:"DELETE",repoName:S,docId:f,data:null,timestamp:new Date().toISOString(),version:Date.now()};await v(i,h);});}return u}function kn(e){let t=e.toUpperCase();switch(t){case "INTEGER":return "INT64";case "FLOAT":return "FLOAT64";case "BOOLEAN":return "BOOL";default:return t}}function Tn(e,t){let n=kn(e),r=kn(t);return n===r?true:{INT64:["NUMERIC","BIGNUMERIC","FLOAT64"],NUMERIC:["BIGNUMERIC","FLOAT64"],DATE:["DATETIME","TIMESTAMP"],DATETIME:["TIMESTAMP"]}[n]?.includes(r)??false}var at=class{constructor(t){this.buffer=[];this.flushing=false;this.flushPromise=null;this.timer=null;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();},n),typeof this.timer=="object"&&"unref"in this.timer&&this.timer.unref());}get size(){return this.buffer.length}enqueue(...t){this.buffer.push(...t),this.buffer.length>=this.batchSize&&this.flush();}async flush(){for(;this.flushPromise;)await this.flushPromise;this.buffer.length!==0&&(this.flushing=true,this.flushPromise=this._drain().finally(()=>{this.flushing=false,this.flushPromise=null;}),await this.flushPromise);}async _drain(){for(;this.buffer.length>0&&await this._doFlush(););}async _doFlush(){let t=this.buffer.splice(0,this.batchSize);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 u=Number(a[me]??0);Number(s.data[me]??0)>=u&&n.set(s.docId,s.data);}}let o=Array.from(n.values());o.length>0&&await this.adapter.upsertRows(this.tableName,o,this.primaryKey),r.length>0&&await this.adapter.deleteRows(this.tableName,this.primaryKey,r);}catch(n){if(this.onFlushError)await this.onFlushError(t,n);else return this.buffer.unshift(...t),console.error(`[SyncQueue] Flush failed for ${this.tableName}:`,n),false}return true}async shutdown(){this.timer&&(clearInterval(this.timer),this.timer=null),await this.flush();}};var An=new Set,Ot=class extends Error{constructor(n,r,o,s){super(`Schema drift detected on \`${n}\`: column \`${r}\` has type ${o} in BigQuery but the current Zod schema maps it to ${s}. BigQuery cannot safely convert between these types \u2014 to resolve, either (a) keep the BigQuery type and add a transform in your repo to coerce values, (b) rename the field in your Zod schema (creates a new column), or (c) drop & recreate the table.`);this.tableName=n;this.column=r;this.existingType=o;this.desiredType=s;this.name="SchemaTypeMismatchError";}};async function to(e,t,n,r,o,s,a){if(An.has(e))return;let u=ot(n,t.dialect,{primaryKey:o,exclude:s,columnMap:a});if(!await t.tableExists(r))await t.createTable({tableName:r,columns:u});else if(t.getTableColumnsWithTypes){let b=await t.getTableColumnsWithTypes(r),v=[];for(let x of u){let A=b.get(x.name);if(A===void 0){v.push(x);continue}if(t.dialect.name==="bigquery"&&!Tn(A,x.sqlType))throw new Ot(r,x.name,A,x.sqlType)}v.length>0&&(await t.addColumns(r,v),await t.onSchemaChange?.(r));}else {let b=new Set(await t.getTableColumns(r)),v=u.filter(x=>!b.has(x.name));v.length>0&&(await t.addColumns(r,v),await t.onSchemaChange?.(r));}An.add(e);}function Cn(e,t){let{deps:n,adapter:r,batchSize:o=100,flushIntervalMs:s=5e3,autoMigrate:a=false,topicPrefix:u="firestore-sync",maxDlqAttempts:d=5,workerOptions:b,repos:v={}}=t,x=new Map;function A(k,y){let g=x.get(k);if(g)return g;let p=v[k]?.tableName??k,l=`${u}-${k}-dlq`,c=n.pubsub.topic(l),f=false,h=async()=>{if(!f){try{await c.create(),console.info(`[SyncWorker] Created DLQ topic "${l}"`);}catch(O){if(O?.code!==6)throw O}f=true;}},w=async(O,T)=>{console.error(`[SyncWorker] Flush failed for "${k}" (${O.length} events):`,T),await h(),await Promise.all(O.map(R=>{let C=(R.attempts??0)+1;if(d>0&&C>d)return console.error(`[SyncWorker] Dropping event for "${k}" after ${C-1} DLQ attempts:`,{docId:R.docId,operation:R.operation}),Promise.resolve();let E={...R,attempts:C,firstFailedAt:R.firstFailedAt??Date.now()};return c.publishMessage({json:E})}));};return g=new at({adapter:r,tableName:p,primaryKey:y,batchSize:o,flushIntervalMs:s,onFlushError:w}),x.set(k,g),g}async function S(k){let{repoName:y}=k,g=e[y];if(!g){console.warn(`[SyncWorker] Unknown repo "${y}", skipping event`);return}let i=g._systemKeys?.[0]??g.documentKey??"docId",p=v[y],l=p?.columnMap,c=l?.[i]??i;if(a){let h=g.schema??void 0;if(h){let w=p?.tableName??y;await to(y,r,h,w,i,p?.exclude,l);}}let f=A(y,c);k.data&&(k.data[me]=k.version??Date.now()),f.enqueue(k);}function m(k){let y=async g=>{let i=g.data?.message?.json??g.data?.json;if(!i){console.warn("[SyncWorker] Received empty PubSub message");return}await S(i);let p=x.get(i.repoName);p&&await p.flush();};return b?n.pubsubHandler.onMessagePublished({topic:k,...b},y):n.pubsubHandler.onMessagePublished(k,y)}return {handleMessage:S,createHandler:m,queues:x,async shutdown(){let k=[];for(let y of x.values())k.push(y.shutdown());await Promise.all(k);}}}var no="firestore-sync";function On(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 En(e,t){let{deps:n,adapter:r,topicPrefix:o=no,batchSize:s,flushIntervalMs:a,autoMigrate:u,admin:d,workerOptions:b,repos:v}=t,x=On(n.pubsub),A=On(r),S=Rn(e,{deps:{firestoreTriggers:n.firestoreTriggers,pubsub:x},topicPrefix:o,repos:v}),m=Cn(e,{deps:{pubsubHandler:n.pubsubHandler,pubsub:x},adapter:A,batchSize:s,flushIntervalMs:a,autoMigrate:u,topicPrefix:o,workerOptions:b,repos:v}),k={};for(let i of Object.keys(e))k[`sync_${i}`]=m.createHandler(`${o}-${i}`);let y=null;d&&(y=Sn(e,A,m.queues,m.handleMessage,d,v??{},x,o),k.adminsync=d.onRequest?d.httpsOptions?d.onRequest(d.httpsOptions,y):d.onRequest(y):y);let g={functions:{...S,...k},adminHandler:y,handleMessage:m.handleMessage,queues:m.queues,shutdown:m.shutdown};for(let i of ["adminHandler","handleMessage","queues","shutdown"])Object.defineProperty(g,i,{enumerable:false});return g}Ze();Ze();function ro(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/^\s/,"").replace(/^./,t=>t.toUpperCase())}function Pn(e){let t=e,n=true,r=false,o;for(;;){let s=q(t);if(s==="ZodOptional")n=false,t=X(t);else if(s==="ZodNullable")n=false,r=true,t=X(t);else if(s==="ZodDefault")n=false,o=hn(t),t=X(t);else if(s==="ZodEffects"||s==="ZodPipe"||s==="ZodTransform"){let a=He(t);if(!a)break;t=a;}else break}return {inner:t,required:n,nullable:r,defaultValue:o}}function re(e,t=""){if(q(e)==="ZodObject"){let r=Y(e);return Object.entries(r).map(([o,s])=>$n(t?`${t}.${o}`:o,o,s))}return [$n(t||"value",t||"value",e)]}function $n(e,t,n){let{inner:r,required:o,nullable:s,defaultValue:a}=Pn(n),u=q(r),d=ro(t.split(".").pop()??t);switch(u){case "ZodString":{let b=bn(r),v=b.includes("email"),x=b.includes("url");return {name:e,label:d,type:"text",required:o,nullable:s,defaultValue:a,hint:v?"email":x?"url":void 0}}case "ZodNumber":case "ZodBigInt":return {name:e,label:d,type:"number",required:o,nullable:s,defaultValue:a};case "ZodBoolean":return {name:e,label:d,type:"checkbox",required:o,nullable:s,defaultValue:a};case "ZodDate":case "ZodCoerce":return {name:e,label:d,type:"datetime-local",required:o,nullable:s,defaultValue:a};case "ZodEnum":{let b=Ne(r);return {name:e,label:d,type:"select",required:o,nullable:s,defaultValue:a,options:b}}case "ZodNativeEnum":{let b=ze(r),v=Object.values(b).filter(x=>typeof x=="string");return {name:e,label:d,type:"select",required:o,nullable:s,defaultValue:a,options:v}}case "ZodLiteral":{let b=String(Be(r)??"");return {name:e,label:d,type:"select",required:o,nullable:s,defaultValue:a,options:[b]}}case "ZodUnion":{let b=qe(r);if(b.length>0&&b.every(S=>q(S)==="ZodLiteral")){let S=b.map(m=>String(Be(m)??""));return {name:e,label:d,type:"select",required:o,nullable:s,defaultValue:a,options:S}}if(b.some(S=>q(S)==="ZodDate"))return {name:e,label:d,type:"datetime-local",required:o,nullable:s,defaultValue:a};let A=b.find(S=>{if(q(S)==="ZodObject"){let m=Y(S);return "_latitude"in m&&"_longitude"in m||"latitude"in m&&"longitude"in m}return false});return A?{name:e,label:d,type:"textarea",required:o,nullable:s,defaultValue:a,nested:re(A,e),hint:"GeoPoint"}:{name:e,label:d,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON"}}case "ZodObject":{let b=re(r,e);return {name:e,label:d,type:"textarea",required:o,nullable:s,defaultValue:a,nested:b,hint:"JSON object"}}case "ZodArray":{let b=gn(r);if(!b)return {name:e,label:d,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON array"};let{inner:v}=Pn(b),x=q(v),A,S,m;switch(x){case "ZodString":A="text";break;case "ZodNumber":case "ZodBigInt":A="number";break;case "ZodBoolean":A="checkbox";break;case "ZodDate":A="datetime-local";break;case "ZodEnum":A="select",S=Ne(v);break;case "ZodNativeEnum":A="select",S=Object.values(ze(v)).filter(k=>typeof k=="string");break;case "ZodObject":A="object",m=re(v);break;default:return {name:e,label:d,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON array"}}return {name:e,label:d,type:"textarea",required:o,nullable:s,defaultValue:a,arrayElementType:A,arrayElementOptions:S,arrayElementFields:m}}default:return {name:e,label:d,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON"}}}function Ue(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__",u=!a&&e.defaultValue!=null?String(e.defaultValue):"",d=e.nullable&&e.type!=="checkbox"?`<span class="flex items-center gap-1 shrink-0">
85
85
  <input type="hidden" id="${r}__isnull" name="${o}__isnull" value="${a?"1":""}">
86
86
  <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">
87
87
  <input type="checkbox" class="checkbox checkbox-xs" ${a?"checked":""}
@@ -93,7 +93,7 @@ ${n}
93
93
  })(this)">
94
94
  <span>null</span>
95
95
  </label>
96
- </span>`:"",b;switch(e.type){case "checkbox":if(e.nullable){let v=a?"__null__":p==="true"?"true":p==="false"?"false":"__null__";return `
96
+ </span>`:"",b;switch(e.type){case "checkbox":if(e.nullable){let v=a?"__null__":u==="true"?"true":u==="false"?"false":"__null__";return `
97
97
  <div class="form-control mb-3 ${n}">
98
98
  <label for="${r}" class="label pb-1">
99
99
  <span class="label-text font-medium">
@@ -109,14 +109,14 @@ ${n}
109
109
  </div>`}return `
110
110
  <div class="form-control ${n}">
111
111
  <label class="label cursor-pointer justify-start gap-3">
112
- <input type="checkbox" id="${r}" name="${o}" value="true"${p==="true"?" checked":""} class="checkbox checkbox-primary checkbox-sm">
112
+ <input type="checkbox" id="${r}" name="${o}" value="true"${u==="true"?" checked":""} class="checkbox checkbox-primary checkbox-sm">
113
113
  <span class="label-text font-medium">
114
114
  ${M(e.label)}${e.required?' <span class="text-error">*</span>':""}
115
115
  </span>
116
116
  </label>
117
117
  </div>`;case "select":b=`<select id="${r}" name="${o}"${s}${a?' disabled style="opacity:0.35"':""} class="select select-bordered select-sm w-full">
118
118
  ${e.required&&!e.nullable?"":'<option value="">\u2014 optional \u2014</option>'}
119
- ${(e.options??[]).map(v=>`<option value="${M(v)}"${p===v?" selected":""}>${M(v)}</option>`).join(`
119
+ ${(e.options??[]).map(v=>`<option value="${M(v)}"${u===v?" selected":""}>${M(v)}</option>`).join(`
120
120
  `)}
121
121
  </select>`;break;case "textarea":if(e.arrayElementType)return oo(e,t);if(e.nested&&e.nested.length>0){let v=e.nested.map(x=>Ue(x,t+1)).join(`
122
122
  `);return `
@@ -128,8 +128,8 @@ ${n}
128
128
  </fieldset>`}b=`<textarea id="${r}" name="${o}"${s} rows="3"${a?' disabled style="opacity:0.35"':""}
129
129
  data-json
130
130
  class="textarea textarea-bordered textarea-sm w-full font-mono text-xs"
131
- placeholder="${M(e.hint??"JSON")}">${M(p)}</textarea>`;break;default:b=`<input type="${e.type}" id="${r}" name="${o}"${s}${a?' disabled style="opacity:0.35"':""}
132
- value="${M(p)}"
131
+ placeholder="${M(e.hint??"JSON")}">${M(u)}</textarea>`;break;default:b=`<input type="${e.type}" id="${r}" name="${o}"${s}${a?' disabled style="opacity:0.35"':""}
132
+ value="${M(u)}"
133
133
  class="input input-bordered input-sm w-full"${e.hint==="email"?' autocomplete="email"':e.hint==="url"?' autocomplete="url"':""}>`;}return `
134
134
  <div class="form-control mb-3 ${n}">
135
135
  <label for="${r}" class="label pb-1">
@@ -142,7 +142,7 @@ ${n}
142
142
  <div class="flex-1 min-w-0">${b}</div>
143
143
  ${d}
144
144
  </div>
145
- </div>`}function M(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function oo(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 p=s?a.map(v=>Dn(e,v??{})).join(`
145
+ </div>`}function M(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function oo(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 u=s?a.map(v=>Dn(e,v??{})).join(`
146
146
  `):a.map(v=>In(e,v)).join(`
147
147
  `),d=s?Dn(e,{}):In(e,""),b=e.nullable?`<span class="flex items-center gap-1 mt-2">
148
148
  <input type="hidden" id="${r}__isnull" name="${M(e.name)}__isnull" value="${o?"1":""}">
@@ -165,7 +165,7 @@ ${n}
165
165
  </legend>
166
166
  <input type="hidden" id="${r}" name="${M(e.name)}" value="${M(JSON.stringify(a))}"${o?" disabled":""}>
167
167
  <div data-frs-array-items${o?' style="opacity:0.35"':""}>
168
- ${p}
168
+ ${u}
169
169
  </div>
170
170
  <template data-frs-array-tpl>${d}</template>
171
171
  <button type="button" class="btn btn-xs btn-outline mt-1" data-frs-array-add>+ Add</button>
@@ -192,7 +192,7 @@ ${n}
192
192
  <label class="label pb-1"><span class="label-text text-sm">${M(o.label)}</span></label>
193
193
  <select data-frs-key="${M(o.name)}" class="select select-bordered select-sm w-full">
194
194
  ${o.required?"":'<option value="">\u2014</option>'}
195
- ${(o.options??[]).map(p=>`<option value="${M(p)}"${a===p?" selected":""}>${M(p)}</option>`).join("")}
195
+ ${(o.options??[]).map(u=>`<option value="${M(u)}"${a===u?" selected":""}>${M(u)}</option>`).join("")}
196
196
  </select>
197
197
  </div>`;case "number":return `<div class="form-control mb-2">
198
198
  <label class="label pb-1"><span class="label-text text-sm">${M(o.label)}</span></label>
@@ -216,7 +216,7 @@ ${n}
216
216
  <button type="submit" class="btn btn-primary btn-sm">${M(r)}</button>
217
217
  <button type="button" class="btn btn-ghost btn-sm" onclick="history.back()">Cancel</button>
218
218
  </div>
219
- </form>`}var so=new Set(["<","<=",">",">=","!="]),ao=new Set(["array-contains","array-contains-any"]);function Et(e){return e==="desc"?"DESCENDING":"ASCENDING"}function io(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function co(e,t,n,r,o){let s=[],a=new Set;for(let d of r)if(d.op==="=="||d.op==="in"||d.op==="not-in"){if(a.has(d.field))continue;a.add(d.field),s.push({fieldPath:d.field,order:"ASCENDING"});}for(let d of r)if(ao.has(d.op)){if(a.has(d.field))continue;a.add(d.field),s.push({fieldPath:d.field,arrayConfig:"CONTAINS"});}for(let d of r)if(so.has(d.op)){if(a.has(d.field))continue;a.add(d.field);let b=o?.field===d.field?Et(o.dir):"ASCENDING";s.push({fieldPath:d.field,order:b});}if(o&&!a.has(o.field)&&s.push({fieldPath:o.field,order:Et(o.dir)}),s.length===1&&n)return po(e,t,s[0]);let p=o&&s.some(d=>d.fieldPath===o.field)?Et(o.dir):"ASCENDING";return s.push({fieldPath:"__name__",order:p}),lo(e,t,n,s)}function lo(e,t,n,r,o="(default)"){let s=`projects/${e}/databases/${o}/collectionGroups/${t}/indexes/_`,a=[...It(1,s),...it(2,n?2:1)];for(let b of r)a.push(..._n(3,jn(b)));let p=o==="(default)"?"-default-":o,d=encodeURIComponent(Fn(a));return `https://console.firebase.google.com/project/${e}/firestore/databases/${p}/indexes?create_composite=${d}`}function uo(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function Pt(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function $t(e,t){return e<<3|t}function It(e,t){let n=Array.from(new TextEncoder().encode(t));return [$t(e,2),...Pt(n.length),...n]}function it(e,t){return [$t(e,0),...Pt(t)]}function _n(e,t){return [$t(e,2),...Pt(t.length),...t]}function jn(e){let t=[...It(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...it(3,1)):t.push(...it(2,e.order==="DESCENDING"?2:1)),t}function Fn(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 po(e,t,n,r="(default)"){let o=`projects/${e}/databases/${r}/collectionGroups/${t}/fields/${n.fieldPath}`,s=[...It(1,o),...it(2,2),..._n(3,jn(n))],a=r==="(default)"?"-default-":r,p=encodeURIComponent(Fn(s));return `https://console.firebase.google.com/project/${e}/firestore/databases/${a}/indexes/automatic?create_exemption=${p}`}function fo(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 Se(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function Ke(e,t){let n=e??{},r=Se(e),o;if(r&&(o=n.message?uo(n.message):void 0,!o)){let s=fo(t.ref);if(s){let a=io(t.path);o=co(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}}ct();var Hn=`// \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
219
+ </form>`}var so=new Set(["<","<=",">",">=","!="]),ao=new Set(["array-contains","array-contains-any"]);function Et(e){return e==="desc"?"DESCENDING":"ASCENDING"}function io(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function co(e,t,n,r,o){let s=[],a=new Set;for(let d of r)if(d.op==="=="||d.op==="in"||d.op==="not-in"){if(a.has(d.field))continue;a.add(d.field),s.push({fieldPath:d.field,order:"ASCENDING"});}for(let d of r)if(ao.has(d.op)){if(a.has(d.field))continue;a.add(d.field),s.push({fieldPath:d.field,arrayConfig:"CONTAINS"});}for(let d of r)if(so.has(d.op)){if(a.has(d.field))continue;a.add(d.field);let b=o?.field===d.field?Et(o.dir):"ASCENDING";s.push({fieldPath:d.field,order:b});}if(o&&!a.has(o.field)&&s.push({fieldPath:o.field,order:Et(o.dir)}),s.length===1&&n)return po(e,t,s[0]);let u=o&&s.some(d=>d.fieldPath===o.field)?Et(o.dir):"ASCENDING";return s.push({fieldPath:"__name__",order:u}),lo(e,t,n,s)}function lo(e,t,n,r,o="(default)"){let s=`projects/${e}/databases/${o}/collectionGroups/${t}/indexes/_`,a=[...It(1,s),...it(2,n?2:1)];for(let b of r)a.push(..._n(3,jn(b)));let u=o==="(default)"?"-default-":o,d=encodeURIComponent(Fn(a));return `https://console.firebase.google.com/project/${e}/firestore/databases/${u}/indexes?create_composite=${d}`}function uo(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function Pt(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function $t(e,t){return e<<3|t}function It(e,t){let n=Array.from(new TextEncoder().encode(t));return [$t(e,2),...Pt(n.length),...n]}function it(e,t){return [$t(e,0),...Pt(t)]}function _n(e,t){return [$t(e,2),...Pt(t.length),...t]}function jn(e){let t=[...It(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...it(3,1)):t.push(...it(2,e.order==="DESCENDING"?2:1)),t}function Fn(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 po(e,t,n,r="(default)"){let o=`projects/${e}/databases/${r}/collectionGroups/${t}/fields/${n.fieldPath}`,s=[...It(1,o),...it(2,2),..._n(3,jn(n))],a=r==="(default)"?"-default-":r,u=encodeURIComponent(Fn(s));return `https://console.firebase.google.com/project/${e}/firestore/databases/${a}/indexes/automatic?create_exemption=${u}`}function fo(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 Se(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function Ke(e,t){let n=e??{},r=Se(e),o;if(r&&(o=n.message?uo(n.message):void 0,!o)){let s=fo(t.ref);if(s){let a=io(t.path);o=co(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}}ct();var Hn=`// \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
220
220
  function frsGetBasePath() {
221
221
  var root = document.querySelector("[data-frs-panel-root]");
222
222
  var bp = root && root.getAttribute("data-frs-base-path");
@@ -1138,7 +1138,7 @@ function initColumnReorder(table) {
1138
1138
  });
1139
1139
  });
1140
1140
  }
1141
- `;function Ve(){return jsx("script",{dangerouslySetInnerHTML:{__html:Hn}})}Mt();function he(e){return "<!DOCTYPE html>"+renderToString(e)}var Ro=["corporate","silk","dark"],ko=()=>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:Ro.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))})]}),be=({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(ko,{})})]}),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,p)=>a.href?jsx("li",{children:jsx("a",{href:a.href,children:a.label})},p):jsx("li",{class:"text-base-content/60",children:a.label},p))})}),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(Ft,{basePath:s}),jsx(Ve,{})]})]})};function Ht(e,t){return he(jsx(be,{opts:t,children:jsx("div",{dangerouslySetInnerHTML:{__html:e}})}))}function Nt(e,t){return he(jsx(be,{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 qn=[{value:"==",label:"="},{value:"!=",label:"\u2260"},{value:"in",label:"in"},{value:"not-in",label:"not in"}],To=[{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"}],Ao=[{value:"array-contains",label:"contains"},{value:"array-contains-any",label:"contains any"}];function Co(e){switch(e){case "ZodNumber":case "ZodBigInt":case "ZodDate":return To;case "ZodBoolean":return qn;case "ZodArray":return Ao;default:return qn}}var we="__null__";function Oo(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="${we}"]');if(!o){o=document.createElement('option');o.value='${we}';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='${we}';i.readOnly=true;}i.style.opacity='0.55';}else{i.style.opacity='';if(i.tagName==='SELECT'){var o2=i.querySelector('option[value="${we}"][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!=='${we}')?i.dataset._prev:'';}}})(this)`}function Eo(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 Je({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:Oo(e)}),jsx("span",{children:"\u2205"})]})}function Po({col:e,active:t}){let n=t?.value??"",r=n===we,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 p=new Set(n.split(",").map(b=>b.trim()).filter(Boolean)),d=`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(b=>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:b,checked:p.has(b),"data-enum-group":d,onchange:Eo(o,d)}),jsx("span",{children:b})]},b))]})}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(p=>jsx("option",{value:p,selected:n===p,children:p},p)),e.nullable&&jsx("option",{value:we,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsx(Je,{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:we,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsx(Je,{inputId:o,active:r})]});if(e.zodType==="ZodArray"){let p=t?.op==="array-contains-any";return jsx("input",{id:o,type:"text",name:`fv_${e.name}`,value:n,placeholder:p?"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(Je,{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(Je,{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(Je,{inputId:o,active:r})]})}function zt({action:e,columnMeta:t,activeFilters:n,isGroup:r}){let o=Object.fromEntries(n.map(d=>[d.field,d])),s=n.length>0,a=n.length>=2||r&&s,p=t.filter(d=>d.zodType!=="ZodObject"&&d.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:p.map(d=>{let b=Co(d.zodType),v=o[d.name],x=v?.op??b[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:d.name}),jsxs("div",{class:"flex gap-1.5",children:[b.length>1?jsx("select",{name:`fo_${d.name}`,class:"select select-sm select-bordered w-20 shrink-0",children:b.map(A=>jsx("option",{value:A.value,selected:A.value===x,children:A.label},A.value))}):jsx("input",{type:"hidden",name:`fo_${d.name}`,value:b[0].value}),jsx(Po,{col:d,active:v})]})]},d.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 Bt(e,t,n,r,o,s){let a=n==="create"?`Create ${e}`:`Edit ${e} / ${r??""}`,p=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 he(jsx(be,{opts:{title:a,breadcrumb:p,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}})})})}))}ct();jt();function qt(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 Zn(e,t,n,r,o){let s=qt(e,r,o);return s.set("cursor",t),s.set("dir",n),`?${s.toString()}`}function $o(e,t,n,r){let o=qt(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 Io(e,t,n){return `?${qt(t,n,e).toString()}`}function Zt(e,t,n,r,o,s,a=[],p=[],d=false,b=[],v,x,A,S,g,k,m,y=false){let i=`${r}/${e}`,u=`${i}/create`,l={};if(m)for(let R of n)l[R]=We(Qe(m,R));let c=(k??[]).filter(R=>true),f=c.length>0,h=d,w=h||f,O=c.map(R=>{let C=Qe(m,R),E=We(C),$=a.find(P=>P.name===R);return {name:R,type:E,enumValues:$?.enumValues??null,nullable:$?.nullable??false}}),T=[];return m&&(T=re(m).filter(C=>c.includes(C.name))),he(jsxs(be,{opts:{title:e,breadcrumb:[{label:"Repositories",href:r},{label:e}],basePath:r,flash:s},children:[a.length>0&&jsx(zt,{action:i,columnMeta:a,activeFilters:p,isGroup:S}),A&&jsxs("div",{role:"alert",class:`alert ${A.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:A.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:A.type==="index"?"Composite index required":"Query failed"}),jsx("div",{class:"text-sm",children:A.message})]}),A.indexUrl&&jsx("a",{href:A.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 g=="number"&&jsxs(Fragment,{children:[" ","of"," ",jsx("span",{class:"font-semibold text-base-content/80",children:g})]})," ","document",(typeof g=="number"?g: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:Io(R,p,v),class:`join-item btn btn-xs ${x===R?"btn-active btn-primary":"btn-outline"}`,children:R},R))})]})]}),jsx("a",{href:u,class:"btn btn-primary btn-sm",children:"+ New"})]}),w&&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 g=="number"?String(g):"","data-frs-page-size":String(x??t.length),"data-frs-allow-delete":h?"1":"0","data-frs-allow-update":f?"1":"0","data-frs-fields":JSON.stringify(O),"data-frs-filters":JSON.stringify(p),children:[jsxs("div",{class:"flex-1 text-sm",children:[jsx("span",{"data-frs-bulk-summary":true,children:"0 selected"}),typeof g=="number"&&g>t.length&&jsxs("button",{type:"button",class:"ml-3 link text-sm hidden","data-frs-bulk-select-all":true,children:["Select all ",g," matching documents"]}),jsxs("span",{class:"hidden ml-3 italic","data-frs-bulk-all-active":true,children:["All ",g??"?"," 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:[f&&jsx("button",{type:"button",class:"btn btn-sm btn-outline","data-frs-bulk-action":"update",children:"Update field\u2026"}),h&&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:[w&&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,C)=>{let E=v?.field===R,$=E?v.dir==="asc"?" \u25B2":" \u25BC":"";return jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:jsxs("a",{href:$o(R,v,p,x),class:`hover:text-base-content inline-flex items-center gap-0.5${E?" text-primary font-bold":""}`,children:[R,$]})},C)}),b.map((R,C)=>jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:R.column},`rel-${C}`)),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+b.length+1+(w?1:0),class:"text-center py-16 text-base-content/40",children:"No documents found"})}):t.map((R,C)=>{let E=String(R.docId??R.id??""),$=`${r}/${e}/${encodeURIComponent(E)}/edit`,P=`${r}/${e}/${encodeURIComponent(E)}/delete`;return jsxs("tr",{class:"hover","data-frs-row-id":E,children:[w&&jsx("td",{class:"align-middle py-2",children:jsx("input",{type:"checkbox",class:"checkbox checkbox-xs checkbox-primary","data-frs-select-row":true,value:E,"aria-label":`Select ${E}`})}),n.map((D,H)=>{let j=R[D],I=l[D],K=I?Ge(I,j):null;return jsx("td",{class:"align-top py-2",children:jsx(Pe,{val:j,mismatch:K})},H)}),b.map((D,H)=>{let j=R[D.key];if(j==null||j==="")return jsx("td",{class:"py-2"},`rel-${H}`);let I=D.type==="one"?`${r}/${D.targetRepo}/${encodeURIComponent(String(j))}/edit`:`${r}/${D.targetRepo}?fv_${D.targetKey}=${encodeURIComponent(String(j))}`;return jsx("td",{class:"align-middle py-2",children:jsx("a",{href:I,class:"btn btn-xs btn-ghost btn-outline","data-frs-relation":true,"data-frs-rel-type":D.type,"data-frs-rel-repo":D.targetRepo,"data-frs-rel-fk":D.targetKey,"data-frs-rel-val":String(j),"data-frs-rel-label":D.column,children:D.column})},`rel-${H}`)}),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"}),y&&jsx("a",{href:`${r}/${e}/${encodeURIComponent(E)}/history`,class:"btn btn-xs btn-outline",title:"View change history",children:"History"}),d&&jsx("form",{method:"post",action:P,onsubmit:"return confirm('Delete this document?')",children:jsx("button",{type:"submit",class:"btn btn-xs btn-error btn-outline",children:"Delete"})})]})})]},C)})})]})}),(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:Zn(p,o.prevCursor,"prev",v,x),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:Zn(p,o.nextCursor,"next",v,x),class:"btn btn-sm btn-outline",children:"Next \u2192"}):jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"Next \u2192"})]}),typeof g=="number"&&jsxs("div",{class:"text-xs text-base-content/50",children:[g," total document",g!==1?"s":"",p.length>0?" matching filters":""]})]}),w&&f&&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"}),c.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:T.map(R=>jsx("div",{"data-frs-bulk-template-for":R.name,dangerouslySetInnerHTML:{__html:Ue(R)}},R.name))})]}))}var _o="";function Xe(e,t){return Ht(e,t)}function Lt(e,t){return Nt(e,t)}function Ut(e,t,n,r,o,s,a,p,d,b,v,x,A,S,g,k,m,y){return Zt(e,t,n,r,o,s,a,p,d,b,v,x,A,S,g,k,m,y)}function ve(e,t,n,r,o,s){return Bt(e,t,n,r,o,s)}var Kt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Mo(){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>=Kt.length*4||(e+=Kt.charAt(r%Kt.length));}}return e}function dt(e,t){if(!t)return;let n=e[t];if(typeof n!="string"||!n)return;let r=n.split("/").filter(Boolean),o=[];for(let s=1;s<r.length;s+=2)o.push(r[s]);return o.length>0?o:void 0}async function $e(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 Vt(e,t,n){let r=e.documentKey??"docId",o=Ke(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 z(e,t,n=200){e.status(n).set("Content-Type","text/html; charset=utf-8").send(t);}function Wt(e,t){e.status(302).set("Location",t).send("");}function ut(e,t){let n=t.shape,r={};for(let[o,s]of Object.entries(n)){let a=Gt(s),p=q(a),d=p==="ZodObject",b=a,v=false;if(p==="ZodUnion"){let S=qe(a);S.some(k=>q(k)==="ZodDate")&&(v=true);let g=S.find(k=>{if(q(k)==="ZodObject"){let m=Y(k);return "latitude"in m&&"longitude"in m}return false});g&&(d=true,b=g);}if(e[o+"__isnull"]==="1"){r[o]=null;continue}if(d){let S={},g=false;for(let[y,i]of Object.entries(e))y.startsWith(`${o}.`)&&(S[y.slice(o.length+1)]=i,g=true);if(g){r[o]=ut(S,b);continue}let k=e[o],m=Array.isArray(k)?k[k.length-1]:k;if(m)try{r[o]=JSON.parse(m);}catch{r[o]=m;}continue}let x=e[o],A=Array.isArray(x)?x[x.length-1]:x;if(A===void 0||A===""){p==="ZodBoolean"&&(r[o]=false);continue}if(v){r[o]=new Date(A);continue}switch(p){case "ZodBoolean":A==="__null__"?r[o]=null:r[o]=A==="true"||A==="on"||A==="1";break;case "ZodNumber":case "ZodBigInt":r[o]=Number(A);break;case "ZodDate":r[o]=new Date(A);break;case "ZodArray":try{r[o]=JSON.parse(A);}catch{r[o]=A;}break;default:if(A.startsWith("{")||A.startsWith("["))try{r[o]=JSON.parse(A);break}catch{}r[o]=A;}}return r}function Ln(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 Kn(e){let t=e;for(;;){let n=q(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=X(t);else if(n==="ZodEffects"||n==="ZodPipe"||n==="ZodTransform"){let r=He(t);if(!r)return n;t=r;}else return n}}function Gt(e){let t=e;for(;;){let n=q(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=X(t);else if(n==="ZodEffects"||n==="ZodPipe"||n==="ZodTransform"){let r=He(t);if(!r)return t;t=r;}else return t}}function Vn(e){let t=e;for(;;){let n=q(t);if(n==="ZodOptional"||n==="ZodNullable")return true;if(n==="ZodDefault"){t=X(t);continue}return false}}function Wn(e){let t=Gt(e),n=q(t);if(n==="ZodEnum"){let r=Ne(t);return r.length>0?r:void 0}if(n==="ZodNativeEnum"){let r=ze(t),o=Object.values(r).filter(s=>typeof s=="string");return o.length>0?o:void 0}if(n==="ZodLiteral"){let r=Be(t);return typeof r=="string"?[r]:void 0}}function Qn(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 p=Gt(t.shape[o]),d=q(p),b=d==="ZodObject",v=p,x=false;if(d==="ZodUnion"){let A=qe(p);A.some(g=>q(g)==="ZodDate")&&(x=true);let S=A.find(g=>{if(q(g)==="ZodObject"){let k=Y(g);return "latitude"in k&&"longitude"in k}return false});S&&(b=true,v=S);}if(b&&typeof a=="object"&&a!==null&&!Array.isArray(a)&&!("_seconds"in a)&&typeof a.toDate!="function"){let A=Qn(a,v,s);Object.assign(r,A);}else if(d==="ZodDate"||x){let A=Ln(a);A!==null&&(r[s]=A);}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)&&("_seconds"in a||typeof a.toDate=="function")){let A=Ln(a);r[s]=A??JSON.stringify(a,null,2);}else typeof a=="object"?r[s]=JSON.stringify(a,null,2):r[s]=String(a);}return r}function Qt(e,t){return e.map(n=>({...n,defaultValue:t[n.name]??n.defaultValue,nested:n.nested?Qt(n.nested,t):void 0}))}function Ho(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 p=(s??"").trim();if(!p)continue;let d=e[`fo_${a}`]??"==",b=n.has(d)?d:"==";r.push({field:a,op:b,value:p});}return r}function Un(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 Gn(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 p=Kn(a);if(p==="ZodObject"){let d=a;for(;;){let v=q(d);if(v==="ZodOptional"||v==="ZodNullable"||v==="ZodDefault")d=X(d);else break}let b=Y(d);r.push(...Gn(Object.keys(b),d,s));}else r.push({name:s,zodType:p,nullable:Vn(a),enumValues:Wn(a)});}return r}function No(e,t){let n=t.split("."),r=e;for(let o of n){for(;;){let a=q(r);if(a==="ZodOptional"||a==="ZodNullable"||a==="ZodDefault")r=X(r);else break}let s=Y(r);if(!(o in s))return null;r=s[o];}return r}function ke(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 p=s.slice(0,a),d=s.slice(a+1);r.has(p)||r.set(p,[]),r.get(p).push(d);}}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 p=e.shape[s];for(;;){let d=q(p);if(d==="ZodOptional"||d==="ZodNullable"||d==="ZodDefault")p=X(p);else break}if(q(p)!=="ZodObject"){o[s]=e.shape[s];continue}o[s]=ke(p,a);}return z$1.object(o)}function pe(e,t,n){return ae(e,t,n)}function Jn(e,t,n){let r=(i,u)=>{let l=pe(i,t,n),c=Object.values(e).map(f=>({name:f.name,path:f.path}));z(u,Lt(c,l));},o=async(i,u)=>{let l=i.params.repoName;if(!l){z(u,"Bad request",400);return}let c=e[l];if(!c){z(u,"Repository not found",404);return}let f=c.pageSize??25,h=i.query??{},w=h.cursor,O=h.dir==="prev"?"prev":"next",T=h.ob??"",R=h.od==="desc"?"desc":"asc",C=T?{field:T,dir:R}:void 0,E=parseInt(h.ps??""),$=Number.isFinite(E)&&E>0?Math.min(E,200):f,P=c.listColumns??Object.keys(c.schema.shape),D=c.documentKey??"docId",H=[D,...P.filter(Q=>Q!==D)];C&&(new Set([D,...P]).has(C.field)||(C=void 0));let j=c.filterableFields?(()=>{let Q=[];for(let le of c.filterableFields)(le.includes(".")||P.includes(le))&&Q.push(le);return Q})():P,I=(()=>{let Q=[];for(let le of j)if(le.includes(".")){let Ce=No(c.schema,le);Q.push({name:le,zodType:Ce?Kn(Ce):"ZodString",nullable:Ce?Vn(Ce):false,enumValues:Ce?Wn(Ce):void 0});}else Q.push(...Gn([le],c.schema));return Q})(),K=new Set(I.map(Q=>Q.name)),ce=Ho(h,K),U=Un(ce),se;if(w)try{let Q=c.repo.ref;typeof Q.doc=="function"&&(se=await Q.doc(w).get());}catch{}let[J,nt]=await Promise.all([c.repo.query.paginate({pageSize:$,cursor:se,direction:O,...U.length>0?{where:U}:{},...C?{orderBy:[{field:C.field,direction:C.dir}]}:{}}).catch(Q=>({queryError:Ke(Q,{ref:c.repo.ref,path:c.path,isGroup:!!c.isGroup,filters:ce,sort:C})})),c.repo.aggregate.count(U.length>0?{where:U}:{}).catch(()=>{})]),Ae="queryError"in J,vr=Ae?[]:J.data,xr=Ae?"":J.nextCursor?.id??"",Sr=Ae?"":J.prevCursor?.id??"",Rr=Ae?J.queryError:void 0,kr=pe(i,t,n);z(u,Ut(c.name,vr,H,kr,{hasPrev:Ae?false:J.hasPrevPage,hasNext:Ae?false:J.hasNextPage,prevCursor:Sr,nextCursor:xr},void 0,I,ce,c.allowDelete??false,c.relationalMeta,C,$,Rr,c.isGroup,nt,c.mutableFields,c.schema,c.historyEnabled));},s=(i,u)=>{let l=i.params.repoName;if(!l){z(u,"Bad request",400);return}let c=e[l];if(!c){z(u,"Repository not found",404);return}let f=pe(i,t,n),h=ke(c.schema,c.createFields),w=re(h),O=`${f}/${c.name}/create`,T=ge(w,O,"POST","Create document");z(u,ve(c.name,T,"create",null,f));},a=async(i,u)=>{let l=i.params.repoName;if(!l){z(u,"Bad request",400);return}let c=e[l];if(!c){z(u,"Repository not found",404);return}let f=pe(i,t,n),h=i.body??{},w=ut(h,c.schema),O=ke(c.schema,c.createFields),T=O.safeParse(w);if(!T.success){let R=re(O),C=`${f}/${c.name}/create`,E=ge(R,C,"POST","Create document"),$=T.error.issues.map(P=>`${P.path.join(".")}: ${P.message}`).join(", ");z(u,ve(c.name,E,"create",null,f,{type:"error",message:`Validation error: ${$}`}),422);return}try{if(c.isGroup&&c.parentKeys&&c.parentKeys.length>0){let R={...T.data};c.createdKey&&(R[c.createdKey]=new Date);let C=c.parentKeys.filter(D=>!R[D]);if(C.length>0)throw new Error(`Missing parent key(s) for subcollection create: ${C.join(", ")}`);let E=c.parentKeys.map(D=>R[D]),$=c.documentKey??"docId",P=R[$]||Mo();await c.repo.set(...E,P,R);}else await c.repo.create(T.data);Wt(u,`${f}/${c.name}?flash=created`);}catch(R){let C=ke(c.schema,c.createFields),E=re(C),$=`${f}/${c.name}/create`,P=ge(E,$,"POST","Create document");z(u,ve(c.name,P,"create",null,f,{type:"error",message:`Save error: ${R.message}`}),500);}},p=async(i,u)=>{let l=i.params.repoName,c=i.params.id;if(!l||!c){z(u,"Bad request",400);return}let f=e[l];if(!f){z(u,"Repository not found",404);return}let h=pe(i,t,n),w=null;try{w=await $e(f,c);}catch($){let P=Vt(f,c,$),D=Se($)?424:500;z(u,Xe("",{title:`Edit ${f.name} / ${c}`,basePath:h,breadcrumb:[{label:"Repositories",href:h},{label:f.name,href:`${h}/${f.name}`},{label:`Edit ${c}`}],flash:P}),D);return}if(!w){z(u,"Document not found",404);return}let O=Qn(w,f.schema),T=ke(f.schema,f.mutableFields),R=Qt(re(T),O),C=`${h}/${f.name}/${encodeURIComponent(c)}/edit`,E=ge(R,C,"POST","Save changes");z(u,ve(f.name,E,"edit",c,h));},d=async(i,u)=>{let l=i.params.repoName,c=i.params.id;if(!l||!c){z(u,"Bad request",400);return}let f=e[l];if(!f){z(u,"Repository not found",404);return}let h=pe(i,t,n),w=i.body??{},O=ut(w,f.schema),T=ke(f.schema,f.mutableFields),C=T.partial().safeParse(O);if(!C.success){let E=Object.fromEntries(Object.entries(w).map(([j,I])=>[j,Array.isArray(I)?I.join(","):I??""])),$=Qt(re(T),E),P=`${h}/${f.name}/${encodeURIComponent(c)}/edit`,D=ge($,P,"POST","Save changes"),H=C.error.issues.map(j=>`${j.path.join(".")}: ${j.message}`).join(", ");z(u,ve(f.name,D,"edit",c,h,{type:"error",message:`Validation error: ${H}`}),422);return}try{let E=await $e(f,c),$=(E&&dt(E,f.pathKey))??[c];await f.repo.update(...$,C.data),Wt(u,`${h}/${f.name}?flash=updated`);}catch(E){let $=ke(f.schema,f.mutableFields),P=re($),D=`${h}/${f.name}/${encodeURIComponent(c)}/edit`,H=ge(P,D,"POST","Save changes"),j=Se(E)?Vt(f,c,E):{type:"error",message:`Save error: ${E.message}`},I=Se(E)?424:500;z(u,ve(f.name,H,"edit",c,h,j),I);}},b=async(i,u)=>{let l=i.params.repoName,c=i.params.id;if(!l||!c){z(u,"Bad request",400);return}let f=e[l];if(!f){z(u,"Repository not found",404);return}if(!f.allowDelete){z(u,"Delete is not allowed for this repository",403);return}let h=pe(i,t,n);try{let w=await $e(f,c),O=(w&&dt(w,f.pathKey))??[c];await f.repo.delete(...O),Wt(u,`${h}/${f.name}?flash=deleted`);}catch(w){let O=Se(w)?Vt(f,c,w):{type:"error",message:`Delete error: ${w.message}`},T=Se(w)?424:500;z(u,Xe("",{title:`Delete ${f.name} / ${c}`,basePath:h,breadcrumb:[{label:"Repositories",href:h},{label:f.name,href:`${h}/${f.name}`},{label:`Delete ${c}`}],flash:O}),T);}},v=async(i,u)=>{let l=i.params.repoName;if(!l){z(u,"Bad request",400);return}let c=e[l];if(!c){z(u,"Repository not found",404);return}let f=pe(i,t,n),h=i.query,w=h?.type==="many"?"many":"one",O=Math.max(1,Math.min(100,Number(h?.ps??25)||25)),T=c.listColumns??Object.keys(Y(c.schema)),{PanelOne:R,PanelMany:C}=await Promise.resolve().then(()=>(Mt(),zn)),{renderToString:E}=await import('hono/jsx/dom/server');if(w==="one"){let I=String(h?.id??"");if(!I){z(u,"<div class='p-6 text-error'>Missing id parameter.</div>",400);return}try{let K=await $e(c,I),ce=E(R({doc:K,repoName:c.name,basePath:f,schema:c.schema,columns:T}));z(u,ce);}catch(K){z(u,`<div class='p-6 text-error text-sm'>Error: ${K.message}</div>`,500);}return}let $=String(h?.fk??""),P=String(h?.fv??"");if(!$||!P){z(u,"<div class='p-6 text-error'>Missing fk/fv parameters.</div>",400);return}let D=h?.cursor??"",H=h?.dir==="prev"?"prev":"next",j;if(D)try{let I=c.repo.ref;typeof I.doc=="function"&&(j=await I.doc(D).get());}catch{}try{let I=await c.repo.query.paginate({pageSize:O,cursor:j,direction:H,where:[[$,"==",zo(P)]]}),K=E(C({docs:I.data,repoName:c.name,basePath:f,fk:$,fv:P,columns:T,schema:c.schema,pagination:{hasPrev:I.hasPrevPage,hasNext:I.hasNextPage,prevCursor:I.prevCursor?.id??"",nextCursor:I.nextCursor?.id??"",pageSize:O}}));z(u,K);}catch(I){z(u,`<div class='p-6 text-error text-sm'>Error: ${I.message}</div>`,500);}},x=async(i,u)=>{let l=[];for(let c of u){let f;if(i.isGroup||i.parentKeys?.length){let h=await $e(i,c);f=h?dt(h,i.pathKey):void 0;}f||(f=[c]);try{let h=i.repo.documentRef(...f);h&&l.push(h);}catch{}}return l},A=async(i,u)=>{let l=Un(u),c=i.documentKey??"docId",f=[],h;for(;;){let w=await i.repo.query.paginate({pageSize:500,cursor:h,direction:"next",...l.length>0?{where:l}:{}});for(let O of w.data){let T=String(O[c]??O.id??"");T&&f.push(T);}if(!w.hasNextPage||!w.nextCursor)break;h=w.nextCursor;}return f},S=async(i,u)=>{let l=i.params.repoName;if(!l){te(u,{error:"Bad request"},400);return}let c=e[l];if(!c){te(u,{error:"Repository not found"},404);return}if(!c.allowDelete){te(u,{error:"Delete is not allowed for this repository"},403);return}let f=i.body??{};try{let h=await k(c,f);if(h.length===0){te(u,{deleted:0});return}let w=await x(c,h);for(let O=0;O<w.length;O+=500)await c.repo.bulk.delete(w.slice(O,O+500));te(u,{deleted:w.length});}catch(h){te(u,{error:h.message},500);}},g=async(i,u)=>{let l=i.params.repoName;if(!l){te(u,{error:"Bad request"},400);return}let c=e[l];if(!c){te(u,{error:"Repository not found"},404);return}let f=i.body??{},h=String(f.field??"");if(!h){te(u,{error:"Missing 'field'"},400);return}if(!c.mutableFields||!c.mutableFields.includes(h)){te(u,{error:`Field '${h}' is not bulk-updatable`},403);return}let w=c.schema.shape?.[h],O;if(w){let T=typeof c.schema=="object"&&c.schema&&"constructor"in c.schema&&c.schema.constructor.name.includes("Zod")?c.schema.pick({[h]:true}):void 0;if(!T){te(u,{error:"Invalid schema structure"},500);return}O=ut(f.formPayload??{},T)[h];let C=w.safeParse(O);if(!C.success){te(u,{error:`Invalid value for '${h}': ${C.error.message}`},400);return}O=C.data;}try{let T=await k(c,f);if(T.length===0){te(u,{updated:0});return}let C=(await x(c,T)).map(E=>({docRef:E,data:{[h]:O}}));for(let E=0;E<C.length;E+=500)await c.repo.bulk.update(C.slice(E,E+500));te(u,{updated:C.length});}catch(T){te(u,{error:T.message},500);}};async function k(i,u){if(u.selectAll){let l=m(u.filters,i);return await A(i,l)}return Array.isArray(u.ids)?u.ids.filter(l=>typeof l=="string"&&!!l):[]}function m(i,u){if(!Array.isArray(i))return [];let l=new Set((u.filterableFields??Object.keys(Y(u.schema))).map(h=>String(h))),c=new Set(["==","!=","<","<=",">",">=","in","not-in","array-contains","array-contains-any"]),f=[];for(let h of i)h&&typeof h=="object"&&typeof h.field=="string"&&l.has(h.field)&&typeof h.value=="string"&&c.has(String(h.op))&&f.push({field:h.field,op:h.op,value:h.value});return f}return {handleDashboard:r,handleList:o,handleCreateForm:s,handleCreateSubmit:a,handleEditForm:p,handleEditSubmit:d,handleDelete:b,handlePanel:v,handleBulkDelete:S,handleBulkUpdate:g,handleHistory:async(i,u)=>{let l=i.params.repoName,c=i.params.id;if(!l||!c){z(u,"Bad request",400);return}let f=e[l];if(!f){z(u,"Repository not found",404);return}if(!f.historyEnabled||!f.repo.history){z(u,"History not enabled for this repository",404);return}let h=pe(i,t,n),w=f.historySubcollection??"history",O=[c];try{let I=await $e(f,c),K=I?dt(I,f.pathKey):void 0;K&&K.length>0&&(O=K);}catch{}let T=parseInt(String(i.query?.limit??"")),R=Number.isFinite(T)&&T>0?Math.min(T,500):100,C=[],E;try{C=await f.repo.history.list(...O,{limit:R});}catch(I){E=I.message;}let $=I=>String(I??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),P=I=>{if(I===void 0)return '<span class="opacity-40">undefined</span>';if(I===null)return '<span class="opacity-40">null</span>';if(typeof I=="object")try{return `<code class="text-xs">${$(JSON.stringify(I))}</code>`}catch{return $(String(I))}return $(String(I))},D=I=>I?typeof I.toDate=="function"?I.toDate().toISOString():I instanceof Date?I.toISOString():$(String(I)):"",H=I=>`<span class="badge badge-sm ${I==="create"?"badge-success":I==="delete"?"badge-error":"badge-info"}">${$(I)}</span>`,j="";if(j+='<div class="flex items-center justify-between mb-4">',j+=`<a href="${h}/${f.name}/${encodeURIComponent(c)}/edit" class="btn btn-sm btn-outline">\u2190 Back to edit</a>`,j+=`<a href="${h}/${f.name}" class="btn btn-sm btn-outline">\u2190 Back to list</a>`,j+="</div>",j+=`<p class="text-sm text-base-content/60 mb-4">Subcollection: <code>${$(w)}</code> \xB7 Showing up to ${R} entries.</p>`,E)j+=`<div class="alert alert-error mb-4">${$(E)}</div>`;else if(C.length===0)j+='<div class="alert">No history entries found.</div>';else {j+='<div class="overflow-x-auto"><table class="table table-zebra table-sm">',j+="<thead><tr><th>When</th><th>Op</th><th>User</th><th>Reason / Comment</th><th>Changes</th></tr></thead><tbody>";for(let I of C){let K=I.meta??{},ce=[K.reason,K.comment].filter(J=>J!=null&&J!=="").map(J=>$(String(J))).join(" \u2014 "),U="",se=Object.keys(I.changes??{});se.length===0?U='<span class="opacity-40">\u2014</span>':U='<ul class="space-y-1">'+se.map(J=>{let nt=I.changes[J];return `<li><strong>${$(J)}</strong>: ${P(nt.oldValue)} \u2192 ${P(nt.newValue)}</li>`}).join("")+"</ul>",j+="<tr>",j+=`<td class="whitespace-nowrap text-xs font-mono">${$(D(I.historySetAt))}</td>`,j+=`<td>${H(I.operation??"update")}</td>`,j+=`<td class="text-xs">${$(K.userEmail??K.userId??"")}</td>`,j+=`<td class="text-xs">${ce}</td>`,j+=`<td>${U}</td>`,j+="</tr>";}j+="</tbody></table></div>";}z(u,Xe(j,{title:`History \u2014 ${f.name} / ${c}`,basePath:h,breadcrumb:[{label:"Repositories",href:h},{label:f.name,href:`${h}/${f.name}`},{label:`History ${c}`}]}));}}}function te(e,t,n=200){e.status(n).set("Content-Type","application/json; charset=utf-8").send(JSON.stringify(t));}function zo(e){return e==="true"?true:e==="false"?false:e!==""&&!isNaN(Number(e))?Number(e):e}ft();async function Bo(e){return typeof e.rawBody=="string"?e.rawBody:Buffer.isBuffer(e.rawBody)?e.rawBody.toString("utf8"):""}function qo(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 tr(e){let{basePath:t="/",repos:n,parseBody:r=true,securityHeaders:o,auth:s,middleware:a=[],httpsOptions:p}=e,d=t==="/"?"":t.replace(/\/$/,""),b={};for(let[S,g]of Object.entries(n)){if(!g.repo)throw new Error(`[createAdminServer] Repository "${S}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let k=g.schema??g.repo.schema??null;if(!k)throw new Error(`[createAdminServer] Repository "${S}" has no Zod schema. Either use createRepositoryConfig(schema)(config) or pass schema: explicitly.`);let m,y,i;if(g.fieldsConfig){let c=g.fieldsConfig;m=[],y=[],i=[];for(let[f,h]of Object.entries(c))for(let w of h)w==="filterable"?m.push(f):w==="mutable"?y.push(f):w==="create"&&i.push(f);m.length===0&&(m=void 0),y.length===0&&(y=void 0),i.length===0&&(i=void 0);}let u=(()=>{let c=g.repo._parentKeys;return c&&c.length>0?c:void 0})();if(u&&i)for(let c of u)i.includes(c)||i.push(c);let l={name:S,path:g.path,repo:g.repo,schema:k,documentKey:g.documentKey??"docId",pathKey:g.repo._pathKey??void 0,isGroup:!!g.repo._isGroup,parentKeys:u,createdKey:g.repo._createdKey??void 0,listColumns:g.listColumns,pageSize:g.pageSize,filterableFields:m,mutableFields:y,createFields:i,allowDelete:g.allowDelete??false,historyEnabled:!!g.repo._historyConfig?.enabled,historySubcollection:(g.repo._historyConfig?.enabled&&g.repo._historySubcollection)??void 0,relationalMeta:(()=>{if(!g.relationalFields||g.relationalFields.length===0)return;let c=g.repo.relationalKeys??{},f=[];for(let h of g.relationalFields){let w=c[h.key];w&&f.push({key:w.sourceKey?String(w.sourceKey):h.key,column:h.column,targetRepo:String(w.repo),targetKey:String(w.key),type:w.type});}return f.length>0?f:void 0})()};b[S]=l;}let v=Jn(b,d,yn(p?.region)),x=new ye;if(o!==false&&x.use(pt(o===void 0?{}:o)),r&&x.use(async(S,g,k)=>{let m=S,y=String(m.headers?.["content-type"]??"");if(y.includes("application/x-www-form-urlencoded")){let i=await Bo(m);S.body=qo(i);}else if(y.includes("application/json")&&typeof m.body=="string")try{S.body=JSON.parse(m.body);}catch{}await k();}),s)if(Me(s)){for(let S of s.routes){let g=`${d}${S.path}`;S.method==="GET"?x.get(g,S.handler):x.post(g,S.handler);}x.use(s.middleware);}else if(typeof s=="function")x.use(s);else {let S=s.realm??"Admin",g="Basic "+Buffer.from(`${s.username}:${s.password}`).toString("base64");x.use((k,m,y)=>{if((k.headers?.authorization??"")!==g){m.status(401).set("WWW-Authenticate",`Basic realm="${S}"`).set("Content-Type","text/plain").send("Unauthorized");return}y();});}for(let S of a)x.use(S);x.get(`${d}/`,v.handleDashboard),x.get(`${d}`,v.handleDashboard),x.get(`${d}/:repoName/_panel`,v.handlePanel),x.post(`${d}/:repoName/_bulk/delete`,v.handleBulkDelete),x.post(`${d}/:repoName/_bulk/update`,v.handleBulkUpdate),x.get(`${d}/:repoName`,v.handleList),x.get(`${d}/:repoName/create`,v.handleCreateForm),x.post(`${d}/:repoName/create`,v.handleCreateSubmit),x.get(`${d}/:repoName/:id/edit`,v.handleEditForm),x.post(`${d}/:repoName/:id/edit`,v.handleEditSubmit),x.get(`${d}/:repoName/:id/history`,v.handleHistory),x.post(`${d}/:repoName/:id/delete`,v.handleDelete);let A=async(S,g)=>{await x.handle(S,g);};return p&&(A.httpsOptions=p),A}function en(e,t,n=200){let r=xe(t);return e.json(r,n)}function Te(e,t,n,r=200){return en(e,{success:true,data:t,meta:n},r)}function F(e,t,n=400){return en(e,{success:false,error:t},n)}function Xt(e,t,n,r,o){let s=Ke(t,n),a=s.type==="index",p=a?424:500,b={success:false,error:a?s.message:o&&t instanceof Error?t.message:r};return a&&(b.errorType="index",s.indexUrl&&(b.indexUrl=s.indexUrl)),en(e,b,p)}var Yt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function nr(){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>=Yt.length*4||(e+=Yt.charAt(r%Yt.length));}}return e}function Ie(e){let t=e._def??e.def;if(!t)return e;let n=t.typeName??t.type;if(n==="ZodDate"||n==="date")return z$1.preprocess(r=>pn(r)??r,e);if(n==="ZodObject"||n==="object"){let r=e.shape,o={};for(let[s,a]of Object.entries(r))o[s]=Ie(a);return z$1.object(o)}if(n==="ZodArray"||n==="array"){let r=t.element??t.type;if(r)return z$1.array(Ie(r))}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(r)return Ie(r).optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(r)return Ie(r).nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType,o=t.defaultValue;if(r){let s=Ie(r);return typeof o=="function"?s.default(o()):s.default(o)}}return e}function Lo(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 p=a.split(".")[0];p&&r[p]&&(o[p]=r[p]);}return z$1.object(o)}function yt(e,t,n,r=false,o=[]){try{let s=Lo(e,n,o),a=r?s.partial():s;return {success:!0,data:(un()==="normalize"?Ie(a):a).parse(t)}}catch(s){return s instanceof z$1.ZodError?{success:false,error:`Validation failed: ${s.issues.map(p=>`${p.path.join(".")}: ${p.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}function Uo(e,t){let n=[],r=t?new Set(t):null,o={eq:"==",ne:"!=",lt:"<",lte:"<=",gt:">",gte:">=",in:"in",nin:"not-in",contains:"array-contains",containsAny:"array-contains-any"};for(let[s,a]of Object.entries(e)){if(a===void 0||["cursor","limit","pageSize","orderBy","orderDir","select"].includes(s))continue;let p=Array.isArray(a)?a[0]:a;if(p===void 0||p==="")continue;let d=s.match(/^(\w+)__(\w+)$/),b,v="==";if(d&&d[1]&&d[2]){b=d[1];let A=d[2];if(o[A])v=o[A];else continue}else if(!d)b=s;else continue;if(r&&!r.has(b))continue;let x=p;v==="in"||v==="not-in"||v==="array-contains-any"?x=p.split(",").map(A=>rr(A.trim())):x=rr(p),n.push({field:b,op:v,value:x});}return n}function rr(e){if(e==="true")return true;if(e==="false")return false;if(e==="null")return null;let t=Number(e);return !isNaN(t)&&e!==""?t:e}function mt(e){return e?{docId:e.id}:null}async function or(e,t){if(!t||typeof t!="object")return;let n=t.docId;if(typeof n=="string")try{let r=e.repo.ref;if(typeof r.doc!="function")return;let o=await r.doc(n).get();return o.exists?o:void 0}catch{return}}function sr(e,t,n){async function r(y,i,u,l){if(!i.rules)return true;let c=i.rules?.[u];if(!c)return F(y,`Operation "${u}" is not allowed for this repository`,403),false;try{return await c(l)?!0:F(y,"Forbidden",403)}catch(f){let h=n&&f instanceof Error?f.message:"Forbidden";return F(y,h,403)}}async function o(y,i,u,l){if(!y.rules)return l;let c=y.rules?.filter;if(!c)return l;let f=[];for(let h of l)try{await c({user:i,doc:h,params:u})&&f.push(h);}catch{}return f}function s(y){return y.get("user")??y.get("docsUser")??null}function a(y,i){if(!y){let u=i.req.path.split("/");for(let l of u)if(e[l]){y=l;break}}return !y||!e[y]?null:e[y]??null}function p(y,i){if(!i)return;let u=y[i];if(typeof u!="string"||!u)return;let l=u.split("/").filter(Boolean),c=[];for(let f=1;f<l.length;f+=2)c.push(l[f]);return c.length>0?c:void 0}async function d(y,i){let u=`by${y.documentKey.charAt(0).toUpperCase()}${y.documentKey.slice(1)}`,l=y.repo.get[u];if(typeof l=="function")try{let f=await l(i);if(f)return f}catch{}return (await y.repo.query.by({where:[[y.documentKey,"==",i]],limit:1}))[0]??null}async function b(y){let i=y.c,u=i.req.param(),l=a(u.repoName,i);if(!l)return F(i,"Repository not found",404);let c=s(i);if(!await r(i,l,"list",{user:c,query:i.req.query(),params:u}))return;let f=[],h;try{let w=i.req.query(),O=Math.min(Number(w.pageSize)||l.pageSize,100),T=w.cursor,R=w.direction?.toLowerCase()==="prev"?"prev":"next",C=w.orderBy,E=w.orderDir?.toLowerCase()==="desc"?"desc":"asc",$=w.select,P=$?$.split(",").map(U=>U.trim()):void 0,D;l.allowedIncludes&&w.includes&&(D=(typeof w.includes=="string"?w.includes.split(",").map(se=>se.trim()):Array.isArray(w.includes)?w.includes:[]).filter(se=>typeof se=="string"&&l.allowedIncludes.includes(se)),D?.length===0&&(D=void 0));let H=Uo(w,l.filterableFields);f=H.map(U=>({field:U.field,op:U.op,value:String(U.value??"")})),C&&(h={field:C,dir:E});let j={pageSize:O,direction:R};if(T)try{let U=typeof T=="string"?JSON.parse(T):T;j.cursor=await or(l,U);}catch{}if(C){if(l.orderableFields&&!l.orderableFields.includes(C))return F(i,`Field not orderable: ${C}`,400);j.orderBy=[{field:C,direction:E}];}H.length>0&&(j.where=H.map(U=>[U.field,U.op,U.value])),P&&(j.select=P),D&&(j.include=D);let I=await l.repo.query.paginate(j),ce={items:await o(l,s(i),u,I.data),hasNextPage:I.hasNextPage,hasPrevPage:I.hasPrevPage,nextCursor:mt(I.nextCursor),prevCursor:mt(I.prevCursor)};return Te(i,ce,{pageSize:O,hasMore:I.hasNextPage})}catch(w){Xt(i,w,{ref:l.repo.ref,path:l.path,isGroup:!!l.isGroup,filters:f,sort:h},"Failed to fetch documents",n);}}async function v(y){let i=y.c,u=i.req.param(),l=a(u.repoName,i);if(!l)return F(i,"Repository not found",404);let c=s(i);if(!await r(i,l,"list",{user:c,query:y.input||{},params:u}))return;let f=[],h;try{let w=y.input||{},O=Math.min(w.pageSize||l.pageSize,100),T=w.direction==="prev"?"prev":"next";w.where&&(f=w.where.map(P=>({field:String(P[0]),op:P[1],value:String(P[2]??"")}))),w.orderBy&&w.orderBy[0]&&(h={field:w.orderBy[0].field,dir:w.orderBy[0].direction==="desc"?"desc":"asc"});let R={pageSize:O,direction:T};if(w.cursor)try{let P=typeof w.cursor=="string"?JSON.parse(w.cursor):w.cursor;R.cursor=await or(l,P);}catch{}if(l.allowedIncludes&&w.includes&&w.includes.length>0){let P=w.includes.filter(D=>typeof D=="string"?l.allowedIncludes.includes(D):typeof D=="object"&&D!==null&&"relation"in D&&typeof D.relation=="string"?l.allowedIncludes.includes(D.relation):!1);P.length>0&&(R.include=P);}if(w.where&&w.where.length>0){if(l.filterableFields){let P=new Set(l.filterableFields),D=w.where.filter(H=>!P.has(H[0]));if(D.length>0){F(i,`Fields not filterable: ${D.map(H=>H[0]).join(", ")}`,400);return}}R.where=w.where;}if(w.orWhere&&w.orWhere.length>0){if(l.filterableFields){let P=new Set(l.filterableFields),D=w.orWhere.filter(H=>!P.has(H[0]));if(D.length>0){F(i,`Fields not filterable: ${D.map(H=>H[0]).join(", ")}`,400);return}}R.orWhere=w.orWhere;}if(w.orWhereGroups&&w.orWhereGroups.length>0){if(l.filterableFields){let P=new Set(l.filterableFields);for(let D of w.orWhereGroups){let H=D.filter(j=>!P.has(j[0]));if(H.length>0){F(i,`Fields not filterable: ${H.map(j=>j[0]).join(", ")}`,400);return}}}R.orWhereGroups=w.orWhereGroups;}if(w.orderBy&&w.orderBy.length>0){if(l.orderableFields){let P=new Set(l.orderableFields),D=w.orderBy.filter(H=>!P.has(H.field));if(D.length>0){F(i,`Fields not orderable: ${D.map(H=>H.field).join(", ")}`,400);return}}R.orderBy=w.orderBy;}w.select&&w.select.length>0&&(R.select=w.select);let C=await l.repo.query.paginate(R),$={items:await o(l,s(i),u,C.data),hasNextPage:C.hasNextPage,hasPrevPage:C.hasPrevPage,nextCursor:mt(C.nextCursor),prevCursor:mt(C.prevCursor)};return Te(i,$,{pageSize:O,hasMore:C.hasNextPage})}catch(w){Xt(i,w,{ref:l.repo.ref,path:l.path,isGroup:!!l.isGroup,filters:f,sort:h},"Failed to query documents",n);}}async function x(y){let i=y.c,u=i.req.param(),l=a(u.repoName,i);if(!l)return F(i,"Repository not found",404);let c=u.id;if(!c)return F(i,"Document ID required",400);try{let f=await d(l,c);if(!f)return F(i,"Document not found",404);let h=s(i);if(!await r(i,l,"get",{user:h,doc:f,params:u}))return;if(l.rules?.filter)try{if(!await l.rules.filter({user:h,doc:f,params:u}))return F(i,"Document not found",404)}catch{return F(i,"Document not found",404)}return Te(i,f)}catch(f){Xt(i,f,{ref:l.repo.ref,path:l.path,isGroup:!!l.isGroup,filters:[{field:l.documentKey,op:"==",value:c}]},"Failed to fetch document",n);}}async function A(y){let i=y.c,u=i.req.param(),l=a(u.repoName,i);if(!l)return F(i,"Repository not found",404);try{let c=y.input||{},f=s(i);if(!await r(i,l,"create",{user:f,body:c,params:u}))return;let h=yt(l.schema,c,l.createFields,!1,l.systemKeys);if(!h.success)return F(i,h.error,400);if(l.validate){let O=await l.validate(h.data,"create");if(O)return F(i,O,400)}let w;if(l.isGroup&&l.parentKeys&&l.parentKeys.length>0){let O={...h.data};l.createdKey&&(O[l.createdKey]=new Date);let T=l.parentKeys.filter(E=>!O[E]);if(T.length>0){F(i,`Missing parent key(s) for subcollection create: ${T.join(", ")}`,400);return}let R=l.parentKeys.map(E=>O[E]),C=O[l.documentKey]||nr();w=await l.repo.set(...R,C,O);}else w=await l.repo.create(h.data);return Te(i,w,void 0,201)}catch(c){let f=n&&c instanceof Error?c.message:"Failed to create document";return F(i,f,500)}}async function S(y,i){let u=y.c,l=u.req.param(),c=a(l.repoName,u);if(!c)return F(u,"Repository not found",404);let f=l.id;if(!f)return F(u,"Document ID required",400);try{let h=y.input||{},w=await d(c,f);if(!w)return F(u,"Document not found",404);let O=s(u);if(!await r(u,c,"update",{user:O,doc:w,body:h,params:l}))return;let T=yt(c.schema,h,c.mutableFields,i,c.systemKeys);if(!T.success)return F(u,T.error,400);if(c.validate){let E=await c.validate(T.data,"update");if(E)return F(u,E,400)}let R=p(w,c.pathKey)??[f],C=await c.repo.update(...R,T.data);return Te(u,C)}catch(h){let w=n&&h instanceof Error?h.message:"Failed to update document";return F(u,w,500)}}async function g(y){let i=y.c,u=i.req.param(),l=a(u.repoName,i);if(!l)return F(i,"Repository not found",404);if(!l.allowDelete)return F(i,"Delete not allowed for this repository",403);let c=u.id;if(!c)return F(i,"Document ID required",400);try{let f=await d(l,c);if(!f)return F(i,"Document not found",404);let h=s(i);if(!await r(i,l,"delete",{user:h,doc:f,params:u}))return;let w=p(f,l.pathKey)??[c];return await l.repo.delete(...w),Te(i,{deleted:!0})}catch(f){let h=n&&f instanceof Error?f.message:"Failed to delete document";return F(i,h,500)}}function k(y){return y.c.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization","Access-Control-Max-Age":"86400"})}async function m(y){let i=y.c,u=i.req.param(),l=a(u.repoName,i);if(!l)return F(i,"Repository not found",404);try{let c=y.input||{};if(!Array.isArray(c.operations))return F(i,"operations array is required",400);let f=s(i),h=l.repo.batch.create(),w=[];for(let O of c.operations){if(!O.type||!["create","update","delete"].includes(O.type))return F(i,"Invalid operation type",400);if(O.type==="create"){if(!await r(i,l,"create",{user:f,body:O.data,params:u}))return;let T=yt(l.schema,O.data,l.createFields,!1,l.systemKeys);if(!T.success)return F(i,T.error,400);let R=O.data[l.documentKey]||nr(),C={...T.data};if(l.createdKey&&(C[l.createdKey]=new Date),l.isGroup&&l.parentKeys){let E=l.parentKeys.map($=>C[$]);h.set(...E,R,C);}else h.set(R,C);w.push({op:"create",id:R});}else if(O.type==="update"){if(!O.id)return F(i,"id required for update",400);let T=await d(l,O.id);if(!T)return F(i,`Document ${O.id} not found`,404);if(!await r(i,l,"update",{user:f,doc:T,body:O.data,params:u}))return;let R=yt(l.schema,O.data,l.mutableFields,!0,l.systemKeys);if(!R.success)return F(i,R.error,400);let C=p(T,l.pathKey)??[O.id];h.update(...C,R.data),w.push({op:"update",id:O.id});}else if(O.type==="delete"){if(!l.allowDelete)return F(i,"Delete not allowed",403);if(!O.id)return F(i,"id required for delete",400);let T=await d(l,O.id);if(!T)return F(i,`Document ${O.id} not found`,404);if(!await r(i,l,"delete",{user:f,doc:T,params:u}))return;let R=p(T,l.pathKey)??[O.id];h.delete(...R),w.push({op:"delete",id:O.id});}}return await h.commit(),Te(i,{results:w})}catch(c){let f=n&&c instanceof Error?c.message:"Batch operation failed";return F(i,f,500)}}return {handleList:b,handleQuery:v,handleGet:x,handleCreate:A,handleUpdate:S,handleDelete:g,handleBatch:m,handleOptions:k}}function tn(e){try{return z$1.toJSONSchema(e,{target:"openapi-3.1",unrepresentable:"any",override:t=>{let n=t.zodSchema?._zod?.def;n&&(n.type==="date"?(t.jsonSchema.type="string",t.jsonSchema.format="date-time"):n.type==="bigint"&&(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 ne(e){return {$ref:`#/components/schemas/${e}`}}function V(e){return {description:e,content:{"application/json":{schema:ne("ErrorResponse")}}}}function De(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function ar(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"}},required:["items","hasNextPage","hasPrevPage"]},meta:{type:"object",properties:{pageSize:{type:"integer"},hasMore:{type:"boolean"},cursor:{oneOf:[{type:"string"},{type:"null"}]}}}},required:["success","data"]}}}}}function Ko(e){return [{name:"pageSize",in:"query",schema:{type:"integer",default:e.pageSize,maximum:100},description:"Number of items per page"},{name:"cursor",in:"query",schema:{type:"string"},description:"Base64 pagination cursor"},{name:"orderBy",in:"query",schema:{type:"string"},description:"Field name to order by"},{name:"orderDir",in:"query",schema:{type:"string",enum:["asc","desc"]},description:"Order direction"},{name:"select",in:"query",schema:{type:"string"},description:"Comma-separated list of fields to return"}]}function Vo(e){let t=e.filterableFields??Object.keys(e.schema.shape),n=["eq","ne","lt","lte","gt","gte","in","nin","contains"],r=[];for(let o of t){r.push({name:o,in:"query",schema:{type:"string"},description:`Filter by ${o} (equality)`});for(let s of n)r.push({name:`${o}__${s}`,in:"query",schema:{type:"string"},description:`Filter ${o} with operator ${s}`});}return r}function Wo(){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",maximum:100,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)"}}}}function Qo(e,t,n,r,o){let s={},a=e.name,p=`${t}/${e.name}`,d=`${p}/{${e.documentKey}}`,b={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};s[p]={get:{operationId:`list${fe(e.name)}`,summary:`List ${e.name} (paginated)`,tags:[a],parameters:[...Ko(e),...Vo(e)],responses:{200:ar(ne(n)),500:V("Internal server error")}},post:{operationId:`create${fe(e.name)}`,summary:`Create a ${ie(e.name)}`,tags:[a],requestBody:{required:true,content:{"application/json":{schema:ne(r??n)}}},responses:{201:De("Document created",ne(n)),400:V("Validation error"),500:V("Internal server error")}}},s[`${p}/query`]={post:{operationId:`query${fe(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[a],requestBody:{required:true,content:{"application/json":{schema:ne("QueryRequestBody")}}},responses:{200:ar(ne(n)),400:V("Invalid query"),500:V("Internal server error")}}},s[`${p}/batch`]={post:{operationId:`batch${fe(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[a],requestBody:{required:true,content:{"application/json":{schema:ne(`${n}BatchRequest`)}}},responses:{200:De("Batch operations completed",{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{op:{type:"string"},id:{type:"string"}}}}}}),400:V("Validation error"),403:V("Forbidden"),404:V("Document not found"),500:V("Internal server error")}}};let v={};return v.get={operationId:`get${fe(ie(e.name))}`,summary:`Get a single ${ie(e.name)}`,tags:[a],parameters:[b],responses:{200:De("Document found",ne(n)),404:V("Document not found"),500:V("Internal server error")}},v.put={operationId:`update${fe(ie(e.name))}`,summary:`Update a ${ie(e.name)} (full replace)`,tags:[a],parameters:[b],requestBody:{required:true,content:{"application/json":{schema:ne(o??n)}}},responses:{200:De("Document updated",ne(n)),400:V("Validation error"),404:V("Document not found"),500:V("Internal server error")}},v.patch={operationId:`patch${fe(ie(e.name))}`,summary:`Partially update a ${ie(e.name)}`,tags:[a],parameters:[b],requestBody:{required:true,content:{"application/json":{schema:{allOf:[ne(o??n)],description:"All fields are optional for partial updates"}}}},responses:{200:De("Document patched",ne(n)),400:V("Validation error"),404:V("Document not found"),500:V("Internal server error")}},e.allowDelete&&(v.delete={operationId:`delete${fe(ie(e.name))}`,summary:`Delete a ${ie(e.name)}`,tags:[a],parameters:[b],responses:{200:De("Document deleted",{type:"object",properties:{id:{type:"string"}}}),404:V("Document not found"),500:V("Internal server error")}}),s[d]=v,s}function rn(e,t,n={}){let{title:r="CRUD API",version:o="1.0.0",description:s,servers:a,auth:p=false}=n,d=t==="/"?"":t.replace(/\/$/,""),b={},v={},x=[];b.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string"}},required:["success","error"]},b.QueryRequestBody=Wo();for(let[k,m]of Object.entries(e)){let y=fe(ie(k)),i=`${y}Create`,u=`${y}Update`;b[y]=tn(m.schema);let l=T=>{let R=T&&T.length>0?T:Object.keys(m.schema.shape),C={};for(let E of R){let $=E.split(".")[0];$&&m.schema.shape[$]&&!m.systemKeys.includes($)&&(C[$]=m.schema.shape[$]);}return C},c=null,f=l(m.createFields);Object.keys(f).length>0&&(b[i]=tn(z$1.object(f)),c=i);let h=null,w=l(m.mutableFields);Object.keys(w).length>0&&(b[u]=tn(z$1.object(w)),h=u),b[`${y}BatchRequest`]={type:"object",properties:{operations:{type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",enum:["create"]},data:ne(c??y)},required:["type","data"]},{type:"object",properties:{type:{type:"string",enum:["update"]},id:{type:"string"},data:{allOf:[ne(h??y)],description:"Partial updates allowed"}},required:["type","id","data"]},...m.allowDelete?[{type:"object",properties:{type:{type:"string",enum:["delete"]},id:{type:"string"}},required:["type","id"]}]:[]]}}},required:["operations"]};let O=Qo(m,d,y,c,h);Object.assign(v,O),x.push({name:k,description:`Operations on ${k} (collection: ${m.path})`});}let A={},S;return p==="basic"?(A.basicAuth={type:"http",scheme:"basic"},S=[{basicAuth:[]}]):p==="bearer"&&(A.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},S=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:r,version:o,...s?{description:s}:{}},...a&&a.length>0?{servers:a}:{},paths:v,components:{schemas:b,...Object.keys(A).length>0?{securitySchemes:A}:{}},...S?{security:S}:{},tags:x}}function fe(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 _e=class extends Error{constructor(n,r){super("Request validation failed");this.zodError=n;this.source=r;this.statusCode=400;this.name="ValidationError";}};var et=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},tt=class extends Error{constructor(n){super("Output validation failed");this.zodError=n;this.statusCode=500;this.name="OutputValidationError";}};function ir(e){return e.issues.map(t=>({path:t.path.join("."),code:t.code,message:t.message}))}function cr(e,t){return t instanceof _e?e.json({success:false,error:"Validation failed",issues:ir(t.zodError)},400):t instanceof et?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof tt?e.json({success:false,error:"Output validation failed",issues:ir(t.zodError)},500):null}extendZodWithOpenApi(z$1);var lr="Successful response",dr="Error response";function es(e){return e==="get"?"query":"json"}function ts(e,t){let n=t?.output;return n?typeof n=="function"?n(e):n:e}function ns(e){if(typeof e.safeParse=="function")return {description:dr,schema:e};let t=e;return {description:t.description??dr,schema:t.schema}}function pr(e,t,n,r){let o=new OpenAPIRegistry;if(n.securitySchemes)for(let[p,d]of Object.entries(n.securitySchemes))o.registerComponent("securitySchemes",p,d);for(let p of e){let d=p.method,b=p.source??es(d),v=ss(t,p.path??"/"),x=p.status??200,A=rs(d,b,p.input),S=ur(b,p.input,"query"),g=ur(b,p.input,"param"),k=as(d,v),m=ts(p.output,r),y={[x]:m?{description:lr,content:{"application/json":{schema:m}}}:{description:lr}};if(r?.errors)for(let[i,u]of Object.entries(r.errors)){let{description:l,schema:c}=ns(u);y[i]=c?{description:l,content:{"application/json":{schema:c}}}:{description:l};}o.registerPath({method:d,path:os(v),operationId:k,summary:p.summary,description:p.description,tags:p.tags,deprecated:p.deprecated,security:p.security,request:{...S?{query:S}:{},...g?{params:g}:{},...A?{body:A}:{}},responses:y});}return new OpenApiGeneratorV31(o.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security})}function rs(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 ur(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function os(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function ss(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,o=`${n}${r}`;return o===""?"/":o}function as(e,t){let n=t.replace(/[{}]/g,"").replace(/\/+/g,"_").replace(/[^A-Za-z0-9_]/g,"").replace(/^_+|_+$/g,"");return `${e}_${n||"root"}`}function fr(e,t){let n=e.replace(/"/g,"&quot;");return `<!doctype html>
1141
+ `;function Ve(){return jsx("script",{dangerouslySetInnerHTML:{__html:Hn}})}Mt();function he(e){return "<!DOCTYPE html>"+renderToString(e)}var Ro=["corporate","silk","dark"],ko=()=>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:Ro.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))})]}),be=({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(ko,{})})]}),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,u)=>a.href?jsx("li",{children:jsx("a",{href:a.href,children:a.label})},u):jsx("li",{class:"text-base-content/60",children:a.label},u))})}),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(Ft,{basePath:s}),jsx(Ve,{})]})]})};function Ht(e,t){return he(jsx(be,{opts:t,children:jsx("div",{dangerouslySetInnerHTML:{__html:e}})}))}function Nt(e,t){return he(jsx(be,{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 qn=[{value:"==",label:"="},{value:"!=",label:"\u2260"},{value:"in",label:"in"},{value:"not-in",label:"not in"}],To=[{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"}],Ao=[{value:"array-contains",label:"contains"},{value:"array-contains-any",label:"contains any"}];function Co(e){switch(e){case "ZodNumber":case "ZodBigInt":case "ZodDate":return To;case "ZodBoolean":return qn;case "ZodArray":return Ao;default:return qn}}var we="__null__";function Oo(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="${we}"]');if(!o){o=document.createElement('option');o.value='${we}';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='${we}';i.readOnly=true;}i.style.opacity='0.55';}else{i.style.opacity='';if(i.tagName==='SELECT'){var o2=i.querySelector('option[value="${we}"][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!=='${we}')?i.dataset._prev:'';}}})(this)`}function Eo(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 Je({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:Oo(e)}),jsx("span",{children:"\u2205"})]})}function Po({col:e,active:t}){let n=t?.value??"",r=n===we,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 u=new Set(n.split(",").map(b=>b.trim()).filter(Boolean)),d=`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(b=>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:b,checked:u.has(b),"data-enum-group":d,onchange:Eo(o,d)}),jsx("span",{children:b})]},b))]})}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(u=>jsx("option",{value:u,selected:n===u,children:u},u)),e.nullable&&jsx("option",{value:we,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsx(Je,{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:we,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsx(Je,{inputId:o,active:r})]});if(e.zodType==="ZodArray"){let u=t?.op==="array-contains-any";return jsx("input",{id:o,type:"text",name:`fv_${e.name}`,value:n,placeholder:u?"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(Je,{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(Je,{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(Je,{inputId:o,active:r})]})}function zt({action:e,columnMeta:t,activeFilters:n,isGroup:r}){let o=Object.fromEntries(n.map(d=>[d.field,d])),s=n.length>0,a=n.length>=2||r&&s,u=t.filter(d=>d.zodType!=="ZodObject"&&d.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:u.map(d=>{let b=Co(d.zodType),v=o[d.name],x=v?.op??b[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:d.name}),jsxs("div",{class:"flex gap-1.5",children:[b.length>1?jsx("select",{name:`fo_${d.name}`,class:"select select-sm select-bordered w-20 shrink-0",children:b.map(A=>jsx("option",{value:A.value,selected:A.value===x,children:A.label},A.value))}):jsx("input",{type:"hidden",name:`fo_${d.name}`,value:b[0].value}),jsx(Po,{col:d,active:v})]})]},d.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 Bt(e,t,n,r,o,s){let a=n==="create"?`Create ${e}`:`Edit ${e} / ${r??""}`,u=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 he(jsx(be,{opts:{title:a,breadcrumb:u,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}})})})}))}ct();jt();function qt(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 Zn(e,t,n,r,o){let s=qt(e,r,o);return s.set("cursor",t),s.set("dir",n),`?${s.toString()}`}function $o(e,t,n,r){let o=qt(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 Io(e,t,n){return `?${qt(t,n,e).toString()}`}function Zt(e,t,n,r,o,s,a=[],u=[],d=false,b=[],v,x,A,S,m,k,y,g=false){let i=`${r}/${e}`,p=`${i}/create`,l={};if(y)for(let R of n)l[R]=We(Qe(y,R));let c=(k??[]).filter(R=>true),f=c.length>0,h=d,w=h||f,O=c.map(R=>{let C=Qe(y,R),E=We(C),$=a.find(P=>P.name===R);return {name:R,type:E,enumValues:$?.enumValues??null,nullable:$?.nullable??false}}),T=[];return y&&(T=re(y).filter(C=>c.includes(C.name))),he(jsxs(be,{opts:{title:e,breadcrumb:[{label:"Repositories",href:r},{label:e}],basePath:r,flash:s},children:[a.length>0&&jsx(zt,{action:i,columnMeta:a,activeFilters:u,isGroup:S}),A&&jsxs("div",{role:"alert",class:`alert ${A.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:A.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:A.type==="index"?"Composite index required":"Query failed"}),jsx("div",{class:"text-sm",children:A.message})]}),A.indexUrl&&jsx("a",{href:A.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 m=="number"&&jsxs(Fragment,{children:[" ","of"," ",jsx("span",{class:"font-semibold text-base-content/80",children:m})]})," ","document",(typeof m=="number"?m: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:Io(R,u,v),class:`join-item btn btn-xs ${x===R?"btn-active btn-primary":"btn-outline"}`,children:R},R))})]})]}),jsx("a",{href:p,class:"btn btn-primary btn-sm",children:"+ New"})]}),w&&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 m=="number"?String(m):"","data-frs-page-size":String(x??t.length),"data-frs-allow-delete":h?"1":"0","data-frs-allow-update":f?"1":"0","data-frs-fields":JSON.stringify(O),"data-frs-filters":JSON.stringify(u),children:[jsxs("div",{class:"flex-1 text-sm",children:[jsx("span",{"data-frs-bulk-summary":true,children:"0 selected"}),typeof m=="number"&&m>t.length&&jsxs("button",{type:"button",class:"ml-3 link text-sm hidden","data-frs-bulk-select-all":true,children:["Select all ",m," matching documents"]}),jsxs("span",{class:"hidden ml-3 italic","data-frs-bulk-all-active":true,children:["All ",m??"?"," 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:[f&&jsx("button",{type:"button",class:"btn btn-sm btn-outline","data-frs-bulk-action":"update",children:"Update field\u2026"}),h&&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:[w&&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,C)=>{let E=v?.field===R,$=E?v.dir==="asc"?" \u25B2":" \u25BC":"";return jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:jsxs("a",{href:$o(R,v,u,x),class:`hover:text-base-content inline-flex items-center gap-0.5${E?" text-primary font-bold":""}`,children:[R,$]})},C)}),b.map((R,C)=>jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:R.column},`rel-${C}`)),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+b.length+1+(w?1:0),class:"text-center py-16 text-base-content/40",children:"No documents found"})}):t.map((R,C)=>{let E=String(R.docId??R.id??""),$=`${r}/${e}/${encodeURIComponent(E)}/edit`,P=`${r}/${e}/${encodeURIComponent(E)}/delete`;return jsxs("tr",{class:"hover","data-frs-row-id":E,children:[w&&jsx("td",{class:"align-middle py-2",children:jsx("input",{type:"checkbox",class:"checkbox checkbox-xs checkbox-primary","data-frs-select-row":true,value:E,"aria-label":`Select ${E}`})}),n.map((D,H)=>{let j=R[D],I=l[D],K=I?Ge(I,j):null;return jsx("td",{class:"align-top py-2",children:jsx(Pe,{val:j,mismatch:K})},H)}),b.map((D,H)=>{let j=R[D.key];if(j==null||j==="")return jsx("td",{class:"py-2"},`rel-${H}`);let I=D.type==="one"?`${r}/${D.targetRepo}/${encodeURIComponent(String(j))}/edit`:`${r}/${D.targetRepo}?fv_${D.targetKey}=${encodeURIComponent(String(j))}`;return jsx("td",{class:"align-middle py-2",children:jsx("a",{href:I,class:"btn btn-xs btn-ghost btn-outline","data-frs-relation":true,"data-frs-rel-type":D.type,"data-frs-rel-repo":D.targetRepo,"data-frs-rel-fk":D.targetKey,"data-frs-rel-val":String(j),"data-frs-rel-label":D.column,children:D.column})},`rel-${H}`)}),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"}),g&&jsx("a",{href:`${r}/${e}/${encodeURIComponent(E)}/history`,class:"btn btn-xs btn-outline",title:"View change history",children:"History"}),d&&jsx("form",{method:"post",action:P,onsubmit:"return confirm('Delete this document?')",children:jsx("button",{type:"submit",class:"btn btn-xs btn-error btn-outline",children:"Delete"})})]})})]},C)})})]})}),(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:Zn(u,o.prevCursor,"prev",v,x),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:Zn(u,o.nextCursor,"next",v,x),class:"btn btn-sm btn-outline",children:"Next \u2192"}):jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"Next \u2192"})]}),typeof m=="number"&&jsxs("div",{class:"text-xs text-base-content/50",children:[m," total document",m!==1?"s":"",u.length>0?" matching filters":""]})]}),w&&f&&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"}),c.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:T.map(R=>jsx("div",{"data-frs-bulk-template-for":R.name,dangerouslySetInnerHTML:{__html:Ue(R)}},R.name))})]}))}var _o="";function Xe(e,t){return Ht(e,t)}function Lt(e,t){return Nt(e,t)}function Ut(e,t,n,r,o,s,a,u,d,b,v,x,A,S,m,k,y,g){return Zt(e,t,n,r,o,s,a,u,d,b,v,x,A,S,m,k,y,g)}function ve(e,t,n,r,o,s){return Bt(e,t,n,r,o,s)}var Kt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Mo(){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>=Kt.length*4||(e+=Kt.charAt(r%Kt.length));}}return e}function dt(e,t){if(!t)return;let n=e[t];if(typeof n!="string"||!n)return;let r=n.split("/").filter(Boolean),o=[];for(let s=1;s<r.length;s+=2)o.push(r[s]);return o.length>0?o:void 0}async function $e(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 Vt(e,t,n){let r=e.documentKey??"docId",o=Ke(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 z(e,t,n=200){e.status(n).set("Content-Type","text/html; charset=utf-8").send(t);}function Wt(e,t){e.status(302).set("Location",t).send("");}function ut(e,t){let n=t.shape,r={};for(let[o,s]of Object.entries(n)){let a=Gt(s),u=q(a),d=u==="ZodObject",b=a,v=false;if(u==="ZodUnion"){let S=qe(a);S.some(k=>q(k)==="ZodDate")&&(v=true);let m=S.find(k=>{if(q(k)==="ZodObject"){let y=Y(k);return "latitude"in y&&"longitude"in y}return false});m&&(d=true,b=m);}if(e[o+"__isnull"]==="1"){r[o]=null;continue}if(d){let S={},m=false;for(let[g,i]of Object.entries(e))g.startsWith(`${o}.`)&&(S[g.slice(o.length+1)]=i,m=true);if(m){r[o]=ut(S,b);continue}let k=e[o],y=Array.isArray(k)?k[k.length-1]:k;if(y)try{r[o]=JSON.parse(y);}catch{r[o]=y;}continue}let x=e[o],A=Array.isArray(x)?x[x.length-1]:x;if(A===void 0||A===""){u==="ZodBoolean"&&(r[o]=false);continue}if(v){r[o]=new Date(A);continue}switch(u){case "ZodBoolean":A==="__null__"?r[o]=null:r[o]=A==="true"||A==="on"||A==="1";break;case "ZodNumber":case "ZodBigInt":r[o]=Number(A);break;case "ZodDate":r[o]=new Date(A);break;case "ZodArray":try{r[o]=JSON.parse(A);}catch{r[o]=A;}break;default:if(A.startsWith("{")||A.startsWith("["))try{r[o]=JSON.parse(A);break}catch{}r[o]=A;}}return r}function Ln(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 Kn(e){let t=e;for(;;){let n=q(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=X(t);else if(n==="ZodEffects"||n==="ZodPipe"||n==="ZodTransform"){let r=He(t);if(!r)return n;t=r;}else return n}}function Gt(e){let t=e;for(;;){let n=q(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=X(t);else if(n==="ZodEffects"||n==="ZodPipe"||n==="ZodTransform"){let r=He(t);if(!r)return t;t=r;}else return t}}function Vn(e){let t=e;for(;;){let n=q(t);if(n==="ZodOptional"||n==="ZodNullable")return true;if(n==="ZodDefault"){t=X(t);continue}return false}}function Wn(e){let t=Gt(e),n=q(t);if(n==="ZodEnum"){let r=Ne(t);return r.length>0?r:void 0}if(n==="ZodNativeEnum"){let r=ze(t),o=Object.values(r).filter(s=>typeof s=="string");return o.length>0?o:void 0}if(n==="ZodLiteral"){let r=Be(t);return typeof r=="string"?[r]:void 0}}function Qn(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 u=Gt(t.shape[o]),d=q(u),b=d==="ZodObject",v=u,x=false;if(d==="ZodUnion"){let A=qe(u);A.some(m=>q(m)==="ZodDate")&&(x=true);let S=A.find(m=>{if(q(m)==="ZodObject"){let k=Y(m);return "latitude"in k&&"longitude"in k}return false});S&&(b=true,v=S);}if(b&&typeof a=="object"&&a!==null&&!Array.isArray(a)&&!("_seconds"in a)&&typeof a.toDate!="function"){let A=Qn(a,v,s);Object.assign(r,A);}else if(d==="ZodDate"||x){let A=Ln(a);A!==null&&(r[s]=A);}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)&&("_seconds"in a||typeof a.toDate=="function")){let A=Ln(a);r[s]=A??JSON.stringify(a,null,2);}else typeof a=="object"?r[s]=JSON.stringify(a,null,2):r[s]=String(a);}return r}function Qt(e,t){return e.map(n=>({...n,defaultValue:t[n.name]??n.defaultValue,nested:n.nested?Qt(n.nested,t):void 0}))}function Ho(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 u=(s??"").trim();if(!u)continue;let d=e[`fo_${a}`]??"==",b=n.has(d)?d:"==";r.push({field:a,op:b,value:u});}return r}function Un(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 Gn(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 u=Kn(a);if(u==="ZodObject"){let d=a;for(;;){let v=q(d);if(v==="ZodOptional"||v==="ZodNullable"||v==="ZodDefault")d=X(d);else break}let b=Y(d);r.push(...Gn(Object.keys(b),d,s));}else r.push({name:s,zodType:u,nullable:Vn(a),enumValues:Wn(a)});}return r}function No(e,t){let n=t.split("."),r=e;for(let o of n){for(;;){let a=q(r);if(a==="ZodOptional"||a==="ZodNullable"||a==="ZodDefault")r=X(r);else break}let s=Y(r);if(!(o in s))return null;r=s[o];}return r}function ke(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 u=s.slice(0,a),d=s.slice(a+1);r.has(u)||r.set(u,[]),r.get(u).push(d);}}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 u=e.shape[s];for(;;){let d=q(u);if(d==="ZodOptional"||d==="ZodNullable"||d==="ZodDefault")u=X(u);else break}if(q(u)!=="ZodObject"){o[s]=e.shape[s];continue}o[s]=ke(u,a);}return z$1.object(o)}function pe(e,t,n){return ae(e,t,n)}function Jn(e,t,n){let r=(i,p)=>{let l=pe(i,t,n),c=Object.values(e).map(f=>({name:f.name,path:f.path}));z(p,Lt(c,l));},o=async(i,p)=>{let l=i.params.repoName;if(!l){z(p,"Bad request",400);return}let c=e[l];if(!c){z(p,"Repository not found",404);return}let f=c.pageSize??25,h=i.query??{},w=h.cursor,O=h.dir==="prev"?"prev":"next",T=h.ob??"",R=h.od==="desc"?"desc":"asc",C=T?{field:T,dir:R}:void 0,E=parseInt(h.ps??""),$=Number.isFinite(E)&&E>0?Math.min(E,200):f,P=c.listColumns??Object.keys(c.schema.shape),D=c.documentKey??"docId",H=[D,...P.filter(Q=>Q!==D)];C&&(new Set([D,...P]).has(C.field)||(C=void 0));let j=c.filterableFields?(()=>{let Q=[];for(let le of c.filterableFields)(le.includes(".")||P.includes(le))&&Q.push(le);return Q})():P,I=(()=>{let Q=[];for(let le of j)if(le.includes(".")){let Ce=No(c.schema,le);Q.push({name:le,zodType:Ce?Kn(Ce):"ZodString",nullable:Ce?Vn(Ce):false,enumValues:Ce?Wn(Ce):void 0});}else Q.push(...Gn([le],c.schema));return Q})(),K=new Set(I.map(Q=>Q.name)),ce=Ho(h,K),U=Un(ce),se;if(w)try{let Q=c.repo.ref;typeof Q.doc=="function"&&(se=await Q.doc(w).get());}catch{}let[J,nt]=await Promise.all([c.repo.query.paginate({pageSize:$,cursor:se,direction:O,...U.length>0?{where:U}:{},...C?{orderBy:[{field:C.field,direction:C.dir}]}:{}}).catch(Q=>({queryError:Ke(Q,{ref:c.repo.ref,path:c.path,isGroup:!!c.isGroup,filters:ce,sort:C})})),c.repo.aggregate.count(U.length>0?{where:U}:{}).catch(()=>{})]),Ae="queryError"in J,vr=Ae?[]:J.data,xr=Ae?"":J.nextCursor?.id??"",Sr=Ae?"":J.prevCursor?.id??"",Rr=Ae?J.queryError:void 0,kr=pe(i,t,n);z(p,Ut(c.name,vr,H,kr,{hasPrev:Ae?false:J.hasPrevPage,hasNext:Ae?false:J.hasNextPage,prevCursor:Sr,nextCursor:xr},void 0,I,ce,c.allowDelete??false,c.relationalMeta,C,$,Rr,c.isGroup,nt,c.mutableFields,c.schema,c.historyEnabled));},s=(i,p)=>{let l=i.params.repoName;if(!l){z(p,"Bad request",400);return}let c=e[l];if(!c){z(p,"Repository not found",404);return}let f=pe(i,t,n),h=ke(c.schema,c.createFields),w=re(h),O=`${f}/${c.name}/create`,T=ge(w,O,"POST","Create document");z(p,ve(c.name,T,"create",null,f));},a=async(i,p)=>{let l=i.params.repoName;if(!l){z(p,"Bad request",400);return}let c=e[l];if(!c){z(p,"Repository not found",404);return}let f=pe(i,t,n),h=i.body??{},w=ut(h,c.schema),O=ke(c.schema,c.createFields),T=O.safeParse(w);if(!T.success){let R=re(O),C=`${f}/${c.name}/create`,E=ge(R,C,"POST","Create document"),$=T.error.issues.map(P=>`${P.path.join(".")}: ${P.message}`).join(", ");z(p,ve(c.name,E,"create",null,f,{type:"error",message:`Validation error: ${$}`}),422);return}try{if(c.isGroup&&c.parentKeys&&c.parentKeys.length>0){let R={...T.data};c.createdKey&&(R[c.createdKey]=new Date);let C=c.parentKeys.filter(D=>!R[D]);if(C.length>0)throw new Error(`Missing parent key(s) for subcollection create: ${C.join(", ")}`);let E=c.parentKeys.map(D=>R[D]),$=c.documentKey??"docId",P=R[$]||Mo();await c.repo.set(...E,P,R);}else await c.repo.create(T.data);Wt(p,`${f}/${c.name}?flash=created`);}catch(R){let C=ke(c.schema,c.createFields),E=re(C),$=`${f}/${c.name}/create`,P=ge(E,$,"POST","Create document");z(p,ve(c.name,P,"create",null,f,{type:"error",message:`Save error: ${R.message}`}),500);}},u=async(i,p)=>{let l=i.params.repoName,c=i.params.id;if(!l||!c){z(p,"Bad request",400);return}let f=e[l];if(!f){z(p,"Repository not found",404);return}let h=pe(i,t,n),w=null;try{w=await $e(f,c);}catch($){let P=Vt(f,c,$),D=Se($)?424:500;z(p,Xe("",{title:`Edit ${f.name} / ${c}`,basePath:h,breadcrumb:[{label:"Repositories",href:h},{label:f.name,href:`${h}/${f.name}`},{label:`Edit ${c}`}],flash:P}),D);return}if(!w){z(p,"Document not found",404);return}let O=Qn(w,f.schema),T=ke(f.schema,f.mutableFields),R=Qt(re(T),O),C=`${h}/${f.name}/${encodeURIComponent(c)}/edit`,E=ge(R,C,"POST","Save changes");z(p,ve(f.name,E,"edit",c,h));},d=async(i,p)=>{let l=i.params.repoName,c=i.params.id;if(!l||!c){z(p,"Bad request",400);return}let f=e[l];if(!f){z(p,"Repository not found",404);return}let h=pe(i,t,n),w=i.body??{},O=ut(w,f.schema),T=ke(f.schema,f.mutableFields),C=T.partial().safeParse(O);if(!C.success){let E=Object.fromEntries(Object.entries(w).map(([j,I])=>[j,Array.isArray(I)?I.join(","):I??""])),$=Qt(re(T),E),P=`${h}/${f.name}/${encodeURIComponent(c)}/edit`,D=ge($,P,"POST","Save changes"),H=C.error.issues.map(j=>`${j.path.join(".")}: ${j.message}`).join(", ");z(p,ve(f.name,D,"edit",c,h,{type:"error",message:`Validation error: ${H}`}),422);return}try{let E=await $e(f,c),$=(E&&dt(E,f.pathKey))??[c];await f.repo.update(...$,C.data),Wt(p,`${h}/${f.name}?flash=updated`);}catch(E){let $=ke(f.schema,f.mutableFields),P=re($),D=`${h}/${f.name}/${encodeURIComponent(c)}/edit`,H=ge(P,D,"POST","Save changes"),j=Se(E)?Vt(f,c,E):{type:"error",message:`Save error: ${E.message}`},I=Se(E)?424:500;z(p,ve(f.name,H,"edit",c,h,j),I);}},b=async(i,p)=>{let l=i.params.repoName,c=i.params.id;if(!l||!c){z(p,"Bad request",400);return}let f=e[l];if(!f){z(p,"Repository not found",404);return}if(!f.allowDelete){z(p,"Delete is not allowed for this repository",403);return}let h=pe(i,t,n);try{let w=await $e(f,c),O=(w&&dt(w,f.pathKey))??[c];await f.repo.delete(...O),Wt(p,`${h}/${f.name}?flash=deleted`);}catch(w){let O=Se(w)?Vt(f,c,w):{type:"error",message:`Delete error: ${w.message}`},T=Se(w)?424:500;z(p,Xe("",{title:`Delete ${f.name} / ${c}`,basePath:h,breadcrumb:[{label:"Repositories",href:h},{label:f.name,href:`${h}/${f.name}`},{label:`Delete ${c}`}],flash:O}),T);}},v=async(i,p)=>{let l=i.params.repoName;if(!l){z(p,"Bad request",400);return}let c=e[l];if(!c){z(p,"Repository not found",404);return}let f=pe(i,t,n),h=i.query,w=h?.type==="many"?"many":"one",O=Math.max(1,Math.min(100,Number(h?.ps??25)||25)),T=c.listColumns??Object.keys(Y(c.schema)),{PanelOne:R,PanelMany:C}=await Promise.resolve().then(()=>(Mt(),zn)),{renderToString:E}=await import('hono/jsx/dom/server');if(w==="one"){let I=String(h?.id??"");if(!I){z(p,"<div class='p-6 text-error'>Missing id parameter.</div>",400);return}try{let K=await $e(c,I),ce=E(R({doc:K,repoName:c.name,basePath:f,schema:c.schema,columns:T}));z(p,ce);}catch(K){z(p,`<div class='p-6 text-error text-sm'>Error: ${K.message}</div>`,500);}return}let $=String(h?.fk??""),P=String(h?.fv??"");if(!$||!P){z(p,"<div class='p-6 text-error'>Missing fk/fv parameters.</div>",400);return}let D=h?.cursor??"",H=h?.dir==="prev"?"prev":"next",j;if(D)try{let I=c.repo.ref;typeof I.doc=="function"&&(j=await I.doc(D).get());}catch{}try{let I=await c.repo.query.paginate({pageSize:O,cursor:j,direction:H,where:[[$,"==",zo(P)]]}),K=E(C({docs:I.data,repoName:c.name,basePath:f,fk:$,fv:P,columns:T,schema:c.schema,pagination:{hasPrev:I.hasPrevPage,hasNext:I.hasNextPage,prevCursor:I.prevCursor?.id??"",nextCursor:I.nextCursor?.id??"",pageSize:O}}));z(p,K);}catch(I){z(p,`<div class='p-6 text-error text-sm'>Error: ${I.message}</div>`,500);}},x=async(i,p)=>{let l=[];for(let c of p){let f;if(i.isGroup||i.parentKeys?.length){let h=await $e(i,c);f=h?dt(h,i.pathKey):void 0;}f||(f=[c]);try{let h=i.repo.documentRef(...f);h&&l.push(h);}catch{}}return l},A=async(i,p)=>{let l=Un(p),c=i.documentKey??"docId",f=[],h;for(;;){let w=await i.repo.query.paginate({pageSize:500,cursor:h,direction:"next",...l.length>0?{where:l}:{}});for(let O of w.data){let T=String(O[c]??O.id??"");T&&f.push(T);}if(!w.hasNextPage||!w.nextCursor)break;h=w.nextCursor;}return f},S=async(i,p)=>{let l=i.params.repoName;if(!l){te(p,{error:"Bad request"},400);return}let c=e[l];if(!c){te(p,{error:"Repository not found"},404);return}if(!c.allowDelete){te(p,{error:"Delete is not allowed for this repository"},403);return}let f=i.body??{};try{let h=await k(c,f);if(h.length===0){te(p,{deleted:0});return}let w=await x(c,h);for(let O=0;O<w.length;O+=500)await c.repo.bulk.delete(w.slice(O,O+500));te(p,{deleted:w.length});}catch(h){te(p,{error:h.message},500);}},m=async(i,p)=>{let l=i.params.repoName;if(!l){te(p,{error:"Bad request"},400);return}let c=e[l];if(!c){te(p,{error:"Repository not found"},404);return}let f=i.body??{},h=String(f.field??"");if(!h){te(p,{error:"Missing 'field'"},400);return}if(!c.mutableFields||!c.mutableFields.includes(h)){te(p,{error:`Field '${h}' is not bulk-updatable`},403);return}let w=c.schema.shape?.[h],O;if(w){let T=typeof c.schema=="object"&&c.schema&&"constructor"in c.schema&&c.schema.constructor.name.includes("Zod")?c.schema.pick({[h]:true}):void 0;if(!T){te(p,{error:"Invalid schema structure"},500);return}O=ut(f.formPayload??{},T)[h];let C=w.safeParse(O);if(!C.success){te(p,{error:`Invalid value for '${h}': ${C.error.message}`},400);return}O=C.data;}try{let T=await k(c,f);if(T.length===0){te(p,{updated:0});return}let C=(await x(c,T)).map(E=>({docRef:E,data:{[h]:O}}));for(let E=0;E<C.length;E+=500)await c.repo.bulk.update(C.slice(E,E+500));te(p,{updated:C.length});}catch(T){te(p,{error:T.message},500);}};async function k(i,p){if(p.selectAll){let l=y(p.filters,i);return await A(i,l)}return Array.isArray(p.ids)?p.ids.filter(l=>typeof l=="string"&&!!l):[]}function y(i,p){if(!Array.isArray(i))return [];let l=new Set((p.filterableFields??Object.keys(Y(p.schema))).map(h=>String(h))),c=new Set(["==","!=","<","<=",">",">=","in","not-in","array-contains","array-contains-any"]),f=[];for(let h of i)h&&typeof h=="object"&&typeof h.field=="string"&&l.has(h.field)&&typeof h.value=="string"&&c.has(String(h.op))&&f.push({field:h.field,op:h.op,value:h.value});return f}return {handleDashboard:r,handleList:o,handleCreateForm:s,handleCreateSubmit:a,handleEditForm:u,handleEditSubmit:d,handleDelete:b,handlePanel:v,handleBulkDelete:S,handleBulkUpdate:m,handleHistory:async(i,p)=>{let l=i.params.repoName,c=i.params.id;if(!l||!c){z(p,"Bad request",400);return}let f=e[l];if(!f){z(p,"Repository not found",404);return}if(!f.historyEnabled||!f.repo.history){z(p,"History not enabled for this repository",404);return}let h=pe(i,t,n),w=f.historySubcollection??"history",O=[c];try{let I=await $e(f,c),K=I?dt(I,f.pathKey):void 0;K&&K.length>0&&(O=K);}catch{}let T=parseInt(String(i.query?.limit??"")),R=Number.isFinite(T)&&T>0?Math.min(T,500):100,C=[],E;try{C=await f.repo.history.list(...O,{limit:R});}catch(I){E=I.message;}let $=I=>String(I??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),P=I=>{if(I===void 0)return '<span class="opacity-40">undefined</span>';if(I===null)return '<span class="opacity-40">null</span>';if(typeof I=="object")try{return `<code class="text-xs">${$(JSON.stringify(I))}</code>`}catch{return $(String(I))}return $(String(I))},D=I=>I?typeof I.toDate=="function"?I.toDate().toISOString():I instanceof Date?I.toISOString():$(String(I)):"",H=I=>`<span class="badge badge-sm ${I==="create"?"badge-success":I==="delete"?"badge-error":"badge-info"}">${$(I)}</span>`,j="";if(j+='<div class="flex items-center justify-between mb-4">',j+=`<a href="${h}/${f.name}/${encodeURIComponent(c)}/edit" class="btn btn-sm btn-outline">\u2190 Back to edit</a>`,j+=`<a href="${h}/${f.name}" class="btn btn-sm btn-outline">\u2190 Back to list</a>`,j+="</div>",j+=`<p class="text-sm text-base-content/60 mb-4">Subcollection: <code>${$(w)}</code> \xB7 Showing up to ${R} entries.</p>`,E)j+=`<div class="alert alert-error mb-4">${$(E)}</div>`;else if(C.length===0)j+='<div class="alert">No history entries found.</div>';else {j+='<div class="overflow-x-auto"><table class="table table-zebra table-sm">',j+="<thead><tr><th>When</th><th>Op</th><th>User</th><th>Reason / Comment</th><th>Changes</th></tr></thead><tbody>";for(let I of C){let K=I.meta??{},ce=[K.reason,K.comment].filter(J=>J!=null&&J!=="").map(J=>$(String(J))).join(" \u2014 "),U="",se=Object.keys(I.changes??{});se.length===0?U='<span class="opacity-40">\u2014</span>':U='<ul class="space-y-1">'+se.map(J=>{let nt=I.changes[J];return `<li><strong>${$(J)}</strong>: ${P(nt.oldValue)} \u2192 ${P(nt.newValue)}</li>`}).join("")+"</ul>",j+="<tr>",j+=`<td class="whitespace-nowrap text-xs font-mono">${$(D(I.historySetAt))}</td>`,j+=`<td>${H(I.operation??"update")}</td>`,j+=`<td class="text-xs">${$(K.userEmail??K.userId??"")}</td>`,j+=`<td class="text-xs">${ce}</td>`,j+=`<td>${U}</td>`,j+="</tr>";}j+="</tbody></table></div>";}z(p,Xe(j,{title:`History \u2014 ${f.name} / ${c}`,basePath:h,breadcrumb:[{label:"Repositories",href:h},{label:f.name,href:`${h}/${f.name}`},{label:`History ${c}`}]}));}}}function te(e,t,n=200){e.status(n).set("Content-Type","application/json; charset=utf-8").send(JSON.stringify(t));}function zo(e){return e==="true"?true:e==="false"?false:e!==""&&!isNaN(Number(e))?Number(e):e}ft();async function Bo(e){return typeof e.rawBody=="string"?e.rawBody:Buffer.isBuffer(e.rawBody)?e.rawBody.toString("utf8"):""}function qo(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 tr(e){let{basePath:t="/",repos:n,parseBody:r=true,securityHeaders:o,auth:s,middleware:a=[],httpsOptions:u}=e,d=t==="/"?"":t.replace(/\/$/,""),b={};for(let[S,m]of Object.entries(n)){if(!m.repo)throw new Error(`[createAdminServer] Repository "${S}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let k=m.schema??m.repo.schema??null;if(!k)throw new Error(`[createAdminServer] Repository "${S}" has no Zod schema. Either use createRepositoryConfig(schema)(config) or pass schema: explicitly.`);let y,g,i;if(m.fieldsConfig){let c=m.fieldsConfig;y=[],g=[],i=[];for(let[f,h]of Object.entries(c))for(let w of h)w==="filterable"?y.push(f):w==="mutable"?g.push(f):w==="create"&&i.push(f);y.length===0&&(y=void 0),g.length===0&&(g=void 0),i.length===0&&(i=void 0);}let p=(()=>{let c=m.repo._parentKeys;return c&&c.length>0?c:void 0})();if(p&&i)for(let c of p)i.includes(c)||i.push(c);let l={name:S,path:m.path,repo:m.repo,schema:k,documentKey:m.documentKey??"docId",pathKey:m.repo._pathKey??void 0,isGroup:!!m.repo._isGroup,parentKeys:p,createdKey:m.repo._createdKey??void 0,listColumns:m.listColumns,pageSize:m.pageSize,filterableFields:y,mutableFields:g,createFields:i,allowDelete:m.allowDelete??false,historyEnabled:!!m.repo._historyConfig?.enabled,historySubcollection:(m.repo._historyConfig?.enabled&&m.repo._historySubcollection)??void 0,relationalMeta:(()=>{if(!m.relationalFields||m.relationalFields.length===0)return;let c=m.repo.relationalKeys??{},f=[];for(let h of m.relationalFields){let w=c[h.key];w&&f.push({key:w.sourceKey?String(w.sourceKey):h.key,column:h.column,targetRepo:String(w.repo),targetKey:String(w.key),type:w.type});}return f.length>0?f:void 0})()};b[S]=l;}let v=Jn(b,d,yn(u?.region)),x=new ye;if(o!==false&&x.use(pt(o===void 0?{}:o)),r&&x.use(async(S,m,k)=>{let y=S,g=String(y.headers?.["content-type"]??"");if(g.includes("application/x-www-form-urlencoded")){let i=await Bo(y);S.body=qo(i);}else if(g.includes("application/json")&&typeof y.body=="string")try{S.body=JSON.parse(y.body);}catch{}await k();}),s)if(Me(s)){for(let S of s.routes){let m=`${d}${S.path}`;S.method==="GET"?x.get(m,S.handler):x.post(m,S.handler);}x.use(s.middleware);}else if(typeof s=="function")x.use(s);else {let S=s.realm??"Admin",m="Basic "+Buffer.from(`${s.username}:${s.password}`).toString("base64");x.use((k,y,g)=>{if((k.headers?.authorization??"")!==m){y.status(401).set("WWW-Authenticate",`Basic realm="${S}"`).set("Content-Type","text/plain").send("Unauthorized");return}g();});}for(let S of a)x.use(S);x.get(`${d}/`,v.handleDashboard),x.get(`${d}`,v.handleDashboard),x.get(`${d}/:repoName/_panel`,v.handlePanel),x.post(`${d}/:repoName/_bulk/delete`,v.handleBulkDelete),x.post(`${d}/:repoName/_bulk/update`,v.handleBulkUpdate),x.get(`${d}/:repoName`,v.handleList),x.get(`${d}/:repoName/create`,v.handleCreateForm),x.post(`${d}/:repoName/create`,v.handleCreateSubmit),x.get(`${d}/:repoName/:id/edit`,v.handleEditForm),x.post(`${d}/:repoName/:id/edit`,v.handleEditSubmit),x.get(`${d}/:repoName/:id/history`,v.handleHistory),x.post(`${d}/:repoName/:id/delete`,v.handleDelete);let A=async(S,m)=>{await x.handle(S,m);};return u&&(A.httpsOptions=u),A}function en(e,t,n=200){let r=xe(t);return e.json(r,n)}function Te(e,t,n,r=200){return en(e,{success:true,data:t,meta:n},r)}function F(e,t,n=400){return en(e,{success:false,error:t},n)}function Xt(e,t,n,r,o){let s=Ke(t,n),a=s.type==="index",u=a?424:500,b={success:false,error:a?s.message:o&&t instanceof Error?t.message:r};return a&&(b.errorType="index",s.indexUrl&&(b.indexUrl=s.indexUrl)),en(e,b,u)}var Yt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function nr(){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>=Yt.length*4||(e+=Yt.charAt(r%Yt.length));}}return e}function Ie(e){let t=e._def??e.def;if(!t)return e;let n=t.typeName??t.type;if(n==="ZodDate"||n==="date")return z$1.preprocess(r=>pn(r)??r,e);if(n==="ZodObject"||n==="object"){let r=e.shape,o={};for(let[s,a]of Object.entries(r))o[s]=Ie(a);return z$1.object(o)}if(n==="ZodArray"||n==="array"){let r=t.element??t.type;if(r)return z$1.array(Ie(r))}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(r)return Ie(r).optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(r)return Ie(r).nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType,o=t.defaultValue;if(r){let s=Ie(r);return typeof o=="function"?s.default(o()):s.default(o)}}return e}function Lo(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 u=a.split(".")[0];u&&r[u]&&(o[u]=r[u]);}return z$1.object(o)}function yt(e,t,n,r=false,o=[]){try{let s=Lo(e,n,o),a=r?s.partial():s;return {success:!0,data:(un()==="normalize"?Ie(a):a).parse(t)}}catch(s){return s instanceof z$1.ZodError?{success:false,error:`Validation failed: ${s.issues.map(u=>`${u.path.join(".")}: ${u.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}function Uo(e,t){let n=[],r=t?new Set(t):null,o={eq:"==",ne:"!=",lt:"<",lte:"<=",gt:">",gte:">=",in:"in",nin:"not-in",contains:"array-contains",containsAny:"array-contains-any"};for(let[s,a]of Object.entries(e)){if(a===void 0||["cursor","limit","pageSize","orderBy","orderDir","select"].includes(s))continue;let u=Array.isArray(a)?a[0]:a;if(u===void 0||u==="")continue;let d=s.match(/^(\w+)__(\w+)$/),b,v="==";if(d&&d[1]&&d[2]){b=d[1];let A=d[2];if(o[A])v=o[A];else continue}else if(!d)b=s;else continue;if(r&&!r.has(b))continue;let x=u;v==="in"||v==="not-in"||v==="array-contains-any"?x=u.split(",").map(A=>rr(A.trim())):x=rr(u),n.push({field:b,op:v,value:x});}return n}function rr(e){if(e==="true")return true;if(e==="false")return false;if(e==="null")return null;let t=Number(e);return !isNaN(t)&&e!==""?t:e}function mt(e){return e?{docId:e.id}:null}async function or(e,t){if(!t||typeof t!="object")return;let n=t.docId;if(typeof n=="string")try{let r=e.repo.ref;if(typeof r.doc!="function")return;let o=await r.doc(n).get();return o.exists?o:void 0}catch{return}}function sr(e,t,n){async function r(g,i,p,l){if(!i.rules)return true;let c=i.rules?.[p];if(!c)return F(g,`Operation "${p}" is not allowed for this repository`,403),false;try{return await c(l)?!0:F(g,"Forbidden",403)}catch(f){let h=n&&f instanceof Error?f.message:"Forbidden";return F(g,h,403)}}async function o(g,i,p,l){if(!g.rules)return l;let c=g.rules?.filter;if(!c)return l;let f=[];for(let h of l)try{await c({user:i,doc:h,params:p})&&f.push(h);}catch{}return f}function s(g){return g.get("user")??g.get("docsUser")??null}function a(g,i){if(!g){let p=i.req.path.split("/");for(let l of p)if(e[l]){g=l;break}}return !g||!e[g]?null:e[g]??null}function u(g,i){if(!i)return;let p=g[i];if(typeof p!="string"||!p)return;let l=p.split("/").filter(Boolean),c=[];for(let f=1;f<l.length;f+=2)c.push(l[f]);return c.length>0?c:void 0}async function d(g,i){let p=`by${g.documentKey.charAt(0).toUpperCase()}${g.documentKey.slice(1)}`,l=g.repo.get[p];if(typeof l=="function")try{let f=await l(i);if(f)return f}catch{}return (await g.repo.query.by({where:[[g.documentKey,"==",i]],limit:1}))[0]??null}async function b(g){let i=g.c,p=i.req.param(),l=a(p.repoName,i);if(!l)return F(i,"Repository not found",404);let c=s(i);if(!await r(i,l,"list",{user:c,query:i.req.query(),params:p}))return;let f=[],h;try{let w=i.req.query(),O=Math.min(Number(w.pageSize)||l.pageSize,100),T=w.cursor,R=w.direction?.toLowerCase()==="prev"?"prev":"next",C=w.orderBy,E=w.orderDir?.toLowerCase()==="desc"?"desc":"asc",$=w.select,P=$?$.split(",").map(U=>U.trim()):void 0,D;l.allowedIncludes&&w.includes&&(D=(typeof w.includes=="string"?w.includes.split(",").map(se=>se.trim()):Array.isArray(w.includes)?w.includes:[]).filter(se=>typeof se=="string"&&l.allowedIncludes.includes(se)),D?.length===0&&(D=void 0));let H=Uo(w,l.filterableFields);f=H.map(U=>({field:U.field,op:U.op,value:String(U.value??"")})),C&&(h={field:C,dir:E});let j={pageSize:O,direction:R};if(T)try{let U=typeof T=="string"?JSON.parse(T):T;j.cursor=await or(l,U);}catch{}if(C){if(l.orderableFields&&!l.orderableFields.includes(C))return F(i,`Field not orderable: ${C}`,400);j.orderBy=[{field:C,direction:E}];}H.length>0&&(j.where=H.map(U=>[U.field,U.op,U.value])),P&&(j.select=P),D&&(j.include=D);let I=await l.repo.query.paginate(j),ce={items:await o(l,s(i),p,I.data),hasNextPage:I.hasNextPage,hasPrevPage:I.hasPrevPage,nextCursor:mt(I.nextCursor),prevCursor:mt(I.prevCursor)};return Te(i,ce,{pageSize:O,hasMore:I.hasNextPage})}catch(w){Xt(i,w,{ref:l.repo.ref,path:l.path,isGroup:!!l.isGroup,filters:f,sort:h},"Failed to fetch documents",n);}}async function v(g){let i=g.c,p=i.req.param(),l=a(p.repoName,i);if(!l)return F(i,"Repository not found",404);let c=s(i);if(!await r(i,l,"list",{user:c,query:g.input||{},params:p}))return;let f=[],h;try{let w=g.input||{},O=Math.min(w.pageSize||l.pageSize,100),T=w.direction==="prev"?"prev":"next";w.where&&(f=w.where.map(P=>({field:String(P[0]),op:P[1],value:String(P[2]??"")}))),w.orderBy&&w.orderBy[0]&&(h={field:w.orderBy[0].field,dir:w.orderBy[0].direction==="desc"?"desc":"asc"});let R={pageSize:O,direction:T};if(w.cursor)try{let P=typeof w.cursor=="string"?JSON.parse(w.cursor):w.cursor;R.cursor=await or(l,P);}catch{}if(l.allowedIncludes&&w.includes&&w.includes.length>0){let P=w.includes.filter(D=>typeof D=="string"?l.allowedIncludes.includes(D):typeof D=="object"&&D!==null&&"relation"in D&&typeof D.relation=="string"?l.allowedIncludes.includes(D.relation):!1);P.length>0&&(R.include=P);}if(w.where&&w.where.length>0){if(l.filterableFields){let P=new Set(l.filterableFields),D=w.where.filter(H=>!P.has(H[0]));if(D.length>0){F(i,`Fields not filterable: ${D.map(H=>H[0]).join(", ")}`,400);return}}R.where=w.where;}if(w.orWhere&&w.orWhere.length>0){if(l.filterableFields){let P=new Set(l.filterableFields),D=w.orWhere.filter(H=>!P.has(H[0]));if(D.length>0){F(i,`Fields not filterable: ${D.map(H=>H[0]).join(", ")}`,400);return}}R.orWhere=w.orWhere;}if(w.orWhereGroups&&w.orWhereGroups.length>0){if(l.filterableFields){let P=new Set(l.filterableFields);for(let D of w.orWhereGroups){let H=D.filter(j=>!P.has(j[0]));if(H.length>0){F(i,`Fields not filterable: ${H.map(j=>j[0]).join(", ")}`,400);return}}}R.orWhereGroups=w.orWhereGroups;}if(w.orderBy&&w.orderBy.length>0){if(l.orderableFields){let P=new Set(l.orderableFields),D=w.orderBy.filter(H=>!P.has(H.field));if(D.length>0){F(i,`Fields not orderable: ${D.map(H=>H.field).join(", ")}`,400);return}}R.orderBy=w.orderBy;}w.select&&w.select.length>0&&(R.select=w.select);let C=await l.repo.query.paginate(R),$={items:await o(l,s(i),p,C.data),hasNextPage:C.hasNextPage,hasPrevPage:C.hasPrevPage,nextCursor:mt(C.nextCursor),prevCursor:mt(C.prevCursor)};return Te(i,$,{pageSize:O,hasMore:C.hasNextPage})}catch(w){Xt(i,w,{ref:l.repo.ref,path:l.path,isGroup:!!l.isGroup,filters:f,sort:h},"Failed to query documents",n);}}async function x(g){let i=g.c,p=i.req.param(),l=a(p.repoName,i);if(!l)return F(i,"Repository not found",404);let c=p.id;if(!c)return F(i,"Document ID required",400);try{let f=await d(l,c);if(!f)return F(i,"Document not found",404);let h=s(i);if(!await r(i,l,"get",{user:h,doc:f,params:p}))return;if(l.rules?.filter)try{if(!await l.rules.filter({user:h,doc:f,params:p}))return F(i,"Document not found",404)}catch{return F(i,"Document not found",404)}return Te(i,f)}catch(f){Xt(i,f,{ref:l.repo.ref,path:l.path,isGroup:!!l.isGroup,filters:[{field:l.documentKey,op:"==",value:c}]},"Failed to fetch document",n);}}async function A(g){let i=g.c,p=i.req.param(),l=a(p.repoName,i);if(!l)return F(i,"Repository not found",404);try{let c=g.input||{},f=s(i);if(!await r(i,l,"create",{user:f,body:c,params:p}))return;let h=yt(l.schema,c,l.createFields,!1,l.systemKeys);if(!h.success)return F(i,h.error,400);if(l.validate){let O=await l.validate(h.data,"create");if(O)return F(i,O,400)}let w;if(l.isGroup&&l.parentKeys&&l.parentKeys.length>0){let O={...h.data};l.createdKey&&(O[l.createdKey]=new Date);let T=l.parentKeys.filter(E=>!O[E]);if(T.length>0){F(i,`Missing parent key(s) for subcollection create: ${T.join(", ")}`,400);return}let R=l.parentKeys.map(E=>O[E]),C=O[l.documentKey]||nr();w=await l.repo.set(...R,C,O);}else w=await l.repo.create(h.data);return Te(i,w,void 0,201)}catch(c){let f=n&&c instanceof Error?c.message:"Failed to create document";return F(i,f,500)}}async function S(g,i){let p=g.c,l=p.req.param(),c=a(l.repoName,p);if(!c)return F(p,"Repository not found",404);let f=l.id;if(!f)return F(p,"Document ID required",400);try{let h=g.input||{},w=await d(c,f);if(!w)return F(p,"Document not found",404);let O=s(p);if(!await r(p,c,"update",{user:O,doc:w,body:h,params:l}))return;let T=yt(c.schema,h,c.mutableFields,i,c.systemKeys);if(!T.success)return F(p,T.error,400);if(c.validate){let E=await c.validate(T.data,"update");if(E)return F(p,E,400)}let R=u(w,c.pathKey)??[f],C=await c.repo.update(...R,T.data);return Te(p,C)}catch(h){let w=n&&h instanceof Error?h.message:"Failed to update document";return F(p,w,500)}}async function m(g){let i=g.c,p=i.req.param(),l=a(p.repoName,i);if(!l)return F(i,"Repository not found",404);if(!l.allowDelete)return F(i,"Delete not allowed for this repository",403);let c=p.id;if(!c)return F(i,"Document ID required",400);try{let f=await d(l,c);if(!f)return F(i,"Document not found",404);let h=s(i);if(!await r(i,l,"delete",{user:h,doc:f,params:p}))return;let w=u(f,l.pathKey)??[c];return await l.repo.delete(...w),Te(i,{deleted:!0})}catch(f){let h=n&&f instanceof Error?f.message:"Failed to delete document";return F(i,h,500)}}function k(g){return g.c.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization","Access-Control-Max-Age":"86400"})}async function y(g){let i=g.c,p=i.req.param(),l=a(p.repoName,i);if(!l)return F(i,"Repository not found",404);try{let c=g.input||{};if(!Array.isArray(c.operations))return F(i,"operations array is required",400);let f=s(i),h=l.repo.batch.create(),w=[];for(let O of c.operations){if(!O.type||!["create","update","delete"].includes(O.type))return F(i,"Invalid operation type",400);if(O.type==="create"){if(!await r(i,l,"create",{user:f,body:O.data,params:p}))return;let T=yt(l.schema,O.data,l.createFields,!1,l.systemKeys);if(!T.success)return F(i,T.error,400);let R=O.data[l.documentKey]||nr(),C={...T.data};if(l.createdKey&&(C[l.createdKey]=new Date),l.isGroup&&l.parentKeys){let E=l.parentKeys.map($=>C[$]);h.set(...E,R,C);}else h.set(R,C);w.push({op:"create",id:R});}else if(O.type==="update"){if(!O.id)return F(i,"id required for update",400);let T=await d(l,O.id);if(!T)return F(i,`Document ${O.id} not found`,404);if(!await r(i,l,"update",{user:f,doc:T,body:O.data,params:p}))return;let R=yt(l.schema,O.data,l.mutableFields,!0,l.systemKeys);if(!R.success)return F(i,R.error,400);let C=u(T,l.pathKey)??[O.id];h.update(...C,R.data),w.push({op:"update",id:O.id});}else if(O.type==="delete"){if(!l.allowDelete)return F(i,"Delete not allowed",403);if(!O.id)return F(i,"id required for delete",400);let T=await d(l,O.id);if(!T)return F(i,`Document ${O.id} not found`,404);if(!await r(i,l,"delete",{user:f,doc:T,params:p}))return;let R=u(T,l.pathKey)??[O.id];h.delete(...R),w.push({op:"delete",id:O.id});}}return await h.commit(),Te(i,{results:w})}catch(c){let f=n&&c instanceof Error?c.message:"Batch operation failed";return F(i,f,500)}}return {handleList:b,handleQuery:v,handleGet:x,handleCreate:A,handleUpdate:S,handleDelete:m,handleBatch:y,handleOptions:k}}function tn(e){try{return z$1.toJSONSchema(e,{target:"openapi-3.1",unrepresentable:"any",override:t=>{let n=getOpenApiMetadata(t.zodSchema);n&&Object.assign(t.jsonSchema,n);let r=t.zodSchema?._zod?.def;r&&(r.type==="date"&&!t.jsonSchema.type?(t.jsonSchema.type="string",t.jsonSchema.format="date-time"):r.type==="bigint"&&!t.jsonSchema.type&&(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 ne(e){return {$ref:`#/components/schemas/${e}`}}function V(e){return {description:e,content:{"application/json":{schema:ne("ErrorResponse")}}}}function De(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function ar(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"}},required:["items","hasNextPage","hasPrevPage"]},meta:{type:"object",properties:{pageSize:{type:"integer"},hasMore:{type:"boolean"},cursor:{oneOf:[{type:"string"},{type:"null"}]}}}},required:["success","data"]}}}}}function Vo(e){return [{name:"pageSize",in:"query",schema:{type:"integer",default:e.pageSize,maximum:100},description:"Number of items per page"},{name:"cursor",in:"query",schema:{type:"string"},description:"Base64 pagination cursor"},{name:"orderBy",in:"query",schema:{type:"string"},description:"Field name to order by"},{name:"orderDir",in:"query",schema:{type:"string",enum:["asc","desc"]},description:"Order direction"},{name:"select",in:"query",schema:{type:"string"},description:"Comma-separated list of fields to return"}]}function Wo(e){let t=e.filterableFields??Object.keys(e.schema.shape),n=["eq","ne","lt","lte","gt","gte","in","nin","contains"],r=[];for(let o of t){r.push({name:o,in:"query",schema:{type:"string"},description:`Filter by ${o} (equality)`});for(let s of n)r.push({name:`${o}__${s}`,in:"query",schema:{type:"string"},description:`Filter ${o} with operator ${s}`});}return r}function Qo(){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",maximum:100,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)"}}}}function Go(e,t,n,r,o){let s={},a=e.name,u=`${t}/${e.name}`,d=`${u}/{${e.documentKey}}`,b={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};s[u]={get:{operationId:`list${fe(e.name)}`,summary:`List ${e.name} (paginated)`,tags:[a],parameters:[...Vo(e),...Wo(e)],responses:{200:ar(ne(n)),500:V("Internal server error")}},post:{operationId:`create${fe(e.name)}`,summary:`Create a ${ie(e.name)}`,tags:[a],requestBody:{required:true,content:{"application/json":{schema:ne(r??n)}}},responses:{201:De("Document created",ne(n)),400:V("Validation error"),500:V("Internal server error")}}},s[`${u}/query`]={post:{operationId:`query${fe(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[a],requestBody:{required:true,content:{"application/json":{schema:ne("QueryRequestBody")}}},responses:{200:ar(ne(n)),400:V("Invalid query"),500:V("Internal server error")}}},s[`${u}/batch`]={post:{operationId:`batch${fe(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[a],requestBody:{required:true,content:{"application/json":{schema:ne(`${n}BatchRequest`)}}},responses:{200:De("Batch operations completed",{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{op:{type:"string"},id:{type:"string"}}}}}}),400:V("Validation error"),403:V("Forbidden"),404:V("Document not found"),500:V("Internal server error")}}};let v={};return v.get={operationId:`get${fe(ie(e.name))}`,summary:`Get a single ${ie(e.name)}`,tags:[a],parameters:[b],responses:{200:De("Document found",ne(n)),404:V("Document not found"),500:V("Internal server error")}},v.put={operationId:`update${fe(ie(e.name))}`,summary:`Update a ${ie(e.name)} (full replace)`,tags:[a],parameters:[b],requestBody:{required:true,content:{"application/json":{schema:ne(o??n)}}},responses:{200:De("Document updated",ne(n)),400:V("Validation error"),404:V("Document not found"),500:V("Internal server error")}},v.patch={operationId:`patch${fe(ie(e.name))}`,summary:`Partially update a ${ie(e.name)}`,tags:[a],parameters:[b],requestBody:{required:true,content:{"application/json":{schema:{allOf:[ne(o??n)],description:"All fields are optional for partial updates"}}}},responses:{200:De("Document patched",ne(n)),400:V("Validation error"),404:V("Document not found"),500:V("Internal server error")}},e.allowDelete&&(v.delete={operationId:`delete${fe(ie(e.name))}`,summary:`Delete a ${ie(e.name)}`,tags:[a],parameters:[b],responses:{200:De("Document deleted",{type:"object",properties:{id:{type:"string"}}}),404:V("Document not found"),500:V("Internal server error")}}),s[d]=v,s}function rn(e,t,n={}){let{title:r="CRUD API",version:o="1.0.0",description:s,servers:a,auth:u=false}=n,d=t==="/"?"":t.replace(/\/$/,""),b={},v={},x=[];b.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string"}},required:["success","error"]},b.QueryRequestBody=Qo();for(let[k,y]of Object.entries(e)){let g=fe(ie(k)),i=`${g}Create`,p=`${g}Update`;b[g]=tn(y.schema);let l=T=>{let R=T&&T.length>0?T:Object.keys(y.schema.shape),C={};for(let E of R){let $=E.split(".")[0];$&&y.schema.shape[$]&&!y.systemKeys.includes($)&&(C[$]=y.schema.shape[$]);}return C},c=null,f=l(y.createFields);Object.keys(f).length>0&&(b[i]=tn(z$1.object(f)),c=i);let h=null,w=l(y.mutableFields);Object.keys(w).length>0&&(b[p]=tn(z$1.object(w)),h=p),b[`${g}BatchRequest`]={type:"object",properties:{operations:{type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",enum:["create"]},data:ne(c??g)},required:["type","data"]},{type:"object",properties:{type:{type:"string",enum:["update"]},id:{type:"string"},data:{allOf:[ne(h??g)],description:"Partial updates allowed"}},required:["type","id","data"]},...y.allowDelete?[{type:"object",properties:{type:{type:"string",enum:["delete"]},id:{type:"string"}},required:["type","id"]}]:[]]}}},required:["operations"]};let O=Go(y,d,g,c,h);Object.assign(v,O),x.push({name:k,description:`Operations on ${k} (collection: ${y.path})`});}let A={},S;return u==="basic"?(A.basicAuth={type:"http",scheme:"basic"},S=[{basicAuth:[]}]):u==="bearer"&&(A.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},S=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:r,version:o,...s?{description:s}:{}},...a&&a.length>0?{servers:a}:{},paths:v,components:{schemas:b,...Object.keys(A).length>0?{securitySchemes:A}:{}},...S?{security:S}:{},tags:x}}function fe(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 _e=class extends Error{constructor(n,r){super("Request validation failed");this.zodError=n;this.source=r;this.statusCode=400;this.name="ValidationError";}};var et=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},tt=class extends Error{constructor(n){super("Output validation failed");this.zodError=n;this.statusCode=500;this.name="OutputValidationError";}};function ir(e){return e.issues.map(t=>({path:t.path.join("."),code:t.code,message:t.message}))}function cr(e,t){return t instanceof _e?e.json({success:false,error:"Validation failed",issues:ir(t.zodError)},400):t instanceof et?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof tt?e.json({success:false,error:"Output validation failed",issues:ir(t.zodError)},500):null}extendZodWithOpenApi(z$1);var lr="Successful response",dr="Error response";function ts(e){return e==="get"?"query":"json"}function ns(e,t){let n=t?.output;return n?typeof n=="function"?n(e):n:e}function rs(e){if(typeof e.safeParse=="function")return {description:dr,schema:e};let t=e;return {description:t.description??dr,schema:t.schema}}function pr(e,t,n,r){let o=new OpenAPIRegistry;if(n.securitySchemes)for(let[u,d]of Object.entries(n.securitySchemes))o.registerComponent("securitySchemes",u,d);for(let u of e){let d=u.method,b=u.source??ts(d),v=as(t,u.path??"/"),x=u.status??200,A=os(d,b,u.input),S=ur(b,u.input,"query"),m=ur(b,u.input,"param"),k=is(d,v),y=ns(u.output,r),g={[x]:y?{description:lr,content:{"application/json":{schema:y}}}:{description:lr}};if(r?.errors)for(let[i,p]of Object.entries(r.errors)){let{description:l,schema:c}=rs(p);g[i]=c?{description:l,content:{"application/json":{schema:c}}}:{description:l};}o.registerPath({method:d,path:ss(v),operationId:k,summary:u.summary,description:u.description,tags:u.tags,deprecated:u.deprecated,security:u.security,request:{...S?{query:S}:{},...m?{params:m}:{},...A?{body:A}:{}},responses:g});}return new OpenApiGeneratorV31(o.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security})}function os(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 ur(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function ss(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function as(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,o=`${n}${r}`;return o===""?"/":o}function is(e,t){let n=t.replace(/[{}]/g,"").replace(/\/+/g,"_").replace(/[^A-Za-z0-9_]/g,"").replace(/^_+|_+$/g,"");return `${e}_${n||"root"}`}function fr(e,t){let n=e.replace(/"/g,"&quot;");return `<!doctype html>
1142
1142
  <html lang="en">
1143
1143
  <head>
1144
1144
  <meta charset="utf-8" />
@@ -1149,5 +1149,5 @@ function initColumnReorder(table) {
1149
1149
  <script id="api-reference" data-url="${n}"></script>
1150
1150
  <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
1151
1151
  </body>
1152
- </html>`}function yr(e){return typeof e=="object"&&e!==null&&e.__docsAuthExtension===true}var on=new AsyncLocalStorage;function mr(){return async(e,t)=>{await on.run({c:e},async()=>{await t();});}}var ds=Object.freeze({}),ht=class{constructor(t){this.cachedSpec=null;this.options=t,this.app=new Hono,this.mountedRoutes=fs(t.routes,t.api),t.services&&this.app.use("*",mr());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=pr(this.mountedRoutes,this.options.basePath??"",this.options.openapi,ps(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=gt(t,o.path),a=o.middlewares??[],p=o.source??(o.method==="get"?"query":"json"),d=gs(o,p,n,us(this.options.interceptor),this.options.services,this.options.errorHandler,this.options.logger),b=o.method.toUpperCase();this.app.on(b,[s],...a,d),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=gt(this.options.basePath??"",n),s=r===false?null:gt(this.options.basePath??"",r),a;if(yr(t.docsAuth)){let p=t.docsAuth;a=[p.middleware];let d=ys(s??o);for(let b of p.routes)this.app.on(b.method,[gt(d,b.name)],b.handler);}else a=t.docsAuth?Array.isArray(t.docsAuth)?t.docsAuth:[t.docsAuth]:[];if(this.app.on("GET",[o],...a,p=>p.json(this.buildOpenApiSpec())),s){let p=ms(s,o);this.app.on("GET",[s],...a,d=>d.html(fr(p,t.info.title)));}}};function gr(e){return typeof e=="object"&&e!==null&&typeof e.handler=="function"}function us(e){if(e)return gr(e)?e.handler:e}function ps(e){return gr(e)?e:void 0}function fs(e,t){return t?e.filter(n=>Array.isArray(n.api)?n.api.includes(t):n.api===t):e.slice()}function gt(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,o=`${n}${r}`;return o===""?"/":o}function ys(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function ms(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 gs(e,t,n,r,o,s,a){let p=e.input,d=e.output,b=e.status??200,v=o??ds;return async x=>{let A=async k=>{if(s){let m=await s.handle({error:k,c:x,route:e,services:v,logger:a});if(m)return m}return cr(x,k)},S=async()=>{let k;if(p){let y;try{y=await hs(x,t,e.method);}catch(u){throw new et(u instanceof Error?u.message:String(u))}let i=p.safeParse(y);if(!i.success)throw new _e(i.error,t);k=i.data;}let m=await e.handler({input:k,c:x,services:v,errorHandler:s,logger:a});if(n&&d&&!(m instanceof Response)){let y=d.safeParse(m);if(!y.success)throw new tt(y.error);return y.data}return m},g;if(r)try{g=await r({next:S,route:e,c:x,services:v,errorHandler:s,logger:a});}catch(k){let m=await A(k);if(m)return m;throw k}else try{g=await S();}catch(k){let m=await A(k);if(m)return m;throw k}return g instanceof Response?g:x.json(g,b)}}async function hs(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 hr(e){let{basePath:t="/",repos:n,parseBody:r=true,securityHeaders:o,verbose:s=false,httpsOptions:a}=e,p=t==="/"?"":t.replace(/\/$/,""),d={};for(let[y,i]of Object.entries(n)){if(!i.repo)throw new Error(`[createCrudServer] Repository "${y}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let u=i.schema??i.repo.schema??null;if(!u)throw new Error(`[createCrudServer] Repository "${y}" has no Zod schema.`);let l,c,f,h;if(i.fieldsConfig){let T=i.fieldsConfig;l=[],c=[],f=[],h=[];for(let[R,C]of Object.entries(T))for(let E of C)E==="filterable"?l.push(R):E==="orderable"?c.push(R):E==="mutable"?f.push(R):E==="create"&&h.push(R);c.length===0&&(c=l),l.length===0&&(l=void 0),c&&c.length===0&&(c=void 0),f.length===0&&(f=void 0),h.length===0&&(h=void 0);}let w=(()=>{let T=i.repo._parentKeys;return T&&T.length>0?T:void 0})();if(w&&h)for(let T of w)h.includes(T)||h.push(T);let O={name:y,path:i.path,repo:i.repo,schema:u,systemKeys:i.repo._systemKeys??[i.documentKey??"docId"],documentKey:i.documentKey??"docId",pathKey:i.repo._pathKey??void 0,isGroup:!!i.repo._isGroup,parentKeys:w,createdKey:i.repo._createdKey??void 0,pageSize:i.pageSize??25,filterableFields:l,orderableFields:c,mutableFields:f,createFields:h,allowDelete:i.allowDelete??false,allowedIncludes:i.allowedIncludes,validate:i.validate,rules:i.rules};d[y]=O;}let b=sr(d,p,s),v=e.openapi,x=v&&typeof v=="object"?v:{},A=null;function S(){return A||(A=rn(d,p,{...x,auth:x.auth??false})),A}let g=[];for(let y of Object.keys(d))g.push({api:"crud",method:"get",path:`/${y}`,source:"query",handler:b.handleList}),g.push({api:"crud",method:"post",path:`/${y}/query`,source:"json",handler:b.handleQuery}),g.push({api:"crud",method:"get",path:`/${y}/:id`,source:"query",handler:b.handleGet}),g.push({api:"crud",method:"post",path:`/${y}`,source:"json",handler:b.handleCreate}),g.push({api:"crud",method:"put",path:`/${y}/:id`,source:"json",handler:i=>b.handleUpdate(i,false)}),g.push({api:"crud",method:"patch",path:`/${y}/:id`,source:"json",handler:i=>b.handleUpdate(i,true)}),g.push({api:"crud",method:"delete",path:`/${y}/:id`,source:"query",handler:b.handleDelete}),g.push({api:"crud",method:"post",path:`/${y}/batch`,source:"json",handler:b.handleBatch});let k=new ht({...e,openapi:v!==false?{path:x.path??"/openapi.json",docsPath:x.docsPath??"/docs",info:{title:x.title??"CRUD API",version:x.version??"1.0.0"},docsAuth:x.docsAuth}:void 0,basePath:t,api:"crud",routes:g,middlewares:[async(y,i)=>{if(y.req.method==="OPTIONS")return y.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization","Access-Control-Max-Age":"86400","Access-Control-Allow-Origin":"*","Access-Control-Allow-Credentials":"true"});y.header("Access-Control-Allow-Origin","*"),y.header("Access-Control-Allow-Credentials","true"),await i();},...e.middlewares||[]]});if(v!==false&&(k.buildOpenApiSpec=S),o!==false){let{securityHeaders:y}=(ft(),Er(er)),i=o===void 0?{csp:false}:o;k.hono.use("*",async(u,l)=>{let c=y(i);await new Promise(f=>{let h=u.req.raw;c(h,{setHeader:(O,T)=>u.header(O,T),removeHeader:O=>u.res.headers.delete(O)},()=>f());}),await l();});}let m=k.nodeHandler;return m.spec=S,a&&(m.httpsOptions=a),m}function br(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 wr(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 d=o?rt(o[s],()=>e[s]):e[s];r[s]={...a,repo:d};}return r}function bs(e,t={}){return {admin(n){let r=wr(e,n.repos,"admin"),o=tr({...n,repos:r,httpsOptions:n.httpsOptions??t.httpsOptions});return br(o,t)},crud(n){let r=wr(e,n.repos,"crud"),o=hr({...n,repos:r,httpsOptions:n.httpsOptions??t.httpsOptions});return br(o,t)},sync(n){let r={...n};return t.onRequest&&r.admin&&!r.admin.onRequest&&(r.admin={...r.admin,onRequest:t.onRequest,httpsOptions:r.admin.httpsOptions??t.httpsOptions}),En(e,r)},history(n){return an(e,n)}}}ft();export{_o as CSS,Ve as ClientScript,Jt as DEFAULT_HTML_CSP,ye as MiniRouter,bs as createServers,Lt as renderDashboard,Ue as renderField,ge as renderForm,ve as renderFormPage,Ut as renderList,Xe as renderPage,pt as securityHeaders,re as zodToFields};//# sourceMappingURL=index.js.map
1152
+ </html>`}function yr(e){return typeof e=="object"&&e!==null&&e.__docsAuthExtension===true}var on=new AsyncLocalStorage;function mr(){return async(e,t)=>{await on.run({c:e},async()=>{await t();});}}var us=Object.freeze({}),ht=class{constructor(t){this.cachedSpec=null;this.options=t,this.app=new Hono,this.mountedRoutes=ys(t.routes,t.api),t.services&&this.app.use("*",mr());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=pr(this.mountedRoutes,this.options.basePath??"",this.options.openapi,fs(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=gt(t,o.path),a=o.middlewares??[],u=o.source??(o.method==="get"?"query":"json"),d=hs(o,u,n,ps(this.options.interceptor),this.options.services,this.options.errorHandler,this.options.logger),b=o.method.toUpperCase();this.app.on(b,[s],...a,d),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=gt(this.options.basePath??"",n),s=r===false?null:gt(this.options.basePath??"",r),a;if(yr(t.docsAuth)){let u=t.docsAuth;a=[u.middleware];let d=ms(s??o);for(let b of u.routes)this.app.on(b.method,[gt(d,b.name)],b.handler);}else a=t.docsAuth?Array.isArray(t.docsAuth)?t.docsAuth:[t.docsAuth]:[];if(this.app.on("GET",[o],...a,u=>u.json(this.buildOpenApiSpec())),s){let u=gs(s,o);this.app.on("GET",[s],...a,d=>d.html(fr(u,t.info.title)));}}};function gr(e){return typeof e=="object"&&e!==null&&typeof e.handler=="function"}function ps(e){if(e)return gr(e)?e.handler:e}function fs(e){return gr(e)?e:void 0}function ys(e,t){return t?e.filter(n=>Array.isArray(n.api)?n.api.includes(t):n.api===t):e.slice()}function gt(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,o=`${n}${r}`;return o===""?"/":o}function ms(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function gs(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 hs(e,t,n,r,o,s,a){let u=e.input,d=e.output,b=e.status??200,v=o??us;return async x=>{let A=async k=>{if(s){let y=await s.handle({error:k,c:x,route:e,services:v,logger:a});if(y)return y}return cr(x,k)},S=async()=>{let k,y;try{y=await bs(x,t,e.method);}catch(i){throw new et(i instanceof Error?i.message:String(i))}if(u){let i=u.safeParse(y);if(!i.success)throw new _e(i.error,t);k=i.data;}else k=y;let g=await e.handler({input:k,c:x,services:v,errorHandler:s,logger:a});if(n&&d&&!(g instanceof Response)){let i=d.safeParse(g);if(!i.success)throw new tt(i.error);return i.data}return g},m;if(r)try{m=await r({next:S,route:e,c:x,services:v,errorHandler:s,logger:a});}catch(k){let y=await A(k);if(y)return y;throw k}else try{m=await S();}catch(k){let y=await A(k);if(y)return y;throw k}return m instanceof Response?m:x.json(m,b)}}async function bs(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 hr(e){let{basePath:t="/",repos:n,parseBody:r=true,securityHeaders:o,verbose:s=false,httpsOptions:a}=e,u=t==="/"?"":t.replace(/\/$/,""),d={};for(let[g,i]of Object.entries(n)){if(!i.repo)throw new Error(`[createCrudServer] Repository "${g}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let p=i.schema??i.repo.schema??null;if(!p)throw new Error(`[createCrudServer] Repository "${g}" has no Zod schema.`);let l,c,f,h;if(i.fieldsConfig){let T=i.fieldsConfig;l=[],c=[],f=[],h=[];for(let[R,C]of Object.entries(T))for(let E of C)E==="filterable"?l.push(R):E==="orderable"?c.push(R):E==="mutable"?f.push(R):E==="create"&&h.push(R);c.length===0&&(c=l),l.length===0&&(l=void 0),c&&c.length===0&&(c=void 0),f.length===0&&(f=void 0),h.length===0&&(h=void 0);}let w=(()=>{let T=i.repo._parentKeys;return T&&T.length>0?T:void 0})();if(w&&h)for(let T of w)h.includes(T)||h.push(T);let O={name:g,path:i.path,repo:i.repo,schema:p,systemKeys:i.repo._systemKeys??[i.documentKey??"docId"],documentKey:i.documentKey??"docId",pathKey:i.repo._pathKey??void 0,isGroup:!!i.repo._isGroup,parentKeys:w,createdKey:i.repo._createdKey??void 0,pageSize:i.pageSize??25,filterableFields:l,orderableFields:c,mutableFields:f,createFields:h,allowDelete:i.allowDelete??false,allowedIncludes:i.allowedIncludes,validate:i.validate,rules:i.rules};d[g]=O;}let b=sr(d,u,s),v=e.openapi,x=v&&typeof v=="object"?v:{},A=null;function S(){return A||(A=rn(d,u,{...x,auth:x.auth??false})),A}let m=[];for(let g of Object.keys(d))m.push({api:"crud",method:"get",path:`/${g}`,source:"query",handler:b.handleList}),m.push({api:"crud",method:"post",path:`/${g}/query`,source:"json",handler:b.handleQuery}),m.push({api:"crud",method:"get",path:`/${g}/:id`,source:"query",handler:b.handleGet}),m.push({api:"crud",method:"post",path:`/${g}`,source:"json",handler:b.handleCreate}),m.push({api:"crud",method:"put",path:`/${g}/:id`,source:"json",handler:i=>b.handleUpdate(i,false)}),m.push({api:"crud",method:"patch",path:`/${g}/:id`,source:"json",handler:i=>b.handleUpdate(i,true)}),m.push({api:"crud",method:"delete",path:`/${g}/:id`,source:"query",handler:b.handleDelete}),m.push({api:"crud",method:"post",path:`/${g}/batch`,source:"json",handler:b.handleBatch});let k=new ht({...e,openapi:v!==false?{path:x.path??"/openapi.json",docsPath:x.docsPath??"/docs",info:{title:x.title??"CRUD API",version:x.version??"1.0.0"},docsAuth:x.docsAuth}:void 0,basePath:t,api:"crud",routes:m,middlewares:[async(g,i)=>{if(g.req.method==="OPTIONS")return g.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization","Access-Control-Max-Age":"86400","Access-Control-Allow-Origin":"*","Access-Control-Allow-Credentials":"true"});g.header("Access-Control-Allow-Origin","*"),g.header("Access-Control-Allow-Credentials","true"),await i();},...e.middlewares||[]]});if(v!==false&&(k.buildOpenApiSpec=S),o!==false){let{securityHeaders:g}=(ft(),Er(er)),i=o===void 0?{csp:false}:o;k.hono.use("*",async(p,l)=>{let c=g(i);await new Promise(f=>{let h=p.req.raw;c(h,{setHeader:(O,T)=>p.header(O,T),removeHeader:O=>p.res.headers.delete(O)},()=>f());}),await l();});}let y=k.nodeHandler;return y.spec=S,a&&(y.httpsOptions=a),y}function br(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 wr(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 d=o?rt(o[s],()=>e[s]):e[s];r[s]={...a,repo:d};}return r}function ws(e,t={}){return {admin(n){let r=wr(e,n.repos,"admin"),o=tr({...n,repos:r,httpsOptions:n.httpsOptions??t.httpsOptions});return br(o,t)},crud(n){let r=wr(e,n.repos,"crud"),o=hr({...n,repos:r,httpsOptions:n.httpsOptions??t.httpsOptions});return br(o,t)},sync(n){let r={...n};return t.onRequest&&r.admin&&!r.admin.onRequest&&(r.admin={...r.admin,onRequest:t.onRequest,httpsOptions:r.admin.httpsOptions??t.httpsOptions}),En(e,r)},history(n){return an(e,n)}}}ft();export{_o as CSS,Ve as ClientScript,Jt as DEFAULT_HTML_CSP,ye as MiniRouter,ws as createServers,Lt as renderDashboard,Ue as renderField,ge as renderForm,ve as renderFormPage,Ut as renderList,Xe as renderPage,pt as securityHeaders,re as zodToFields};//# sourceMappingURL=index.js.map
1153
1153
  //# sourceMappingURL=index.js.map