@lpdjs/firestore-repo-service 2.6.38 → 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`,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>
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>
@@ -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,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=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,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:[...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[`${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=Wo();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=Qo(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 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[u,d]of Object.entries(n.securitySchemes))o.registerComponent("securitySchemes",u,d);for(let u of e){let d=u.method,b=u.source??es(d),v=ss(t,u.path??"/"),x=u.status??200,A=rs(d,b,u.input),S=ur(b,u.input,"query"),m=ur(b,u.input,"param"),k=as(d,v),y=ts(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}=ns(p);g[i]=c?{description:l,content:{"application/json":{schema:c}}}:{description:l};}o.registerPath({method:d,path:os(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 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??[],u=o.source??(o.method==="get"?"query":"json"),d=gs(o,u,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 u=t.docsAuth;a=[u.middleware];let d=ys(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=ms(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 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 u=e.input,d=e.output,b=e.status??200,v=o??ds;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 hs(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 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,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 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