@lpdjs/firestore-repo-service 2.2.9-beta.1 → 2.2.9-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- 'use strict';var jsxRuntime=require('hono/jsx/jsx-runtime'),firestore=require('firebase-admin/firestore'),crypto=require('crypto'),zod=require('zod'),server=require('hono/jsx/dom/server');var yr=Object.defineProperty;var Xe=(e,t)=>()=>(e&&(t=e(e=0)),t);var mr=(e,t)=>{for(var n in t)yr(e,n,{get:t[n],enumerable:true});};function Z(e){let t=e,n=t._zod?.def?.type;if(n)return Mr[n]??`Zod${n.charAt(0).toUpperCase()}${n.slice(1)}`;let r=t._def?.typeName;return r||""}function U(e){let t=e;if(t._zod?.def?.innerType)return t._zod.def.innerType;if(t._def?.innerType)return t._def.innerType}function bn(e){let t=e;if(t._zod?.def?.element)return t._zod.def.element;if(t._def?.type)return t._def.type}function vn(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 ee(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 ze(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 He(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 lt(e){let t=e;return Array.isArray(t._zod?.def?.values)?t._zod.def.values[0]:t._def?.value}function xn(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 Mr,Be=Xe(()=>{Mr={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 Nn({val:e}){return jsxRuntime.jsx("span",{class:"text-sm text-base-content/80 font-mono tabular-nums whitespace-nowrap",children:e.toLocaleString()})}function Qr({message:e}){return jsxRuntime.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:jsxRuntime.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",class:"size-3.5",children:jsxRuntime.jsx("path",{d:"M12 2 1 22h22L12 2zm0 6 7.5 13h-15L12 8zm-1 4v4h2v-4h-2zm0 5v2h2v-2h-2z"})})})}function Pe({val:e,mismatch:t}){let n=Gr(e);return t?jsxRuntime.jsxs("span",{class:"inline-flex items-start gap-0.5",children:[n,jsxRuntime.jsx(Qr,{message:t})]}):n}function Gr(e){if(e==null)return jsxRuntime.jsx("span",{class:"opacity-30 italic text-xs",children:"\u2014"});if(typeof e=="boolean")return e?jsxRuntime.jsx("span",{class:"badge badge-success badge-sm",children:"true"}):jsxRuntime.jsx("span",{class:"badge badge-error badge-sm",children:"false"});if(e instanceof Date)return jsxRuntime.jsx(Nn,{val:e});if(typeof e=="object"&&e!==null&&typeof e.toDate=="function")return jsxRuntime.jsx(Nn,{val:e.toDate()});if(typeof e=="number")return jsxRuntime.jsx("span",{class:"text-sm font-mono tabular-nums",children:String(e)});if(Array.isArray(e))return e.length===0?jsxRuntime.jsx("span",{class:"text-xs text-base-content/30",children:"[]"}):jsxRuntime.jsxs("ul",{class:"list-none p-0 m-0 space-y-0.5 text-xs",children:[e.slice(0,8).map((n,r)=>jsxRuntime.jsx("li",{class:"break-all",children:typeof n=="object"?JSON.stringify(n):String(n)},r)),e.length>8&&jsxRuntime.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?jsxRuntime.jsx("span",{class:"text-xs text-base-content/30",children:"{}"}):jsxRuntime.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])=>jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("dt",{class:"text-base-content/50 font-semibold whitespace-nowrap",children:r}),jsxRuntime.jsx("dd",{class:"break-all",children:String(o??"")})]})),n.length>8&&jsxRuntime.jsxs("dt",{class:"col-span-2 text-base-content/40 italic",children:["+",n.length-8," more\u2026"]})]})}let t=String(e);return jsxRuntime.jsx("span",{class:"text-sm break-all",children:t})}var ut=Xe(()=>{});function Ee(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=U(e);return n?Ct(n):e}return e}function De(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=ee(s)[o];}return r}function Yr(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 Le(e,t){if(e==="unknown")return null;let n=Yr(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 Ot=Xe(()=>{Be();});var Fn={};mr(Fn,{PanelMany:()=>to,PanelOne:()=>eo,RightPanel:()=>$t});function eo({doc:e,repoName:t,basePath:n,schema:r,columns:o}){if(!e)return jsxRuntime.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`,c=jn(r,o);return jsxRuntime.jsxs("div",{class:"space-y-4",children:[jsxRuntime.jsxs("div",{class:"flex items-center justify-between gap-2",children:[jsxRuntime.jsxs("div",{class:"text-xs text-base-content/60",children:[jsxRuntime.jsx("span",{class:"font-mono",children:t}),jsxRuntime.jsx("span",{class:"opacity-50",children:" \xB7 "}),jsxRuntime.jsx("span",{class:"font-mono break-all",children:s})]}),jsxRuntime.jsx("a",{href:a,class:"btn btn-sm btn-primary",children:"Edit \u2192"})]}),jsxRuntime.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(i=>{let p=e[i],d=c[i],h=d?Le(d,p):null;return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("dt",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide pt-0.5",children:i}),jsxRuntime.jsx("dd",{class:"min-w-0",children:jsxRuntime.jsx(Pe,{val:p,mismatch:h})})]})})})]})}function to({docs:e,repoName:t,basePath:n,fk:r,fv:o,columns:s,schema:a,pagination:c}){let i=`${n}/${t}?fv_${r}=${encodeURIComponent(o)}`,p=jn(a,s);return jsxRuntime.jsxs("div",{class:"space-y-4",children:[jsxRuntime.jsxs("div",{class:"flex items-center justify-between gap-2",children:[jsxRuntime.jsxs("div",{class:"text-xs text-base-content/60",children:[jsxRuntime.jsx("span",{class:"font-mono",children:t}),jsxRuntime.jsx("span",{class:"opacity-50",children:" where "}),jsxRuntime.jsx("span",{class:"font-mono",children:r}),jsxRuntime.jsx("span",{class:"opacity-50",children:" = "}),jsxRuntime.jsx("span",{class:"font-mono break-all",children:o}),jsxRuntime.jsx("span",{class:"opacity-50",children:" \xB7 "}),jsxRuntime.jsxs("span",{children:[e.length," doc",e.length!==1?"s":""]})]}),jsxRuntime.jsx("a",{href:i,class:"btn btn-sm btn-outline",children:"Full view \u2192"})]}),jsxRuntime.jsx("div",{class:"overflow-x-auto rounded-box border border-base-300 bg-base-100",children:jsxRuntime.jsxs("table",{class:"table table-xs w-full",children:[jsxRuntime.jsx("thead",{children:jsxRuntime.jsxs("tr",{class:"bg-base-200/50",children:[s.map((d,h)=>jsxRuntime.jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:d},h)),jsxRuntime.jsx("th",{})]})}),jsxRuntime.jsx("tbody",{children:e.length===0?jsxRuntime.jsx("tr",{children:jsxRuntime.jsx("td",{colspan:s.length+1,class:"text-center py-10 text-base-content/40",children:"No related documents"})}):e.map((d,h)=>{let v=String(d.docId??d.id??""),g=`${n}/${t}/${encodeURIComponent(v)}/edit`;return jsxRuntime.jsxs("tr",{class:"hover",children:[s.map((u,b)=>{let m=d[u],f=p[u],l=f?Le(f,m):null;return jsxRuntime.jsx("td",{class:"align-top py-1.5",children:jsxRuntime.jsx(Pe,{val:m,mismatch:l})},b)}),jsxRuntime.jsx("td",{class:"text-right py-1.5",children:jsxRuntime.jsx("a",{href:g,class:"btn btn-xs btn-ghost",children:"Edit"})})]},h)})})]})}),(c.hasPrev||c.hasNext)&&jsxRuntime.jsxs("div",{class:"flex justify-center items-center gap-2",children:[c.hasPrev?jsxRuntime.jsx("button",{type:"button",class:"btn btn-xs btn-outline","data-frs-panel-page":"prev","data-cursor":c.prevCursor,children:"\u2190 Previous"}):jsxRuntime.jsx("button",{class:"btn btn-xs btn-outline",disabled:true,children:"\u2190 Previous"}),c.hasNext?jsxRuntime.jsx("button",{type:"button",class:"btn btn-xs btn-outline","data-frs-panel-page":"next","data-cursor":c.nextCursor,children:"Next \u2192"}):jsxRuntime.jsx("button",{class:"btn btn-xs btn-outline",disabled:true,children:"Next \u2192"})]})]})}function jn(e,t){if(!e)return {};let n={};for(let r of t)n[r]=Ee(De(e,r));return n}var $t,At=Xe(()=>{ut();Ot();$t=({basePath:e=""})=>jsxRuntime.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:[jsxRuntime.jsx("div",{class:"absolute inset-0 bg-black/30 opacity-0 transition-opacity duration-200 pointer-events-auto","data-frs-panel-backdrop":true}),jsxRuntime.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:[jsxRuntime.jsxs("header",{class:"flex items-center justify-between px-5 py-3 border-b border-base-300 bg-base-200/40 shrink-0",children:[jsxRuntime.jsx("h2",{class:"font-semibold text-base truncate","data-frs-panel-title":true,children:"Relation"}),jsxRuntime.jsx("button",{type:"button",class:"btn btn-sm btn-ghost btn-circle","data-frs-panel-close":true,"aria-label":"Close panel",children:"\u2715"})]}),jsxRuntime.jsx("div",{class:"flex-1 overflow-auto p-5 text-sm","data-frs-panel-body":true,children:jsxRuntime.jsx("div",{class:"flex items-center justify-center py-12 text-base-content/40",children:jsxRuntime.jsx("span",{class:"loading loading-spinner loading-md"})})})]})]});});function gr(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Fe(e,t){return t.orderBy&&t.orderBy.forEach(n=>{e=e.orderBy(String(n.field),n.direction??"asc");}),t.limit&&(e=e.limit(t.limit)),t.offset&&(e=e.offset(t.offset)),t.select&&t.select.length>0&&(e=e.select(...t.select.map(n=>String(n)))),t.startAt&&(e=Array.isArray(t.startAt)?e.startAt(...t.startAt):e.startAt(t.startAt)),t.startAfter&&(e=Array.isArray(t.startAfter)?e.startAfter(...t.startAfter):e.startAfter(t.startAfter)),t.endAt&&(e=Array.isArray(t.endAt)?e.endAt(...t.endAt):e.endAt(t.endAt)),t.endBefore&&(e=Array.isArray(t.endBefore)?e.endBefore(...t.endBefore):e.endBefore(t.endBefore)),e}function gt(e){let[,t,n]=e;return (t==="in"||t==="array-contains-any")&&Array.isArray(n)&&n.length>30}function Yt(e){let[t,n,r]=e;return gt(e)?gr(r,30).map(s=>[t,n,s]):[e]}function Ye(e,t){let n=e;for(let[r,o,s]of t)n=n.where(String(r),o,s);return n}async function en(e){let t=await Promise.all(e.map(o=>o.get())),n=new Map;t.forEach(o=>{o.docs.forEach(s=>{n.has(s.id)||n.set(s.id,s);});});let r=t[0];if(!r)throw new Error("No snapshots returned");return {...r,docs:Array.from(n.values()),size:n.size,empty:n.size===0}}async function we(e,t){let n=t.orWhere&&t.orWhere.length>0,r=t.orWhereGroups&&t.orWhereGroups.length>0;if(!n&&!r){if(!t.where||t.where.length===0)return Fe(e,t).get();if(!t.where.some(gt)){let h=Ye(e,t.where);return h=Fe(h,t),h.get()}let i=t.where.map(Yt),d=ht(i).map(h=>{let v=Ye(e,h);return v=Fe(v,t),v});return en(d)}let o=t.where??[],s=[...t.orWhere?.map(c=>[c])??[],...t.orWhereGroups??[]],a=[];for(let c of s){let i=[...o,...c];if(i.some(gt)){let d=i.map(Yt),v=ht(d).map(g=>{let u=Ye(e,g);return u=Fe(u,t),u});a.push(...v);}else {let d=Ye(e,i);d=Fe(d,t),a.push(d);}}return en(a)}function ht(e){if(e.length===0)return [[]];let t=e[0];if(e.length===1&&t)return t.map(s=>[s]);if(!t)return [[]];let n=e.slice(1),r=ht(n),o=[];for(let s of t)for(let a of r)o.push([s,...a]);return o}var bt="preserve";function hr(e){bt=e;}function vt(){return bt}function br(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function xt(e){if(e==null)return null;if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(e instanceof firestore.Timestamp)return e.toDate();if(br(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 vr(e){if(typeof e!="object"||e===null)return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function et(e){if(e instanceof firestore.Timestamp)return e.toDate();if(Array.isArray(e))return e.map(t=>et(t));if(vr(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=et(r);return t}return e}function K(e){return bt==="normalize"?et(e):e}function nn(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function ce(e){return e.charAt(0).toUpperCase()+e.slice(1)}function pe(e,t){return t.where&&t.where.forEach(([n,r,o])=>{e=e.where(String(n),r,o);}),t.orderBy&&t.orderBy.forEach(n=>{e=e.orderBy(String(n.field),n.direction??"asc");}),t.limit&&(e=e.limit(t.limit)),t.offset&&(e=e.offset(t.offset)),t.select&&t.select.length>0&&(e=e.select(...t.select.map(n=>String(n)))),t.startAt&&(e=Array.isArray(t.startAt)?e.startAt(...t.startAt):e.startAt(t.startAt)),t.startAfter&&(e=Array.isArray(t.startAfter)?e.startAfter(...t.startAfter):e.startAfter(t.startAfter)),t.endAt&&(e=Array.isArray(t.endAt)?e.endAt(...t.endAt):e.endAt(t.endAt)),t.endBefore&&(e=Array.isArray(t.endBefore)?e.endBefore(...t.endBefore):e.endBefore(t.endBefore)),e}async function tt(e,t){let n={...t,limit:t.pageSize+1};t.cursor&&(t.direction==="prev"?n.endBefore=t.cursor:n.startAfter=t.cursor);let o=(await we(e,n)).docs,s=o.length>t.pageSize,a=s?o.slice(0,t.pageSize):o,c=a.map(p=>K({...p.data(),docId:p.id})),i=t.direction==="prev";return {data:c,nextCursor:i?a.length>0?a[a.length-1]:void 0:s?a[a.length-1]:void 0,prevCursor:i?s?a[0]:void 0:a[0],hasNextPage:i?!!t.cursor:s,hasPrevPage:i?s:!!t.cursor,pageSize:c.length}}async function*wt(e,t){let n,r=true;for(;r;){let o=await tt(e,{...t,cursor:n,direction:"next"});yield o,r=o.hasNextPage,n=o.nextCursor;}}function Me(e){if(e===null)return "null";if(e===void 0)return "undefined";if(e instanceof firestore.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 rn(e,t){if(e===t)return true;if(e===null||t===null||e===void 0||t===void 0)return e===t;if(e instanceof firestore.Timestamp&&t instanceof firestore.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(e.length!==t.length)return false;for(let n=0;n<e.length;n++)if(!rn(e[n],t[n]))return false;return true}if(typeof e=="object"&&typeof t=="object")try{return JSON.stringify(e)===JSON.stringify(t)}catch{return false}return false}function nt(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??{},c=new Set([...Object.keys(s),...Object.keys(a)]),i={};for(let p of c){if(r.has(p)||o&&!o.has(p))continue;let d=s[p],h=a[p];rn(d,h)||(i[p]={oldValue:d===void 0?null:d,newValue:h===void 0?null:h,type:{old:Me(d),new:Me(h)}});}return i}var xr=5;function wr(e){return e.schemaVersion===2}function on(e){if(typeof e!="string")return "object";switch(e){case "string":case "number":case "boolean":case "object":case "array":case "timestamp":case "date":case "null":case "undefined":return e;default:return "object"}}function Rr(e){return {historyDocId:e.historyDocId,historyToObjectId:e.historyToObjectId,historySetAt:e.historySetAt,schemaVersion:2,operation:e.operation,meta:e.meta??{},changes:e.changes??{}}}function Sr(e){let t={};e.historyUserId!==void 0&&(t.userId=e.historyUserId??null),e.historyUserEmail!==void 0&&(t.userEmail=e.historyUserEmail??null);let n=e.extraHistoryDetails??null;n&&(n.reason!==void 0&&(t.reason=n.reason??null),n.comment!==void 0&&(t.comment=n.comment??null));let r={},o=false;if(e.historyDetails&&typeof e.historyDetails=="object")for(let[s,a]of Object.entries(e.historyDetails))r[s]=a,o=true;if(e.extraContentKeys&&typeof e.extraContentKeys=="object")for(let[s,a]of Object.entries(e.extraContentKeys))r[`content.${s}`]=a,o=true;return o&&(t.extras=r),t}function Tr(e){let t=e.changes?.oldValue??null,n=e.changes?.newValue??null,r=e.types?.oldValue,o=e.types?.newValue;return {oldValue:t,newValue:n,type:{old:r?on(r):Me(t),new:o?on(o):Me(n)}}}function kr(e){let t=Tr(e),n=Sr(e);return {historyDocId:e.historyDocId,historyToObjectId:e.historyToObjectId,historySetAt:e.historySetAt,schemaVersion:1,operation:"update",meta:n,changes:{[e.field]:t}}}function Cr(e,t,n){return Math.abs(e.toMillis()-t.toMillis())<=n}function Or(e,t){return (e.userId??null)===(t.userId??null)}function sn(e,t={}){let n=t.groupToleranceMs??xr,r=[];for(let o of e){if(wr(o)){r.push(Rr(o));continue}let a=kr(o),c=r[r.length-1];c&&c.schemaVersion===1&&Cr(c.historySetAt,a.historySetAt,n)&&Or(c.meta,a.meta)?Object.assign(c.changes,a.changes):r.push(a);}return r}var Ar=7e5;function rt(e){let t=e.ttlOverride??e.config.ttl,r={schemaVersion:2,historyDocId:crypto.randomUUID(),historyToObjectId:e.entityId,historySetAt:firestore.Timestamp.now(),operation:e.operation,meta:e.meta,changes:e.changes};t&&(r.expiresAt=firestore.Timestamp.fromMillis(Date.now()+t.days*24*60*60*1e3));let o=s=>{try{return Buffer.byteLength(JSON.stringify(s,(a,c)=>c instanceof firestore.Timestamp?c.toMillis():c),"utf8")}catch{return 0}};if(o(r.changes)>Ar){let s={};for(let[a,c]of Object.entries(r.changes)){let i=o(c.oldValue),p=o(c.newValue);s[a]={oldValue:i>5e4?"[truncated]":c.oldValue,newValue:p>5e4?"[truncated]":c.newValue,type:c.type};}r.changes=s,r._truncated=true;}return r}async function ot(e,t,n,r){let o=t;return n.onBeforeWrite&&(o=await n.onBeforeWrite(t,r)),o?(await e.doc(o.historyDocId).set(o),{written:true,entry:o}):{written:false,reason:"dropped-by-onBeforeWrite"}}function st(e,t){let n=e??{},r={},o=t.meta;if(!o)return r;let s=d=>{if(!d)return;let h=n[d];return h===void 0||h===null?null:String(h)},a=s(o.userId);a!==void 0&&(r.userId=a);let c=s(o.userEmail);c!==void 0&&(r.userEmail=c);let i=s(o.reason);i!==void 0&&(r.reason=i);let p=s(o.comment);if(p!==void 0&&(r.comment=p),o.extras&&o.extras.length>0){let d={},h=false;for(let v of o.extras)v in n&&(d[v]=n[v],h=true);h&&(r.extras=d);}return r}function at(e){let t=e.meta;if(!t)return [];let n=[];return t.userId&&n.push(t.userId),t.userEmail&&n.push(t.userEmail),t.reason&&n.push(t.reason),t.comment&&n.push(t.comment),t.extras&&n.push(...t.extras),n}var Pr="history",Er=50;function an(e,t,n){return e(...n).collection(t)}function Dr(e){return String(e[e.length-1]??"")}function ln(e,t,n,r){if(!r?.enabled)return null;let o=r.subcollection??Pr;async function s(...d){let h={},v=d,g=d[d.length-1];g!==null&&typeof g=="object"&&!(g instanceof firestore.Timestamp)&&("limit"in g||"cursor"in g||"direction"in g)&&(h=g,v=d.slice(0,-1));let u=an(e,o,v),b=h.direction??"desc",m=u.orderBy("historySetAt",b);return h.cursor&&(m=m.startAfter(h.cursor)),h.limit&&h.limit>0&&(m=m.limit(h.limit)),(await m.get()).docs.map(l=>({id:l.id,data:l.data()}))}async function a(...d){let h={},v=d,g=d[d.length-1];g!==null&&typeof g=="object"&&!(g instanceof firestore.Timestamp)&&("limit"in g||"cursor"in g||"direction"in g||"fields"in g||"operations"in g)&&(h=g,v=d.slice(0,-1));let u=h.limit??Er,b=Math.max(u,Math.min(u*8,500)),m=await s(...v,{limit:b,cursor:h.cursor,direction:h.direction??"desc"}),f=sn(m.map(l=>l.data));if(h.fields&&h.fields.length>0){let l=new Set(h.fields);f=f.filter(x=>Object.keys(x.changes).some(y=>l.has(y)));}if(h.operations&&h.operations.length>0){let l=new Set(h.operations);f=f.filter(x=>l.has(x.operation));}return f.slice(0,u)}async function c(...d){let h=d[d.length-1],v={},g,u;return h!==null&&typeof h=="object"&&!(h instanceof firestore.Timestamp)?(v=h,g=d[d.length-2],u=d.slice(0,-2)):(g=h,u=d.slice(0,-1)),a(...u,{...v,fields:[g]})}async function i(...d){let h=d[d.length-1],v={},g,u;return h!==null&&typeof h=="object"&&!(h instanceof firestore.Timestamp)?(v=h,g=d[d.length-2],u=d.slice(0,-2)):(g=h,u=d.slice(0,-1)),a(...u,{...v,operations:[g]})}async function p(...d){let h=d[d.length-1],v=d.slice(0,-1),g=Dr(v),u=nt(h.before??{},h.after??{},{include:r.include,exclude:r.exclude,metaFields:at(r),systemKeys:t});if(h.operation==="update"&&Object.keys(u).length===0)return null;let m={...st(h.after??h.before??null,r),...h.meta??{}},f=rt({entityId:g,operation:h.operation,changes:u,meta:m,config:r}),l=an(e,o,v),x=await ot(l,f,r,{repoName:n,docId:g,before:h.before??null,after:h.after??null});return !x.written||!x.entry?null:{historyDocId:x.entry.historyDocId,historyToObjectId:x.entry.historyToObjectId,historySetAt:x.entry.historySetAt,schemaVersion:2,operation:x.entry.operation,meta:x.entry.meta,changes:x.entry.changes}}return {list:a,raw:s,byField:c,byOperation:i,recordManual:p}}function cn(e){return {count:async(t={})=>{let n=e;return n=pe(n,t),(await n.count().get()).data().count},sum:async(t,n={})=>{let r=e;r=pe(r,n);let o=await r.get(),s=0;return o.forEach(a=>{let c=a.data()[t];typeof c=="number"&&(s+=c);}),s},average:async(t,n={})=>{let r=e;r=pe(r,n);let o=await r.get();if(o.empty)return null;let s=0,a=0;return o.forEach(c=>{let i=c.data()[t];typeof i=="number"&&(s+=i,a++);}),a>0?s/a:null}}}function dn(e,t,n,r,o,s){let a=()=>new Date;return {create:()=>{let c=e.batch();return {batch:c,set:(...i)=>{let p=i[i.length-1],d=typeof p=="object"&&p!==null&&"merge"in p,h=d?i[i.length-2]:i[i.length-1],v=d?i.slice(0,-2):i.slice(0,-1),g=d?p:{merge:true},u=t(...v),b={...h},m=v[v.length-1];n&&m&&(b[n]=m),r&&(b[r]=u.path),o&&(b[o]=a()),s&&(b[s]=a()),c.set(u,b,g);},update:(...i)=>{let p=i.pop(),h=t(...i),v={...p};s&&(v[s]=a()),c.update(h,v);},delete:(...i)=>{let p=t(...i);c.delete(p);},commit:async()=>{await c.commit();}}}}}function un(e,t,n){let r=()=>new Date;return {set:async o=>{let s=e.bulkWriter(),a=0;for(let c of o){if(!c)continue;let{docRef:i,data:p,merge:d=true}=c,h={...p};t&&(h[t]=r()),n&&(h[n]=r()),s.set(i,h,{merge:d}),a++,a>=500&&(await s.flush(),a=0);}await s.close();},update:async o=>{let s=e.bulkWriter(),a=0;for(let c of o){if(!c)continue;let{docRef:i,data:p}=c,d={...p};n&&(d[n]=r()),s.update(i,d),a++,a>=500&&(await s.flush(),a=0);}await s.close();},delete:async o=>{let s=e.bulkWriter(),a=0;for(let c of o)c&&(s.delete(c),a++,a>=500&&(await s.flush(),a=0));await s.close();}}}function pn(e,t,n,r,o,s){let a=()=>new Date;return {create:async h=>{if(!e)throw new Error("Cannot use create() on collection groups. Use set() with a specific document ID instead.");let v,g,u={...h};if(o&&(u[o]=a()),s&&(u[s]=a()),h[n]){g=h[n],v=e.doc(g);let m=r?{...u,[r]:v.path}:u;await v.set(m);}else {v=await e.add(u),g=v.id;let m={[n]:g};r&&(m[r]=v.path),await v.update(m);}let b=await v.get();return K(b.data())},set:async(...h)=>{let v=h[h.length-1],g=typeof v=="object"&&v!==null&&"merge"in v,u=g?h[h.length-2]:h[h.length-1],b=g?h.slice(0,-2):h.slice(0,-1),m=g?v:{merge:true},f={...u};s&&(f[s]=a());let l=t(...b),x=b[b.length-1];n&&x!=null&&(f[n]=x),r&&(f[r]=l.path),await l.set(f,m);let y=await l.get();return K(y.data())},update:async(...h)=>{let v=h.pop(),g=h,u={...v};s&&(u[s]=a());let b=t(...g);await b.update(u);let m=await b.get();return K(m.data())},delete:async(...h)=>{await t(...h).delete();}}}function fn(e,t,n,r,o){let s={};return s.byList=async(a,c,i="in",p={})=>{if(c.length===0)return [];let d=[],h=nn(c,30);for(let v of h){let g=e;g=g.where(a,i,v),p.select&&p.select.length>0&&(g=g.select(...p.select.map(b=>String(b)))),(await g.get()).forEach(b=>{let m=K(b.data());d.push(p.returnDoc?{data:m,doc:b}:m);});}return d},t.forEach(a=>{let c=`by${ce(String(a))}`;s[c]=async(i,p={})=>{let d=typeof p=="boolean"?{returnDoc:p}:p;if(String(a)===o){let m=await r(i).get();if(!m.exists)return null;let f=K(m.data());return d.returnDoc?{data:f,doc:m}:f}let h=e;h=h.where(String(a),"==",i).limit(1),d.select&&d.select.length>0&&(h=h.select(...d.select.map(b=>String(b))));let v=await h.get();if(v.empty)return null;let g=v.docs[0];if(!g)return null;let u=K(g.data());return d.returnDoc?{data:u,doc:g}:u};}),s}function yn(e,t,n,r){let o={},s=async(a,c)=>{if(!n||!r||c.length===0)return a;let i=c.map(p=>typeof p=="string"?{key:p}:{key:p.relation,select:p.select});return Promise.all(a.map(async p=>{let d=await Promise.all(i.map(async({key:v,select:g})=>{let u=n[v];if(!u)return [v,void 0];let b=r[u.repo];if(!b)return [v,void 0];let m=p[v];if(m==null)return [v,u.type==="one"?null:[]];let f=g?{select:g}:void 0;try{if(u.type==="one"){let l=`by${ce(u.key)}`,x=typeof b.get?.[l]=="function"?await b.get[l](m,f):null;return [v,x]}else {let l=`by${ce(u.key)}`,x=typeof b.query?.[l]=="function"?await b.query[l](m,f):[];return [v,x]}}catch(l){return console.error(`[include] Error populating "${v}":`,l),[v,u.type==="one"?null:[]]}})),h={};for(let[v,g]of d)v!==void 0&&(h[v]=g);return {...p,populated:h}}))};return t.forEach(a=>{let c=`by${ce(a)}`;o[c]=async(i,p={})=>{let d={...p,where:[[a,"==",i],...p.where??[]]};return (await we(e,d)).docs.map(v=>K(v.data()))};}),o.by=async a=>(await we(e,a)).docs.map(i=>K(i.data())),o.getAll=async(a={})=>(await we(e,a)).docs.map(i=>K(i.data())),o.onSnapshot=(a,c,i)=>pe(e,a).onSnapshot(d=>{c(d.docs.map(h=>K(h.data())));},i),o.paginate=async a=>{let{include:c,...i}=a,p=await tt(e,i);if(c&&c.length>0){let d=await s(p.data,c);return {...p,data:d}}return p},o.paginateAll=async function*(a){let{include:c,...i}=a;for await(let p of wt(e,i))if(c&&c.length>0){let d=await s(p.data,c);yield {...p,data:d};}else yield p;},o}function mn(e,t){return {populate:async(n,r)=>{if(!e.relationalKeys)return {...n,populated:{}};let o,s={};if(typeof r=="object"&&!Array.isArray(r))if("relation"in r){let i=r;o=[i.relation],i.select&&(s[i.relation]=i.select);}else if("relations"in r){let i=r;o=Array.isArray(i.relations)?i.relations:[i.relations],s=i.select??{};}else o=[];else o=Array.isArray(r)?r:[r];let a=await Promise.all(o.map(async i=>{let p=e.relationalKeys?.[i];if(!p)return console.warn(`[populate] Relation "${i}" not found in config`),[i,void 0];let d=t[p.repo];if(!d)return console.warn(`[populate] Repository "${p.repo}" not found in mapping`),[i,void 0];let h=n[i];if(h==null)return [i,p.type==="one"?null:[]];let v=s[i],g=v?{select:v}:void 0;try{if(p.type==="one"){let u=`by${ce(p.key)}`,b=typeof d.get?.[u]=="function"?await d.get[u](h,g):null;return [i,b]}else {let u=`by${ce(p.key)}`,b=typeof d.query?.[u]=="function"?await d.query[u](h,g):[];return [i,b]}}catch(u){return console.error(`[populate] Error populating "${i}":`,u),[i,p.type==="one"?null:[]]}})),c={};for(let[i,p]of a)p!==void 0&&(c[i]=p);return {...n,populated:c}}}}function gn(e,t){return {run:async n=>e.runTransaction(async r=>n({get:async(...s)=>{let a=t(...s),c=await r.get(a);return c.exists?K({...c.data(),docId:c.id}):null},set:(...s)=>{let a=s[s.length-1],c=typeof a=="object"&&a!==null&&"merge"in a,i=c?s[s.length-2]:s[s.length-1],p=c?s.slice(0,-2):s.slice(0,-1),d=c?a:{merge:true},h=t(...p);r.set(h,i,d);},update:(...s)=>{let a=s[s.length-1],c=s.slice(0,-1),i=t(...c);r.update(i,a);},delete:(...s)=>{let a=t(...s);r.delete(a);},raw:r}))}}function Ir(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 Tt(e,t,n={}){let r=t.isGroup?e.collectionGroup(t.path):e.collection(t.path),o=t.isGroup?null:e.collection(t.path),s=(...m)=>t.refCb(e,...m),a=fn(r,t.foreignKeys,o,s,t.documentKey),c=yn(r,t.queryKeys,t.relationalKeys,n),i=cn(r),p=pn(o,s,t.documentKey,t.pathKey,t.createdKey,t.updatedKey),d=dn(e,s,t.documentKey,t.pathKey,t.createdKey,t.updatedKey),h=gn(e,s),v=un(e,t.createdKey,t.updatedKey),g=mn(t,n),u=t.history,b=u?.enabled?ln(s,[t.documentKey,t.pathKey,t.createdKey,t.updatedKey].filter(m=>typeof m=="string"),t.path??"(unknown)",u):null;return {ref:r,documentRef:s,get:a,query:c,aggregate:i,...p,batch:d,transaction:h,bulk:v,...g,...b?{history:b}:{},_historySubcollection:b?u?.subcollection??"history":void 0,_historyConfig:u,schema:t.schema,relationalKeys:t.relationalKeys,_systemKeys:[t.documentKey,t.pathKey,t.createdKey,t.updatedKey].filter(m=>typeof m=="string"),_pathKey:t.pathKey??null,_isGroup:!!t.isGroup,_parentKeys:t.isGroup?Ir(t.refCb):[],_createdKey:t.createdKey??null}}var Nr="history";function _r(e,t){let n=t.ref?.path??void 0;return n?`${n}/{docId}`:(console.warn(`[HistoryTriggers] Cannot determine collection path for "${e}". Skipping.`),null)}function hn(e,t){let{onDocumentWritten:n}=t.deps,r={};for(let[o,s]of Object.entries(e)){let a=s._historyConfig??(typeof s.history=="object"&&s.history!==null&&"enabled"in s.history?s.history:void 0);if(!a?.enabled)continue;let c=a.subcollection??Nr,i=a.ttl??t.defaults?.ttl,p=t.repos?.[o],d;if(s._isGroup){if(!p?.triggerPath){console.warn(`[HistoryTriggers] Skipping collection-group repo "${o}". Provide a triggerPath in the history triggers repos override.`);continue}d=p.triggerPath;}else d=p?.triggerPath??_r(o,s);if(!d)continue;let h=s._systemKeys??[],v=h[0]??"docId",g=at(a);r[`${o}_onHistory`]=n(d,async u=>{try{let b=u.data?.before?.data(),m=u.data?.after?.data(),f;if(!b&&m)f="create";else if(b&&!m)f="delete";else if(b&&m)f="update";else return;let l=String(m?.[v]??b?.[v]??u.params?.docId??u.data?.after?.id??u.data?.before?.id??"");if(!l)return;let x=nt(b??{},m??{},{include:a.include,exclude:a.exclude,metaFields:g,systemKeys:h});if(f==="update"&&Object.keys(x).length===0)return;let y=st(m??b??null,a),w=rt({entityId:l,operation:f,changes:x,meta:y,config:a,ttlOverride:i}),R=u.data?.after?.ref??u.data?.before?.ref;if(!R)return;let C=R.collection(c);await ot(C,w,a,{repoName:o,docId:l,before:b??null,after:m??null});}catch(b){console.error(`[HistoryTriggers] Failed to record history for "${o}":`,b);}});}return r}function jr(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 Fr(e){let t=e.path??e.url??"/",n=t.indexOf("?");return n===-1?t:t.slice(0,n)}var te=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}=jr(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=Fr(t),s=null,a={};for(let p of this.routes){if(p.method!==r)continue;let d=o.match(p.pattern);if(d){s=p,a={},p.paramNames.forEach((h,v)=>{a[h]=decodeURIComponent(d[v+1]??"");});break}}let c=Object.assign(t,{params:a}),i=s?s.handler:this.notFoundHandler;try{await this.runMiddlewareChain(c,n,i);}catch(p){this.errorHandler(p,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();}};Be();var fe="__sync_version";var zr=new Set(["ZodOptional","ZodNullable","ZodDefault"]);function Hr(e){let t=e,n=false;for(;;){let r=Z(t);if(!zr.has(r))break;(r==="ZodOptional"||r==="ZodNullable")&&(n=true);let o=U(t);if(!o)break;t=o;}return {inner:t,nullable:n}}var Br={ZodString:"string",ZodNumber:"number",ZodBigInt:"bigint",ZodBoolean:"boolean",ZodDate:"timestamp",ZodEnum:"string",ZodNativeEnum:"string",ZodLiteral:"string"};function wn(e,t,n,r,o,s,a,c){for(let[i,p]of Object.entries(e)){let d=n?`${n}__${i}`:i;if(o.has(i)||o.has(d))continue;let{inner:h,nullable:v}=Hr(p),g=Z(h),u=r||v;if(g==="ZodObject"){let l=ee(h);wn(l,t,d,u,o,s,a,c);continue}let b=Br[g]??"json",m=d===a||i===a,f=s[d]??s[i]??d;c.push({name:f,sqlType:t.mapType(b),nullable:m?false:u,isPrimaryKey:m});}}function ct(e,t,n={}){let{primaryKey:r,exclude:o=[],columnMap:s={}}=n,a=new Set(o),c=ee(e),i=[];return wn(c,t,"",false,a,s,r,i),i.some(p=>p.name===fe)||i.push({name:fe,sqlType:t.mapType("bigint"),nullable:true,isPrimaryKey:false,description:"Monotonic publish version (Date.now() ms). Internal."}),i}function Rn(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(Rn)):e}function Sn(e,t,n){for(let[r,o]of Object.entries(e)){let s=t?`${t}__${r}`:r;o!=null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!Buffer.isBuffer(o)&&!(o instanceof Uint8Array)&&typeof o.toDate!="function"&&!("latitude"in o&&"longitude"in o)?Sn(o,s,n):n[s]=Rn(o);}}function Ze(e,t){let n=new Set(t?.exclude),r=t?.columnMap??{},o={};Sn(e,"",o);let s={};for(let[a,c]of Object.entries(o)){if(n.has(a))continue;let i=a.split("__")[0];if(i!==a&&n.has(i))continue;let p=r[a]??(a.includes("__")?r[a.split("__").pop()]:void 0)??a;s[p]=c;}return s}function Re(e,t){if(process.env.FUNCTIONS_EMULATOR==="true"){let o=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??"demo-project",s=process.env.FUNCTION_REGION??"us-central1",a=(process.env.FUNCTION_TARGET??"").replace(/\./g,"-");return `/${o}/${s}/${a}${t}`}let n=process.env.K_SERVICE,r=e.hostname??e.headers?.host??"";return n&&r.includes("cloudfunctions.net")?`/${n.toLowerCase()}${t}`:t}function oe(e,t,n){return `<!DOCTYPE html>
1
+ 'use strict';var jsxRuntime=require('hono/jsx/jsx-runtime'),firestore=require('firebase-admin/firestore'),crypto=require('crypto'),zod=require('zod'),server=require('hono/jsx/dom/server');var yr=Object.defineProperty;var Xe=(e,t)=>()=>(e&&(t=e(e=0)),t);var mr=(e,t)=>{for(var n in t)yr(e,n,{get:t[n],enumerable:true});};function Z(e){let t=e,n=t._zod?.def?.type;if(n)return Mr[n]??`Zod${n.charAt(0).toUpperCase()}${n.slice(1)}`;let r=t._def?.typeName;return r||""}function U(e){let t=e;if(t._zod?.def?.innerType)return t._zod.def.innerType;if(t._def?.innerType)return t._def.innerType}function bn(e){let t=e;if(t._zod?.def?.element)return t._zod.def.element;if(t._def?.type)return t._def.type}function vn(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 ee(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 ze(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 He(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 lt(e){let t=e;return Array.isArray(t._zod?.def?.values)?t._zod.def.values[0]:t._def?.value}function xn(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 Mr,Be=Xe(()=>{Mr={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 Fn({val:e}){return jsxRuntime.jsx("span",{class:"text-sm text-base-content/80 font-mono tabular-nums whitespace-nowrap",children:e.toLocaleString()})}function no({message:e}){return jsxRuntime.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:jsxRuntime.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",class:"size-3.5",children:jsxRuntime.jsx("path",{d:"M12 2 1 22h22L12 2zm0 6 7.5 13h-15L12 8zm-1 4v4h2v-4h-2zm0 5v2h2v-2h-2z"})})})}function Pe({val:e,mismatch:t}){let n=ro(e);return t?jsxRuntime.jsxs("span",{class:"inline-flex items-start gap-0.5",children:[n,jsxRuntime.jsx(no,{message:t})]}):n}function ro(e){if(e==null)return jsxRuntime.jsx("span",{class:"opacity-30 italic text-xs",children:"\u2014"});if(typeof e=="boolean")return e?jsxRuntime.jsx("span",{class:"badge badge-success badge-sm",children:"true"}):jsxRuntime.jsx("span",{class:"badge badge-error badge-sm",children:"false"});if(e instanceof Date)return jsxRuntime.jsx(Fn,{val:e});if(typeof e=="object"&&e!==null&&typeof e.toDate=="function")return jsxRuntime.jsx(Fn,{val:e.toDate()});if(typeof e=="number")return jsxRuntime.jsx("span",{class:"text-sm font-mono tabular-nums",children:String(e)});if(Array.isArray(e))return e.length===0?jsxRuntime.jsx("span",{class:"text-xs text-base-content/30",children:"[]"}):jsxRuntime.jsxs("ul",{class:"list-none p-0 m-0 space-y-0.5 text-xs",children:[e.slice(0,8).map((n,r)=>jsxRuntime.jsx("li",{class:"break-all",children:typeof n=="object"?JSON.stringify(n):String(n)},r)),e.length>8&&jsxRuntime.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?jsxRuntime.jsx("span",{class:"text-xs text-base-content/30",children:"{}"}):jsxRuntime.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])=>jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("dt",{class:"text-base-content/50 font-semibold whitespace-nowrap",children:r}),jsxRuntime.jsx("dd",{class:"break-all",children:String(o??"")})]})),n.length>8&&jsxRuntime.jsxs("dt",{class:"col-span-2 text-base-content/40 italic",children:["+",n.length-8," more\u2026"]})]})}let t=String(e);return jsxRuntime.jsx("span",{class:"text-sm break-all",children:t})}var pt=Xe(()=>{});function Ee(e){if(!e)return "unknown";let t=Pt(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 Pt(e){let t=Z(e);if(t==="ZodOptional"||t==="ZodNullable"||t==="ZodDefault"){let n=U(e);return n?Pt(n):e}return e}function De(e,t){if(!e)return;let n=t.split("."),r=e;for(let o of n){if(!r)return;let s=Pt(r);if(Z(s)!=="ZodObject")return;r=ee(s)[o];}return r}function io(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 Ue(e,t){if(e==="unknown")return null;let n=io(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 Et=Xe(()=>{Be();});var Hn={};mr(Hn,{PanelMany:()=>co,PanelOne:()=>lo,RightPanel:()=>Dt});function lo({doc:e,repoName:t,basePath:n,schema:r,columns:o}){if(!e)return jsxRuntime.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`,c=zn(r,o);return jsxRuntime.jsxs("div",{class:"space-y-4",children:[jsxRuntime.jsxs("div",{class:"flex items-center justify-between gap-2",children:[jsxRuntime.jsxs("div",{class:"text-xs text-base-content/60",children:[jsxRuntime.jsx("span",{class:"font-mono",children:t}),jsxRuntime.jsx("span",{class:"opacity-50",children:" \xB7 "}),jsxRuntime.jsx("span",{class:"font-mono break-all",children:s})]}),jsxRuntime.jsx("a",{href:a,class:"btn btn-sm btn-primary",children:"Edit \u2192"})]}),jsxRuntime.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(i=>{let p=e[i],d=c[i],h=d?Ue(d,p):null;return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("dt",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide pt-0.5",children:i}),jsxRuntime.jsx("dd",{class:"min-w-0",children:jsxRuntime.jsx(Pe,{val:p,mismatch:h})})]})})})]})}function co({docs:e,repoName:t,basePath:n,fk:r,fv:o,columns:s,schema:a,pagination:c}){let i=`${n}/${t}?fv_${r}=${encodeURIComponent(o)}`,p=zn(a,s);return jsxRuntime.jsxs("div",{class:"space-y-4",children:[jsxRuntime.jsxs("div",{class:"flex items-center justify-between gap-2",children:[jsxRuntime.jsxs("div",{class:"text-xs text-base-content/60",children:[jsxRuntime.jsx("span",{class:"font-mono",children:t}),jsxRuntime.jsx("span",{class:"opacity-50",children:" where "}),jsxRuntime.jsx("span",{class:"font-mono",children:r}),jsxRuntime.jsx("span",{class:"opacity-50",children:" = "}),jsxRuntime.jsx("span",{class:"font-mono break-all",children:o}),jsxRuntime.jsx("span",{class:"opacity-50",children:" \xB7 "}),jsxRuntime.jsxs("span",{children:[e.length," doc",e.length!==1?"s":""]})]}),jsxRuntime.jsx("a",{href:i,class:"btn btn-sm btn-outline",children:"Full view \u2192"})]}),jsxRuntime.jsx("div",{class:"overflow-x-auto rounded-box border border-base-300 bg-base-100",children:jsxRuntime.jsxs("table",{class:"table table-xs w-full",children:[jsxRuntime.jsx("thead",{children:jsxRuntime.jsxs("tr",{class:"bg-base-200/50",children:[s.map((d,h)=>jsxRuntime.jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:d},h)),jsxRuntime.jsx("th",{})]})}),jsxRuntime.jsx("tbody",{children:e.length===0?jsxRuntime.jsx("tr",{children:jsxRuntime.jsx("td",{colspan:s.length+1,class:"text-center py-10 text-base-content/40",children:"No related documents"})}):e.map((d,h)=>{let v=String(d.docId??d.id??""),g=`${n}/${t}/${encodeURIComponent(v)}/edit`;return jsxRuntime.jsxs("tr",{class:"hover",children:[s.map((u,b)=>{let m=d[u],f=p[u],l=f?Ue(f,m):null;return jsxRuntime.jsx("td",{class:"align-top py-1.5",children:jsxRuntime.jsx(Pe,{val:m,mismatch:l})},b)}),jsxRuntime.jsx("td",{class:"text-right py-1.5",children:jsxRuntime.jsx("a",{href:g,class:"btn btn-xs btn-ghost",children:"Edit"})})]},h)})})]})}),(c.hasPrev||c.hasNext)&&jsxRuntime.jsxs("div",{class:"flex justify-center items-center gap-2",children:[c.hasPrev?jsxRuntime.jsx("button",{type:"button",class:"btn btn-xs btn-outline","data-frs-panel-page":"prev","data-cursor":c.prevCursor,children:"\u2190 Previous"}):jsxRuntime.jsx("button",{class:"btn btn-xs btn-outline",disabled:true,children:"\u2190 Previous"}),c.hasNext?jsxRuntime.jsx("button",{type:"button",class:"btn btn-xs btn-outline","data-frs-panel-page":"next","data-cursor":c.nextCursor,children:"Next \u2192"}):jsxRuntime.jsx("button",{class:"btn btn-xs btn-outline",disabled:true,children:"Next \u2192"})]})]})}function zn(e,t){if(!e)return {};let n={};for(let r of t)n[r]=Ee(De(e,r));return n}var Dt,It=Xe(()=>{pt();Et();Dt=({basePath:e=""})=>jsxRuntime.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:[jsxRuntime.jsx("div",{class:"absolute inset-0 bg-black/30 opacity-0 transition-opacity duration-200 pointer-events-auto","data-frs-panel-backdrop":true}),jsxRuntime.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:[jsxRuntime.jsxs("header",{class:"flex items-center justify-between px-5 py-3 border-b border-base-300 bg-base-200/40 shrink-0",children:[jsxRuntime.jsx("h2",{class:"font-semibold text-base truncate","data-frs-panel-title":true,children:"Relation"}),jsxRuntime.jsx("button",{type:"button",class:"btn btn-sm btn-ghost btn-circle","data-frs-panel-close":true,"aria-label":"Close panel",children:"\u2715"})]}),jsxRuntime.jsx("div",{class:"flex-1 overflow-auto p-5 text-sm","data-frs-panel-body":true,children:jsxRuntime.jsx("div",{class:"flex items-center justify-center py-12 text-base-content/40",children:jsxRuntime.jsx("span",{class:"loading loading-spinner loading-md"})})})]})]});});function gr(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Fe(e,t){return t.orderBy&&t.orderBy.forEach(n=>{e=e.orderBy(String(n.field),n.direction??"asc");}),t.limit&&(e=e.limit(t.limit)),t.offset&&(e=e.offset(t.offset)),t.select&&t.select.length>0&&(e=e.select(...t.select.map(n=>String(n)))),t.startAt&&(e=Array.isArray(t.startAt)?e.startAt(...t.startAt):e.startAt(t.startAt)),t.startAfter&&(e=Array.isArray(t.startAfter)?e.startAfter(...t.startAfter):e.startAfter(t.startAfter)),t.endAt&&(e=Array.isArray(t.endAt)?e.endAt(...t.endAt):e.endAt(t.endAt)),t.endBefore&&(e=Array.isArray(t.endBefore)?e.endBefore(...t.endBefore):e.endBefore(t.endBefore)),e}function gt(e){let[,t,n]=e;return (t==="in"||t==="array-contains-any")&&Array.isArray(n)&&n.length>30}function Yt(e){let[t,n,r]=e;return gt(e)?gr(r,30).map(s=>[t,n,s]):[e]}function Ye(e,t){let n=e;for(let[r,o,s]of t)n=n.where(String(r),o,s);return n}async function en(e){let t=await Promise.all(e.map(o=>o.get())),n=new Map;t.forEach(o=>{o.docs.forEach(s=>{n.has(s.id)||n.set(s.id,s);});});let r=t[0];if(!r)throw new Error("No snapshots returned");return {...r,docs:Array.from(n.values()),size:n.size,empty:n.size===0}}async function we(e,t){let n=t.orWhere&&t.orWhere.length>0,r=t.orWhereGroups&&t.orWhereGroups.length>0;if(!n&&!r){if(!t.where||t.where.length===0)return Fe(e,t).get();if(!t.where.some(gt)){let h=Ye(e,t.where);return h=Fe(h,t),h.get()}let i=t.where.map(Yt),d=ht(i).map(h=>{let v=Ye(e,h);return v=Fe(v,t),v});return en(d)}let o=t.where??[],s=[...t.orWhere?.map(c=>[c])??[],...t.orWhereGroups??[]],a=[];for(let c of s){let i=[...o,...c];if(i.some(gt)){let d=i.map(Yt),v=ht(d).map(g=>{let u=Ye(e,g);return u=Fe(u,t),u});a.push(...v);}else {let d=Ye(e,i);d=Fe(d,t),a.push(d);}}return en(a)}function ht(e){if(e.length===0)return [[]];let t=e[0];if(e.length===1&&t)return t.map(s=>[s]);if(!t)return [[]];let n=e.slice(1),r=ht(n),o=[];for(let s of t)for(let a of r)o.push([s,...a]);return o}var bt="preserve";function hr(e){bt=e;}function vt(){return bt}function br(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function xt(e){if(e==null)return null;if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(e instanceof firestore.Timestamp)return e.toDate();if(br(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 vr(e){if(typeof e!="object"||e===null)return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function et(e){if(e instanceof firestore.Timestamp)return e.toDate();if(Array.isArray(e))return e.map(t=>et(t));if(vr(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=et(r);return t}return e}function K(e){return bt==="normalize"?et(e):e}function nn(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function ce(e){return e.charAt(0).toUpperCase()+e.slice(1)}function pe(e,t){return t.where&&t.where.forEach(([n,r,o])=>{e=e.where(String(n),r,o);}),t.orderBy&&t.orderBy.forEach(n=>{e=e.orderBy(String(n.field),n.direction??"asc");}),t.limit&&(e=e.limit(t.limit)),t.offset&&(e=e.offset(t.offset)),t.select&&t.select.length>0&&(e=e.select(...t.select.map(n=>String(n)))),t.startAt&&(e=Array.isArray(t.startAt)?e.startAt(...t.startAt):e.startAt(t.startAt)),t.startAfter&&(e=Array.isArray(t.startAfter)?e.startAfter(...t.startAfter):e.startAfter(t.startAfter)),t.endAt&&(e=Array.isArray(t.endAt)?e.endAt(...t.endAt):e.endAt(t.endAt)),t.endBefore&&(e=Array.isArray(t.endBefore)?e.endBefore(...t.endBefore):e.endBefore(t.endBefore)),e}async function tt(e,t){let n={...t,limit:t.pageSize+1};t.cursor&&(t.direction==="prev"?n.endBefore=t.cursor:n.startAfter=t.cursor);let o=(await we(e,n)).docs,s=o.length>t.pageSize,a=s?o.slice(0,t.pageSize):o,c=a.map(p=>K({...p.data(),docId:p.id})),i=t.direction==="prev";return {data:c,nextCursor:i?a.length>0?a[a.length-1]:void 0:s?a[a.length-1]:void 0,prevCursor:i?s?a[0]:void 0:a[0],hasNextPage:i?!!t.cursor:s,hasPrevPage:i?s:!!t.cursor,pageSize:c.length}}async function*wt(e,t){let n,r=true;for(;r;){let o=await tt(e,{...t,cursor:n,direction:"next"});yield o,r=o.hasNextPage,n=o.nextCursor;}}function Me(e){if(e===null)return "null";if(e===void 0)return "undefined";if(e instanceof firestore.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 rn(e,t){if(e===t)return true;if(e===null||t===null||e===void 0||t===void 0)return e===t;if(e instanceof firestore.Timestamp&&t instanceof firestore.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(e.length!==t.length)return false;for(let n=0;n<e.length;n++)if(!rn(e[n],t[n]))return false;return true}if(typeof e=="object"&&typeof t=="object")try{return JSON.stringify(e)===JSON.stringify(t)}catch{return false}return false}function nt(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??{},c=new Set([...Object.keys(s),...Object.keys(a)]),i={};for(let p of c){if(r.has(p)||o&&!o.has(p))continue;let d=s[p],h=a[p];rn(d,h)||(i[p]={oldValue:d===void 0?null:d,newValue:h===void 0?null:h,type:{old:Me(d),new:Me(h)}});}return i}var xr=5;function wr(e){return e.schemaVersion===2}function on(e){if(typeof e!="string")return "object";switch(e){case "string":case "number":case "boolean":case "object":case "array":case "timestamp":case "date":case "null":case "undefined":return e;default:return "object"}}function Rr(e){return {historyDocId:e.historyDocId,historyToObjectId:e.historyToObjectId,historySetAt:e.historySetAt,schemaVersion:2,operation:e.operation,meta:e.meta??{},changes:e.changes??{}}}function Sr(e){let t={};e.historyUserId!==void 0&&(t.userId=e.historyUserId??null),e.historyUserEmail!==void 0&&(t.userEmail=e.historyUserEmail??null);let n=e.extraHistoryDetails??null;n&&(n.reason!==void 0&&(t.reason=n.reason??null),n.comment!==void 0&&(t.comment=n.comment??null));let r={},o=false;if(e.historyDetails&&typeof e.historyDetails=="object")for(let[s,a]of Object.entries(e.historyDetails))r[s]=a,o=true;if(e.extraContentKeys&&typeof e.extraContentKeys=="object")for(let[s,a]of Object.entries(e.extraContentKeys))r[`content.${s}`]=a,o=true;return o&&(t.extras=r),t}function Tr(e){let t=e.changes?.oldValue??null,n=e.changes?.newValue??null,r=e.types?.oldValue,o=e.types?.newValue;return {oldValue:t,newValue:n,type:{old:r?on(r):Me(t),new:o?on(o):Me(n)}}}function kr(e){let t=Tr(e),n=Sr(e);return {historyDocId:e.historyDocId,historyToObjectId:e.historyToObjectId,historySetAt:e.historySetAt,schemaVersion:1,operation:"update",meta:n,changes:{[e.field]:t}}}function Cr(e,t,n){return Math.abs(e.toMillis()-t.toMillis())<=n}function Or(e,t){return (e.userId??null)===(t.userId??null)}function sn(e,t={}){let n=t.groupToleranceMs??xr,r=[];for(let o of e){if(wr(o)){r.push(Rr(o));continue}let a=kr(o),c=r[r.length-1];c&&c.schemaVersion===1&&Cr(c.historySetAt,a.historySetAt,n)&&Or(c.meta,a.meta)?Object.assign(c.changes,a.changes):r.push(a);}return r}var Ar=7e5;function rt(e){let t=e.ttlOverride??e.config.ttl,r={schemaVersion:2,historyDocId:crypto.randomUUID(),historyToObjectId:e.entityId,historySetAt:firestore.Timestamp.now(),operation:e.operation,meta:e.meta,changes:e.changes};t&&(r.expiresAt=firestore.Timestamp.fromMillis(Date.now()+t.days*24*60*60*1e3));let o=s=>{try{return Buffer.byteLength(JSON.stringify(s,(a,c)=>c instanceof firestore.Timestamp?c.toMillis():c),"utf8")}catch{return 0}};if(o(r.changes)>Ar){let s={};for(let[a,c]of Object.entries(r.changes)){let i=o(c.oldValue),p=o(c.newValue);s[a]={oldValue:i>5e4?"[truncated]":c.oldValue,newValue:p>5e4?"[truncated]":c.newValue,type:c.type};}r.changes=s,r._truncated=true;}return r}async function ot(e,t,n,r){let o=t;return n.onBeforeWrite&&(o=await n.onBeforeWrite(t,r)),o?(await e.doc(o.historyDocId).set(o),{written:true,entry:o}):{written:false,reason:"dropped-by-onBeforeWrite"}}function st(e,t){let n=e??{},r={},o=t.meta;if(!o)return r;let s=d=>{if(!d)return;let h=n[d];return h===void 0||h===null?null:String(h)},a=s(o.userId);a!==void 0&&(r.userId=a);let c=s(o.userEmail);c!==void 0&&(r.userEmail=c);let i=s(o.reason);i!==void 0&&(r.reason=i);let p=s(o.comment);if(p!==void 0&&(r.comment=p),o.extras&&o.extras.length>0){let d={},h=false;for(let v of o.extras)v in n&&(d[v]=n[v],h=true);h&&(r.extras=d);}return r}function at(e){let t=e.meta;if(!t)return [];let n=[];return t.userId&&n.push(t.userId),t.userEmail&&n.push(t.userEmail),t.reason&&n.push(t.reason),t.comment&&n.push(t.comment),t.extras&&n.push(...t.extras),n}var Pr="history",Er=50;function an(e,t,n){return e(...n).collection(t)}function Dr(e){return String(e[e.length-1]??"")}function ln(e,t,n,r){if(!r?.enabled)return null;let o=r.subcollection??Pr;async function s(...d){let h={},v=d,g=d[d.length-1];g!==null&&typeof g=="object"&&!(g instanceof firestore.Timestamp)&&("limit"in g||"cursor"in g||"direction"in g)&&(h=g,v=d.slice(0,-1));let u=an(e,o,v),b=h.direction??"desc",m=u.orderBy("historySetAt",b);return h.cursor&&(m=m.startAfter(h.cursor)),h.limit&&h.limit>0&&(m=m.limit(h.limit)),(await m.get()).docs.map(l=>({id:l.id,data:l.data()}))}async function a(...d){let h={},v=d,g=d[d.length-1];g!==null&&typeof g=="object"&&!(g instanceof firestore.Timestamp)&&("limit"in g||"cursor"in g||"direction"in g||"fields"in g||"operations"in g)&&(h=g,v=d.slice(0,-1));let u=h.limit??Er,b=Math.max(u,Math.min(u*8,500)),m=await s(...v,{limit:b,cursor:h.cursor,direction:h.direction??"desc"}),f=sn(m.map(l=>l.data));if(h.fields&&h.fields.length>0){let l=new Set(h.fields);f=f.filter(x=>Object.keys(x.changes).some(y=>l.has(y)));}if(h.operations&&h.operations.length>0){let l=new Set(h.operations);f=f.filter(x=>l.has(x.operation));}return f.slice(0,u)}async function c(...d){let h=d[d.length-1],v={},g,u;return h!==null&&typeof h=="object"&&!(h instanceof firestore.Timestamp)?(v=h,g=d[d.length-2],u=d.slice(0,-2)):(g=h,u=d.slice(0,-1)),a(...u,{...v,fields:[g]})}async function i(...d){let h=d[d.length-1],v={},g,u;return h!==null&&typeof h=="object"&&!(h instanceof firestore.Timestamp)?(v=h,g=d[d.length-2],u=d.slice(0,-2)):(g=h,u=d.slice(0,-1)),a(...u,{...v,operations:[g]})}async function p(...d){let h=d[d.length-1],v=d.slice(0,-1),g=Dr(v),u=nt(h.before??{},h.after??{},{include:r.include,exclude:r.exclude,metaFields:at(r),systemKeys:t});if(h.operation==="update"&&Object.keys(u).length===0)return null;let m={...st(h.after??h.before??null,r),...h.meta??{}},f=rt({entityId:g,operation:h.operation,changes:u,meta:m,config:r}),l=an(e,o,v),x=await ot(l,f,r,{repoName:n,docId:g,before:h.before??null,after:h.after??null});return !x.written||!x.entry?null:{historyDocId:x.entry.historyDocId,historyToObjectId:x.entry.historyToObjectId,historySetAt:x.entry.historySetAt,schemaVersion:2,operation:x.entry.operation,meta:x.entry.meta,changes:x.entry.changes}}return {list:a,raw:s,byField:c,byOperation:i,recordManual:p}}function cn(e){return {count:async(t={})=>{let n=e;return n=pe(n,t),(await n.count().get()).data().count},sum:async(t,n={})=>{let r=e;r=pe(r,n);let o=await r.get(),s=0;return o.forEach(a=>{let c=a.data()[t];typeof c=="number"&&(s+=c);}),s},average:async(t,n={})=>{let r=e;r=pe(r,n);let o=await r.get();if(o.empty)return null;let s=0,a=0;return o.forEach(c=>{let i=c.data()[t];typeof i=="number"&&(s+=i,a++);}),a>0?s/a:null}}}function dn(e,t,n,r,o,s){let a=()=>new Date;return {create:()=>{let c=e.batch();return {batch:c,set:(...i)=>{let p=i[i.length-1],d=typeof p=="object"&&p!==null&&"merge"in p,h=d?i[i.length-2]:i[i.length-1],v=d?i.slice(0,-2):i.slice(0,-1),g=d?p:{merge:true},u=t(...v),b={...h},m=v[v.length-1];n&&m&&(b[n]=m),r&&(b[r]=u.path),o&&(b[o]=a()),s&&(b[s]=a()),c.set(u,b,g);},update:(...i)=>{let p=i.pop(),h=t(...i),v={...p};s&&(v[s]=a()),c.update(h,v);},delete:(...i)=>{let p=t(...i);c.delete(p);},commit:async()=>{await c.commit();}}}}}function un(e,t,n){let r=()=>new Date;return {set:async o=>{let s=e.bulkWriter(),a=0;for(let c of o){if(!c)continue;let{docRef:i,data:p,merge:d=true}=c,h={...p};t&&(h[t]=r()),n&&(h[n]=r()),s.set(i,h,{merge:d}),a++,a>=500&&(await s.flush(),a=0);}await s.close();},update:async o=>{let s=e.bulkWriter(),a=0;for(let c of o){if(!c)continue;let{docRef:i,data:p}=c,d={...p};n&&(d[n]=r()),s.update(i,d),a++,a>=500&&(await s.flush(),a=0);}await s.close();},delete:async o=>{let s=e.bulkWriter(),a=0;for(let c of o)c&&(s.delete(c),a++,a>=500&&(await s.flush(),a=0));await s.close();}}}function pn(e,t,n,r,o,s){let a=()=>new Date;return {create:async h=>{if(!e)throw new Error("Cannot use create() on collection groups. Use set() with a specific document ID instead.");let v,g,u={...h};if(o&&(u[o]=a()),s&&(u[s]=a()),h[n]){g=h[n],v=e.doc(g);let m=r?{...u,[r]:v.path}:u;await v.set(m);}else {v=await e.add(u),g=v.id;let m={[n]:g};r&&(m[r]=v.path),await v.update(m);}let b=await v.get();return K(b.data())},set:async(...h)=>{let v=h[h.length-1],g=typeof v=="object"&&v!==null&&"merge"in v,u=g?h[h.length-2]:h[h.length-1],b=g?h.slice(0,-2):h.slice(0,-1),m=g?v:{merge:true},f={...u};s&&(f[s]=a());let l=t(...b),x=b[b.length-1];n&&x!=null&&(f[n]=x),r&&(f[r]=l.path),await l.set(f,m);let y=await l.get();return K(y.data())},update:async(...h)=>{let v=h.pop(),g=h,u={...v};s&&(u[s]=a());let b=t(...g);await b.update(u);let m=await b.get();return K(m.data())},delete:async(...h)=>{await t(...h).delete();}}}function fn(e,t,n,r,o){let s={};return s.byList=async(a,c,i="in",p={})=>{if(c.length===0)return [];let d=[],h=nn(c,30);for(let v of h){let g=e;g=g.where(a,i,v),p.select&&p.select.length>0&&(g=g.select(...p.select.map(b=>String(b)))),(await g.get()).forEach(b=>{let m=K(b.data());d.push(p.returnDoc?{data:m,doc:b}:m);});}return d},t.forEach(a=>{let c=`by${ce(String(a))}`;s[c]=async(i,p={})=>{let d=typeof p=="boolean"?{returnDoc:p}:p;if(String(a)===o){let m=await r(i).get();if(!m.exists)return null;let f=K(m.data());return d.returnDoc?{data:f,doc:m}:f}let h=e;h=h.where(String(a),"==",i).limit(1),d.select&&d.select.length>0&&(h=h.select(...d.select.map(b=>String(b))));let v=await h.get();if(v.empty)return null;let g=v.docs[0];if(!g)return null;let u=K(g.data());return d.returnDoc?{data:u,doc:g}:u};}),s}function yn(e,t,n,r){let o={},s=async(a,c)=>{if(!n||!r||c.length===0)return a;let i=c.map(p=>typeof p=="string"?{key:p}:{key:p.relation,select:p.select});return Promise.all(a.map(async p=>{let d=await Promise.all(i.map(async({key:v,select:g})=>{let u=n[v];if(!u)return [v,void 0];let b=r[u.repo];if(!b)return [v,void 0];let m=p[v];if(m==null)return [v,u.type==="one"?null:[]];let f=g?{select:g}:void 0;try{if(u.type==="one"){let l=`by${ce(u.key)}`,x=typeof b.get?.[l]=="function"?await b.get[l](m,f):null;return [v,x]}else {let l=`by${ce(u.key)}`,x=typeof b.query?.[l]=="function"?await b.query[l](m,f):[];return [v,x]}}catch(l){return console.error(`[include] Error populating "${v}":`,l),[v,u.type==="one"?null:[]]}})),h={};for(let[v,g]of d)v!==void 0&&(h[v]=g);return {...p,populated:h}}))};return t.forEach(a=>{let c=`by${ce(a)}`;o[c]=async(i,p={})=>{let d={...p,where:[[a,"==",i],...p.where??[]]};return (await we(e,d)).docs.map(v=>K(v.data()))};}),o.by=async a=>(await we(e,a)).docs.map(i=>K(i.data())),o.getAll=async(a={})=>(await we(e,a)).docs.map(i=>K(i.data())),o.onSnapshot=(a,c,i)=>pe(e,a).onSnapshot(d=>{c(d.docs.map(h=>K(h.data())));},i),o.paginate=async a=>{let{include:c,...i}=a,p=await tt(e,i);if(c&&c.length>0){let d=await s(p.data,c);return {...p,data:d}}return p},o.paginateAll=async function*(a){let{include:c,...i}=a;for await(let p of wt(e,i))if(c&&c.length>0){let d=await s(p.data,c);yield {...p,data:d};}else yield p;},o}function mn(e,t){return {populate:async(n,r)=>{if(!e.relationalKeys)return {...n,populated:{}};let o,s={};if(typeof r=="object"&&!Array.isArray(r))if("relation"in r){let i=r;o=[i.relation],i.select&&(s[i.relation]=i.select);}else if("relations"in r){let i=r;o=Array.isArray(i.relations)?i.relations:[i.relations],s=i.select??{};}else o=[];else o=Array.isArray(r)?r:[r];let a=await Promise.all(o.map(async i=>{let p=e.relationalKeys?.[i];if(!p)return console.warn(`[populate] Relation "${i}" not found in config`),[i,void 0];let d=t[p.repo];if(!d)return console.warn(`[populate] Repository "${p.repo}" not found in mapping`),[i,void 0];let h=n[i];if(h==null)return [i,p.type==="one"?null:[]];let v=s[i],g=v?{select:v}:void 0;try{if(p.type==="one"){let u=`by${ce(p.key)}`,b=typeof d.get?.[u]=="function"?await d.get[u](h,g):null;return [i,b]}else {let u=`by${ce(p.key)}`,b=typeof d.query?.[u]=="function"?await d.query[u](h,g):[];return [i,b]}}catch(u){return console.error(`[populate] Error populating "${i}":`,u),[i,p.type==="one"?null:[]]}})),c={};for(let[i,p]of a)p!==void 0&&(c[i]=p);return {...n,populated:c}}}}function gn(e,t){return {run:async n=>e.runTransaction(async r=>n({get:async(...s)=>{let a=t(...s),c=await r.get(a);return c.exists?K({...c.data(),docId:c.id}):null},set:(...s)=>{let a=s[s.length-1],c=typeof a=="object"&&a!==null&&"merge"in a,i=c?s[s.length-2]:s[s.length-1],p=c?s.slice(0,-2):s.slice(0,-1),d=c?a:{merge:true},h=t(...p);r.set(h,i,d);},update:(...s)=>{let a=s[s.length-1],c=s.slice(0,-1),i=t(...c);r.update(i,a);},delete:(...s)=>{let a=t(...s);r.delete(a);},raw:r}))}}function Ir(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 Tt(e,t,n={}){let r=t.isGroup?e.collectionGroup(t.path):e.collection(t.path),o=t.isGroup?null:e.collection(t.path),s=(...m)=>t.refCb(e,...m),a=fn(r,t.foreignKeys,o,s,t.documentKey),c=yn(r,t.queryKeys,t.relationalKeys,n),i=cn(r),p=pn(o,s,t.documentKey,t.pathKey,t.createdKey,t.updatedKey),d=dn(e,s,t.documentKey,t.pathKey,t.createdKey,t.updatedKey),h=gn(e,s),v=un(e,t.createdKey,t.updatedKey),g=mn(t,n),u=t.history,b=u?.enabled?ln(s,[t.documentKey,t.pathKey,t.createdKey,t.updatedKey].filter(m=>typeof m=="string"),t.path??"(unknown)",u):null;return {ref:r,documentRef:s,get:a,query:c,aggregate:i,...p,batch:d,transaction:h,bulk:v,...g,...b?{history:b}:{},_historySubcollection:b?u?.subcollection??"history":void 0,_historyConfig:u,schema:t.schema,relationalKeys:t.relationalKeys,_systemKeys:[t.documentKey,t.pathKey,t.createdKey,t.updatedKey].filter(m=>typeof m=="string"),_pathKey:t.pathKey??null,_isGroup:!!t.isGroup,_parentKeys:t.isGroup?Ir(t.refCb):[],_createdKey:t.createdKey??null}}var Nr="history";function _r(e,t){let n=t.ref?.path??void 0;return n?`${n}/{docId}`:(console.warn(`[HistoryTriggers] Cannot determine collection path for "${e}". Skipping.`),null)}function hn(e,t){let{onDocumentWritten:n}=t.deps,r={};for(let[o,s]of Object.entries(e)){let a=s._historyConfig??(typeof s.history=="object"&&s.history!==null&&"enabled"in s.history?s.history:void 0);if(!a?.enabled)continue;let c=a.subcollection??Nr,i=a.ttl??t.defaults?.ttl,p=t.repos?.[o],d;if(s._isGroup){if(!p?.triggerPath){console.warn(`[HistoryTriggers] Skipping collection-group repo "${o}". Provide a triggerPath in the history triggers repos override.`);continue}d=p.triggerPath;}else d=p?.triggerPath??_r(o,s);if(!d)continue;let h=s._systemKeys??[],v=h[0]??"docId",g=at(a);r[`${o}_onHistory`]=n(d,async u=>{try{let b=u.data?.before?.data(),m=u.data?.after?.data(),f;if(!b&&m)f="create";else if(b&&!m)f="delete";else if(b&&m)f="update";else return;let l=String(m?.[v]??b?.[v]??u.params?.docId??u.data?.after?.id??u.data?.before?.id??"");if(!l)return;let x=nt(b??{},m??{},{include:a.include,exclude:a.exclude,metaFields:g,systemKeys:h});if(f==="update"&&Object.keys(x).length===0)return;let y=st(m??b??null,a),w=rt({entityId:l,operation:f,changes:x,meta:y,config:a,ttlOverride:i}),R=u.data?.after?.ref??u.data?.before?.ref;if(!R)return;let C=R.collection(c);await ot(C,w,a,{repoName:o,docId:l,before:b??null,after:m??null});}catch(b){console.error(`[HistoryTriggers] Failed to record history for "${o}":`,b);}});}return r}function jr(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 Fr(e){let t=e.path??e.url??"/",n=t.indexOf("?");return n===-1?t:t.slice(0,n)}var te=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}=jr(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=Fr(t),s=null,a={};for(let p of this.routes){if(p.method!==r)continue;let d=o.match(p.pattern);if(d){s=p,a={},p.paramNames.forEach((h,v)=>{a[h]=decodeURIComponent(d[v+1]??"");});break}}let c=Object.assign(t,{params:a}),i=s?s.handler:this.notFoundHandler;try{await this.runMiddlewareChain(c,n,i);}catch(p){this.errorHandler(p,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();}};Be();var fe="__sync_version";var zr=new Set(["ZodOptional","ZodNullable","ZodDefault"]);function Hr(e){let t=e,n=false;for(;;){let r=Z(t);if(!zr.has(r))break;(r==="ZodOptional"||r==="ZodNullable")&&(n=true);let o=U(t);if(!o)break;t=o;}return {inner:t,nullable:n}}var Br={ZodString:"string",ZodNumber:"number",ZodBigInt:"bigint",ZodBoolean:"boolean",ZodDate:"timestamp",ZodEnum:"string",ZodNativeEnum:"string",ZodLiteral:"string"};function wn(e,t,n,r,o,s,a,c){for(let[i,p]of Object.entries(e)){let d=n?`${n}__${i}`:i;if(o.has(i)||o.has(d))continue;let{inner:h,nullable:v}=Hr(p),g=Z(h),u=r||v;if(g==="ZodObject"){let l=ee(h);wn(l,t,d,u,o,s,a,c);continue}let b=Br[g]??"json",m=d===a||i===a,f=s[d]??s[i]??d;c.push({name:f,sqlType:t.mapType(b),nullable:m?false:u,isPrimaryKey:m});}}function ct(e,t,n={}){let{primaryKey:r,exclude:o=[],columnMap:s={}}=n,a=new Set(o),c=ee(e),i=[];return wn(c,t,"",false,a,s,r,i),i.some(p=>p.name===fe)||i.push({name:fe,sqlType:t.mapType("bigint"),nullable:true,isPrimaryKey:false,description:"Monotonic publish version (Date.now() ms). Internal."}),i}function Rn(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(Rn)):e}function Sn(e,t,n){for(let[r,o]of Object.entries(e)){let s=t?`${t}__${r}`:r;o!=null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!Buffer.isBuffer(o)&&!(o instanceof Uint8Array)&&typeof o.toDate!="function"&&!("latitude"in o&&"longitude"in o)?Sn(o,s,n):n[s]=Rn(o);}}function Ze(e,t){let n=new Set(t?.exclude),r=t?.columnMap??{},o={};Sn(e,"",o);let s={};for(let[a,c]of Object.entries(o)){if(n.has(a))continue;let i=a.split("__")[0];if(i!==a&&n.has(i))continue;let p=r[a]??(a.includes("__")?r[a.split("__").pop()]:void 0)??a;s[p]=c;}return s}function Re(e,t){if(process.env.FUNCTIONS_EMULATOR==="true"){let o=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??"demo-project",s=process.env.FUNCTION_REGION??"us-central1",a=(process.env.FUNCTION_TARGET??"").replace(/\./g,"-");return `/${o}/${s}/${a}${t}`}let n=process.env.K_SERVICE,r=e.hostname??e.headers?.host??"";return n&&r.includes("cloudfunctions.net")?`/${n.toLowerCase()}${t}`:t}function oe(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>
@@ -223,7 +223,7 @@ ${n}
223
223
  <button type="submit" class="btn btn-primary btn-sm">${N(r)}</button>
224
224
  <button type="button" class="btn btn-ghost btn-sm" onclick="history.back()">Cancel</button>
225
225
  </div>
226
- </form>`}ut();var _n=`// \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
226
+ </form>`}var Qr=new Set(["<","<=",">",">=","!="]),Gr=new Set(["array-contains","array-contains-any"]);function Ct(e){return e==="desc"?"DESCENDING":"ASCENDING"}function Wr(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 i of r)if(i.op==="=="||i.op==="in"||i.op==="not-in"){if(a.has(i.field))continue;a.add(i.field),s.push({fieldPath:i.field,order:"ASCENDING"});}for(let i of r)if(Gr.has(i.op)){if(a.has(i.field))continue;a.add(i.field),s.push({fieldPath:i.field,arrayConfig:"CONTAINS"});}for(let i of r)if(Qr.has(i.op)){if(a.has(i.field))continue;a.add(i.field);let p=o?.field===i.field?Ct(o.dir):"ASCENDING";s.push({fieldPath:i.field,order:p});}if(o&&!a.has(o.field)&&s.push({fieldPath:o.field,order:Ct(o.dir)}),s.length===1&&n)return eo(e,t,s[0]);let c=o&&s.some(i=>i.fieldPath===o.field)?Ct(o.dir):"ASCENDING";return s.push({fieldPath:"__name__",order:c}),Xr(e,t,n,s)}function Xr(e,t,n,r,o="(default)"){let s=`projects/${e}/databases/${o}/collectionGroups/${t}/indexes/_`,a=[...At(1,s),...ut(2,n?2:1)];for(let p of r)a.push(...Nn(3,_n(p)));let c=o==="(default)"?"-default-":o,i=encodeURIComponent(jn(a));return `https://console.firebase.google.com/project/${e}/firestore/databases/${c}/indexes?create_composite=${i}`}function Yr(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function Ot(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function $t(e,t){return e<<3|t}function At(e,t){let n=Array.from(new TextEncoder().encode(t));return [$t(e,2),...Ot(n.length),...n]}function ut(e,t){return [$t(e,0),...Ot(t)]}function Nn(e,t){return [$t(e,2),...Ot(t.length),...t]}function _n(e){let t=[...At(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...ut(3,1)):t.push(...ut(2,e.order==="DESCENDING"?2:1)),t}function jn(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 eo(e,t,n,r="(default)"){let o=`projects/${e}/databases/${r}/collectionGroups/${t}/fields/${n.fieldPath}`,s=[...At(1,o),...ut(2,2),...Nn(3,_n(n))],a=r==="(default)"?"-default-":r,c=encodeURIComponent(jn(s));return `https://console.firebase.google.com/project/${e}/firestore/databases/${a}/indexes/automatic?create_exemption=${c}`}function to(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 Te(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function Ke(e,t){let n=e??{},r=Te(e),o;if(r&&(o=n.message?Yr(n.message):void 0,!o)){let s=to(t.ref);if(s){let a=Wr(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}}pt();var Mn=`// \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
227
227
  function frsGetBasePath() {
228
228
  var root = document.querySelector("[data-frs-panel-root]");
229
229
  var bp = root && root.getAttribute("data-frs-base-path");
@@ -1132,7 +1132,7 @@ function initColumnReorder(table) {
1132
1132
  });
1133
1133
  });
1134
1134
  }
1135
- `;function Ke(){return jsxRuntime.jsx("script",{dangerouslySetInnerHTML:{__html:_n}})}At();function me(e){return "<!DOCTYPE html>"+server.renderToString(e)}var oo=["corporate","silk","dark"],so=()=>jsxRuntime.jsxs("div",{class:"dropdown dropdown-end","data-frs-theme-switcher":true,children:[jsxRuntime.jsxs("button",{type:"button",tabIndex:0,class:"btn btn-sm btn-ghost text-neutral-content gap-1.5","aria-label":"Switch theme",children:[jsxRuntime.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:[jsxRuntime.jsx("circle",{cx:"12",cy:"12",r:"4"}),jsxRuntime.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"})]}),jsxRuntime.jsx("span",{class:"text-xs hidden sm:inline","data-frs-theme-current":true,children:"Theme"})]}),jsxRuntime.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:oo.map(e=>jsxRuntime.jsx("li",{children:jsxRuntime.jsxs("button",{type:"button","data-frs-theme":e,class:"capitalize justify-between",children:[jsxRuntime.jsx("span",{children:e}),jsxRuntime.jsx("span",{class:"hidden text-primary","data-frs-theme-check":e,children:"\u2713"})]})},e))})]}),ge=({opts:e,children:t})=>{let{title:n,breadcrumb:r,flash:o,basePath:s="/"}=e;return jsxRuntime.jsxs("html",{lang:"en","data-theme":"corporate",children:[jsxRuntime.jsxs("head",{children:[jsxRuntime.jsx("meta",{charset:"UTF-8"}),jsxRuntime.jsx("meta",{name:"viewport",content:"width=device-width, initial-scale=1"}),jsxRuntime.jsxs("title",{children:[n," \u2014 FRS Admin"]}),jsxRuntime.jsx("script",{dangerouslySetInnerHTML:{__html:"(function(){try{var t=localStorage.getItem('frs-admin-theme');if(t){document.documentElement.setAttribute('data-theme',t);}}catch(_){}})();"}}),jsxRuntime.jsx("link",{href:"https://cdn.jsdelivr.net/npm/daisyui@5/themes.css",rel:"stylesheet",type:"text/css"}),jsxRuntime.jsx("link",{href:"https://cdn.jsdelivr.net/npm/daisyui@5/daisyui.css",rel:"stylesheet",type:"text/css"}),jsxRuntime.jsx("script",{src:"https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"})]}),jsxRuntime.jsxs("body",{class:"bg-base-200/50 min-h-screen flex flex-col",children:[jsxRuntime.jsxs("div",{class:"navbar bg-neutral text-neutral-content shadow-sm sticky top-0 z-50 px-6",children:[jsxRuntime.jsx("div",{class:"flex-1",children:jsxRuntime.jsx("a",{href:s,class:"font-bold text-lg tracking-tight hover:opacity-80 transition-opacity",children:"FRS Admin"})}),jsxRuntime.jsx("div",{class:"flex-none",children:jsxRuntime.jsx(so,{})})]}),jsxRuntime.jsxs("main",{class:"px-6 py-8 w-full flex-1",children:[r&&r.length>0&&jsxRuntime.jsx("div",{class:"text-sm breadcrumbs mb-4",children:jsxRuntime.jsx("ul",{children:r.map((a,c)=>a.href?jsxRuntime.jsx("li",{children:jsxRuntime.jsx("a",{href:a.href,children:a.label})},c):jsxRuntime.jsx("li",{class:"text-base-content/60",children:a.label},c))})}),jsxRuntime.jsx("h1",{class:"text-2xl font-bold mb-6",children:n}),o&&jsxRuntime.jsxs("div",{role:"alert",class:`alert ${o.type==="success"?"alert-success":o.type==="warning"?"alert-warning":"alert-error"} mb-6`,children:[jsxRuntime.jsx("span",{class:"flex-1",children:o.message}),o.action&&jsxRuntime.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]}),jsxRuntime.jsx($t,{basePath:s}),jsxRuntime.jsx(Ke,{})]})]})};function Pt(e,t){return me(jsxRuntime.jsx(ge,{opts:t,children:jsxRuntime.jsx("div",{dangerouslySetInnerHTML:{__html:e}})}))}function Et(e,t){return me(jsxRuntime.jsx(ge,{opts:{title:"Repositories",basePath:t},children:e.length===0?jsxRuntime.jsxs("div",{class:"text-center py-20 text-base-content/50",children:[jsxRuntime.jsx("p",{class:"text-lg font-medium mb-1",children:"No repositories configured"}),jsxRuntime.jsx("p",{class:"text-sm",children:"Add a repository to your FRS config to get started."})]}):jsxRuntime.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=>jsxRuntime.jsx("a",{href:`${t}/${n.name}`,class:"card bg-base-100 border border-base-300 hover:shadow-md no-underline transition-shadow",children:jsxRuntime.jsxs("div",{class:"card-body p-5",children:[jsxRuntime.jsx("h2",{class:"card-title text-sm font-semibold",children:n.name}),jsxRuntime.jsx("p",{class:"text-xs text-base-content/50 font-mono",children:n.path})]})},n.name))})}))}var zn=[{value:"==",label:"="},{value:"!=",label:"\u2260"},{value:"in",label:"in"},{value:"not-in",label:"not in"}],ao=[{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"}],io=[{value:"array-contains",label:"contains"},{value:"array-contains-any",label:"contains any"}];function lo(e){switch(e){case "ZodNumber":case "ZodBigInt":case "ZodDate":return ao;case "ZodBoolean":return zn;case "ZodArray":return io;default:return zn}}var he="__null__";function co(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="${he}"]');if(!o){o=document.createElement('option');o.value='${he}';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='${he}';i.readOnly=true;}i.style.opacity='0.55';}else{i.style.opacity='';if(i.tagName==='SELECT'){var o2=i.querySelector('option[value="${he}"][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!=='${he}')?i.dataset._prev:'';}}})(this)`}function uo(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 Ue({inputId:e,active:t}){return jsxRuntime.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:[jsxRuntime.jsx("input",{type:"checkbox",class:"checkbox checkbox-xs",checked:t,onchange:co(e)}),jsxRuntime.jsx("span",{children:"\u2205"})]})}function po({col:e,active:t}){let n=t?.value??"",r=n===he,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 c=new Set(n.split(",").map(p=>p.trim()).filter(Boolean)),i=`eg_${e.name.replace(/\./g,"__")}`;return jsxRuntime.jsxs("div",{class:"flex flex-wrap items-center gap-1 w-full",children:[jsxRuntime.jsx("input",{type:"hidden",id:o,name:`fv_${e.name}`,value:n}),e.enumValues.map(p=>jsxRuntime.jsxs("label",{class:"flex items-center gap-1 text-xs border border-base-300 rounded px-2 cursor-pointer hover:bg-base-200",children:[jsxRuntime.jsx("input",{type:"checkbox",class:"checkbox checkbox-xs",value:p,checked:c.has(p),"data-enum-group":i,onchange:uo(o,i)}),jsxRuntime.jsx("span",{children:p})]},p))]})}return jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.jsxs("select",{id:o,name:`fv_${e.name}`,class:"select select-sm select-bordered w-full",style:r?"opacity:0.55":void 0,children:[jsxRuntime.jsx("option",{value:"",selected:n===""&&!r,children:"\u2014"}),e.enumValues.map(c=>jsxRuntime.jsx("option",{value:c,selected:n===c,children:c},c)),e.nullable&&jsxRuntime.jsx("option",{value:he,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsxRuntime.jsx(Ue,{inputId:o,active:r})]})}if(e.zodType==="ZodBoolean")return jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.jsxs("select",{id:o,name:`fv_${e.name}`,class:"select select-sm select-bordered w-full",style:r?"opacity:0.55":void 0,children:[jsxRuntime.jsx("option",{value:"",selected:n===""&&!r,children:"\u2014"}),jsxRuntime.jsx("option",{value:"true",selected:n==="true",children:"true"}),jsxRuntime.jsx("option",{value:"false",selected:n==="false",children:"false"}),e.nullable&&jsxRuntime.jsx("option",{value:he,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsxRuntime.jsx(Ue,{inputId:o,active:r})]});if(e.zodType==="ZodArray"){let c=t?.op==="array-contains-any";return jsxRuntime.jsx("input",{id:o,type:"text",name:`fv_${e.name}`,value:n,placeholder:c?"val1, val2, \u2026":"value",class:"input input-sm input-bordered w-full"})}return e.zodType==="ZodNumber"||e.zodType==="ZodBigInt"?jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.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&&jsxRuntime.jsx(Ue,{inputId:o,active:r})]}):e.zodType==="ZodDate"?jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.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&&jsxRuntime.jsx(Ue,{inputId:o,active:r})]}):jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.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&&jsxRuntime.jsx(Ue,{inputId:o,active:r})]})}function Dt({action:e,columnMeta:t,activeFilters:n,isGroup:r}){let o=Object.fromEntries(n.map(i=>[i.field,i])),s=n.length>0,a=n.length>=2||r&&s,c=t.filter(i=>i.zodType!=="ZodObject"&&i.zodType!=="ZodRecord");return jsxRuntime.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:[jsxRuntime.jsxs("summary",{class:"collapse-title text-sm font-medium py-2 min-h-0",children:["Filters",s&&jsxRuntime.jsxs("span",{class:"badge badge-primary badge-sm ml-2",children:[n.length," active"]})]}),jsxRuntime.jsx("div",{class:"collapse-content pb-4 pt-2",children:jsxRuntime.jsxs("form",{method:"get",action:e,children:[jsxRuntime.jsx("div",{class:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:c.map(i=>{let p=lo(i.zodType),d=o[i.name],h=d?.op??p[0].value;return jsxRuntime.jsxs("div",{class:"flex flex-col gap-1.5",children:[jsxRuntime.jsx("label",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:i.name}),jsxRuntime.jsxs("div",{class:"flex gap-1.5",children:[p.length>1?jsxRuntime.jsx("select",{name:`fo_${i.name}`,class:"select select-sm select-bordered w-20 shrink-0",children:p.map(v=>jsxRuntime.jsx("option",{value:v.value,selected:v.value===h,children:v.label},v.value))}):jsxRuntime.jsx("input",{type:"hidden",name:`fo_${i.name}`,value:p[0].value}),jsxRuntime.jsx(po,{col:i,active:d})]})]},i.name)})}),jsxRuntime.jsxs("div",{class:"flex flex-wrap gap-2 mt-4 pt-3 border-t border-base-200 items-center",children:[jsxRuntime.jsx("button",{type:"submit",class:"btn btn-sm btn-primary",children:"Apply"}),s&&jsxRuntime.jsx("a",{href:e,class:"btn btn-sm btn-ghost",children:"Clear"}),a&&jsxRuntime.jsxs("span",{class:"text-xs text-warning ml-auto flex items-center gap-1",children:[jsxRuntime.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-4 w-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:jsxRuntime.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??""}`,c=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 me(jsxRuntime.jsx(ge,{opts:{title:a,breadcrumb:c,basePath:o,flash:s},children:jsxRuntime.jsx("div",{class:"card bg-base-100 border border-base-300",children:jsxRuntime.jsx("div",{class:"card-body p-6",children:jsxRuntime.jsx("div",{dangerouslySetInnerHTML:{__html:t}})})})}))}ut();Ot();function Nt(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 Hn(e,t,n,r,o){let s=Nt(e,r,o);return s.set("cursor",t),s.set("dir",n),`?${s.toString()}`}function fo(e,t,n,r){let o=Nt(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 yo(e,t,n){return `?${Nt(t,n,e).toString()}`}function _t(e,t,n,r,o,s,a=[],c=[],i=false,p=[],d,h,v,g,u,b,m,f=false){let l=`${r}/${e}`,x=`${l}/create`,y={};if(m)for(let S of n)y[S]=Ee(De(m,S));let w=(b??[]).filter(S=>{let k=y[S]??Ee(De(m,S));return k==="string"||k==="number"||k==="bigint"||k==="boolean"||k==="enum"||k==="literal"}),R=w.length>0,C=i,P=C||R,T=w.map(S=>{let k=De(m,S),O=Ee(k),A=a.find($=>$.name===S);return {name:S,type:O,enumValues:A?.enumValues??null,nullable:A?.nullable??false}});return me(jsxRuntime.jsxs(ge,{opts:{title:e,breadcrumb:[{label:"Repositories",href:r},{label:e}],basePath:r,flash:s},children:[a.length>0&&jsxRuntime.jsx(Dt,{action:l,columnMeta:a,activeFilters:c,isGroup:g}),v&&jsxRuntime.jsxs("div",{role:"alert",class:`alert ${v.type==="index"?"alert-warning":"alert-error"} mb-6 shadow-sm`,children:[jsxRuntime.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:v.type==="index"?jsxRuntime.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"}):jsxRuntime.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"})}),jsxRuntime.jsxs("div",{class:"flex-1",children:[jsxRuntime.jsx("h3",{class:"font-bold",children:v.type==="index"?"Composite index required":"Query failed"}),jsxRuntime.jsx("div",{class:"text-sm",children:v.message})]}),v.indexUrl&&jsxRuntime.jsx("a",{href:v.indexUrl,target:"_blank",rel:"noopener noreferrer",class:"btn btn-sm btn-outline",children:"Create Index \u2192"})]}),jsxRuntime.jsxs("div",{class:"flex flex-wrap justify-between items-center mb-4 gap-3","data-frs-toolbar":true,children:[jsxRuntime.jsxs("div",{class:"flex items-center gap-3",children:[jsxRuntime.jsxs("span",{class:"text-sm text-base-content/60",children:[t.length,typeof u=="number"&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[" ","of ",jsxRuntime.jsx("span",{class:"font-semibold text-base-content/80",children:u})]})," ","document",(typeof u=="number"?u:t.length)!==1&&"s"]}),jsxRuntime.jsxs("div",{class:"flex items-center gap-1.5 text-sm text-base-content/60",children:[jsxRuntime.jsx("span",{children:"Rows"}),jsxRuntime.jsx("div",{class:"join",children:[10,25,50,100].map(S=>jsxRuntime.jsx("a",{href:yo(S,c,d),class:`join-item btn btn-xs ${h===S?"btn-active btn-primary":"btn-outline"}`,children:S},S))})]})]}),jsxRuntime.jsx("a",{href:x,class:"btn btn-primary btn-sm",children:"+ New"})]}),P&&jsxRuntime.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 u=="number"?String(u):"","data-frs-page-size":String(h??t.length),"data-frs-allow-delete":C?"1":"0","data-frs-allow-update":R?"1":"0","data-frs-fields":JSON.stringify(T),"data-frs-filters":JSON.stringify(c),children:[jsxRuntime.jsxs("div",{class:"flex-1 text-sm",children:[jsxRuntime.jsx("span",{"data-frs-bulk-summary":true,children:"0 selected"}),typeof u=="number"&&u>t.length&&jsxRuntime.jsxs("button",{type:"button",class:"ml-3 link link-primary text-sm hidden","data-frs-bulk-select-all":true,children:["Select all ",u," matching documents"]}),jsxRuntime.jsxs("span",{class:"hidden ml-3 italic","data-frs-bulk-all-active":true,children:["All ",u??"?"," matching documents are selected."," ",jsxRuntime.jsx("button",{type:"button",class:"link","data-frs-bulk-clear":true,children:"Clear selection"})]})]}),jsxRuntime.jsxs("div",{class:"flex gap-2",children:[R&&jsxRuntime.jsx("button",{type:"button",class:"btn btn-sm btn-outline","data-frs-bulk-action":"update",children:"Update field\u2026"}),C&&jsxRuntime.jsx("button",{type:"button",class:"btn btn-sm btn-error btn-outline","data-frs-bulk-action":"delete",children:"Delete"})]})]}),jsxRuntime.jsx("div",{class:"overflow-x-auto rounded-box border border-base-300 bg-base-100","data-frs-table-wrap":true,children:jsxRuntime.jsxs("table",{class:"table table-sm w-full","data-frs-table":true,"data-frs-repo":e,"data-frs-colcount":n.length,children:[jsxRuntime.jsx("thead",{children:jsxRuntime.jsxs("tr",{class:"bg-base-200/50",children:[P&&jsxRuntime.jsx("th",{class:"w-8",children:jsxRuntime.jsx("input",{type:"checkbox",class:"checkbox checkbox-xs checkbox-primary","data-frs-select-page":true,"aria-label":"Select all on this page"})}),[...n].map((S,k)=>{let O=d?.field===S,A=O?d.dir==="asc"?" \u25B2":" \u25BC":"";return jsxRuntime.jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:jsxRuntime.jsxs("a",{href:fo(S,d,c,h),class:`hover:text-base-content inline-flex items-center gap-0.5${O?" text-primary font-bold":""}`,children:[S,A]})},k)}),p.map((S,k)=>jsxRuntime.jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:S.column},`rel-${k}`)),jsxRuntime.jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide text-right",children:"Actions"})]})}),jsxRuntime.jsx("tbody",{children:t.length===0?jsxRuntime.jsx("tr",{children:jsxRuntime.jsx("td",{colspan:n.length+p.length+1+(P?1:0),class:"text-center py-16 text-base-content/40",children:"No documents found"})}):t.map((S,k)=>{let O=String(S.docId??S.id??""),A=`${r}/${e}/${encodeURIComponent(O)}/edit`,$=`${r}/${e}/${encodeURIComponent(O)}/delete`;return jsxRuntime.jsxs("tr",{class:"hover","data-frs-row-id":O,children:[P&&jsxRuntime.jsx("td",{class:"align-middle py-2",children:jsxRuntime.jsx("input",{type:"checkbox",class:"checkbox checkbox-xs checkbox-primary","data-frs-select-row":true,value:O,"aria-label":`Select ${O}`})}),n.map((_,z)=>{let I=S[_],E=y[_],q=E?Le(E,I):null;return jsxRuntime.jsx("td",{class:"align-top py-2",children:jsxRuntime.jsx(Pe,{val:I,mismatch:q})},z)}),p.map((_,z)=>{let I=S[_.key];if(I==null||I==="")return jsxRuntime.jsx("td",{class:"py-2"},`rel-${z}`);let E=_.type==="one"?`${r}/${_.targetRepo}/${encodeURIComponent(String(I))}/edit`:`${r}/${_.targetRepo}?fv_${_.targetKey}=${encodeURIComponent(String(I))}`;return jsxRuntime.jsx("td",{class:"align-middle py-2",children:jsxRuntime.jsx("a",{href:E,class:"btn btn-xs btn-ghost btn-outline","data-frs-relation":true,"data-frs-rel-type":_.type,"data-frs-rel-repo":_.targetRepo,"data-frs-rel-fk":_.targetKey,"data-frs-rel-val":String(I),"data-frs-rel-label":_.column,children:_.column})},`rel-${z}`)}),jsxRuntime.jsx("td",{class:"align-middle text-right whitespace-nowrap py-2",children:jsxRuntime.jsxs("div",{class:"flex gap-1 justify-end",children:[jsxRuntime.jsx("a",{href:A,class:"btn btn-xs btn-outline",children:"Edit"}),f&&jsxRuntime.jsx("a",{href:`${r}/${e}/${encodeURIComponent(O)}/history`,class:"btn btn-xs btn-outline",title:"View change history",children:"History"}),i&&jsxRuntime.jsx("form",{method:"post",action:$,onsubmit:"return confirm('Delete this document?')",children:jsxRuntime.jsx("button",{type:"submit",class:"btn btn-xs btn-error btn-outline",children:"Delete"})})]})})]},k)})})]})}),(o.hasPrev||o.hasNext)&&jsxRuntime.jsxs("div",{class:"flex flex-col items-center mt-6 gap-2",children:[jsxRuntime.jsxs("div",{class:"flex justify-center items-center gap-2",children:[o.hasPrev?jsxRuntime.jsx("a",{href:Hn(c,o.prevCursor,"prev",d,h),class:"btn btn-sm btn-outline",children:"\u2190 Previous"}):jsxRuntime.jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"\u2190 Previous"}),o.hasNext?jsxRuntime.jsx("a",{href:Hn(c,o.nextCursor,"next",d,h),class:"btn btn-sm btn-outline",children:"Next \u2192"}):jsxRuntime.jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"Next \u2192"})]}),typeof u=="number"&&jsxRuntime.jsxs("div",{class:"text-xs text-base-content/50",children:[u," total document",u!==1?"s":"",c.length>0?" matching filters":""]})]}),P&&R&&jsxRuntime.jsxs("dialog",{id:"frs-bulk-update-modal",class:"modal",children:[jsxRuntime.jsxs("div",{class:"modal-box",children:[jsxRuntime.jsx("h3",{class:"font-bold text-lg mb-3",children:"Bulk update field"}),jsxRuntime.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."}),jsxRuntime.jsxs("form",{method:"dialog","data-frs-bulk-update-form":true,children:[jsxRuntime.jsxs("label",{class:"form-control w-full mb-3",children:[jsxRuntime.jsx("div",{class:"label",children:jsxRuntime.jsx("span",{class:"label-text text-xs uppercase tracking-wide",children:"Field"})}),jsxRuntime.jsxs("select",{class:"select select-bordered select-sm w-full",name:"field",required:true,"data-frs-bulk-field-select":true,children:[jsxRuntime.jsx("option",{value:"",children:"\u2014 Select a field \u2014"}),w.map(S=>jsxRuntime.jsx("option",{value:S,children:S},S))]})]}),jsxRuntime.jsx("div",{class:"mb-4","data-frs-bulk-value-container":true}),jsxRuntime.jsxs("div",{class:"modal-action",children:[jsxRuntime.jsx("button",{type:"button",class:"btn btn-sm btn-ghost","data-frs-bulk-update-cancel":true,children:"Cancel"}),jsxRuntime.jsx("button",{type:"submit",class:"btn btn-sm btn-primary","data-frs-bulk-update-submit":true,children:"Apply"})]})]})]}),jsxRuntime.jsx("form",{method:"dialog",class:"modal-backdrop",children:jsxRuntime.jsx("button",{children:"close"})})]})]}))}function Ve(e,t){return Pt(e,t)}function jt(e,t){return Et(e,t)}function Ft(e,t,n,r,o,s,a,c,i,p,d,h,v,g,u,b,m,f){return _t(e,t,n,r,o,s,a,c,i,p,d,h,v,g,u,b,m,f)}function be(e,t,n,r,o,s){return It(e,t,n,r,o,s)}var go=new Set(["<","<=",">",">=","!="]),ho=new Set(["array-contains","array-contains-any"]);function Mt(e){return e==="desc"?"DESCENDING":"ASCENDING"}function bo(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function vo(e,t,n,r,o){let s=[],a=new Set;for(let i of r)if(i.op==="=="||i.op==="in"||i.op==="not-in"){if(a.has(i.field))continue;a.add(i.field),s.push({fieldPath:i.field,order:"ASCENDING"});}for(let i of r)if(ho.has(i.op)){if(a.has(i.field))continue;a.add(i.field),s.push({fieldPath:i.field,arrayConfig:"CONTAINS"});}for(let i of r)if(go.has(i.op)){if(a.has(i.field))continue;a.add(i.field);let p=o?.field===i.field?Mt(o.dir):"ASCENDING";s.push({fieldPath:i.field,order:p});}if(o&&!a.has(o.field)&&s.push({fieldPath:o.field,order:Mt(o.dir)}),s.length===1&&n)return Ro(e,t,s[0]);let c=o&&s.some(i=>i.fieldPath===o.field)?Mt(o.dir):"ASCENDING";return s.push({fieldPath:"__name__",order:c}),xo(e,t,n,s)}function xo(e,t,n,r,o="(default)"){let s=`projects/${e}/databases/${o}/collectionGroups/${t}/indexes/_`,a=[...Bt(1,s),...ft(2,n?2:1)];for(let p of r)a.push(...Bn(3,Zn(p)));let c=o==="(default)"?"-default-":o,i=encodeURIComponent(qn(a));return `https://console.firebase.google.com/project/${e}/firestore/databases/${c}/indexes?create_composite=${i}`}function wo(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function zt(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function Ht(e,t){return e<<3|t}function Bt(e,t){let n=Array.from(new TextEncoder().encode(t));return [Ht(e,2),...zt(n.length),...n]}function ft(e,t){return [Ht(e,0),...zt(t)]}function Bn(e,t){return [Ht(e,2),...zt(t.length),...t]}function Zn(e){let t=[...Bt(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...ft(3,1)):t.push(...ft(2,e.order==="DESCENDING"?2:1)),t}function qn(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 Ro(e,t,n,r="(default)"){let o=`projects/${e}/databases/${r}/collectionGroups/${t}/fields/${n.fieldPath}`,s=[...Bt(1,o),...ft(2,2),...Bn(3,Zn(n))],a=r==="(default)"?"-default-":r,c=encodeURIComponent(qn(s));return `https://console.firebase.google.com/project/${e}/firestore/databases/${a}/indexes/automatic?create_exemption=${c}`}function So(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 ke(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function Qe(e,t){let n=e??{},r=ke(e),o;if(r&&(o=n.message?wo(n.message):void 0,!o)){let s=So(t.ref);if(s){let a=bo(t.path);o=vo(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}}var Kn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function ko(){let e="";for(let t=0;t<20;t++)e+=Kn.charAt(Math.floor(Math.random()*Kn.length));return e}function yt(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 Ie(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 Zt(e,t,n){let r=e.documentKey??"docId",o=Qe(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 F(e,t,n=200){e.status(n).set("Content-Type","text/html; charset=utf-8").send(t);}function qt(e,t){e.status(302).set("Location",t).send("");}function Kt(e,t){let n=t.shape,r={};for(let[o,s]of Object.entries(n)){let a=Ut(s);if(a==="ZodObject"){if(e[o+"__isnull"]==="1"){r[o]=null;continue}let p={},d=false;for(let[g,u]of Object.entries(e))g.startsWith(`${o}.`)&&(p[g.slice(o.length+1)]=u,d=true);if(d){let g=s;for(;;){let u=Z(g);if(u==="ZodOptional"||u==="ZodNullable"||u==="ZodDefault")g=U(g);else break}r[o]=Kt(p,g);continue}let h=e[o],v=Array.isArray(h)?h[h.length-1]:h;if(v)try{r[o]=JSON.parse(v);}catch{r[o]=v;}continue}let c=e[o],i=Array.isArray(c)?c[c.length-1]:c;if(e[o+"__isnull"]==="1"){r[o]=null;continue}if(i===void 0||i===""){a==="ZodBoolean"&&(r[o]=false);continue}switch(a){case "ZodBoolean":i==="__null__"?r[o]=null:r[o]=i==="true"||i==="on"||i==="1";break;case "ZodNumber":case "ZodBigInt":r[o]=Number(i);break;case "ZodDate":r[o]=new Date(i);break;case "ZodArray":try{r[o]=JSON.parse(i);}catch{r[o]=i;}break;default:if(i.startsWith("{")||i.startsWith("["))try{r[o]=JSON.parse(i);break}catch{}r[o]=i;}}return r}function Ln(e){let t=null;if(e instanceof Date)t=e;else if(typeof e=="object"&&e!==null&&typeof e.toDate=="function")t=e.toDate();else if(typeof e=="object"&&e!==null&&"_seconds"in e&&"_nanoseconds"in e)t=new Date(e._seconds*1e3+Math.floor(e._nanoseconds/1e6));else if(typeof e=="string"||typeof e=="number"){let r=new Date(e);isNaN(r.getTime())||(t=r);}if(!t||isNaN(t.getTime()))return null;let n=r=>String(r).padStart(2,"0");return `${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`}function Ut(e){let t=e;for(;;){let n=Z(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=U(t);else return n}}function Co(e){let t=e;for(;;){let n=Z(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=U(t);else return t}}function Vn(e){let t=e;for(;;){let n=Z(t);if(n==="ZodOptional"||n==="ZodNullable")return true;if(n==="ZodDefault"){t=U(t);continue}return false}}function Qn(e){let t=Co(e),n=Z(t);if(n==="ZodEnum"){let r=ze(t);return r.length>0?r:void 0}if(n==="ZodNativeEnum"){let r=He(t),o=Object.values(r).filter(s=>typeof s=="string");return o.length>0?o:void 0}if(n==="ZodLiteral"){let r=lt(t);return typeof r=="string"?[r]:void 0}}function Gn(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 c=t.shape[o];for(;;){let p=Z(c);if(p==="ZodOptional"||p==="ZodNullable"||p==="ZodDefault")c=U(c);else break}let i=Z(c);if(i==="ZodObject"&&typeof a=="object"&&a!==null&&!Array.isArray(a)){let p=Gn(a,c,s);Object.assign(r,p);}else if(i==="ZodDate"){let p=Ln(a);p!==null&&(r[s]=p);}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)&&("_seconds"in a||typeof a.toDate=="function")){let p=Ln(a);r[s]=p??JSON.stringify(a,null,2);}else typeof a=="object"?r[s]=JSON.stringify(a,null,2):r[s]=String(a);}return r}function Lt(e,t){return e.map(n=>({...n,defaultValue:t[n.name]??n.defaultValue,nested:n.nested?Lt(n.nested,t):void 0}))}function Oo(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 c=(s??"").trim();if(!c)continue;let i=e[`fo_${a}`]??"==",p=n.has(i)?i:"==";r.push({field:a,op:p,value:c});}return r}function Un(e){let t="__null__",n=r=>r===t?null:r==="true"?true:r==="false"?false:r!==""&&!isNaN(Number(r))?Number(r):r;return e.map(r=>{if(r.op==="array-contains-any"||r.op==="in"||r.op==="not-in"){let o=r.value.split(",").map(s=>s.trim()).filter(s=>s!==""&&s!==t).map(s=>n(s));return [r.field,r.op,o]}return [r.field,r.op,n(r.value)]})}function Wn(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 c=Ut(a);if(c==="ZodObject"){let i=a;for(;;){let d=Z(i);if(d==="ZodOptional"||d==="ZodNullable"||d==="ZodDefault")i=U(i);else break}let p=ee(i);r.push(...Wn(Object.keys(p),i,s));}else r.push({name:s,zodType:c,nullable:Vn(a),enumValues:Qn(a)});}return r}function $o(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=U(r);else break}let s=ee(r);if(!(o in s))return null;r=s[o];}return r}function Ce(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 c=s.slice(0,a),i=s.slice(a+1);r.has(c)||r.set(c,[]),r.get(c).push(i);}}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 c=e.shape[s];for(;;){let i=Z(c);if(i==="ZodOptional"||i==="ZodNullable"||i==="ZodDefault")c=U(c);else break}if(Z(c)!=="ZodObject"){o[s]=e.shape[s];continue}o[s]=Ce(c,a);}return zod.z.object(o)}function de(e,t){let n=t==="/"?"":t.replace(/\/$/,"");if(process.env.FUNCTIONS_EMULATOR==="true"){let s=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??"demo-project",a=process.env.FUNCTION_REGION??"us-central1",c=(process.env.FUNCTION_TARGET??"").replace(/\./g,"-");return `/${s}/${a}/${c}${n}`}let r=process.env.K_SERVICE,o=e.hostname??e.headers?.host??"";return r&&o.includes("cloudfunctions.net")?`/${r.toLowerCase()}${n}`:n}function Jn(e,t){let n=(f,l)=>{let x=de(f,t),y=Object.values(e).map(w=>({name:w.name,path:w.path}));F(l,jt(y,x));},r=async(f,l)=>{let x=f.params.repoName;if(!x){F(l,"Bad request",400);return}let y=e[x];if(!y){F(l,"Repository not found",404);return}let w=y.pageSize??25,R=f.query??{},C=R.cursor,P=R.dir==="prev"?"prev":"next",T=R.ob??"",S=R.od==="desc"?"desc":"asc",k=T?{field:T,dir:S}:void 0,O=parseInt(R.ps??""),A=Number.isFinite(O)&&O>0?Math.min(O,200):w,$=y.listColumns??Object.keys(y.schema.shape),_=y.documentKey??"docId",z=[_,...$.filter(G=>G!==_)],I=y.filterableFields?(()=>{let G=[];for(let le of y.filterableFields)(le.includes(".")||$.includes(le))&&G.push(le);return G})():$,E=(()=>{let G=[];for(let le of I)if(le.includes(".")){let $e=$o(y.schema,le);G.push({name:le,zodType:$e?Ut($e):"ZodString",nullable:$e?Vn($e):false,enumValues:$e?Qn($e):void 0});}else G.push(...Wn([le],y.schema));return G})(),q=new Set(E.map(G=>G.name)),xe=Oo(R,q),ue=Un(xe),je;if(C)try{let G=y.repo.ref;typeof G.doc=="function"&&(je=await G.doc(C).get());}catch{}let[W,Je]=await Promise.all([y.repo.query.paginate({pageSize:A,cursor:je,direction:P,...ue.length>0?{where:ue}:{},...k?{orderBy:[{field:k.field,direction:k.dir}]}:{}}).catch(G=>({queryError:Qe(G,{ref:y.repo.ref,path:y.path,isGroup:!!y.isGroup,filters:xe,sort:k})})),y.repo.aggregate.count(ue.length>0?{where:ue}:{}).catch(()=>{})]),Oe="queryError"in W,cr=Oe?[]:W.data,dr=Oe?"":W.nextCursor?.id??"",ur=Oe?"":W.prevCursor?.id??"",pr=Oe?W.queryError:void 0,fr=de(f,t);F(l,Ft(y.name,cr,z,fr,{hasPrev:Oe?false:W.hasPrevPage,hasNext:Oe?false:W.hasNextPage,prevCursor:ur,nextCursor:dr},void 0,E,xe,y.allowDelete??false,y.relationalMeta,k,A,pr,y.isGroup,Je,y.mutableFields,y.schema,y.historyEnabled));},o=(f,l)=>{let x=f.params.repoName;if(!x){F(l,"Bad request",400);return}let y=e[x];if(!y){F(l,"Repository not found",404);return}let w=de(f,t),R=Ce(y.schema,y.createFields),C=ae(R),P=`${w}/${y.name}/create`,T=ye(C,P,"POST","Create document");F(l,be(y.name,T,"create",null,w));},s=async(f,l)=>{let x=f.params.repoName;if(!x){F(l,"Bad request",400);return}let y=e[x];if(!y){F(l,"Repository not found",404);return}let w=de(f,t),R=f.body??{},C=Kt(R,y.schema),P=Ce(y.schema,y.createFields),T=P.safeParse(C);if(!T.success){let S=ae(P),k=`${w}/${y.name}/create`,O=ye(S,k,"POST","Create document"),A=T.error.issues.map($=>`${$.path.join(".")}: ${$.message}`).join(", ");F(l,be(y.name,O,"create",null,w,{type:"error",message:`Validation error: ${A}`}),422);return}try{if(y.isGroup&&y.parentKeys&&y.parentKeys.length>0){let S={...T.data};y.createdKey&&(S[y.createdKey]=new Date);let k=y.parentKeys.filter(_=>!S[_]);if(k.length>0)throw new Error(`Missing parent key(s) for subcollection create: ${k.join(", ")}`);let O=y.parentKeys.map(_=>S[_]),A=y.documentKey??"docId",$=S[A]||ko();await y.repo.set(...O,$,S);}else await y.repo.create(T.data);qt(l,`${w}/${y.name}?flash=created`);}catch(S){let k=Ce(y.schema,y.createFields),O=ae(k),A=`${w}/${y.name}/create`,$=ye(O,A,"POST","Create document");F(l,be(y.name,$,"create",null,w,{type:"error",message:`Save error: ${S.message}`}),500);}},a=async(f,l)=>{let x=f.params.repoName,y=f.params.id;if(!x||!y){F(l,"Bad request",400);return}let w=e[x];if(!w){F(l,"Repository not found",404);return}let R=de(f,t),C=null;try{C=await Ie(w,y);}catch(A){let $=Zt(w,y,A),_=ke(A)?424:500;F(l,Ve("",{title:`Edit ${w.name} / ${y}`,basePath:R,breadcrumb:[{label:"Repositories",href:R},{label:w.name,href:`${R}/${w.name}`},{label:`Edit ${y}`}],flash:$}),_);return}if(!C){F(l,"Document not found",404);return}let P=Gn(C,w.schema),T=Ce(w.schema,w.mutableFields),S=Lt(ae(T),P),k=`${R}/${w.name}/${encodeURIComponent(y)}/edit`,O=ye(S,k,"POST","Save changes");F(l,be(w.name,O,"edit",y,R));},c=async(f,l)=>{let x=f.params.repoName,y=f.params.id;if(!x||!y){F(l,"Bad request",400);return}let w=e[x];if(!w){F(l,"Repository not found",404);return}let R=de(f,t),C=f.body??{},P=Kt(C,w.schema),T=Ce(w.schema,w.mutableFields),k=T.partial().safeParse(P);if(!k.success){let O=Object.fromEntries(Object.entries(C).map(([I,E])=>[I,Array.isArray(E)?E.join(","):E??""])),A=Lt(ae(T),O),$=`${R}/${w.name}/${encodeURIComponent(y)}/edit`,_=ye(A,$,"POST","Save changes"),z=k.error.issues.map(I=>`${I.path.join(".")}: ${I.message}`).join(", ");F(l,be(w.name,_,"edit",y,R,{type:"error",message:`Validation error: ${z}`}),422);return}try{let O=await Ie(w,y),A=(O&&yt(O,w.pathKey))??[y];await w.repo.update(...A,k.data),qt(l,`${R}/${w.name}?flash=updated`);}catch(O){let A=Ce(w.schema,w.mutableFields),$=ae(A),_=`${R}/${w.name}/${encodeURIComponent(y)}/edit`,z=ye($,_,"POST","Save changes"),I=ke(O)?Zt(w,y,O):{type:"error",message:`Save error: ${O.message}`},E=ke(O)?424:500;F(l,be(w.name,z,"edit",y,R,I),E);}},i=async(f,l)=>{let x=f.params.repoName,y=f.params.id;if(!x||!y){F(l,"Bad request",400);return}let w=e[x];if(!w){F(l,"Repository not found",404);return}if(!w.allowDelete){F(l,"Delete is not allowed for this repository",403);return}let R=de(f,t);try{let C=await Ie(w,y),P=(C&&yt(C,w.pathKey))??[y];await w.repo.delete(...P),qt(l,`${R}/${w.name}?flash=deleted`);}catch(C){let P=ke(C)?Zt(w,y,C):{type:"error",message:`Delete error: ${C.message}`},T=ke(C)?424:500;F(l,Ve("",{title:`Delete ${w.name} / ${y}`,basePath:R,breadcrumb:[{label:"Repositories",href:R},{label:w.name,href:`${R}/${w.name}`},{label:`Delete ${y}`}],flash:P}),T);}},p=async(f,l)=>{let x=f.params.repoName;if(!x){F(l,"Bad request",400);return}let y=e[x];if(!y){F(l,"Repository not found",404);return}let w=de(f,t),R=f.query,C=R?.type==="many"?"many":"one",P=Math.max(1,Math.min(100,Number(R?.ps??25)||25)),T=y.listColumns??Object.keys(ee(y.schema)),{PanelOne:S,PanelMany:k}=await Promise.resolve().then(()=>(At(),Fn)),{renderToString:O}=await import('hono/jsx/dom/server');if(C==="one"){let E=String(R?.id??"");if(!E){F(l,"<div class='p-6 text-error'>Missing id parameter.</div>",400);return}try{let q=await Ie(y,E),xe=O(S({doc:q,repoName:y.name,basePath:w,schema:y.schema,columns:T}));F(l,xe);}catch(q){F(l,`<div class='p-6 text-error text-sm'>Error: ${q.message}</div>`,500);}return}let A=String(R?.fk??""),$=String(R?.fv??"");if(!A||!$){F(l,"<div class='p-6 text-error'>Missing fk/fv parameters.</div>",400);return}let _=R?.cursor??"",z=R?.dir==="prev"?"prev":"next",I;if(_)try{let E=y.repo.ref;typeof E.doc=="function"&&(I=await E.doc(_).get());}catch{}try{let E=await y.repo.query.paginate({pageSize:P,cursor:I,direction:z,where:[[A,"==",Ao($)]]}),q=O(k({docs:E.data,repoName:y.name,basePath:w,fk:A,fv:$,columns:T,schema:y.schema,pagination:{hasPrev:E.hasPrevPage,hasNext:E.hasNextPage,prevCursor:E.prevCursor?.id??"",nextCursor:E.nextCursor?.id??"",pageSize:P}}));F(l,q);}catch(E){F(l,`<div class='p-6 text-error text-sm'>Error: ${E.message}</div>`,500);}},d=async(f,l)=>{let x=[];for(let y of l){let w;if(f.isGroup||f.parentKeys?.length){let R=await Ie(f,y);w=R?yt(R,f.pathKey):void 0;}w||(w=[y]);try{let R=f.repo.documentRef(...w);R&&x.push(R);}catch{}}return x},h=async(f,l)=>{let x=Un(l),y=f.documentKey??"docId",w=[],R;for(;;){let C=await f.repo.query.paginate({pageSize:500,cursor:R,direction:"next",...x.length>0?{where:x}:{}});for(let P of C.data){let T=String(P[y]??P.id??"");T&&w.push(T);}if(!C.hasNextPage||!C.nextCursor)break;R=C.nextCursor;}return w},v=async(f,l)=>{let x=f.params.repoName;if(!x){Y(l,{error:"Bad request"},400);return}let y=e[x];if(!y){Y(l,{error:"Repository not found"},404);return}if(!y.allowDelete){Y(l,{error:"Delete is not allowed for this repository"},403);return}let w=f.body??{};try{let R=await u(y,w);if(R.length===0){Y(l,{deleted:0});return}let C=await d(y,R);for(let P=0;P<C.length;P+=500)await y.repo.bulk.delete(C.slice(P,P+500));Y(l,{deleted:C.length});}catch(R){Y(l,{error:R.message},500);}},g=async(f,l)=>{let x=f.params.repoName;if(!x){Y(l,{error:"Bad request"},400);return}let y=e[x];if(!y){Y(l,{error:"Repository not found"},404);return}let w=f.body??{},R=String(w.field??"");if(!R){Y(l,{error:"Missing 'field'"},400);return}if(!y.mutableFields||!y.mutableFields.includes(R)){Y(l,{error:`Field '${R}' is not bulk-updatable`},403);return}let C=y.schema.shape?.[R],P=w.value;if(C){let T=C.safeParse(w.value);if(!T.success){Y(l,{error:`Invalid value for '${R}': ${T.error.message}`},400);return}P=T.data;}try{let T=await u(y,w);if(T.length===0){Y(l,{updated:0});return}let k=(await d(y,T)).map(O=>({docRef:O,data:{[R]:P}}));for(let O=0;O<k.length;O+=500)await y.repo.bulk.update(k.slice(O,O+500));Y(l,{updated:k.length});}catch(T){Y(l,{error:T.message},500);}};async function u(f,l){if(l.selectAll){let x=b(l.filters,f);return await h(f,x)}return Array.isArray(l.ids)?l.ids.filter(x=>typeof x=="string"&&!!x):[]}function b(f,l){if(!Array.isArray(f))return [];let x=new Set((l.filterableFields??Object.keys(ee(l.schema))).map(R=>String(R))),y=new Set(["==","!=","<","<=",">",">=","in","not-in","array-contains","array-contains-any"]),w=[];for(let R of f)R&&typeof R=="object"&&typeof R.field=="string"&&x.has(R.field)&&typeof R.value=="string"&&y.has(String(R.op))&&w.push({field:R.field,op:R.op,value:R.value});return w}return {handleDashboard:n,handleList:r,handleCreateForm:o,handleCreateSubmit:s,handleEditForm:a,handleEditSubmit:c,handleDelete:i,handlePanel:p,handleBulkDelete:v,handleBulkUpdate:g,handleHistory:async(f,l)=>{let x=f.params.repoName,y=f.params.id;if(!x||!y){F(l,"Bad request",400);return}let w=e[x];if(!w){F(l,"Repository not found",404);return}if(!w.historyEnabled||!w.repo.history){F(l,"History not enabled for this repository",404);return}let R=de(f,t),C=w.historySubcollection??"history",P=[y];try{let E=await Ie(w,y),q=E?yt(E,w.pathKey):void 0;q&&q.length>0&&(P=q);}catch{}let T=parseInt(String(f.query?.limit??"")),S=Number.isFinite(T)&&T>0?Math.min(T,500):100,k=[],O;try{k=await w.repo.history.list(...P,{limit:S});}catch(E){O=E.message;}let A=E=>String(E??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),$=E=>{if(E===void 0)return '<span class="opacity-40">undefined</span>';if(E===null)return '<span class="opacity-40">null</span>';if(typeof E=="object")try{return `<code class="text-xs">${A(JSON.stringify(E))}</code>`}catch{return A(String(E))}return A(String(E))},_=E=>E?typeof E.toDate=="function"?E.toDate().toISOString():E instanceof Date?E.toISOString():A(String(E)):"",z=E=>`<span class="badge badge-sm ${E==="create"?"badge-success":E==="delete"?"badge-error":"badge-info"}">${A(E)}</span>`,I="";if(I+='<div class="flex items-center justify-between mb-4">',I+=`<h1 class="text-2xl font-semibold">History \u2014 ${A(w.name)} / ${A(y)}</h1>`,I+=`<a href="${R}/${w.name}/${encodeURIComponent(y)}/edit" class="btn btn-sm btn-outline">\u2190 Back to edit</a>`,I+="</div>",I+=`<p class="text-sm text-base-content/60 mb-4">Subcollection: <code>${A(C)}</code> \xB7 Showing up to ${S} entries.</p>`,O)I+=`<div class="alert alert-error mb-4">${A(O)}</div>`;else if(k.length===0)I+='<div class="alert">No history entries found.</div>';else {I+='<div class="overflow-x-auto"><table class="table table-zebra table-sm">',I+="<thead><tr><th>When</th><th>Op</th><th>User</th><th>Reason / Comment</th><th>Changes</th></tr></thead><tbody>";for(let E of k){let q=E.meta??{},xe=[q.reason,q.comment].filter(W=>W!=null&&W!=="").map(W=>A(String(W))).join(" \u2014 "),ue="",je=Object.keys(E.changes??{});je.length===0?ue='<span class="opacity-40">\u2014</span>':ue='<ul class="space-y-1">'+je.map(W=>{let Je=E.changes[W];return `<li><strong>${A(W)}</strong>: ${$(Je.oldValue)} \u2192 ${$(Je.newValue)}</li>`}).join("")+"</ul>",I+="<tr>",I+=`<td class="whitespace-nowrap text-xs font-mono">${A(_(E.historySetAt))}</td>`,I+=`<td>${z(E.operation??"update")}</td>`,I+=`<td class="text-xs">${A(q.userEmail??q.userId??"")}</td>`,I+=`<td class="text-xs">${xe}</td>`,I+=`<td>${ue}</td>`,I+="</tr>";}I+="</tbody></table></div>";}F(l,Ve(I,{title:`History \u2014 ${w.name} / ${y}`,basePath:R,breadcrumb:[{label:"Repositories",href:R},{label:w.name,href:`${R}/${w.name}`},{label:`History ${y}`}]}));}}}function Y(e,t,n=200){e.status(n).set("Content-Type","application/json; charset=utf-8").send(JSON.stringify(t));}function Ao(e){return e==="true"?true:e==="false"?false:e!==""&&!isNaN(Number(e))?Number(e):e}async function Po(e){return typeof e.rawBody=="string"?e.rawBody:Buffer.isBuffer(e.rawBody)?e.rawBody.toString("utf8"):""}function Eo(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 Xn(e){let{basePath:t="/",repos:n,parseBody:r=true,auth:o,middleware:s=[],httpsOptions:a}=e,c=t==="/"?"":t.replace(/\/$/,""),i={};for(let[v,g]of Object.entries(n)){let u=g.schema??g.repo.schema??null;if(!u)throw new Error(`[createAdminServer] Repository "${v}" has no Zod schema. Either use createRepositoryConfig(schema)(config) or pass schema: explicitly.`);let b,m,f;if(g.fieldsConfig){let y=g.fieldsConfig;b=[],m=[],f=[];for(let[w,R]of Object.entries(y))for(let C of R)C==="filterable"?b.push(w):C==="mutable"?m.push(w):C==="create"&&f.push(w);b.length===0&&(b=void 0),m.length===0&&(m=void 0),f.length===0&&(f=void 0);}let l=(()=>{let y=g.repo._parentKeys;return y&&y.length>0?y:void 0})();if(l&&f)for(let y of l)f.includes(y)||f.push(y);let x={name:v,path:g.path,repo:g.repo,schema:u,documentKey:g.documentKey??"docId",pathKey:g.repo._pathKey??void 0,isGroup:!!g.repo._isGroup,parentKeys:l,createdKey:g.repo._createdKey??void 0,listColumns:g.listColumns,pageSize:g.pageSize,filterableFields:b,mutableFields:m,createFields:f,allowDelete:g.allowDelete??false,historyEnabled:!!g.repo.history,historySubcollection:(g.repo.history&&g.repo._historySubcollection)??void 0,relationalMeta:(()=>{if(!g.relationalFields||g.relationalFields.length===0)return;let y=g.repo.relationalKeys??{},w=[];for(let R of g.relationalFields){let C=y[R.key];C&&w.push({key:R.key,column:R.column,targetRepo:String(C.repo),targetKey:String(C.key),type:C.type});}return w.length>0?w:void 0})()};i[v]=x;}let p=Jn(i,c),d=new te;if(r&&d.use(async(v,g,u)=>{let b=v,m=String(b.headers?.["content-type"]??"");if(m.includes("application/x-www-form-urlencoded")){let f=await Po(b);v.body=Eo(f);}else if(m.includes("application/json")&&typeof b.body=="string")try{v.body=JSON.parse(b.body);}catch{}await u();}),o)if(typeof o=="function")d.use(o);else {let v=o.realm??"Admin",g="Basic "+Buffer.from(`${o.username}:${o.password}`).toString("base64");d.use((u,b,m)=>{if((u.headers?.authorization??"")!==g){b.status(401).set("WWW-Authenticate",`Basic realm="${v}"`).set("Content-Type","text/plain").send("Unauthorized");return}m();});}for(let v of s)d.use(v);d.get(`${c}/`,p.handleDashboard),d.get(`${c}`,p.handleDashboard),d.get(`${c}/:repoName/_panel`,p.handlePanel),d.post(`${c}/:repoName/_bulk/delete`,p.handleBulkDelete),d.post(`${c}/:repoName/_bulk/update`,p.handleBulkUpdate),d.get(`${c}/:repoName`,p.handleList),d.get(`${c}/:repoName/create`,p.handleCreateForm),d.post(`${c}/:repoName/create`,p.handleCreateSubmit),d.get(`${c}/:repoName/:id/edit`,p.handleEditForm),d.post(`${c}/:repoName/:id/edit`,p.handleEditSubmit),d.get(`${c}/:repoName/:id/history`,p.handleHistory),d.post(`${c}/:repoName/:id/delete`,p.handleDelete);let h=async(v,g)=>{await d.handle(v,g);};return a&&(h.httpsOptions=a),h}function Qt(e,t,n=200){let r=K(t);e.status(n).set("Content-Type","application/json; charset=utf-8").send(JSON.stringify(r));}function Ne(e,t,n,r=200){Qt(e,{success:true,data:t,meta:n},r);}function Q(e,t,n=400){Qt(e,{success:false,error:t},n);}function Vt(e,t,n,r,o){let s=Qe(t,n),a=s.type==="index",c=a?424:500,p={success:false,error:a?s.message:o&&t instanceof Error?t.message:r};a&&(p.errorType="index",s.indexUrl&&(p.indexUrl=s.indexUrl)),Qt(e,p,c);}var Yn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Do(){let e="";for(let t=0;t<20;t++)e+=Yn.charAt(Math.floor(Math.random()*Yn.length));return e}function _e(e){let t=e._def??e.def;if(!t)return e;let n=t.typeName??t.type;if(n==="ZodDate"||n==="date")return zod.z.preprocess(r=>xt(r)??r,e);if(n==="ZodObject"||n==="object"){let r=e.shape,o={};for(let[s,a]of Object.entries(r))o[s]=_e(a);return zod.z.object(o)}if(n==="ZodArray"||n==="array"){let r=t.element??t.type;if(r)return zod.z.array(_e(r))}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(r)return _e(r).optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(r)return _e(r).nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType,o=t.defaultValue;if(r){let s=_e(r);return typeof o=="function"?s.default(o()):s.default(o)}}return e}function Io(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 c=a.split(".")[0];c&&r[c]&&(o[c]=r[c]);}return zod.z.object(o)}function er(e,t,n,r=false,o=[]){try{let s=Io(e,n,o),a=r?s.partial():s;return {success:!0,data:(vt()==="normalize"?_e(a):a).parse(t)}}catch(s){return s instanceof zod.z.ZodError?{success:false,error:`Validation failed: ${s.issues.map(c=>`${c.path.join(".")}: ${c.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}function No(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 c=Array.isArray(a)?a[0]:a;if(c===void 0||c==="")continue;let i=s.match(/^(\w+)__(\w+)$/),p,d="==";if(i&&i[1]&&i[2]){p=i[1];let v=i[2];if(o[v])d=o[v];else continue}else if(!i)p=s;else continue;if(r&&!r.has(p))continue;let h=c;d==="in"||d==="not-in"||d==="array-contains-any"?h=c.split(",").map(v=>tr(v.trim())):h=tr(c),n.push({field:p,op:d,value:h});}return n}function tr(e){if(e==="true")return true;if(e==="false")return false;if(e==="null")return null;let t=Number(e);return !isNaN(t)&&e!==""?t:e}function mt(e){return e?{docId:e.id}:null}async function nr(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 rr(e,t,n){function r(g,u){return !g||!e[g]?(Q(u,`Repository "${g}" not found`,404),null):e[g]}function o(g,u){if(!u)return;let b=g[u];if(typeof b!="string"||!b)return;let m=b.split("/").filter(Boolean),f=[];for(let l=1;l<m.length;l+=2)f.push(m[l]);return f.length>0?f:void 0}async function s(g,u){let b=`by${g.documentKey.charAt(0).toUpperCase()}${g.documentKey.slice(1)}`,m=g.repo.get[b];if(typeof m=="function")try{let l=await m(u);if(l)return l}catch{}return (await g.repo.query.by({where:[[g.documentKey,"==",u]],limit:1}))[0]??null}async function a(g,u){let b=g.params||{},m=r(b.repoName,u);if(!m)return;let f=[],l;try{let x=g.query??{},y=Math.min(Number(x.pageSize)||m.pageSize,100),w=x.cursor,R=x.direction?.toLowerCase()==="prev"?"prev":"next",C=x.orderBy,P=x.orderDir?.toLowerCase()==="desc"?"desc":"asc",T=x.select,S=T?T.split(",").map(z=>z.trim()):void 0,k;m.allowedIncludes&&x.includes&&(k=(typeof x.includes=="string"?x.includes.split(",").map(I=>I.trim()):Array.isArray(x.includes)?x.includes:[]).filter(I=>typeof I=="string"&&m.allowedIncludes.includes(I)),k?.length===0&&(k=void 0));let O=No(x,m.filterableFields);f=O.map(z=>({field:z.field,op:z.op,value:String(z.value??"")})),C&&(l={field:C,dir:P});let A={pageSize:y,direction:R};if(w)try{let z=typeof w=="string"?JSON.parse(w):w;A.cursor=await nr(m,z);}catch{}C&&(A.orderBy=[{field:C,direction:P}]),O.length>0&&(A.where=O.map(z=>[z.field,z.op,z.value])),S&&(A.select=S),k&&(A.include=k);let $=await m.repo.query.paginate(A),_={items:$.data,hasNextPage:$.hasNextPage,hasPrevPage:$.hasPrevPage,nextCursor:mt($.nextCursor),prevCursor:mt($.prevCursor)};Ne(u,_,{pageSize:y,hasMore:$.hasNextPage});}catch(x){Vt(u,x,{ref:m.repo.ref,path:m.path,isGroup:!!m.isGroup,filters:f,sort:l},"Failed to fetch documents",n);}}async function c(g,u){let b=g.params||{},m=r(b.repoName,u);if(!m)return;let f=[],l;try{let x=g.body??{},y=Math.min(x.pageSize||m.pageSize,100),w=x.direction==="prev"?"prev":"next";x.where&&(f=x.where.map(T=>({field:String(T[0]),op:T[1],value:String(T[2]??"")}))),x.orderBy&&x.orderBy[0]&&(l={field:x.orderBy[0].field,dir:x.orderBy[0].direction==="desc"?"desc":"asc"});let R={pageSize:y,direction:w};if(x.cursor)try{let T=typeof x.cursor=="string"?JSON.parse(x.cursor):x.cursor;R.cursor=await nr(m,T);}catch{}if(m.allowedIncludes&&x.includes&&x.includes.length>0){let T=x.includes.filter(S=>typeof S=="string"?m.allowedIncludes.includes(S):typeof S=="object"&&S!==null&&"relation"in S&&typeof S.relation=="string"?m.allowedIncludes.includes(S.relation):!1);T.length>0&&(R.include=T);}if(x.where&&x.where.length>0){if(m.filterableFields){let T=new Set(m.filterableFields),S=x.where.filter(k=>!T.has(k[0]));if(S.length>0){Q(u,`Fields not filterable: ${S.map(k=>k[0]).join(", ")}`,400);return}}R.where=x.where;}if(x.orWhere&&x.orWhere.length>0){if(m.filterableFields){let T=new Set(m.filterableFields),S=x.orWhere.filter(k=>!T.has(k[0]));if(S.length>0){Q(u,`Fields not filterable: ${S.map(k=>k[0]).join(", ")}`,400);return}}R.orWhere=x.orWhere;}if(x.orWhereGroups&&x.orWhereGroups.length>0){if(m.filterableFields){let T=new Set(m.filterableFields);for(let S of x.orWhereGroups){let k=S.filter(O=>!T.has(O[0]));if(k.length>0){Q(u,`Fields not filterable: ${k.map(O=>O[0]).join(", ")}`,400);return}}}R.orWhereGroups=x.orWhereGroups;}x.orderBy&&x.orderBy.length>0&&(R.orderBy=x.orderBy),x.select&&x.select.length>0&&(R.select=x.select);let C=await m.repo.query.paginate(R),P={items:C.data,hasNextPage:C.hasNextPage,hasPrevPage:C.hasPrevPage,nextCursor:mt(C.nextCursor),prevCursor:mt(C.prevCursor)};Ne(u,P,{pageSize:y,hasMore:C.hasNextPage});}catch(x){Vt(u,x,{ref:m.repo.ref,path:m.path,isGroup:!!m.isGroup,filters:f,sort:l},"Failed to query documents",n);}}async function i(g,u){let b=g.params||{},m=r(b.repoName,u);if(!m)return;let f=b.id;if(!f){Q(u,"Document ID required",400);return}try{let l=await s(m,f);if(!l){Q(u,"Document not found",404);return}Ne(u,l);}catch(l){Vt(u,l,{ref:m.repo.ref,path:m.path,isGroup:!!m.isGroup,filters:[{field:m.documentKey,op:"==",value:f}]},"Failed to fetch document",n);}}async function p(g,u){let b=g.params||{},m=r(b.repoName,u);if(m)try{let f=g.body??{},l=er(m.schema,f,m.createFields,!1,m.systemKeys);if(!l.success){Q(u,l.error,400);return}if(m.validate){let y=await m.validate(l.data,"create");if(y){Q(u,y,400);return}}let x;if(m.isGroup&&m.parentKeys&&m.parentKeys.length>0){let y={...l.data};m.createdKey&&(y[m.createdKey]=new Date);let w=m.parentKeys.filter(P=>!y[P]);if(w.length>0){Q(u,`Missing parent key(s) for subcollection create: ${w.join(", ")}`,400);return}let R=m.parentKeys.map(P=>y[P]),C=y[m.documentKey]||Do();x=await m.repo.set(...R,C,y);}else x=await m.repo.create(l.data);Ne(u,x,void 0,201);}catch(f){let l=n&&f instanceof Error?f.message:"Failed to create document";Q(u,l,500);}}async function d(g,u,b){let m=g.params||{},f=r(m.repoName,u);if(!f)return;let l=m.id;if(!l){Q(u,"Document ID required",400);return}try{let x=g.body??{},y=er(f.schema,x,f.mutableFields,b,f.systemKeys);if(!y.success){Q(u,y.error,400);return}if(f.validate){let P=await f.validate(y.data,"update");if(P){Q(u,P,400);return}}let w=await s(f,l),R=(w&&o(w,f.pathKey))??[l],C=await f.repo.update(...R,y.data);Ne(u,C);}catch(x){let y=n&&x instanceof Error?x.message:"Failed to update document";Q(u,y,500);}}async function h(g,u){let b=g.params||{},m=r(b.repoName,u);if(!m)return;if(!m.allowDelete){Q(u,"Delete not allowed for this repository",403);return}let f=b.id;if(!f){Q(u,"Document ID required",400);return}try{let l=await s(m,f),x=(l&&o(l,m.pathKey))??[f];await m.repo.delete(...x),Ne(u,{deleted:!0});}catch(l){let x=n&&l instanceof Error?l.message:"Failed to delete document";Q(u,x,500);}}function v(g,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:a,handleQuery:c,handleGet:i,handleCreate:p,handleUpdate:d,handleDelete:h,handleOptions:v}}function Gt(e){try{return zod.z.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 re(e){return {$ref:`#/components/schemas/${e}`}}function X(e){return {description:e,content:{"application/json":{schema:re("ErrorResponse")}}}}function We(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function or(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 _o(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 jo(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 Fo(){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 Mo(e,t,n,r,o){let s={},a=e.name,c=`${t}/${e.name}`,i=`${c}/{${e.documentKey}}`,p={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};s[c]={get:{operationId:`list${ve(e.name)}`,summary:`List ${e.name} (paginated)`,tags:[a],parameters:[..._o(e),...jo(e)],responses:{200:or(re(n)),500:X("Internal server error")}},post:{operationId:`create${ve(e.name)}`,summary:`Create a ${ie(e.name)}`,tags:[a],requestBody:{required:true,content:{"application/json":{schema:re(r??n)}}},responses:{201:We("Document created",re(n)),400:X("Validation error"),500:X("Internal server error")}}},s[`${c}/query`]={post:{operationId:`query${ve(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[a],requestBody:{required:true,content:{"application/json":{schema:re("QueryRequestBody")}}},responses:{200:or(re(n)),400:X("Invalid query"),500:X("Internal server error")}}};let d={};return d.get={operationId:`get${ve(ie(e.name))}`,summary:`Get a single ${ie(e.name)}`,tags:[a],parameters:[p],responses:{200:We("Document found",re(n)),404:X("Document not found"),500:X("Internal server error")}},d.put={operationId:`update${ve(ie(e.name))}`,summary:`Update a ${ie(e.name)} (full replace)`,tags:[a],parameters:[p],requestBody:{required:true,content:{"application/json":{schema:re(o??n)}}},responses:{200:We("Document updated",re(n)),400:X("Validation error"),404:X("Document not found"),500:X("Internal server error")}},d.patch={operationId:`patch${ve(ie(e.name))}`,summary:`Partially update a ${ie(e.name)}`,tags:[a],parameters:[p],requestBody:{required:true,content:{"application/json":{schema:{allOf:[re(o??n)],description:"All fields are optional for partial updates"}}}},responses:{200:We("Document patched",re(n)),400:X("Validation error"),404:X("Document not found"),500:X("Internal server error")}},e.allowDelete&&(d.delete={operationId:`delete${ve(ie(e.name))}`,summary:`Delete a ${ie(e.name)}`,tags:[a],parameters:[p],responses:{200:We("Document deleted",{type:"object",properties:{id:{type:"string"}}}),404:X("Document not found"),500:X("Internal server error")}}),s[i]=d,s}function Jt(e,t,n={}){let{title:r="CRUD API",version:o="1.0.0",description:s,servers:a,auth:c=false}=n,i=t==="/"?"":t.replace(/\/$/,""),p={},d={},h=[];p.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string"}},required:["success","error"]},p.QueryRequestBody=Fo();for(let[b,m]of Object.entries(e)){let f=ve(ie(b)),l=`${f}Create`,x=`${f}Update`;p[f]=Gt(m.schema);let y=S=>{let k=S&&S.length>0?S:Object.keys(m.schema.shape),O={};for(let A of k){let $=A.split(".")[0];$&&m.schema.shape[$]&&!m.systemKeys.includes($)&&(O[$]=m.schema.shape[$]);}return O},w=null,R=y(m.createFields);Object.keys(R).length>0&&(p[l]=Gt(zod.z.object(R)),w=l);let C=null,P=y(m.mutableFields);Object.keys(P).length>0&&(p[x]=Gt(zod.z.object(P)),C=x);let T=Mo(m,i,f,w,C);Object.assign(d,T),h.push({name:b,description:`Operations on ${b} (collection: ${m.path})`});}let v={},g;return c==="basic"?(v.basicAuth={type:"http",scheme:"basic"},g=[{basicAuth:[]}]):c==="bearer"&&(v.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},g=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:r,version:o,...s?{description:s}:{}},...a&&a.length>0?{servers:a}:{},paths:d,components:{schemas:p,...Object.keys(v).length>0?{securitySchemes:v}:{}},...g?{security:g}:{},tags:h}}function ve(e){return e.charAt(0).toUpperCase()+e.slice(1)}function ie(e){return e.endsWith("ies")?e.slice(0,-3)+"y":e.endsWith("ses")||e.endsWith("xes")||e.endsWith("zes")?e.slice(0,-2):e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e}function zo(e,t){return `<!DOCTYPE html>
1135
+ `;function Le(){return jsxRuntime.jsx("script",{dangerouslySetInnerHTML:{__html:Mn}})}It();function me(e){return "<!DOCTYPE html>"+server.renderToString(e)}var fo=["corporate","silk","dark"],yo=()=>jsxRuntime.jsxs("div",{class:"dropdown dropdown-end","data-frs-theme-switcher":true,children:[jsxRuntime.jsxs("button",{type:"button",tabIndex:0,class:"btn btn-sm btn-ghost text-neutral-content gap-1.5","aria-label":"Switch theme",children:[jsxRuntime.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:[jsxRuntime.jsx("circle",{cx:"12",cy:"12",r:"4"}),jsxRuntime.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"})]}),jsxRuntime.jsx("span",{class:"text-xs hidden sm:inline","data-frs-theme-current":true,children:"Theme"})]}),jsxRuntime.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:fo.map(e=>jsxRuntime.jsx("li",{children:jsxRuntime.jsxs("button",{type:"button","data-frs-theme":e,class:"capitalize justify-between",children:[jsxRuntime.jsx("span",{children:e}),jsxRuntime.jsx("span",{class:"hidden text-primary","data-frs-theme-check":e,children:"\u2713"})]})},e))})]}),ge=({opts:e,children:t})=>{let{title:n,breadcrumb:r,flash:o,basePath:s="/"}=e;return jsxRuntime.jsxs("html",{lang:"en","data-theme":"corporate",children:[jsxRuntime.jsxs("head",{children:[jsxRuntime.jsx("meta",{charset:"UTF-8"}),jsxRuntime.jsx("meta",{name:"viewport",content:"width=device-width, initial-scale=1"}),jsxRuntime.jsxs("title",{children:[n," \u2014 FRS Admin"]}),jsxRuntime.jsx("script",{dangerouslySetInnerHTML:{__html:"(function(){try{var t=localStorage.getItem('frs-admin-theme');if(t){document.documentElement.setAttribute('data-theme',t);}}catch(_){}})();"}}),jsxRuntime.jsx("link",{href:"https://cdn.jsdelivr.net/npm/daisyui@5/themes.css",rel:"stylesheet",type:"text/css"}),jsxRuntime.jsx("link",{href:"https://cdn.jsdelivr.net/npm/daisyui@5/daisyui.css",rel:"stylesheet",type:"text/css"}),jsxRuntime.jsx("script",{src:"https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"})]}),jsxRuntime.jsxs("body",{class:"bg-base-200/50 min-h-screen flex flex-col",children:[jsxRuntime.jsxs("div",{class:"navbar bg-neutral text-neutral-content shadow-sm sticky top-0 z-50 px-6",children:[jsxRuntime.jsx("div",{class:"flex-1",children:jsxRuntime.jsx("a",{href:s,class:"font-bold text-lg tracking-tight hover:opacity-80 transition-opacity",children:"FRS Admin"})}),jsxRuntime.jsx("div",{class:"flex-none",children:jsxRuntime.jsx(yo,{})})]}),jsxRuntime.jsxs("main",{class:"px-6 py-8 w-full flex-1",children:[r&&r.length>0&&jsxRuntime.jsx("div",{class:"text-sm breadcrumbs mb-4",children:jsxRuntime.jsx("ul",{children:r.map((a,c)=>a.href?jsxRuntime.jsx("li",{children:jsxRuntime.jsx("a",{href:a.href,children:a.label})},c):jsxRuntime.jsx("li",{class:"text-base-content/60",children:a.label},c))})}),jsxRuntime.jsx("h1",{class:"text-2xl font-bold mb-6",children:n}),o&&jsxRuntime.jsxs("div",{role:"alert",class:`alert ${o.type==="success"?"alert-success":o.type==="warning"?"alert-warning":"alert-error"} mb-6`,children:[jsxRuntime.jsx("span",{class:"flex-1",children:o.message}),o.action&&jsxRuntime.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]}),jsxRuntime.jsx(Dt,{basePath:s}),jsxRuntime.jsx(Le,{})]})]})};function Nt(e,t){return me(jsxRuntime.jsx(ge,{opts:t,children:jsxRuntime.jsx("div",{dangerouslySetInnerHTML:{__html:e}})}))}function _t(e,t){return me(jsxRuntime.jsx(ge,{opts:{title:"Repositories",basePath:t},children:e.length===0?jsxRuntime.jsxs("div",{class:"text-center py-20 text-base-content/50",children:[jsxRuntime.jsx("p",{class:"text-lg font-medium mb-1",children:"No repositories configured"}),jsxRuntime.jsx("p",{class:"text-sm",children:"Add a repository to your FRS config to get started."})]}):jsxRuntime.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=>jsxRuntime.jsx("a",{href:`${t}/${n.name}`,class:"card bg-base-100 border border-base-300 hover:shadow-md no-underline transition-shadow",children:jsxRuntime.jsxs("div",{class:"card-body p-5",children:[jsxRuntime.jsx("h2",{class:"card-title text-sm font-semibold",children:n.name}),jsxRuntime.jsx("p",{class:"text-xs text-base-content/50 font-mono",children:n.path})]})},n.name))})}))}var Zn=[{value:"==",label:"="},{value:"!=",label:"\u2260"},{value:"in",label:"in"},{value:"not-in",label:"not in"}],mo=[{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"}],go=[{value:"array-contains",label:"contains"},{value:"array-contains-any",label:"contains any"}];function ho(e){switch(e){case "ZodNumber":case "ZodBigInt":case "ZodDate":return mo;case "ZodBoolean":return Zn;case "ZodArray":return go;default:return Zn}}var he="__null__";function bo(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="${he}"]');if(!o){o=document.createElement('option');o.value='${he}';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='${he}';i.readOnly=true;}i.style.opacity='0.55';}else{i.style.opacity='';if(i.tagName==='SELECT'){var o2=i.querySelector('option[value="${he}"][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!=='${he}')?i.dataset._prev:'';}}})(this)`}function vo(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 Ve({inputId:e,active:t}){return jsxRuntime.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:[jsxRuntime.jsx("input",{type:"checkbox",class:"checkbox checkbox-xs",checked:t,onchange:bo(e)}),jsxRuntime.jsx("span",{children:"\u2205"})]})}function xo({col:e,active:t}){let n=t?.value??"",r=n===he,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 c=new Set(n.split(",").map(p=>p.trim()).filter(Boolean)),i=`eg_${e.name.replace(/\./g,"__")}`;return jsxRuntime.jsxs("div",{class:"flex flex-wrap items-center gap-1 w-full",children:[jsxRuntime.jsx("input",{type:"hidden",id:o,name:`fv_${e.name}`,value:n}),e.enumValues.map(p=>jsxRuntime.jsxs("label",{class:"flex items-center gap-1 text-xs border border-base-300 rounded px-2 cursor-pointer hover:bg-base-200",children:[jsxRuntime.jsx("input",{type:"checkbox",class:"checkbox checkbox-xs",value:p,checked:c.has(p),"data-enum-group":i,onchange:vo(o,i)}),jsxRuntime.jsx("span",{children:p})]},p))]})}return jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.jsxs("select",{id:o,name:`fv_${e.name}`,class:"select select-sm select-bordered w-full",style:r?"opacity:0.55":void 0,children:[jsxRuntime.jsx("option",{value:"",selected:n===""&&!r,children:"\u2014"}),e.enumValues.map(c=>jsxRuntime.jsx("option",{value:c,selected:n===c,children:c},c)),e.nullable&&jsxRuntime.jsx("option",{value:he,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsxRuntime.jsx(Ve,{inputId:o,active:r})]})}if(e.zodType==="ZodBoolean")return jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.jsxs("select",{id:o,name:`fv_${e.name}`,class:"select select-sm select-bordered w-full",style:r?"opacity:0.55":void 0,children:[jsxRuntime.jsx("option",{value:"",selected:n===""&&!r,children:"\u2014"}),jsxRuntime.jsx("option",{value:"true",selected:n==="true",children:"true"}),jsxRuntime.jsx("option",{value:"false",selected:n==="false",children:"false"}),e.nullable&&jsxRuntime.jsx("option",{value:he,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsxRuntime.jsx(Ve,{inputId:o,active:r})]});if(e.zodType==="ZodArray"){let c=t?.op==="array-contains-any";return jsxRuntime.jsx("input",{id:o,type:"text",name:`fv_${e.name}`,value:n,placeholder:c?"val1, val2, \u2026":"value",class:"input input-sm input-bordered w-full"})}return e.zodType==="ZodNumber"||e.zodType==="ZodBigInt"?jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.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&&jsxRuntime.jsx(Ve,{inputId:o,active:r})]}):e.zodType==="ZodDate"?jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.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&&jsxRuntime.jsx(Ve,{inputId:o,active:r})]}):jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.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&&jsxRuntime.jsx(Ve,{inputId:o,active:r})]})}function jt({action:e,columnMeta:t,activeFilters:n,isGroup:r}){let o=Object.fromEntries(n.map(i=>[i.field,i])),s=n.length>0,a=n.length>=2||r&&s,c=t.filter(i=>i.zodType!=="ZodObject"&&i.zodType!=="ZodRecord");return jsxRuntime.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:[jsxRuntime.jsxs("summary",{class:"collapse-title text-sm font-medium py-2 min-h-0",children:["Filters",s&&jsxRuntime.jsxs("span",{class:"badge badge-primary badge-sm ml-2",children:[n.length," active"]})]}),jsxRuntime.jsx("div",{class:"collapse-content pb-4 pt-2",children:jsxRuntime.jsxs("form",{method:"get",action:e,children:[jsxRuntime.jsx("div",{class:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:c.map(i=>{let p=ho(i.zodType),d=o[i.name],h=d?.op??p[0].value;return jsxRuntime.jsxs("div",{class:"flex flex-col gap-1.5",children:[jsxRuntime.jsx("label",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:i.name}),jsxRuntime.jsxs("div",{class:"flex gap-1.5",children:[p.length>1?jsxRuntime.jsx("select",{name:`fo_${i.name}`,class:"select select-sm select-bordered w-20 shrink-0",children:p.map(v=>jsxRuntime.jsx("option",{value:v.value,selected:v.value===h,children:v.label},v.value))}):jsxRuntime.jsx("input",{type:"hidden",name:`fo_${i.name}`,value:p[0].value}),jsxRuntime.jsx(xo,{col:i,active:d})]})]},i.name)})}),jsxRuntime.jsxs("div",{class:"flex flex-wrap gap-2 mt-4 pt-3 border-t border-base-200 items-center",children:[jsxRuntime.jsx("button",{type:"submit",class:"btn btn-sm btn-primary",children:"Apply"}),s&&jsxRuntime.jsx("a",{href:e,class:"btn btn-sm btn-ghost",children:"Clear"}),a&&jsxRuntime.jsxs("span",{class:"text-xs text-warning ml-auto flex items-center gap-1",children:[jsxRuntime.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-4 w-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:jsxRuntime.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 Ft(e,t,n,r,o,s){let a=n==="create"?`Create ${e}`:`Edit ${e} / ${r??""}`,c=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 me(jsxRuntime.jsx(ge,{opts:{title:a,breadcrumb:c,basePath:o,flash:s},children:jsxRuntime.jsx("div",{class:"card bg-base-100 border border-base-300",children:jsxRuntime.jsx("div",{class:"card-body p-6",children:jsxRuntime.jsx("div",{dangerouslySetInnerHTML:{__html:t}})})})}))}pt();Et();function Mt(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 qn(e,t,n,r,o){let s=Mt(e,r,o);return s.set("cursor",t),s.set("dir",n),`?${s.toString()}`}function wo(e,t,n,r){let o=Mt(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 Ro(e,t,n){return `?${Mt(t,n,e).toString()}`}function zt(e,t,n,r,o,s,a=[],c=[],i=false,p=[],d,h,v,g,u,b,m,f=false){let l=`${r}/${e}`,x=`${l}/create`,y={};if(m)for(let S of n)y[S]=Ee(De(m,S));let w=(b??[]).filter(S=>{let k=y[S]??Ee(De(m,S));return k==="string"||k==="number"||k==="bigint"||k==="boolean"||k==="enum"||k==="literal"}),R=w.length>0,C=i,P=C||R,T=w.map(S=>{let k=De(m,S),O=Ee(k),A=a.find($=>$.name===S);return {name:S,type:O,enumValues:A?.enumValues??null,nullable:A?.nullable??false}});return me(jsxRuntime.jsxs(ge,{opts:{title:e,breadcrumb:[{label:"Repositories",href:r},{label:e}],basePath:r,flash:s},children:[a.length>0&&jsxRuntime.jsx(jt,{action:l,columnMeta:a,activeFilters:c,isGroup:g}),v&&jsxRuntime.jsxs("div",{role:"alert",class:`alert ${v.type==="index"?"alert-warning":"alert-error"} mb-6 shadow-sm`,children:[jsxRuntime.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:v.type==="index"?jsxRuntime.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"}):jsxRuntime.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"})}),jsxRuntime.jsxs("div",{class:"flex-1",children:[jsxRuntime.jsx("h3",{class:"font-bold",children:v.type==="index"?"Composite index required":"Query failed"}),jsxRuntime.jsx("div",{class:"text-sm",children:v.message})]}),v.indexUrl&&jsxRuntime.jsx("a",{href:v.indexUrl,target:"_blank",rel:"noopener noreferrer",class:"btn btn-sm btn-outline",children:"Create Index \u2192"})]}),jsxRuntime.jsxs("div",{class:"flex flex-wrap justify-between items-center mb-4 gap-3","data-frs-toolbar":true,children:[jsxRuntime.jsxs("div",{class:"flex items-center gap-3",children:[jsxRuntime.jsxs("span",{class:"text-sm text-base-content/60",children:[t.length,typeof u=="number"&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[" ","of ",jsxRuntime.jsx("span",{class:"font-semibold text-base-content/80",children:u})]})," ","document",(typeof u=="number"?u:t.length)!==1&&"s"]}),jsxRuntime.jsxs("div",{class:"flex items-center gap-1.5 text-sm text-base-content/60",children:[jsxRuntime.jsx("span",{children:"Rows"}),jsxRuntime.jsx("div",{class:"join",children:[10,25,50,100].map(S=>jsxRuntime.jsx("a",{href:Ro(S,c,d),class:`join-item btn btn-xs ${h===S?"btn-active btn-primary":"btn-outline"}`,children:S},S))})]})]}),jsxRuntime.jsx("a",{href:x,class:"btn btn-primary btn-sm",children:"+ New"})]}),P&&jsxRuntime.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 u=="number"?String(u):"","data-frs-page-size":String(h??t.length),"data-frs-allow-delete":C?"1":"0","data-frs-allow-update":R?"1":"0","data-frs-fields":JSON.stringify(T),"data-frs-filters":JSON.stringify(c),children:[jsxRuntime.jsxs("div",{class:"flex-1 text-sm",children:[jsxRuntime.jsx("span",{"data-frs-bulk-summary":true,children:"0 selected"}),typeof u=="number"&&u>t.length&&jsxRuntime.jsxs("button",{type:"button",class:"ml-3 link link-primary text-sm hidden","data-frs-bulk-select-all":true,children:["Select all ",u," matching documents"]}),jsxRuntime.jsxs("span",{class:"hidden ml-3 italic","data-frs-bulk-all-active":true,children:["All ",u??"?"," matching documents are selected."," ",jsxRuntime.jsx("button",{type:"button",class:"link","data-frs-bulk-clear":true,children:"Clear selection"})]})]}),jsxRuntime.jsxs("div",{class:"flex gap-2",children:[R&&jsxRuntime.jsx("button",{type:"button",class:"btn btn-sm btn-outline","data-frs-bulk-action":"update",children:"Update field\u2026"}),C&&jsxRuntime.jsx("button",{type:"button",class:"btn btn-sm btn-error btn-outline","data-frs-bulk-action":"delete",children:"Delete"})]})]}),jsxRuntime.jsx("div",{class:"overflow-x-auto rounded-box border border-base-300 bg-base-100","data-frs-table-wrap":true,children:jsxRuntime.jsxs("table",{class:"table table-sm w-full","data-frs-table":true,"data-frs-repo":e,"data-frs-colcount":n.length,children:[jsxRuntime.jsx("thead",{children:jsxRuntime.jsxs("tr",{class:"bg-base-200/50",children:[P&&jsxRuntime.jsx("th",{class:"w-8",children:jsxRuntime.jsx("input",{type:"checkbox",class:"checkbox checkbox-xs checkbox-primary","data-frs-select-page":true,"aria-label":"Select all on this page"})}),[...n].map((S,k)=>{let O=d?.field===S,A=O?d.dir==="asc"?" \u25B2":" \u25BC":"";return jsxRuntime.jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:jsxRuntime.jsxs("a",{href:wo(S,d,c,h),class:`hover:text-base-content inline-flex items-center gap-0.5${O?" text-primary font-bold":""}`,children:[S,A]})},k)}),p.map((S,k)=>jsxRuntime.jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:S.column},`rel-${k}`)),jsxRuntime.jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide text-right",children:"Actions"})]})}),jsxRuntime.jsx("tbody",{children:t.length===0?jsxRuntime.jsx("tr",{children:jsxRuntime.jsx("td",{colspan:n.length+p.length+1+(P?1:0),class:"text-center py-16 text-base-content/40",children:"No documents found"})}):t.map((S,k)=>{let O=String(S.docId??S.id??""),A=`${r}/${e}/${encodeURIComponent(O)}/edit`,$=`${r}/${e}/${encodeURIComponent(O)}/delete`;return jsxRuntime.jsxs("tr",{class:"hover","data-frs-row-id":O,children:[P&&jsxRuntime.jsx("td",{class:"align-middle py-2",children:jsxRuntime.jsx("input",{type:"checkbox",class:"checkbox checkbox-xs checkbox-primary","data-frs-select-row":true,value:O,"aria-label":`Select ${O}`})}),n.map((_,z)=>{let I=S[_],E=y[_],q=E?Ue(E,I):null;return jsxRuntime.jsx("td",{class:"align-top py-2",children:jsxRuntime.jsx(Pe,{val:I,mismatch:q})},z)}),p.map((_,z)=>{let I=S[_.key];if(I==null||I==="")return jsxRuntime.jsx("td",{class:"py-2"},`rel-${z}`);let E=_.type==="one"?`${r}/${_.targetRepo}/${encodeURIComponent(String(I))}/edit`:`${r}/${_.targetRepo}?fv_${_.targetKey}=${encodeURIComponent(String(I))}`;return jsxRuntime.jsx("td",{class:"align-middle py-2",children:jsxRuntime.jsx("a",{href:E,class:"btn btn-xs btn-ghost btn-outline","data-frs-relation":true,"data-frs-rel-type":_.type,"data-frs-rel-repo":_.targetRepo,"data-frs-rel-fk":_.targetKey,"data-frs-rel-val":String(I),"data-frs-rel-label":_.column,children:_.column})},`rel-${z}`)}),jsxRuntime.jsx("td",{class:"align-middle text-right whitespace-nowrap py-2",children:jsxRuntime.jsxs("div",{class:"flex gap-1 justify-end",children:[jsxRuntime.jsx("a",{href:A,class:"btn btn-xs btn-outline",children:"Edit"}),f&&jsxRuntime.jsx("a",{href:`${r}/${e}/${encodeURIComponent(O)}/history`,class:"btn btn-xs btn-outline",title:"View change history",children:"History"}),i&&jsxRuntime.jsx("form",{method:"post",action:$,onsubmit:"return confirm('Delete this document?')",children:jsxRuntime.jsx("button",{type:"submit",class:"btn btn-xs btn-error btn-outline",children:"Delete"})})]})})]},k)})})]})}),(o.hasPrev||o.hasNext)&&jsxRuntime.jsxs("div",{class:"flex flex-col items-center mt-6 gap-2",children:[jsxRuntime.jsxs("div",{class:"flex justify-center items-center gap-2",children:[o.hasPrev?jsxRuntime.jsx("a",{href:qn(c,o.prevCursor,"prev",d,h),class:"btn btn-sm btn-outline",children:"\u2190 Previous"}):jsxRuntime.jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"\u2190 Previous"}),o.hasNext?jsxRuntime.jsx("a",{href:qn(c,o.nextCursor,"next",d,h),class:"btn btn-sm btn-outline",children:"Next \u2192"}):jsxRuntime.jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"Next \u2192"})]}),typeof u=="number"&&jsxRuntime.jsxs("div",{class:"text-xs text-base-content/50",children:[u," total document",u!==1?"s":"",c.length>0?" matching filters":""]})]}),P&&R&&jsxRuntime.jsxs("dialog",{id:"frs-bulk-update-modal",class:"modal",children:[jsxRuntime.jsxs("div",{class:"modal-box",children:[jsxRuntime.jsx("h3",{class:"font-bold text-lg mb-3",children:"Bulk update field"}),jsxRuntime.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."}),jsxRuntime.jsxs("form",{method:"dialog","data-frs-bulk-update-form":true,children:[jsxRuntime.jsxs("label",{class:"form-control w-full mb-3",children:[jsxRuntime.jsx("div",{class:"label",children:jsxRuntime.jsx("span",{class:"label-text text-xs uppercase tracking-wide",children:"Field"})}),jsxRuntime.jsxs("select",{class:"select select-bordered select-sm w-full",name:"field",required:true,"data-frs-bulk-field-select":true,children:[jsxRuntime.jsx("option",{value:"",children:"\u2014 Select a field \u2014"}),w.map(S=>jsxRuntime.jsx("option",{value:S,children:S},S))]})]}),jsxRuntime.jsx("div",{class:"mb-4","data-frs-bulk-value-container":true}),jsxRuntime.jsxs("div",{class:"modal-action",children:[jsxRuntime.jsx("button",{type:"button",class:"btn btn-sm btn-ghost","data-frs-bulk-update-cancel":true,children:"Cancel"}),jsxRuntime.jsx("button",{type:"submit",class:"btn btn-sm btn-primary","data-frs-bulk-update-submit":true,children:"Apply"})]})]})]}),jsxRuntime.jsx("form",{method:"dialog",class:"modal-backdrop",children:jsxRuntime.jsx("button",{children:"close"})})]})]}))}function Qe(e,t){return Nt(e,t)}function Ht(e,t){return _t(e,t)}function Bt(e,t,n,r,o,s,a,c,i,p,d,h,v,g,u,b,m,f){return zt(e,t,n,r,o,s,a,c,i,p,d,h,v,g,u,b,m,f)}function be(e,t,n,r,o,s){return Ft(e,t,n,r,o,s)}var Kn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function ko(){let e="";for(let t=0;t<20;t++)e+=Kn.charAt(Math.floor(Math.random()*Kn.length));return e}function yt(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 Ie(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 Zt(e,t,n){let r=e.documentKey??"docId",o=Ke(n,{ref:e.repo.ref,path:e.path,isGroup:!!e.isGroup,filters:[{field:r,op:"==",value:t}]});return o.type==="index"?{type:"warning",message:"Loading this document requires a composite index that does not exist yet.",...o.indexUrl?{action:{href:o.indexUrl,label:"Create Index \u2192",external:true}}:{}}:{type:"error",message:o.message}}function F(e,t,n=200){e.status(n).set("Content-Type","text/html; charset=utf-8").send(t);}function qt(e,t){e.status(302).set("Location",t).send("");}function Kt(e,t){let n=t.shape,r={};for(let[o,s]of Object.entries(n)){let a=Ut(s);if(a==="ZodObject"){if(e[o+"__isnull"]==="1"){r[o]=null;continue}let p={},d=false;for(let[g,u]of Object.entries(e))g.startsWith(`${o}.`)&&(p[g.slice(o.length+1)]=u,d=true);if(d){let g=s;for(;;){let u=Z(g);if(u==="ZodOptional"||u==="ZodNullable"||u==="ZodDefault")g=U(g);else break}r[o]=Kt(p,g);continue}let h=e[o],v=Array.isArray(h)?h[h.length-1]:h;if(v)try{r[o]=JSON.parse(v);}catch{r[o]=v;}continue}let c=e[o],i=Array.isArray(c)?c[c.length-1]:c;if(e[o+"__isnull"]==="1"){r[o]=null;continue}if(i===void 0||i===""){a==="ZodBoolean"&&(r[o]=false);continue}switch(a){case "ZodBoolean":i==="__null__"?r[o]=null:r[o]=i==="true"||i==="on"||i==="1";break;case "ZodNumber":case "ZodBigInt":r[o]=Number(i);break;case "ZodDate":r[o]=new Date(i);break;case "ZodArray":try{r[o]=JSON.parse(i);}catch{r[o]=i;}break;default:if(i.startsWith("{")||i.startsWith("["))try{r[o]=JSON.parse(i);break}catch{}r[o]=i;}}return r}function Ln(e){let t=null;if(e instanceof Date)t=e;else if(typeof e=="object"&&e!==null&&typeof e.toDate=="function")t=e.toDate();else if(typeof e=="object"&&e!==null&&"_seconds"in e&&"_nanoseconds"in e)t=new Date(e._seconds*1e3+Math.floor(e._nanoseconds/1e6));else if(typeof e=="string"||typeof e=="number"){let r=new Date(e);isNaN(r.getTime())||(t=r);}if(!t||isNaN(t.getTime()))return null;let n=r=>String(r).padStart(2,"0");return `${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`}function Ut(e){let t=e;for(;;){let n=Z(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=U(t);else return n}}function Co(e){let t=e;for(;;){let n=Z(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=U(t);else return t}}function Vn(e){let t=e;for(;;){let n=Z(t);if(n==="ZodOptional"||n==="ZodNullable")return true;if(n==="ZodDefault"){t=U(t);continue}return false}}function Qn(e){let t=Co(e),n=Z(t);if(n==="ZodEnum"){let r=ze(t);return r.length>0?r:void 0}if(n==="ZodNativeEnum"){let r=He(t),o=Object.values(r).filter(s=>typeof s=="string");return o.length>0?o:void 0}if(n==="ZodLiteral"){let r=lt(t);return typeof r=="string"?[r]:void 0}}function Gn(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 c=t.shape[o];for(;;){let p=Z(c);if(p==="ZodOptional"||p==="ZodNullable"||p==="ZodDefault")c=U(c);else break}let i=Z(c);if(i==="ZodObject"&&typeof a=="object"&&a!==null&&!Array.isArray(a)){let p=Gn(a,c,s);Object.assign(r,p);}else if(i==="ZodDate"){let p=Ln(a);p!==null&&(r[s]=p);}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)&&("_seconds"in a||typeof a.toDate=="function")){let p=Ln(a);r[s]=p??JSON.stringify(a,null,2);}else typeof a=="object"?r[s]=JSON.stringify(a,null,2):r[s]=String(a);}return r}function Lt(e,t){return e.map(n=>({...n,defaultValue:t[n.name]??n.defaultValue,nested:n.nested?Lt(n.nested,t):void 0}))}function Oo(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 c=(s??"").trim();if(!c)continue;let i=e[`fo_${a}`]??"==",p=n.has(i)?i:"==";r.push({field:a,op:p,value:c});}return r}function Un(e){let t="__null__",n=r=>r===t?null:r==="true"?true:r==="false"?false:r!==""&&!isNaN(Number(r))?Number(r):r;return e.map(r=>{if(r.op==="array-contains-any"||r.op==="in"||r.op==="not-in"){let o=r.value.split(",").map(s=>s.trim()).filter(s=>s!==""&&s!==t).map(s=>n(s));return [r.field,r.op,o]}return [r.field,r.op,n(r.value)]})}function Wn(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 c=Ut(a);if(c==="ZodObject"){let i=a;for(;;){let d=Z(i);if(d==="ZodOptional"||d==="ZodNullable"||d==="ZodDefault")i=U(i);else break}let p=ee(i);r.push(...Wn(Object.keys(p),i,s));}else r.push({name:s,zodType:c,nullable:Vn(a),enumValues:Qn(a)});}return r}function $o(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=U(r);else break}let s=ee(r);if(!(o in s))return null;r=s[o];}return r}function Ce(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 c=s.slice(0,a),i=s.slice(a+1);r.has(c)||r.set(c,[]),r.get(c).push(i);}}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 c=e.shape[s];for(;;){let i=Z(c);if(i==="ZodOptional"||i==="ZodNullable"||i==="ZodDefault")c=U(c);else break}if(Z(c)!=="ZodObject"){o[s]=e.shape[s];continue}o[s]=Ce(c,a);}return zod.z.object(o)}function de(e,t){let n=t==="/"?"":t.replace(/\/$/,"");if(process.env.FUNCTIONS_EMULATOR==="true"){let s=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??"demo-project",a=process.env.FUNCTION_REGION??"us-central1",c=(process.env.FUNCTION_TARGET??"").replace(/\./g,"-");return `/${s}/${a}/${c}${n}`}let r=process.env.K_SERVICE,o=e.hostname??e.headers?.host??"";return r&&o.includes("cloudfunctions.net")?`/${r.toLowerCase()}${n}`:n}function Jn(e,t){let n=(f,l)=>{let x=de(f,t),y=Object.values(e).map(w=>({name:w.name,path:w.path}));F(l,Ht(y,x));},r=async(f,l)=>{let x=f.params.repoName;if(!x){F(l,"Bad request",400);return}let y=e[x];if(!y){F(l,"Repository not found",404);return}let w=y.pageSize??25,R=f.query??{},C=R.cursor,P=R.dir==="prev"?"prev":"next",T=R.ob??"",S=R.od==="desc"?"desc":"asc",k=T?{field:T,dir:S}:void 0,O=parseInt(R.ps??""),A=Number.isFinite(O)&&O>0?Math.min(O,200):w,$=y.listColumns??Object.keys(y.schema.shape),_=y.documentKey??"docId",z=[_,...$.filter(G=>G!==_)],I=y.filterableFields?(()=>{let G=[];for(let le of y.filterableFields)(le.includes(".")||$.includes(le))&&G.push(le);return G})():$,E=(()=>{let G=[];for(let le of I)if(le.includes(".")){let $e=$o(y.schema,le);G.push({name:le,zodType:$e?Ut($e):"ZodString",nullable:$e?Vn($e):false,enumValues:$e?Qn($e):void 0});}else G.push(...Wn([le],y.schema));return G})(),q=new Set(E.map(G=>G.name)),xe=Oo(R,q),ue=Un(xe),je;if(C)try{let G=y.repo.ref;typeof G.doc=="function"&&(je=await G.doc(C).get());}catch{}let[W,Je]=await Promise.all([y.repo.query.paginate({pageSize:A,cursor:je,direction:P,...ue.length>0?{where:ue}:{},...k?{orderBy:[{field:k.field,direction:k.dir}]}:{}}).catch(G=>({queryError:Ke(G,{ref:y.repo.ref,path:y.path,isGroup:!!y.isGroup,filters:xe,sort:k})})),y.repo.aggregate.count(ue.length>0?{where:ue}:{}).catch(()=>{})]),Oe="queryError"in W,cr=Oe?[]:W.data,dr=Oe?"":W.nextCursor?.id??"",ur=Oe?"":W.prevCursor?.id??"",pr=Oe?W.queryError:void 0,fr=de(f,t);F(l,Bt(y.name,cr,z,fr,{hasPrev:Oe?false:W.hasPrevPage,hasNext:Oe?false:W.hasNextPage,prevCursor:ur,nextCursor:dr},void 0,E,xe,y.allowDelete??false,y.relationalMeta,k,A,pr,y.isGroup,Je,y.mutableFields,y.schema,y.historyEnabled));},o=(f,l)=>{let x=f.params.repoName;if(!x){F(l,"Bad request",400);return}let y=e[x];if(!y){F(l,"Repository not found",404);return}let w=de(f,t),R=Ce(y.schema,y.createFields),C=ae(R),P=`${w}/${y.name}/create`,T=ye(C,P,"POST","Create document");F(l,be(y.name,T,"create",null,w));},s=async(f,l)=>{let x=f.params.repoName;if(!x){F(l,"Bad request",400);return}let y=e[x];if(!y){F(l,"Repository not found",404);return}let w=de(f,t),R=f.body??{},C=Kt(R,y.schema),P=Ce(y.schema,y.createFields),T=P.safeParse(C);if(!T.success){let S=ae(P),k=`${w}/${y.name}/create`,O=ye(S,k,"POST","Create document"),A=T.error.issues.map($=>`${$.path.join(".")}: ${$.message}`).join(", ");F(l,be(y.name,O,"create",null,w,{type:"error",message:`Validation error: ${A}`}),422);return}try{if(y.isGroup&&y.parentKeys&&y.parentKeys.length>0){let S={...T.data};y.createdKey&&(S[y.createdKey]=new Date);let k=y.parentKeys.filter(_=>!S[_]);if(k.length>0)throw new Error(`Missing parent key(s) for subcollection create: ${k.join(", ")}`);let O=y.parentKeys.map(_=>S[_]),A=y.documentKey??"docId",$=S[A]||ko();await y.repo.set(...O,$,S);}else await y.repo.create(T.data);qt(l,`${w}/${y.name}?flash=created`);}catch(S){let k=Ce(y.schema,y.createFields),O=ae(k),A=`${w}/${y.name}/create`,$=ye(O,A,"POST","Create document");F(l,be(y.name,$,"create",null,w,{type:"error",message:`Save error: ${S.message}`}),500);}},a=async(f,l)=>{let x=f.params.repoName,y=f.params.id;if(!x||!y){F(l,"Bad request",400);return}let w=e[x];if(!w){F(l,"Repository not found",404);return}let R=de(f,t),C=null;try{C=await Ie(w,y);}catch(A){let $=Zt(w,y,A),_=Te(A)?424:500;F(l,Qe("",{title:`Edit ${w.name} / ${y}`,basePath:R,breadcrumb:[{label:"Repositories",href:R},{label:w.name,href:`${R}/${w.name}`},{label:`Edit ${y}`}],flash:$}),_);return}if(!C){F(l,"Document not found",404);return}let P=Gn(C,w.schema),T=Ce(w.schema,w.mutableFields),S=Lt(ae(T),P),k=`${R}/${w.name}/${encodeURIComponent(y)}/edit`,O=ye(S,k,"POST","Save changes");F(l,be(w.name,O,"edit",y,R));},c=async(f,l)=>{let x=f.params.repoName,y=f.params.id;if(!x||!y){F(l,"Bad request",400);return}let w=e[x];if(!w){F(l,"Repository not found",404);return}let R=de(f,t),C=f.body??{},P=Kt(C,w.schema),T=Ce(w.schema,w.mutableFields),k=T.partial().safeParse(P);if(!k.success){let O=Object.fromEntries(Object.entries(C).map(([I,E])=>[I,Array.isArray(E)?E.join(","):E??""])),A=Lt(ae(T),O),$=`${R}/${w.name}/${encodeURIComponent(y)}/edit`,_=ye(A,$,"POST","Save changes"),z=k.error.issues.map(I=>`${I.path.join(".")}: ${I.message}`).join(", ");F(l,be(w.name,_,"edit",y,R,{type:"error",message:`Validation error: ${z}`}),422);return}try{let O=await Ie(w,y),A=(O&&yt(O,w.pathKey))??[y];await w.repo.update(...A,k.data),qt(l,`${R}/${w.name}?flash=updated`);}catch(O){let A=Ce(w.schema,w.mutableFields),$=ae(A),_=`${R}/${w.name}/${encodeURIComponent(y)}/edit`,z=ye($,_,"POST","Save changes"),I=Te(O)?Zt(w,y,O):{type:"error",message:`Save error: ${O.message}`},E=Te(O)?424:500;F(l,be(w.name,z,"edit",y,R,I),E);}},i=async(f,l)=>{let x=f.params.repoName,y=f.params.id;if(!x||!y){F(l,"Bad request",400);return}let w=e[x];if(!w){F(l,"Repository not found",404);return}if(!w.allowDelete){F(l,"Delete is not allowed for this repository",403);return}let R=de(f,t);try{let C=await Ie(w,y),P=(C&&yt(C,w.pathKey))??[y];await w.repo.delete(...P),qt(l,`${R}/${w.name}?flash=deleted`);}catch(C){let P=Te(C)?Zt(w,y,C):{type:"error",message:`Delete error: ${C.message}`},T=Te(C)?424:500;F(l,Qe("",{title:`Delete ${w.name} / ${y}`,basePath:R,breadcrumb:[{label:"Repositories",href:R},{label:w.name,href:`${R}/${w.name}`},{label:`Delete ${y}`}],flash:P}),T);}},p=async(f,l)=>{let x=f.params.repoName;if(!x){F(l,"Bad request",400);return}let y=e[x];if(!y){F(l,"Repository not found",404);return}let w=de(f,t),R=f.query,C=R?.type==="many"?"many":"one",P=Math.max(1,Math.min(100,Number(R?.ps??25)||25)),T=y.listColumns??Object.keys(ee(y.schema)),{PanelOne:S,PanelMany:k}=await Promise.resolve().then(()=>(It(),Hn)),{renderToString:O}=await import('hono/jsx/dom/server');if(C==="one"){let E=String(R?.id??"");if(!E){F(l,"<div class='p-6 text-error'>Missing id parameter.</div>",400);return}try{let q=await Ie(y,E),xe=O(S({doc:q,repoName:y.name,basePath:w,schema:y.schema,columns:T}));F(l,xe);}catch(q){F(l,`<div class='p-6 text-error text-sm'>Error: ${q.message}</div>`,500);}return}let A=String(R?.fk??""),$=String(R?.fv??"");if(!A||!$){F(l,"<div class='p-6 text-error'>Missing fk/fv parameters.</div>",400);return}let _=R?.cursor??"",z=R?.dir==="prev"?"prev":"next",I;if(_)try{let E=y.repo.ref;typeof E.doc=="function"&&(I=await E.doc(_).get());}catch{}try{let E=await y.repo.query.paginate({pageSize:P,cursor:I,direction:z,where:[[A,"==",Ao($)]]}),q=O(k({docs:E.data,repoName:y.name,basePath:w,fk:A,fv:$,columns:T,schema:y.schema,pagination:{hasPrev:E.hasPrevPage,hasNext:E.hasNextPage,prevCursor:E.prevCursor?.id??"",nextCursor:E.nextCursor?.id??"",pageSize:P}}));F(l,q);}catch(E){F(l,`<div class='p-6 text-error text-sm'>Error: ${E.message}</div>`,500);}},d=async(f,l)=>{let x=[];for(let y of l){let w;if(f.isGroup||f.parentKeys?.length){let R=await Ie(f,y);w=R?yt(R,f.pathKey):void 0;}w||(w=[y]);try{let R=f.repo.documentRef(...w);R&&x.push(R);}catch{}}return x},h=async(f,l)=>{let x=Un(l),y=f.documentKey??"docId",w=[],R;for(;;){let C=await f.repo.query.paginate({pageSize:500,cursor:R,direction:"next",...x.length>0?{where:x}:{}});for(let P of C.data){let T=String(P[y]??P.id??"");T&&w.push(T);}if(!C.hasNextPage||!C.nextCursor)break;R=C.nextCursor;}return w},v=async(f,l)=>{let x=f.params.repoName;if(!x){Y(l,{error:"Bad request"},400);return}let y=e[x];if(!y){Y(l,{error:"Repository not found"},404);return}if(!y.allowDelete){Y(l,{error:"Delete is not allowed for this repository"},403);return}let w=f.body??{};try{let R=await u(y,w);if(R.length===0){Y(l,{deleted:0});return}let C=await d(y,R);for(let P=0;P<C.length;P+=500)await y.repo.bulk.delete(C.slice(P,P+500));Y(l,{deleted:C.length});}catch(R){Y(l,{error:R.message},500);}},g=async(f,l)=>{let x=f.params.repoName;if(!x){Y(l,{error:"Bad request"},400);return}let y=e[x];if(!y){Y(l,{error:"Repository not found"},404);return}let w=f.body??{},R=String(w.field??"");if(!R){Y(l,{error:"Missing 'field'"},400);return}if(!y.mutableFields||!y.mutableFields.includes(R)){Y(l,{error:`Field '${R}' is not bulk-updatable`},403);return}let C=y.schema.shape?.[R],P=w.value;if(C){let T=C.safeParse(w.value);if(!T.success){Y(l,{error:`Invalid value for '${R}': ${T.error.message}`},400);return}P=T.data;}try{let T=await u(y,w);if(T.length===0){Y(l,{updated:0});return}let k=(await d(y,T)).map(O=>({docRef:O,data:{[R]:P}}));for(let O=0;O<k.length;O+=500)await y.repo.bulk.update(k.slice(O,O+500));Y(l,{updated:k.length});}catch(T){Y(l,{error:T.message},500);}};async function u(f,l){if(l.selectAll){let x=b(l.filters,f);return await h(f,x)}return Array.isArray(l.ids)?l.ids.filter(x=>typeof x=="string"&&!!x):[]}function b(f,l){if(!Array.isArray(f))return [];let x=new Set((l.filterableFields??Object.keys(ee(l.schema))).map(R=>String(R))),y=new Set(["==","!=","<","<=",">",">=","in","not-in","array-contains","array-contains-any"]),w=[];for(let R of f)R&&typeof R=="object"&&typeof R.field=="string"&&x.has(R.field)&&typeof R.value=="string"&&y.has(String(R.op))&&w.push({field:R.field,op:R.op,value:R.value});return w}return {handleDashboard:n,handleList:r,handleCreateForm:o,handleCreateSubmit:s,handleEditForm:a,handleEditSubmit:c,handleDelete:i,handlePanel:p,handleBulkDelete:v,handleBulkUpdate:g,handleHistory:async(f,l)=>{let x=f.params.repoName,y=f.params.id;if(!x||!y){F(l,"Bad request",400);return}let w=e[x];if(!w){F(l,"Repository not found",404);return}if(!w.historyEnabled||!w.repo.history){F(l,"History not enabled for this repository",404);return}let R=de(f,t),C=w.historySubcollection??"history",P=[y];try{let E=await Ie(w,y),q=E?yt(E,w.pathKey):void 0;q&&q.length>0&&(P=q);}catch{}let T=parseInt(String(f.query?.limit??"")),S=Number.isFinite(T)&&T>0?Math.min(T,500):100,k=[],O;try{k=await w.repo.history.list(...P,{limit:S});}catch(E){O=E.message;}let A=E=>String(E??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),$=E=>{if(E===void 0)return '<span class="opacity-40">undefined</span>';if(E===null)return '<span class="opacity-40">null</span>';if(typeof E=="object")try{return `<code class="text-xs">${A(JSON.stringify(E))}</code>`}catch{return A(String(E))}return A(String(E))},_=E=>E?typeof E.toDate=="function"?E.toDate().toISOString():E instanceof Date?E.toISOString():A(String(E)):"",z=E=>`<span class="badge badge-sm ${E==="create"?"badge-success":E==="delete"?"badge-error":"badge-info"}">${A(E)}</span>`,I="";if(I+='<div class="flex items-center justify-between mb-4">',I+=`<a href="${R}/${w.name}/${encodeURIComponent(y)}/edit" class="btn btn-sm btn-outline">\u2190 Back to edit</a>`,I+=`<a href="${R}/${w.name}" class="btn btn-sm btn-outline">\u2190 Back to list</a>`,I+="</div>",I+=`<p class="text-sm text-base-content/60 mb-4">Subcollection: <code>${A(C)}</code> \xB7 Showing up to ${S} entries.</p>`,O)I+=`<div class="alert alert-error mb-4">${A(O)}</div>`;else if(k.length===0)I+='<div class="alert">No history entries found.</div>';else {I+='<div class="overflow-x-auto"><table class="table table-zebra table-sm">',I+="<thead><tr><th>When</th><th>Op</th><th>User</th><th>Reason / Comment</th><th>Changes</th></tr></thead><tbody>";for(let E of k){let q=E.meta??{},xe=[q.reason,q.comment].filter(W=>W!=null&&W!=="").map(W=>A(String(W))).join(" \u2014 "),ue="",je=Object.keys(E.changes??{});je.length===0?ue='<span class="opacity-40">\u2014</span>':ue='<ul class="space-y-1">'+je.map(W=>{let Je=E.changes[W];return `<li><strong>${A(W)}</strong>: ${$(Je.oldValue)} \u2192 ${$(Je.newValue)}</li>`}).join("")+"</ul>",I+="<tr>",I+=`<td class="whitespace-nowrap text-xs font-mono">${A(_(E.historySetAt))}</td>`,I+=`<td>${z(E.operation??"update")}</td>`,I+=`<td class="text-xs">${A(q.userEmail??q.userId??"")}</td>`,I+=`<td class="text-xs">${xe}</td>`,I+=`<td>${ue}</td>`,I+="</tr>";}I+="</tbody></table></div>";}F(l,Qe(I,{title:`History \u2014 ${w.name} / ${y}`,basePath:R,breadcrumb:[{label:"Repositories",href:R},{label:w.name,href:`${R}/${w.name}`},{label:`History ${y}`}]}));}}}function Y(e,t,n=200){e.status(n).set("Content-Type","application/json; charset=utf-8").send(JSON.stringify(t));}function Ao(e){return e==="true"?true:e==="false"?false:e!==""&&!isNaN(Number(e))?Number(e):e}async function Po(e){return typeof e.rawBody=="string"?e.rawBody:Buffer.isBuffer(e.rawBody)?e.rawBody.toString("utf8"):""}function Eo(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 Xn(e){let{basePath:t="/",repos:n,parseBody:r=true,auth:o,middleware:s=[],httpsOptions:a}=e,c=t==="/"?"":t.replace(/\/$/,""),i={};for(let[v,g]of Object.entries(n)){let u=g.schema??g.repo.schema??null;if(!u)throw new Error(`[createAdminServer] Repository "${v}" has no Zod schema. Either use createRepositoryConfig(schema)(config) or pass schema: explicitly.`);let b,m,f;if(g.fieldsConfig){let y=g.fieldsConfig;b=[],m=[],f=[];for(let[w,R]of Object.entries(y))for(let C of R)C==="filterable"?b.push(w):C==="mutable"?m.push(w):C==="create"&&f.push(w);b.length===0&&(b=void 0),m.length===0&&(m=void 0),f.length===0&&(f=void 0);}let l=(()=>{let y=g.repo._parentKeys;return y&&y.length>0?y:void 0})();if(l&&f)for(let y of l)f.includes(y)||f.push(y);let x={name:v,path:g.path,repo:g.repo,schema:u,documentKey:g.documentKey??"docId",pathKey:g.repo._pathKey??void 0,isGroup:!!g.repo._isGroup,parentKeys:l,createdKey:g.repo._createdKey??void 0,listColumns:g.listColumns,pageSize:g.pageSize,filterableFields:b,mutableFields:m,createFields:f,allowDelete:g.allowDelete??false,historyEnabled:!!g.repo.history,historySubcollection:(g.repo.history&&g.repo._historySubcollection)??void 0,relationalMeta:(()=>{if(!g.relationalFields||g.relationalFields.length===0)return;let y=g.repo.relationalKeys??{},w=[];for(let R of g.relationalFields){let C=y[R.key];C&&w.push({key:R.key,column:R.column,targetRepo:String(C.repo),targetKey:String(C.key),type:C.type});}return w.length>0?w:void 0})()};i[v]=x;}let p=Jn(i,c),d=new te;if(r&&d.use(async(v,g,u)=>{let b=v,m=String(b.headers?.["content-type"]??"");if(m.includes("application/x-www-form-urlencoded")){let f=await Po(b);v.body=Eo(f);}else if(m.includes("application/json")&&typeof b.body=="string")try{v.body=JSON.parse(b.body);}catch{}await u();}),o)if(typeof o=="function")d.use(o);else {let v=o.realm??"Admin",g="Basic "+Buffer.from(`${o.username}:${o.password}`).toString("base64");d.use((u,b,m)=>{if((u.headers?.authorization??"")!==g){b.status(401).set("WWW-Authenticate",`Basic realm="${v}"`).set("Content-Type","text/plain").send("Unauthorized");return}m();});}for(let v of s)d.use(v);d.get(`${c}/`,p.handleDashboard),d.get(`${c}`,p.handleDashboard),d.get(`${c}/:repoName/_panel`,p.handlePanel),d.post(`${c}/:repoName/_bulk/delete`,p.handleBulkDelete),d.post(`${c}/:repoName/_bulk/update`,p.handleBulkUpdate),d.get(`${c}/:repoName`,p.handleList),d.get(`${c}/:repoName/create`,p.handleCreateForm),d.post(`${c}/:repoName/create`,p.handleCreateSubmit),d.get(`${c}/:repoName/:id/edit`,p.handleEditForm),d.post(`${c}/:repoName/:id/edit`,p.handleEditSubmit),d.get(`${c}/:repoName/:id/history`,p.handleHistory),d.post(`${c}/:repoName/:id/delete`,p.handleDelete);let h=async(v,g)=>{await d.handle(v,g);};return a&&(h.httpsOptions=a),h}function Qt(e,t,n=200){let r=K(t);e.status(n).set("Content-Type","application/json; charset=utf-8").send(JSON.stringify(r));}function Ne(e,t,n,r=200){Qt(e,{success:true,data:t,meta:n},r);}function Q(e,t,n=400){Qt(e,{success:false,error:t},n);}function Vt(e,t,n,r,o){let s=Ke(t,n),a=s.type==="index",c=a?424:500,p={success:false,error:a?s.message:o&&t instanceof Error?t.message:r};a&&(p.errorType="index",s.indexUrl&&(p.indexUrl=s.indexUrl)),Qt(e,p,c);}var Yn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Do(){let e="";for(let t=0;t<20;t++)e+=Yn.charAt(Math.floor(Math.random()*Yn.length));return e}function _e(e){let t=e._def??e.def;if(!t)return e;let n=t.typeName??t.type;if(n==="ZodDate"||n==="date")return zod.z.preprocess(r=>xt(r)??r,e);if(n==="ZodObject"||n==="object"){let r=e.shape,o={};for(let[s,a]of Object.entries(r))o[s]=_e(a);return zod.z.object(o)}if(n==="ZodArray"||n==="array"){let r=t.element??t.type;if(r)return zod.z.array(_e(r))}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(r)return _e(r).optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(r)return _e(r).nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType,o=t.defaultValue;if(r){let s=_e(r);return typeof o=="function"?s.default(o()):s.default(o)}}return e}function Io(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 c=a.split(".")[0];c&&r[c]&&(o[c]=r[c]);}return zod.z.object(o)}function er(e,t,n,r=false,o=[]){try{let s=Io(e,n,o),a=r?s.partial():s;return {success:!0,data:(vt()==="normalize"?_e(a):a).parse(t)}}catch(s){return s instanceof zod.z.ZodError?{success:false,error:`Validation failed: ${s.issues.map(c=>`${c.path.join(".")}: ${c.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}function No(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 c=Array.isArray(a)?a[0]:a;if(c===void 0||c==="")continue;let i=s.match(/^(\w+)__(\w+)$/),p,d="==";if(i&&i[1]&&i[2]){p=i[1];let v=i[2];if(o[v])d=o[v];else continue}else if(!i)p=s;else continue;if(r&&!r.has(p))continue;let h=c;d==="in"||d==="not-in"||d==="array-contains-any"?h=c.split(",").map(v=>tr(v.trim())):h=tr(c),n.push({field:p,op:d,value:h});}return n}function tr(e){if(e==="true")return true;if(e==="false")return false;if(e==="null")return null;let t=Number(e);return !isNaN(t)&&e!==""?t:e}function mt(e){return e?{docId:e.id}:null}async function nr(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 rr(e,t,n){function r(g,u){return !g||!e[g]?(Q(u,`Repository "${g}" not found`,404),null):e[g]}function o(g,u){if(!u)return;let b=g[u];if(typeof b!="string"||!b)return;let m=b.split("/").filter(Boolean),f=[];for(let l=1;l<m.length;l+=2)f.push(m[l]);return f.length>0?f:void 0}async function s(g,u){let b=`by${g.documentKey.charAt(0).toUpperCase()}${g.documentKey.slice(1)}`,m=g.repo.get[b];if(typeof m=="function")try{let l=await m(u);if(l)return l}catch{}return (await g.repo.query.by({where:[[g.documentKey,"==",u]],limit:1}))[0]??null}async function a(g,u){let b=g.params||{},m=r(b.repoName,u);if(!m)return;let f=[],l;try{let x=g.query??{},y=Math.min(Number(x.pageSize)||m.pageSize,100),w=x.cursor,R=x.direction?.toLowerCase()==="prev"?"prev":"next",C=x.orderBy,P=x.orderDir?.toLowerCase()==="desc"?"desc":"asc",T=x.select,S=T?T.split(",").map(z=>z.trim()):void 0,k;m.allowedIncludes&&x.includes&&(k=(typeof x.includes=="string"?x.includes.split(",").map(I=>I.trim()):Array.isArray(x.includes)?x.includes:[]).filter(I=>typeof I=="string"&&m.allowedIncludes.includes(I)),k?.length===0&&(k=void 0));let O=No(x,m.filterableFields);f=O.map(z=>({field:z.field,op:z.op,value:String(z.value??"")})),C&&(l={field:C,dir:P});let A={pageSize:y,direction:R};if(w)try{let z=typeof w=="string"?JSON.parse(w):w;A.cursor=await nr(m,z);}catch{}C&&(A.orderBy=[{field:C,direction:P}]),O.length>0&&(A.where=O.map(z=>[z.field,z.op,z.value])),S&&(A.select=S),k&&(A.include=k);let $=await m.repo.query.paginate(A),_={items:$.data,hasNextPage:$.hasNextPage,hasPrevPage:$.hasPrevPage,nextCursor:mt($.nextCursor),prevCursor:mt($.prevCursor)};Ne(u,_,{pageSize:y,hasMore:$.hasNextPage});}catch(x){Vt(u,x,{ref:m.repo.ref,path:m.path,isGroup:!!m.isGroup,filters:f,sort:l},"Failed to fetch documents",n);}}async function c(g,u){let b=g.params||{},m=r(b.repoName,u);if(!m)return;let f=[],l;try{let x=g.body??{},y=Math.min(x.pageSize||m.pageSize,100),w=x.direction==="prev"?"prev":"next";x.where&&(f=x.where.map(T=>({field:String(T[0]),op:T[1],value:String(T[2]??"")}))),x.orderBy&&x.orderBy[0]&&(l={field:x.orderBy[0].field,dir:x.orderBy[0].direction==="desc"?"desc":"asc"});let R={pageSize:y,direction:w};if(x.cursor)try{let T=typeof x.cursor=="string"?JSON.parse(x.cursor):x.cursor;R.cursor=await nr(m,T);}catch{}if(m.allowedIncludes&&x.includes&&x.includes.length>0){let T=x.includes.filter(S=>typeof S=="string"?m.allowedIncludes.includes(S):typeof S=="object"&&S!==null&&"relation"in S&&typeof S.relation=="string"?m.allowedIncludes.includes(S.relation):!1);T.length>0&&(R.include=T);}if(x.where&&x.where.length>0){if(m.filterableFields){let T=new Set(m.filterableFields),S=x.where.filter(k=>!T.has(k[0]));if(S.length>0){Q(u,`Fields not filterable: ${S.map(k=>k[0]).join(", ")}`,400);return}}R.where=x.where;}if(x.orWhere&&x.orWhere.length>0){if(m.filterableFields){let T=new Set(m.filterableFields),S=x.orWhere.filter(k=>!T.has(k[0]));if(S.length>0){Q(u,`Fields not filterable: ${S.map(k=>k[0]).join(", ")}`,400);return}}R.orWhere=x.orWhere;}if(x.orWhereGroups&&x.orWhereGroups.length>0){if(m.filterableFields){let T=new Set(m.filterableFields);for(let S of x.orWhereGroups){let k=S.filter(O=>!T.has(O[0]));if(k.length>0){Q(u,`Fields not filterable: ${k.map(O=>O[0]).join(", ")}`,400);return}}}R.orWhereGroups=x.orWhereGroups;}x.orderBy&&x.orderBy.length>0&&(R.orderBy=x.orderBy),x.select&&x.select.length>0&&(R.select=x.select);let C=await m.repo.query.paginate(R),P={items:C.data,hasNextPage:C.hasNextPage,hasPrevPage:C.hasPrevPage,nextCursor:mt(C.nextCursor),prevCursor:mt(C.prevCursor)};Ne(u,P,{pageSize:y,hasMore:C.hasNextPage});}catch(x){Vt(u,x,{ref:m.repo.ref,path:m.path,isGroup:!!m.isGroup,filters:f,sort:l},"Failed to query documents",n);}}async function i(g,u){let b=g.params||{},m=r(b.repoName,u);if(!m)return;let f=b.id;if(!f){Q(u,"Document ID required",400);return}try{let l=await s(m,f);if(!l){Q(u,"Document not found",404);return}Ne(u,l);}catch(l){Vt(u,l,{ref:m.repo.ref,path:m.path,isGroup:!!m.isGroup,filters:[{field:m.documentKey,op:"==",value:f}]},"Failed to fetch document",n);}}async function p(g,u){let b=g.params||{},m=r(b.repoName,u);if(m)try{let f=g.body??{},l=er(m.schema,f,m.createFields,!1,m.systemKeys);if(!l.success){Q(u,l.error,400);return}if(m.validate){let y=await m.validate(l.data,"create");if(y){Q(u,y,400);return}}let x;if(m.isGroup&&m.parentKeys&&m.parentKeys.length>0){let y={...l.data};m.createdKey&&(y[m.createdKey]=new Date);let w=m.parentKeys.filter(P=>!y[P]);if(w.length>0){Q(u,`Missing parent key(s) for subcollection create: ${w.join(", ")}`,400);return}let R=m.parentKeys.map(P=>y[P]),C=y[m.documentKey]||Do();x=await m.repo.set(...R,C,y);}else x=await m.repo.create(l.data);Ne(u,x,void 0,201);}catch(f){let l=n&&f instanceof Error?f.message:"Failed to create document";Q(u,l,500);}}async function d(g,u,b){let m=g.params||{},f=r(m.repoName,u);if(!f)return;let l=m.id;if(!l){Q(u,"Document ID required",400);return}try{let x=g.body??{},y=er(f.schema,x,f.mutableFields,b,f.systemKeys);if(!y.success){Q(u,y.error,400);return}if(f.validate){let P=await f.validate(y.data,"update");if(P){Q(u,P,400);return}}let w=await s(f,l),R=(w&&o(w,f.pathKey))??[l],C=await f.repo.update(...R,y.data);Ne(u,C);}catch(x){let y=n&&x instanceof Error?x.message:"Failed to update document";Q(u,y,500);}}async function h(g,u){let b=g.params||{},m=r(b.repoName,u);if(!m)return;if(!m.allowDelete){Q(u,"Delete not allowed for this repository",403);return}let f=b.id;if(!f){Q(u,"Document ID required",400);return}try{let l=await s(m,f),x=(l&&o(l,m.pathKey))??[f];await m.repo.delete(...x),Ne(u,{deleted:!0});}catch(l){let x=n&&l instanceof Error?l.message:"Failed to delete document";Q(u,x,500);}}function v(g,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:a,handleQuery:c,handleGet:i,handleCreate:p,handleUpdate:d,handleDelete:h,handleOptions:v}}function Gt(e){try{return zod.z.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 re(e){return {$ref:`#/components/schemas/${e}`}}function X(e){return {description:e,content:{"application/json":{schema:re("ErrorResponse")}}}}function We(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function or(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 _o(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 jo(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 Fo(){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 Mo(e,t,n,r,o){let s={},a=e.name,c=`${t}/${e.name}`,i=`${c}/{${e.documentKey}}`,p={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};s[c]={get:{operationId:`list${ve(e.name)}`,summary:`List ${e.name} (paginated)`,tags:[a],parameters:[..._o(e),...jo(e)],responses:{200:or(re(n)),500:X("Internal server error")}},post:{operationId:`create${ve(e.name)}`,summary:`Create a ${ie(e.name)}`,tags:[a],requestBody:{required:true,content:{"application/json":{schema:re(r??n)}}},responses:{201:We("Document created",re(n)),400:X("Validation error"),500:X("Internal server error")}}},s[`${c}/query`]={post:{operationId:`query${ve(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[a],requestBody:{required:true,content:{"application/json":{schema:re("QueryRequestBody")}}},responses:{200:or(re(n)),400:X("Invalid query"),500:X("Internal server error")}}};let d={};return d.get={operationId:`get${ve(ie(e.name))}`,summary:`Get a single ${ie(e.name)}`,tags:[a],parameters:[p],responses:{200:We("Document found",re(n)),404:X("Document not found"),500:X("Internal server error")}},d.put={operationId:`update${ve(ie(e.name))}`,summary:`Update a ${ie(e.name)} (full replace)`,tags:[a],parameters:[p],requestBody:{required:true,content:{"application/json":{schema:re(o??n)}}},responses:{200:We("Document updated",re(n)),400:X("Validation error"),404:X("Document not found"),500:X("Internal server error")}},d.patch={operationId:`patch${ve(ie(e.name))}`,summary:`Partially update a ${ie(e.name)}`,tags:[a],parameters:[p],requestBody:{required:true,content:{"application/json":{schema:{allOf:[re(o??n)],description:"All fields are optional for partial updates"}}}},responses:{200:We("Document patched",re(n)),400:X("Validation error"),404:X("Document not found"),500:X("Internal server error")}},e.allowDelete&&(d.delete={operationId:`delete${ve(ie(e.name))}`,summary:`Delete a ${ie(e.name)}`,tags:[a],parameters:[p],responses:{200:We("Document deleted",{type:"object",properties:{id:{type:"string"}}}),404:X("Document not found"),500:X("Internal server error")}}),s[i]=d,s}function Jt(e,t,n={}){let{title:r="CRUD API",version:o="1.0.0",description:s,servers:a,auth:c=false}=n,i=t==="/"?"":t.replace(/\/$/,""),p={},d={},h=[];p.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string"}},required:["success","error"]},p.QueryRequestBody=Fo();for(let[b,m]of Object.entries(e)){let f=ve(ie(b)),l=`${f}Create`,x=`${f}Update`;p[f]=Gt(m.schema);let y=S=>{let k=S&&S.length>0?S:Object.keys(m.schema.shape),O={};for(let A of k){let $=A.split(".")[0];$&&m.schema.shape[$]&&!m.systemKeys.includes($)&&(O[$]=m.schema.shape[$]);}return O},w=null,R=y(m.createFields);Object.keys(R).length>0&&(p[l]=Gt(zod.z.object(R)),w=l);let C=null,P=y(m.mutableFields);Object.keys(P).length>0&&(p[x]=Gt(zod.z.object(P)),C=x);let T=Mo(m,i,f,w,C);Object.assign(d,T),h.push({name:b,description:`Operations on ${b} (collection: ${m.path})`});}let v={},g;return c==="basic"?(v.basicAuth={type:"http",scheme:"basic"},g=[{basicAuth:[]}]):c==="bearer"&&(v.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},g=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:r,version:o,...s?{description:s}:{}},...a&&a.length>0?{servers:a}:{},paths:d,components:{schemas:p,...Object.keys(v).length>0?{securitySchemes:v}:{}},...g?{security:g}:{},tags:h}}function ve(e){return e.charAt(0).toUpperCase()+e.slice(1)}function ie(e){return e.endsWith("ies")?e.slice(0,-3)+"y":e.endsWith("ses")||e.endsWith("xes")||e.endsWith("zes")?e.slice(0,-2):e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e}function zo(e,t){return `<!DOCTYPE html>
1136
1136
  <html lang="en">
1137
1137
  <head>
1138
1138
  <meta charset="utf-8" />