@lpdjs/firestore-repo-service 2.1.10 → 2.1.11

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 zod=require('zod'),jsxRuntime=require('hono/jsx/jsx-runtime'),server=require('hono/jsx/dom/server');function Bt(e,t){let n=[];for(let s=0;s<e.length;s+=t)n.push(e.slice(s,s+t));return n}function pe(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 Te(e){let[,t,n]=e;return (t==="in"||t==="array-contains-any")&&Array.isArray(n)&&n.length>30}function Xe(e){let[t,n,s]=e;return Te(e)?Bt(s,30).map(o=>[t,n,o]):[e]}function be(e,t){let n=e;for(let[s,r,o]of t)n=n.where(String(s),r,o);return n}async function Ye(e){let t=await Promise.all(e.map(r=>r.get())),n=new Map;t.forEach(r=>{r.docs.forEach(o=>{n.has(o.id)||n.set(o.id,o);});});let s=t[0];if(!s)throw new Error("No snapshots returned");return {...s,docs:Array.from(n.values()),size:n.size,empty:n.size===0}}async function se(e,t){let n=t.orWhere&&t.orWhere.length>0,s=t.orWhereGroups&&t.orWhereGroups.length>0;if(!n&&!s){if(!t.where||t.where.length===0)return pe(e,t).get();if(!t.where.some(Te)){let m=be(e,t.where);return m=pe(m,t),m.get()}let c=t.where.map(Xe),u=Se(c).map(m=>{let l=be(e,m);return l=pe(l,t),l});return Ye(u)}let r=t.where??[],o=[...t.orWhere?.map(d=>[d])??[],...t.orWhereGroups??[]],a=[];for(let d of o){let c=[...r,...d];if(c.some(Te)){let u=c.map(Xe),l=Se(u).map(p=>{let y=be(e,p);return y=pe(y,t),y});a.push(...l);}else {let u=be(e,c);u=pe(u,t),a.push(u);}}return Ye(a)}function Se(e){if(e.length===0)return [[]];let t=e[0];if(e.length===1&&t)return t.map(o=>[o]);if(!t)return [[]];let n=e.slice(1),s=Se(n),r=[];for(let o of t)for(let a of s)r.push([o,...a]);return r}function et(e,t){let n=[];for(let s=0;s<e.length;s+=t)n.push(e.slice(s,s+t));return n}function H(e){return e.charAt(0).toUpperCase()+e.slice(1)}function X(e,t){return t.where&&t.where.forEach(([n,s,r])=>{e=e.where(String(n),s,r);}),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 ve(e,t){let n={...t,limit:t.pageSize+1};t.cursor&&(t.direction==="prev"?n.endBefore=t.cursor:n.startAfter=t.cursor);let r=(await se(e,n)).docs,o=r.length>t.pageSize,a=o?r.slice(0,t.pageSize):r,d=a.map(i=>({...i.data(),docId:i.id})),c=t.direction==="prev";return {data:d,nextCursor:c?a.length>0?a[a.length-1]:void 0:o?a[a.length-1]:void 0,prevCursor:c?o?a[0]:void 0:a[0],hasNextPage:c?!!t.cursor:o,hasPrevPage:c?o:!!t.cursor,pageSize:d.length}}async function*Ce(e,t){let n,s=true;for(;s;){let r=await ve(e,{...t,cursor:n,direction:"next"});yield r,s=r.hasNextPage,n=r.nextCursor;}}function tt(e){return {count:async(t={})=>{let n=e;return n=X(n,t),(await n.count().get()).data().count},sum:async(t,n={})=>{let s=e;s=X(s,n);let r=await s.get(),o=0;return r.forEach(a=>{let d=a.data()[t];typeof d=="number"&&(o+=d);}),o},average:async(t,n={})=>{let s=e;s=X(s,n);let r=await s.get();if(r.empty)return null;let o=0,a=0;return r.forEach(d=>{let c=d.data()[t];typeof c=="number"&&(o+=c,a++);}),a>0?o/a:null}}}function nt(e,t,n,s,r,o){let a=()=>new Date;return {create:()=>{let d=e.batch();return {batch:d,set:(...c)=>{let i=c[c.length-1],u=typeof i=="object"&&i!==null&&"merge"in i,m=u?c[c.length-2]:c[c.length-1],l=u?c.slice(0,-2):c.slice(0,-1),p=u?i:{merge:true},y=t(...l),h={...m},f=l[l.length-1];n&&f&&(h[n]=f),s&&(h[s]=y.path),r&&(h[r]=a()),o&&(h[o]=a()),d.set(y,h,p);},update:(...c)=>{let i=c.pop(),m=t(...c),l={...i};o&&(l[o]=a()),d.update(m,l);},delete:(...c)=>{let i=t(...c);d.delete(i);},commit:async()=>{await d.commit();}}}}}function rt(e,t,n){let s=()=>new Date;return {set:async r=>{let o=e.bulkWriter(),a=0;for(let d of r){if(!d)continue;let{docRef:c,data:i,merge:u=true}=d,m={...i};t&&(m[t]=s()),n&&(m[n]=s()),o.set(c,m,{merge:u}),a++,a>=500&&(await o.flush(),a=0);}await o.close();},update:async r=>{let o=e.bulkWriter(),a=0;for(let d of r){if(!d)continue;let{docRef:c,data:i}=d,u={...i};n&&(u[n]=s()),o.update(c,u),a++,a>=500&&(await o.flush(),a=0);}await o.close();},delete:async r=>{let o=e.bulkWriter(),a=0;for(let d of r)d&&(o.delete(d),a++,a>=500&&(await o.flush(),a=0));await o.close();}}}function st(e,t,n,s,r,o){let a=()=>new Date;return {create:async m=>{if(!e)throw new Error("Cannot use create() on collection groups. Use set() with a specific document ID instead.");let l,p,y={...m};if(r&&(y[r]=a()),o&&(y[o]=a()),m[n]){p=m[n],l=e.doc(p);let f=s?{...y,[s]:l.path}:y;await l.set(f);}else {l=await e.add(y),p=l.id;let f={[n]:p};s&&(f[s]=l.path),await l.update(f);}return (await l.get()).data()},set:async(...m)=>{let l=m[m.length-1],p=typeof l=="object"&&l!==null&&"merge"in l,y=p?m[m.length-2]:m[m.length-1],h=p?m.slice(0,-2):m.slice(0,-1),f=p?l:{merge:true},b={...y};o&&(b[o]=a());let v=t(...h),g=h[h.length-1];return n&&g!=null&&(b[n]=g),s&&(b[s]=v.path),await v.set(b,f),(await v.get()).data()},update:async(...m)=>{let l=m.pop(),p=m,y={...l};o&&(y[o]=a());let h=t(...p);return await h.update(y),(await h.get()).data()},delete:async(...m)=>{await t(...m).delete();}}}function ot(e,t,n,s,r){let o={};return o.byList=async(a,d,c="in",i={})=>{if(d.length===0)return [];let u=[],m=et(d,30);for(let l of m){let p=e;p=p.where(a,c,l),i.select&&i.select.length>0&&(p=p.select(...i.select.map(h=>String(h)))),(await p.get()).forEach(h=>{let f=h.data();u.push(i.returnDoc?{data:f,doc:h}:f);});}return u},t.forEach(a=>{let d=`by${H(String(a))}`;o[d]=async(c,i={})=>{let u=typeof i=="boolean"?{returnDoc:i}:i;if(String(a)===r){let f=await s(c).get();if(!f.exists)return null;let b=f.data();return u.returnDoc?{data:b,doc:f}:b}let m=e;m=m.where(String(a),"==",c).limit(1),u.select&&u.select.length>0&&(m=m.select(...u.select.map(h=>String(h))));let l=await m.get();if(l.empty)return null;let p=l.docs[0];if(!p)return null;let y=p.data();return u.returnDoc?{data:y,doc:p}:y};}),o}function at(e,t,n,s){let r={},o=async(a,d)=>{if(!n||!s||d.length===0)return a;let c=d.map(i=>typeof i=="string"?{key:i}:{key:i.relation,select:i.select});return Promise.all(a.map(async i=>{let u=await Promise.all(c.map(async({key:l,select:p})=>{let y=n[l];if(!y)return [l,void 0];let h=s[y.repo];if(!h)return [l,void 0];let f=i[l];if(f==null)return [l,y.type==="one"?null:[]];let b=p?{select:p}:void 0;try{if(y.type==="one"){let v=`by${H(y.key)}`,g=typeof h.get?.[v]=="function"?await h.get[v](f,b):null;return [l,g]}else {let v=`by${H(y.key)}`,g=typeof h.query?.[v]=="function"?await h.query[v](f,b):[];return [l,g]}}catch(v){return console.error(`[include] Error populating "${l}":`,v),[l,y.type==="one"?null:[]]}})),m={};for(let[l,p]of u)l!==void 0&&(m[l]=p);return {...i,populated:m}}))};return t.forEach(a=>{let d=`by${H(a)}`;r[d]=async(c,i={})=>{let u={...i,where:[[a,"==",c],...i.where??[]]};return (await se(e,u)).docs.map(l=>l.data())};}),r.by=async a=>(await se(e,a)).docs.map(c=>c.data()),r.getAll=async(a={})=>(await se(e,a)).docs.map(c=>c.data()),r.onSnapshot=(a,d,c)=>X(e,a).onSnapshot(u=>{d(u.docs.map(m=>m.data()));},c),r.paginate=async a=>{let{include:d,...c}=a,i=await ve(e,c);if(d&&d.length>0){let u=await o(i.data,d);return {...i,data:u}}return i},r.paginateAll=async function*(a){let{include:d,...c}=a;for await(let i of Ce(e,c))if(d&&d.length>0){let u=await o(i.data,d);yield {...i,data:u};}else yield i;},r}function it(e,t){return {populate:async(n,s)=>{if(!e.relationalKeys)return {...n,populated:{}};let r,o={};if(typeof s=="object"&&!Array.isArray(s))if("relation"in s){let c=s;r=[c.relation],c.select&&(o[c.relation]=c.select);}else if("relations"in s){let c=s;r=Array.isArray(c.relations)?c.relations:[c.relations],o=c.select??{};}else r=[];else r=Array.isArray(s)?s:[s];let a=await Promise.all(r.map(async c=>{let i=e.relationalKeys?.[c];if(!i)return console.warn(`[populate] Relation "${c}" not found in config`),[c,void 0];let u=t[i.repo];if(!u)return console.warn(`[populate] Repository "${i.repo}" not found in mapping`),[c,void 0];let m=n[c];if(m==null)return [c,i.type==="one"?null:[]];let l=o[c],p=l?{select:l}:void 0;try{if(i.type==="one"){let y=`by${H(i.key)}`,h=typeof u.get?.[y]=="function"?await u.get[y](m,p):null;return [c,h]}else {let y=`by${H(i.key)}`,h=typeof u.query?.[y]=="function"?await u.query[y](m,p):[];return [c,h]}}catch(y){return console.error(`[populate] Error populating "${c}":`,y),[c,i.type==="one"?null:[]]}})),d={};for(let[c,i]of a)i!==void 0&&(d[c]=i);return {...n,populated:d}}}}function lt(e,t){return {run:async n=>e.runTransaction(async s=>n({get:async(...o)=>{let a=t(...o),d=await s.get(a);return d.exists?{...d.data(),docId:d.id}:null},set:(...o)=>{let a=o[o.length-1],d=typeof a=="object"&&a!==null&&"merge"in a,c=d?o[o.length-2]:o[o.length-1],i=d?o.slice(0,-2):o.slice(0,-1),u=d?a:{merge:true},m=t(...i);s.set(m,c,u);},update:(...o)=>{let a=o[o.length-1],d=o.slice(0,-1),c=t(...d);s.update(c,a);},delete:(...o)=>{let a=t(...o);s.delete(a);},raw:s}))}}function Qt(e){if(typeof e!="function")return [];let n=e.toString().match(/^\s*(?:function\s*\w*\s*)?\(([^)]*)\)/);if(!n?.[1])return [];let s=n[1].split(",").map(r=>r.trim().replace(/\s*[:=].*$/,"").trim()).filter(Boolean);return s.length<=2?[]:s.slice(1,-1)}function Oe(e,t,n={}){let s=t.isGroup?e.collectionGroup(t.path):e.collection(t.path),r=t.isGroup?null:e.collection(t.path),o=(...y)=>t.refCb(e,...y),a=ot(s,t.foreignKeys,r,o,t.documentKey),d=at(s,t.queryKeys,t.relationalKeys,n),c=tt(s),i=st(r,o,t.documentKey,t.pathKey,t.createdKey,t.updatedKey),u=nt(e,o,t.documentKey,t.pathKey,t.createdKey,t.updatedKey),m=lt(e,o),l=rt(e,t.createdKey,t.updatedKey),p=it(t,n);return {ref:s,documentRef:o,get:a,query:d,aggregate:c,...i,batch:u,transaction:m,bulk:l,...p,schema:t.schema,relationalKeys:t.relationalKeys,_systemKeys:[t.documentKey,t.pathKey,t.createdKey,t.updatedKey].filter(y=>typeof y=="string"),_pathKey:t.pathKey??null,_isGroup:!!t.isGroup,_parentKeys:t.isGroup?Qt(t.refCb):[],_createdKey:t.createdKey??null}}var qt={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 Z(e){let t=e,n=t._zod?.def?.type;if(n)return qt[n]??`Zod${n.charAt(0).toUpperCase()}${n.slice(1)}`;let s=t._def?.typeName;return s||""}function Q(e){let t=e;if(t._zod?.def?.innerType)return t._zod.def.innerType;if(t._def?.innerType)return t._def.innerType}function ct(e){let t=e;if(t._zod?.def?.element)return t._zod.def.element;if(t._def?.type)return t._def.type}function dt(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 fe(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 Ae(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 $e(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 ut(e){let t=e;return Array.isArray(t._zod?.def?.values)?t._zod.def.values[0]:t._def?.value}function pt(e){let t=e,n=[],s=t._zod?.def?.checks;if(Array.isArray(s)){for(let o of s)o.format&&n.push(o.format);if(n.length>0)return n}let r=t._def?.checks;if(Array.isArray(r))for(let o of r)o.kind&&n.push(o.kind);return n}function Gt(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/^\s/,"").replace(/^./,t=>t.toUpperCase())}function ft(e){let t=e,n=true,s=false,r;for(;;){let o=Z(t);if(o==="ZodOptional")n=false,t=Q(t);else if(o==="ZodNullable")n=false,s=true,t=Q(t);else if(o==="ZodDefault")n=false,r=dt(t),t=Q(t);else break}return {inner:t,required:n,nullable:s,defaultValue:r}}function G(e,t=""){if(Z(e)==="ZodObject"){let s=fe(e);return Object.entries(s).map(([r,o])=>yt(t?`${t}.${r}`:r,r,o))}return [yt(t||"value",t||"value",e)]}function yt(e,t,n){let{inner:s,required:r,nullable:o,defaultValue:a}=ft(n),d=Z(s),c=Gt(t.split(".").pop()??t);switch(d){case "ZodString":{let i=pt(s),u=i.includes("email"),m=i.includes("url");return {name:e,label:c,type:"text",required:r,nullable:o,defaultValue:a,hint:u?"email":m?"url":void 0}}case "ZodNumber":case "ZodBigInt":return {name:e,label:c,type:"number",required:r,nullable:o,defaultValue:a};case "ZodBoolean":return {name:e,label:c,type:"checkbox",required:r,nullable:o,defaultValue:a};case "ZodDate":case "ZodCoerce":return {name:e,label:c,type:"datetime-local",required:r,nullable:o,defaultValue:a};case "ZodEnum":{let i=Ae(s);return {name:e,label:c,type:"select",required:r,nullable:o,defaultValue:a,options:i}}case "ZodNativeEnum":{let i=$e(s),u=Object.values(i).filter(m=>typeof m=="string");return {name:e,label:c,type:"select",required:r,nullable:o,defaultValue:a,options:u}}case "ZodLiteral":{let i=String(ut(s)??"");return {name:e,label:c,type:"select",required:r,nullable:o,defaultValue:a,options:[i]}}case "ZodObject":{let i=G(s,e);return {name:e,label:c,type:"textarea",required:r,nullable:o,defaultValue:a,nested:i,hint:"JSON object"}}case "ZodArray":{let i=ct(s);if(!i)return {name:e,label:c,type:"textarea",required:r,nullable:o,defaultValue:a,hint:"JSON array"};let{inner:u}=ft(i),m=Z(u),l,p,y;switch(m){case "ZodString":l="text";break;case "ZodNumber":case "ZodBigInt":l="number";break;case "ZodBoolean":l="checkbox";break;case "ZodDate":l="datetime-local";break;case "ZodEnum":l="select",p=Ae(u);break;case "ZodNativeEnum":l="select",p=Object.values($e(u)).filter(h=>typeof h=="string");break;case "ZodObject":l="object",y=G(u);break;default:return {name:e,label:c,type:"textarea",required:r,nullable:o,defaultValue:a,hint:"JSON array"}}return {name:e,label:c,type:"textarea",required:r,nullable:o,defaultValue:a,arrayElementType:l,arrayElementOptions:p,arrayElementFields:y}}default:return {name:e,label:c,type:"textarea",required:r,nullable:o,defaultValue:a,hint:"JSON"}}}function ke(e,t=0){let n=t>0?`ml-${t*4}`:"",s=`field_${e.name.replace(/\./g,"__")}`,r=e.name,o=e.required?" required":"",a=e.defaultValue==="__null__",d=!a&&e.defaultValue!=null?String(e.defaultValue):"",c=e.nullable&&e.type!=="checkbox"?`<span class="flex items-center gap-1 shrink-0">
1
+ 'use strict';var zod=require('zod'),jsxRuntime=require('hono/jsx/jsx-runtime'),server=require('hono/jsx/dom/server');function Ht(e,t){let n=[];for(let s=0;s<e.length;s+=t)n.push(e.slice(s,s+t));return n}function pe(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 Se(e){let[,t,n]=e;return (t==="in"||t==="array-contains-any")&&Array.isArray(n)&&n.length>30}function rt(e){let[t,n,s]=e;return Se(e)?Ht(s,30).map(o=>[t,n,o]):[e]}function be(e,t){let n=e;for(let[s,r,o]of t)n=n.where(String(s),r,o);return n}async function st(e){let t=await Promise.all(e.map(r=>r.get())),n=new Map;t.forEach(r=>{r.docs.forEach(o=>{n.has(o.id)||n.set(o.id,o);});});let s=t[0];if(!s)throw new Error("No snapshots returned");return {...s,docs:Array.from(n.values()),size:n.size,empty:n.size===0}}async function se(e,t){let n=t.orWhere&&t.orWhere.length>0,s=t.orWhereGroups&&t.orWhereGroups.length>0;if(!n&&!s){if(!t.where||t.where.length===0)return pe(e,t).get();if(!t.where.some(Se)){let m=be(e,t.where);return m=pe(m,t),m.get()}let i=t.where.map(rt),u=Ce(i).map(m=>{let l=be(e,m);return l=pe(l,t),l});return st(u)}let r=t.where??[],o=[...t.orWhere?.map(d=>[d])??[],...t.orWhereGroups??[]],a=[];for(let d of o){let i=[...r,...d];if(i.some(Se)){let u=i.map(rt),l=Ce(u).map(p=>{let y=be(e,p);return y=pe(y,t),y});a.push(...l);}else {let u=be(e,i);u=pe(u,t),a.push(u);}}return st(a)}function Ce(e){if(e.length===0)return [[]];let t=e[0];if(e.length===1&&t)return t.map(o=>[o]);if(!t)return [[]];let n=e.slice(1),s=Ce(n),r=[];for(let o of t)for(let a of s)r.push([o,...a]);return r}function ot(e,t){let n=[];for(let s=0;s<e.length;s+=t)n.push(e.slice(s,s+t));return n}function H(e){return e.charAt(0).toUpperCase()+e.slice(1)}function X(e,t){return t.where&&t.where.forEach(([n,s,r])=>{e=e.where(String(n),s,r);}),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 xe(e,t){let n={...t,limit:t.pageSize+1};t.cursor&&(t.direction==="prev"?n.endBefore=t.cursor:n.startAfter=t.cursor);let r=(await se(e,n)).docs,o=r.length>t.pageSize,a=o?r.slice(0,t.pageSize):r,d=a.map(c=>({...c.data(),docId:c.id})),i=t.direction==="prev";return {data:d,nextCursor:i?a.length>0?a[a.length-1]:void 0:o?a[a.length-1]:void 0,prevCursor:i?o?a[0]:void 0:a[0],hasNextPage:i?!!t.cursor:o,hasPrevPage:i?o:!!t.cursor,pageSize:d.length}}async function*Ae(e,t){let n,s=true;for(;s;){let r=await xe(e,{...t,cursor:n,direction:"next"});yield r,s=r.hasNextPage,n=r.nextCursor;}}function at(e){return {count:async(t={})=>{let n=e;return n=X(n,t),(await n.count().get()).data().count},sum:async(t,n={})=>{let s=e;s=X(s,n);let r=await s.get(),o=0;return r.forEach(a=>{let d=a.data()[t];typeof d=="number"&&(o+=d);}),o},average:async(t,n={})=>{let s=e;s=X(s,n);let r=await s.get();if(r.empty)return null;let o=0,a=0;return r.forEach(d=>{let i=d.data()[t];typeof i=="number"&&(o+=i,a++);}),a>0?o/a:null}}}function it(e,t,n,s,r,o){let a=()=>new Date;return {create:()=>{let d=e.batch();return {batch:d,set:(...i)=>{let c=i[i.length-1],u=typeof c=="object"&&c!==null&&"merge"in c,m=u?i[i.length-2]:i[i.length-1],l=u?i.slice(0,-2):i.slice(0,-1),p=u?c:{merge:true},y=t(...l),h={...m},f=l[l.length-1];n&&f&&(h[n]=f),s&&(h[s]=y.path),r&&(h[r]=a()),o&&(h[o]=a()),d.set(y,h,p);},update:(...i)=>{let c=i.pop(),m=t(...i),l={...c};o&&(l[o]=a()),d.update(m,l);},delete:(...i)=>{let c=t(...i);d.delete(c);},commit:async()=>{await d.commit();}}}}}function lt(e,t,n){let s=()=>new Date;return {set:async r=>{let o=e.bulkWriter(),a=0;for(let d of r){if(!d)continue;let{docRef:i,data:c,merge:u=true}=d,m={...c};t&&(m[t]=s()),n&&(m[n]=s()),o.set(i,m,{merge:u}),a++,a>=500&&(await o.flush(),a=0);}await o.close();},update:async r=>{let o=e.bulkWriter(),a=0;for(let d of r){if(!d)continue;let{docRef:i,data:c}=d,u={...c};n&&(u[n]=s()),o.update(i,u),a++,a>=500&&(await o.flush(),a=0);}await o.close();},delete:async r=>{let o=e.bulkWriter(),a=0;for(let d of r)d&&(o.delete(d),a++,a>=500&&(await o.flush(),a=0));await o.close();}}}function ct(e,t,n,s,r,o){let a=()=>new Date;return {create:async m=>{if(!e)throw new Error("Cannot use create() on collection groups. Use set() with a specific document ID instead.");let l,p,y={...m};if(r&&(y[r]=a()),o&&(y[o]=a()),m[n]){p=m[n],l=e.doc(p);let f=s?{...y,[s]:l.path}:y;await l.set(f);}else {l=await e.add(y),p=l.id;let f={[n]:p};s&&(f[s]=l.path),await l.update(f);}return (await l.get()).data()},set:async(...m)=>{let l=m[m.length-1],p=typeof l=="object"&&l!==null&&"merge"in l,y=p?m[m.length-2]:m[m.length-1],h=p?m.slice(0,-2):m.slice(0,-1),f=p?l:{merge:true},b={...y};o&&(b[o]=a());let x=t(...h),g=h[h.length-1];return n&&g!=null&&(b[n]=g),s&&(b[s]=x.path),await x.set(b,f),(await x.get()).data()},update:async(...m)=>{let l=m.pop(),p=m,y={...l};o&&(y[o]=a());let h=t(...p);return await h.update(y),(await h.get()).data()},delete:async(...m)=>{await t(...m).delete();}}}function dt(e,t,n,s,r){let o={};return o.byList=async(a,d,i="in",c={})=>{if(d.length===0)return [];let u=[],m=ot(d,30);for(let l of m){let p=e;p=p.where(a,i,l),c.select&&c.select.length>0&&(p=p.select(...c.select.map(h=>String(h)))),(await p.get()).forEach(h=>{let f=h.data();u.push(c.returnDoc?{data:f,doc:h}:f);});}return u},t.forEach(a=>{let d=`by${H(String(a))}`;o[d]=async(i,c={})=>{let u=typeof c=="boolean"?{returnDoc:c}:c;if(String(a)===r){let f=await s(i).get();if(!f.exists)return null;let b=f.data();return u.returnDoc?{data:b,doc:f}:b}let m=e;m=m.where(String(a),"==",i).limit(1),u.select&&u.select.length>0&&(m=m.select(...u.select.map(h=>String(h))));let l=await m.get();if(l.empty)return null;let p=l.docs[0];if(!p)return null;let y=p.data();return u.returnDoc?{data:y,doc:p}:y};}),o}function ut(e,t,n,s){let r={},o=async(a,d)=>{if(!n||!s||d.length===0)return a;let i=d.map(c=>typeof c=="string"?{key:c}:{key:c.relation,select:c.select});return Promise.all(a.map(async c=>{let u=await Promise.all(i.map(async({key:l,select:p})=>{let y=n[l];if(!y)return [l,void 0];let h=s[y.repo];if(!h)return [l,void 0];let f=c[l];if(f==null)return [l,y.type==="one"?null:[]];let b=p?{select:p}:void 0;try{if(y.type==="one"){let x=`by${H(y.key)}`,g=typeof h.get?.[x]=="function"?await h.get[x](f,b):null;return [l,g]}else {let x=`by${H(y.key)}`,g=typeof h.query?.[x]=="function"?await h.query[x](f,b):[];return [l,g]}}catch(x){return console.error(`[include] Error populating "${l}":`,x),[l,y.type==="one"?null:[]]}})),m={};for(let[l,p]of u)l!==void 0&&(m[l]=p);return {...c,populated:m}}))};return t.forEach(a=>{let d=`by${H(a)}`;r[d]=async(i,c={})=>{let u={...c,where:[[a,"==",i],...c.where??[]]};return (await se(e,u)).docs.map(l=>l.data())};}),r.by=async a=>(await se(e,a)).docs.map(i=>i.data()),r.getAll=async(a={})=>(await se(e,a)).docs.map(i=>i.data()),r.onSnapshot=(a,d,i)=>X(e,a).onSnapshot(u=>{d(u.docs.map(m=>m.data()));},i),r.paginate=async a=>{let{include:d,...i}=a,c=await xe(e,i);if(d&&d.length>0){let u=await o(c.data,d);return {...c,data:u}}return c},r.paginateAll=async function*(a){let{include:d,...i}=a;for await(let c of Ae(e,i))if(d&&d.length>0){let u=await o(c.data,d);yield {...c,data:u};}else yield c;},r}function pt(e,t){return {populate:async(n,s)=>{if(!e.relationalKeys)return {...n,populated:{}};let r,o={};if(typeof s=="object"&&!Array.isArray(s))if("relation"in s){let i=s;r=[i.relation],i.select&&(o[i.relation]=i.select);}else if("relations"in s){let i=s;r=Array.isArray(i.relations)?i.relations:[i.relations],o=i.select??{};}else r=[];else r=Array.isArray(s)?s:[s];let a=await Promise.all(r.map(async i=>{let c=e.relationalKeys?.[i];if(!c)return console.warn(`[populate] Relation "${i}" not found in config`),[i,void 0];let u=t[c.repo];if(!u)return console.warn(`[populate] Repository "${c.repo}" not found in mapping`),[i,void 0];let m=n[i];if(m==null)return [i,c.type==="one"?null:[]];let l=o[i],p=l?{select:l}:void 0;try{if(c.type==="one"){let y=`by${H(c.key)}`,h=typeof u.get?.[y]=="function"?await u.get[y](m,p):null;return [i,h]}else {let y=`by${H(c.key)}`,h=typeof u.query?.[y]=="function"?await u.query[y](m,p):[];return [i,h]}}catch(y){return console.error(`[populate] Error populating "${i}":`,y),[i,c.type==="one"?null:[]]}})),d={};for(let[i,c]of a)c!==void 0&&(d[i]=c);return {...n,populated:d}}}}function ft(e,t){return {run:async n=>e.runTransaction(async s=>n({get:async(...o)=>{let a=t(...o),d=await s.get(a);return d.exists?{...d.data(),docId:d.id}:null},set:(...o)=>{let a=o[o.length-1],d=typeof a=="object"&&a!==null&&"merge"in a,i=d?o[o.length-2]:o[o.length-1],c=d?o.slice(0,-2):o.slice(0,-1),u=d?a:{merge:true},m=t(...c);s.set(m,i,u);},update:(...o)=>{let a=o[o.length-1],d=o.slice(0,-1),i=t(...d);s.update(i,a);},delete:(...o)=>{let a=t(...o);s.delete(a);},raw:s}))}}function Vt(e){if(typeof e!="function")return [];let n=e.toString().match(/^\s*(?:function\s*\w*\s*)?\(([^)]*)\)/);if(!n?.[1])return [];let s=n[1].split(",").map(r=>r.trim().replace(/\s*[:=].*$/,"").trim()).filter(Boolean);return s.length<=2?[]:s.slice(1,-1)}function Oe(e,t,n={}){let s=t.isGroup?e.collectionGroup(t.path):e.collection(t.path),r=t.isGroup?null:e.collection(t.path),o=(...y)=>t.refCb(e,...y),a=dt(s,t.foreignKeys,r,o,t.documentKey),d=ut(s,t.queryKeys,t.relationalKeys,n),i=at(s),c=ct(r,o,t.documentKey,t.pathKey,t.createdKey,t.updatedKey),u=it(e,o,t.documentKey,t.pathKey,t.createdKey,t.updatedKey),m=ft(e,o),l=lt(e,t.createdKey,t.updatedKey),p=pt(t,n);return {ref:s,documentRef:o,get:a,query:d,aggregate:i,...c,batch:u,transaction:m,bulk:l,...p,schema:t.schema,relationalKeys:t.relationalKeys,_systemKeys:[t.documentKey,t.pathKey,t.createdKey,t.updatedKey].filter(y=>typeof y=="string"),_pathKey:t.pathKey??null,_isGroup:!!t.isGroup,_parentKeys:t.isGroup?Vt(t.refCb):[],_createdKey:t.createdKey??null}}var Jt={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 Z(e){let t=e,n=t._zod?.def?.type;if(n)return Jt[n]??`Zod${n.charAt(0).toUpperCase()}${n.slice(1)}`;let s=t._def?.typeName;return s||""}function Q(e){let t=e;if(t._zod?.def?.innerType)return t._zod.def.innerType;if(t._def?.innerType)return t._def.innerType}function yt(e){let t=e;if(t._zod?.def?.element)return t._zod.def.element;if(t._def?.type)return t._def.type}function mt(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 fe(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 $e(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 ke(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 gt(e){let t=e;return Array.isArray(t._zod?.def?.values)?t._zod.def.values[0]:t._def?.value}function ht(e){let t=e,n=[],s=t._zod?.def?.checks;if(Array.isArray(s)){for(let o of s)o.format&&n.push(o.format);if(n.length>0)return n}let r=t._def?.checks;if(Array.isArray(r))for(let o of r)o.kind&&n.push(o.kind);return n}function Xt(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/^\s/,"").replace(/^./,t=>t.toUpperCase())}function bt(e){let t=e,n=true,s=false,r;for(;;){let o=Z(t);if(o==="ZodOptional")n=false,t=Q(t);else if(o==="ZodNullable")n=false,s=true,t=Q(t);else if(o==="ZodDefault")n=false,r=mt(t),t=Q(t);else break}return {inner:t,required:n,nullable:s,defaultValue:r}}function U(e,t=""){if(Z(e)==="ZodObject"){let s=fe(e);return Object.entries(s).map(([r,o])=>xt(t?`${t}.${r}`:r,r,o))}return [xt(t||"value",t||"value",e)]}function xt(e,t,n){let{inner:s,required:r,nullable:o,defaultValue:a}=bt(n),d=Z(s),i=Xt(t.split(".").pop()??t);switch(d){case "ZodString":{let c=ht(s),u=c.includes("email"),m=c.includes("url");return {name:e,label:i,type:"text",required:r,nullable:o,defaultValue:a,hint:u?"email":m?"url":void 0}}case "ZodNumber":case "ZodBigInt":return {name:e,label:i,type:"number",required:r,nullable:o,defaultValue:a};case "ZodBoolean":return {name:e,label:i,type:"checkbox",required:r,nullable:o,defaultValue:a};case "ZodDate":case "ZodCoerce":return {name:e,label:i,type:"datetime-local",required:r,nullable:o,defaultValue:a};case "ZodEnum":{let c=$e(s);return {name:e,label:i,type:"select",required:r,nullable:o,defaultValue:a,options:c}}case "ZodNativeEnum":{let c=ke(s),u=Object.values(c).filter(m=>typeof m=="string");return {name:e,label:i,type:"select",required:r,nullable:o,defaultValue:a,options:u}}case "ZodLiteral":{let c=String(gt(s)??"");return {name:e,label:i,type:"select",required:r,nullable:o,defaultValue:a,options:[c]}}case "ZodObject":{let c=U(s,e);return {name:e,label:i,type:"textarea",required:r,nullable:o,defaultValue:a,nested:c,hint:"JSON object"}}case "ZodArray":{let c=yt(s);if(!c)return {name:e,label:i,type:"textarea",required:r,nullable:o,defaultValue:a,hint:"JSON array"};let{inner:u}=bt(c),m=Z(u),l,p,y;switch(m){case "ZodString":l="text";break;case "ZodNumber":case "ZodBigInt":l="number";break;case "ZodBoolean":l="checkbox";break;case "ZodDate":l="datetime-local";break;case "ZodEnum":l="select",p=$e(u);break;case "ZodNativeEnum":l="select",p=Object.values(ke(u)).filter(h=>typeof h=="string");break;case "ZodObject":l="object",y=U(u);break;default:return {name:e,label:i,type:"textarea",required:r,nullable:o,defaultValue:a,hint:"JSON array"}}return {name:e,label:i,type:"textarea",required:r,nullable:o,defaultValue:a,arrayElementType:l,arrayElementOptions:p,arrayElementFields:y}}default:return {name:e,label:i,type:"textarea",required:r,nullable:o,defaultValue:a,hint:"JSON"}}}function Pe(e,t=0){let n=t>0?`ml-${t*4}`:"",s=`field_${e.name.replace(/\./g,"__")}`,r=e.name,o=e.required?" required":"",a=e.defaultValue==="__null__",d=!a&&e.defaultValue!=null?String(e.defaultValue):"",i=e.nullable&&e.type!=="checkbox"?`<span class="flex items-center gap-1 shrink-0">
2
2
  <input type="hidden" id="${s}__isnull" name="${r}__isnull" value="${a?"1":""}">
3
3
  <label class="flex items-center gap-1 cursor-pointer select-none text-xs text-base-content/40 hover:text-base-content/70 border border-base-300 rounded px-2 py-1">
4
4
  <input type="checkbox" class="checkbox checkbox-xs" ${a?"checked":""}
@@ -10,7 +10,7 @@
10
10
  })(this)">
11
11
  <span>null</span>
12
12
  </label>
13
- </span>`:"",i;switch(e.type){case "checkbox":if(e.nullable){let u=a?"__null__":d==="true"?"true":d==="false"?"false":"__null__";return `
13
+ </span>`:"",c;switch(e.type){case "checkbox":if(e.nullable){let u=a?"__null__":d==="true"?"true":d==="false"?"false":"__null__";return `
14
14
  <div class="form-control mb-3 ${n}">
15
15
  <label for="${s}" class="label pb-1">
16
16
  <span class="label-text font-medium">
@@ -31,21 +31,21 @@
31
31
  ${S(e.label)}${e.required?' <span class="text-error">*</span>':""}
32
32
  </span>
33
33
  </label>
34
- </div>`;case "select":i=`<select id="${s}" name="${r}"${o}${a?' disabled style="opacity:0.35"':""} class="select select-bordered select-sm w-full">
34
+ </div>`;case "select":c=`<select id="${s}" name="${r}"${o}${a?' disabled style="opacity:0.35"':""} class="select select-bordered select-sm w-full">
35
35
  ${e.required&&!e.nullable?"":'<option value="">\u2014 optional \u2014</option>'}
36
36
  ${(e.options??[]).map(u=>`<option value="${S(u)}"${d===u?" selected":""}>${S(u)}</option>`).join(`
37
37
  `)}
38
- </select>`;break;case "textarea":if(e.arrayElementType)return Ut(e,t);if(e.nested&&e.nested.length>0){let u=e.nested.map(m=>ke(m,t+1)).join(`
38
+ </select>`;break;case "textarea":if(e.arrayElementType)return Yt(e,t);if(e.nested&&e.nested.length>0){let u=e.nested.map(m=>Pe(m,t+1)).join(`
39
39
  `);return `
40
40
  <fieldset class="fieldset border border-base-300 rounded-box p-3 mb-3 ${n}">
41
41
  <legend class="fieldset-legend text-xs font-semibold text-base-content/60 px-1">
42
42
  ${S(e.label)}${e.required?' <span class="text-error">*</span>':""}
43
43
  </legend>
44
44
  ${u}
45
- </fieldset>`}i=`<textarea id="${s}" name="${r}"${o} rows="3"${a?' disabled style="opacity:0.35"':""}
45
+ </fieldset>`}c=`<textarea id="${s}" name="${r}"${o} rows="3"${a?' disabled style="opacity:0.35"':""}
46
46
  data-json
47
47
  class="textarea textarea-bordered textarea-sm w-full font-mono text-xs"
48
- placeholder="${S(e.hint??"JSON")}">${S(d)}</textarea>`;break;default:i=`<input type="${e.type}" id="${s}" name="${r}"${o}${a?' disabled style="opacity:0.35"':""}
48
+ placeholder="${S(e.hint??"JSON")}">${S(d)}</textarea>`;break;default:c=`<input type="${e.type}" id="${s}" name="${r}"${o}${a?' disabled style="opacity:0.35"':""}
49
49
  value="${S(d)}"
50
50
  class="input input-bordered input-sm w-full"${e.hint==="email"?' autocomplete="email"':e.hint==="url"?' autocomplete="url"':""}>`;}return `
51
51
  <div class="form-control mb-3 ${n}">
@@ -56,12 +56,12 @@
56
56
  </span>
57
57
  </label>
58
58
  <div class="flex items-center gap-2">
59
- <div class="flex-1 min-w-0">${i}</div>
60
- ${c}
59
+ <div class="flex-1 min-w-0">${c}</div>
60
+ ${i}
61
61
  </div>
62
- </div>`}function S(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Ut(e,t){let n=t>0?`ml-${t*4}`:"",s=`field_${e.name.replace(/\./g,"__")}`,r=e.defaultValue==="__null__",o=e.arrayElementType==="object",a=[];if(e.defaultValue!=null&&e.defaultValue!==""&&e.defaultValue!=="__null__")try{a=JSON.parse(String(e.defaultValue));}catch{}Array.isArray(a)||(a=[]);let d=o?a.map(u=>gt(e,u??{})).join(`
63
- `):a.map(u=>mt(e,u)).join(`
64
- `),c=o?gt(e,{}):mt(e,""),i=e.nullable?`<span class="flex items-center gap-1 mt-2">
62
+ </div>`}function S(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Yt(e,t){let n=t>0?`ml-${t*4}`:"",s=`field_${e.name.replace(/\./g,"__")}`,r=e.defaultValue==="__null__",o=e.arrayElementType==="object",a=[];if(e.defaultValue!=null&&e.defaultValue!==""&&e.defaultValue!=="__null__")try{a=JSON.parse(String(e.defaultValue));}catch{}Array.isArray(a)||(a=[]);let d=o?a.map(u=>Rt(e,u??{})).join(`
63
+ `):a.map(u=>vt(e,u)).join(`
64
+ `),i=o?Rt(e,{}):vt(e,""),c=e.nullable?`<span class="flex items-center gap-1 mt-2">
65
65
  <input type="hidden" id="${s}__isnull" name="${S(e.name)}__isnull" value="${r?"1":""}">
66
66
  <label class="flex items-center gap-1 cursor-pointer select-none text-xs text-base-content/40 hover:text-base-content/70 border border-base-300 rounded px-2 py-1">
67
67
  <input type="checkbox" class="checkbox checkbox-xs" ${r?"checked":""}
@@ -84,10 +84,10 @@
84
84
  <div data-frs-array-items${r?' style="opacity:0.35"':""}>
85
85
  ${d}
86
86
  </div>
87
- <template data-frs-array-tpl>${c}</template>
87
+ <template data-frs-array-tpl>${i}</template>
88
88
  <button type="button" class="btn btn-xs btn-outline mt-1" data-frs-array-add>+ Add</button>
89
- ${i}
90
- </fieldset>`}function mt(e,t){let n=t!=null?String(t):"",s;switch(e.arrayElementType){case "select":s=`<select data-frs-val class="select select-bordered select-sm flex-1">
89
+ ${c}
90
+ </fieldset>`}function vt(e,t){let n=t!=null?String(t):"",s;switch(e.arrayElementType){case "select":s=`<select data-frs-val class="select select-bordered select-sm flex-1">
91
91
  <option value="">\u2014</option>
92
92
  ${(e.arrayElementOptions??[]).map(r=>`<option value="${S(r)}"${n===r?" selected":""}>${S(r)}</option>`).join("")}
93
93
  </select>`;break;case "checkbox":s=`<label class="flex items-center gap-2 flex-1 cursor-pointer">
@@ -96,7 +96,7 @@
96
96
  </label>`;break;case "number":s=`<input type="number" data-frs-val value="${S(n)}" class="input input-bordered input-sm flex-1">`;break;case "datetime-local":s=`<input type="datetime-local" data-frs-val value="${S(n)}" class="input input-bordered input-sm flex-1">`;break;default:s=`<input type="text" data-frs-val value="${S(n)}" class="input input-bordered input-sm flex-1">`;}return `<div class="flex items-center gap-2 mb-2" data-frs-array-item>
97
97
  ${s}
98
98
  <button type="button" class="btn btn-xs btn-ghost text-error" data-frs-array-rm>&times;</button>
99
- </div>`}function gt(e,t){return `<div class="border border-base-200 rounded p-3 mb-2" data-frs-array-item>
99
+ </div>`}function Rt(e,t){return `<div class="border border-base-200 rounded p-3 mb-2" data-frs-array-item>
100
100
  <div class="flex justify-end mb-1">
101
101
  <button type="button" class="btn btn-xs btn-ghost text-error" data-frs-array-rm>&times;</button>
102
102
  </div>
@@ -125,7 +125,7 @@
125
125
  <input type="text" data-frs-key="${S(r.name)}" value="${S(a)}" class="input input-bordered input-sm w-full">
126
126
  </div>`}}).join(`
127
127
  `)}
128
- </div>`}function Y(e,t,n,s="Save"){let r=e.map(o=>ke(o)).join(`
128
+ </div>`}function Y(e,t,n,s="Save"){let r=e.map(o=>Pe(o)).join(`
129
129
  `);return `
130
130
  <form action="${S(t)}" method="${n}" novalidate data-frs-form>
131
131
  ${r}
@@ -133,7 +133,7 @@
133
133
  <button type="submit" class="btn btn-primary btn-sm">${S(s)}</button>
134
134
  <button type="button" class="btn btn-ghost btn-sm" onclick="history.back()">Cancel</button>
135
135
  </div>
136
- </form>`}function ht({val:e}){return jsxRuntime.jsx("span",{class:"text-sm text-base-content/80 font-mono tabular-nums whitespace-nowrap",children:e.toLocaleString()})}function Pe({val: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(ht,{val:e});if(typeof e=="object"&&e!==null&&typeof e.toDate=="function")return jsxRuntime.jsx(ht,{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,s)=>jsxRuntime.jsx("li",{class:"break-all",children:typeof n=="object"?JSON.stringify(n):String(n)},s)),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(([s,r])=>jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("dt",{class:"text-base-content/50 font-semibold whitespace-nowrap",children:s}),jsxRuntime.jsx("dd",{class:"break-all",children:String(r??"")})]})),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 bt=`// \u2500\u2500 Form validation + array serialization \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
136
+ </form>`}function wt({val:e}){return jsxRuntime.jsx("span",{class:"text-sm text-base-content/80 font-mono tabular-nums whitespace-nowrap",children:e.toLocaleString()})}function De({val: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(wt,{val:e});if(typeof e=="object"&&e!==null&&typeof e.toDate=="function")return jsxRuntime.jsx(wt,{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,s)=>jsxRuntime.jsx("li",{class:"break-all",children:typeof n=="object"?JSON.stringify(n):String(n)},s)),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(([s,r])=>jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("dt",{class:"text-base-content/50 font-semibold whitespace-nowrap",children:s}),jsxRuntime.jsx("dd",{class:"break-all",children:String(r??"")})]})),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 Tt=`// \u2500\u2500 Form validation + array serialization \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
137
137
  document.addEventListener("submit", function (e) {
138
138
  var form = e.target;
139
139
  if (!form.hasAttribute("data-frs-form")) return;
@@ -552,7 +552,7 @@ function initColumnReorder(table) {
552
552
  });
553
553
  });
554
554
  }
555
- `;function me(){return jsxRuntime.jsx("script",{dangerouslySetInnerHTML:{__html:bt}})}function ee(e){return "<!DOCTYPE html>"+server.renderToString(e)}var te=({opts:e,children:t})=>{let{title:n,breadcrumb:s,flash:r,basePath:o="/"}=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("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.jsx("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:o,class:"font-bold text-lg tracking-tight hover:opacity-80 transition-opacity",children:"FRS Admin"})})}),jsxRuntime.jsxs("main",{class:"px-6 py-8 w-full flex-1",children:[s&&s.length>0&&jsxRuntime.jsx("div",{class:"text-sm breadcrumbs mb-4",children:jsxRuntime.jsx("ul",{children:s.map((a,d)=>a.href?jsxRuntime.jsx("li",{children:jsxRuntime.jsx("a",{href:a.href,children:a.label})},d):jsxRuntime.jsx("li",{class:"text-base-content/60",children:a.label},d))})}),jsxRuntime.jsx("h1",{class:"text-2xl font-bold mb-6",children:n}),r&&jsxRuntime.jsxs("div",{role:"alert",class:`alert ${r.type==="success"?"alert-success":r.type==="warning"?"alert-warning":"alert-error"} mb-6`,children:[jsxRuntime.jsx("span",{class:"flex-1",children:r.message}),r.action&&jsxRuntime.jsx("a",{href:r.action.href,...r.action.external?{target:"_blank",rel:"noopener noreferrer"}:{},class:"btn btn-sm btn-outline",children:r.action.label})]}),t]}),jsxRuntime.jsx(me,{})]})]})};function Ee(e,t){return ee(jsxRuntime.jsx(te,{opts:t,children:jsxRuntime.jsx("div",{dangerouslySetInnerHTML:{__html:e}})}))}function De(e,t){return ee(jsxRuntime.jsx(te,{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 xt=[{value:"==",label:"="},{value:"!=",label:"\u2260"},{value:"in",label:"in"},{value:"not-in",label:"not in"}],Jt=[{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"}],Xt=[{value:"array-contains",label:"contains"},{value:"array-contains-any",label:"contains any"}];function Yt(e){switch(e){case "ZodNumber":case "ZodBigInt":case "ZodDate":return Jt;case "ZodBoolean":return xt;case "ZodArray":return Xt;default:return xt}}function en({col:e,active:t}){let n=t?.value??"";if(e.zodType==="ZodBoolean")return jsxRuntime.jsxs("select",{name:`fv_${e.name}`,class:"select select-sm select-bordered w-full",children:[jsxRuntime.jsx("option",{value:"",selected:n==="",children:"\u2014"}),jsxRuntime.jsx("option",{value:"true",selected:n==="true",children:"true"}),jsxRuntime.jsx("option",{value:"false",selected:n==="false",children:"false"})]});if(e.zodType==="ZodArray"){let s=t?.op==="array-contains-any";return jsxRuntime.jsx("input",{type:"text",name:`fv_${e.name}`,value:n,placeholder:s?"val1, val2, \u2026":"value",class:"input input-sm input-bordered w-full"})}return e.zodType==="ZodNumber"||e.zodType==="ZodBigInt"?jsxRuntime.jsx("input",{type:"number",name:`fv_${e.name}`,value:n,placeholder:"value",class:"input input-sm input-bordered w-full"}):e.zodType==="ZodDate"?jsxRuntime.jsx("input",{type:"datetime-local",name:`fv_${e.name}`,value:n,class:"input input-sm input-bordered w-full"}):jsxRuntime.jsx("input",{type:"text",name:`fv_${e.name}`,value:n,placeholder:"value",class:"input input-sm input-bordered w-full"})}function Ie({action:e,columnMeta:t,activeFilters:n,isGroup:s}){let r=Object.fromEntries(n.map(c=>[c.field,c])),o=n.length>0,a=n.length>=2||s&&o,d=t.filter(c=>c.zodType!=="ZodObject"&&c.zodType!=="ZodRecord");return jsxRuntime.jsxs("details",{class:"collapse collapse-arrow bg-base-100 border border-base-300 rounded-box mb-6 shadow-sm",open:o?true:void 0,children:[jsxRuntime.jsxs("summary",{class:"collapse-title text-sm font-medium py-2 min-h-0",children:["Filters",o&&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:d.map(c=>{let i=Yt(c.zodType),u=r[c.name],m=u?.op??i[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:c.name}),jsxRuntime.jsxs("div",{class:"flex gap-1.5",children:[i.length>1?jsxRuntime.jsx("select",{name:`fo_${c.name}`,class:"select select-sm select-bordered w-20 shrink-0",children:i.map(l=>jsxRuntime.jsx("option",{value:l.value,selected:l.value===m,children:l.label},l.value))}):jsxRuntime.jsx("input",{type:"hidden",name:`fo_${c.name}`,value:i[0].value}),jsxRuntime.jsx(en,{col:c,active:u})]})]},c.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"}),o&&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"})}),s?"Collection group queries require a composite index":"Multiple filters may require a composite index"]})]})]})})]})}function Fe(e,t,n,s,r,o){let a=n==="create"?`Create ${e}`:`Edit ${e} / ${s??""}`,d=n==="create"?[{label:"Repositories",href:r},{label:e,href:`${r}/${e}`},{label:"New document"}]:[{label:"Repositories",href:r},{label:e,href:`${r}/${e}`},{label:`Edit ${s??""}`}];return ee(jsxRuntime.jsx(te,{opts:{title:a,breadcrumb:d,basePath:r,flash:o},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}})})})}))}function _e(e,t,n){let s=new URLSearchParams;for(let r of e)s.set(`fv_${r.field}`,r.value),s.set(`fo_${r.field}`,r.op);return t&&(s.set("ob",t.field),s.set("od",t.dir)),n&&s.set("ps",String(n)),s}function Rt(e,t,n,s,r){let o=_e(e,s,r);return o.set("cursor",t),o.set("dir",n),`?${o.toString()}`}function tn(e,t,n,s){let r=_e(n,void 0,s);return t?.field===e?t.dir==="asc"&&(r.set("ob",e),r.set("od","desc")):(r.set("ob",e),r.set("od","asc")),`?${r.toString()}`}function nn(e,t,n){return `?${_e(t,n,e).toString()}`}function Ne(e,t,n,s,r,o,a=[],d=[],c=false,i=[],u,m,l,p){let y=`${s}/${e}`,h=`${y}/create`;return ee(jsxRuntime.jsxs(te,{opts:{title:e,breadcrumb:[{label:"Repositories",href:s},{label:e}],basePath:s,flash:o},children:[a.length>0&&jsxRuntime.jsx(Ie,{action:y,columnMeta:a,activeFilters:d,isGroup:p}),l&&jsxRuntime.jsxs("div",{role:"alert",class:`alert ${l.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:l.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:l.type==="index"?"Composite index required":"Query failed"}),jsxRuntime.jsx("div",{class:"text-sm",children:l.message})]}),l.indexUrl&&jsxRuntime.jsx("a",{href:l.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",children:[jsxRuntime.jsxs("div",{class:"flex items-center gap-3",children:[jsxRuntime.jsxs("span",{class:"text-sm text-base-content/60",children:[t.length," document",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(f=>jsxRuntime.jsx("a",{href:nn(f,d,u),class:`join-item btn btn-xs ${m===f?"btn-active btn-primary":"btn-outline"}`,children:f},f))})]})]}),jsxRuntime.jsx("a",{href:h,class:"btn btn-primary btn-sm",children:"+ New"})]}),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:[[...n].map((f,b)=>{let v=u?.field===f,g=v?u.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:tn(f,u,d,m),class:`hover:text-base-content inline-flex items-center gap-0.5${v?" text-primary font-bold":""}`,children:[f,g]})},b)}),i.map((f,b)=>jsxRuntime.jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:f.column},`rel-${b}`)),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+i.length+1,class:"text-center py-16 text-base-content/40",children:"No documents found"})}):t.map((f,b)=>{let v=String(f.docId??f.id??""),g=`${s}/${e}/${encodeURIComponent(v)}/edit`,x=`${s}/${e}/${encodeURIComponent(v)}/delete`;return jsxRuntime.jsxs("tr",{class:"hover",children:[n.map((R,w)=>jsxRuntime.jsx("td",{class:"align-top py-2",children:jsxRuntime.jsx(Pe,{val:f[R]})},w)),i.map((R,w)=>{let T=f[R.key];if(T==null||T==="")return jsxRuntime.jsx("td",{class:"py-2"},`rel-${w}`);let $=`${s}/${R.targetRepo}?fv_${R.targetKey}=${encodeURIComponent(String(T))}`;return jsxRuntime.jsx("td",{class:"align-middle py-2",children:jsxRuntime.jsx("a",{href:$,class:"btn btn-xs btn-ghost btn-outline",children:R.column})},`rel-${w}`)}),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:g,class:"btn btn-xs btn-outline",children:"Edit"}),c&&jsxRuntime.jsx("form",{method:"post",action:x,onsubmit:"return confirm('Delete this document?')",children:jsxRuntime.jsx("button",{type:"submit",class:"btn btn-xs btn-error btn-outline",children:"Delete"})})]})})]},b)})})]})}),(r.hasPrev||r.hasNext)&&jsxRuntime.jsxs("div",{class:"flex justify-center items-center mt-6 gap-2",children:[r.hasPrev?jsxRuntime.jsx("a",{href:Rt(d,r.prevCursor,"prev",u,m),class:"btn btn-sm btn-outline",children:"\u2190 Previous"}):jsxRuntime.jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"\u2190 Previous"}),r.hasNext?jsxRuntime.jsx("a",{href:Rt(d,r.nextCursor,"next",u,m),class:"btn btn-sm btn-outline",children:"Next \u2192"}):jsxRuntime.jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"Next \u2192"})]})]}))}function Re(e,t){return Ee(e,t)}function je(e,t){return De(e,t)}function ze(e,t,n,s,r,o,a,d,c,i,u,m,l,p){return Ne(e,t,n,s,r,o,a,d,c,i,u,m,l,p)}function ne(e,t,n,s,r,o){return Fe(e,t,n,s,r,o)}var rn=new Set(["<","<=",">",">=","!="]),sn=new Set(["array-contains","array-contains-any"]);function wt(e){return e==="desc"?"DESCENDING":"ASCENDING"}function on(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function an(e,t,n,s,r){let o=[],a=new Set;for(let i of s)if(i.op==="=="||i.op==="in"||i.op==="not-in"){if(a.has(i.field))continue;a.add(i.field),o.push({fieldPath:i.field,order:"ASCENDING"});}for(let i of s)if(sn.has(i.op)){if(a.has(i.field))continue;a.add(i.field),o.push({fieldPath:i.field,arrayConfig:"CONTAINS"});}for(let i of s)if(rn.has(i.op)){if(a.has(i.field))continue;a.add(i.field);let u=r?.field===i.field?wt(r.dir):"ASCENDING";o.push({fieldPath:i.field,order:u});}r&&!a.has(r.field)&&o.push({fieldPath:r.field,order:wt(r.dir)});let c=encodeURIComponent(JSON.stringify({collectionGroup:t,queryScope:n?"COLLECTION_GROUP":"COLLECTION",fields:o}));return `https://console.firebase.google.com/v1/r/project/${e}/firestore/indexes?create_composite=${c}`}function ln(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function cn(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 r of n)if(typeof r=="string"&&r.length>0)return r;return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.FIREBASE_PROJECT_ID||void 0}function ae(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function ge(e,t){let n=e??{},s=ae(e),r;if(s&&(r=n.message?ln(n.message):void 0,!r)){let o=cn(t.ref);if(o){let a=on(t.path);r=an(o,a,t.isGroup,t.filters,t.sort);}}return {type:s?"index":"error",message:s?"This query requires a composite index that does not exist yet.":n.message??"Query failed",indexUrl:r}}var Tt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function un(){let e="";for(let t=0;t<20;t++)e+=Tt.charAt(Math.floor(Math.random()*Tt.length));return e}function St(e,t){if(!t)return;let n=e[t];if(typeof n!="string"||!n)return;let s=n.split("/").filter(Boolean),r=[];for(let o=1;o<s.length;o+=2)r.push(s[o]);return r.length>0?r:void 0}async function Ze(e,t){let n=e.documentKey??"docId",s=`by${n.charAt(0).toUpperCase()}${n.slice(1)}`;if(typeof e.repo.get[s]=="function")try{let o=await e.repo.get[s](t);if(o)return o}catch{}return (await e.repo.query.by({where:[[n,"==",t]],limit:1}))[0]??null}function Me(e,t,n){let s=e.documentKey??"docId",r=ge(n,{ref:e.repo.ref,path:e.path,isGroup:!!e.isGroup,filters:[{field:s,op:"==",value:t}]});return r.type==="index"?{type:"warning",message:"Loading this document requires a composite index that does not exist yet.",...r.indexUrl?{action:{href:r.indexUrl,label:"Create Index \u2192",external:true}}:{}}:{type:"error",message:r.message}}function k(e,t,n=200){e.status(n).set("Content-Type","text/html; charset=utf-8").send(t);}function Ke(e,t){e.status(302).set("Location",t).send("");}function Be(e,t){let n=t.shape,s={};for(let[r,o]of Object.entries(n)){let a=qe(o);if(a==="ZodObject"){if(e[r+"__isnull"]==="1"){s[r]=null;continue}let i={},u=false;for(let[p,y]of Object.entries(e))p.startsWith(`${r}.`)&&(i[p.slice(r.length+1)]=y,u=true);if(u){let p=o;for(;;){let y=Z(p);if(y==="ZodOptional"||y==="ZodNullable"||y==="ZodDefault")p=Q(p);else break}s[r]=Be(i,p);continue}let m=e[r],l=Array.isArray(m)?m[m.length-1]:m;if(l)try{s[r]=JSON.parse(l);}catch{s[r]=l;}continue}let d=e[r],c=Array.isArray(d)?d[d.length-1]:d;if(e[r+"__isnull"]==="1"){s[r]=null;continue}if(c===void 0||c===""){a==="ZodBoolean"&&(s[r]=false);continue}switch(a){case "ZodBoolean":c==="__null__"?s[r]=null:s[r]=c==="true"||c==="on"||c==="1";break;case "ZodNumber":case "ZodBigInt":s[r]=Number(c);break;case "ZodDate":s[r]=new Date(c);break;case "ZodArray":try{s[r]=JSON.parse(c);}catch{s[r]=c;}break;default:if(c.startsWith("{")||c.startsWith("["))try{s[r]=JSON.parse(c);break}catch{}s[r]=c;}}return s}function Ct(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 s=new Date(e);isNaN(s.getTime())||(t=s);}if(!t||isNaN(t.getTime()))return null;let n=s=>String(s).padStart(2,"0");return `${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`}function qe(e){let t=e;for(;;){let n=Z(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=Q(t);else return n}}function Ot(e,t,n=""){let s={};for(let r of Object.keys(t.shape)){let o=n?`${n}.${r}`:r,a=e[r];if(a===null){s[o]="__null__";continue}if(a===void 0)continue;let d=t.shape[r];for(;;){let i=Z(d);if(i==="ZodOptional"||i==="ZodNullable"||i==="ZodDefault")d=Q(d);else break}let c=Z(d);if(c==="ZodObject"&&typeof a=="object"&&a!==null&&!Array.isArray(a)){let i=Ot(a,d,o);Object.assign(s,i);}else if(c==="ZodDate"){let i=Ct(a);i!==null&&(s[o]=i);}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)&&("_seconds"in a||typeof a.toDate=="function")){let i=Ct(a);s[o]=i??JSON.stringify(a,null,2);}else typeof a=="object"?s[o]=JSON.stringify(a,null,2):s[o]=String(a);}return s}function Qe(e,t){return e.map(n=>({...n,defaultValue:t[n.name]??n.defaultValue,nested:n.nested?Qe(n.nested,t):void 0}))}function pn(e,t){let n=new Set(["==","!=","<","<=",">",">=","in","not-in","array-contains","array-contains-any"]),s=[];for(let[r,o]of Object.entries(e)){if(!r.startsWith("fv_"))continue;let a=r.slice(3);if(!t.has(a))continue;let d=(o??"").trim();if(!d)continue;let c=e[`fo_${a}`]??"==",i=n.has(c)?c:"==";s.push({field:a,op:i,value:d});}return s}function fn(e){let t=n=>n==="true"?true:n==="false"?false:n!==""&&!isNaN(Number(n))?Number(n):n;return e.map(n=>{if(n.op==="array-contains-any"||n.op==="in"||n.op==="not-in"){let s=n.value.split(",").map(r=>t(r.trim())).filter(r=>r!=="");return [n.field,n.op,s]}return [n.field,n.op,t(n.value)]})}function At(e,t,n=""){let s=[];for(let r of e){let o=n?`${n}.${r}`:r,a=t.shape[r];if(!a){s.push({name:o,zodType:"ZodString"});continue}let d=qe(a);if(d==="ZodObject"){let c=a;for(;;){let u=Z(c);if(u==="ZodOptional"||u==="ZodNullable"||u==="ZodDefault")c=Q(c);else break}let i=fe(c);s.push(...At(Object.keys(i),c,o));}else s.push({name:o,zodType:d});}return s}function yn(e,t){let n=t.split("."),s=e;for(let r of n){for(;;){let a=Z(s);if(a==="ZodOptional"||a==="ZodNullable"||a==="ZodDefault")s=Q(s);else break}let o=fe(s);if(!(r in o))return null;s=o[r];}return s}function le(e,t){if(!t||t.length===0)return e;let n=[],s=new Map;for(let o of t){let a=o.indexOf(".");if(a===-1)n.push(o);else {let d=o.slice(0,a),c=o.slice(a+1);s.has(d)||s.set(d,[]),s.get(d).push(c);}}let r={};for(let o of n)o in e.shape&&(r[o]=e.shape[o]);for(let[o,a]of s){if(!(o in e.shape))continue;let d=e.shape[o];for(;;){let c=Z(d);if(c==="ZodOptional"||c==="ZodNullable"||c==="ZodDefault")d=Q(d);else break}if(Z(d)!=="ZodObject"){r[o]=e.shape[o];continue}r[o]=le(d,a);}return zod.z.object(r)}function ie(e,t){let n=t==="/"?"":t.replace(/\/$/,"");if(process.env.FUNCTIONS_EMULATOR==="true"){let o=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??"demo-project",a=process.env.FUNCTION_REGION??"us-central1",d=(process.env.FUNCTION_TARGET??"").replace(/\./g,"-");return `/${o}/${a}/${d}${n}`}let s=process.env.K_SERVICE,r=e.hostname??e.headers?.host??"";return s&&r.includes("cloudfunctions.net")?`/${s.toLowerCase()}${n}`:n}function $t(e,t){return {handleDashboard:(i,u)=>{let m=ie(i,t),l=Object.values(e).map(p=>({name:p.name,path:p.path}));k(u,je(l,m));},handleList:async(i,u)=>{let m=i.params.repoName;if(!m){k(u,"Bad request",400);return}let l=e[m];if(!l){k(u,"Repository not found",404);return}let p=l.pageSize??25,y=i.query??{},h=y.cursor,f=y.dir==="prev"?"prev":"next",b=y.ob??"",v=y.od==="desc"?"desc":"asc",g=b?{field:b,dir:v}:void 0,x=parseInt(y.ps??""),R=Number.isFinite(x)&&x>0?Math.min(x,200):p,w=l.listColumns??Object.keys(l.schema.shape),T=l.documentKey??"docId",$=[T,...w.filter(N=>N!==T)],C=l.filterableFields?(()=>{let N=[];for(let L of l.filterableFields)(L.includes(".")||w.includes(L))&&N.push(L);return N})():w,O=(()=>{let N=[];for(let L of C)if(L.includes(".")){let Je=yn(l.schema,L);N.push({name:L,zodType:Je?qe(Je):"ZodString"});}else N.push(...At([L],l.schema));return N})(),P=new Set(O.map(N=>N.name)),I=pn(y,P),B=fn(I),j;if(h)try{let N=l.repo.ref;typeof N.doc=="function"&&(j=await N.doc(h).get());}catch{}let W=await l.repo.query.paginate({pageSize:R,cursor:j,direction:f,...B.length>0?{where:B}:{},...g?{orderBy:[{field:g.field,direction:g.dir}]}:{}}).catch(N=>({queryError:ge(N,{ref:l.repo.ref,path:l.path,isGroup:!!l.isGroup,filters:I,sort:g})})),E="queryError"in W,ce=E?[]:W.data,zt=E?"":W.nextCursor?.id??"",Zt=E?"":W.prevCursor?.id??"",Mt=E?W.queryError:void 0,Kt=ie(i,t);k(u,ze(l.name,ce,$,Kt,{hasPrev:E?false:W.hasPrevPage,hasNext:E?false:W.hasNextPage,prevCursor:Zt,nextCursor:zt},void 0,O,I,l.allowDelete??false,l.relationalMeta,g,R,Mt,l.isGroup));},handleCreateForm:(i,u)=>{let m=i.params.repoName;if(!m){k(u,"Bad request",400);return}let l=e[m];if(!l){k(u,"Repository not found",404);return}let p=ie(i,t),y=le(l.schema,l.createFields),h=G(y),f=`${p}/${l.name}/create`,b=Y(h,f,"POST","Create document");k(u,ne(l.name,b,"create",null,p));},handleCreateSubmit:async(i,u)=>{let m=i.params.repoName;if(!m){k(u,"Bad request",400);return}let l=e[m];if(!l){k(u,"Repository not found",404);return}let p=ie(i,t),y=i.body??{},h=Be(y,l.schema),f=le(l.schema,l.createFields),b=f.safeParse(h);if(!b.success){let v=G(f),g=`${p}/${l.name}/create`,x=Y(v,g,"POST","Create document"),R=b.error.issues.map(w=>`${w.path.join(".")}: ${w.message}`).join(", ");k(u,ne(l.name,x,"create",null,p,{type:"error",message:`Validation error: ${R}`}),422);return}try{if(l.isGroup&&l.parentKeys&&l.parentKeys.length>0){let v={...b.data};l.createdKey&&(v[l.createdKey]=new Date);let g=l.parentKeys.filter(T=>!v[T]);if(g.length>0)throw new Error(`Missing parent key(s) for subcollection create: ${g.join(", ")}`);let x=l.parentKeys.map(T=>v[T]),R=l.documentKey??"docId",w=v[R]||un();await l.repo.set(...x,w,v);}else await l.repo.create(b.data);Ke(u,`${p}/${l.name}?flash=created`);}catch(v){let g=le(l.schema,l.createFields),x=G(g),R=`${p}/${l.name}/create`,w=Y(x,R,"POST","Create document");k(u,ne(l.name,w,"create",null,p,{type:"error",message:`Save error: ${v.message}`}),500);}},handleEditForm:async(i,u)=>{let m=i.params.repoName,l=i.params.id;if(!m||!l){k(u,"Bad request",400);return}let p=e[m];if(!p){k(u,"Repository not found",404);return}let y=ie(i,t),h=null;try{h=await Ze(p,l);}catch(R){let w=Me(p,l,R),T=ae(R)?424:500;k(u,Re("",{title:`Edit ${p.name} / ${l}`,basePath:y,breadcrumb:[{label:"Repositories",href:y},{label:p.name,href:`${y}/${p.name}`},{label:`Edit ${l}`}],flash:w}),T);return}if(!h){k(u,"Document not found",404);return}let f=Ot(h,p.schema),b=le(p.schema,p.mutableFields),v=Qe(G(b),f),g=`${y}/${p.name}/${encodeURIComponent(l)}/edit`,x=Y(v,g,"POST","Save changes");k(u,ne(p.name,x,"edit",l,y));},handleEditSubmit:async(i,u)=>{let m=i.params.repoName,l=i.params.id;if(!m||!l){k(u,"Bad request",400);return}let p=e[m];if(!p){k(u,"Repository not found",404);return}let y=ie(i,t),h=i.body??{},f=Be(h,p.schema),b=le(p.schema,p.mutableFields),g=b.partial().safeParse(f);if(!g.success){let x=Object.fromEntries(Object.entries(h).map(([C,O])=>[C,Array.isArray(O)?O.join(","):O??""])),R=Qe(G(b),x),w=`${y}/${p.name}/${encodeURIComponent(l)}/edit`,T=Y(R,w,"POST","Save changes"),$=g.error.issues.map(C=>`${C.path.join(".")}: ${C.message}`).join(", ");k(u,ne(p.name,T,"edit",l,y,{type:"error",message:`Validation error: ${$}`}),422);return}try{let x=await Ze(p,l),R=(x&&St(x,p.pathKey))??[l];await p.repo.update(...R,g.data),Ke(u,`${y}/${p.name}?flash=updated`);}catch(x){let R=le(p.schema,p.mutableFields),w=G(R),T=`${y}/${p.name}/${encodeURIComponent(l)}/edit`,$=Y(w,T,"POST","Save changes"),C=ae(x)?Me(p,l,x):{type:"error",message:`Save error: ${x.message}`},O=ae(x)?424:500;k(u,ne(p.name,$,"edit",l,y,C),O);}},handleDelete:async(i,u)=>{let m=i.params.repoName,l=i.params.id;if(!m||!l){k(u,"Bad request",400);return}let p=e[m];if(!p){k(u,"Repository not found",404);return}if(!p.allowDelete){k(u,"Delete is not allowed for this repository",403);return}let y=ie(i,t);try{let h=await Ze(p,l),f=(h&&St(h,p.pathKey))??[l];await p.repo.delete(...f),Ke(u,`${y}/${p.name}?flash=deleted`);}catch(h){let f=ae(h)?Me(p,l,h):{type:"error",message:`Delete error: ${h.message}`},b=ae(h)?424:500;k(u,Re("",{title:`Delete ${p.name} / ${l}`,basePath:y,breadcrumb:[{label:"Repositories",href:y},{label:p.name,href:`${y}/${p.name}`},{label:`Delete ${l}`}],flash:f}),b);}}}}function mn(e){let t=[],n=e.replace(/[.*+?^${}()|[\]\\]/g,s=>s===":"?s:`\\${s}`).replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,(s,r)=>(t.push(r),"([^/]+)"));return {pattern:new RegExp(`^${n}$`),paramNames:t}}function gn(e){let t=e.path??e.url??"/",n=t.indexOf("?");return n===-1?t:t.slice(0,n)}var J=class{constructor(){this.routes=[];this.middlewares=[];this.notFoundHandler=(t,n)=>{n.status(404).send("Not Found");};this.errorHandler=(t,n,s)=>{console.error("[MiniRouter]",t),s.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,s){let{pattern:r,paramNames:o}=mn(n);return this.routes.push({method:t.toUpperCase(),pattern:r,paramNames:o,handler:s}),this}async handle(t,n){let s=(t.method??"GET").toUpperCase(),r=gn(t),o=null,a={};for(let i of this.routes){if(i.method!==s)continue;let u=r.match(i.pattern);if(u){o=i,a={},i.paramNames.forEach((m,l)=>{a[m]=decodeURIComponent(u[l+1]??"");});break}}let d=Object.assign(t,{params:a}),c=o?o.handler:this.notFoundHandler;try{await this.runMiddlewareChain(d,n,c);}catch(i){this.errorHandler(i,t,n);}}async runMiddlewareChain(t,n,s){let r=0,o=async()=>{if(r<this.middlewares.length){let a=this.middlewares[r++];await a(t,n,o);}else await s(t,n);};await o();}};async function hn(e){return typeof e.rawBody=="string"?e.rawBody:Buffer.isBuffer(e.rawBody)?e.rawBody.toString("utf8"):""}function bn(e){let t={};if(!e)return t;for(let n of e.split("&")){let s=n.indexOf("=");if(s===-1)continue;let r=decodeURIComponent(n.slice(0,s).replace(/\+/g," ")),o=decodeURIComponent(n.slice(s+1).replace(/\+/g," ")),a=t[r];a===void 0?t[r]=o:Array.isArray(a)?a.push(o):t[r]=[a,o];}return t}function kt(e){let{basePath:t="/",repos:n,parseBody:s=true,auth:r,middleware:o=[],httpsOptions:a}=e,d=t==="/"?"":t.replace(/\/$/,""),c={};for(let[l,p]of Object.entries(n)){let y=p.schema??p.repo.schema??null;if(!y)throw new Error(`[createAdminServer] Repository "${l}" has no Zod schema. Either use createRepositoryConfig(schema)(config) or pass schema: explicitly.`);let h,f,b;if(p.fieldsConfig){let x=p.fieldsConfig;h=[],f=[],b=[];for(let[R,w]of Object.entries(x))for(let T of w)T==="filterable"?h.push(R):T==="mutable"?f.push(R):T==="create"&&b.push(R);h.length===0&&(h=void 0),f.length===0&&(f=void 0),b.length===0&&(b=void 0);}let v=(()=>{let x=p.repo._parentKeys;return x&&x.length>0?x:void 0})();if(v&&b)for(let x of v)b.includes(x)||b.push(x);let g={name:l,path:p.path,repo:p.repo,schema:y,documentKey:p.documentKey??"docId",pathKey:p.repo._pathKey??void 0,isGroup:!!p.repo._isGroup,parentKeys:v,createdKey:p.repo._createdKey??void 0,listColumns:p.listColumns,pageSize:p.pageSize,filterableFields:h,mutableFields:f,createFields:b,allowDelete:p.allowDelete??false,relationalMeta:(()=>{if(!p.relationalFields||p.relationalFields.length===0)return;let x=p.repo.relationalKeys??{},R=[];for(let w of p.relationalFields){let T=x[w.key];T&&R.push({key:w.key,column:w.column,targetRepo:String(T.repo),targetKey:String(T.key),type:T.type});}return R.length>0?R:void 0})()};c[l]=g;}let i=$t(c,d),u=new J;if(s&&u.use(async(l,p,y)=>{let h=l,f=String(h.headers?.["content-type"]??"");if(f.includes("application/x-www-form-urlencoded")){let b=await hn(h);l.body=bn(b);}else if(f.includes("application/json")&&typeof h.body=="string")try{l.body=JSON.parse(h.body);}catch{}await y();}),r)if(typeof r=="function")u.use(r);else {let l=r.realm??"Admin",p="Basic "+Buffer.from(`${r.username}:${r.password}`).toString("base64");u.use((y,h,f)=>{if((y.headers?.authorization??"")!==p){h.status(401).set("WWW-Authenticate",`Basic realm="${l}"`).set("Content-Type","text/plain").send("Unauthorized");return}f();});}for(let l of o)u.use(l);u.get(`${d}/`,i.handleDashboard),u.get(`${d}`,i.handleDashboard),u.get(`${d}/:repoName`,i.handleList),u.get(`${d}/:repoName/create`,i.handleCreateForm),u.post(`${d}/:repoName/create`,i.handleCreateSubmit),u.get(`${d}/:repoName/:id/edit`,i.handleEditForm),u.post(`${d}/:repoName/:id/edit`,i.handleEditSubmit),u.post(`${d}/:repoName/:id/delete`,i.handleDelete);let m=async(l,p)=>{await u.handle(l,p);};return a&&(m.httpsOptions=a),m}function Ue(e,t,n=200){e.status(n).set("Content-Type","application/json; charset=utf-8").send(JSON.stringify(t));}function ue(e,t,n,s=200){Ue(e,{success:true,data:t,meta:n},s);}function _(e,t,n=400){Ue(e,{success:false,error:t},n);}function Ge(e,t,n,s,r){let o=ge(t,n),a=o.type==="index",d=a?424:500,i={success:false,error:a?o.message:r&&t instanceof Error?t.message:s};a&&(i.errorType="index",o.indexUrl&&(i.indexUrl=o.indexUrl)),Ue(e,i,d);}var Pt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function vn(){let e="";for(let t=0;t<20;t++)e+=Pt.charAt(Math.floor(Math.random()*Pt.length));return e}function xn(e,t,n=[]){let s=e.shape,r={},o=t&&t.length>0?t:Object.keys(s);for(let a of o){if(n.includes(a))continue;let d=a.split(".")[0];d&&s[d]&&(r[d]=s[d]);}return zod.z.object(r)}function Et(e,t,n,s=false,r=[]){try{let o=xn(e,n,r);return {success:!0,data:(s?o.partial():o).parse(t)}}catch(o){return o instanceof zod.z.ZodError?{success:false,error:`Validation failed: ${o.issues.map(d=>`${d.path.join(".")}: ${d.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}function Rn(e,t){let n=[],s=t?new Set(t):null,r={eq:"==",ne:"!=",lt:"<",lte:"<=",gt:">",gte:">=",in:"in",nin:"not-in",contains:"array-contains",containsAny:"array-contains-any"};for(let[o,a]of Object.entries(e)){if(a===void 0||["cursor","limit","pageSize","orderBy","orderDir","select"].includes(o))continue;let d=Array.isArray(a)?a[0]:a;if(d===void 0||d==="")continue;let c=o.match(/^(\w+)__(\w+)$/),i,u="==";if(c&&c[1]&&c[2]){i=c[1];let l=c[2];if(r[l])u=r[l];else continue}else if(!c)i=o;else continue;if(s&&!s.has(i))continue;let m=d;u==="in"||u==="not-in"||u==="array-contains-any"?m=d.split(",").map(l=>Dt(l.trim())):m=Dt(d),n.push({field:i,op:u,value:m});}return n}function Dt(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 we(e){return e?{docId:e.id}:null}async function It(e,t){if(!t||typeof t!="object")return;let n=t.docId;if(typeof n=="string")try{let s=e.repo.ref;if(typeof s.doc!="function")return;let r=await s.doc(n).get();return r.exists?r:void 0}catch{return}}function _t(e,t,n){function s(p,y){return !p||!e[p]?(_(y,`Repository "${p}" not found`,404),null):e[p]}function r(p,y){if(!y)return;let h=p[y];if(typeof h!="string"||!h)return;let f=h.split("/").filter(Boolean),b=[];for(let v=1;v<f.length;v+=2)b.push(f[v]);return b.length>0?b:void 0}async function o(p,y){let h=`by${p.documentKey.charAt(0).toUpperCase()}${p.documentKey.slice(1)}`,f=p.repo.get[h];if(typeof f=="function")try{let v=await f(y);if(v)return v}catch{}return (await p.repo.query.by({where:[[p.documentKey,"==",y]],limit:1}))[0]??null}async function a(p,y){let h=p.params||{},f=s(h.repoName,y);if(!f)return;let b=[],v;try{let g=p.query??{},x=Math.min(Number(g.pageSize)||f.pageSize,100),R=g.cursor,w=g.direction?.toLowerCase()==="prev"?"prev":"next",T=g.orderBy,$=g.orderDir?.toLowerCase()==="desc"?"desc":"asc",C=g.select,O=C?C.split(",").map(E=>E.trim()):void 0,P;f.allowedIncludes&&g.includes&&(P=(typeof g.includes=="string"?g.includes.split(",").map(ce=>ce.trim()):Array.isArray(g.includes)?g.includes:[]).filter(ce=>typeof ce=="string"&&f.allowedIncludes.includes(ce)),P?.length===0&&(P=void 0));let I=Rn(g,f.filterableFields);b=I.map(E=>({field:E.field,op:E.op,value:String(E.value??"")})),T&&(v={field:T,dir:$});let B={pageSize:x,direction:w};if(R)try{let E=typeof R=="string"?JSON.parse(R):R;B.cursor=await It(f,E);}catch{}T&&(B.orderBy=[{field:T,direction:$}]),I.length>0&&(B.where=I.map(E=>[E.field,E.op,E.value])),O&&(B.select=O),P&&(B.include=P);let j=await f.repo.query.paginate(B),W={items:j.data,hasNextPage:j.hasNextPage,hasPrevPage:j.hasPrevPage,nextCursor:we(j.nextCursor),prevCursor:we(j.prevCursor)};ue(y,W,{pageSize:x,hasMore:j.hasNextPage});}catch(g){Ge(y,g,{ref:f.repo.ref,path:f.path,isGroup:!!f.isGroup,filters:b,sort:v},"Failed to fetch documents",n);}}async function d(p,y){let h=p.params||{},f=s(h.repoName,y);if(!f)return;let b=[],v;try{let g=p.body??{},x=Math.min(g.pageSize||f.pageSize,100),R=g.direction==="prev"?"prev":"next";g.where&&(b=g.where.map(C=>({field:String(C[0]),op:C[1],value:String(C[2]??"")}))),g.orderBy&&g.orderBy[0]&&(v={field:g.orderBy[0].field,dir:g.orderBy[0].direction==="desc"?"desc":"asc"});let w={pageSize:x,direction:R};if(g.cursor)try{let C=typeof g.cursor=="string"?JSON.parse(g.cursor):g.cursor;w.cursor=await It(f,C);}catch{}if(f.allowedIncludes&&g.includes&&g.includes.length>0){let C=g.includes.filter(O=>typeof O=="string"?f.allowedIncludes.includes(O):typeof O=="object"&&O!==null&&"relation"in O&&typeof O.relation=="string"?f.allowedIncludes.includes(O.relation):!1);C.length>0&&(w.include=C);}if(g.where&&g.where.length>0){if(f.filterableFields){let C=new Set(f.filterableFields),O=g.where.filter(P=>!C.has(P[0]));if(O.length>0){_(y,`Fields not filterable: ${O.map(P=>P[0]).join(", ")}`,400);return}}w.where=g.where;}if(g.orWhere&&g.orWhere.length>0){if(f.filterableFields){let C=new Set(f.filterableFields),O=g.orWhere.filter(P=>!C.has(P[0]));if(O.length>0){_(y,`Fields not filterable: ${O.map(P=>P[0]).join(", ")}`,400);return}}w.orWhere=g.orWhere;}if(g.orWhereGroups&&g.orWhereGroups.length>0){if(f.filterableFields){let C=new Set(f.filterableFields);for(let O of g.orWhereGroups){let P=O.filter(I=>!C.has(I[0]));if(P.length>0){_(y,`Fields not filterable: ${P.map(I=>I[0]).join(", ")}`,400);return}}}w.orWhereGroups=g.orWhereGroups;}g.orderBy&&g.orderBy.length>0&&(w.orderBy=g.orderBy),g.select&&g.select.length>0&&(w.select=g.select);let T=await f.repo.query.paginate(w),$={items:T.data,hasNextPage:T.hasNextPage,hasPrevPage:T.hasPrevPage,nextCursor:we(T.nextCursor),prevCursor:we(T.prevCursor)};ue(y,$,{pageSize:x,hasMore:T.hasNextPage});}catch(g){Ge(y,g,{ref:f.repo.ref,path:f.path,isGroup:!!f.isGroup,filters:b,sort:v},"Failed to query documents",n);}}async function c(p,y){let h=p.params||{},f=s(h.repoName,y);if(!f)return;let b=h.id;if(!b){_(y,"Document ID required",400);return}try{let v=await o(f,b);if(!v){_(y,"Document not found",404);return}ue(y,v);}catch(v){Ge(y,v,{ref:f.repo.ref,path:f.path,isGroup:!!f.isGroup,filters:[{field:f.documentKey,op:"==",value:b}]},"Failed to fetch document",n);}}async function i(p,y){let h=p.params||{},f=s(h.repoName,y);if(f)try{let b=p.body??{},v=Et(f.schema,b,f.createFields,!1,f.systemKeys);if(!v.success){_(y,v.error,400);return}if(f.validate){let x=await f.validate(v.data,"create");if(x){_(y,x,400);return}}let g;if(f.isGroup&&f.parentKeys&&f.parentKeys.length>0){let x={...v.data};f.createdKey&&(x[f.createdKey]=new Date);let R=f.parentKeys.filter($=>!x[$]);if(R.length>0){_(y,`Missing parent key(s) for subcollection create: ${R.join(", ")}`,400);return}let w=f.parentKeys.map($=>x[$]),T=x[f.documentKey]||vn();g=await f.repo.set(...w,T,x);}else g=await f.repo.create(v.data);ue(y,g,void 0,201);}catch(b){let v=n&&b instanceof Error?b.message:"Failed to create document";_(y,v,500);}}async function u(p,y,h){let f=p.params||{},b=s(f.repoName,y);if(!b)return;let v=f.id;if(!v){_(y,"Document ID required",400);return}try{let g=p.body??{},x=Et(b.schema,g,b.mutableFields,h,b.systemKeys);if(!x.success){_(y,x.error,400);return}if(b.validate){let $=await b.validate(x.data,"update");if($){_(y,$,400);return}}let R=await o(b,v),w=(R&&r(R,b.pathKey))??[v],T=await b.repo.update(...w,x.data);ue(y,T);}catch(g){let x=n&&g instanceof Error?g.message:"Failed to update document";_(y,x,500);}}async function m(p,y){let h=p.params||{},f=s(h.repoName,y);if(!f)return;if(!f.allowDelete){_(y,"Delete not allowed for this repository",403);return}let b=h.id;if(!b){_(y,"Document ID required",400);return}try{let v=await o(f,b),g=(v&&r(v,f.pathKey))??[b];await f.repo.delete(...g),ue(y,{deleted:!0});}catch(v){let g=n&&v instanceof Error?v.message:"Failed to delete document";_(y,g,500);}}function l(p,y){y.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:d,handleGet:c,handleCreate:i,handleUpdate:u,handleDelete:m,handleOptions:l}}function We(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 q(e){return {$ref:`#/components/schemas/${e}`}}function z(e){return {description:e,content:{"application/json":{schema:q("ErrorResponse")}}}}function he(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function Nt(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 wn(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 Tn(e){let t=e.filterableFields??Object.keys(e.schema.shape),n=["eq","ne","lt","lte","gt","gte","in","nin","contains"],s=[];for(let r of t){s.push({name:r,in:"query",schema:{type:"string"},description:`Filter by ${r} (equality)`});for(let o of n)s.push({name:`${r}__${o}`,in:"query",schema:{type:"string"},description:`Filter ${r} with operator ${o}`});}return s}function Sn(){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 Cn(e,t,n,s,r){let o={},a=e.name,d=`${t}/${e.name}`,c=`${d}/{${e.documentKey}}`,i={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};o[d]={get:{operationId:`list${re(e.name)}`,summary:`List ${e.name} (paginated)`,tags:[a],parameters:[...wn(e),...Tn(e)],responses:{200:Nt(q(n)),500:z("Internal server error")}},post:{operationId:`create${re(e.name)}`,summary:`Create a ${U(e.name)}`,tags:[a],requestBody:{required:true,content:{"application/json":{schema:q(s??n)}}},responses:{201:he("Document created",q(n)),400:z("Validation error"),500:z("Internal server error")}}},o[`${d}/query`]={post:{operationId:`query${re(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[a],requestBody:{required:true,content:{"application/json":{schema:q("QueryRequestBody")}}},responses:{200:Nt(q(n)),400:z("Invalid query"),500:z("Internal server error")}}};let u={};return u.get={operationId:`get${re(U(e.name))}`,summary:`Get a single ${U(e.name)}`,tags:[a],parameters:[i],responses:{200:he("Document found",q(n)),404:z("Document not found"),500:z("Internal server error")}},u.put={operationId:`update${re(U(e.name))}`,summary:`Update a ${U(e.name)} (full replace)`,tags:[a],parameters:[i],requestBody:{required:true,content:{"application/json":{schema:q(r??n)}}},responses:{200:he("Document updated",q(n)),400:z("Validation error"),404:z("Document not found"),500:z("Internal server error")}},u.patch={operationId:`patch${re(U(e.name))}`,summary:`Partially update a ${U(e.name)}`,tags:[a],parameters:[i],requestBody:{required:true,content:{"application/json":{schema:{allOf:[q(r??n)],description:"All fields are optional for partial updates"}}}},responses:{200:he("Document patched",q(n)),400:z("Validation error"),404:z("Document not found"),500:z("Internal server error")}},e.allowDelete&&(u.delete={operationId:`delete${re(U(e.name))}`,summary:`Delete a ${U(e.name)}`,tags:[a],parameters:[i],responses:{200:he("Document deleted",{type:"object",properties:{id:{type:"string"}}}),404:z("Document not found"),500:z("Internal server error")}}),o[c]=u,o}function He(e,t,n={}){let{title:s="CRUD API",version:r="1.0.0",description:o,servers:a,auth:d=false}=n,c=t==="/"?"":t.replace(/\/$/,""),i={},u={},m=[];i.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string"}},required:["success","error"]},i.QueryRequestBody=Sn();for(let[h,f]of Object.entries(e)){let b=re(U(h)),v=`${b}Create`,g=`${b}Update`;i[b]=We(f.schema);let x=O=>{let P=O&&O.length>0?O:Object.keys(f.schema.shape),I={};for(let B of P){let j=B.split(".")[0];j&&f.schema.shape[j]&&!f.systemKeys.includes(j)&&(I[j]=f.schema.shape[j]);}return I},R=null,w=x(f.createFields);Object.keys(w).length>0&&(i[v]=We(zod.z.object(w)),R=v);let T=null,$=x(f.mutableFields);Object.keys($).length>0&&(i[g]=We(zod.z.object($)),T=g);let C=Cn(f,c,b,R,T);Object.assign(u,C),m.push({name:h,description:`Operations on ${h} (collection: ${f.path})`});}let l={},p;return d==="basic"?(l.basicAuth={type:"http",scheme:"basic"},p=[{basicAuth:[]}]):d==="bearer"&&(l.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},p=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:s,version:r,...o?{description:o}:{}},...a&&a.length>0?{servers:a}:{},paths:u,components:{schemas:i,...Object.keys(l).length>0?{securitySchemes:l}:{}},...p?{security:p}:{},tags:m}}function re(e){return e.charAt(0).toUpperCase()+e.slice(1)}function U(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 On(e,t){return `<!DOCTYPE html>
555
+ `;function me(){return jsxRuntime.jsx("script",{dangerouslySetInnerHTML:{__html:Tt}})}function ee(e){return "<!DOCTYPE html>"+server.renderToString(e)}var te=({opts:e,children:t})=>{let{title:n,breadcrumb:s,flash:r,basePath:o="/"}=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("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.jsx("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:o,class:"font-bold text-lg tracking-tight hover:opacity-80 transition-opacity",children:"FRS Admin"})})}),jsxRuntime.jsxs("main",{class:"px-6 py-8 w-full flex-1",children:[s&&s.length>0&&jsxRuntime.jsx("div",{class:"text-sm breadcrumbs mb-4",children:jsxRuntime.jsx("ul",{children:s.map((a,d)=>a.href?jsxRuntime.jsx("li",{children:jsxRuntime.jsx("a",{href:a.href,children:a.label})},d):jsxRuntime.jsx("li",{class:"text-base-content/60",children:a.label},d))})}),jsxRuntime.jsx("h1",{class:"text-2xl font-bold mb-6",children:n}),r&&jsxRuntime.jsxs("div",{role:"alert",class:`alert ${r.type==="success"?"alert-success":r.type==="warning"?"alert-warning":"alert-error"} mb-6`,children:[jsxRuntime.jsx("span",{class:"flex-1",children:r.message}),r.action&&jsxRuntime.jsx("a",{href:r.action.href,...r.action.external?{target:"_blank",rel:"noopener noreferrer"}:{},class:"btn btn-sm btn-outline",children:r.action.label})]}),t]}),jsxRuntime.jsx(me,{})]})]})};function Ee(e,t){return ee(jsxRuntime.jsx(te,{opts:t,children:jsxRuntime.jsx("div",{dangerouslySetInnerHTML:{__html:e}})}))}function Ie(e,t){return ee(jsxRuntime.jsx(te,{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 Ct=[{value:"==",label:"="},{value:"!=",label:"\u2260"},{value:"in",label:"in"},{value:"not-in",label:"not in"}],sn=[{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"}],on=[{value:"array-contains",label:"contains"},{value:"array-contains-any",label:"contains any"}];function an(e){switch(e){case "ZodNumber":case "ZodBigInt":case "ZodDate":return sn;case "ZodBoolean":return Ct;case "ZodArray":return on;default:return Ct}}function ln({col:e,active:t}){let n=t?.value??"";if(e.zodType==="ZodBoolean")return jsxRuntime.jsxs("select",{name:`fv_${e.name}`,class:"select select-sm select-bordered w-full",children:[jsxRuntime.jsx("option",{value:"",selected:n==="",children:"\u2014"}),jsxRuntime.jsx("option",{value:"true",selected:n==="true",children:"true"}),jsxRuntime.jsx("option",{value:"false",selected:n==="false",children:"false"})]});if(e.zodType==="ZodArray"){let s=t?.op==="array-contains-any";return jsxRuntime.jsx("input",{type:"text",name:`fv_${e.name}`,value:n,placeholder:s?"val1, val2, \u2026":"value",class:"input input-sm input-bordered w-full"})}return e.zodType==="ZodNumber"||e.zodType==="ZodBigInt"?jsxRuntime.jsx("input",{type:"number",name:`fv_${e.name}`,value:n,placeholder:"value",class:"input input-sm input-bordered w-full"}):e.zodType==="ZodDate"?jsxRuntime.jsx("input",{type:"datetime-local",name:`fv_${e.name}`,value:n,class:"input input-sm input-bordered w-full"}):jsxRuntime.jsx("input",{type:"text",name:`fv_${e.name}`,value:n,placeholder:"value",class:"input input-sm input-bordered w-full"})}function Fe({action:e,columnMeta:t,activeFilters:n,isGroup:s}){let r=Object.fromEntries(n.map(i=>[i.field,i])),o=n.length>0,a=n.length>=2||s&&o,d=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:o?true:void 0,children:[jsxRuntime.jsxs("summary",{class:"collapse-title text-sm font-medium py-2 min-h-0",children:["Filters",o&&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:d.map(i=>{let c=an(i.zodType),u=r[i.name],m=u?.op??c[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:[c.length>1?jsxRuntime.jsx("select",{name:`fo_${i.name}`,class:"select select-sm select-bordered w-20 shrink-0",children:c.map(l=>jsxRuntime.jsx("option",{value:l.value,selected:l.value===m,children:l.label},l.value))}):jsxRuntime.jsx("input",{type:"hidden",name:`fo_${i.name}`,value:c[0].value}),jsxRuntime.jsx(ln,{col:i,active:u})]})]},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"}),o&&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"})}),s?"Collection group queries require a composite index":"Multiple filters may require a composite index"]})]})]})})]})}function _e(e,t,n,s,r,o){let a=n==="create"?`Create ${e}`:`Edit ${e} / ${s??""}`,d=n==="create"?[{label:"Repositories",href:r},{label:e,href:`${r}/${e}`},{label:"New document"}]:[{label:"Repositories",href:r},{label:e,href:`${r}/${e}`},{label:`Edit ${s??""}`}];return ee(jsxRuntime.jsx(te,{opts:{title:a,breadcrumb:d,basePath:r,flash:o},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}})})})}))}function Ne(e,t,n){let s=new URLSearchParams;for(let r of e)s.set(`fv_${r.field}`,r.value),s.set(`fo_${r.field}`,r.op);return t&&(s.set("ob",t.field),s.set("od",t.dir)),n&&s.set("ps",String(n)),s}function At(e,t,n,s,r){let o=Ne(e,s,r);return o.set("cursor",t),o.set("dir",n),`?${o.toString()}`}function cn(e,t,n,s){let r=Ne(n,void 0,s);return t?.field===e?t.dir==="asc"&&(r.set("ob",e),r.set("od","desc")):(r.set("ob",e),r.set("od","asc")),`?${r.toString()}`}function dn(e,t,n){return `?${Ne(t,n,e).toString()}`}function je(e,t,n,s,r,o,a=[],d=[],i=false,c=[],u,m,l,p){let y=`${s}/${e}`,h=`${y}/create`;return ee(jsxRuntime.jsxs(te,{opts:{title:e,breadcrumb:[{label:"Repositories",href:s},{label:e}],basePath:s,flash:o},children:[a.length>0&&jsxRuntime.jsx(Fe,{action:y,columnMeta:a,activeFilters:d,isGroup:p}),l&&jsxRuntime.jsxs("div",{role:"alert",class:`alert ${l.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:l.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:l.type==="index"?"Composite index required":"Query failed"}),jsxRuntime.jsx("div",{class:"text-sm",children:l.message})]}),l.indexUrl&&jsxRuntime.jsx("a",{href:l.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",children:[jsxRuntime.jsxs("div",{class:"flex items-center gap-3",children:[jsxRuntime.jsxs("span",{class:"text-sm text-base-content/60",children:[t.length," document",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(f=>jsxRuntime.jsx("a",{href:dn(f,d,u),class:`join-item btn btn-xs ${m===f?"btn-active btn-primary":"btn-outline"}`,children:f},f))})]})]}),jsxRuntime.jsx("a",{href:h,class:"btn btn-primary btn-sm",children:"+ New"})]}),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:[[...n].map((f,b)=>{let x=u?.field===f,g=x?u.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:cn(f,u,d,m),class:`hover:text-base-content inline-flex items-center gap-0.5${x?" text-primary font-bold":""}`,children:[f,g]})},b)}),c.map((f,b)=>jsxRuntime.jsx("th",{class:"text-xs font-semibold text-base-content/60 uppercase tracking-wide",children:f.column},`rel-${b}`)),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+c.length+1,class:"text-center py-16 text-base-content/40",children:"No documents found"})}):t.map((f,b)=>{let x=String(f.docId??f.id??""),g=`${s}/${e}/${encodeURIComponent(x)}/edit`,v=`${s}/${e}/${encodeURIComponent(x)}/delete`;return jsxRuntime.jsxs("tr",{class:"hover",children:[n.map((R,w)=>jsxRuntime.jsx("td",{class:"align-top py-2",children:jsxRuntime.jsx(De,{val:f[R]})},w)),c.map((R,w)=>{let T=f[R.key];if(T==null||T==="")return jsxRuntime.jsx("td",{class:"py-2"},`rel-${w}`);let $=`${s}/${R.targetRepo}?fv_${R.targetKey}=${encodeURIComponent(String(T))}`;return jsxRuntime.jsx("td",{class:"align-middle py-2",children:jsxRuntime.jsx("a",{href:$,class:"btn btn-xs btn-ghost btn-outline",children:R.column})},`rel-${w}`)}),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:g,class:"btn btn-xs btn-outline",children:"Edit"}),i&&jsxRuntime.jsx("form",{method:"post",action:v,onsubmit:"return confirm('Delete this document?')",children:jsxRuntime.jsx("button",{type:"submit",class:"btn btn-xs btn-error btn-outline",children:"Delete"})})]})})]},b)})})]})}),(r.hasPrev||r.hasNext)&&jsxRuntime.jsxs("div",{class:"flex justify-center items-center mt-6 gap-2",children:[r.hasPrev?jsxRuntime.jsx("a",{href:At(d,r.prevCursor,"prev",u,m),class:"btn btn-sm btn-outline",children:"\u2190 Previous"}):jsxRuntime.jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"\u2190 Previous"}),r.hasNext?jsxRuntime.jsx("a",{href:At(d,r.nextCursor,"next",u,m),class:"btn btn-sm btn-outline",children:"Next \u2192"}):jsxRuntime.jsx("button",{class:"btn btn-sm btn-outline",disabled:true,children:"Next \u2192"})]})]}))}function Re(e,t){return Ee(e,t)}function ze(e,t){return Ie(e,t)}function Ze(e,t,n,s,r,o,a,d,i,c,u,m,l,p){return je(e,t,n,s,r,o,a,d,i,c,u,m,l,p)}function ne(e,t,n,s,r,o){return _e(e,t,n,s,r,o)}var un=new Set(["<","<=",">",">=","!="]),pn=new Set(["array-contains","array-contains-any"]);function Me(e){return e==="desc"?"DESCENDING":"ASCENDING"}function fn(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function yn(e,t,n,s,r){let o=[],a=new Set;for(let i of s)if(i.op==="=="||i.op==="in"||i.op==="not-in"){if(a.has(i.field))continue;a.add(i.field),o.push({fieldPath:i.field,order:"ASCENDING"});}for(let i of s)if(pn.has(i.op)){if(a.has(i.field))continue;a.add(i.field),o.push({fieldPath:i.field,arrayConfig:"CONTAINS"});}for(let i of s)if(un.has(i.op)){if(a.has(i.field))continue;a.add(i.field);let c=r?.field===i.field?Me(r.dir):"ASCENDING";o.push({fieldPath:i.field,order:c});}if(r&&!a.has(r.field)&&o.push({fieldPath:r.field,order:Me(r.dir)}),o.length===1&&n)return hn(e,t,o[0]);let d=r&&o.some(i=>i.fieldPath===r.field)?Me(r.dir):"ASCENDING";return o.push({fieldPath:"__name__",order:d}),mn(e,t,n,o)}function mn(e,t,n,s,r="(default)"){let o=`projects/${e}/databases/${r}/collectionGroups/${t}/indexes/_`,a=[...Qe(1,o),...we(2,n?2:1)];for(let c of s)a.push(...Ot(3,$t(c)));let d=r==="(default)"?"-default-":r,i=encodeURIComponent(kt(a));return `https://console.firebase.google.com/project/${e}/firestore/databases/${d}/indexes?create_composite=${i}`}function gn(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function Ke(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function Be(e,t){return e<<3|t}function Qe(e,t){let n=Array.from(new TextEncoder().encode(t));return [Be(e,2),...Ke(n.length),...n]}function we(e,t){return [Be(e,0),...Ke(t)]}function Ot(e,t){return [Be(e,2),...Ke(t.length),...t]}function $t(e){let t=[...Qe(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...we(3,1)):t.push(...we(2,e.order==="DESCENDING"?2:1)),t}function kt(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 hn(e,t,n,s="(default)"){let r=`projects/${e}/databases/${s}/collectionGroups/${t}/fields/${n.fieldPath}`,o=[...Qe(1,r),...we(2,2),...Ot(3,$t(n))],a=s==="(default)"?"-default-":s,d=encodeURIComponent(kt(o));return `https://console.firebase.google.com/project/${e}/firestore/databases/${a}/indexes/automatic?create_exemption=${d}`}function bn(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 r of n)if(typeof r=="string"&&r.length>0)return r;return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.FIREBASE_PROJECT_ID||void 0}function ae(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function ge(e,t){let n=e??{},s=ae(e),r;if(s&&(r=n.message?gn(n.message):void 0,!r)){let o=bn(t.ref);if(o){let a=fn(t.path);r=yn(o,a,t.isGroup,t.filters,t.sort);}}return {type:s?"index":"error",message:s?"This query requires a composite index that does not exist yet.":n.message??"Query failed",indexUrl:r}}var Pt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function vn(){let e="";for(let t=0;t<20;t++)e+=Pt.charAt(Math.floor(Math.random()*Pt.length));return e}function Dt(e,t){if(!t)return;let n=e[t];if(typeof n!="string"||!n)return;let s=n.split("/").filter(Boolean),r=[];for(let o=1;o<s.length;o+=2)r.push(s[o]);return r.length>0?r:void 0}async function qe(e,t){let n=e.documentKey??"docId",s=`by${n.charAt(0).toUpperCase()}${n.slice(1)}`;if(typeof e.repo.get[s]=="function")try{let o=await e.repo.get[s](t);if(o)return o}catch{}return (await e.repo.query.by({where:[[n,"==",t]],limit:1}))[0]??null}function Ue(e,t,n){let s=e.documentKey??"docId",r=ge(n,{ref:e.repo.ref,path:e.path,isGroup:!!e.isGroup,filters:[{field:s,op:"==",value:t}]});return r.type==="index"?{type:"warning",message:"Loading this document requires a composite index that does not exist yet.",...r.indexUrl?{action:{href:r.indexUrl,label:"Create Index \u2192",external:true}}:{}}:{type:"error",message:r.message}}function k(e,t,n=200){e.status(n).set("Content-Type","text/html; charset=utf-8").send(t);}function Ge(e,t){e.status(302).set("Location",t).send("");}function We(e,t){let n=t.shape,s={};for(let[r,o]of Object.entries(n)){let a=He(o);if(a==="ZodObject"){if(e[r+"__isnull"]==="1"){s[r]=null;continue}let c={},u=false;for(let[p,y]of Object.entries(e))p.startsWith(`${r}.`)&&(c[p.slice(r.length+1)]=y,u=true);if(u){let p=o;for(;;){let y=Z(p);if(y==="ZodOptional"||y==="ZodNullable"||y==="ZodDefault")p=Q(p);else break}s[r]=We(c,p);continue}let m=e[r],l=Array.isArray(m)?m[m.length-1]:m;if(l)try{s[r]=JSON.parse(l);}catch{s[r]=l;}continue}let d=e[r],i=Array.isArray(d)?d[d.length-1]:d;if(e[r+"__isnull"]==="1"){s[r]=null;continue}if(i===void 0||i===""){a==="ZodBoolean"&&(s[r]=false);continue}switch(a){case "ZodBoolean":i==="__null__"?s[r]=null:s[r]=i==="true"||i==="on"||i==="1";break;case "ZodNumber":case "ZodBigInt":s[r]=Number(i);break;case "ZodDate":s[r]=new Date(i);break;case "ZodArray":try{s[r]=JSON.parse(i);}catch{s[r]=i;}break;default:if(i.startsWith("{")||i.startsWith("["))try{s[r]=JSON.parse(i);break}catch{}s[r]=i;}}return s}function Et(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 s=new Date(e);isNaN(s.getTime())||(t=s);}if(!t||isNaN(t.getTime()))return null;let n=s=>String(s).padStart(2,"0");return `${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`}function He(e){let t=e;for(;;){let n=Z(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=Q(t);else return n}}function It(e,t,n=""){let s={};for(let r of Object.keys(t.shape)){let o=n?`${n}.${r}`:r,a=e[r];if(a===null){s[o]="__null__";continue}if(a===void 0)continue;let d=t.shape[r];for(;;){let c=Z(d);if(c==="ZodOptional"||c==="ZodNullable"||c==="ZodDefault")d=Q(d);else break}let i=Z(d);if(i==="ZodObject"&&typeof a=="object"&&a!==null&&!Array.isArray(a)){let c=It(a,d,o);Object.assign(s,c);}else if(i==="ZodDate"){let c=Et(a);c!==null&&(s[o]=c);}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)&&("_seconds"in a||typeof a.toDate=="function")){let c=Et(a);s[o]=c??JSON.stringify(a,null,2);}else typeof a=="object"?s[o]=JSON.stringify(a,null,2):s[o]=String(a);}return s}function Le(e,t){return e.map(n=>({...n,defaultValue:t[n.name]??n.defaultValue,nested:n.nested?Le(n.nested,t):void 0}))}function Rn(e,t){let n=new Set(["==","!=","<","<=",">",">=","in","not-in","array-contains","array-contains-any"]),s=[];for(let[r,o]of Object.entries(e)){if(!r.startsWith("fv_"))continue;let a=r.slice(3);if(!t.has(a))continue;let d=(o??"").trim();if(!d)continue;let i=e[`fo_${a}`]??"==",c=n.has(i)?i:"==";s.push({field:a,op:c,value:d});}return s}function wn(e){let t=n=>n==="true"?true:n==="false"?false:n!==""&&!isNaN(Number(n))?Number(n):n;return e.map(n=>{if(n.op==="array-contains-any"||n.op==="in"||n.op==="not-in"){let s=n.value.split(",").map(r=>t(r.trim())).filter(r=>r!=="");return [n.field,n.op,s]}return [n.field,n.op,t(n.value)]})}function Ft(e,t,n=""){let s=[];for(let r of e){let o=n?`${n}.${r}`:r,a=t.shape[r];if(!a){s.push({name:o,zodType:"ZodString"});continue}let d=He(a);if(d==="ZodObject"){let i=a;for(;;){let u=Z(i);if(u==="ZodOptional"||u==="ZodNullable"||u==="ZodDefault")i=Q(i);else break}let c=fe(i);s.push(...Ft(Object.keys(c),i,o));}else s.push({name:o,zodType:d});}return s}function Tn(e,t){let n=t.split("."),s=e;for(let r of n){for(;;){let a=Z(s);if(a==="ZodOptional"||a==="ZodNullable"||a==="ZodDefault")s=Q(s);else break}let o=fe(s);if(!(r in o))return null;s=o[r];}return s}function le(e,t){if(!t||t.length===0)return e;let n=[],s=new Map;for(let o of t){let a=o.indexOf(".");if(a===-1)n.push(o);else {let d=o.slice(0,a),i=o.slice(a+1);s.has(d)||s.set(d,[]),s.get(d).push(i);}}let r={};for(let o of n)o in e.shape&&(r[o]=e.shape[o]);for(let[o,a]of s){if(!(o in e.shape))continue;let d=e.shape[o];for(;;){let i=Z(d);if(i==="ZodOptional"||i==="ZodNullable"||i==="ZodDefault")d=Q(d);else break}if(Z(d)!=="ZodObject"){r[o]=e.shape[o];continue}r[o]=le(d,a);}return zod.z.object(r)}function ie(e,t){let n=t==="/"?"":t.replace(/\/$/,"");if(process.env.FUNCTIONS_EMULATOR==="true"){let o=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??"demo-project",a=process.env.FUNCTION_REGION??"us-central1",d=(process.env.FUNCTION_TARGET??"").replace(/\./g,"-");return `/${o}/${a}/${d}${n}`}let s=process.env.K_SERVICE,r=e.hostname??e.headers?.host??"";return s&&r.includes("cloudfunctions.net")?`/${s.toLowerCase()}${n}`:n}function _t(e,t){return {handleDashboard:(c,u)=>{let m=ie(c,t),l=Object.values(e).map(p=>({name:p.name,path:p.path}));k(u,ze(l,m));},handleList:async(c,u)=>{let m=c.params.repoName;if(!m){k(u,"Bad request",400);return}let l=e[m];if(!l){k(u,"Repository not found",404);return}let p=l.pageSize??25,y=c.query??{},h=y.cursor,f=y.dir==="prev"?"prev":"next",b=y.ob??"",x=y.od==="desc"?"desc":"asc",g=b?{field:b,dir:x}:void 0,v=parseInt(y.ps??""),R=Number.isFinite(v)&&v>0?Math.min(v,200):p,w=l.listColumns??Object.keys(l.schema.shape),T=l.documentKey??"docId",$=[T,...w.filter(N=>N!==T)],C=l.filterableFields?(()=>{let N=[];for(let L of l.filterableFields)(L.includes(".")||w.includes(L))&&N.push(L);return N})():w,A=(()=>{let N=[];for(let L of C)if(L.includes(".")){let nt=Tn(l.schema,L);N.push({name:L,zodType:nt?He(nt):"ZodString"});}else N.push(...Ft([L],l.schema));return N})(),P=new Set(A.map(N=>N.name)),I=Rn(y,P),B=wn(I),j;if(h)try{let N=l.repo.ref;typeof N.doc=="function"&&(j=await N.doc(h).get());}catch{}let W=await l.repo.query.paginate({pageSize:R,cursor:j,direction:f,...B.length>0?{where:B}:{},...g?{orderBy:[{field:g.field,direction:g.dir}]}:{}}).catch(N=>({queryError:ge(N,{ref:l.repo.ref,path:l.path,isGroup:!!l.isGroup,filters:I,sort:g})})),D="queryError"in W,ce=D?[]:W.data,Ut=D?"":W.nextCursor?.id??"",Gt=D?"":W.prevCursor?.id??"",Wt=D?W.queryError:void 0,Lt=ie(c,t);k(u,Ze(l.name,ce,$,Lt,{hasPrev:D?false:W.hasPrevPage,hasNext:D?false:W.hasNextPage,prevCursor:Gt,nextCursor:Ut},void 0,A,I,l.allowDelete??false,l.relationalMeta,g,R,Wt,l.isGroup));},handleCreateForm:(c,u)=>{let m=c.params.repoName;if(!m){k(u,"Bad request",400);return}let l=e[m];if(!l){k(u,"Repository not found",404);return}let p=ie(c,t),y=le(l.schema,l.createFields),h=U(y),f=`${p}/${l.name}/create`,b=Y(h,f,"POST","Create document");k(u,ne(l.name,b,"create",null,p));},handleCreateSubmit:async(c,u)=>{let m=c.params.repoName;if(!m){k(u,"Bad request",400);return}let l=e[m];if(!l){k(u,"Repository not found",404);return}let p=ie(c,t),y=c.body??{},h=We(y,l.schema),f=le(l.schema,l.createFields),b=f.safeParse(h);if(!b.success){let x=U(f),g=`${p}/${l.name}/create`,v=Y(x,g,"POST","Create document"),R=b.error.issues.map(w=>`${w.path.join(".")}: ${w.message}`).join(", ");k(u,ne(l.name,v,"create",null,p,{type:"error",message:`Validation error: ${R}`}),422);return}try{if(l.isGroup&&l.parentKeys&&l.parentKeys.length>0){let x={...b.data};l.createdKey&&(x[l.createdKey]=new Date);let g=l.parentKeys.filter(T=>!x[T]);if(g.length>0)throw new Error(`Missing parent key(s) for subcollection create: ${g.join(", ")}`);let v=l.parentKeys.map(T=>x[T]),R=l.documentKey??"docId",w=x[R]||vn();await l.repo.set(...v,w,x);}else await l.repo.create(b.data);Ge(u,`${p}/${l.name}?flash=created`);}catch(x){let g=le(l.schema,l.createFields),v=U(g),R=`${p}/${l.name}/create`,w=Y(v,R,"POST","Create document");k(u,ne(l.name,w,"create",null,p,{type:"error",message:`Save error: ${x.message}`}),500);}},handleEditForm:async(c,u)=>{let m=c.params.repoName,l=c.params.id;if(!m||!l){k(u,"Bad request",400);return}let p=e[m];if(!p){k(u,"Repository not found",404);return}let y=ie(c,t),h=null;try{h=await qe(p,l);}catch(R){let w=Ue(p,l,R),T=ae(R)?424:500;k(u,Re("",{title:`Edit ${p.name} / ${l}`,basePath:y,breadcrumb:[{label:"Repositories",href:y},{label:p.name,href:`${y}/${p.name}`},{label:`Edit ${l}`}],flash:w}),T);return}if(!h){k(u,"Document not found",404);return}let f=It(h,p.schema),b=le(p.schema,p.mutableFields),x=Le(U(b),f),g=`${y}/${p.name}/${encodeURIComponent(l)}/edit`,v=Y(x,g,"POST","Save changes");k(u,ne(p.name,v,"edit",l,y));},handleEditSubmit:async(c,u)=>{let m=c.params.repoName,l=c.params.id;if(!m||!l){k(u,"Bad request",400);return}let p=e[m];if(!p){k(u,"Repository not found",404);return}let y=ie(c,t),h=c.body??{},f=We(h,p.schema),b=le(p.schema,p.mutableFields),g=b.partial().safeParse(f);if(!g.success){let v=Object.fromEntries(Object.entries(h).map(([C,A])=>[C,Array.isArray(A)?A.join(","):A??""])),R=Le(U(b),v),w=`${y}/${p.name}/${encodeURIComponent(l)}/edit`,T=Y(R,w,"POST","Save changes"),$=g.error.issues.map(C=>`${C.path.join(".")}: ${C.message}`).join(", ");k(u,ne(p.name,T,"edit",l,y,{type:"error",message:`Validation error: ${$}`}),422);return}try{let v=await qe(p,l),R=(v&&Dt(v,p.pathKey))??[l];await p.repo.update(...R,g.data),Ge(u,`${y}/${p.name}?flash=updated`);}catch(v){let R=le(p.schema,p.mutableFields),w=U(R),T=`${y}/${p.name}/${encodeURIComponent(l)}/edit`,$=Y(w,T,"POST","Save changes"),C=ae(v)?Ue(p,l,v):{type:"error",message:`Save error: ${v.message}`},A=ae(v)?424:500;k(u,ne(p.name,$,"edit",l,y,C),A);}},handleDelete:async(c,u)=>{let m=c.params.repoName,l=c.params.id;if(!m||!l){k(u,"Bad request",400);return}let p=e[m];if(!p){k(u,"Repository not found",404);return}if(!p.allowDelete){k(u,"Delete is not allowed for this repository",403);return}let y=ie(c,t);try{let h=await qe(p,l),f=(h&&Dt(h,p.pathKey))??[l];await p.repo.delete(...f),Ge(u,`${y}/${p.name}?flash=deleted`);}catch(h){let f=ae(h)?Ue(p,l,h):{type:"error",message:`Delete error: ${h.message}`},b=ae(h)?424:500;k(u,Re("",{title:`Delete ${p.name} / ${l}`,basePath:y,breadcrumb:[{label:"Repositories",href:y},{label:p.name,href:`${y}/${p.name}`},{label:`Delete ${l}`}],flash:f}),b);}}}}function Sn(e){let t=[],n=e.replace(/[.*+?^${}()|[\]\\]/g,s=>s===":"?s:`\\${s}`).replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,(s,r)=>(t.push(r),"([^/]+)"));return {pattern:new RegExp(`^${n}$`),paramNames:t}}function Cn(e){let t=e.path??e.url??"/",n=t.indexOf("?");return n===-1?t:t.slice(0,n)}var J=class{constructor(){this.routes=[];this.middlewares=[];this.notFoundHandler=(t,n)=>{n.status(404).send("Not Found");};this.errorHandler=(t,n,s)=>{console.error("[MiniRouter]",t),s.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,s){let{pattern:r,paramNames:o}=Sn(n);return this.routes.push({method:t.toUpperCase(),pattern:r,paramNames:o,handler:s}),this}async handle(t,n){let s=(t.method??"GET").toUpperCase(),r=Cn(t),o=null,a={};for(let c of this.routes){if(c.method!==s)continue;let u=r.match(c.pattern);if(u){o=c,a={},c.paramNames.forEach((m,l)=>{a[m]=decodeURIComponent(u[l+1]??"");});break}}let d=Object.assign(t,{params:a}),i=o?o.handler:this.notFoundHandler;try{await this.runMiddlewareChain(d,n,i);}catch(c){this.errorHandler(c,t,n);}}async runMiddlewareChain(t,n,s){let r=0,o=async()=>{if(r<this.middlewares.length){let a=this.middlewares[r++];await a(t,n,o);}else await s(t,n);};await o();}};async function An(e){return typeof e.rawBody=="string"?e.rawBody:Buffer.isBuffer(e.rawBody)?e.rawBody.toString("utf8"):""}function On(e){let t={};if(!e)return t;for(let n of e.split("&")){let s=n.indexOf("=");if(s===-1)continue;let r=decodeURIComponent(n.slice(0,s).replace(/\+/g," ")),o=decodeURIComponent(n.slice(s+1).replace(/\+/g," ")),a=t[r];a===void 0?t[r]=o:Array.isArray(a)?a.push(o):t[r]=[a,o];}return t}function Nt(e){let{basePath:t="/",repos:n,parseBody:s=true,auth:r,middleware:o=[],httpsOptions:a}=e,d=t==="/"?"":t.replace(/\/$/,""),i={};for(let[l,p]of Object.entries(n)){let y=p.schema??p.repo.schema??null;if(!y)throw new Error(`[createAdminServer] Repository "${l}" has no Zod schema. Either use createRepositoryConfig(schema)(config) or pass schema: explicitly.`);let h,f,b;if(p.fieldsConfig){let v=p.fieldsConfig;h=[],f=[],b=[];for(let[R,w]of Object.entries(v))for(let T of w)T==="filterable"?h.push(R):T==="mutable"?f.push(R):T==="create"&&b.push(R);h.length===0&&(h=void 0),f.length===0&&(f=void 0),b.length===0&&(b=void 0);}let x=(()=>{let v=p.repo._parentKeys;return v&&v.length>0?v:void 0})();if(x&&b)for(let v of x)b.includes(v)||b.push(v);let g={name:l,path:p.path,repo:p.repo,schema:y,documentKey:p.documentKey??"docId",pathKey:p.repo._pathKey??void 0,isGroup:!!p.repo._isGroup,parentKeys:x,createdKey:p.repo._createdKey??void 0,listColumns:p.listColumns,pageSize:p.pageSize,filterableFields:h,mutableFields:f,createFields:b,allowDelete:p.allowDelete??false,relationalMeta:(()=>{if(!p.relationalFields||p.relationalFields.length===0)return;let v=p.repo.relationalKeys??{},R=[];for(let w of p.relationalFields){let T=v[w.key];T&&R.push({key:w.key,column:w.column,targetRepo:String(T.repo),targetKey:String(T.key),type:T.type});}return R.length>0?R:void 0})()};i[l]=g;}let c=_t(i,d),u=new J;if(s&&u.use(async(l,p,y)=>{let h=l,f=String(h.headers?.["content-type"]??"");if(f.includes("application/x-www-form-urlencoded")){let b=await An(h);l.body=On(b);}else if(f.includes("application/json")&&typeof h.body=="string")try{l.body=JSON.parse(h.body);}catch{}await y();}),r)if(typeof r=="function")u.use(r);else {let l=r.realm??"Admin",p="Basic "+Buffer.from(`${r.username}:${r.password}`).toString("base64");u.use((y,h,f)=>{if((y.headers?.authorization??"")!==p){h.status(401).set("WWW-Authenticate",`Basic realm="${l}"`).set("Content-Type","text/plain").send("Unauthorized");return}f();});}for(let l of o)u.use(l);u.get(`${d}/`,c.handleDashboard),u.get(`${d}`,c.handleDashboard),u.get(`${d}/:repoName`,c.handleList),u.get(`${d}/:repoName/create`,c.handleCreateForm),u.post(`${d}/:repoName/create`,c.handleCreateSubmit),u.get(`${d}/:repoName/:id/edit`,c.handleEditForm),u.post(`${d}/:repoName/:id/edit`,c.handleEditSubmit),u.post(`${d}/:repoName/:id/delete`,c.handleDelete);let m=async(l,p)=>{await u.handle(l,p);};return a&&(m.httpsOptions=a),m}function Je(e,t,n=200){e.status(n).set("Content-Type","application/json; charset=utf-8").send(JSON.stringify(t));}function ue(e,t,n,s=200){Je(e,{success:true,data:t,meta:n},s);}function _(e,t,n=400){Je(e,{success:false,error:t},n);}function Ve(e,t,n,s,r){let o=ge(t,n),a=o.type==="index",d=a?424:500,c={success:false,error:a?o.message:r&&t instanceof Error?t.message:s};a&&(c.errorType="index",o.indexUrl&&(c.indexUrl=o.indexUrl)),Je(e,c,d);}var jt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function $n(){let e="";for(let t=0;t<20;t++)e+=jt.charAt(Math.floor(Math.random()*jt.length));return e}function kn(e,t,n=[]){let s=e.shape,r={},o=t&&t.length>0?t:Object.keys(s);for(let a of o){if(n.includes(a))continue;let d=a.split(".")[0];d&&s[d]&&(r[d]=s[d]);}return zod.z.object(r)}function zt(e,t,n,s=false,r=[]){try{let o=kn(e,n,r);return {success:!0,data:(s?o.partial():o).parse(t)}}catch(o){return o instanceof zod.z.ZodError?{success:false,error:`Validation failed: ${o.issues.map(d=>`${d.path.join(".")}: ${d.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}function Pn(e,t){let n=[],s=t?new Set(t):null,r={eq:"==",ne:"!=",lt:"<",lte:"<=",gt:">",gte:">=",in:"in",nin:"not-in",contains:"array-contains",containsAny:"array-contains-any"};for(let[o,a]of Object.entries(e)){if(a===void 0||["cursor","limit","pageSize","orderBy","orderDir","select"].includes(o))continue;let d=Array.isArray(a)?a[0]:a;if(d===void 0||d==="")continue;let i=o.match(/^(\w+)__(\w+)$/),c,u="==";if(i&&i[1]&&i[2]){c=i[1];let l=i[2];if(r[l])u=r[l];else continue}else if(!i)c=o;else continue;if(s&&!s.has(c))continue;let m=d;u==="in"||u==="not-in"||u==="array-contains-any"?m=d.split(",").map(l=>Zt(l.trim())):m=Zt(d),n.push({field:c,op:u,value:m});}return n}function Zt(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 Te(e){return e?{docId:e.id}:null}async function Mt(e,t){if(!t||typeof t!="object")return;let n=t.docId;if(typeof n=="string")try{let s=e.repo.ref;if(typeof s.doc!="function")return;let r=await s.doc(n).get();return r.exists?r:void 0}catch{return}}function Bt(e,t,n){function s(p,y){return !p||!e[p]?(_(y,`Repository "${p}" not found`,404),null):e[p]}function r(p,y){if(!y)return;let h=p[y];if(typeof h!="string"||!h)return;let f=h.split("/").filter(Boolean),b=[];for(let x=1;x<f.length;x+=2)b.push(f[x]);return b.length>0?b:void 0}async function o(p,y){let h=`by${p.documentKey.charAt(0).toUpperCase()}${p.documentKey.slice(1)}`,f=p.repo.get[h];if(typeof f=="function")try{let x=await f(y);if(x)return x}catch{}return (await p.repo.query.by({where:[[p.documentKey,"==",y]],limit:1}))[0]??null}async function a(p,y){let h=p.params||{},f=s(h.repoName,y);if(!f)return;let b=[],x;try{let g=p.query??{},v=Math.min(Number(g.pageSize)||f.pageSize,100),R=g.cursor,w=g.direction?.toLowerCase()==="prev"?"prev":"next",T=g.orderBy,$=g.orderDir?.toLowerCase()==="desc"?"desc":"asc",C=g.select,A=C?C.split(",").map(D=>D.trim()):void 0,P;f.allowedIncludes&&g.includes&&(P=(typeof g.includes=="string"?g.includes.split(",").map(ce=>ce.trim()):Array.isArray(g.includes)?g.includes:[]).filter(ce=>typeof ce=="string"&&f.allowedIncludes.includes(ce)),P?.length===0&&(P=void 0));let I=Pn(g,f.filterableFields);b=I.map(D=>({field:D.field,op:D.op,value:String(D.value??"")})),T&&(x={field:T,dir:$});let B={pageSize:v,direction:w};if(R)try{let D=typeof R=="string"?JSON.parse(R):R;B.cursor=await Mt(f,D);}catch{}T&&(B.orderBy=[{field:T,direction:$}]),I.length>0&&(B.where=I.map(D=>[D.field,D.op,D.value])),A&&(B.select=A),P&&(B.include=P);let j=await f.repo.query.paginate(B),W={items:j.data,hasNextPage:j.hasNextPage,hasPrevPage:j.hasPrevPage,nextCursor:Te(j.nextCursor),prevCursor:Te(j.prevCursor)};ue(y,W,{pageSize:v,hasMore:j.hasNextPage});}catch(g){Ve(y,g,{ref:f.repo.ref,path:f.path,isGroup:!!f.isGroup,filters:b,sort:x},"Failed to fetch documents",n);}}async function d(p,y){let h=p.params||{},f=s(h.repoName,y);if(!f)return;let b=[],x;try{let g=p.body??{},v=Math.min(g.pageSize||f.pageSize,100),R=g.direction==="prev"?"prev":"next";g.where&&(b=g.where.map(C=>({field:String(C[0]),op:C[1],value:String(C[2]??"")}))),g.orderBy&&g.orderBy[0]&&(x={field:g.orderBy[0].field,dir:g.orderBy[0].direction==="desc"?"desc":"asc"});let w={pageSize:v,direction:R};if(g.cursor)try{let C=typeof g.cursor=="string"?JSON.parse(g.cursor):g.cursor;w.cursor=await Mt(f,C);}catch{}if(f.allowedIncludes&&g.includes&&g.includes.length>0){let C=g.includes.filter(A=>typeof A=="string"?f.allowedIncludes.includes(A):typeof A=="object"&&A!==null&&"relation"in A&&typeof A.relation=="string"?f.allowedIncludes.includes(A.relation):!1);C.length>0&&(w.include=C);}if(g.where&&g.where.length>0){if(f.filterableFields){let C=new Set(f.filterableFields),A=g.where.filter(P=>!C.has(P[0]));if(A.length>0){_(y,`Fields not filterable: ${A.map(P=>P[0]).join(", ")}`,400);return}}w.where=g.where;}if(g.orWhere&&g.orWhere.length>0){if(f.filterableFields){let C=new Set(f.filterableFields),A=g.orWhere.filter(P=>!C.has(P[0]));if(A.length>0){_(y,`Fields not filterable: ${A.map(P=>P[0]).join(", ")}`,400);return}}w.orWhere=g.orWhere;}if(g.orWhereGroups&&g.orWhereGroups.length>0){if(f.filterableFields){let C=new Set(f.filterableFields);for(let A of g.orWhereGroups){let P=A.filter(I=>!C.has(I[0]));if(P.length>0){_(y,`Fields not filterable: ${P.map(I=>I[0]).join(", ")}`,400);return}}}w.orWhereGroups=g.orWhereGroups;}g.orderBy&&g.orderBy.length>0&&(w.orderBy=g.orderBy),g.select&&g.select.length>0&&(w.select=g.select);let T=await f.repo.query.paginate(w),$={items:T.data,hasNextPage:T.hasNextPage,hasPrevPage:T.hasPrevPage,nextCursor:Te(T.nextCursor),prevCursor:Te(T.prevCursor)};ue(y,$,{pageSize:v,hasMore:T.hasNextPage});}catch(g){Ve(y,g,{ref:f.repo.ref,path:f.path,isGroup:!!f.isGroup,filters:b,sort:x},"Failed to query documents",n);}}async function i(p,y){let h=p.params||{},f=s(h.repoName,y);if(!f)return;let b=h.id;if(!b){_(y,"Document ID required",400);return}try{let x=await o(f,b);if(!x){_(y,"Document not found",404);return}ue(y,x);}catch(x){Ve(y,x,{ref:f.repo.ref,path:f.path,isGroup:!!f.isGroup,filters:[{field:f.documentKey,op:"==",value:b}]},"Failed to fetch document",n);}}async function c(p,y){let h=p.params||{},f=s(h.repoName,y);if(f)try{let b=p.body??{},x=zt(f.schema,b,f.createFields,!1,f.systemKeys);if(!x.success){_(y,x.error,400);return}if(f.validate){let v=await f.validate(x.data,"create");if(v){_(y,v,400);return}}let g;if(f.isGroup&&f.parentKeys&&f.parentKeys.length>0){let v={...x.data};f.createdKey&&(v[f.createdKey]=new Date);let R=f.parentKeys.filter($=>!v[$]);if(R.length>0){_(y,`Missing parent key(s) for subcollection create: ${R.join(", ")}`,400);return}let w=f.parentKeys.map($=>v[$]),T=v[f.documentKey]||$n();g=await f.repo.set(...w,T,v);}else g=await f.repo.create(x.data);ue(y,g,void 0,201);}catch(b){let x=n&&b instanceof Error?b.message:"Failed to create document";_(y,x,500);}}async function u(p,y,h){let f=p.params||{},b=s(f.repoName,y);if(!b)return;let x=f.id;if(!x){_(y,"Document ID required",400);return}try{let g=p.body??{},v=zt(b.schema,g,b.mutableFields,h,b.systemKeys);if(!v.success){_(y,v.error,400);return}if(b.validate){let $=await b.validate(v.data,"update");if($){_(y,$,400);return}}let R=await o(b,x),w=(R&&r(R,b.pathKey))??[x],T=await b.repo.update(...w,v.data);ue(y,T);}catch(g){let v=n&&g instanceof Error?g.message:"Failed to update document";_(y,v,500);}}async function m(p,y){let h=p.params||{},f=s(h.repoName,y);if(!f)return;if(!f.allowDelete){_(y,"Delete not allowed for this repository",403);return}let b=h.id;if(!b){_(y,"Document ID required",400);return}try{let x=await o(f,b),g=(x&&r(x,f.pathKey))??[b];await f.repo.delete(...g),ue(y,{deleted:!0});}catch(x){let g=n&&x instanceof Error?x.message:"Failed to delete document";_(y,g,500);}}function l(p,y){y.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:d,handleGet:i,handleCreate:c,handleUpdate:u,handleDelete:m,handleOptions:l}}function Xe(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 q(e){return {$ref:`#/components/schemas/${e}`}}function z(e){return {description:e,content:{"application/json":{schema:q("ErrorResponse")}}}}function he(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function Qt(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 Dn(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 En(e){let t=e.filterableFields??Object.keys(e.schema.shape),n=["eq","ne","lt","lte","gt","gte","in","nin","contains"],s=[];for(let r of t){s.push({name:r,in:"query",schema:{type:"string"},description:`Filter by ${r} (equality)`});for(let o of n)s.push({name:`${r}__${o}`,in:"query",schema:{type:"string"},description:`Filter ${r} with operator ${o}`});}return s}function In(){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 Fn(e,t,n,s,r){let o={},a=e.name,d=`${t}/${e.name}`,i=`${d}/{${e.documentKey}}`,c={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};o[d]={get:{operationId:`list${re(e.name)}`,summary:`List ${e.name} (paginated)`,tags:[a],parameters:[...Dn(e),...En(e)],responses:{200:Qt(q(n)),500:z("Internal server error")}},post:{operationId:`create${re(e.name)}`,summary:`Create a ${G(e.name)}`,tags:[a],requestBody:{required:true,content:{"application/json":{schema:q(s??n)}}},responses:{201:he("Document created",q(n)),400:z("Validation error"),500:z("Internal server error")}}},o[`${d}/query`]={post:{operationId:`query${re(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[a],requestBody:{required:true,content:{"application/json":{schema:q("QueryRequestBody")}}},responses:{200:Qt(q(n)),400:z("Invalid query"),500:z("Internal server error")}}};let u={};return u.get={operationId:`get${re(G(e.name))}`,summary:`Get a single ${G(e.name)}`,tags:[a],parameters:[c],responses:{200:he("Document found",q(n)),404:z("Document not found"),500:z("Internal server error")}},u.put={operationId:`update${re(G(e.name))}`,summary:`Update a ${G(e.name)} (full replace)`,tags:[a],parameters:[c],requestBody:{required:true,content:{"application/json":{schema:q(r??n)}}},responses:{200:he("Document updated",q(n)),400:z("Validation error"),404:z("Document not found"),500:z("Internal server error")}},u.patch={operationId:`patch${re(G(e.name))}`,summary:`Partially update a ${G(e.name)}`,tags:[a],parameters:[c],requestBody:{required:true,content:{"application/json":{schema:{allOf:[q(r??n)],description:"All fields are optional for partial updates"}}}},responses:{200:he("Document patched",q(n)),400:z("Validation error"),404:z("Document not found"),500:z("Internal server error")}},e.allowDelete&&(u.delete={operationId:`delete${re(G(e.name))}`,summary:`Delete a ${G(e.name)}`,tags:[a],parameters:[c],responses:{200:he("Document deleted",{type:"object",properties:{id:{type:"string"}}}),404:z("Document not found"),500:z("Internal server error")}}),o[i]=u,o}function et(e,t,n={}){let{title:s="CRUD API",version:r="1.0.0",description:o,servers:a,auth:d=false}=n,i=t==="/"?"":t.replace(/\/$/,""),c={},u={},m=[];c.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string"}},required:["success","error"]},c.QueryRequestBody=In();for(let[h,f]of Object.entries(e)){let b=re(G(h)),x=`${b}Create`,g=`${b}Update`;c[b]=Xe(f.schema);let v=A=>{let P=A&&A.length>0?A:Object.keys(f.schema.shape),I={};for(let B of P){let j=B.split(".")[0];j&&f.schema.shape[j]&&!f.systemKeys.includes(j)&&(I[j]=f.schema.shape[j]);}return I},R=null,w=v(f.createFields);Object.keys(w).length>0&&(c[x]=Xe(zod.z.object(w)),R=x);let T=null,$=v(f.mutableFields);Object.keys($).length>0&&(c[g]=Xe(zod.z.object($)),T=g);let C=Fn(f,i,b,R,T);Object.assign(u,C),m.push({name:h,description:`Operations on ${h} (collection: ${f.path})`});}let l={},p;return d==="basic"?(l.basicAuth={type:"http",scheme:"basic"},p=[{basicAuth:[]}]):d==="bearer"&&(l.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},p=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:s,version:r,...o?{description:o}:{}},...a&&a.length>0?{servers:a}:{},paths:u,components:{schemas:c,...Object.keys(l).length>0?{securitySchemes:l}:{}},...p?{security:p}:{},tags:m}}function re(e){return e.charAt(0).toUpperCase()+e.slice(1)}function G(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 _n(e,t){return `<!DOCTYPE html>
556
556
  <html lang="en">
557
557
  <head>
558
558
  <meta charset="utf-8" />
@@ -563,5 +563,5 @@ function initColumnReorder(table) {
563
563
  <script id="api-reference" data-url="${t}"></script>
564
564
  <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
565
565
  </body>
566
- </html>`}function An(e,t){let n=t==="/"?"":t.replace(/\/$/,"");if(process.env.FUNCTIONS_EMULATOR==="true"){let o=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??"demo-project",a=process.env.FUNCTION_REGION??"us-central1",d=process.env.FUNCTION_TARGET??"";return `/${o}/${a}/${d}${n}`}let s=process.env.K_SERVICE,r=e?.hostname??e?.headers?.host??"";return s&&r.includes("cloudfunctions.net")?`/${s.toLowerCase()}${n}`:n}async function $n(e){return typeof e.rawBody=="string"?e.rawBody:Buffer.isBuffer(e.rawBody)?e.rawBody.toString("utf8"):""}function jt(e){let{basePath:t="/",repos:n,parseBody:s=true,auth:r,middleware:o=[],verbose:a=false,httpsOptions:d}=e,c=t==="/"?"":t.replace(/\/$/,""),i={};for(let[b,v]of Object.entries(n)){let g=v.schema??v.repo.schema??null;if(!g)throw new Error(`[createCrudServer] Repository "${b}" has no Zod schema. Either use createRepositoryConfig(schema)(config) or pass schema: explicitly.`);let x,R,w;if(v.fieldsConfig){let C=v.fieldsConfig;x=[],R=[],w=[];for(let[O,P]of Object.entries(C))for(let I of P)I==="filterable"?x.push(O):I==="mutable"?R.push(O):I==="create"&&w.push(O);x.length===0&&(x=void 0),R.length===0&&(R=void 0),w.length===0&&(w=void 0);}let T=(()=>{let C=v.repo._parentKeys;return C&&C.length>0?C:void 0})();if(T&&w)for(let C of T)w.includes(C)||w.push(C);let $={name:b,path:v.path,repo:v.repo,schema:g,systemKeys:v.repo._systemKeys??[v.documentKey??"docId"],documentKey:v.documentKey??"docId",pathKey:v.repo._pathKey??void 0,isGroup:!!v.repo._isGroup,parentKeys:T,createdKey:v.repo._createdKey??void 0,pageSize:v.pageSize??25,filterableFields:x,mutableFields:R,createFields:w,allowDelete:v.allowDelete??false,allowedIncludes:v.allowedIncludes,validate:v.validate};i[b]=$;}let u=_t(i,c,a),m=e.openapi,l=m&&typeof m=="object"?m:{},p=null;function y(){if(!p){let b=r&&typeof r!="function"?"basic":r?"bearer":false;p=He(i,c,{...l,auth:l.auth??b});}return p}let h=new J;if(h.use((b,v,g)=>{v.set("Access-Control-Allow-Origin","*"),v.set("Access-Control-Allow-Credentials","true"),g();}),s&&h.use(async(b,v,g)=>{let x=b;if(String(x.headers?.["content-type"]??"").includes("application/json")){if(typeof x.body=="string")try{b.body=JSON.parse(x.body);}catch{}else if(Buffer.isBuffer(b.rawBody))try{let w=await $n(x);b.body=JSON.parse(w);}catch{}}await g();}),r)if(typeof r=="function")h.use(r);else {let b=r.realm??"API",v="Basic "+Buffer.from(`${r.username}:${r.password}`).toString("base64");h.use((g,x,R)=>{if((g.headers?.authorization??"")!==v){x.status(401).set("WWW-Authenticate",`Basic realm="${b}"`).set("Content-Type","application/json").send(JSON.stringify({success:false,error:"Unauthorized"}));return}R();});}for(let b of o)h.use(b);if(m!==false){let b=`${c}/__spec.json`,v=`${c}/__docs`;h.get(b,(g,x)=>{let R=y();x.status(200).set("Content-Type","application/json; charset=utf-8").send(JSON.stringify(R,null,2));}),h.get(v,(g,x)=>{let R=An(g,c)+"/__spec.json",w=On(l.title??"CRUD API",R);x.status(200).set("Content-Type","text/html; charset=utf-8").send(w);});}h.use((b,v,g)=>{if(b.method==="OPTIONS"){u.handleOptions(b,v);return}g();}),h.get(`${c}/:repoName`,u.handleList),h.post(`${c}/:repoName/query`,u.handleQuery),h.get(`${c}/:repoName/:id`,u.handleGet),h.post(`${c}/:repoName`,u.handleCreate),h.put(`${c}/:repoName/:id`,(b,v)=>u.handleUpdate(b,v,false)),h.patch(`${c}/:repoName/:id`,(b,v)=>u.handleUpdate(b,v,true)),h.delete(`${c}/:repoName/:id`,u.handleDelete);let f=async(b,v)=>{await h.handle(b,v);};return f.spec=y,d&&(f.httpsOptions=d),f}function gs(e){return t=>({...t,schema:e,type:null,documentRef:null,update:null})}function hs(e,t){let n={...e};for(let s in t)t[s]&&(n[s]={...e[s],relationalKeys:t[s]});return n}var Ve=class{constructor(t,n){this.repositoryCache=new Map;this.allRepositories={};this.db=t,this.mapping=n,this.initializeRepositories();}initializeRepositories(){for(let t of Object.keys(this.mapping))this.allRepositories[t]=Oe(this.db,this.mapping[t],{});for(let t of Object.keys(this.mapping))this.allRepositories[t]=Oe(this.db,this.mapping[t],this.allRepositories);}getRepository(t){return this.allRepositories[t]}};function bs(e,t){let n=new Ve(e,t),s=Object.keys(t);return new Proxy(n,{get(r,o){return typeof o=="string"&&o in t?r.getRepository(o):r[o]},ownKeys(){return s},getOwnPropertyDescriptor(r,o){if(typeof o=="string"&&o in t)return {configurable:true,enumerable:true,writable:false}}})}exports.MiniRouter=J;exports.RepositoryMapping=Ve;exports.applyPaginationQueryOptions=X;exports.buildAndExecuteQuery=se;exports.buildRepositoryRelations=hs;exports.createAdminServer=kt;exports.createCrudServer=jt;exports.createPaginationIterator=Ce;exports.createRepositoryConfig=gs;exports.createRepositoryMapping=bs;exports.executePaginatedQuery=ve;//# sourceMappingURL=index.cjs.map
566
+ </html>`}function Nn(e,t){let n=t==="/"?"":t.replace(/\/$/,"");if(process.env.FUNCTIONS_EMULATOR==="true"){let o=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??"demo-project",a=process.env.FUNCTION_REGION??"us-central1",d=process.env.FUNCTION_TARGET??"";return `/${o}/${a}/${d}${n}`}let s=process.env.K_SERVICE,r=e?.hostname??e?.headers?.host??"";return s&&r.includes("cloudfunctions.net")?`/${s.toLowerCase()}${n}`:n}async function jn(e){return typeof e.rawBody=="string"?e.rawBody:Buffer.isBuffer(e.rawBody)?e.rawBody.toString("utf8"):""}function qt(e){let{basePath:t="/",repos:n,parseBody:s=true,auth:r,middleware:o=[],verbose:a=false,httpsOptions:d}=e,i=t==="/"?"":t.replace(/\/$/,""),c={};for(let[b,x]of Object.entries(n)){let g=x.schema??x.repo.schema??null;if(!g)throw new Error(`[createCrudServer] Repository "${b}" has no Zod schema. Either use createRepositoryConfig(schema)(config) or pass schema: explicitly.`);let v,R,w;if(x.fieldsConfig){let C=x.fieldsConfig;v=[],R=[],w=[];for(let[A,P]of Object.entries(C))for(let I of P)I==="filterable"?v.push(A):I==="mutable"?R.push(A):I==="create"&&w.push(A);v.length===0&&(v=void 0),R.length===0&&(R=void 0),w.length===0&&(w=void 0);}let T=(()=>{let C=x.repo._parentKeys;return C&&C.length>0?C:void 0})();if(T&&w)for(let C of T)w.includes(C)||w.push(C);let $={name:b,path:x.path,repo:x.repo,schema:g,systemKeys:x.repo._systemKeys??[x.documentKey??"docId"],documentKey:x.documentKey??"docId",pathKey:x.repo._pathKey??void 0,isGroup:!!x.repo._isGroup,parentKeys:T,createdKey:x.repo._createdKey??void 0,pageSize:x.pageSize??25,filterableFields:v,mutableFields:R,createFields:w,allowDelete:x.allowDelete??false,allowedIncludes:x.allowedIncludes,validate:x.validate};c[b]=$;}let u=Bt(c,i,a),m=e.openapi,l=m&&typeof m=="object"?m:{},p=null;function y(){if(!p){let b=r&&typeof r!="function"?"basic":r?"bearer":false;p=et(c,i,{...l,auth:l.auth??b});}return p}let h=new J;if(h.use((b,x,g)=>{x.set("Access-Control-Allow-Origin","*"),x.set("Access-Control-Allow-Credentials","true"),g();}),s&&h.use(async(b,x,g)=>{let v=b;if(String(v.headers?.["content-type"]??"").includes("application/json")){if(typeof v.body=="string")try{b.body=JSON.parse(v.body);}catch{}else if(Buffer.isBuffer(b.rawBody))try{let w=await jn(v);b.body=JSON.parse(w);}catch{}}await g();}),r)if(typeof r=="function")h.use(r);else {let b=r.realm??"API",x="Basic "+Buffer.from(`${r.username}:${r.password}`).toString("base64");h.use((g,v,R)=>{if((g.headers?.authorization??"")!==x){v.status(401).set("WWW-Authenticate",`Basic realm="${b}"`).set("Content-Type","application/json").send(JSON.stringify({success:false,error:"Unauthorized"}));return}R();});}for(let b of o)h.use(b);if(m!==false){let b=`${i}/__spec.json`,x=`${i}/__docs`;h.get(b,(g,v)=>{let R=y();v.status(200).set("Content-Type","application/json; charset=utf-8").send(JSON.stringify(R,null,2));}),h.get(x,(g,v)=>{let R=Nn(g,i)+"/__spec.json",w=_n(l.title??"CRUD API",R);v.status(200).set("Content-Type","text/html; charset=utf-8").send(w);});}h.use((b,x,g)=>{if(b.method==="OPTIONS"){u.handleOptions(b,x);return}g();}),h.get(`${i}/:repoName`,u.handleList),h.post(`${i}/:repoName/query`,u.handleQuery),h.get(`${i}/:repoName/:id`,u.handleGet),h.post(`${i}/:repoName`,u.handleCreate),h.put(`${i}/:repoName/:id`,(b,x)=>u.handleUpdate(b,x,false)),h.patch(`${i}/:repoName/:id`,(b,x)=>u.handleUpdate(b,x,true)),h.delete(`${i}/:repoName/:id`,u.handleDelete);let f=async(b,x)=>{await h.handle(b,x);};return f.spec=y,d&&(f.httpsOptions=d),f}function Cs(e){return t=>({...t,schema:e,type:null,documentRef:null,update:null})}function As(e,t){let n={...e};for(let s in t)t[s]&&(n[s]={...e[s],relationalKeys:t[s]});return n}var tt=class{constructor(t,n){this.repositoryCache=new Map;this.allRepositories={};this.db=t,this.mapping=n,this.initializeRepositories();}initializeRepositories(){for(let t of Object.keys(this.mapping))this.allRepositories[t]=Oe(this.db,this.mapping[t],{});for(let t of Object.keys(this.mapping))this.allRepositories[t]=Oe(this.db,this.mapping[t],this.allRepositories);}getRepository(t){return this.allRepositories[t]}};function Os(e,t){let n=new tt(e,t),s=Object.keys(t);return new Proxy(n,{get(r,o){return typeof o=="string"&&o in t?r.getRepository(o):r[o]},ownKeys(){return s},getOwnPropertyDescriptor(r,o){if(typeof o=="string"&&o in t)return {configurable:true,enumerable:true,writable:false}}})}exports.MiniRouter=J;exports.RepositoryMapping=tt;exports.applyPaginationQueryOptions=X;exports.buildAndExecuteQuery=se;exports.buildRepositoryRelations=As;exports.createAdminServer=Nt;exports.createCrudServer=qt;exports.createPaginationIterator=Ae;exports.createRepositoryConfig=Cs;exports.createRepositoryMapping=Os;exports.executePaginatedQuery=xe;//# sourceMappingURL=index.cjs.map
567
567
  //# sourceMappingURL=index.cjs.map