@lpdjs/firestore-repo-service 2.6.26 → 2.6.27

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';var rr=Object.defineProperty;var et=(e,t)=>()=>(e&&(t=e(e=0)),t);var or=(e,t)=>{for(var n in t)rr(e,n,{get:t[n],enumerable:true});};function z(e){let t=e,n=t._zod?.def?.type;if(n)return wr[n]??`Zod${n.charAt(0).toUpperCase()}${n.slice(1)}`;let r=t._def?.typeName;return r||""}function J(e){let t=e;if(t._zod?.def?.innerType)return t._zod.def.innerType;if(t._def?.innerType)return t._def.innerType}function Ne(e){let t=e,n=t._zod?.def?.in;if(n)return n;if(t._def?.schema)return t._def.schema}function rn(e){let t=e;if(t._zod?.def?.element)return t._zod.def.element;if(t._def?.type)return t._def.type}function on(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 X(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 Fe(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 je(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 Me(e){let t=e;return Array.isArray(t._zod?.def?.values)?t._zod.def.values[0]:t._def?.value}function Be(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 sn(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 wr,He=et(()=>{wr={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 Tn({val:e}){return jsx("span",{class:"text-sm text-base-content/80 font-mono tabular-nums whitespace-nowrap",children:e.toLocaleString()})}function Zr({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 Ee({val:e,mismatch:t}){let n=Tt(e);return t?jsxs("span",{class:"inline-flex items-start gap-0.5",children:[n,jsx(Zr,{message:t})]}):n}function Tt(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(Tn,{val:e});if(typeof e=="object"&&e!==null&&typeof e.toDate=="function")return jsx(Tn,{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:Tt(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:Tt(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 at=et(()=>{});function qe(e){if(!e)return "unknown";let t=Ct(e);switch(z(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 Ct(e){let t=z(e);if(t==="ZodOptional"||t==="ZodNullable"||t==="ZodDefault"){let n=J(e);return n?Ct(n):e}return e}function Ke(e,t){if(!e)return;let n=t.split("."),r=e;for(let o of n){if(!r)return;let s=Ct(r);if(z(s)!=="ZodObject")return;r=X(s)[o];}return r}function Kr(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 Ve(e,t){if(e==="unknown")return null;let n=Kr(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 At=et(()=>{He();});var On={};or(On,{PanelMany:()=>Qr,PanelOne:()=>Vr,RightPanel:()=>Ot});function Vr({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`,f=An(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 g=e[d],w=f[d],S=w?Ve(w,g):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(Ee,{val:g,mismatch:S})})]})})})]})}function Qr({docs:e,repoName:t,basePath:n,fk:r,fv:o,columns:s,schema:a,pagination:f}){let d=`${n}/${t}?fv_${r}=${encodeURIComponent(o)}`,g=An(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((w,S)=>jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:w},S)),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((w,S)=>{let R=String(w.docId??w.id??""),v=`${n}/${t}/${encodeURIComponent(R)}/edit`;return jsxs("tr",{class:"hover",children:[s.map((b,T)=>{let x=w[b],y=g[b],u=y?Ve(y,x):null;return jsx("td",{class:"align-top py-1.5",children:jsx(Ee,{val:x,mismatch:u})},T)}),jsx("td",{class:"text-right py-1.5",children:jsx("a",{href:v,class:"btn btn-xs btn-ghost",children:"Edit"})})]},S)})})]})}),(f.hasPrev||f.hasNext)&&jsxs("div",{class:"flex justify-center items-center gap-2",children:[f.hasPrev?jsx("button",{type:"button",class:"btn btn-xs btn-outline","data-frs-panel-page":"prev","data-cursor":f.prevCursor,children:"\u2190 Previous"}):jsx("button",{class:"btn btn-xs btn-outline",disabled:true,children:"\u2190 Previous"}),f.hasNext?jsx("button",{type:"button",class:"btn btn-xs btn-outline","data-frs-panel-page":"next","data-cursor":f.nextCursor,children:"Next \u2192"}):jsx("button",{class:"btn btn-xs btn-outline",disabled:true,children:"Next \u2192"})]})]})}function An(e,t){if(!e)return {};let n={};for(let r of t)n[r]=qe(Ke(e,r));return n}var Ot,$t=et(()=>{at();At();Ot=({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"})})})]})]});});function ut(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 pt(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(!pt(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)||!pt(e[s],t[s],n))return false;return true}return false}function ft(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??{},f=new Set([...Object.keys(s),...Object.keys(a)]),d={};for(let g of f){if(r.has(g)||o&&!o.has(g))continue;let w=s[g],S=a[g];pt(w,S)||(d[g]={oldValue:w===void 0?null:w,newValue:S===void 0?null:S,type:{old:ut(w),new:ut(S)}});}return d}var ar=7e5;function yt(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,f)=>f instanceof Timestamp?f.toMillis():f),"utf8")}catch{return 0}};if(o(r.changes)>ar){let s={};for(let[a,f]of Object.entries(r.changes)){let d=o(f.oldValue),g=o(f.newValue);s[a]={oldValue:d>5e4?"[truncated]":f.oldValue,newValue:g>5e4?"[truncated]":f.newValue,type:f.type};}r.changes=s,r._truncated=true;}return r}async function gt(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 ht(e,t){let n=e??{},r={},o=t.meta;if(!o)return r;let s=w=>{if(!w)return;let S=n[w];return S===void 0||S===null?null:String(S)},a=s(o.userId);a!==void 0&&(r.userId=a);let f=s(o.userEmail);f!==void 0&&(r.userEmail=f);let d=s(o.reason);d!==void 0&&(r.reason=d);let g=s(o.comment);if(g!==void 0&&(r.comment=g),o.extras&&o.extras.length>0){let w={},S=false;for(let R of o.extras)R in n&&(w[R]=n[R],S=true);S&&(r.extras=w);}return r}function bt(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 lr(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 cr(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 dr(e,t){return t?`${t}/{docId}`:(console.warn(`[HistoryTriggers] Cannot determine collection path for "${e}". Skipping.`),null)}function Wt(e,t){let{onDocumentWritten:n}=t.deps,r={},o=e?.rawMapping,s=o?Object.entries(o).map(([a,f])=>[a,lr(f)]):Object.entries(e).map(([a,f])=>[a,cr(f)]);for(let[a,f]of s){let d=f.historyConfig;if(!d?.enabled)continue;let g=d.subcollection??ir,w=d.ttl??t.defaults?.ttl,S=t.repos?.[a],R;if(f.isGroup){if(!S?.triggerPath){console.warn(`[HistoryTriggers] Skipping collection-group repo "${a}". Provide a triggerPath in the history triggers repos override.`);continue}R=S.triggerPath;}else R=S?.triggerPath??dr(a,f.collectionPath);if(!R)continue;let v=f.systemKeys,b=v[0]??"docId",T=bt(d);r[`${a}_onHistory`]=n(R,async x=>{try{let y=x.data?.before?.data(),u=x.data?.after?.data(),c;if(!y&&u)c="create";else if(y&&!u)c="delete";else if(y&&u)c="update";else return;let l=String(u?.[b]??y?.[b]??x.params?.docId??x.data?.after?.id??x.data?.before?.id??"");if(!l)return;let i=ft(y??{},u??{},{include:d.include,exclude:d.exclude,metaFields:T,systemKeys:v});if(c==="update"&&Object.keys(i).length===0)return;let p=ht(u??y??null,d),m=yt({entityId:l,operation:c,changes:i,meta:p,config:d,ttlOverride:w}),h=x.data?.after?.ref??x.data?.before?.ref;if(!h)return;let E=h.collection(g);await gt(E,m,d,{repoName:a,docId:l,before:y??null,after:u??null});}catch(y){console.error(`[HistoryTriggers] Failed to record history for "${a}":`,y);}});}return r}var Xt="preserve";function Yt(){return Xt}function ur(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function en(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(ur(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 Se(e){return e}function mr(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 yr(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?mr(e?.refCb):[],relationalKeys:e?.relationalKeys,_historyConfig:n,_historySubcollection:n?.enabled?n.subcollection??"history":void 0,_collectionPath:typeof e?.path=="string"?e.path:null}}function tt(e,t){let n=yr(e),r,o=()=>r??(r=t());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 gr(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 hr(e){let t=e.path??e.url??"/",n=t.indexOf("?");return n===-1?t:t.slice(0,n)}var ie=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}=gr(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=hr(t),s=null,a={};for(let g of this.routes){if(g.method!==r)continue;let w=o.match(g.pattern);if(w){s=g,a={},g.paramNames.forEach((S,R)=>{a[S]=decodeURIComponent(w[R+1]??"");});break}}let f=Object.assign(t,{params:a}),d=s?s.handler:this.notFoundHandler;try{await this.runMiddlewareChain(f,n,d);}catch(g){this.errorHandler(g,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 re(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",f=n??process.env.FUNCTION_REGION??"us-central1",d=(process.env.FUNCTION_TARGET??"").replace(/\./g,"-");return `/${a}/${f}/${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 nn(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}He();var ye="__sync_version";var vr=new Set(["ZodOptional","ZodNullable","ZodDefault"]);function Sr(e){let t=e,n=false;for(;;){let r=z(t);if(!vr.has(r))break;(r==="ZodOptional"||r==="ZodNullable")&&(n=true);let o=J(t);if(!o)break;t=o;}return {inner:t,nullable:n}}var Rr={ZodString:"string",ZodNumber:"number",ZodBigInt:"bigint",ZodBoolean:"boolean",ZodDate:"timestamp",ZodEnum:"string",ZodNativeEnum:"string",ZodLiteral:"string"};function an(e,t,n,r,o,s,a,f){for(let[d,g]of Object.entries(e)){let w=n?`${n}__${d}`:d;if(o.has(d)||o.has(w))continue;let{inner:S,nullable:R}=Sr(g),v=z(S),b=r||R;if(v==="ZodObject"){let u=X(S);an(u,t,w,b,o,s,a,f);continue}let T=Rr[v]??"json",x=w===a||d===a,y=s[w]??s[d]??w;f.push({name:y,sqlType:t.mapType(T),nullable:x?false:b,isPrimaryKey:x});}}function nt(e,t,n={}){let{primaryKey:r,exclude:o=[],columnMap:s={}}=n,a=new Set(o),f=X(e),d=[];return an(f,t,"",false,a,s,r,d),d.some(g=>g.name===ye)||d.push({name:ye,sqlType:t.mapType("bigint"),nullable:true,isPrimaryKey:false,description:"Monotonic publish version (Date.now() ms). Internal."}),d}function ln(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(ln)):e}var kr=32,Tr=5e3;function cn(e,t,n,r=new WeakSet,o=0){if(o>kr){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>=Tr)break;let f=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)?cn(a,f,n,r,o+1):n[f]=ln(a);}r.delete(e);}function ze(e,t){let n=new Set(t?.exclude),r=t?.columnMap??{},o={};cn(e,"",o);let s={};for(let[a,f]of Object.entries(o)){if(n.has(a))continue;let d=a.split("__")[0];if(d!==a&&n.has(d))continue;let g=r[a]??(a.includes("__")?r[a.split("__").pop()]:void 0)??a;s[g]=f;}return s}function ue(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';var rr=Object.defineProperty;var et=(e,t)=>()=>(e&&(t=e(e=0)),t);var or=(e,t)=>{for(var n in t)rr(e,n,{get:t[n],enumerable:true});};function z(e){let t=e,n=t._zod?.def?.type;if(n)return wr[n]??`Zod${n.charAt(0).toUpperCase()}${n.slice(1)}`;let r=t._def?.typeName;return r||""}function J(e){let t=e;if(t._zod?.def?.innerType)return t._zod.def.innerType;if(t._def?.innerType)return t._def.innerType}function Ne(e){let t=e,n=t._zod?.def?.in;if(n)return n;if(t._def?.schema)return t._def.schema}function rn(e){let t=e;if(t._zod?.def?.element)return t._zod.def.element;if(t._def?.type)return t._def.type}function on(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 X(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 Fe(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 je(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 Me(e){let t=e;return Array.isArray(t._zod?.def?.values)?t._zod.def.values[0]:t._def?.value}function He(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 sn(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 wr,Be=et(()=>{wr={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 Tn({val:e}){return jsx("span",{class:"text-sm text-base-content/80 font-mono tabular-nums whitespace-nowrap",children:e.toLocaleString()})}function Zr({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 Ee({val:e,mismatch:t}){let n=Tt(e);return t?jsxs("span",{class:"inline-flex items-start gap-0.5",children:[n,jsx(Zr,{message:t})]}):n}function Tt(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(Tn,{val:e});if(typeof e=="object"&&e!==null&&typeof e.toDate=="function")return jsx(Tn,{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:Tt(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:Tt(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 at=et(()=>{});function qe(e){if(!e)return "unknown";let t=Ct(e);switch(z(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 Ct(e){let t=z(e);if(t==="ZodOptional"||t==="ZodNullable"||t==="ZodDefault"){let n=J(e);return n?Ct(n):e}return e}function Ke(e,t){if(!e)return;let n=t.split("."),r=e;for(let o of n){if(!r)return;let s=Ct(r);if(z(s)!=="ZodObject")return;r=X(s)[o];}return r}function Kr(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 Ve(e,t){if(e==="unknown")return null;let n=Kr(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 At=et(()=>{Be();});var On={};or(On,{PanelMany:()=>Qr,PanelOne:()=>Vr,RightPanel:()=>Ot});function Vr({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`,f=An(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 g=e[d],w=f[d],S=w?Ve(w,g):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(Ee,{val:g,mismatch:S})})]})})})]})}function Qr({docs:e,repoName:t,basePath:n,fk:r,fv:o,columns:s,schema:a,pagination:f}){let d=`${n}/${t}?fv_${r}=${encodeURIComponent(o)}`,g=An(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((w,S)=>jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:w},S)),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((w,S)=>{let R=String(w.docId??w.id??""),v=`${n}/${t}/${encodeURIComponent(R)}/edit`;return jsxs("tr",{class:"hover",children:[s.map((b,T)=>{let x=w[b],y=g[b],u=y?Ve(y,x):null;return jsx("td",{class:"align-top py-1.5",children:jsx(Ee,{val:x,mismatch:u})},T)}),jsx("td",{class:"text-right py-1.5",children:jsx("a",{href:v,class:"btn btn-xs btn-ghost",children:"Edit"})})]},S)})})]})}),(f.hasPrev||f.hasNext)&&jsxs("div",{class:"flex justify-center items-center gap-2",children:[f.hasPrev?jsx("button",{type:"button",class:"btn btn-xs btn-outline","data-frs-panel-page":"prev","data-cursor":f.prevCursor,children:"\u2190 Previous"}):jsx("button",{class:"btn btn-xs btn-outline",disabled:true,children:"\u2190 Previous"}),f.hasNext?jsx("button",{type:"button",class:"btn btn-xs btn-outline","data-frs-panel-page":"next","data-cursor":f.nextCursor,children:"Next \u2192"}):jsx("button",{class:"btn btn-xs btn-outline",disabled:true,children:"Next \u2192"})]})]})}function An(e,t){if(!e)return {};let n={};for(let r of t)n[r]=qe(Ke(e,r));return n}var Ot,$t=et(()=>{at();At();Ot=({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"})})})]})]});});function ut(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 pt(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(!pt(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)||!pt(e[s],t[s],n))return false;return true}return false}function ft(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??{},f=new Set([...Object.keys(s),...Object.keys(a)]),d={};for(let g of f){if(r.has(g)||o&&!o.has(g))continue;let w=s[g],S=a[g];pt(w,S)||(d[g]={oldValue:w===void 0?null:w,newValue:S===void 0?null:S,type:{old:ut(w),new:ut(S)}});}return d}var ar=7e5;function yt(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,f)=>f instanceof Timestamp?f.toMillis():f),"utf8")}catch{return 0}};if(o(r.changes)>ar){let s={};for(let[a,f]of Object.entries(r.changes)){let d=o(f.oldValue),g=o(f.newValue);s[a]={oldValue:d>5e4?"[truncated]":f.oldValue,newValue:g>5e4?"[truncated]":f.newValue,type:f.type};}r.changes=s,r._truncated=true;}return r}async function gt(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 ht(e,t){let n=e??{},r={},o=t.meta;if(!o)return r;let s=w=>{if(!w)return;let S=n[w];return S===void 0||S===null?null:String(S)},a=s(o.userId);a!==void 0&&(r.userId=a);let f=s(o.userEmail);f!==void 0&&(r.userEmail=f);let d=s(o.reason);d!==void 0&&(r.reason=d);let g=s(o.comment);if(g!==void 0&&(r.comment=g),o.extras&&o.extras.length>0){let w={},S=false;for(let R of o.extras)R in n&&(w[R]=n[R],S=true);S&&(r.extras=w);}return r}function bt(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 lr(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 cr(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 dr(e,t){return t?`${t}/{docId}`:(console.warn(`[HistoryTriggers] Cannot determine collection path for "${e}". Skipping.`),null)}function Wt(e,t){let{onDocumentWritten:n}=t.deps,r={},o=e?.rawMapping,s=o?Object.entries(o).map(([a,f])=>[a,lr(f)]):Object.entries(e).map(([a,f])=>[a,cr(f)]);for(let[a,f]of s){let d=f.historyConfig;if(!d?.enabled)continue;let g=d.subcollection??ir,w=d.ttl??t.defaults?.ttl,S=t.repos?.[a],R;if(f.isGroup){if(!S?.triggerPath){console.warn(`[HistoryTriggers] Skipping collection-group repo "${a}". Provide a triggerPath in the history triggers repos override.`);continue}R=S.triggerPath;}else R=S?.triggerPath??dr(a,f.collectionPath);if(!R)continue;let v=f.systemKeys,b=v[0]??"docId",T=bt(d);r[`${a}_onHistory`]=n(R,async x=>{try{let y=x.data?.before?.data(),u=x.data?.after?.data(),c;if(!y&&u)c="create";else if(y&&!u)c="delete";else if(y&&u)c="update";else return;let l=String(u?.[b]??y?.[b]??x.params?.docId??x.data?.after?.id??x.data?.before?.id??"");if(!l)return;let i=ft(y??{},u??{},{include:d.include,exclude:d.exclude,metaFields:T,systemKeys:v});if(c==="update"&&Object.keys(i).length===0)return;let p=ht(u??y??null,d),m=yt({entityId:l,operation:c,changes:i,meta:p,config:d,ttlOverride:w}),h=x.data?.after?.ref??x.data?.before?.ref;if(!h)return;let E=h.collection(g);await gt(E,m,d,{repoName:a,docId:l,before:y??null,after:u??null});}catch(y){console.error(`[HistoryTriggers] Failed to record history for "${a}":`,y);}});}return r}var Xt="preserve";function Yt(){return Xt}function ur(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function en(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(ur(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 Se(e){return e}function mr(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 yr(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?mr(e?.refCb):[],relationalKeys:e?.relationalKeys,_historyConfig:n,_historySubcollection:n?.enabled?n.subcollection??"history":void 0,_collectionPath:typeof e?.path=="string"?e.path:null}}function tt(e,t){let n=yr(e),r,o=()=>r??(r=t());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 gr(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 hr(e){let t=e.path??e.url??"/",n=t.indexOf("?");return n===-1?t:t.slice(0,n)}var ie=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}=gr(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=hr(t),s=null,a={};for(let g of this.routes){if(g.method!==r)continue;let w=o.match(g.pattern);if(w){s=g,a={},g.paramNames.forEach((S,R)=>{a[S]=decodeURIComponent(w[R+1]??"");});break}}let f=Object.assign(t,{params:a}),d=s?s.handler:this.notFoundHandler;try{await this.runMiddlewareChain(f,n,d);}catch(g){this.errorHandler(g,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 re(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",f=n??process.env.FUNCTION_REGION??"us-central1",d=(process.env.FUNCTION_TARGET??"").replace(/\./g,"-");return `/${a}/${f}/${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 nn(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}Be();var ye="__sync_version";var vr=new Set(["ZodOptional","ZodNullable","ZodDefault"]);function Sr(e){let t=e,n=false;for(;;){let r=z(t);if(!vr.has(r))break;(r==="ZodOptional"||r==="ZodNullable")&&(n=true);let o=J(t);if(!o)break;t=o;}return {inner:t,nullable:n}}var Rr={ZodString:"string",ZodNumber:"number",ZodBigInt:"bigint",ZodBoolean:"boolean",ZodDate:"timestamp",ZodEnum:"string",ZodNativeEnum:"string",ZodLiteral:"string"};function an(e,t,n,r,o,s,a,f){for(let[d,g]of Object.entries(e)){let w=n?`${n}__${d}`:d;if(o.has(d)||o.has(w))continue;let{inner:S,nullable:R}=Sr(g),v=z(S),b=r||R;if(v==="ZodObject"){let u=X(S);an(u,t,w,b,o,s,a,f);continue}let T=Rr[v]??"json",x=w===a||d===a,y=s[w]??s[d]??w;f.push({name:y,sqlType:t.mapType(T),nullable:x?false:b,isPrimaryKey:x});}}function nt(e,t,n={}){let{primaryKey:r,exclude:o=[],columnMap:s={}}=n,a=new Set(o),f=X(e),d=[];return an(f,t,"",false,a,s,r,d),d.some(g=>g.name===ye)||d.push({name:ye,sqlType:t.mapType("bigint"),nullable:true,isPrimaryKey:false,description:"Monotonic publish version (Date.now() ms). Internal."}),d}function ln(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(ln)):e}var kr=32,Tr=5e3;function cn(e,t,n,r=new WeakSet,o=0){if(o>kr){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>=Tr)break;let f=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)?cn(a,f,n,r,o+1):n[f]=ln(a);}r.delete(e);}function ze(e,t){let n=new Set(t?.exclude),r=t?.columnMap??{},o={};cn(e,"",o);let s={};for(let[a,f]of Object.entries(o)){if(n.has(a))continue;let d=a.split("__")[0];if(d!==a&&n.has(d))continue;let g=r[a]??(a.includes("__")?r[a.split("__").pop()]:void 0)??a;s[g]=f;}return s}function ue(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>
@@ -81,7 +81,7 @@ ${n}
81
81
  ${p("BigQuery",i.bigquery)}
82
82
  ${p("Pub/Sub",i.pubsub)}
83
83
  ${p("Firestore",i.firestore)}
84
- </div>`);pe(b,E);}),async(v,b)=>{await R.handle(v,b);}}var Cr="firestore-sync";function Ar(e,t){return t?`${t}/{docId}`:(console.warn(`[SyncTriggers] Cannot determine collection path for "${e}". Skipping.`),null)}function Or(e){let t=[e?.documentKey,e?.pathKey,e?.createdKey,e?.updatedKey].filter(n=>typeof n=="string");return {isGroup:!!e?.isGroup,documentKey:t[0]??"docId",collectionPath:typeof e?.path=="string"?e.path:null}}function $r(e){return {isGroup:!!e?._isGroup,documentKey:e?._systemKeys?.[0]??"docId",collectionPath:e?.ref?.path??null}}function un(e,t){let{onDocumentCreated:n,onDocumentUpdated:r,onDocumentDeleted:o}=t.deps.firestoreTriggers,s=t.deps.pubsub,a=t?.topicPrefix??Cr,f={},d=new Map;function g(v){let b=d.get(v);return b||(b=s.topic(v),d.set(v,b),b)}async function w(v,b){await g(v).publishMessage({json:b});}let S=e?.rawMapping,R=S?Object.entries(S).map(([v,b])=>[v,Or(b)]):Object.entries(e).map(([v,b])=>[v,$r(b)]);for(let[v,b]of R){let T=t?.repos?.[v],x;if(b.isGroup){if(!T?.triggerPath){console.warn(`[SyncTriggers] Skipping collection-group repo "${v}". Provide a triggerPath in the sync repos config for group collections.`);continue}x=T.triggerPath;}else x=T?.triggerPath??Ar(v,b.collectionPath);if(!x)continue;let y=b.documentKey,u=`${a}-${v}`;f[`${v}_onCreate`]=n(x,async c=>{let l=c.data;if(!l)return;let i=l.data();if(!i)return;let p=String(i[y]??l.id),m=ze(i,{exclude:T?.exclude,columnMap:T?.columnMap}),h={operation:"INSERT",repoName:v,docId:p,data:m,timestamp:new Date().toISOString(),version:Date.now()};await w(u,h);}),f[`${v}_onUpdate`]=r(x,async c=>{let l=c.data?.after;if(!l)return;let i=l.data();if(!i)return;let p=String(i[y]??l.id),m=ze(i,{exclude:T?.exclude,columnMap:T?.columnMap}),h={operation:"UPSERT",repoName:v,docId:p,data:m,timestamp:new Date().toISOString(),version:Date.now()};await w(u,h);}),f[`${v}_onDelete`]=o(x,async c=>{let l=c.data;if(!l)return;let i=l.data(),p=String(i?.[y]??l.id),m={operation:"DELETE",repoName:v,docId:p,data:null,timestamp:new Date().toISOString(),version:Date.now()};await w(u,m);});}return f}function pn(e){let t=e.toUpperCase();switch(t){case "INTEGER":return "INT64";case "FLOAT":return "FLOAT64";case "BOOLEAN":return "BOOL";default:return t}}function fn(e,t){let n=pn(e),r=pn(t);return n===r?true:{INT64:["NUMERIC","BIGNUMERIC","FLOAT64"],NUMERIC:["BIGNUMERIC","FLOAT64"],DATE:["DATETIME","TIMESTAMP"],DATETIME:["TIMESTAMP"]}[n]?.includes(r)??false}var ot=class{constructor(t){this.buffer=[];this.flushing=false;this.flushPromise=null;this.timer=null;this.adapter=t.adapter,this.tableName=t.tableName,this.primaryKey=t.primaryKey,this.batchSize=t.batchSize??100,this.onFlushError=t.onFlushError;let n=t.flushIntervalMs??5e3;n>0&&(this.timer=setInterval(()=>{this.flush();},n),typeof this.timer=="object"&&"unref"in this.timer&&this.timer.unref());}get size(){return this.buffer.length}enqueue(...t){this.buffer.push(...t),this.buffer.length>=this.batchSize&&this.flush();}async flush(){for(;this.flushPromise;)await this.flushPromise;this.buffer.length!==0&&(this.flushing=true,this.flushPromise=this._drain().finally(()=>{this.flushing=false,this.flushPromise=null;}),await this.flushPromise);}async _drain(){for(;this.buffer.length>0&&await this._doFlush(););}async _doFlush(){let t=this.buffer.splice(0,this.batchSize);try{let n=new Map,r=[];for(let s of t)if(s.operation==="DELETE")r.push(s.docId),n.delete(s.docId);else if(s.data){let a=n.get(s.docId);if(!a)n.set(s.docId,s.data);else {let f=Number(a[ye]??0);Number(s.data[ye]??0)>=f&&n.set(s.docId,s.data);}}let o=Array.from(n.values());o.length>0&&await this.adapter.upsertRows(this.tableName,o,this.primaryKey),r.length>0&&await this.adapter.deleteRows(this.tableName,this.primaryKey,r);}catch(n){if(this.onFlushError)await this.onFlushError(t,n);else return this.buffer.unshift(...t),console.error(`[SyncQueue] Flush failed for ${this.tableName}:`,n),false}return true}async shutdown(){this.timer&&(clearInterval(this.timer),this.timer=null),await this.flush();}};var mn=new Set,wt=class extends Error{constructor(n,r,o,s){super(`Schema drift detected on \`${n}\`: column \`${r}\` has type ${o} in BigQuery but the current Zod schema maps it to ${s}. BigQuery cannot safely convert between these types \u2014 to resolve, either (a) keep the BigQuery type and add a transform in your repo to coerce values, (b) rename the field in your Zod schema (creates a new column), or (c) drop & recreate the table.`);this.tableName=n;this.column=r;this.existingType=o;this.desiredType=s;this.name="SchemaTypeMismatchError";}};async function Er(e,t,n,r,o,s,a){if(mn.has(e))return;let f=nt(n,t.dialect,{primaryKey:o,exclude:s,columnMap:a});if(!await t.tableExists(r))await t.createTable({tableName:r,columns:f});else if(t.getTableColumnsWithTypes){let g=await t.getTableColumnsWithTypes(r),w=[];for(let S of f){let R=g.get(S.name);if(R===void 0){w.push(S);continue}if(t.dialect.name==="bigquery"&&!fn(R,S.sqlType))throw new wt(r,S.name,R,S.sqlType)}w.length>0&&(await t.addColumns(r,w),await t.onSchemaChange?.(r));}else {let g=new Set(await t.getTableColumns(r)),w=f.filter(S=>!g.has(S.name));w.length>0&&(await t.addColumns(r,w),await t.onSchemaChange?.(r));}mn.add(e);}function yn(e,t){let{deps:n,adapter:r,batchSize:o=100,flushIntervalMs:s=5e3,autoMigrate:a=false,topicPrefix:f="firestore-sync",maxDlqAttempts:d=5,workerOptions:g,repos:w={}}=t,S=new Map;function R(T,x){let y=S.get(T);if(y)return y;let c=w[T]?.tableName??T,l=`${f}-${T}-dlq`,i=n.pubsub.topic(l),p=false,m=async()=>{if(!p){try{await i.create(),console.info(`[SyncWorker] Created DLQ topic "${l}"`);}catch(E){if(E?.code!==6)throw E}p=true;}},h=async(E,A)=>{console.error(`[SyncWorker] Flush failed for "${T}" (${E.length} events):`,A),await m(),await Promise.all(E.map(k=>{let C=(k.attempts??0)+1;if(d>0&&C>d)return console.error(`[SyncWorker] Dropping event for "${T}" after ${C-1} DLQ attempts:`,{docId:k.docId,operation:k.operation}),Promise.resolve();let $={...k,attempts:C,firstFailedAt:k.firstFailedAt??Date.now()};return i.publishMessage({json:$})}));};return y=new ot({adapter:r,tableName:c,primaryKey:x,batchSize:o,flushIntervalMs:s,onFlushError:h}),S.set(T,y),y}async function v(T){let{repoName:x}=T,y=e[x];if(!y){console.warn(`[SyncWorker] Unknown repo "${x}", skipping event`);return}let u=y._systemKeys?.[0]??y.documentKey??"docId",c=w[x],l=c?.columnMap,i=l?.[u]??u;if(a){let m=y.schema??void 0;if(m){let h=c?.tableName??x;await Er(x,r,m,h,u,c?.exclude,l);}}let p=R(x,i);T.data&&(T.data[ye]=T.version??Date.now()),p.enqueue(T);}function b(T){let x=async y=>{let u=y.data?.message?.json??y.data?.json;if(!u){console.warn("[SyncWorker] Received empty PubSub message");return}await v(u);let c=S.get(u.repoName);c&&await c.flush();};return g?n.pubsubHandler.onMessagePublished({topic:T,...g},x):n.pubsubHandler.onMessagePublished(T,x)}return {handleMessage:v,createHandler:b,queues:S,async shutdown(){let T=[];for(let x of S.values())T.push(x.shutdown());await Promise.all(T);}}}var Pr="firestore-sync";function gn(e){if(typeof e!="function")return e;let t=e,n;return new Proxy({},{get(r,o){return n||(n=t()),n[o]},has(r,o){return n||(n=t()),o in n}})}function hn(e,t){let{deps:n,adapter:r,topicPrefix:o=Pr,batchSize:s,flushIntervalMs:a,autoMigrate:f,admin:d,workerOptions:g,repos:w}=t,S=gn(n.pubsub),R=gn(r),v=un(e,{deps:{firestoreTriggers:n.firestoreTriggers,pubsub:S},topicPrefix:o,repos:w}),b=yn(e,{deps:{pubsubHandler:n.pubsubHandler,pubsub:S},adapter:R,batchSize:s,flushIntervalMs:a,autoMigrate:f,topicPrefix:o,workerOptions:g,repos:w}),T={};for(let u of Object.keys(e))T[`sync_${u}`]=b.createHandler(`${o}-${u}`);let x=null;d&&(x=dn(e,R,b.queues,b.handleMessage,d,w??{},S,o),T.adminsync=d.onRequest?d.httpsOptions?d.onRequest(d.httpsOptions,x):d.onRequest(x):x);let y={functions:{...v,...T},adminHandler:x,handleMessage:b.handleMessage,queues:b.queues,shutdown:b.shutdown};for(let u of ["adminHandler","handleMessage","queues","shutdown"])Object.defineProperty(y,u,{enumerable:false});return y}He();He();function Dr(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/^\s/,"").replace(/^./,t=>t.toUpperCase())}function bn(e){let t=e,n=true,r=false,o;for(;;){let s=z(t);if(s==="ZodOptional")n=false,t=J(t);else if(s==="ZodNullable")n=false,r=true,t=J(t);else if(s==="ZodDefault")n=false,o=on(t),t=J(t);else if(s==="ZodEffects"||s==="ZodPipe"||s==="ZodTransform"){let a=Ne(t);if(!a)break;t=a;}else break}return {inner:t,required:n,nullable:r,defaultValue:o}}function ne(e,t=""){if(z(e)==="ZodObject"){let r=X(e);return Object.entries(r).map(([o,s])=>xn(t?`${t}.${o}`:o,o,s))}return [xn(t||"value",t||"value",e)]}function xn(e,t,n){let{inner:r,required:o,nullable:s,defaultValue:a}=bn(n),f=z(r),d=Dr(t.split(".").pop()??t);switch(f){case "ZodString":{let g=sn(r),w=g.includes("email"),S=g.includes("url");return {name:e,label:d,type:"text",required:o,nullable:s,defaultValue:a,hint:w?"email":S?"url":void 0}}case "ZodNumber":case "ZodBigInt":return {name:e,label:d,type:"number",required:o,nullable:s,defaultValue:a};case "ZodBoolean":return {name:e,label:d,type:"checkbox",required:o,nullable:s,defaultValue:a};case "ZodDate":case "ZodCoerce":return {name:e,label:d,type:"datetime-local",required:o,nullable:s,defaultValue:a};case "ZodEnum":{let g=Fe(r);return {name:e,label:d,type:"select",required:o,nullable:s,defaultValue:a,options:g}}case "ZodNativeEnum":{let g=je(r),w=Object.values(g).filter(S=>typeof S=="string");return {name:e,label:d,type:"select",required:o,nullable:s,defaultValue:a,options:w}}case "ZodLiteral":{let g=String(Me(r)??"");return {name:e,label:d,type:"select",required:o,nullable:s,defaultValue:a,options:[g]}}case "ZodUnion":{let g=Be(r);if(g.length>0&&g.every(v=>z(v)==="ZodLiteral")){let v=g.map(b=>String(Me(b)??""));return {name:e,label:d,type:"select",required:o,nullable:s,defaultValue:a,options:v}}if(g.some(v=>z(v)==="ZodDate"))return {name:e,label:d,type:"datetime-local",required:o,nullable:s,defaultValue:a};let R=g.find(v=>{if(z(v)==="ZodObject"){let b=X(v);return "_latitude"in b&&"_longitude"in b||"latitude"in b&&"longitude"in b}return false});return R?{name:e,label:d,type:"textarea",required:o,nullable:s,defaultValue:a,nested:ne(R,e),hint:"GeoPoint"}:{name:e,label:d,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON"}}case "ZodObject":{let g=ne(r,e);return {name:e,label:d,type:"textarea",required:o,nullable:s,defaultValue:a,nested:g,hint:"JSON object"}}case "ZodArray":{let g=rn(r);if(!g)return {name:e,label:d,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON array"};let{inner:w}=bn(g),S=z(w),R,v,b;switch(S){case "ZodString":R="text";break;case "ZodNumber":case "ZodBigInt":R="number";break;case "ZodBoolean":R="checkbox";break;case "ZodDate":R="datetime-local";break;case "ZodEnum":R="select",v=Fe(w);break;case "ZodNativeEnum":R="select",v=Object.values(je(w)).filter(T=>typeof T=="string");break;case "ZodObject":R="object",b=ne(w);break;default:return {name:e,label:d,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON array"}}return {name:e,label:d,type:"textarea",required:o,nullable:s,defaultValue:a,arrayElementType:R,arrayElementOptions:v,arrayElementFields:b}}default:return {name:e,label:d,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON"}}}function Ze(e,t=0){let n=t>0?`ml-${t*4}`:"",r=`field_${e.name.replace(/\./g,"__")}`,o=e.name,s=e.required?" required":"",a=e.defaultValue==="__null__",f=!a&&e.defaultValue!=null?String(e.defaultValue):"",d=e.nullable&&e.type!=="checkbox"?`<span class="flex items-center gap-1 shrink-0">
84
+ </div>`);pe(b,E);}),async(v,b)=>{await R.handle(v,b);}}var Cr="firestore-sync";function Ar(e,t){return t?`${t}/{docId}`:(console.warn(`[SyncTriggers] Cannot determine collection path for "${e}". Skipping.`),null)}function Or(e){let t=[e?.documentKey,e?.pathKey,e?.createdKey,e?.updatedKey].filter(n=>typeof n=="string");return {isGroup:!!e?.isGroup,documentKey:t[0]??"docId",collectionPath:typeof e?.path=="string"?e.path:null}}function $r(e){return {isGroup:!!e?._isGroup,documentKey:e?._systemKeys?.[0]??"docId",collectionPath:e?.ref?.path??null}}function un(e,t){let{onDocumentCreated:n,onDocumentUpdated:r,onDocumentDeleted:o}=t.deps.firestoreTriggers,s=t.deps.pubsub,a=t?.topicPrefix??Cr,f={},d=new Map;function g(v){let b=d.get(v);return b||(b=s.topic(v),d.set(v,b),b)}async function w(v,b){await g(v).publishMessage({json:b});}let S=e?.rawMapping,R=S?Object.entries(S).map(([v,b])=>[v,Or(b)]):Object.entries(e).map(([v,b])=>[v,$r(b)]);for(let[v,b]of R){let T=t?.repos?.[v],x;if(b.isGroup){if(!T?.triggerPath){console.warn(`[SyncTriggers] Skipping collection-group repo "${v}". Provide a triggerPath in the sync repos config for group collections.`);continue}x=T.triggerPath;}else x=T?.triggerPath??Ar(v,b.collectionPath);if(!x)continue;let y=b.documentKey,u=`${a}-${v}`;f[`${v}_onCreate`]=n(x,async c=>{let l=c.data;if(!l)return;let i=l.data();if(!i)return;let p=String(i[y]??l.id),m=ze(i,{exclude:T?.exclude,columnMap:T?.columnMap}),h={operation:"INSERT",repoName:v,docId:p,data:m,timestamp:new Date().toISOString(),version:Date.now()};await w(u,h);}),f[`${v}_onUpdate`]=r(x,async c=>{let l=c.data?.after;if(!l)return;let i=l.data();if(!i)return;let p=String(i[y]??l.id),m=ze(i,{exclude:T?.exclude,columnMap:T?.columnMap}),h={operation:"UPSERT",repoName:v,docId:p,data:m,timestamp:new Date().toISOString(),version:Date.now()};await w(u,h);}),f[`${v}_onDelete`]=o(x,async c=>{let l=c.data;if(!l)return;let i=l.data(),p=String(i?.[y]??l.id),m={operation:"DELETE",repoName:v,docId:p,data:null,timestamp:new Date().toISOString(),version:Date.now()};await w(u,m);});}return f}function pn(e){let t=e.toUpperCase();switch(t){case "INTEGER":return "INT64";case "FLOAT":return "FLOAT64";case "BOOLEAN":return "BOOL";default:return t}}function fn(e,t){let n=pn(e),r=pn(t);return n===r?true:{INT64:["NUMERIC","BIGNUMERIC","FLOAT64"],NUMERIC:["BIGNUMERIC","FLOAT64"],DATE:["DATETIME","TIMESTAMP"],DATETIME:["TIMESTAMP"]}[n]?.includes(r)??false}var ot=class{constructor(t){this.buffer=[];this.flushing=false;this.flushPromise=null;this.timer=null;this.adapter=t.adapter,this.tableName=t.tableName,this.primaryKey=t.primaryKey,this.batchSize=t.batchSize??100,this.onFlushError=t.onFlushError;let n=t.flushIntervalMs??5e3;n>0&&(this.timer=setInterval(()=>{this.flush();},n),typeof this.timer=="object"&&"unref"in this.timer&&this.timer.unref());}get size(){return this.buffer.length}enqueue(...t){this.buffer.push(...t),this.buffer.length>=this.batchSize&&this.flush();}async flush(){for(;this.flushPromise;)await this.flushPromise;this.buffer.length!==0&&(this.flushing=true,this.flushPromise=this._drain().finally(()=>{this.flushing=false,this.flushPromise=null;}),await this.flushPromise);}async _drain(){for(;this.buffer.length>0&&await this._doFlush(););}async _doFlush(){let t=this.buffer.splice(0,this.batchSize);try{let n=new Map,r=[];for(let s of t)if(s.operation==="DELETE")r.push(s.docId),n.delete(s.docId);else if(s.data){let a=n.get(s.docId);if(!a)n.set(s.docId,s.data);else {let f=Number(a[ye]??0);Number(s.data[ye]??0)>=f&&n.set(s.docId,s.data);}}let o=Array.from(n.values());o.length>0&&await this.adapter.upsertRows(this.tableName,o,this.primaryKey),r.length>0&&await this.adapter.deleteRows(this.tableName,this.primaryKey,r);}catch(n){if(this.onFlushError)await this.onFlushError(t,n);else return this.buffer.unshift(...t),console.error(`[SyncQueue] Flush failed for ${this.tableName}:`,n),false}return true}async shutdown(){this.timer&&(clearInterval(this.timer),this.timer=null),await this.flush();}};var mn=new Set,wt=class extends Error{constructor(n,r,o,s){super(`Schema drift detected on \`${n}\`: column \`${r}\` has type ${o} in BigQuery but the current Zod schema maps it to ${s}. BigQuery cannot safely convert between these types \u2014 to resolve, either (a) keep the BigQuery type and add a transform in your repo to coerce values, (b) rename the field in your Zod schema (creates a new column), or (c) drop & recreate the table.`);this.tableName=n;this.column=r;this.existingType=o;this.desiredType=s;this.name="SchemaTypeMismatchError";}};async function Er(e,t,n,r,o,s,a){if(mn.has(e))return;let f=nt(n,t.dialect,{primaryKey:o,exclude:s,columnMap:a});if(!await t.tableExists(r))await t.createTable({tableName:r,columns:f});else if(t.getTableColumnsWithTypes){let g=await t.getTableColumnsWithTypes(r),w=[];for(let S of f){let R=g.get(S.name);if(R===void 0){w.push(S);continue}if(t.dialect.name==="bigquery"&&!fn(R,S.sqlType))throw new wt(r,S.name,R,S.sqlType)}w.length>0&&(await t.addColumns(r,w),await t.onSchemaChange?.(r));}else {let g=new Set(await t.getTableColumns(r)),w=f.filter(S=>!g.has(S.name));w.length>0&&(await t.addColumns(r,w),await t.onSchemaChange?.(r));}mn.add(e);}function yn(e,t){let{deps:n,adapter:r,batchSize:o=100,flushIntervalMs:s=5e3,autoMigrate:a=false,topicPrefix:f="firestore-sync",maxDlqAttempts:d=5,workerOptions:g,repos:w={}}=t,S=new Map;function R(T,x){let y=S.get(T);if(y)return y;let c=w[T]?.tableName??T,l=`${f}-${T}-dlq`,i=n.pubsub.topic(l),p=false,m=async()=>{if(!p){try{await i.create(),console.info(`[SyncWorker] Created DLQ topic "${l}"`);}catch(E){if(E?.code!==6)throw E}p=true;}},h=async(E,A)=>{console.error(`[SyncWorker] Flush failed for "${T}" (${E.length} events):`,A),await m(),await Promise.all(E.map(k=>{let C=(k.attempts??0)+1;if(d>0&&C>d)return console.error(`[SyncWorker] Dropping event for "${T}" after ${C-1} DLQ attempts:`,{docId:k.docId,operation:k.operation}),Promise.resolve();let $={...k,attempts:C,firstFailedAt:k.firstFailedAt??Date.now()};return i.publishMessage({json:$})}));};return y=new ot({adapter:r,tableName:c,primaryKey:x,batchSize:o,flushIntervalMs:s,onFlushError:h}),S.set(T,y),y}async function v(T){let{repoName:x}=T,y=e[x];if(!y){console.warn(`[SyncWorker] Unknown repo "${x}", skipping event`);return}let u=y._systemKeys?.[0]??y.documentKey??"docId",c=w[x],l=c?.columnMap,i=l?.[u]??u;if(a){let m=y.schema??void 0;if(m){let h=c?.tableName??x;await Er(x,r,m,h,u,c?.exclude,l);}}let p=R(x,i);T.data&&(T.data[ye]=T.version??Date.now()),p.enqueue(T);}function b(T){let x=async y=>{let u=y.data?.message?.json??y.data?.json;if(!u){console.warn("[SyncWorker] Received empty PubSub message");return}await v(u);let c=S.get(u.repoName);c&&await c.flush();};return g?n.pubsubHandler.onMessagePublished({topic:T,...g},x):n.pubsubHandler.onMessagePublished(T,x)}return {handleMessage:v,createHandler:b,queues:S,async shutdown(){let T=[];for(let x of S.values())T.push(x.shutdown());await Promise.all(T);}}}var Pr="firestore-sync";function gn(e){if(typeof e!="function")return e;let t=e,n;return new Proxy({},{get(r,o){return n||(n=t()),n[o]},has(r,o){return n||(n=t()),o in n}})}function hn(e,t){let{deps:n,adapter:r,topicPrefix:o=Pr,batchSize:s,flushIntervalMs:a,autoMigrate:f,admin:d,workerOptions:g,repos:w}=t,S=gn(n.pubsub),R=gn(r),v=un(e,{deps:{firestoreTriggers:n.firestoreTriggers,pubsub:S},topicPrefix:o,repos:w}),b=yn(e,{deps:{pubsubHandler:n.pubsubHandler,pubsub:S},adapter:R,batchSize:s,flushIntervalMs:a,autoMigrate:f,topicPrefix:o,workerOptions:g,repos:w}),T={};for(let u of Object.keys(e))T[`sync_${u}`]=b.createHandler(`${o}-${u}`);let x=null;d&&(x=dn(e,R,b.queues,b.handleMessage,d,w??{},S,o),T.adminsync=d.onRequest?d.httpsOptions?d.onRequest(d.httpsOptions,x):d.onRequest(x):x);let y={functions:{...v,...T},adminHandler:x,handleMessage:b.handleMessage,queues:b.queues,shutdown:b.shutdown};for(let u of ["adminHandler","handleMessage","queues","shutdown"])Object.defineProperty(y,u,{enumerable:false});return y}Be();Be();function Dr(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/^\s/,"").replace(/^./,t=>t.toUpperCase())}function bn(e){let t=e,n=true,r=false,o;for(;;){let s=z(t);if(s==="ZodOptional")n=false,t=J(t);else if(s==="ZodNullable")n=false,r=true,t=J(t);else if(s==="ZodDefault")n=false,o=on(t),t=J(t);else if(s==="ZodEffects"||s==="ZodPipe"||s==="ZodTransform"){let a=Ne(t);if(!a)break;t=a;}else break}return {inner:t,required:n,nullable:r,defaultValue:o}}function ne(e,t=""){if(z(e)==="ZodObject"){let r=X(e);return Object.entries(r).map(([o,s])=>xn(t?`${t}.${o}`:o,o,s))}return [xn(t||"value",t||"value",e)]}function xn(e,t,n){let{inner:r,required:o,nullable:s,defaultValue:a}=bn(n),f=z(r),d=Dr(t.split(".").pop()??t);switch(f){case "ZodString":{let g=sn(r),w=g.includes("email"),S=g.includes("url");return {name:e,label:d,type:"text",required:o,nullable:s,defaultValue:a,hint:w?"email":S?"url":void 0}}case "ZodNumber":case "ZodBigInt":return {name:e,label:d,type:"number",required:o,nullable:s,defaultValue:a};case "ZodBoolean":return {name:e,label:d,type:"checkbox",required:o,nullable:s,defaultValue:a};case "ZodDate":case "ZodCoerce":return {name:e,label:d,type:"datetime-local",required:o,nullable:s,defaultValue:a};case "ZodEnum":{let g=Fe(r);return {name:e,label:d,type:"select",required:o,nullable:s,defaultValue:a,options:g}}case "ZodNativeEnum":{let g=je(r),w=Object.values(g).filter(S=>typeof S=="string");return {name:e,label:d,type:"select",required:o,nullable:s,defaultValue:a,options:w}}case "ZodLiteral":{let g=String(Me(r)??"");return {name:e,label:d,type:"select",required:o,nullable:s,defaultValue:a,options:[g]}}case "ZodUnion":{let g=He(r);if(g.length>0&&g.every(v=>z(v)==="ZodLiteral")){let v=g.map(b=>String(Me(b)??""));return {name:e,label:d,type:"select",required:o,nullable:s,defaultValue:a,options:v}}if(g.some(v=>z(v)==="ZodDate"))return {name:e,label:d,type:"datetime-local",required:o,nullable:s,defaultValue:a};let R=g.find(v=>{if(z(v)==="ZodObject"){let b=X(v);return "_latitude"in b&&"_longitude"in b||"latitude"in b&&"longitude"in b}return false});return R?{name:e,label:d,type:"textarea",required:o,nullable:s,defaultValue:a,nested:ne(R,e),hint:"GeoPoint"}:{name:e,label:d,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON"}}case "ZodObject":{let g=ne(r,e);return {name:e,label:d,type:"textarea",required:o,nullable:s,defaultValue:a,nested:g,hint:"JSON object"}}case "ZodArray":{let g=rn(r);if(!g)return {name:e,label:d,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON array"};let{inner:w}=bn(g),S=z(w),R,v,b;switch(S){case "ZodString":R="text";break;case "ZodNumber":case "ZodBigInt":R="number";break;case "ZodBoolean":R="checkbox";break;case "ZodDate":R="datetime-local";break;case "ZodEnum":R="select",v=Fe(w);break;case "ZodNativeEnum":R="select",v=Object.values(je(w)).filter(T=>typeof T=="string");break;case "ZodObject":R="object",b=ne(w);break;default:return {name:e,label:d,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON array"}}return {name:e,label:d,type:"textarea",required:o,nullable:s,defaultValue:a,arrayElementType:R,arrayElementOptions:v,arrayElementFields:b}}default:return {name:e,label:d,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON"}}}function Ze(e,t=0){let n=t>0?`ml-${t*4}`:"",r=`field_${e.name.replace(/\./g,"__")}`,o=e.name,s=e.required?" required":"",a=e.defaultValue==="__null__",f=!a&&e.defaultValue!=null?String(e.defaultValue):"",d=e.nullable&&e.type!=="checkbox"?`<span class="flex items-center gap-1 shrink-0">
85
85
  <input type="hidden" id="${r}__isnull" name="${o}__isnull" value="${a?"1":""}">
86
86
  <label class="flex items-center gap-1 cursor-pointer select-none text-xs text-base-content/40 hover:text-base-content/70 border border-base-300 rounded px-2 py-1">
87
87
  <input type="checkbox" class="checkbox checkbox-xs" ${a?"checked":""}
@@ -216,7 +216,7 @@ ${n}
216
216
  <button type="submit" class="btn btn-primary btn-sm">${F(r)}</button>
217
217
  <button type="button" class="btn btn-ghost btn-sm" onclick="history.back()">Cancel</button>
218
218
  </div>
219
- </form>`}var _r=new Set(["<","<=",">",">=","!="]),Nr=new Set(["array-contains","array-contains-any"]);function vt(e){return e==="desc"?"DESCENDING":"ASCENDING"}function Fr(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function jr(e,t,n,r,o){let s=[],a=new Set;for(let d of r)if(d.op==="=="||d.op==="in"||d.op==="not-in"){if(a.has(d.field))continue;a.add(d.field),s.push({fieldPath:d.field,order:"ASCENDING"});}for(let d of r)if(Nr.has(d.op)){if(a.has(d.field))continue;a.add(d.field),s.push({fieldPath:d.field,arrayConfig:"CONTAINS"});}for(let d of r)if(_r.has(d.op)){if(a.has(d.field))continue;a.add(d.field);let g=o?.field===d.field?vt(o.dir):"ASCENDING";s.push({fieldPath:d.field,order:g});}if(o&&!a.has(o.field)&&s.push({fieldPath:o.field,order:vt(o.dir)}),s.length===1&&n)return Hr(e,t,s[0]);let f=o&&s.some(d=>d.fieldPath===o.field)?vt(o.dir):"ASCENDING";return s.push({fieldPath:"__name__",order:f}),Mr(e,t,n,s)}function Mr(e,t,n,r,o="(default)"){let s=`projects/${e}/databases/${o}/collectionGroups/${t}/indexes/_`,a=[...kt(1,s),...st(2,n?2:1)];for(let g of r)a.push(...Sn(3,Rn(g)));let f=o==="(default)"?"-default-":o,d=encodeURIComponent(kn(a));return `https://console.firebase.google.com/project/${e}/firestore/databases/${f}/indexes?create_composite=${d}`}function Br(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function St(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function Rt(e,t){return e<<3|t}function kt(e,t){let n=Array.from(new TextEncoder().encode(t));return [Rt(e,2),...St(n.length),...n]}function st(e,t){return [Rt(e,0),...St(t)]}function Sn(e,t){return [Rt(e,2),...St(t.length),...t]}function Rn(e){let t=[...kt(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...st(3,1)):t.push(...st(2,e.order==="DESCENDING"?2:1)),t}function kn(e){let t=String.fromCharCode(...e),n;if(typeof Buffer<"u")n=Buffer.from(e).toString("base64");else if(typeof btoa<"u")n=btoa(t);else throw new Error("No base64 encoder available");return n.replace(/=+$/,"")}function Hr(e,t,n,r="(default)"){let o=`projects/${e}/databases/${r}/collectionGroups/${t}/fields/${n.fieldPath}`,s=[...kt(1,o),...st(2,2),...Sn(3,Rn(n))],a=r==="(default)"?"-default-":r,f=encodeURIComponent(kn(s));return `https://console.firebase.google.com/project/${e}/firestore/databases/${a}/indexes/automatic?create_exemption=${f}`}function zr(e){let t=e,n=[t?.firestore?.projectId,t?.firestore?.app?.options?.projectId,t?.firestore?._settings?.projectId,t?.firestore?.databaseId?.projectId,t?._firestore?.projectId];for(let o of n)if(typeof o=="string"&&o.length>0)return o;return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.FIREBASE_PROJECT_ID||void 0}function Re(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function Le(e,t){let n=e??{},r=Re(e),o;if(r&&(o=n.message?Br(n.message):void 0,!o)){let s=zr(t.ref);if(s){let a=Fr(t.path);o=jr(s,a,t.isGroup,t.filters,t.sort);}}return {type:r?"index":"error",message:r?"This query requires a composite index that does not exist yet.":n.message??"Query failed",indexUrl:o}}at();var Cn=`// \u2500\u2500 Shared helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
219
+ </form>`}var _r=new Set(["<","<=",">",">=","!="]),Nr=new Set(["array-contains","array-contains-any"]);function vt(e){return e==="desc"?"DESCENDING":"ASCENDING"}function Fr(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function jr(e,t,n,r,o){let s=[],a=new Set;for(let d of r)if(d.op==="=="||d.op==="in"||d.op==="not-in"){if(a.has(d.field))continue;a.add(d.field),s.push({fieldPath:d.field,order:"ASCENDING"});}for(let d of r)if(Nr.has(d.op)){if(a.has(d.field))continue;a.add(d.field),s.push({fieldPath:d.field,arrayConfig:"CONTAINS"});}for(let d of r)if(_r.has(d.op)){if(a.has(d.field))continue;a.add(d.field);let g=o?.field===d.field?vt(o.dir):"ASCENDING";s.push({fieldPath:d.field,order:g});}if(o&&!a.has(o.field)&&s.push({fieldPath:o.field,order:vt(o.dir)}),s.length===1&&n)return Br(e,t,s[0]);let f=o&&s.some(d=>d.fieldPath===o.field)?vt(o.dir):"ASCENDING";return s.push({fieldPath:"__name__",order:f}),Mr(e,t,n,s)}function Mr(e,t,n,r,o="(default)"){let s=`projects/${e}/databases/${o}/collectionGroups/${t}/indexes/_`,a=[...kt(1,s),...st(2,n?2:1)];for(let g of r)a.push(...Sn(3,Rn(g)));let f=o==="(default)"?"-default-":o,d=encodeURIComponent(kn(a));return `https://console.firebase.google.com/project/${e}/firestore/databases/${f}/indexes?create_composite=${d}`}function Hr(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function St(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function Rt(e,t){return e<<3|t}function kt(e,t){let n=Array.from(new TextEncoder().encode(t));return [Rt(e,2),...St(n.length),...n]}function st(e,t){return [Rt(e,0),...St(t)]}function Sn(e,t){return [Rt(e,2),...St(t.length),...t]}function Rn(e){let t=[...kt(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...st(3,1)):t.push(...st(2,e.order==="DESCENDING"?2:1)),t}function kn(e){let t=String.fromCharCode(...e),n;if(typeof Buffer<"u")n=Buffer.from(e).toString("base64");else if(typeof btoa<"u")n=btoa(t);else throw new Error("No base64 encoder available");return n.replace(/=+$/,"")}function Br(e,t,n,r="(default)"){let o=`projects/${e}/databases/${r}/collectionGroups/${t}/fields/${n.fieldPath}`,s=[...kt(1,o),...st(2,2),...Sn(3,Rn(n))],a=r==="(default)"?"-default-":r,f=encodeURIComponent(kn(s));return `https://console.firebase.google.com/project/${e}/firestore/databases/${a}/indexes/automatic?create_exemption=${f}`}function zr(e){let t=e,n=[t?.firestore?.projectId,t?.firestore?.app?.options?.projectId,t?.firestore?._settings?.projectId,t?.firestore?.databaseId?.projectId,t?._firestore?.projectId];for(let o of n)if(typeof o=="string"&&o.length>0)return o;return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.FIREBASE_PROJECT_ID||void 0}function Re(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function Le(e,t){let n=e??{},r=Re(e),o;if(r&&(o=n.message?Hr(n.message):void 0,!o)){let s=zr(t.ref);if(s){let a=Fr(t.path);o=jr(s,a,t.isGroup,t.filters,t.sort);}}return {type:r?"index":"error",message:r?"This query requires a composite index that does not exist yet.":n.message??"Query failed",indexUrl:o}}at();var Cn=`// \u2500\u2500 Shared helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
220
220
  function frsGetBasePath() {
221
221
  var root = document.querySelector("[data-frs-panel-root]");
222
222
  var bp = root && root.getAttribute("data-frs-base-path");
@@ -1138,7 +1138,7 @@ function initColumnReorder(table) {
1138
1138
  });
1139
1139
  });
1140
1140
  }
1141
- `;function Ue(){return jsx("script",{dangerouslySetInnerHTML:{__html:Cn}})}$t();function he(e){return "<!DOCTYPE html>"+renderToString(e)}var Jr=["corporate","silk","dark"],Xr=()=>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:Jr.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(Xr,{})})]}),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,f)=>a.href?jsx("li",{children:jsx("a",{href:a.href,children:a.label})},f):jsx("li",{class:"text-base-content/60",children:a.label},f))})}),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(Ot,{basePath:s}),jsx(Ue,{})]})]})};function Et(e,t){return he(jsx(be,{opts:t,children:jsx("div",{dangerouslySetInnerHTML:{__html:e}})}))}function Pt(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 En=[{value:"==",label:"="},{value:"!=",label:"\u2260"},{value:"in",label:"in"},{value:"not-in",label:"not in"}],Yr=[{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"}],eo=[{value:"array-contains",label:"contains"},{value:"array-contains-any",label:"contains any"}];function to(e){switch(e){case "ZodNumber":case "ZodBigInt":case "ZodDate":return Yr;case "ZodBoolean":return En;case "ZodArray":return eo;default:return En}}var xe="__null__";function no(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="${xe}"]');if(!o){o=document.createElement('option');o.value='${xe}';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='${xe}';i.readOnly=true;}i.style.opacity='0.55';}else{i.style.opacity='';if(i.tagName==='SELECT'){var o2=i.querySelector('option[value="${xe}"][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!=='${xe}')?i.dataset._prev:'';}}})(this)`}function ro(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 Qe({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:no(e)}),jsx("span",{children:"\u2205"})]})}function oo({col:e,active:t}){let n=t?.value??"",r=n===xe,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 f=new Set(n.split(",").map(g=>g.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(g=>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:g,checked:f.has(g),"data-enum-group":d,onchange:ro(o,d)}),jsx("span",{children:g})]},g))]})}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(f=>jsx("option",{value:f,selected:n===f,children:f},f)),e.nullable&&jsx("option",{value:xe,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsx(Qe,{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:xe,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsx(Qe,{inputId:o,active:r})]});if(e.zodType==="ZodArray"){let f=t?.op==="array-contains-any";return jsx("input",{id:o,type:"text",name:`fv_${e.name}`,value:n,placeholder:f?"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(Qe,{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(Qe,{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(Qe,{inputId:o,active:r})]})}function Dt({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,f=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:f.map(d=>{let g=to(d.zodType),w=o[d.name],S=w?.op??g[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:[g.length>1?jsx("select",{name:`fo_${d.name}`,class:"select select-sm select-bordered w-20 shrink-0",children:g.map(R=>jsx("option",{value:R.value,selected:R.value===S,children:R.label},R.value))}):jsx("input",{type:"hidden",name:`fo_${d.name}`,value:g[0].value}),jsx(oo,{col:d,active:w})]})]},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 It(e,t,n,r,o,s){let a=n==="create"?`Create ${e}`:`Edit ${e} / ${r??""}`,f=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:f,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}})})})}))}at();At();function _t(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 Pn(e,t,n,r,o){let s=_t(e,r,o);return s.set("cursor",t),s.set("dir",n),`?${s.toString()}`}function so(e,t,n,r){let o=_t(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 ao(e,t,n){return `?${_t(t,n,e).toString()}`}function Nt(e,t,n,r,o,s,a=[],f=[],d=false,g=[],w,S,R,v,b,T,x,y=false){let u=`${r}/${e}`,c=`${u}/create`,l={};if(x)for(let k of n)l[k]=qe(Ke(x,k));let i=(T??[]).filter(k=>true),p=i.length>0,m=d,h=m||p,E=i.map(k=>{let C=Ke(x,k),$=qe(C),P=a.find(O=>O.name===k);return {name:k,type:$,enumValues:P?.enumValues??null,nullable:P?.nullable??false}}),A=[];return x&&(A=ne(x).filter(C=>i.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(Dt,{action:u,columnMeta:a,activeFilters:f,isGroup:v}),R&&jsxs("div",{role:"alert",class:`alert ${R.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:R.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:R.type==="index"?"Composite index required":"Query failed"}),jsx("div",{class:"text-sm",children:R.message})]}),R.indexUrl&&jsx("a",{href:R.indexUrl,target:"_blank",rel:"noopener noreferrer",class:"btn btn-sm btn-outline",children:"Create Index \u2192"})]}),jsxs("div",{class:"flex flex-wrap justify-between items-center mb-4 gap-3","data-frs-toolbar":true,children:[jsxs("div",{class:"flex items-center gap-3",children:[jsxs("span",{class:"text-sm text-base-content/60",children:[t.length,typeof b=="number"&&jsxs(Fragment,{children:[" ","of"," ",jsx("span",{class:"font-semibold text-base-content/80",children:b})]})," ","document",(typeof b=="number"?b:t.length)!==1&&"s"]}),jsxs("div",{class:"flex items-center gap-1.5 text-sm text-base-content/60",children:[jsx("span",{children:"Rows"}),jsx("div",{class:"join",children:[10,25,50,100].map(k=>jsx("a",{href:ao(k,f,w),class:`join-item btn btn-xs ${S===k?"btn-active btn-primary":"btn-outline"}`,children:k},k))})]})]}),jsx("a",{href:c,class:"btn btn-primary btn-sm",children:"+ New"})]}),h&&jsxs("div",{class:"hidden mb-3 alert alert-info py-2 px-3","data-frs-bulk-bar":true,"data-frs-repo":e,"data-frs-total":typeof b=="number"?String(b):"","data-frs-page-size":String(S??t.length),"data-frs-allow-delete":m?"1":"0","data-frs-allow-update":p?"1":"0","data-frs-fields":JSON.stringify(E),"data-frs-filters":JSON.stringify(f),children:[jsxs("div",{class:"flex-1 text-sm",children:[jsx("span",{"data-frs-bulk-summary":true,children:"0 selected"}),typeof b=="number"&&b>t.length&&jsxs("button",{type:"button",class:"ml-3 link text-sm hidden","data-frs-bulk-select-all":true,children:["Select all ",b," matching documents"]}),jsxs("span",{class:"hidden ml-3 italic","data-frs-bulk-all-active":true,children:["All ",b??"?"," matching documents are selected."," ",jsx("button",{type:"button",class:"link","data-frs-bulk-clear":true,children:"Clear selection"})]})]}),jsxs("div",{class:"flex gap-2",children:[p&&jsx("button",{type:"button",class:"btn btn-sm btn-outline","data-frs-bulk-action":"update",children:"Update field\u2026"}),m&&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:[h&&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((k,C)=>{let $=w?.field===k,P=$?w.dir==="asc"?" \u25B2":" \u25BC":"";return jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:jsxs("a",{href:so(k,w,f,S),class:`hover:text-base-content inline-flex items-center gap-0.5${$?" text-primary font-bold":""}`,children:[k,P]})},C)}),g.map((k,C)=>jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:k.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+g.length+1+(h?1:0),class:"text-center py-16 text-base-content/40",children:"No documents found"})}):t.map((k,C)=>{let $=String(k.docId??k.id??""),P=`${r}/${e}/${encodeURIComponent($)}/edit`,O=`${r}/${e}/${encodeURIComponent($)}/delete`;return jsxs("tr",{class:"hover","data-frs-row-id":$,children:[h&&jsx("td",{class:"align-middle py-2",children:jsx("input",{type:"checkbox",class:"checkbox checkbox-xs checkbox-primary","data-frs-select-row":true,value:$,"aria-label":`Select ${$}`})}),n.map((I,j)=>{let N=k[I],D=l[I],K=D?Ve(D,N):null;return jsx("td",{class:"align-top py-2",children:jsx(Ee,{val:N,mismatch:K})},j)}),g.map((I,j)=>{let N=k[I.key];if(N==null||N==="")return jsx("td",{class:"py-2"},`rel-${j}`);let D=I.type==="one"?`${r}/${I.targetRepo}/${encodeURIComponent(String(N))}/edit`:`${r}/${I.targetRepo}?fv_${I.targetKey}=${encodeURIComponent(String(N))}`;return jsx("td",{class:"align-middle py-2",children:jsx("a",{href:D,class:"btn btn-xs btn-ghost btn-outline","data-frs-relation":true,"data-frs-rel-type":I.type,"data-frs-rel-repo":I.targetRepo,"data-frs-rel-fk":I.targetKey,"data-frs-rel-val":String(N),"data-frs-rel-label":I.column,children:I.column})},`rel-${j}`)}),jsx("td",{class:"align-middle text-right whitespace-nowrap py-2",children:jsxs("div",{class:"flex gap-1 justify-end",children:[jsx("a",{href:P,class:"btn btn-xs btn-outline",children:"Edit"}),y&&jsx("a",{href:`${r}/${e}/${encodeURIComponent($)}/history`,class:"btn btn-xs btn-outline",title:"View change history",children:"History"}),d&&jsx("form",{method:"post",action:O,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:Pn(f,o.prevCursor,"prev",w,S),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:Pn(f,o.nextCursor,"next",w,S),class:"btn btn-sm btn-outline",children:"Next \u2192"}):jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"Next \u2192"})]}),typeof b=="number"&&jsxs("div",{class:"text-xs text-base-content/50",children:[b," total document",b!==1?"s":"",f.length>0?" matching filters":""]})]}),h&&p&&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"}),i.map(k=>jsx("option",{value:k,children:k},k))]})]}),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:A.map(k=>jsx("div",{"data-frs-bulk-template-for":k.name,children:Ze(k)},k.name))})]}))}var lo="";function We(e,t){return Et(e,t)}function Ft(e,t){return Pt(e,t)}function jt(e,t,n,r,o,s,a,f,d,g,w,S,R,v,b,T,x,y){return Nt(e,t,n,r,o,s,a,f,d,g,w,S,R,v,b,T,x,y)}function we(e,t,n,r,o,s){return It(e,t,n,r,o,s)}var Mt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function po(){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>=Mt.length*4||(e+=Mt.charAt(r%Mt.length));}}return e}function lt(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 Pe(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 Bt(e,t,n){let r=e.documentKey??"docId",o=Le(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 B(e,t,n=200){e.status(n).set("Content-Type","text/html; charset=utf-8").send(t);}function Ht(e,t){e.status(302).set("Location",t).send("");}function ct(e,t){let n=t.shape,r={};for(let[o,s]of Object.entries(n)){let a=Zt(s),f=z(a),d=f==="ZodObject",g=a,w=false;if(f==="ZodUnion"){let v=Be(a);v.some(T=>z(T)==="ZodDate")&&(w=true);let b=v.find(T=>{if(z(T)==="ZodObject"){let x=X(T);return "latitude"in x&&"longitude"in x}return false});b&&(d=true,g=b);}if(e[o+"__isnull"]==="1"){r[o]=null;continue}if(d){let v={},b=false;for(let[y,u]of Object.entries(e))y.startsWith(`${o}.`)&&(v[y.slice(o.length+1)]=u,b=true);if(b){r[o]=ct(v,g);continue}let T=e[o],x=Array.isArray(T)?T[T.length-1]:T;if(x)try{r[o]=JSON.parse(x);}catch{r[o]=x;}continue}let S=e[o],R=Array.isArray(S)?S[S.length-1]:S;if(R===void 0||R===""){f==="ZodBoolean"&&(r[o]=false);continue}if(w){r[o]=new Date(R);continue}switch(f){case "ZodBoolean":R==="__null__"?r[o]=null:r[o]=R==="true"||R==="on"||R==="1";break;case "ZodNumber":case "ZodBigInt":r[o]=Number(R);break;case "ZodDate":r[o]=new Date(R);break;case "ZodArray":try{r[o]=JSON.parse(R);}catch{r[o]=R;}break;default:if(R.startsWith("{")||R.startsWith("["))try{r[o]=JSON.parse(R);break}catch{}r[o]=R;}}return r}function Dn(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 _n(e){let t=e;for(;;){let n=z(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=J(t);else if(n==="ZodEffects"||n==="ZodPipe"||n==="ZodTransform"){let r=Ne(t);if(!r)return n;t=r;}else return n}}function Zt(e){let t=e;for(;;){let n=z(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=J(t);else if(n==="ZodEffects"||n==="ZodPipe"||n==="ZodTransform"){let r=Ne(t);if(!r)return t;t=r;}else return t}}function Nn(e){let t=e;for(;;){let n=z(t);if(n==="ZodOptional"||n==="ZodNullable")return true;if(n==="ZodDefault"){t=J(t);continue}return false}}function Fn(e){let t=Zt(e),n=z(t);if(n==="ZodEnum"){let r=Fe(t);return r.length>0?r:void 0}if(n==="ZodNativeEnum"){let r=je(t),o=Object.values(r).filter(s=>typeof s=="string");return o.length>0?o:void 0}if(n==="ZodLiteral"){let r=Me(t);return typeof r=="string"?[r]:void 0}}function jn(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 f=Zt(t.shape[o]),d=z(f),g=d==="ZodObject",w=f,S=false;if(d==="ZodUnion"){let R=Be(f);R.some(b=>z(b)==="ZodDate")&&(S=true);let v=R.find(b=>{if(z(b)==="ZodObject"){let T=X(b);return "latitude"in T&&"longitude"in T}return false});v&&(g=true,w=v);}if(g&&typeof a=="object"&&a!==null&&!Array.isArray(a)&&!("_seconds"in a)&&typeof a.toDate!="function"){let R=jn(a,w,s);Object.assign(r,R);}else if(d==="ZodDate"||S){let R=Dn(a);R!==null&&(r[s]=R);}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)&&("_seconds"in a||typeof a.toDate=="function")){let R=Dn(a);r[s]=R??JSON.stringify(a,null,2);}else typeof a=="object"?r[s]=JSON.stringify(a,null,2):r[s]=String(a);}return r}function zt(e,t){return e.map(n=>({...n,defaultValue:t[n.name]??n.defaultValue,nested:n.nested?zt(n.nested,t):void 0}))}function fo(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 f=(s??"").trim();if(!f)continue;let d=e[`fo_${a}`]??"==",g=n.has(d)?d:"==";r.push({field:a,op:g,value:f});}return r}function In(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 Mn(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 f=_n(a);if(f==="ZodObject"){let d=a;for(;;){let w=z(d);if(w==="ZodOptional"||w==="ZodNullable"||w==="ZodDefault")d=J(d);else break}let g=X(d);r.push(...Mn(Object.keys(g),d,s));}else r.push({name:s,zodType:f,nullable:Nn(a),enumValues:Fn(a)});}return r}function mo(e,t){let n=t.split("."),r=e;for(let o of n){for(;;){let a=z(r);if(a==="ZodOptional"||a==="ZodNullable"||a==="ZodDefault")r=J(r);else break}let s=X(r);if(!(o in s))return null;r=s[o];}return r}function Te(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 f=s.slice(0,a),d=s.slice(a+1);r.has(f)||r.set(f,[]),r.get(f).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 f=e.shape[s];for(;;){let d=z(f);if(d==="ZodOptional"||d==="ZodNullable"||d==="ZodDefault")f=J(f);else break}if(z(f)!=="ZodObject"){o[s]=e.shape[s];continue}o[s]=Te(f,a);}return z$1.object(o)}function fe(e,t,n){return re(e,t,n)}function Bn(e,t,n){let r=(u,c)=>{let l=fe(u,t,n),i=Object.values(e).map(p=>({name:p.name,path:p.path}));B(c,Ft(i,l));},o=async(u,c)=>{let l=u.params.repoName;if(!l){B(c,"Bad request",400);return}let i=e[l];if(!i){B(c,"Repository not found",404);return}let p=i.pageSize??25,m=u.query??{},h=m.cursor,E=m.dir==="prev"?"prev":"next",A=m.ob??"",k=m.od==="desc"?"desc":"asc",C=A?{field:A,dir:k}:void 0,$=parseInt(m.ps??""),P=Number.isFinite($)&&$>0?Math.min($,200):p,O=i.listColumns??Object.keys(i.schema.shape),I=i.documentKey??"docId",j=[I,...O.filter(Q=>Q!==I)];C&&(new Set([I,...O]).has(C.field)||(C=void 0));let N=i.filterableFields?(()=>{let Q=[];for(let de of i.filterableFields)(de.includes(".")||O.includes(de))&&Q.push(de);return Q})():O,D=(()=>{let Q=[];for(let de of N)if(de.includes(".")){let Ae=mo(i.schema,de);Q.push({name:de,zodType:Ae?_n(Ae):"ZodString",nullable:Ae?Nn(Ae):false,enumValues:Ae?Fn(Ae):void 0});}else Q.push(...Mn([de],i.schema));return Q})(),K=new Set(D.map(Q=>Q.name)),ce=fo(m,K),q=In(ce),ae;if(h)try{let Q=i.repo.ref;typeof Q.doc=="function"&&(ae=await Q.doc(h).get());}catch{}let[G,Ye]=await Promise.all([i.repo.query.paginate({pageSize:P,cursor:ae,direction:E,...q.length>0?{where:q}:{},...C?{orderBy:[{field:C.field,direction:C.dir}]}:{}}).catch(Q=>({queryError:Le(Q,{ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:ce,sort:C})})),i.repo.aggregate.count(q.length>0?{where:q}:{}).catch(()=>{})]),Ce="queryError"in G,Xn=Ce?[]:G.data,Yn=Ce?"":G.nextCursor?.id??"",er=Ce?"":G.prevCursor?.id??"",tr=Ce?G.queryError:void 0,nr=fe(u,t,n);B(c,jt(i.name,Xn,j,nr,{hasPrev:Ce?false:G.hasPrevPage,hasNext:Ce?false:G.hasNextPage,prevCursor:er,nextCursor:Yn},void 0,D,ce,i.allowDelete??false,i.relationalMeta,C,P,tr,i.isGroup,Ye,i.mutableFields,i.schema,i.historyEnabled));},s=(u,c)=>{let l=u.params.repoName;if(!l){B(c,"Bad request",400);return}let i=e[l];if(!i){B(c,"Repository not found",404);return}let p=fe(u,t,n),m=Te(i.schema,i.createFields),h=ne(m),E=`${p}/${i.name}/create`,A=ge(h,E,"POST","Create document");B(c,we(i.name,A,"create",null,p));},a=async(u,c)=>{let l=u.params.repoName;if(!l){B(c,"Bad request",400);return}let i=e[l];if(!i){B(c,"Repository not found",404);return}let p=fe(u,t,n),m=u.body??{},h=ct(m,i.schema),E=Te(i.schema,i.createFields),A=E.safeParse(h);if(!A.success){let k=ne(E),C=`${p}/${i.name}/create`,$=ge(k,C,"POST","Create document"),P=A.error.issues.map(O=>`${O.path.join(".")}: ${O.message}`).join(", ");B(c,we(i.name,$,"create",null,p,{type:"error",message:`Validation error: ${P}`}),422);return}try{if(i.isGroup&&i.parentKeys&&i.parentKeys.length>0){let k={...A.data};i.createdKey&&(k[i.createdKey]=new Date);let C=i.parentKeys.filter(I=>!k[I]);if(C.length>0)throw new Error(`Missing parent key(s) for subcollection create: ${C.join(", ")}`);let $=i.parentKeys.map(I=>k[I]),P=i.documentKey??"docId",O=k[P]||po();await i.repo.set(...$,O,k);}else await i.repo.create(A.data);Ht(c,`${p}/${i.name}?flash=created`);}catch(k){let C=Te(i.schema,i.createFields),$=ne(C),P=`${p}/${i.name}/create`,O=ge($,P,"POST","Create document");B(c,we(i.name,O,"create",null,p,{type:"error",message:`Save error: ${k.message}`}),500);}},f=async(u,c)=>{let l=u.params.repoName,i=u.params.id;if(!l||!i){B(c,"Bad request",400);return}let p=e[l];if(!p){B(c,"Repository not found",404);return}let m=fe(u,t,n),h=null;try{h=await Pe(p,i);}catch(P){let O=Bt(p,i,P),I=Re(P)?424:500;B(c,We("",{title:`Edit ${p.name} / ${i}`,basePath:m,breadcrumb:[{label:"Repositories",href:m},{label:p.name,href:`${m}/${p.name}`},{label:`Edit ${i}`}],flash:O}),I);return}if(!h){B(c,"Document not found",404);return}let E=jn(h,p.schema),A=Te(p.schema,p.mutableFields),k=zt(ne(A),E),C=`${m}/${p.name}/${encodeURIComponent(i)}/edit`,$=ge(k,C,"POST","Save changes");B(c,we(p.name,$,"edit",i,m));},d=async(u,c)=>{let l=u.params.repoName,i=u.params.id;if(!l||!i){B(c,"Bad request",400);return}let p=e[l];if(!p){B(c,"Repository not found",404);return}let m=fe(u,t,n),h=u.body??{},E=ct(h,p.schema),A=Te(p.schema,p.mutableFields),C=A.partial().safeParse(E);if(!C.success){let $=Object.fromEntries(Object.entries(h).map(([N,D])=>[N,Array.isArray(D)?D.join(","):D??""])),P=zt(ne(A),$),O=`${m}/${p.name}/${encodeURIComponent(i)}/edit`,I=ge(P,O,"POST","Save changes"),j=C.error.issues.map(N=>`${N.path.join(".")}: ${N.message}`).join(", ");B(c,we(p.name,I,"edit",i,m,{type:"error",message:`Validation error: ${j}`}),422);return}try{let $=await Pe(p,i),P=($&&lt($,p.pathKey))??[i];await p.repo.update(...P,C.data),Ht(c,`${m}/${p.name}?flash=updated`);}catch($){let P=Te(p.schema,p.mutableFields),O=ne(P),I=`${m}/${p.name}/${encodeURIComponent(i)}/edit`,j=ge(O,I,"POST","Save changes"),N=Re($)?Bt(p,i,$):{type:"error",message:`Save error: ${$.message}`},D=Re($)?424:500;B(c,we(p.name,j,"edit",i,m,N),D);}},g=async(u,c)=>{let l=u.params.repoName,i=u.params.id;if(!l||!i){B(c,"Bad request",400);return}let p=e[l];if(!p){B(c,"Repository not found",404);return}if(!p.allowDelete){B(c,"Delete is not allowed for this repository",403);return}let m=fe(u,t,n);try{let h=await Pe(p,i),E=(h&&lt(h,p.pathKey))??[i];await p.repo.delete(...E),Ht(c,`${m}/${p.name}?flash=deleted`);}catch(h){let E=Re(h)?Bt(p,i,h):{type:"error",message:`Delete error: ${h.message}`},A=Re(h)?424:500;B(c,We("",{title:`Delete ${p.name} / ${i}`,basePath:m,breadcrumb:[{label:"Repositories",href:m},{label:p.name,href:`${m}/${p.name}`},{label:`Delete ${i}`}],flash:E}),A);}},w=async(u,c)=>{let l=u.params.repoName;if(!l){B(c,"Bad request",400);return}let i=e[l];if(!i){B(c,"Repository not found",404);return}let p=fe(u,t,n),m=u.query,h=m?.type==="many"?"many":"one",E=Math.max(1,Math.min(100,Number(m?.ps??25)||25)),A=i.listColumns??Object.keys(X(i.schema)),{PanelOne:k,PanelMany:C}=await Promise.resolve().then(()=>($t(),On)),{renderToString:$}=await import('hono/jsx/dom/server');if(h==="one"){let D=String(m?.id??"");if(!D){B(c,"<div class='p-6 text-error'>Missing id parameter.</div>",400);return}try{let K=await Pe(i,D),ce=$(k({doc:K,repoName:i.name,basePath:p,schema:i.schema,columns:A}));B(c,ce);}catch(K){B(c,`<div class='p-6 text-error text-sm'>Error: ${K.message}</div>`,500);}return}let P=String(m?.fk??""),O=String(m?.fv??"");if(!P||!O){B(c,"<div class='p-6 text-error'>Missing fk/fv parameters.</div>",400);return}let I=m?.cursor??"",j=m?.dir==="prev"?"prev":"next",N;if(I)try{let D=i.repo.ref;typeof D.doc=="function"&&(N=await D.doc(I).get());}catch{}try{let D=await i.repo.query.paginate({pageSize:E,cursor:N,direction:j,where:[[P,"==",yo(O)]]}),K=$(C({docs:D.data,repoName:i.name,basePath:p,fk:P,fv:O,columns:A,schema:i.schema,pagination:{hasPrev:D.hasPrevPage,hasNext:D.hasNextPage,prevCursor:D.prevCursor?.id??"",nextCursor:D.nextCursor?.id??"",pageSize:E}}));B(c,K);}catch(D){B(c,`<div class='p-6 text-error text-sm'>Error: ${D.message}</div>`,500);}},S=async(u,c)=>{let l=[];for(let i of c){let p;if(u.isGroup||u.parentKeys?.length){let m=await Pe(u,i);p=m?lt(m,u.pathKey):void 0;}p||(p=[i]);try{let m=u.repo.documentRef(...p);m&&l.push(m);}catch{}}return l},R=async(u,c)=>{let l=In(c),i=u.documentKey??"docId",p=[],m;for(;;){let h=await u.repo.query.paginate({pageSize:500,cursor:m,direction:"next",...l.length>0?{where:l}:{}});for(let E of h.data){let A=String(E[i]??E.id??"");A&&p.push(A);}if(!h.hasNextPage||!h.nextCursor)break;m=h.nextCursor;}return p},v=async(u,c)=>{let l=u.params.repoName;if(!l){ee(c,{error:"Bad request"},400);return}let i=e[l];if(!i){ee(c,{error:"Repository not found"},404);return}if(!i.allowDelete){ee(c,{error:"Delete is not allowed for this repository"},403);return}let p=u.body??{};try{let m=await T(i,p);if(m.length===0){ee(c,{deleted:0});return}let h=await S(i,m);for(let E=0;E<h.length;E+=500)await i.repo.bulk.delete(h.slice(E,E+500));ee(c,{deleted:h.length});}catch(m){ee(c,{error:m.message},500);}},b=async(u,c)=>{let l=u.params.repoName;if(!l){ee(c,{error:"Bad request"},400);return}let i=e[l];if(!i){ee(c,{error:"Repository not found"},404);return}let p=u.body??{},m=String(p.field??"");if(!m){ee(c,{error:"Missing 'field'"},400);return}if(!i.mutableFields||!i.mutableFields.includes(m)){ee(c,{error:`Field '${m}' is not bulk-updatable`},403);return}let h=i.schema.shape?.[m],E;if(h){let A=typeof i.schema=="object"&&i.schema&&"constructor"in i.schema&&i.schema.constructor.name.includes("Zod")?i.schema.pick({[m]:true}):void 0;if(!A){ee(c,{error:"Invalid schema structure"},500);return}E=ct(p.formPayload??{},A)[m];let C=h.safeParse(E);if(!C.success){ee(c,{error:`Invalid value for '${m}': ${C.error.message}`},400);return}E=C.data;}try{let A=await T(i,p);if(A.length===0){ee(c,{updated:0});return}let C=(await S(i,A)).map($=>({docRef:$,data:{[m]:E}}));for(let $=0;$<C.length;$+=500)await i.repo.bulk.update(C.slice($,$+500));ee(c,{updated:C.length});}catch(A){ee(c,{error:A.message},500);}};async function T(u,c){if(c.selectAll){let l=x(c.filters,u);return await R(u,l)}return Array.isArray(c.ids)?c.ids.filter(l=>typeof l=="string"&&!!l):[]}function x(u,c){if(!Array.isArray(u))return [];let l=new Set((c.filterableFields??Object.keys(X(c.schema))).map(m=>String(m))),i=new Set(["==","!=","<","<=",">",">=","in","not-in","array-contains","array-contains-any"]),p=[];for(let m of u)m&&typeof m=="object"&&typeof m.field=="string"&&l.has(m.field)&&typeof m.value=="string"&&i.has(String(m.op))&&p.push({field:m.field,op:m.op,value:m.value});return p}return {handleDashboard:r,handleList:o,handleCreateForm:s,handleCreateSubmit:a,handleEditForm:f,handleEditSubmit:d,handleDelete:g,handlePanel:w,handleBulkDelete:v,handleBulkUpdate:b,handleHistory:async(u,c)=>{let l=u.params.repoName,i=u.params.id;if(!l||!i){B(c,"Bad request",400);return}let p=e[l];if(!p){B(c,"Repository not found",404);return}if(!p.historyEnabled||!p.repo.history){B(c,"History not enabled for this repository",404);return}let m=fe(u,t,n),h=p.historySubcollection??"history",E=[i];try{let D=await Pe(p,i),K=D?lt(D,p.pathKey):void 0;K&&K.length>0&&(E=K);}catch{}let A=parseInt(String(u.query?.limit??"")),k=Number.isFinite(A)&&A>0?Math.min(A,500):100,C=[],$;try{C=await p.repo.history.list(...E,{limit:k});}catch(D){$=D.message;}let P=D=>String(D??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),O=D=>{if(D===void 0)return '<span class="opacity-40">undefined</span>';if(D===null)return '<span class="opacity-40">null</span>';if(typeof D=="object")try{return `<code class="text-xs">${P(JSON.stringify(D))}</code>`}catch{return P(String(D))}return P(String(D))},I=D=>D?typeof D.toDate=="function"?D.toDate().toISOString():D instanceof Date?D.toISOString():P(String(D)):"",j=D=>`<span class="badge badge-sm ${D==="create"?"badge-success":D==="delete"?"badge-error":"badge-info"}">${P(D)}</span>`,N="";if(N+='<div class="flex items-center justify-between mb-4">',N+=`<a href="${m}/${p.name}/${encodeURIComponent(i)}/edit" class="btn btn-sm btn-outline">\u2190 Back to edit</a>`,N+=`<a href="${m}/${p.name}" class="btn btn-sm btn-outline">\u2190 Back to list</a>`,N+="</div>",N+=`<p class="text-sm text-base-content/60 mb-4">Subcollection: <code>${P(h)}</code> \xB7 Showing up to ${k} entries.</p>`,$)N+=`<div class="alert alert-error mb-4">${P($)}</div>`;else if(C.length===0)N+='<div class="alert">No history entries found.</div>';else {N+='<div class="overflow-x-auto"><table class="table table-zebra table-sm">',N+="<thead><tr><th>When</th><th>Op</th><th>User</th><th>Reason / Comment</th><th>Changes</th></tr></thead><tbody>";for(let D of C){let K=D.meta??{},ce=[K.reason,K.comment].filter(G=>G!=null&&G!=="").map(G=>P(String(G))).join(" \u2014 "),q="",ae=Object.keys(D.changes??{});ae.length===0?q='<span class="opacity-40">\u2014</span>':q='<ul class="space-y-1">'+ae.map(G=>{let Ye=D.changes[G];return `<li><strong>${P(G)}</strong>: ${O(Ye.oldValue)} \u2192 ${O(Ye.newValue)}</li>`}).join("")+"</ul>",N+="<tr>",N+=`<td class="whitespace-nowrap text-xs font-mono">${P(I(D.historySetAt))}</td>`,N+=`<td>${j(D.operation??"update")}</td>`,N+=`<td class="text-xs">${P(K.userEmail??K.userId??"")}</td>`,N+=`<td class="text-xs">${ce}</td>`,N+=`<td>${q}</td>`,N+="</tr>";}N+="</tbody></table></div>";}B(c,We(N,{title:`History \u2014 ${p.name} / ${i}`,basePath:m,breadcrumb:[{label:"Repositories",href:m},{label:p.name,href:`${m}/${p.name}`},{label:`History ${i}`}]}));}}}function ee(e,t,n=200){e.status(n).set("Content-Type","application/json; charset=utf-8").send(JSON.stringify(t));}function yo(e){return e==="true"?true:e==="false"?false:e!==""&&!isNaN(Number(e))?Number(e):e}var Hn="https://cdn.jsdelivr.net",zn="https://www.gstatic.com",Zn=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${Hn} ${zn}`,`style-src 'self' 'unsafe-inline' ${Hn}`,`connect-src 'self' ${zn} 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 Ge(e={}){let t=e.csp===void 0?Zn: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,f)=>{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 f();}}async function go(e){return typeof e.rawBody=="string"?e.rawBody:Buffer.isBuffer(e.rawBody)?e.rawBody.toString("utf8"):""}function ho(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 Ln(e){let{basePath:t="/",repos:n,parseBody:r=true,securityHeaders:o,auth:s,middleware:a=[],httpsOptions:f}=e,d=t==="/"?"":t.replace(/\/$/,""),g={};for(let[v,b]of Object.entries(n)){let T=b.schema??b.repo.schema??null;if(!T)throw new Error(`[createAdminServer] Repository "${v}" has no Zod schema. Either use createRepositoryConfig(schema)(config) or pass schema: explicitly.`);let x,y,u;if(b.fieldsConfig){let i=b.fieldsConfig;x=[],y=[],u=[];for(let[p,m]of Object.entries(i))for(let h of m)h==="filterable"?x.push(p):h==="mutable"?y.push(p):h==="create"&&u.push(p);x.length===0&&(x=void 0),y.length===0&&(y=void 0),u.length===0&&(u=void 0);}let c=(()=>{let i=b.repo._parentKeys;return i&&i.length>0?i:void 0})();if(c&&u)for(let i of c)u.includes(i)||u.push(i);let l={name:v,path:b.path,repo:b.repo,schema:T,documentKey:b.documentKey??"docId",pathKey:b.repo._pathKey??void 0,isGroup:!!b.repo._isGroup,parentKeys:c,createdKey:b.repo._createdKey??void 0,listColumns:b.listColumns,pageSize:b.pageSize,filterableFields:x,mutableFields:y,createFields:u,allowDelete:b.allowDelete??false,historyEnabled:!!b.repo._historyConfig?.enabled,historySubcollection:(b.repo._historyConfig?.enabled&&b.repo._historySubcollection)??void 0,relationalMeta:(()=>{if(!b.relationalFields||b.relationalFields.length===0)return;let i=b.repo.relationalKeys??{},p=[];for(let m of b.relationalFields){let h=i[m.key];h&&p.push({key:m.key,column:m.column,targetRepo:String(h.repo),targetKey:String(h.key),type:h.type});}return p.length>0?p:void 0})()};g[v]=l;}let w=Bn(g,d,nn(f?.region)),S=new ie;if(o!==false&&S.use(Ge(o===void 0?{}:o)),r&&S.use(async(v,b,T)=>{let x=v,y=String(x.headers?.["content-type"]??"");if(y.includes("application/x-www-form-urlencoded")){let u=await go(x);v.body=ho(u);}else if(y.includes("application/json")&&typeof x.body=="string")try{v.body=JSON.parse(x.body);}catch{}await T();}),s)if(me(s)){for(let v of s.routes){let b=`${d}${v.path}`;v.method==="GET"?S.get(b,v.handler):S.post(b,v.handler);}S.use(s.middleware);}else if(typeof s=="function")S.use(s);else {let v=s.realm??"Admin",b="Basic "+Buffer.from(`${s.username}:${s.password}`).toString("base64");S.use((T,x,y)=>{if((T.headers?.authorization??"")!==b){x.status(401).set("WWW-Authenticate",`Basic realm="${v}"`).set("Content-Type","text/plain").send("Unauthorized");return}y();});}for(let v of a)S.use(v);S.get(`${d}/`,w.handleDashboard),S.get(`${d}`,w.handleDashboard),S.get(`${d}/:repoName/_panel`,w.handlePanel),S.post(`${d}/:repoName/_bulk/delete`,w.handleBulkDelete),S.post(`${d}/:repoName/_bulk/update`,w.handleBulkUpdate),S.get(`${d}/:repoName`,w.handleList),S.get(`${d}/:repoName/create`,w.handleCreateForm),S.post(`${d}/:repoName/create`,w.handleCreateSubmit),S.get(`${d}/:repoName/:id/edit`,w.handleEditForm),S.post(`${d}/:repoName/:id/edit`,w.handleEditSubmit),S.get(`${d}/:repoName/:id/history`,w.handleHistory),S.post(`${d}/:repoName/:id/delete`,w.handleDelete);let R=async(v,b)=>{await S.handle(v,b);};return f&&(R.httpsOptions=f),R}function qt(e,t,n=200){let r=Se(t);e.status(n).set("Content-Type","application/json; charset=utf-8").send(JSON.stringify(r));}function De(e,t,n,r=200){qt(e,{success:true,data:t,meta:n},r);}function U(e,t,n=400){qt(e,{success:false,error:t},n);}function Lt(e,t,n,r,o){let s=Le(t,n),a=s.type==="index",f=a?424:500,g={success:false,error:a?s.message:o&&t instanceof Error?t.message:r};a&&(g.errorType="index",s.indexUrl&&(g.indexUrl=s.indexUrl)),qt(e,g,f);}var Ut="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function xo(){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>=Ut.length*4||(e+=Ut.charAt(r%Ut.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=>en(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 wo(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 f=a.split(".")[0];f&&r[f]&&(o[f]=r[f]);}return z$1.object(o)}function Un(e,t,n,r=false,o=[]){try{let s=wo(e,n,o),a=r?s.partial():s;return {success:!0,data:(Yt()==="normalize"?Ie(a):a).parse(t)}}catch(s){return s instanceof z$1.ZodError?{success:false,error:`Validation failed: ${s.issues.map(f=>`${f.path.join(".")}: ${f.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}function vo(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 f=Array.isArray(a)?a[0]:a;if(f===void 0||f==="")continue;let d=s.match(/^(\w+)__(\w+)$/),g,w="==";if(d&&d[1]&&d[2]){g=d[1];let R=d[2];if(o[R])w=o[R];else continue}else if(!d)g=s;else continue;if(r&&!r.has(g))continue;let S=f;w==="in"||w==="not-in"||w==="array-contains-any"?S=f.split(",").map(R=>qn(R.trim())):S=qn(f),n.push({field:g,op:w,value:S});}return n}function qn(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 dt(e){return e?{docId:e.id}:null}async function Kn(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 Vn(e,t,n,r=false){async function o(y,u,c,l){if(!r)return true;let i=u.rules?.[c];if(!i)return U(y,`Operation "${c}" is not allowed for this repository`,403),false;try{return await i(l)?!0:(U(y,"Forbidden",403),!1)}catch(p){let m=n&&p instanceof Error?p.message:"Forbidden";return U(y,m,403),false}}async function s(y,u,c,l){if(!r)return l;let i=y.rules?.filter;if(!i)return l;let p=[];for(let m of l)try{await i({user:u,doc:m,params:c})&&p.push(m);}catch{}return p}function a(y){return y?.user??null}function f(y,u){return !y||!e[y]?(U(u,`Repository "${y}" not found`,404),null):e[y]}function d(y,u){if(!u)return;let c=y[u];if(typeof c!="string"||!c)return;let l=c.split("/").filter(Boolean),i=[];for(let p=1;p<l.length;p+=2)i.push(l[p]);return i.length>0?i:void 0}async function g(y,u){let c=`by${y.documentKey.charAt(0).toUpperCase()}${y.documentKey.slice(1)}`,l=y.repo.get[c];if(typeof l=="function")try{let p=await l(u);if(p)return p}catch{}return (await y.repo.query.by({where:[[y.documentKey,"==",u]],limit:1}))[0]??null}async function w(y,u){let c=y.params||{},l=f(c.repoName,u);if(!l)return;let i=a(y);if(!await o(u,l,"list",{user:i,query:y.query??{},params:c}))return;let p=[],m;try{let h=y.query??{},E=Math.min(Number(h.pageSize)||l.pageSize,100),A=h.cursor,k=h.direction?.toLowerCase()==="prev"?"prev":"next",C=h.orderBy,$=h.orderDir?.toLowerCase()==="desc"?"desc":"asc",P=h.select,O=P?P.split(",").map(q=>q.trim()):void 0,I;l.allowedIncludes&&h.includes&&(I=(typeof h.includes=="string"?h.includes.split(",").map(ae=>ae.trim()):Array.isArray(h.includes)?h.includes:[]).filter(ae=>typeof ae=="string"&&l.allowedIncludes.includes(ae)),I?.length===0&&(I=void 0));let j=vo(h,l.filterableFields);p=j.map(q=>({field:q.field,op:q.op,value:String(q.value??"")})),C&&(m={field:C,dir:$});let N={pageSize:E,direction:k};if(A)try{let q=typeof A=="string"?JSON.parse(A):A;N.cursor=await Kn(l,q);}catch{}if(C){if(l.orderableFields&&!l.orderableFields.includes(C)){U(u,`Field not orderable: ${C}`,400);return}N.orderBy=[{field:C,direction:$}];}j.length>0&&(N.where=j.map(q=>[q.field,q.op,q.value])),O&&(N.select=O),I&&(N.include=I);let D=await l.repo.query.paginate(N),ce={items:await s(l,a(y),c,D.data),hasNextPage:D.hasNextPage,hasPrevPage:D.hasPrevPage,nextCursor:dt(D.nextCursor),prevCursor:dt(D.prevCursor)};De(u,ce,{pageSize:E,hasMore:D.hasNextPage});}catch(h){Lt(u,h,{ref:l.repo.ref,path:l.path,isGroup:!!l.isGroup,filters:p,sort:m},"Failed to fetch documents",n);}}async function S(y,u){let c=y.params||{},l=f(c.repoName,u);if(!l)return;let i=a(y);if(!await o(u,l,"list",{user:i,query:y.body??{},params:c}))return;let p=[],m;try{let h=y.body??{},E=Math.min(h.pageSize||l.pageSize,100),A=h.direction==="prev"?"prev":"next";h.where&&(p=h.where.map(O=>({field:String(O[0]),op:O[1],value:String(O[2]??"")}))),h.orderBy&&h.orderBy[0]&&(m={field:h.orderBy[0].field,dir:h.orderBy[0].direction==="desc"?"desc":"asc"});let k={pageSize:E,direction:A};if(h.cursor)try{let O=typeof h.cursor=="string"?JSON.parse(h.cursor):h.cursor;k.cursor=await Kn(l,O);}catch{}if(l.allowedIncludes&&h.includes&&h.includes.length>0){let O=h.includes.filter(I=>typeof I=="string"?l.allowedIncludes.includes(I):typeof I=="object"&&I!==null&&"relation"in I&&typeof I.relation=="string"?l.allowedIncludes.includes(I.relation):!1);O.length>0&&(k.include=O);}if(h.where&&h.where.length>0){if(l.filterableFields){let O=new Set(l.filterableFields),I=h.where.filter(j=>!O.has(j[0]));if(I.length>0){U(u,`Fields not filterable: ${I.map(j=>j[0]).join(", ")}`,400);return}}k.where=h.where;}if(h.orWhere&&h.orWhere.length>0){if(l.filterableFields){let O=new Set(l.filterableFields),I=h.orWhere.filter(j=>!O.has(j[0]));if(I.length>0){U(u,`Fields not filterable: ${I.map(j=>j[0]).join(", ")}`,400);return}}k.orWhere=h.orWhere;}if(h.orWhereGroups&&h.orWhereGroups.length>0){if(l.filterableFields){let O=new Set(l.filterableFields);for(let I of h.orWhereGroups){let j=I.filter(N=>!O.has(N[0]));if(j.length>0){U(u,`Fields not filterable: ${j.map(N=>N[0]).join(", ")}`,400);return}}}k.orWhereGroups=h.orWhereGroups;}if(h.orderBy&&h.orderBy.length>0){if(l.orderableFields){let O=new Set(l.orderableFields),I=h.orderBy.filter(j=>!O.has(j.field));if(I.length>0){U(u,`Fields not orderable: ${I.map(j=>j.field).join(", ")}`,400);return}}k.orderBy=h.orderBy;}h.select&&h.select.length>0&&(k.select=h.select);let C=await l.repo.query.paginate(k),P={items:await s(l,a(y),c,C.data),hasNextPage:C.hasNextPage,hasPrevPage:C.hasPrevPage,nextCursor:dt(C.nextCursor),prevCursor:dt(C.prevCursor)};De(u,P,{pageSize:E,hasMore:C.hasNextPage});}catch(h){Lt(u,h,{ref:l.repo.ref,path:l.path,isGroup:!!l.isGroup,filters:p,sort:m},"Failed to query documents",n);}}async function R(y,u){let c=y.params||{},l=f(c.repoName,u);if(!l)return;let i=c.id;if(!i){U(u,"Document ID required",400);return}try{let p=await g(l,i);if(!p){U(u,"Document not found",404);return}let m=a(y);if(!await o(u,l,"get",{user:m,doc:p,params:c}))return;if(r&&l.rules?.filter)try{if(!await l.rules.filter({user:m,doc:p,params:c})){U(u,"Document not found",404);return}}catch{U(u,"Document not found",404);return}De(u,p);}catch(p){Lt(u,p,{ref:l.repo.ref,path:l.path,isGroup:!!l.isGroup,filters:[{field:l.documentKey,op:"==",value:i}]},"Failed to fetch document",n);}}async function v(y,u){let c=y.params||{},l=f(c.repoName,u);if(l)try{let i=y.body??{},p=a(y);if(!await o(u,l,"create",{user:p,body:i,params:c}))return;let m=Un(l.schema,i,l.createFields,!1,l.systemKeys);if(!m.success){U(u,m.error,400);return}if(l.validate){let E=await l.validate(m.data,"create");if(E){U(u,E,400);return}}let h;if(l.isGroup&&l.parentKeys&&l.parentKeys.length>0){let E={...m.data};l.createdKey&&(E[l.createdKey]=new Date);let A=l.parentKeys.filter($=>!E[$]);if(A.length>0){U(u,`Missing parent key(s) for subcollection create: ${A.join(", ")}`,400);return}let k=l.parentKeys.map($=>E[$]),C=E[l.documentKey]||xo();h=await l.repo.set(...k,C,E);}else h=await l.repo.create(m.data);De(u,h,void 0,201);}catch(i){let p=n&&i instanceof Error?i.message:"Failed to create document";U(u,p,500);}}async function b(y,u,c){let l=y.params||{},i=f(l.repoName,u);if(!i)return;let p=l.id;if(!p){U(u,"Document ID required",400);return}try{let m=y.body??{},h=await g(i,p);if(!h){U(u,"Document not found",404);return}let E=a(y);if(!await o(u,i,"update",{user:E,doc:h,body:m,params:l}))return;let A=Un(i.schema,m,i.mutableFields,c,i.systemKeys);if(!A.success){U(u,A.error,400);return}if(i.validate){let $=await i.validate(A.data,"update");if($){U(u,$,400);return}}let k=d(h,i.pathKey)??[p],C=await i.repo.update(...k,A.data);De(u,C);}catch(m){let h=n&&m instanceof Error?m.message:"Failed to update document";U(u,h,500);}}async function T(y,u){let c=y.params||{},l=f(c.repoName,u);if(!l)return;if(!l.allowDelete){U(u,"Delete not allowed for this repository",403);return}let i=c.id;if(!i){U(u,"Document ID required",400);return}try{let p=await g(l,i);if(!p){U(u,"Document not found",404);return}let m=a(y);if(!await o(u,l,"delete",{user:m,doc:p,params:c}))return;let h=d(p,l.pathKey)??[i];await l.repo.delete(...h),De(u,{deleted:!0});}catch(p){let m=n&&p instanceof Error?p.message:"Failed to delete document";U(u,m,500);}}function x(y,u){u.status(204).set("Access-Control-Allow-Methods","GET, POST, PUT, PATCH, DELETE, OPTIONS").set("Access-Control-Allow-Headers","Content-Type, Authorization").set("Access-Control-Max-Age","86400").send("");}return {handleList:w,handleQuery:S,handleGet:R,handleCreate:v,handleUpdate:b,handleDelete:T,handleOptions:x}}function Kt(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 se(e){return {$ref:`#/components/schemas/${e}`}}function te(e){return {description:e,content:{"application/json":{schema:se("ErrorResponse")}}}}function Xe(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function Qn(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 So(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 Ro(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 ko(){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 To(e,t,n,r,o){let s={},a=e.name,f=`${t}/${e.name}`,d=`${f}/{${e.documentKey}}`,g={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};s[f]={get:{operationId:`list${ve(e.name)}`,summary:`List ${e.name} (paginated)`,tags:[a],parameters:[...So(e),...Ro(e)],responses:{200:Qn(se(n)),500:te("Internal server error")}},post:{operationId:`create${ve(e.name)}`,summary:`Create a ${le(e.name)}`,tags:[a],requestBody:{required:true,content:{"application/json":{schema:se(r??n)}}},responses:{201:Xe("Document created",se(n)),400:te("Validation error"),500:te("Internal server error")}}},s[`${f}/query`]={post:{operationId:`query${ve(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[a],requestBody:{required:true,content:{"application/json":{schema:se("QueryRequestBody")}}},responses:{200:Qn(se(n)),400:te("Invalid query"),500:te("Internal server error")}}};let w={};return w.get={operationId:`get${ve(le(e.name))}`,summary:`Get a single ${le(e.name)}`,tags:[a],parameters:[g],responses:{200:Xe("Document found",se(n)),404:te("Document not found"),500:te("Internal server error")}},w.put={operationId:`update${ve(le(e.name))}`,summary:`Update a ${le(e.name)} (full replace)`,tags:[a],parameters:[g],requestBody:{required:true,content:{"application/json":{schema:se(o??n)}}},responses:{200:Xe("Document updated",se(n)),400:te("Validation error"),404:te("Document not found"),500:te("Internal server error")}},w.patch={operationId:`patch${ve(le(e.name))}`,summary:`Partially update a ${le(e.name)}`,tags:[a],parameters:[g],requestBody:{required:true,content:{"application/json":{schema:{allOf:[se(o??n)],description:"All fields are optional for partial updates"}}}},responses:{200:Xe("Document patched",se(n)),400:te("Validation error"),404:te("Document not found"),500:te("Internal server error")}},e.allowDelete&&(w.delete={operationId:`delete${ve(le(e.name))}`,summary:`Delete a ${le(e.name)}`,tags:[a],parameters:[g],responses:{200:Xe("Document deleted",{type:"object",properties:{id:{type:"string"}}}),404:te("Document not found"),500:te("Internal server error")}}),s[d]=w,s}function Qt(e,t,n={}){let{title:r="CRUD API",version:o="1.0.0",description:s,servers:a,auth:f=false}=n,d=t==="/"?"":t.replace(/\/$/,""),g={},w={},S=[];g.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string"}},required:["success","error"]},g.QueryRequestBody=ko();for(let[T,x]of Object.entries(e)){let y=ve(le(T)),u=`${y}Create`,c=`${y}Update`;g[y]=Kt(x.schema);let l=A=>{let k=A&&A.length>0?A:Object.keys(x.schema.shape),C={};for(let $ of k){let P=$.split(".")[0];P&&x.schema.shape[P]&&!x.systemKeys.includes(P)&&(C[P]=x.schema.shape[P]);}return C},i=null,p=l(x.createFields);Object.keys(p).length>0&&(g[u]=Kt(z$1.object(p)),i=u);let m=null,h=l(x.mutableFields);Object.keys(h).length>0&&(g[c]=Kt(z$1.object(h)),m=c);let E=To(x,d,y,i,m);Object.assign(w,E),S.push({name:T,description:`Operations on ${T} (collection: ${x.path})`});}let R={},v;return f==="basic"?(R.basicAuth={type:"http",scheme:"basic"},v=[{basicAuth:[]}]):f==="bearer"&&(R.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},v=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:r,version:o,...s?{description:s}:{}},...a&&a.length>0?{servers:a}:{},paths:w,components:{schemas:g,...Object.keys(R).length>0?{securitySchemes:R}:{}},...v?{security:v}:{},tags:S}}function ve(e){return e.charAt(0).toUpperCase()+e.slice(1)}function le(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}function Co(e,t){return `<!DOCTYPE html>
1141
+ `;function Ue(){return jsx("script",{dangerouslySetInnerHTML:{__html:Cn}})}$t();function he(e){return "<!DOCTYPE html>"+renderToString(e)}var Jr=["corporate","silk","dark"],Xr=()=>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:Jr.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(Xr,{})})]}),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,f)=>a.href?jsx("li",{children:jsx("a",{href:a.href,children:a.label})},f):jsx("li",{class:"text-base-content/60",children:a.label},f))})}),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(Ot,{basePath:s}),jsx(Ue,{})]})]})};function Et(e,t){return he(jsx(be,{opts:t,children:jsx("div",{dangerouslySetInnerHTML:{__html:e}})}))}function Pt(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 En=[{value:"==",label:"="},{value:"!=",label:"\u2260"},{value:"in",label:"in"},{value:"not-in",label:"not in"}],Yr=[{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"}],eo=[{value:"array-contains",label:"contains"},{value:"array-contains-any",label:"contains any"}];function to(e){switch(e){case "ZodNumber":case "ZodBigInt":case "ZodDate":return Yr;case "ZodBoolean":return En;case "ZodArray":return eo;default:return En}}var xe="__null__";function no(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="${xe}"]');if(!o){o=document.createElement('option');o.value='${xe}';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='${xe}';i.readOnly=true;}i.style.opacity='0.55';}else{i.style.opacity='';if(i.tagName==='SELECT'){var o2=i.querySelector('option[value="${xe}"][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!=='${xe}')?i.dataset._prev:'';}}})(this)`}function ro(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 Qe({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:no(e)}),jsx("span",{children:"\u2205"})]})}function oo({col:e,active:t}){let n=t?.value??"",r=n===xe,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 f=new Set(n.split(",").map(g=>g.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(g=>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:g,checked:f.has(g),"data-enum-group":d,onchange:ro(o,d)}),jsx("span",{children:g})]},g))]})}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(f=>jsx("option",{value:f,selected:n===f,children:f},f)),e.nullable&&jsx("option",{value:xe,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsx(Qe,{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:xe,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsx(Qe,{inputId:o,active:r})]});if(e.zodType==="ZodArray"){let f=t?.op==="array-contains-any";return jsx("input",{id:o,type:"text",name:`fv_${e.name}`,value:n,placeholder:f?"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(Qe,{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(Qe,{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(Qe,{inputId:o,active:r})]})}function Dt({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,f=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:f.map(d=>{let g=to(d.zodType),w=o[d.name],S=w?.op??g[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:[g.length>1?jsx("select",{name:`fo_${d.name}`,class:"select select-sm select-bordered w-20 shrink-0",children:g.map(R=>jsx("option",{value:R.value,selected:R.value===S,children:R.label},R.value))}):jsx("input",{type:"hidden",name:`fo_${d.name}`,value:g[0].value}),jsx(oo,{col:d,active:w})]})]},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 It(e,t,n,r,o,s){let a=n==="create"?`Create ${e}`:`Edit ${e} / ${r??""}`,f=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:f,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}})})})}))}at();At();function _t(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 Pn(e,t,n,r,o){let s=_t(e,r,o);return s.set("cursor",t),s.set("dir",n),`?${s.toString()}`}function so(e,t,n,r){let o=_t(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 ao(e,t,n){return `?${_t(t,n,e).toString()}`}function Nt(e,t,n,r,o,s,a=[],f=[],d=false,g=[],w,S,R,v,b,T,x,y=false){let u=`${r}/${e}`,c=`${u}/create`,l={};if(x)for(let k of n)l[k]=qe(Ke(x,k));let i=(T??[]).filter(k=>true),p=i.length>0,m=d,h=m||p,E=i.map(k=>{let C=Ke(x,k),$=qe(C),P=a.find(O=>O.name===k);return {name:k,type:$,enumValues:P?.enumValues??null,nullable:P?.nullable??false}}),A=[];return x&&(A=ne(x).filter(C=>i.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(Dt,{action:u,columnMeta:a,activeFilters:f,isGroup:v}),R&&jsxs("div",{role:"alert",class:`alert ${R.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:R.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:R.type==="index"?"Composite index required":"Query failed"}),jsx("div",{class:"text-sm",children:R.message})]}),R.indexUrl&&jsx("a",{href:R.indexUrl,target:"_blank",rel:"noopener noreferrer",class:"btn btn-sm btn-outline",children:"Create Index \u2192"})]}),jsxs("div",{class:"flex flex-wrap justify-between items-center mb-4 gap-3","data-frs-toolbar":true,children:[jsxs("div",{class:"flex items-center gap-3",children:[jsxs("span",{class:"text-sm text-base-content/60",children:[t.length,typeof b=="number"&&jsxs(Fragment,{children:[" ","of"," ",jsx("span",{class:"font-semibold text-base-content/80",children:b})]})," ","document",(typeof b=="number"?b:t.length)!==1&&"s"]}),jsxs("div",{class:"flex items-center gap-1.5 text-sm text-base-content/60",children:[jsx("span",{children:"Rows"}),jsx("div",{class:"join",children:[10,25,50,100].map(k=>jsx("a",{href:ao(k,f,w),class:`join-item btn btn-xs ${S===k?"btn-active btn-primary":"btn-outline"}`,children:k},k))})]})]}),jsx("a",{href:c,class:"btn btn-primary btn-sm",children:"+ New"})]}),h&&jsxs("div",{class:"hidden mb-3 alert alert-info py-2 px-3","data-frs-bulk-bar":true,"data-frs-repo":e,"data-frs-total":typeof b=="number"?String(b):"","data-frs-page-size":String(S??t.length),"data-frs-allow-delete":m?"1":"0","data-frs-allow-update":p?"1":"0","data-frs-fields":JSON.stringify(E),"data-frs-filters":JSON.stringify(f),children:[jsxs("div",{class:"flex-1 text-sm",children:[jsx("span",{"data-frs-bulk-summary":true,children:"0 selected"}),typeof b=="number"&&b>t.length&&jsxs("button",{type:"button",class:"ml-3 link text-sm hidden","data-frs-bulk-select-all":true,children:["Select all ",b," matching documents"]}),jsxs("span",{class:"hidden ml-3 italic","data-frs-bulk-all-active":true,children:["All ",b??"?"," matching documents are selected."," ",jsx("button",{type:"button",class:"link","data-frs-bulk-clear":true,children:"Clear selection"})]})]}),jsxs("div",{class:"flex gap-2",children:[p&&jsx("button",{type:"button",class:"btn btn-sm btn-outline","data-frs-bulk-action":"update",children:"Update field\u2026"}),m&&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:[h&&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((k,C)=>{let $=w?.field===k,P=$?w.dir==="asc"?" \u25B2":" \u25BC":"";return jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:jsxs("a",{href:so(k,w,f,S),class:`hover:text-base-content inline-flex items-center gap-0.5${$?" text-primary font-bold":""}`,children:[k,P]})},C)}),g.map((k,C)=>jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:k.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+g.length+1+(h?1:0),class:"text-center py-16 text-base-content/40",children:"No documents found"})}):t.map((k,C)=>{let $=String(k.docId??k.id??""),P=`${r}/${e}/${encodeURIComponent($)}/edit`,O=`${r}/${e}/${encodeURIComponent($)}/delete`;return jsxs("tr",{class:"hover","data-frs-row-id":$,children:[h&&jsx("td",{class:"align-middle py-2",children:jsx("input",{type:"checkbox",class:"checkbox checkbox-xs checkbox-primary","data-frs-select-row":true,value:$,"aria-label":`Select ${$}`})}),n.map((I,j)=>{let N=k[I],D=l[I],K=D?Ve(D,N):null;return jsx("td",{class:"align-top py-2",children:jsx(Ee,{val:N,mismatch:K})},j)}),g.map((I,j)=>{let N=k[I.key];if(N==null||N==="")return jsx("td",{class:"py-2"},`rel-${j}`);let D=I.type==="one"?`${r}/${I.targetRepo}/${encodeURIComponent(String(N))}/edit`:`${r}/${I.targetRepo}?fv_${I.targetKey}=${encodeURIComponent(String(N))}`;return jsx("td",{class:"align-middle py-2",children:jsx("a",{href:D,class:"btn btn-xs btn-ghost btn-outline","data-frs-relation":true,"data-frs-rel-type":I.type,"data-frs-rel-repo":I.targetRepo,"data-frs-rel-fk":I.targetKey,"data-frs-rel-val":String(N),"data-frs-rel-label":I.column,children:I.column})},`rel-${j}`)}),jsx("td",{class:"align-middle text-right whitespace-nowrap py-2",children:jsxs("div",{class:"flex gap-1 justify-end",children:[jsx("a",{href:P,class:"btn btn-xs btn-outline",children:"Edit"}),y&&jsx("a",{href:`${r}/${e}/${encodeURIComponent($)}/history`,class:"btn btn-xs btn-outline",title:"View change history",children:"History"}),d&&jsx("form",{method:"post",action:O,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:Pn(f,o.prevCursor,"prev",w,S),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:Pn(f,o.nextCursor,"next",w,S),class:"btn btn-sm btn-outline",children:"Next \u2192"}):jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"Next \u2192"})]}),typeof b=="number"&&jsxs("div",{class:"text-xs text-base-content/50",children:[b," total document",b!==1?"s":"",f.length>0?" matching filters":""]})]}),h&&p&&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"}),i.map(k=>jsx("option",{value:k,children:k},k))]})]}),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:A.map(k=>jsx("div",{"data-frs-bulk-template-for":k.name,dangerouslySetInnerHTML:{__html:Ze(k)}},k.name))})]}))}var lo="";function We(e,t){return Et(e,t)}function Ft(e,t){return Pt(e,t)}function jt(e,t,n,r,o,s,a,f,d,g,w,S,R,v,b,T,x,y){return Nt(e,t,n,r,o,s,a,f,d,g,w,S,R,v,b,T,x,y)}function we(e,t,n,r,o,s){return It(e,t,n,r,o,s)}var Mt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function po(){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>=Mt.length*4||(e+=Mt.charAt(r%Mt.length));}}return e}function lt(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 Pe(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 Ht(e,t,n){let r=e.documentKey??"docId",o=Le(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 H(e,t,n=200){e.status(n).set("Content-Type","text/html; charset=utf-8").send(t);}function Bt(e,t){e.status(302).set("Location",t).send("");}function ct(e,t){let n=t.shape,r={};for(let[o,s]of Object.entries(n)){let a=Zt(s),f=z(a),d=f==="ZodObject",g=a,w=false;if(f==="ZodUnion"){let v=He(a);v.some(T=>z(T)==="ZodDate")&&(w=true);let b=v.find(T=>{if(z(T)==="ZodObject"){let x=X(T);return "latitude"in x&&"longitude"in x}return false});b&&(d=true,g=b);}if(e[o+"__isnull"]==="1"){r[o]=null;continue}if(d){let v={},b=false;for(let[y,u]of Object.entries(e))y.startsWith(`${o}.`)&&(v[y.slice(o.length+1)]=u,b=true);if(b){r[o]=ct(v,g);continue}let T=e[o],x=Array.isArray(T)?T[T.length-1]:T;if(x)try{r[o]=JSON.parse(x);}catch{r[o]=x;}continue}let S=e[o],R=Array.isArray(S)?S[S.length-1]:S;if(R===void 0||R===""){f==="ZodBoolean"&&(r[o]=false);continue}if(w){r[o]=new Date(R);continue}switch(f){case "ZodBoolean":R==="__null__"?r[o]=null:r[o]=R==="true"||R==="on"||R==="1";break;case "ZodNumber":case "ZodBigInt":r[o]=Number(R);break;case "ZodDate":r[o]=new Date(R);break;case "ZodArray":try{r[o]=JSON.parse(R);}catch{r[o]=R;}break;default:if(R.startsWith("{")||R.startsWith("["))try{r[o]=JSON.parse(R);break}catch{}r[o]=R;}}return r}function Dn(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 _n(e){let t=e;for(;;){let n=z(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=J(t);else if(n==="ZodEffects"||n==="ZodPipe"||n==="ZodTransform"){let r=Ne(t);if(!r)return n;t=r;}else return n}}function Zt(e){let t=e;for(;;){let n=z(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=J(t);else if(n==="ZodEffects"||n==="ZodPipe"||n==="ZodTransform"){let r=Ne(t);if(!r)return t;t=r;}else return t}}function Nn(e){let t=e;for(;;){let n=z(t);if(n==="ZodOptional"||n==="ZodNullable")return true;if(n==="ZodDefault"){t=J(t);continue}return false}}function Fn(e){let t=Zt(e),n=z(t);if(n==="ZodEnum"){let r=Fe(t);return r.length>0?r:void 0}if(n==="ZodNativeEnum"){let r=je(t),o=Object.values(r).filter(s=>typeof s=="string");return o.length>0?o:void 0}if(n==="ZodLiteral"){let r=Me(t);return typeof r=="string"?[r]:void 0}}function jn(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 f=Zt(t.shape[o]),d=z(f),g=d==="ZodObject",w=f,S=false;if(d==="ZodUnion"){let R=He(f);R.some(b=>z(b)==="ZodDate")&&(S=true);let v=R.find(b=>{if(z(b)==="ZodObject"){let T=X(b);return "latitude"in T&&"longitude"in T}return false});v&&(g=true,w=v);}if(g&&typeof a=="object"&&a!==null&&!Array.isArray(a)&&!("_seconds"in a)&&typeof a.toDate!="function"){let R=jn(a,w,s);Object.assign(r,R);}else if(d==="ZodDate"||S){let R=Dn(a);R!==null&&(r[s]=R);}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)&&("_seconds"in a||typeof a.toDate=="function")){let R=Dn(a);r[s]=R??JSON.stringify(a,null,2);}else typeof a=="object"?r[s]=JSON.stringify(a,null,2):r[s]=String(a);}return r}function zt(e,t){return e.map(n=>({...n,defaultValue:t[n.name]??n.defaultValue,nested:n.nested?zt(n.nested,t):void 0}))}function fo(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 f=(s??"").trim();if(!f)continue;let d=e[`fo_${a}`]??"==",g=n.has(d)?d:"==";r.push({field:a,op:g,value:f});}return r}function In(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 Mn(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 f=_n(a);if(f==="ZodObject"){let d=a;for(;;){let w=z(d);if(w==="ZodOptional"||w==="ZodNullable"||w==="ZodDefault")d=J(d);else break}let g=X(d);r.push(...Mn(Object.keys(g),d,s));}else r.push({name:s,zodType:f,nullable:Nn(a),enumValues:Fn(a)});}return r}function mo(e,t){let n=t.split("."),r=e;for(let o of n){for(;;){let a=z(r);if(a==="ZodOptional"||a==="ZodNullable"||a==="ZodDefault")r=J(r);else break}let s=X(r);if(!(o in s))return null;r=s[o];}return r}function Te(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 f=s.slice(0,a),d=s.slice(a+1);r.has(f)||r.set(f,[]),r.get(f).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 f=e.shape[s];for(;;){let d=z(f);if(d==="ZodOptional"||d==="ZodNullable"||d==="ZodDefault")f=J(f);else break}if(z(f)!=="ZodObject"){o[s]=e.shape[s];continue}o[s]=Te(f,a);}return z$1.object(o)}function fe(e,t,n){return re(e,t,n)}function Hn(e,t,n){let r=(u,c)=>{let l=fe(u,t,n),i=Object.values(e).map(p=>({name:p.name,path:p.path}));H(c,Ft(i,l));},o=async(u,c)=>{let l=u.params.repoName;if(!l){H(c,"Bad request",400);return}let i=e[l];if(!i){H(c,"Repository not found",404);return}let p=i.pageSize??25,m=u.query??{},h=m.cursor,E=m.dir==="prev"?"prev":"next",A=m.ob??"",k=m.od==="desc"?"desc":"asc",C=A?{field:A,dir:k}:void 0,$=parseInt(m.ps??""),P=Number.isFinite($)&&$>0?Math.min($,200):p,O=i.listColumns??Object.keys(i.schema.shape),I=i.documentKey??"docId",j=[I,...O.filter(Q=>Q!==I)];C&&(new Set([I,...O]).has(C.field)||(C=void 0));let N=i.filterableFields?(()=>{let Q=[];for(let de of i.filterableFields)(de.includes(".")||O.includes(de))&&Q.push(de);return Q})():O,D=(()=>{let Q=[];for(let de of N)if(de.includes(".")){let Ae=mo(i.schema,de);Q.push({name:de,zodType:Ae?_n(Ae):"ZodString",nullable:Ae?Nn(Ae):false,enumValues:Ae?Fn(Ae):void 0});}else Q.push(...Mn([de],i.schema));return Q})(),K=new Set(D.map(Q=>Q.name)),ce=fo(m,K),q=In(ce),ae;if(h)try{let Q=i.repo.ref;typeof Q.doc=="function"&&(ae=await Q.doc(h).get());}catch{}let[G,Ye]=await Promise.all([i.repo.query.paginate({pageSize:P,cursor:ae,direction:E,...q.length>0?{where:q}:{},...C?{orderBy:[{field:C.field,direction:C.dir}]}:{}}).catch(Q=>({queryError:Le(Q,{ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:ce,sort:C})})),i.repo.aggregate.count(q.length>0?{where:q}:{}).catch(()=>{})]),Ce="queryError"in G,Xn=Ce?[]:G.data,Yn=Ce?"":G.nextCursor?.id??"",er=Ce?"":G.prevCursor?.id??"",tr=Ce?G.queryError:void 0,nr=fe(u,t,n);H(c,jt(i.name,Xn,j,nr,{hasPrev:Ce?false:G.hasPrevPage,hasNext:Ce?false:G.hasNextPage,prevCursor:er,nextCursor:Yn},void 0,D,ce,i.allowDelete??false,i.relationalMeta,C,P,tr,i.isGroup,Ye,i.mutableFields,i.schema,i.historyEnabled));},s=(u,c)=>{let l=u.params.repoName;if(!l){H(c,"Bad request",400);return}let i=e[l];if(!i){H(c,"Repository not found",404);return}let p=fe(u,t,n),m=Te(i.schema,i.createFields),h=ne(m),E=`${p}/${i.name}/create`,A=ge(h,E,"POST","Create document");H(c,we(i.name,A,"create",null,p));},a=async(u,c)=>{let l=u.params.repoName;if(!l){H(c,"Bad request",400);return}let i=e[l];if(!i){H(c,"Repository not found",404);return}let p=fe(u,t,n),m=u.body??{},h=ct(m,i.schema),E=Te(i.schema,i.createFields),A=E.safeParse(h);if(!A.success){let k=ne(E),C=`${p}/${i.name}/create`,$=ge(k,C,"POST","Create document"),P=A.error.issues.map(O=>`${O.path.join(".")}: ${O.message}`).join(", ");H(c,we(i.name,$,"create",null,p,{type:"error",message:`Validation error: ${P}`}),422);return}try{if(i.isGroup&&i.parentKeys&&i.parentKeys.length>0){let k={...A.data};i.createdKey&&(k[i.createdKey]=new Date);let C=i.parentKeys.filter(I=>!k[I]);if(C.length>0)throw new Error(`Missing parent key(s) for subcollection create: ${C.join(", ")}`);let $=i.parentKeys.map(I=>k[I]),P=i.documentKey??"docId",O=k[P]||po();await i.repo.set(...$,O,k);}else await i.repo.create(A.data);Bt(c,`${p}/${i.name}?flash=created`);}catch(k){let C=Te(i.schema,i.createFields),$=ne(C),P=`${p}/${i.name}/create`,O=ge($,P,"POST","Create document");H(c,we(i.name,O,"create",null,p,{type:"error",message:`Save error: ${k.message}`}),500);}},f=async(u,c)=>{let l=u.params.repoName,i=u.params.id;if(!l||!i){H(c,"Bad request",400);return}let p=e[l];if(!p){H(c,"Repository not found",404);return}let m=fe(u,t,n),h=null;try{h=await Pe(p,i);}catch(P){let O=Ht(p,i,P),I=Re(P)?424:500;H(c,We("",{title:`Edit ${p.name} / ${i}`,basePath:m,breadcrumb:[{label:"Repositories",href:m},{label:p.name,href:`${m}/${p.name}`},{label:`Edit ${i}`}],flash:O}),I);return}if(!h){H(c,"Document not found",404);return}let E=jn(h,p.schema),A=Te(p.schema,p.mutableFields),k=zt(ne(A),E),C=`${m}/${p.name}/${encodeURIComponent(i)}/edit`,$=ge(k,C,"POST","Save changes");H(c,we(p.name,$,"edit",i,m));},d=async(u,c)=>{let l=u.params.repoName,i=u.params.id;if(!l||!i){H(c,"Bad request",400);return}let p=e[l];if(!p){H(c,"Repository not found",404);return}let m=fe(u,t,n),h=u.body??{},E=ct(h,p.schema),A=Te(p.schema,p.mutableFields),C=A.partial().safeParse(E);if(!C.success){let $=Object.fromEntries(Object.entries(h).map(([N,D])=>[N,Array.isArray(D)?D.join(","):D??""])),P=zt(ne(A),$),O=`${m}/${p.name}/${encodeURIComponent(i)}/edit`,I=ge(P,O,"POST","Save changes"),j=C.error.issues.map(N=>`${N.path.join(".")}: ${N.message}`).join(", ");H(c,we(p.name,I,"edit",i,m,{type:"error",message:`Validation error: ${j}`}),422);return}try{let $=await Pe(p,i),P=($&&lt($,p.pathKey))??[i];await p.repo.update(...P,C.data),Bt(c,`${m}/${p.name}?flash=updated`);}catch($){let P=Te(p.schema,p.mutableFields),O=ne(P),I=`${m}/${p.name}/${encodeURIComponent(i)}/edit`,j=ge(O,I,"POST","Save changes"),N=Re($)?Ht(p,i,$):{type:"error",message:`Save error: ${$.message}`},D=Re($)?424:500;H(c,we(p.name,j,"edit",i,m,N),D);}},g=async(u,c)=>{let l=u.params.repoName,i=u.params.id;if(!l||!i){H(c,"Bad request",400);return}let p=e[l];if(!p){H(c,"Repository not found",404);return}if(!p.allowDelete){H(c,"Delete is not allowed for this repository",403);return}let m=fe(u,t,n);try{let h=await Pe(p,i),E=(h&&lt(h,p.pathKey))??[i];await p.repo.delete(...E),Bt(c,`${m}/${p.name}?flash=deleted`);}catch(h){let E=Re(h)?Ht(p,i,h):{type:"error",message:`Delete error: ${h.message}`},A=Re(h)?424:500;H(c,We("",{title:`Delete ${p.name} / ${i}`,basePath:m,breadcrumb:[{label:"Repositories",href:m},{label:p.name,href:`${m}/${p.name}`},{label:`Delete ${i}`}],flash:E}),A);}},w=async(u,c)=>{let l=u.params.repoName;if(!l){H(c,"Bad request",400);return}let i=e[l];if(!i){H(c,"Repository not found",404);return}let p=fe(u,t,n),m=u.query,h=m?.type==="many"?"many":"one",E=Math.max(1,Math.min(100,Number(m?.ps??25)||25)),A=i.listColumns??Object.keys(X(i.schema)),{PanelOne:k,PanelMany:C}=await Promise.resolve().then(()=>($t(),On)),{renderToString:$}=await import('hono/jsx/dom/server');if(h==="one"){let D=String(m?.id??"");if(!D){H(c,"<div class='p-6 text-error'>Missing id parameter.</div>",400);return}try{let K=await Pe(i,D),ce=$(k({doc:K,repoName:i.name,basePath:p,schema:i.schema,columns:A}));H(c,ce);}catch(K){H(c,`<div class='p-6 text-error text-sm'>Error: ${K.message}</div>`,500);}return}let P=String(m?.fk??""),O=String(m?.fv??"");if(!P||!O){H(c,"<div class='p-6 text-error'>Missing fk/fv parameters.</div>",400);return}let I=m?.cursor??"",j=m?.dir==="prev"?"prev":"next",N;if(I)try{let D=i.repo.ref;typeof D.doc=="function"&&(N=await D.doc(I).get());}catch{}try{let D=await i.repo.query.paginate({pageSize:E,cursor:N,direction:j,where:[[P,"==",yo(O)]]}),K=$(C({docs:D.data,repoName:i.name,basePath:p,fk:P,fv:O,columns:A,schema:i.schema,pagination:{hasPrev:D.hasPrevPage,hasNext:D.hasNextPage,prevCursor:D.prevCursor?.id??"",nextCursor:D.nextCursor?.id??"",pageSize:E}}));H(c,K);}catch(D){H(c,`<div class='p-6 text-error text-sm'>Error: ${D.message}</div>`,500);}},S=async(u,c)=>{let l=[];for(let i of c){let p;if(u.isGroup||u.parentKeys?.length){let m=await Pe(u,i);p=m?lt(m,u.pathKey):void 0;}p||(p=[i]);try{let m=u.repo.documentRef(...p);m&&l.push(m);}catch{}}return l},R=async(u,c)=>{let l=In(c),i=u.documentKey??"docId",p=[],m;for(;;){let h=await u.repo.query.paginate({pageSize:500,cursor:m,direction:"next",...l.length>0?{where:l}:{}});for(let E of h.data){let A=String(E[i]??E.id??"");A&&p.push(A);}if(!h.hasNextPage||!h.nextCursor)break;m=h.nextCursor;}return p},v=async(u,c)=>{let l=u.params.repoName;if(!l){ee(c,{error:"Bad request"},400);return}let i=e[l];if(!i){ee(c,{error:"Repository not found"},404);return}if(!i.allowDelete){ee(c,{error:"Delete is not allowed for this repository"},403);return}let p=u.body??{};try{let m=await T(i,p);if(m.length===0){ee(c,{deleted:0});return}let h=await S(i,m);for(let E=0;E<h.length;E+=500)await i.repo.bulk.delete(h.slice(E,E+500));ee(c,{deleted:h.length});}catch(m){ee(c,{error:m.message},500);}},b=async(u,c)=>{let l=u.params.repoName;if(!l){ee(c,{error:"Bad request"},400);return}let i=e[l];if(!i){ee(c,{error:"Repository not found"},404);return}let p=u.body??{},m=String(p.field??"");if(!m){ee(c,{error:"Missing 'field'"},400);return}if(!i.mutableFields||!i.mutableFields.includes(m)){ee(c,{error:`Field '${m}' is not bulk-updatable`},403);return}let h=i.schema.shape?.[m],E;if(h){let A=typeof i.schema=="object"&&i.schema&&"constructor"in i.schema&&i.schema.constructor.name.includes("Zod")?i.schema.pick({[m]:true}):void 0;if(!A){ee(c,{error:"Invalid schema structure"},500);return}E=ct(p.formPayload??{},A)[m];let C=h.safeParse(E);if(!C.success){ee(c,{error:`Invalid value for '${m}': ${C.error.message}`},400);return}E=C.data;}try{let A=await T(i,p);if(A.length===0){ee(c,{updated:0});return}let C=(await S(i,A)).map($=>({docRef:$,data:{[m]:E}}));for(let $=0;$<C.length;$+=500)await i.repo.bulk.update(C.slice($,$+500));ee(c,{updated:C.length});}catch(A){ee(c,{error:A.message},500);}};async function T(u,c){if(c.selectAll){let l=x(c.filters,u);return await R(u,l)}return Array.isArray(c.ids)?c.ids.filter(l=>typeof l=="string"&&!!l):[]}function x(u,c){if(!Array.isArray(u))return [];let l=new Set((c.filterableFields??Object.keys(X(c.schema))).map(m=>String(m))),i=new Set(["==","!=","<","<=",">",">=","in","not-in","array-contains","array-contains-any"]),p=[];for(let m of u)m&&typeof m=="object"&&typeof m.field=="string"&&l.has(m.field)&&typeof m.value=="string"&&i.has(String(m.op))&&p.push({field:m.field,op:m.op,value:m.value});return p}return {handleDashboard:r,handleList:o,handleCreateForm:s,handleCreateSubmit:a,handleEditForm:f,handleEditSubmit:d,handleDelete:g,handlePanel:w,handleBulkDelete:v,handleBulkUpdate:b,handleHistory:async(u,c)=>{let l=u.params.repoName,i=u.params.id;if(!l||!i){H(c,"Bad request",400);return}let p=e[l];if(!p){H(c,"Repository not found",404);return}if(!p.historyEnabled||!p.repo.history){H(c,"History not enabled for this repository",404);return}let m=fe(u,t,n),h=p.historySubcollection??"history",E=[i];try{let D=await Pe(p,i),K=D?lt(D,p.pathKey):void 0;K&&K.length>0&&(E=K);}catch{}let A=parseInt(String(u.query?.limit??"")),k=Number.isFinite(A)&&A>0?Math.min(A,500):100,C=[],$;try{C=await p.repo.history.list(...E,{limit:k});}catch(D){$=D.message;}let P=D=>String(D??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),O=D=>{if(D===void 0)return '<span class="opacity-40">undefined</span>';if(D===null)return '<span class="opacity-40">null</span>';if(typeof D=="object")try{return `<code class="text-xs">${P(JSON.stringify(D))}</code>`}catch{return P(String(D))}return P(String(D))},I=D=>D?typeof D.toDate=="function"?D.toDate().toISOString():D instanceof Date?D.toISOString():P(String(D)):"",j=D=>`<span class="badge badge-sm ${D==="create"?"badge-success":D==="delete"?"badge-error":"badge-info"}">${P(D)}</span>`,N="";if(N+='<div class="flex items-center justify-between mb-4">',N+=`<a href="${m}/${p.name}/${encodeURIComponent(i)}/edit" class="btn btn-sm btn-outline">\u2190 Back to edit</a>`,N+=`<a href="${m}/${p.name}" class="btn btn-sm btn-outline">\u2190 Back to list</a>`,N+="</div>",N+=`<p class="text-sm text-base-content/60 mb-4">Subcollection: <code>${P(h)}</code> \xB7 Showing up to ${k} entries.</p>`,$)N+=`<div class="alert alert-error mb-4">${P($)}</div>`;else if(C.length===0)N+='<div class="alert">No history entries found.</div>';else {N+='<div class="overflow-x-auto"><table class="table table-zebra table-sm">',N+="<thead><tr><th>When</th><th>Op</th><th>User</th><th>Reason / Comment</th><th>Changes</th></tr></thead><tbody>";for(let D of C){let K=D.meta??{},ce=[K.reason,K.comment].filter(G=>G!=null&&G!=="").map(G=>P(String(G))).join(" \u2014 "),q="",ae=Object.keys(D.changes??{});ae.length===0?q='<span class="opacity-40">\u2014</span>':q='<ul class="space-y-1">'+ae.map(G=>{let Ye=D.changes[G];return `<li><strong>${P(G)}</strong>: ${O(Ye.oldValue)} \u2192 ${O(Ye.newValue)}</li>`}).join("")+"</ul>",N+="<tr>",N+=`<td class="whitespace-nowrap text-xs font-mono">${P(I(D.historySetAt))}</td>`,N+=`<td>${j(D.operation??"update")}</td>`,N+=`<td class="text-xs">${P(K.userEmail??K.userId??"")}</td>`,N+=`<td class="text-xs">${ce}</td>`,N+=`<td>${q}</td>`,N+="</tr>";}N+="</tbody></table></div>";}H(c,We(N,{title:`History \u2014 ${p.name} / ${i}`,basePath:m,breadcrumb:[{label:"Repositories",href:m},{label:p.name,href:`${m}/${p.name}`},{label:`History ${i}`}]}));}}}function ee(e,t,n=200){e.status(n).set("Content-Type","application/json; charset=utf-8").send(JSON.stringify(t));}function yo(e){return e==="true"?true:e==="false"?false:e!==""&&!isNaN(Number(e))?Number(e):e}var Bn="https://cdn.jsdelivr.net",zn="https://www.gstatic.com",Zn=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${Bn} ${zn}`,`style-src 'self' 'unsafe-inline' ${Bn}`,`connect-src 'self' ${zn} 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 Ge(e={}){let t=e.csp===void 0?Zn: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,f)=>{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 f();}}async function go(e){return typeof e.rawBody=="string"?e.rawBody:Buffer.isBuffer(e.rawBody)?e.rawBody.toString("utf8"):""}function ho(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 Ln(e){let{basePath:t="/",repos:n,parseBody:r=true,securityHeaders:o,auth:s,middleware:a=[],httpsOptions:f}=e,d=t==="/"?"":t.replace(/\/$/,""),g={};for(let[v,b]of Object.entries(n)){let T=b.schema??b.repo.schema??null;if(!T)throw new Error(`[createAdminServer] Repository "${v}" has no Zod schema. Either use createRepositoryConfig(schema)(config) or pass schema: explicitly.`);let x,y,u;if(b.fieldsConfig){let i=b.fieldsConfig;x=[],y=[],u=[];for(let[p,m]of Object.entries(i))for(let h of m)h==="filterable"?x.push(p):h==="mutable"?y.push(p):h==="create"&&u.push(p);x.length===0&&(x=void 0),y.length===0&&(y=void 0),u.length===0&&(u=void 0);}let c=(()=>{let i=b.repo._parentKeys;return i&&i.length>0?i:void 0})();if(c&&u)for(let i of c)u.includes(i)||u.push(i);let l={name:v,path:b.path,repo:b.repo,schema:T,documentKey:b.documentKey??"docId",pathKey:b.repo._pathKey??void 0,isGroup:!!b.repo._isGroup,parentKeys:c,createdKey:b.repo._createdKey??void 0,listColumns:b.listColumns,pageSize:b.pageSize,filterableFields:x,mutableFields:y,createFields:u,allowDelete:b.allowDelete??false,historyEnabled:!!b.repo._historyConfig?.enabled,historySubcollection:(b.repo._historyConfig?.enabled&&b.repo._historySubcollection)??void 0,relationalMeta:(()=>{if(!b.relationalFields||b.relationalFields.length===0)return;let i=b.repo.relationalKeys??{},p=[];for(let m of b.relationalFields){let h=i[m.key];h&&p.push({key:m.key,column:m.column,targetRepo:String(h.repo),targetKey:String(h.key),type:h.type});}return p.length>0?p:void 0})()};g[v]=l;}let w=Hn(g,d,nn(f?.region)),S=new ie;if(o!==false&&S.use(Ge(o===void 0?{}:o)),r&&S.use(async(v,b,T)=>{let x=v,y=String(x.headers?.["content-type"]??"");if(y.includes("application/x-www-form-urlencoded")){let u=await go(x);v.body=ho(u);}else if(y.includes("application/json")&&typeof x.body=="string")try{v.body=JSON.parse(x.body);}catch{}await T();}),s)if(me(s)){for(let v of s.routes){let b=`${d}${v.path}`;v.method==="GET"?S.get(b,v.handler):S.post(b,v.handler);}S.use(s.middleware);}else if(typeof s=="function")S.use(s);else {let v=s.realm??"Admin",b="Basic "+Buffer.from(`${s.username}:${s.password}`).toString("base64");S.use((T,x,y)=>{if((T.headers?.authorization??"")!==b){x.status(401).set("WWW-Authenticate",`Basic realm="${v}"`).set("Content-Type","text/plain").send("Unauthorized");return}y();});}for(let v of a)S.use(v);S.get(`${d}/`,w.handleDashboard),S.get(`${d}`,w.handleDashboard),S.get(`${d}/:repoName/_panel`,w.handlePanel),S.post(`${d}/:repoName/_bulk/delete`,w.handleBulkDelete),S.post(`${d}/:repoName/_bulk/update`,w.handleBulkUpdate),S.get(`${d}/:repoName`,w.handleList),S.get(`${d}/:repoName/create`,w.handleCreateForm),S.post(`${d}/:repoName/create`,w.handleCreateSubmit),S.get(`${d}/:repoName/:id/edit`,w.handleEditForm),S.post(`${d}/:repoName/:id/edit`,w.handleEditSubmit),S.get(`${d}/:repoName/:id/history`,w.handleHistory),S.post(`${d}/:repoName/:id/delete`,w.handleDelete);let R=async(v,b)=>{await S.handle(v,b);};return f&&(R.httpsOptions=f),R}function qt(e,t,n=200){let r=Se(t);e.status(n).set("Content-Type","application/json; charset=utf-8").send(JSON.stringify(r));}function De(e,t,n,r=200){qt(e,{success:true,data:t,meta:n},r);}function U(e,t,n=400){qt(e,{success:false,error:t},n);}function Lt(e,t,n,r,o){let s=Le(t,n),a=s.type==="index",f=a?424:500,g={success:false,error:a?s.message:o&&t instanceof Error?t.message:r};a&&(g.errorType="index",s.indexUrl&&(g.indexUrl=s.indexUrl)),qt(e,g,f);}var Ut="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function xo(){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>=Ut.length*4||(e+=Ut.charAt(r%Ut.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=>en(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 wo(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 f=a.split(".")[0];f&&r[f]&&(o[f]=r[f]);}return z$1.object(o)}function Un(e,t,n,r=false,o=[]){try{let s=wo(e,n,o),a=r?s.partial():s;return {success:!0,data:(Yt()==="normalize"?Ie(a):a).parse(t)}}catch(s){return s instanceof z$1.ZodError?{success:false,error:`Validation failed: ${s.issues.map(f=>`${f.path.join(".")}: ${f.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}function vo(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 f=Array.isArray(a)?a[0]:a;if(f===void 0||f==="")continue;let d=s.match(/^(\w+)__(\w+)$/),g,w="==";if(d&&d[1]&&d[2]){g=d[1];let R=d[2];if(o[R])w=o[R];else continue}else if(!d)g=s;else continue;if(r&&!r.has(g))continue;let S=f;w==="in"||w==="not-in"||w==="array-contains-any"?S=f.split(",").map(R=>qn(R.trim())):S=qn(f),n.push({field:g,op:w,value:S});}return n}function qn(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 dt(e){return e?{docId:e.id}:null}async function Kn(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 Vn(e,t,n,r=false){async function o(y,u,c,l){if(!r)return true;let i=u.rules?.[c];if(!i)return U(y,`Operation "${c}" is not allowed for this repository`,403),false;try{return await i(l)?!0:(U(y,"Forbidden",403),!1)}catch(p){let m=n&&p instanceof Error?p.message:"Forbidden";return U(y,m,403),false}}async function s(y,u,c,l){if(!r)return l;let i=y.rules?.filter;if(!i)return l;let p=[];for(let m of l)try{await i({user:u,doc:m,params:c})&&p.push(m);}catch{}return p}function a(y){return y?.user??null}function f(y,u){return !y||!e[y]?(U(u,`Repository "${y}" not found`,404),null):e[y]}function d(y,u){if(!u)return;let c=y[u];if(typeof c!="string"||!c)return;let l=c.split("/").filter(Boolean),i=[];for(let p=1;p<l.length;p+=2)i.push(l[p]);return i.length>0?i:void 0}async function g(y,u){let c=`by${y.documentKey.charAt(0).toUpperCase()}${y.documentKey.slice(1)}`,l=y.repo.get[c];if(typeof l=="function")try{let p=await l(u);if(p)return p}catch{}return (await y.repo.query.by({where:[[y.documentKey,"==",u]],limit:1}))[0]??null}async function w(y,u){let c=y.params||{},l=f(c.repoName,u);if(!l)return;let i=a(y);if(!await o(u,l,"list",{user:i,query:y.query??{},params:c}))return;let p=[],m;try{let h=y.query??{},E=Math.min(Number(h.pageSize)||l.pageSize,100),A=h.cursor,k=h.direction?.toLowerCase()==="prev"?"prev":"next",C=h.orderBy,$=h.orderDir?.toLowerCase()==="desc"?"desc":"asc",P=h.select,O=P?P.split(",").map(q=>q.trim()):void 0,I;l.allowedIncludes&&h.includes&&(I=(typeof h.includes=="string"?h.includes.split(",").map(ae=>ae.trim()):Array.isArray(h.includes)?h.includes:[]).filter(ae=>typeof ae=="string"&&l.allowedIncludes.includes(ae)),I?.length===0&&(I=void 0));let j=vo(h,l.filterableFields);p=j.map(q=>({field:q.field,op:q.op,value:String(q.value??"")})),C&&(m={field:C,dir:$});let N={pageSize:E,direction:k};if(A)try{let q=typeof A=="string"?JSON.parse(A):A;N.cursor=await Kn(l,q);}catch{}if(C){if(l.orderableFields&&!l.orderableFields.includes(C)){U(u,`Field not orderable: ${C}`,400);return}N.orderBy=[{field:C,direction:$}];}j.length>0&&(N.where=j.map(q=>[q.field,q.op,q.value])),O&&(N.select=O),I&&(N.include=I);let D=await l.repo.query.paginate(N),ce={items:await s(l,a(y),c,D.data),hasNextPage:D.hasNextPage,hasPrevPage:D.hasPrevPage,nextCursor:dt(D.nextCursor),prevCursor:dt(D.prevCursor)};De(u,ce,{pageSize:E,hasMore:D.hasNextPage});}catch(h){Lt(u,h,{ref:l.repo.ref,path:l.path,isGroup:!!l.isGroup,filters:p,sort:m},"Failed to fetch documents",n);}}async function S(y,u){let c=y.params||{},l=f(c.repoName,u);if(!l)return;let i=a(y);if(!await o(u,l,"list",{user:i,query:y.body??{},params:c}))return;let p=[],m;try{let h=y.body??{},E=Math.min(h.pageSize||l.pageSize,100),A=h.direction==="prev"?"prev":"next";h.where&&(p=h.where.map(O=>({field:String(O[0]),op:O[1],value:String(O[2]??"")}))),h.orderBy&&h.orderBy[0]&&(m={field:h.orderBy[0].field,dir:h.orderBy[0].direction==="desc"?"desc":"asc"});let k={pageSize:E,direction:A};if(h.cursor)try{let O=typeof h.cursor=="string"?JSON.parse(h.cursor):h.cursor;k.cursor=await Kn(l,O);}catch{}if(l.allowedIncludes&&h.includes&&h.includes.length>0){let O=h.includes.filter(I=>typeof I=="string"?l.allowedIncludes.includes(I):typeof I=="object"&&I!==null&&"relation"in I&&typeof I.relation=="string"?l.allowedIncludes.includes(I.relation):!1);O.length>0&&(k.include=O);}if(h.where&&h.where.length>0){if(l.filterableFields){let O=new Set(l.filterableFields),I=h.where.filter(j=>!O.has(j[0]));if(I.length>0){U(u,`Fields not filterable: ${I.map(j=>j[0]).join(", ")}`,400);return}}k.where=h.where;}if(h.orWhere&&h.orWhere.length>0){if(l.filterableFields){let O=new Set(l.filterableFields),I=h.orWhere.filter(j=>!O.has(j[0]));if(I.length>0){U(u,`Fields not filterable: ${I.map(j=>j[0]).join(", ")}`,400);return}}k.orWhere=h.orWhere;}if(h.orWhereGroups&&h.orWhereGroups.length>0){if(l.filterableFields){let O=new Set(l.filterableFields);for(let I of h.orWhereGroups){let j=I.filter(N=>!O.has(N[0]));if(j.length>0){U(u,`Fields not filterable: ${j.map(N=>N[0]).join(", ")}`,400);return}}}k.orWhereGroups=h.orWhereGroups;}if(h.orderBy&&h.orderBy.length>0){if(l.orderableFields){let O=new Set(l.orderableFields),I=h.orderBy.filter(j=>!O.has(j.field));if(I.length>0){U(u,`Fields not orderable: ${I.map(j=>j.field).join(", ")}`,400);return}}k.orderBy=h.orderBy;}h.select&&h.select.length>0&&(k.select=h.select);let C=await l.repo.query.paginate(k),P={items:await s(l,a(y),c,C.data),hasNextPage:C.hasNextPage,hasPrevPage:C.hasPrevPage,nextCursor:dt(C.nextCursor),prevCursor:dt(C.prevCursor)};De(u,P,{pageSize:E,hasMore:C.hasNextPage});}catch(h){Lt(u,h,{ref:l.repo.ref,path:l.path,isGroup:!!l.isGroup,filters:p,sort:m},"Failed to query documents",n);}}async function R(y,u){let c=y.params||{},l=f(c.repoName,u);if(!l)return;let i=c.id;if(!i){U(u,"Document ID required",400);return}try{let p=await g(l,i);if(!p){U(u,"Document not found",404);return}let m=a(y);if(!await o(u,l,"get",{user:m,doc:p,params:c}))return;if(r&&l.rules?.filter)try{if(!await l.rules.filter({user:m,doc:p,params:c})){U(u,"Document not found",404);return}}catch{U(u,"Document not found",404);return}De(u,p);}catch(p){Lt(u,p,{ref:l.repo.ref,path:l.path,isGroup:!!l.isGroup,filters:[{field:l.documentKey,op:"==",value:i}]},"Failed to fetch document",n);}}async function v(y,u){let c=y.params||{},l=f(c.repoName,u);if(l)try{let i=y.body??{},p=a(y);if(!await o(u,l,"create",{user:p,body:i,params:c}))return;let m=Un(l.schema,i,l.createFields,!1,l.systemKeys);if(!m.success){U(u,m.error,400);return}if(l.validate){let E=await l.validate(m.data,"create");if(E){U(u,E,400);return}}let h;if(l.isGroup&&l.parentKeys&&l.parentKeys.length>0){let E={...m.data};l.createdKey&&(E[l.createdKey]=new Date);let A=l.parentKeys.filter($=>!E[$]);if(A.length>0){U(u,`Missing parent key(s) for subcollection create: ${A.join(", ")}`,400);return}let k=l.parentKeys.map($=>E[$]),C=E[l.documentKey]||xo();h=await l.repo.set(...k,C,E);}else h=await l.repo.create(m.data);De(u,h,void 0,201);}catch(i){let p=n&&i instanceof Error?i.message:"Failed to create document";U(u,p,500);}}async function b(y,u,c){let l=y.params||{},i=f(l.repoName,u);if(!i)return;let p=l.id;if(!p){U(u,"Document ID required",400);return}try{let m=y.body??{},h=await g(i,p);if(!h){U(u,"Document not found",404);return}let E=a(y);if(!await o(u,i,"update",{user:E,doc:h,body:m,params:l}))return;let A=Un(i.schema,m,i.mutableFields,c,i.systemKeys);if(!A.success){U(u,A.error,400);return}if(i.validate){let $=await i.validate(A.data,"update");if($){U(u,$,400);return}}let k=d(h,i.pathKey)??[p],C=await i.repo.update(...k,A.data);De(u,C);}catch(m){let h=n&&m instanceof Error?m.message:"Failed to update document";U(u,h,500);}}async function T(y,u){let c=y.params||{},l=f(c.repoName,u);if(!l)return;if(!l.allowDelete){U(u,"Delete not allowed for this repository",403);return}let i=c.id;if(!i){U(u,"Document ID required",400);return}try{let p=await g(l,i);if(!p){U(u,"Document not found",404);return}let m=a(y);if(!await o(u,l,"delete",{user:m,doc:p,params:c}))return;let h=d(p,l.pathKey)??[i];await l.repo.delete(...h),De(u,{deleted:!0});}catch(p){let m=n&&p instanceof Error?p.message:"Failed to delete document";U(u,m,500);}}function x(y,u){u.status(204).set("Access-Control-Allow-Methods","GET, POST, PUT, PATCH, DELETE, OPTIONS").set("Access-Control-Allow-Headers","Content-Type, Authorization").set("Access-Control-Max-Age","86400").send("");}return {handleList:w,handleQuery:S,handleGet:R,handleCreate:v,handleUpdate:b,handleDelete:T,handleOptions:x}}function Kt(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 se(e){return {$ref:`#/components/schemas/${e}`}}function te(e){return {description:e,content:{"application/json":{schema:se("ErrorResponse")}}}}function Xe(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function Qn(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 So(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 Ro(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 ko(){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 To(e,t,n,r,o){let s={},a=e.name,f=`${t}/${e.name}`,d=`${f}/{${e.documentKey}}`,g={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};s[f]={get:{operationId:`list${ve(e.name)}`,summary:`List ${e.name} (paginated)`,tags:[a],parameters:[...So(e),...Ro(e)],responses:{200:Qn(se(n)),500:te("Internal server error")}},post:{operationId:`create${ve(e.name)}`,summary:`Create a ${le(e.name)}`,tags:[a],requestBody:{required:true,content:{"application/json":{schema:se(r??n)}}},responses:{201:Xe("Document created",se(n)),400:te("Validation error"),500:te("Internal server error")}}},s[`${f}/query`]={post:{operationId:`query${ve(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[a],requestBody:{required:true,content:{"application/json":{schema:se("QueryRequestBody")}}},responses:{200:Qn(se(n)),400:te("Invalid query"),500:te("Internal server error")}}};let w={};return w.get={operationId:`get${ve(le(e.name))}`,summary:`Get a single ${le(e.name)}`,tags:[a],parameters:[g],responses:{200:Xe("Document found",se(n)),404:te("Document not found"),500:te("Internal server error")}},w.put={operationId:`update${ve(le(e.name))}`,summary:`Update a ${le(e.name)} (full replace)`,tags:[a],parameters:[g],requestBody:{required:true,content:{"application/json":{schema:se(o??n)}}},responses:{200:Xe("Document updated",se(n)),400:te("Validation error"),404:te("Document not found"),500:te("Internal server error")}},w.patch={operationId:`patch${ve(le(e.name))}`,summary:`Partially update a ${le(e.name)}`,tags:[a],parameters:[g],requestBody:{required:true,content:{"application/json":{schema:{allOf:[se(o??n)],description:"All fields are optional for partial updates"}}}},responses:{200:Xe("Document patched",se(n)),400:te("Validation error"),404:te("Document not found"),500:te("Internal server error")}},e.allowDelete&&(w.delete={operationId:`delete${ve(le(e.name))}`,summary:`Delete a ${le(e.name)}`,tags:[a],parameters:[g],responses:{200:Xe("Document deleted",{type:"object",properties:{id:{type:"string"}}}),404:te("Document not found"),500:te("Internal server error")}}),s[d]=w,s}function Qt(e,t,n={}){let{title:r="CRUD API",version:o="1.0.0",description:s,servers:a,auth:f=false}=n,d=t==="/"?"":t.replace(/\/$/,""),g={},w={},S=[];g.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string"}},required:["success","error"]},g.QueryRequestBody=ko();for(let[T,x]of Object.entries(e)){let y=ve(le(T)),u=`${y}Create`,c=`${y}Update`;g[y]=Kt(x.schema);let l=A=>{let k=A&&A.length>0?A:Object.keys(x.schema.shape),C={};for(let $ of k){let P=$.split(".")[0];P&&x.schema.shape[P]&&!x.systemKeys.includes(P)&&(C[P]=x.schema.shape[P]);}return C},i=null,p=l(x.createFields);Object.keys(p).length>0&&(g[u]=Kt(z$1.object(p)),i=u);let m=null,h=l(x.mutableFields);Object.keys(h).length>0&&(g[c]=Kt(z$1.object(h)),m=c);let E=To(x,d,y,i,m);Object.assign(w,E),S.push({name:T,description:`Operations on ${T} (collection: ${x.path})`});}let R={},v;return f==="basic"?(R.basicAuth={type:"http",scheme:"basic"},v=[{basicAuth:[]}]):f==="bearer"&&(R.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},v=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:r,version:o,...s?{description:s}:{}},...a&&a.length>0?{servers:a}:{},paths:w,components:{schemas:g,...Object.keys(R).length>0?{securitySchemes:R}:{}},...v?{security:v}:{},tags:S}}function ve(e){return e.charAt(0).toUpperCase()+e.slice(1)}function le(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}function Co(e,t){return `<!DOCTYPE html>
1142
1142
  <html lang="en">
1143
1143
  <head>
1144
1144
  <meta charset="utf-8" />