@lpdjs/firestore-repo-service 2.2.1 → 2.2.3
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/README.md +111 -529
- package/dist/{index-BJQXYHTC.d.ts → index-Bw1fvzu5.d.ts} +8 -4
- package/dist/{index-BjH87AI4.d.cts → index-bqqrGjxe.d.cts} +8 -4
- package/dist/index.cjs +3 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -3
- package/dist/index.d.ts +4 -3
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/servers/admin/index.cjs +2 -2
- package/dist/servers/admin/index.cjs.map +1 -1
- package/dist/servers/admin/index.d.cts +3 -2
- package/dist/servers/admin/index.d.ts +3 -2
- package/dist/servers/admin/index.js +2 -2
- package/dist/servers/admin/index.js.map +1 -1
- package/dist/servers/crud/index.cjs +2 -2
- package/dist/servers/crud/index.cjs.map +1 -1
- package/dist/servers/crud/index.d.cts +4 -3
- package/dist/servers/crud/index.d.ts +4 -3
- package/dist/servers/crud/index.js +2 -2
- package/dist/servers/crud/index.js.map +1 -1
- package/dist/servers/index.cjs +6 -6
- package/dist/servers/index.cjs.map +1 -1
- package/dist/servers/index.d.cts +4 -3
- package/dist/servers/index.d.ts +4 -3
- package/dist/servers/index.js +6 -6
- package/dist/servers/index.js.map +1 -1
- package/dist/{types-CYVwoOQx.d.cts → types-DKgWRTDf.d.cts} +7 -3
- package/dist/{types-CYVwoOQx.d.ts → types-DKgWRTDf.d.ts} +7 -3
- package/package.json +1 -1
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
-
import {
|
|
2
|
+
import { HttpsOptions } from 'firebase-functions/v2/https';
|
|
3
|
+
import { C as ConfiguredRepository, R as RepositoryConfig, F as FieldPath, n as FieldRole } from './types-DKgWRTDf.js';
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* Minimal zero-dependency HTTP router for Firebase Functions.
|
|
@@ -273,9 +274,12 @@ type RepoRegistry = Record<string, AdminRepoEntry>;
|
|
|
273
274
|
|
|
274
275
|
/**
|
|
275
276
|
* Extracts the model type `T` from a `ConfiguredRepository`.
|
|
277
|
+
* Two-step inference so it survives intersection types
|
|
278
|
+
* (e.g. `RepositoryConfig<...> & { schema: ZodObject }` produced by
|
|
279
|
+
* `createRepositoryConfig(schema)`).
|
|
276
280
|
* @internal
|
|
277
281
|
*/
|
|
278
|
-
type RepoModelType<TRepo> = TRepo extends ConfiguredRepository<RepositoryConfig<infer T, any, any, any, any, any, any, any, any, any
|
|
282
|
+
type RepoModelType<TRepo> = TRepo extends ConfiguredRepository<infer C> ? C extends RepositoryConfig<infer T, any, any, any, any, any, any, any, any, any> ? T : never : never;
|
|
279
283
|
/**
|
|
280
284
|
* Configuration for a single repository in the admin server.
|
|
281
285
|
*
|
|
@@ -440,7 +444,7 @@ interface AdminServerOptions<TRepos extends Record<string, ConfiguredRepository<
|
|
|
440
444
|
* export const admin = onRequest(handler.httpsOptions!, handler);
|
|
441
445
|
* ```
|
|
442
446
|
*/
|
|
443
|
-
httpsOptions?:
|
|
447
|
+
httpsOptions?: HttpsOptions;
|
|
444
448
|
}
|
|
445
449
|
/**
|
|
446
450
|
* Creates an Express-compatible request handler for the admin ORM UI.
|
|
@@ -555,7 +559,7 @@ interface AdminServerOptions<TRepos extends Record<string, ConfiguredRepository<
|
|
|
555
559
|
* ```
|
|
556
560
|
*/
|
|
557
561
|
declare function createAdminServer<TRepos extends Record<string, ConfiguredRepository<any>>>(options: AdminServerOptions<TRepos>): ((req: any, res: any) => Promise<void>) & {
|
|
558
|
-
httpsOptions?:
|
|
562
|
+
httpsOptions?: HttpsOptions;
|
|
559
563
|
};
|
|
560
564
|
|
|
561
565
|
export { type AdminRepoConfig as A, type BasicAuthConfig as B, type ColumnMeta as C, type FilterState as F, MiniRouter as M, type PageOptions as P, type QueryError as Q, type RelationalFieldMeta as R, type SortState as S, type AdminRepoEntry as a, type AdminServerOptions as b, createAdminServer as c, type Middleware as d, type RepoRegistry as e, type RouteHandler as f };
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
-
import {
|
|
2
|
+
import { HttpsOptions } from 'firebase-functions/v2/https';
|
|
3
|
+
import { C as ConfiguredRepository, R as RepositoryConfig, F as FieldPath, n as FieldRole } from './types-DKgWRTDf.cjs';
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* Minimal zero-dependency HTTP router for Firebase Functions.
|
|
@@ -273,9 +274,12 @@ type RepoRegistry = Record<string, AdminRepoEntry>;
|
|
|
273
274
|
|
|
274
275
|
/**
|
|
275
276
|
* Extracts the model type `T` from a `ConfiguredRepository`.
|
|
277
|
+
* Two-step inference so it survives intersection types
|
|
278
|
+
* (e.g. `RepositoryConfig<...> & { schema: ZodObject }` produced by
|
|
279
|
+
* `createRepositoryConfig(schema)`).
|
|
276
280
|
* @internal
|
|
277
281
|
*/
|
|
278
|
-
type RepoModelType<TRepo> = TRepo extends ConfiguredRepository<RepositoryConfig<infer T, any, any, any, any, any, any, any, any, any
|
|
282
|
+
type RepoModelType<TRepo> = TRepo extends ConfiguredRepository<infer C> ? C extends RepositoryConfig<infer T, any, any, any, any, any, any, any, any, any> ? T : never : never;
|
|
279
283
|
/**
|
|
280
284
|
* Configuration for a single repository in the admin server.
|
|
281
285
|
*
|
|
@@ -440,7 +444,7 @@ interface AdminServerOptions<TRepos extends Record<string, ConfiguredRepository<
|
|
|
440
444
|
* export const admin = onRequest(handler.httpsOptions!, handler);
|
|
441
445
|
* ```
|
|
442
446
|
*/
|
|
443
|
-
httpsOptions?:
|
|
447
|
+
httpsOptions?: HttpsOptions;
|
|
444
448
|
}
|
|
445
449
|
/**
|
|
446
450
|
* Creates an Express-compatible request handler for the admin ORM UI.
|
|
@@ -555,7 +559,7 @@ interface AdminServerOptions<TRepos extends Record<string, ConfiguredRepository<
|
|
|
555
559
|
* ```
|
|
556
560
|
*/
|
|
557
561
|
declare function createAdminServer<TRepos extends Record<string, ConfiguredRepository<any>>>(options: AdminServerOptions<TRepos>): ((req: any, res: any) => Promise<void>) & {
|
|
558
|
-
httpsOptions?:
|
|
562
|
+
httpsOptions?: HttpsOptions;
|
|
559
563
|
};
|
|
560
564
|
|
|
561
565
|
export { type AdminRepoConfig as A, type BasicAuthConfig as B, type ColumnMeta as C, type FilterState as F, MiniRouter as M, type PageOptions as P, type QueryError as Q, type RelationalFieldMeta as R, type SortState as S, type AdminRepoEntry as a, type AdminServerOptions as b, createAdminServer as c, type Middleware as d, type RepoRegistry as e, type RouteHandler as f };
|
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';var firestore=require('firebase-admin/firestore'),zod=require('zod'),jsxRuntime=require('hono/jsx/jsx-runtime'),server=require('hono/jsx/dom/server');function an(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function ge(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 Ie(e){let[,t,n]=e;return (t==="in"||t==="array-contains-any")&&Array.isArray(n)&&n.length>30}function ft(e){let[t,n,r]=e;return Ie(e)?an(r,30).map(s=>[t,n,s]):[e]}function Oe(e,t){let n=e;for(let[r,o,s]of t)n=n.where(String(r),o,s);return n}async function yt(e){let t=await Promise.all(e.map(o=>o.get())),n=new Map;t.forEach(o=>{o.docs.forEach(s=>{n.has(s.id)||n.set(s.id,s);});});let r=t[0];if(!r)throw new Error("No snapshots returned");return {...r,docs:Array.from(n.values()),size:n.size,empty:n.size===0}}async function ae(e,t){let n=t.orWhere&&t.orWhere.length>0,r=t.orWhereGroups&&t.orWhereGroups.length>0;if(!n&&!r){if(!t.where||t.where.length===0)return ge(e,t).get();if(!t.where.some(Ie)){let m=Oe(e,t.where);return m=ge(m,t),m.get()}let i=t.where.map(ft),u=Ne(i).map(m=>{let c=Oe(e,m);return c=ge(c,t),c});return yt(u)}let o=t.where??[],s=[...t.orWhere?.map(d=>[d])??[],...t.orWhereGroups??[]],a=[];for(let d of s){let i=[...o,...d];if(i.some(Ie)){let u=i.map(ft),c=Ne(u).map(p=>{let y=Oe(e,p);return y=ge(y,t),y});a.push(...c);}else {let u=Oe(e,i);u=ge(u,t),a.push(u);}}return yt(a)}function Ne(e){if(e.length===0)return [[]];let t=e[0];if(e.length===1&&t)return t.map(s=>[s]);if(!t)return [[]];let n=e.slice(1),r=Ne(n),o=[];for(let s of t)for(let a of r)o.push([s,...a]);return o}var Fe="preserve";function ln(e){Fe=e;}function Ze(){return Fe}function cn(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function ze(e){if(e==null)return null;if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(e instanceof firestore.Timestamp)return e.toDate();if(cn(e))return new Date(e._seconds*1e3+Math.floor(e._nanoseconds/1e6));if(typeof e=="string"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}if(typeof e=="number"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null}function dn(e){if(typeof e!="object"||e===null)return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Ae(e){if(e instanceof firestore.Timestamp)return e.toDate();if(Array.isArray(e))return e.map(t=>Ae(t));if(dn(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=Ae(r);return t}return e}function _(e){return Fe==="normalize"?Ae(e):e}function gt(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function J(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Y(e,t){return t.where&&t.where.forEach(([n,r,o])=>{e=e.where(String(n),r,o);}),t.orderBy&&t.orderBy.forEach(n=>{e=e.orderBy(String(n.field),n.direction??"asc");}),t.limit&&(e=e.limit(t.limit)),t.offset&&(e=e.offset(t.offset)),t.select&&t.select.length>0&&(e=e.select(...t.select.map(n=>String(n)))),t.startAt&&(e=Array.isArray(t.startAt)?e.startAt(...t.startAt):e.startAt(t.startAt)),t.startAfter&&(e=Array.isArray(t.startAfter)?e.startAfter(...t.startAfter):e.startAfter(t.startAfter)),t.endAt&&(e=Array.isArray(t.endAt)?e.endAt(...t.endAt):e.endAt(t.endAt)),t.endBefore&&(e=Array.isArray(t.endBefore)?e.endBefore(...t.endBefore):e.endBefore(t.endBefore)),e}async function ke(e,t){let n={...t,limit:t.pageSize+1};t.cursor&&(t.direction==="prev"?n.endBefore=t.cursor:n.startAfter=t.cursor);let o=(await ae(e,n)).docs,s=o.length>t.pageSize,a=s?o.slice(0,t.pageSize):o,d=a.map(l=>_({...l.data(),docId:l.id})),i=t.direction==="prev";return {data:d,nextCursor:i?a.length>0?a[a.length-1]:void 0:s?a[a.length-1]:void 0,prevCursor:i?s?a[0]:void 0:a[0],hasNextPage:i?!!t.cursor:s,hasPrevPage:i?s:!!t.cursor,pageSize:d.length}}async function*je(e,t){let n,r=true;for(;r;){let o=await ke(e,{...t,cursor:n,direction:"next"});yield o,r=o.hasNextPage,n=o.nextCursor;}}function ht(e){return {count:async(t={})=>{let n=e;return n=Y(n,t),(await n.count().get()).data().count},sum:async(t,n={})=>{let r=e;r=Y(r,n);let o=await r.get(),s=0;return o.forEach(a=>{let d=a.data()[t];typeof d=="number"&&(s+=d);}),s},average:async(t,n={})=>{let r=e;r=Y(r,n);let o=await r.get();if(o.empty)return null;let s=0,a=0;return o.forEach(d=>{let i=d.data()[t];typeof i=="number"&&(s+=i,a++);}),a>0?s/a:null}}}function bt(e,t,n,r,o,s){let a=()=>new Date;return {create:()=>{let d=e.batch();return {batch:d,set:(...i)=>{let l=i[i.length-1],u=typeof l=="object"&&l!==null&&"merge"in l,m=u?i[i.length-2]:i[i.length-1],c=u?i.slice(0,-2):i.slice(0,-1),p=u?l:{merge:true},y=t(...c),g={...m},f=c[c.length-1];n&&f&&(g[n]=f),r&&(g[r]=y.path),o&&(g[o]=a()),s&&(g[s]=a()),d.set(y,g,p);},update:(...i)=>{let l=i.pop(),m=t(...i),c={...l};s&&(c[s]=a()),d.update(m,c);},delete:(...i)=>{let l=t(...i);d.delete(l);},commit:async()=>{await d.commit();}}}}}function xt(e,t,n){let r=()=>new Date;return {set:async o=>{let s=e.bulkWriter(),a=0;for(let d of o){if(!d)continue;let{docRef:i,data:l,merge:u=true}=d,m={...l};t&&(m[t]=r()),n&&(m[n]=r()),s.set(i,m,{merge:u}),a++,a>=500&&(await s.flush(),a=0);}await s.close();},update:async o=>{let s=e.bulkWriter(),a=0;for(let d of o){if(!d)continue;let{docRef:i,data:l}=d,u={...l};n&&(u[n]=r()),s.update(i,u),a++,a>=500&&(await s.flush(),a=0);}await s.close();},delete:async o=>{let s=e.bulkWriter(),a=0;for(let d of o)d&&(s.delete(d),a++,a>=500&&(await s.flush(),a=0));await s.close();}}}function vt(e,t,n,r,o,s){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 c,p,y={...m};if(o&&(y[o]=a()),s&&(y[s]=a()),m[n]){p=m[n],c=e.doc(p);let f=r?{...y,[r]:c.path}:y;await c.set(f);}else {c=await e.add(y),p=c.id;let f={[n]:p};r&&(f[r]=c.path),await c.update(f);}let g=await c.get();return _(g.data())},set:async(...m)=>{let c=m[m.length-1],p=typeof c=="object"&&c!==null&&"merge"in c,y=p?m[m.length-2]:m[m.length-1],g=p?m.slice(0,-2):m.slice(0,-1),f=p?c:{merge:true},b={...y};s&&(b[s]=a());let x=t(...g),h=g[g.length-1];n&&h!=null&&(b[n]=h),r&&(b[r]=x.path),await x.set(b,f);let v=await x.get();return _(v.data())},update:async(...m)=>{let c=m.pop(),p=m,y={...c};s&&(y[s]=a());let g=t(...p);await g.update(y);let f=await g.get();return _(f.data())},delete:async(...m)=>{await t(...m).delete();}}}function Rt(e,t,n,r,o){let s={};return s.byList=async(a,d,i="in",l={})=>{if(d.length===0)return [];let u=[],m=gt(d,30);for(let c of m){let p=e;p=p.where(a,i,c),l.select&&l.select.length>0&&(p=p.select(...l.select.map(g=>String(g)))),(await p.get()).forEach(g=>{let f=_(g.data());u.push(l.returnDoc?{data:f,doc:g}:f);});}return u},t.forEach(a=>{let d=`by${J(String(a))}`;s[d]=async(i,l={})=>{let u=typeof l=="boolean"?{returnDoc:l}:l;if(String(a)===o){let f=await r(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(g=>String(g))));let c=await m.get();if(c.empty)return null;let p=c.docs[0];if(!p)return null;let y=_(p.data());return u.returnDoc?{data:y,doc:p}:y};}),s}function wt(e,t,n,r){let o={},s=async(a,d)=>{if(!n||!r||d.length===0)return a;let i=d.map(l=>typeof l=="string"?{key:l}:{key:l.relation,select:l.select});return Promise.all(a.map(async l=>{let u=await Promise.all(i.map(async({key:c,select:p})=>{let y=n[c];if(!y)return [c,void 0];let g=r[y.repo];if(!g)return [c,void 0];let f=l[c];if(f==null)return [c,y.type==="one"?null:[]];let b=p?{select:p}:void 0;try{if(y.type==="one"){let x=`by${J(y.key)}`,h=typeof g.get?.[x]=="function"?await g.get[x](f,b):null;return [c,h]}else {let x=`by${J(y.key)}`,h=typeof g.query?.[x]=="function"?await g.query[x](f,b):[];return [c,h]}}catch(x){return console.error(`[include] Error populating "${c}":`,x),[c,y.type==="one"?null:[]]}})),m={};for(let[c,p]of u)c!==void 0&&(m[c]=p);return {...l,populated:m}}))};return t.forEach(a=>{let d=`by${J(a)}`;o[d]=async(i,l={})=>{let u={...l,where:[[a,"==",i],...l.where??[]]};return (await ae(e,u)).docs.map(c=>_(c.data()))};}),o.by=async a=>(await ae(e,a)).docs.map(i=>_(i.data())),o.getAll=async(a={})=>(await ae(e,a)).docs.map(i=>_(i.data())),o.onSnapshot=(a,d,i)=>Y(e,a).onSnapshot(u=>{d(u.docs.map(m=>_(m.data())));},i),o.paginate=async a=>{let{include:d,...i}=a,l=await ke(e,i);if(d&&d.length>0){let u=await s(l.data,d);return {...l,data:u}}return l},o.paginateAll=async function*(a){let{include:d,...i}=a;for await(let l of je(e,i))if(d&&d.length>0){let u=await s(l.data,d);yield {...l,data:u};}else yield l;},o}function Tt(e,t){return {populate:async(n,r)=>{if(!e.relationalKeys)return {...n,populated:{}};let o,s={};if(typeof r=="object"&&!Array.isArray(r))if("relation"in r){let i=r;o=[i.relation],i.select&&(s[i.relation]=i.select);}else if("relations"in r){let i=r;o=Array.isArray(i.relations)?i.relations:[i.relations],s=i.select??{};}else o=[];else o=Array.isArray(r)?r:[r];let a=await Promise.all(o.map(async i=>{let l=e.relationalKeys?.[i];if(!l)return console.warn(`[populate] Relation "${i}" not found in config`),[i,void 0];let u=t[l.repo];if(!u)return console.warn(`[populate] Repository "${l.repo}" not found in mapping`),[i,void 0];let m=n[i];if(m==null)return [i,l.type==="one"?null:[]];let c=s[i],p=c?{select:c}:void 0;try{if(l.type==="one"){let y=`by${J(l.key)}`,g=typeof u.get?.[y]=="function"?await u.get[y](m,p):null;return [i,g]}else {let y=`by${J(l.key)}`,g=typeof u.query?.[y]=="function"?await u.query[y](m,p):[];return [i,g]}}catch(y){return console.error(`[populate] Error populating "${i}":`,y),[i,l.type==="one"?null:[]]}})),d={};for(let[i,l]of a)l!==void 0&&(d[i]=l);return {...n,populated:d}}}}function St(e,t){return {run:async n=>e.runTransaction(async r=>n({get:async(...s)=>{let a=t(...s),d=await r.get(a);return d.exists?_({...d.data(),docId:d.id}):null},set:(...s)=>{let a=s[s.length-1],d=typeof a=="object"&&a!==null&&"merge"in a,i=d?s[s.length-2]:s[s.length-1],l=d?s.slice(0,-2):s.slice(0,-1),u=d?a:{merge:true},m=t(...l);r.set(m,i,u);},update:(...s)=>{let a=s[s.length-1],d=s.slice(0,-1),i=t(...d);r.update(i,a);},delete:(...s)=>{let a=t(...s);r.delete(a);},raw:r}))}}function un(e){if(typeof e!="function")return [];let n=e.toString().match(/^\s*(?:function\s*\w*\s*)?\(([^)]*)\)/);if(!n?.[1])return [];let r=n[1].split(",").map(o=>o.trim().replace(/\s*[:=].*$/,"").trim()).filter(Boolean);return r.length<=2?[]:r.slice(1,-1)}function Me(e,t,n={}){let r=t.isGroup?e.collectionGroup(t.path):e.collection(t.path),o=t.isGroup?null:e.collection(t.path),s=(...y)=>t.refCb(e,...y),a=Rt(r,t.foreignKeys,o,s,t.documentKey),d=wt(r,t.queryKeys,t.relationalKeys,n),i=ht(r),l=vt(o,s,t.documentKey,t.pathKey,t.createdKey,t.updatedKey),u=bt(e,s,t.documentKey,t.pathKey,t.createdKey,t.updatedKey),m=St(e,s),c=xt(e,t.createdKey,t.updatedKey),p=Tt(t,n);return {ref:r,documentRef:s,get:a,query:d,aggregate:i,...l,batch:u,transaction:m,bulk:c,...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?un(t.refCb):[],_createdKey:t.createdKey??null}}var pn={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 pn[n]??`Zod${n.charAt(0).toUpperCase()}${n.slice(1)}`;let r=t._def?.typeName;return r||""}function K(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 Ot(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 he(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 be(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 xe(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 $e(e){let t=e;return Array.isArray(t._zod?.def?.values)?t._zod.def.values[0]:t._def?.value}function At(e){let t=e,n=[],r=t._zod?.def?.checks;if(Array.isArray(r)){for(let s of r)s.format&&n.push(s.format);if(n.length>0)return n}let o=t._def?.checks;if(Array.isArray(o))for(let s of o)s.kind&&n.push(s.kind);return n}function fn(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/^\s/,"").replace(/^./,t=>t.toUpperCase())}function kt(e){let t=e,n=true,r=false,o;for(;;){let s=Z(t);if(s==="ZodOptional")n=false,t=K(t);else if(s==="ZodNullable")n=false,r=true,t=K(t);else if(s==="ZodDefault")n=false,o=Ot(t),t=K(t);else break}return {inner:t,required:n,nullable:r,defaultValue:o}}function W(e,t=""){if(Z(e)==="ZodObject"){let r=he(e);return Object.entries(r).map(([o,s])=>$t(t?`${t}.${o}`:o,o,s))}return [$t(t||"value",t||"value",e)]}function $t(e,t,n){let{inner:r,required:o,nullable:s,defaultValue:a}=kt(n),d=Z(r),i=fn(t.split(".").pop()??t);switch(d){case "ZodString":{let l=At(r),u=l.includes("email"),m=l.includes("url");return {name:e,label:i,type:"text",required:o,nullable:s,defaultValue:a,hint:u?"email":m?"url":void 0}}case "ZodNumber":case "ZodBigInt":return {name:e,label:i,type:"number",required:o,nullable:s,defaultValue:a};case "ZodBoolean":return {name:e,label:i,type:"checkbox",required:o,nullable:s,defaultValue:a};case "ZodDate":case "ZodCoerce":return {name:e,label:i,type:"datetime-local",required:o,nullable:s,defaultValue:a};case "ZodEnum":{let l=be(r);return {name:e,label:i,type:"select",required:o,nullable:s,defaultValue:a,options:l}}case "ZodNativeEnum":{let l=xe(r),u=Object.values(l).filter(m=>typeof m=="string");return {name:e,label:i,type:"select",required:o,nullable:s,defaultValue:a,options:u}}case "ZodLiteral":{let l=String($e(r)??"");return {name:e,label:i,type:"select",required:o,nullable:s,defaultValue:a,options:[l]}}case "ZodObject":{let l=W(r,e);return {name:e,label:i,type:"textarea",required:o,nullable:s,defaultValue:a,nested:l,hint:"JSON object"}}case "ZodArray":{let l=Ct(r);if(!l)return {name:e,label:i,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON array"};let{inner:u}=kt(l),m=Z(u),c,p,y;switch(m){case "ZodString":c="text";break;case "ZodNumber":case "ZodBigInt":c="number";break;case "ZodBoolean":c="checkbox";break;case "ZodDate":c="datetime-local";break;case "ZodEnum":c="select",p=be(u);break;case "ZodNativeEnum":c="select",p=Object.values(xe(u)).filter(g=>typeof g=="string");break;case "ZodObject":c="object",y=W(u);break;default:return {name:e,label:i,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON array"}}return {name:e,label:i,type:"textarea",required:o,nullable:s,defaultValue:a,arrayElementType:c,arrayElementOptions:p,arrayElementFields:y}}default:return {name:e,label:i,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON"}}}function Be(e,t=0){let n=t>0?`ml-${t*4}`:"",r=`field_${e.name.replace(/\./g,"__")}`,o=e.name,s=e.required?" required":"",a=e.defaultValue==="__null__",d=!a&&e.defaultValue!=null?String(e.defaultValue):"",i=e.nullable&&e.type!=="checkbox"?`<span class="flex items-center gap-1 shrink-0">
|
|
1
|
+
'use strict';var firestore=require('firebase-admin/firestore'),zod=require('zod'),jsxRuntime=require('hono/jsx/jsx-runtime'),server=require('hono/jsx/dom/server');function an(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function ge(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 Ie(e){let[,t,n]=e;return (t==="in"||t==="array-contains-any")&&Array.isArray(n)&&n.length>30}function ft(e){let[t,n,r]=e;return Ie(e)?an(r,30).map(s=>[t,n,s]):[e]}function Oe(e,t){let n=e;for(let[r,o,s]of t)n=n.where(String(r),o,s);return n}async function yt(e){let t=await Promise.all(e.map(o=>o.get())),n=new Map;t.forEach(o=>{o.docs.forEach(s=>{n.has(s.id)||n.set(s.id,s);});});let r=t[0];if(!r)throw new Error("No snapshots returned");return {...r,docs:Array.from(n.values()),size:n.size,empty:n.size===0}}async function ae(e,t){let n=t.orWhere&&t.orWhere.length>0,r=t.orWhereGroups&&t.orWhereGroups.length>0;if(!n&&!r){if(!t.where||t.where.length===0)return ge(e,t).get();if(!t.where.some(Ie)){let m=Oe(e,t.where);return m=ge(m,t),m.get()}let i=t.where.map(ft),u=Ne(i).map(m=>{let c=Oe(e,m);return c=ge(c,t),c});return yt(u)}let o=t.where??[],s=[...t.orWhere?.map(d=>[d])??[],...t.orWhereGroups??[]],a=[];for(let d of s){let i=[...o,...d];if(i.some(Ie)){let u=i.map(ft),c=Ne(u).map(p=>{let y=Oe(e,p);return y=ge(y,t),y});a.push(...c);}else {let u=Oe(e,i);u=ge(u,t),a.push(u);}}return yt(a)}function Ne(e){if(e.length===0)return [[]];let t=e[0];if(e.length===1&&t)return t.map(s=>[s]);if(!t)return [[]];let n=e.slice(1),r=Ne(n),o=[];for(let s of t)for(let a of r)o.push([s,...a]);return o}var Fe="preserve";function ln(e){Fe=e;}function Ze(){return Fe}function cn(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function ze(e){if(e==null)return null;if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(e instanceof firestore.Timestamp)return e.toDate();if(cn(e))return new Date(e._seconds*1e3+Math.floor(e._nanoseconds/1e6));if(typeof e=="string"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}if(typeof e=="number"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null}function dn(e){if(typeof e!="object"||e===null)return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Ae(e){if(e instanceof firestore.Timestamp)return e.toDate();if(Array.isArray(e))return e.map(t=>Ae(t));if(dn(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=Ae(r);return t}return e}function _(e){return Fe==="normalize"?Ae(e):e}function gt(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function J(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Y(e,t){return t.where&&t.where.forEach(([n,r,o])=>{e=e.where(String(n),r,o);}),t.orderBy&&t.orderBy.forEach(n=>{e=e.orderBy(String(n.field),n.direction??"asc");}),t.limit&&(e=e.limit(t.limit)),t.offset&&(e=e.offset(t.offset)),t.select&&t.select.length>0&&(e=e.select(...t.select.map(n=>String(n)))),t.startAt&&(e=Array.isArray(t.startAt)?e.startAt(...t.startAt):e.startAt(t.startAt)),t.startAfter&&(e=Array.isArray(t.startAfter)?e.startAfter(...t.startAfter):e.startAfter(t.startAfter)),t.endAt&&(e=Array.isArray(t.endAt)?e.endAt(...t.endAt):e.endAt(t.endAt)),t.endBefore&&(e=Array.isArray(t.endBefore)?e.endBefore(...t.endBefore):e.endBefore(t.endBefore)),e}async function $e(e,t){let n={...t,limit:t.pageSize+1};t.cursor&&(t.direction==="prev"?n.endBefore=t.cursor:n.startAfter=t.cursor);let o=(await ae(e,n)).docs,s=o.length>t.pageSize,a=s?o.slice(0,t.pageSize):o,d=a.map(l=>_({...l.data(),docId:l.id})),i=t.direction==="prev";return {data:d,nextCursor:i?a.length>0?a[a.length-1]:void 0:s?a[a.length-1]:void 0,prevCursor:i?s?a[0]:void 0:a[0],hasNextPage:i?!!t.cursor:s,hasPrevPage:i?s:!!t.cursor,pageSize:d.length}}async function*je(e,t){let n,r=true;for(;r;){let o=await $e(e,{...t,cursor:n,direction:"next"});yield o,r=o.hasNextPage,n=o.nextCursor;}}function ht(e){return {count:async(t={})=>{let n=e;return n=Y(n,t),(await n.count().get()).data().count},sum:async(t,n={})=>{let r=e;r=Y(r,n);let o=await r.get(),s=0;return o.forEach(a=>{let d=a.data()[t];typeof d=="number"&&(s+=d);}),s},average:async(t,n={})=>{let r=e;r=Y(r,n);let o=await r.get();if(o.empty)return null;let s=0,a=0;return o.forEach(d=>{let i=d.data()[t];typeof i=="number"&&(s+=i,a++);}),a>0?s/a:null}}}function bt(e,t,n,r,o,s){let a=()=>new Date;return {create:()=>{let d=e.batch();return {batch:d,set:(...i)=>{let l=i[i.length-1],u=typeof l=="object"&&l!==null&&"merge"in l,m=u?i[i.length-2]:i[i.length-1],c=u?i.slice(0,-2):i.slice(0,-1),p=u?l:{merge:true},y=t(...c),g={...m},f=c[c.length-1];n&&f&&(g[n]=f),r&&(g[r]=y.path),o&&(g[o]=a()),s&&(g[s]=a()),d.set(y,g,p);},update:(...i)=>{let l=i.pop(),m=t(...i),c={...l};s&&(c[s]=a()),d.update(m,c);},delete:(...i)=>{let l=t(...i);d.delete(l);},commit:async()=>{await d.commit();}}}}}function xt(e,t,n){let r=()=>new Date;return {set:async o=>{let s=e.bulkWriter(),a=0;for(let d of o){if(!d)continue;let{docRef:i,data:l,merge:u=true}=d,m={...l};t&&(m[t]=r()),n&&(m[n]=r()),s.set(i,m,{merge:u}),a++,a>=500&&(await s.flush(),a=0);}await s.close();},update:async o=>{let s=e.bulkWriter(),a=0;for(let d of o){if(!d)continue;let{docRef:i,data:l}=d,u={...l};n&&(u[n]=r()),s.update(i,u),a++,a>=500&&(await s.flush(),a=0);}await s.close();},delete:async o=>{let s=e.bulkWriter(),a=0;for(let d of o)d&&(s.delete(d),a++,a>=500&&(await s.flush(),a=0));await s.close();}}}function vt(e,t,n,r,o,s){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 c,p,y={...m};if(o&&(y[o]=a()),s&&(y[s]=a()),m[n]){p=m[n],c=e.doc(p);let f=r?{...y,[r]:c.path}:y;await c.set(f);}else {c=await e.add(y),p=c.id;let f={[n]:p};r&&(f[r]=c.path),await c.update(f);}let g=await c.get();return _(g.data())},set:async(...m)=>{let c=m[m.length-1],p=typeof c=="object"&&c!==null&&"merge"in c,y=p?m[m.length-2]:m[m.length-1],g=p?m.slice(0,-2):m.slice(0,-1),f=p?c:{merge:true},b={...y};s&&(b[s]=a());let x=t(...g),h=g[g.length-1];n&&h!=null&&(b[n]=h),r&&(b[r]=x.path),await x.set(b,f);let v=await x.get();return _(v.data())},update:async(...m)=>{let c=m.pop(),p=m,y={...c};s&&(y[s]=a());let g=t(...p);await g.update(y);let f=await g.get();return _(f.data())},delete:async(...m)=>{await t(...m).delete();}}}function Rt(e,t,n,r,o){let s={};return s.byList=async(a,d,i="in",l={})=>{if(d.length===0)return [];let u=[],m=gt(d,30);for(let c of m){let p=e;p=p.where(a,i,c),l.select&&l.select.length>0&&(p=p.select(...l.select.map(g=>String(g)))),(await p.get()).forEach(g=>{let f=_(g.data());u.push(l.returnDoc?{data:f,doc:g}:f);});}return u},t.forEach(a=>{let d=`by${J(String(a))}`;s[d]=async(i,l={})=>{let u=typeof l=="boolean"?{returnDoc:l}:l;if(String(a)===o){let f=await r(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(g=>String(g))));let c=await m.get();if(c.empty)return null;let p=c.docs[0];if(!p)return null;let y=_(p.data());return u.returnDoc?{data:y,doc:p}:y};}),s}function wt(e,t,n,r){let o={},s=async(a,d)=>{if(!n||!r||d.length===0)return a;let i=d.map(l=>typeof l=="string"?{key:l}:{key:l.relation,select:l.select});return Promise.all(a.map(async l=>{let u=await Promise.all(i.map(async({key:c,select:p})=>{let y=n[c];if(!y)return [c,void 0];let g=r[y.repo];if(!g)return [c,void 0];let f=l[c];if(f==null)return [c,y.type==="one"?null:[]];let b=p?{select:p}:void 0;try{if(y.type==="one"){let x=`by${J(y.key)}`,h=typeof g.get?.[x]=="function"?await g.get[x](f,b):null;return [c,h]}else {let x=`by${J(y.key)}`,h=typeof g.query?.[x]=="function"?await g.query[x](f,b):[];return [c,h]}}catch(x){return console.error(`[include] Error populating "${c}":`,x),[c,y.type==="one"?null:[]]}})),m={};for(let[c,p]of u)c!==void 0&&(m[c]=p);return {...l,populated:m}}))};return t.forEach(a=>{let d=`by${J(a)}`;o[d]=async(i,l={})=>{let u={...l,where:[[a,"==",i],...l.where??[]]};return (await ae(e,u)).docs.map(c=>_(c.data()))};}),o.by=async a=>(await ae(e,a)).docs.map(i=>_(i.data())),o.getAll=async(a={})=>(await ae(e,a)).docs.map(i=>_(i.data())),o.onSnapshot=(a,d,i)=>Y(e,a).onSnapshot(u=>{d(u.docs.map(m=>_(m.data())));},i),o.paginate=async a=>{let{include:d,...i}=a,l=await $e(e,i);if(d&&d.length>0){let u=await s(l.data,d);return {...l,data:u}}return l},o.paginateAll=async function*(a){let{include:d,...i}=a;for await(let l of je(e,i))if(d&&d.length>0){let u=await s(l.data,d);yield {...l,data:u};}else yield l;},o}function Tt(e,t){return {populate:async(n,r)=>{if(!e.relationalKeys)return {...n,populated:{}};let o,s={};if(typeof r=="object"&&!Array.isArray(r))if("relation"in r){let i=r;o=[i.relation],i.select&&(s[i.relation]=i.select);}else if("relations"in r){let i=r;o=Array.isArray(i.relations)?i.relations:[i.relations],s=i.select??{};}else o=[];else o=Array.isArray(r)?r:[r];let a=await Promise.all(o.map(async i=>{let l=e.relationalKeys?.[i];if(!l)return console.warn(`[populate] Relation "${i}" not found in config`),[i,void 0];let u=t[l.repo];if(!u)return console.warn(`[populate] Repository "${l.repo}" not found in mapping`),[i,void 0];let m=n[i];if(m==null)return [i,l.type==="one"?null:[]];let c=s[i],p=c?{select:c}:void 0;try{if(l.type==="one"){let y=`by${J(l.key)}`,g=typeof u.get?.[y]=="function"?await u.get[y](m,p):null;return [i,g]}else {let y=`by${J(l.key)}`,g=typeof u.query?.[y]=="function"?await u.query[y](m,p):[];return [i,g]}}catch(y){return console.error(`[populate] Error populating "${i}":`,y),[i,l.type==="one"?null:[]]}})),d={};for(let[i,l]of a)l!==void 0&&(d[i]=l);return {...n,populated:d}}}}function St(e,t){return {run:async n=>e.runTransaction(async r=>n({get:async(...s)=>{let a=t(...s),d=await r.get(a);return d.exists?_({...d.data(),docId:d.id}):null},set:(...s)=>{let a=s[s.length-1],d=typeof a=="object"&&a!==null&&"merge"in a,i=d?s[s.length-2]:s[s.length-1],l=d?s.slice(0,-2):s.slice(0,-1),u=d?a:{merge:true},m=t(...l);r.set(m,i,u);},update:(...s)=>{let a=s[s.length-1],d=s.slice(0,-1),i=t(...d);r.update(i,a);},delete:(...s)=>{let a=t(...s);r.delete(a);},raw:r}))}}function un(e){if(typeof e!="function")return [];let n=e.toString().match(/^\s*(?:function\s*\w*\s*)?\(([^)]*)\)/);if(!n?.[1])return [];let r=n[1].split(",").map(o=>o.trim().replace(/\s*[:=].*$/,"").trim()).filter(Boolean);return r.length<=2?[]:r.slice(1,-1)}function Me(e,t,n={}){let r=t.isGroup?e.collectionGroup(t.path):e.collection(t.path),o=t.isGroup?null:e.collection(t.path),s=(...y)=>t.refCb(e,...y),a=Rt(r,t.foreignKeys,o,s,t.documentKey),d=wt(r,t.queryKeys,t.relationalKeys,n),i=ht(r),l=vt(o,s,t.documentKey,t.pathKey,t.createdKey,t.updatedKey),u=bt(e,s,t.documentKey,t.pathKey,t.createdKey,t.updatedKey),m=St(e,s),c=xt(e,t.createdKey,t.updatedKey),p=Tt(t,n);return {ref:r,documentRef:s,get:a,query:d,aggregate:i,...l,batch:u,transaction:m,bulk:c,...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?un(t.refCb):[],_createdKey:t.createdKey??null}}var pn={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 pn[n]??`Zod${n.charAt(0).toUpperCase()}${n.slice(1)}`;let r=t._def?.typeName;return r||""}function K(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 Ot(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 he(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 be(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 xe(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 ke(e){let t=e;return Array.isArray(t._zod?.def?.values)?t._zod.def.values[0]:t._def?.value}function At(e){let t=e,n=[],r=t._zod?.def?.checks;if(Array.isArray(r)){for(let s of r)s.format&&n.push(s.format);if(n.length>0)return n}let o=t._def?.checks;if(Array.isArray(o))for(let s of o)s.kind&&n.push(s.kind);return n}function fn(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/^\s/,"").replace(/^./,t=>t.toUpperCase())}function $t(e){let t=e,n=true,r=false,o;for(;;){let s=Z(t);if(s==="ZodOptional")n=false,t=K(t);else if(s==="ZodNullable")n=false,r=true,t=K(t);else if(s==="ZodDefault")n=false,o=Ot(t),t=K(t);else break}return {inner:t,required:n,nullable:r,defaultValue:o}}function W(e,t=""){if(Z(e)==="ZodObject"){let r=he(e);return Object.entries(r).map(([o,s])=>kt(t?`${t}.${o}`:o,o,s))}return [kt(t||"value",t||"value",e)]}function kt(e,t,n){let{inner:r,required:o,nullable:s,defaultValue:a}=$t(n),d=Z(r),i=fn(t.split(".").pop()??t);switch(d){case "ZodString":{let l=At(r),u=l.includes("email"),m=l.includes("url");return {name:e,label:i,type:"text",required:o,nullable:s,defaultValue:a,hint:u?"email":m?"url":void 0}}case "ZodNumber":case "ZodBigInt":return {name:e,label:i,type:"number",required:o,nullable:s,defaultValue:a};case "ZodBoolean":return {name:e,label:i,type:"checkbox",required:o,nullable:s,defaultValue:a};case "ZodDate":case "ZodCoerce":return {name:e,label:i,type:"datetime-local",required:o,nullable:s,defaultValue:a};case "ZodEnum":{let l=be(r);return {name:e,label:i,type:"select",required:o,nullable:s,defaultValue:a,options:l}}case "ZodNativeEnum":{let l=xe(r),u=Object.values(l).filter(m=>typeof m=="string");return {name:e,label:i,type:"select",required:o,nullable:s,defaultValue:a,options:u}}case "ZodLiteral":{let l=String(ke(r)??"");return {name:e,label:i,type:"select",required:o,nullable:s,defaultValue:a,options:[l]}}case "ZodObject":{let l=W(r,e);return {name:e,label:i,type:"textarea",required:o,nullable:s,defaultValue:a,nested:l,hint:"JSON object"}}case "ZodArray":{let l=Ct(r);if(!l)return {name:e,label:i,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON array"};let{inner:u}=$t(l),m=Z(u),c,p,y;switch(m){case "ZodString":c="text";break;case "ZodNumber":case "ZodBigInt":c="number";break;case "ZodBoolean":c="checkbox";break;case "ZodDate":c="datetime-local";break;case "ZodEnum":c="select",p=be(u);break;case "ZodNativeEnum":c="select",p=Object.values(xe(u)).filter(g=>typeof g=="string");break;case "ZodObject":c="object",y=W(u);break;default:return {name:e,label:i,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON array"}}return {name:e,label:i,type:"textarea",required:o,nullable:s,defaultValue:a,arrayElementType:c,arrayElementOptions:p,arrayElementFields:y}}default:return {name:e,label:i,type:"textarea",required:o,nullable:s,defaultValue:a,hint:"JSON"}}}function Be(e,t=0){let n=t>0?`ml-${t*4}`:"",r=`field_${e.name.replace(/\./g,"__")}`,o=e.name,s=e.required?" required":"",a=e.defaultValue==="__null__",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="${r}__isnull" name="${o}__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":""}
|
|
@@ -552,7 +552,7 @@ function initColumnReorder(table) {
|
|
|
552
552
|
});
|
|
553
553
|
});
|
|
554
554
|
}
|
|
555
|
-
`;function Re(){return jsxRuntime.jsx("script",{dangerouslySetInnerHTML:{__html:_t}})}function te(e){return "<!DOCTYPE html>"+server.renderToString(e)}var ne=({opts:e,children:t})=>{let{title:n,breadcrumb:r,flash:o,basePath:s="/"}=e;return jsxRuntime.jsxs("html",{lang:"en","data-theme":"corporate",children:[jsxRuntime.jsxs("head",{children:[jsxRuntime.jsx("meta",{charset:"UTF-8"}),jsxRuntime.jsx("meta",{name:"viewport",content:"width=device-width, initial-scale=1"}),jsxRuntime.jsxs("title",{children:[n," \u2014 FRS Admin"]}),jsxRuntime.jsx("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:s,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:[r&&r.length>0&&jsxRuntime.jsx("div",{class:"text-sm breadcrumbs mb-4",children:jsxRuntime.jsx("ul",{children:r.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}),o&&jsxRuntime.jsxs("div",{role:"alert",class:`alert ${o.type==="success"?"alert-success":o.type==="warning"?"alert-warning":"alert-error"} mb-6`,children:[jsxRuntime.jsx("span",{class:"flex-1",children:o.message}),o.action&&jsxRuntime.jsx("a",{href:o.action.href,...o.action.external?{target:"_blank",rel:"noopener noreferrer"}:{},class:"btn btn-sm btn-outline",children:o.action.label})]}),t]}),jsxRuntime.jsx(Re,{})]})]})};function Qe(e,t){return te(jsxRuntime.jsx(ne,{opts:t,children:jsxRuntime.jsx("div",{dangerouslySetInnerHTML:{__html:e}})}))}function qe(e,t){return te(jsxRuntime.jsx(ne,{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 Nt=[{value:"==",label:"="},{value:"!=",label:"\u2260"},{value:"in",label:"in"},{value:"not-in",label:"not in"}],xn=[{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"}],vn=[{value:"array-contains",label:"contains"},{value:"array-contains-any",label:"contains any"}];function Rn(e){switch(e){case "ZodNumber":case "ZodBigInt":case "ZodDate":return xn;case "ZodBoolean":return Nt;case "ZodArray":return vn;default:return Nt}}var re="__null__";function wn(e){return `(function(cb){var i=document.getElementById('${e}');if(!i)return;if(cb.checked){i.dataset._prev=i.value;if(i.tagName==='SELECT'){var o=i.querySelector('option[value="${re}"]');if(!o){o=document.createElement('option');o.value='${re}';o.textContent='\u2205 null';o.dataset._auto='1';i.appendChild(o);}o.selected=true;}else{if(i.type==='number'||i.type==='datetime-local'){i.dataset._type=i.type;i.type='text';}i.value='${re}';i.readOnly=true;}i.style.opacity='0.55';}else{i.style.opacity='';if(i.tagName==='SELECT'){var o2=i.querySelector('option[value="${re}"][data-_auto="1"]');if(o2)o2.remove();var prev=i.dataset._prev||'';for(var k=0;k<i.options.length;k++)i.options[k].selected=(i.options[k].value===prev);}else{if(i.dataset._type){i.type=i.dataset._type;delete i.dataset._type;}i.readOnly=false;i.value=(i.dataset._prev&&i.dataset._prev!=='${re}')?i.dataset._prev:'';}}})(this)`}function Tn(e,t){return `(function(){var h=document.getElementById('${e}');var boxes=document.querySelectorAll('input[data-enum-group="${t}"]');h.value=Array.from(boxes).filter(function(b){return b.checked;}).map(function(b){return b.value;}).join(',');})()`}function we({inputId:e,active:t}){return jsxRuntime.jsxs("label",{class:"flex items-center gap-1 cursor-pointer select-none text-xs text-base-content/60 hover:text-base-content border border-base-300 rounded-md px-1.5 py-1 shrink-0 leading-none h-8",title:"Filter where field IS NULL",children:[jsxRuntime.jsx("input",{type:"checkbox",class:"checkbox checkbox-xs",checked:t,onchange:wn(e)}),jsxRuntime.jsx("span",{children:"\u2205"})]})}function Sn({col:e,active:t}){let n=t?.value??"",r=n===re,o=`fv_input_${e.name.replace(/\./g,"__")}`,s=t?.op,a=s==="in"||s==="not-in";if(e.enumValues&&e.enumValues.length>0){if(a){let d=new Set(n.split(",").map(l=>l.trim()).filter(Boolean)),i=`eg_${e.name.replace(/\./g,"__")}`;return jsxRuntime.jsxs("div",{class:"flex flex-wrap items-center gap-1 w-full",children:[jsxRuntime.jsx("input",{type:"hidden",id:o,name:`fv_${e.name}`,value:n}),e.enumValues.map(l=>jsxRuntime.jsxs("label",{class:"flex items-center gap-1 text-xs border border-base-300 rounded px-2 cursor-pointer hover:bg-base-200",children:[jsxRuntime.jsx("input",{type:"checkbox",class:"checkbox checkbox-xs",value:l,checked:d.has(l),"data-enum-group":i,onchange:Tn(o,i)}),jsxRuntime.jsx("span",{children:l})]},l))]})}return jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.jsxs("select",{id:o,name:`fv_${e.name}`,class:"select select-sm select-bordered w-full",style:r?"opacity:0.55":void 0,children:[jsxRuntime.jsx("option",{value:"",selected:n===""&&!r,children:"\u2014"}),e.enumValues.map(d=>jsxRuntime.jsx("option",{value:d,selected:n===d,children:d},d)),e.nullable&&jsxRuntime.jsx("option",{value:re,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsxRuntime.jsx(we,{inputId:o,active:r})]})}if(e.zodType==="ZodBoolean")return jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.jsxs("select",{id:o,name:`fv_${e.name}`,class:"select select-sm select-bordered w-full",style:r?"opacity:0.55":void 0,children:[jsxRuntime.jsx("option",{value:"",selected:n===""&&!r,children:"\u2014"}),jsxRuntime.jsx("option",{value:"true",selected:n==="true",children:"true"}),jsxRuntime.jsx("option",{value:"false",selected:n==="false",children:"false"}),e.nullable&&jsxRuntime.jsx("option",{value:re,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsxRuntime.jsx(we,{inputId:o,active:r})]});if(e.zodType==="ZodArray"){let d=t?.op==="array-contains-any";return jsxRuntime.jsx("input",{id:o,type:"text",name:`fv_${e.name}`,value:n,placeholder:d?"val1, val2, \u2026":"value",class:"input input-sm input-bordered w-full"})}return e.zodType==="ZodNumber"||e.zodType==="ZodBigInt"?jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.jsx("input",{id:o,type:r?"text":"number",name:`fv_${e.name}`,value:n,placeholder:"value",class:"input input-sm input-bordered w-full",readOnly:r,style:r?"opacity:0.55":void 0,"data-_type":r?"number":void 0}),e.nullable&&jsxRuntime.jsx(we,{inputId:o,active:r})]}):e.zodType==="ZodDate"?jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.jsx("input",{id:o,type:r?"text":"datetime-local",name:`fv_${e.name}`,value:n,class:"input input-sm input-bordered w-full",readOnly:r,style:r?"opacity:0.55":void 0,"data-_type":r?"datetime-local":void 0}),e.nullable&&jsxRuntime.jsx(we,{inputId:o,active:r})]}):jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.jsx("input",{id:o,type:"text",name:`fv_${e.name}`,value:n,placeholder:"value",class:"input input-sm input-bordered w-full",readOnly:r,style:r?"opacity:0.55":void 0}),e.nullable&&jsxRuntime.jsx(we,{inputId:o,active:r})]})}function Ue({action:e,columnMeta:t,activeFilters:n,isGroup:r}){let o=Object.fromEntries(n.map(i=>[i.field,i])),s=n.length>0,a=n.length>=2||r&&s,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:s?true:void 0,children:[jsxRuntime.jsxs("summary",{class:"collapse-title text-sm font-medium py-2 min-h-0",children:["Filters",s&&jsxRuntime.jsxs("span",{class:"badge badge-primary badge-sm ml-2",children:[n.length," active"]})]}),jsxRuntime.jsx("div",{class:"collapse-content pb-4 pt-2",children:jsxRuntime.jsxs("form",{method:"get",action:e,children:[jsxRuntime.jsx("div",{class:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:d.map(i=>{let l=Rn(i.zodType),u=o[i.name],m=u?.op??l[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:[l.length>1?jsxRuntime.jsx("select",{name:`fo_${i.name}`,class:"select select-sm select-bordered w-20 shrink-0",children:l.map(c=>jsxRuntime.jsx("option",{value:c.value,selected:c.value===m,children:c.label},c.value))}):jsxRuntime.jsx("input",{type:"hidden",name:`fo_${i.name}`,value:l[0].value}),jsxRuntime.jsx(Sn,{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"}),s&&jsxRuntime.jsx("a",{href:e,class:"btn btn-sm btn-ghost",children:"Clear"}),a&&jsxRuntime.jsxs("span",{class:"text-xs text-warning ml-auto flex items-center gap-1",children:[jsxRuntime.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-4 w-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:jsxRuntime.jsx("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),r?"Collection group queries require a composite index":"Multiple filters may require a composite index"]})]})]})})]})}function Ge(e,t,n,r,o,s){let a=n==="create"?`Create ${e}`:`Edit ${e} / ${r??""}`,d=n==="create"?[{label:"Repositories",href:o},{label:e,href:`${o}/${e}`},{label:"New document"}]:[{label:"Repositories",href:o},{label:e,href:`${o}/${e}`},{label:`Edit ${r??""}`}];return te(jsxRuntime.jsx(ne,{opts:{title:a,breadcrumb:d,basePath:o,flash:s},children:jsxRuntime.jsx("div",{class:"card bg-base-100 border border-base-300",children:jsxRuntime.jsx("div",{class:"card-body p-6",children:jsxRuntime.jsx("div",{dangerouslySetInnerHTML:{__html:t}})})})}))}function We(e,t,n){let r=new URLSearchParams;for(let o of e)r.set(`fv_${o.field}`,o.value),r.set(`fo_${o.field}`,o.op);return t&&(r.set("ob",t.field),r.set("od",t.dir)),n&&r.set("ps",String(n)),r}function Ft(e,t,n,r,o){let s=We(e,r,o);return s.set("cursor",t),s.set("dir",n),`?${s.toString()}`}function Cn(e,t,n,r){let o=We(n,void 0,r);return t?.field===e?t.dir==="asc"&&(o.set("ob",e),o.set("od","desc")):(o.set("ob",e),o.set("od","asc")),`?${o.toString()}`}function On(e,t,n){return `?${We(t,n,e).toString()}`}function Le(e,t,n,r,o,s,a=[],d=[],i=false,l=[],u,m,c,p){let y=`${r}/${e}`,g=`${y}/create`;return te(jsxRuntime.jsxs(ne,{opts:{title:e,breadcrumb:[{label:"Repositories",href:r},{label:e}],basePath:r,flash:s},children:[a.length>0&&jsxRuntime.jsx(Ue,{action:y,columnMeta:a,activeFilters:d,isGroup:p}),c&&jsxRuntime.jsxs("div",{role:"alert",class:`alert ${c.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:c.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:c.type==="index"?"Composite index required":"Query failed"}),jsxRuntime.jsx("div",{class:"text-sm",children:c.message})]}),c.indexUrl&&jsxRuntime.jsx("a",{href:c.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:On(f,d,u),class:`join-item btn btn-xs ${m===f?"btn-active btn-primary":"btn-outline"}`,children:f},f))})]})]}),jsxRuntime.jsx("a",{href:g,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,h=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,h]})},b)}),l.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+l.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??""),h=`${r}/${e}/${encodeURIComponent(x)}/edit`,v=`${r}/${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(Ke,{val:f[R]})},w)),l.map((R,w)=>{let T=f[R.key];if(T==null||T==="")return jsxRuntime.jsx("td",{class:"py-2"},`rel-${w}`);let $=`${r}/${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:h,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)})})]})}),(o.hasPrev||o.hasNext)&&jsxRuntime.jsxs("div",{class:"flex justify-center items-center mt-6 gap-2",children:[o.hasPrev?jsxRuntime.jsx("a",{href:Ft(d,o.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"}),o.hasNext?jsxRuntime.jsx("a",{href:Ft(d,o.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 De(e,t){return Qe(e,t)}function He(e,t){return qe(e,t)}function Ve(e,t,n,r,o,s,a,d,i,l,u,m,c,p){return Le(e,t,n,r,o,s,a,d,i,l,u,m,c,p)}function oe(e,t,n,r,o,s){return Ge(e,t,n,r,o,s)}var An=new Set(["<","<=",">",">=","!="]),kn=new Set(["array-contains","array-contains-any"]);function Je(e){return e==="desc"?"DESCENDING":"ASCENDING"}function $n(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function Pn(e,t,n,r,o){let s=[],a=new Set;for(let i of r)if(i.op==="=="||i.op==="in"||i.op==="not-in"){if(a.has(i.field))continue;a.add(i.field),s.push({fieldPath:i.field,order:"ASCENDING"});}for(let i of r)if(kn.has(i.op)){if(a.has(i.field))continue;a.add(i.field),s.push({fieldPath:i.field,arrayConfig:"CONTAINS"});}for(let i of r)if(An.has(i.op)){if(a.has(i.field))continue;a.add(i.field);let l=o?.field===i.field?Je(o.dir):"ASCENDING";s.push({fieldPath:i.field,order:l});}if(o&&!a.has(o.field)&&s.push({fieldPath:o.field,order:Je(o.dir)}),s.length===1&&n)return _n(e,t,s[0]);let d=o&&s.some(i=>i.fieldPath===o.field)?Je(o.dir):"ASCENDING";return s.push({fieldPath:"__name__",order:d}),Dn(e,t,n,s)}function Dn(e,t,n,r,o="(default)"){let s=`projects/${e}/databases/${o}/collectionGroups/${t}/indexes/_`,a=[...et(1,s),...Ee(2,n?2:1)];for(let l of r)a.push(...Zt(3,zt(l)));let d=o==="(default)"?"-default-":o,i=encodeURIComponent(jt(a));return `https://console.firebase.google.com/project/${e}/firestore/databases/${d}/indexes?create_composite=${i}`}function En(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function Xe(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function Ye(e,t){return e<<3|t}function et(e,t){let n=Array.from(new TextEncoder().encode(t));return [Ye(e,2),...Xe(n.length),...n]}function Ee(e,t){return [Ye(e,0),...Xe(t)]}function Zt(e,t){return [Ye(e,2),...Xe(t.length),...t]}function zt(e){let t=[...et(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...Ee(3,1)):t.push(...Ee(2,e.order==="DESCENDING"?2:1)),t}function jt(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 _n(e,t,n,r="(default)"){let o=`projects/${e}/databases/${r}/collectionGroups/${t}/fields/${n.fieldPath}`,s=[...et(1,o),...Ee(2,2),...Zt(3,zt(n))],a=r==="(default)"?"-default-":r,d=encodeURIComponent(jt(s));return `https://console.firebase.google.com/project/${e}/firestore/databases/${a}/indexes/automatic?create_exemption=${d}`}function In(e){let t=e,n=[t?.firestore?.projectId,t?.firestore?.app?.options?.projectId,t?.firestore?._settings?.projectId,t?.firestore?.databaseId?.projectId,t?._firestore?.projectId];for(let o of n)if(typeof o=="string"&&o.length>0)return o;return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.FIREBASE_PROJECT_ID||void 0}function le(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function Te(e,t){let n=e??{},r=le(e),o;if(r&&(o=n.message?En(n.message):void 0,!o)){let s=In(t.ref);if(s){let a=$n(t.path);o=Pn(s,a,t.isGroup,t.filters,t.sort);}}return {type:r?"index":"error",message:r?"This query requires a composite index that does not exist yet.":n.message??"Query failed",indexUrl:o}}var Mt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Fn(){let e="";for(let t=0;t<20;t++)e+=Mt.charAt(Math.floor(Math.random()*Mt.length));return e}function Bt(e,t){if(!t)return;let n=e[t];if(typeof n!="string"||!n)return;let r=n.split("/").filter(Boolean),o=[];for(let s=1;s<r.length;s+=2)o.push(r[s]);return o.length>0?o:void 0}async function tt(e,t){let n=e.documentKey??"docId",r=`by${n.charAt(0).toUpperCase()}${n.slice(1)}`;if(typeof e.repo.get[r]=="function")try{let s=await e.repo.get[r](t);if(s)return s}catch{}return (await e.repo.query.by({where:[[n,"==",t]],limit:1}))[0]??null}function nt(e,t,n){let r=e.documentKey??"docId",o=Te(n,{ref:e.repo.ref,path:e.path,isGroup:!!e.isGroup,filters:[{field:r,op:"==",value:t}]});return o.type==="index"?{type:"warning",message:"Loading this document requires a composite index that does not exist yet.",...o.indexUrl?{action:{href:o.indexUrl,label:"Create Index \u2192",external:true}}:{}}:{type:"error",message:o.message}}function P(e,t,n=200){e.status(n).set("Content-Type","text/html; charset=utf-8").send(t);}function rt(e,t){e.status(302).set("Location",t).send("");}function ot(e,t){let n=t.shape,r={};for(let[o,s]of Object.entries(n)){let a=at(s);if(a==="ZodObject"){if(e[o+"__isnull"]==="1"){r[o]=null;continue}let l={},u=false;for(let[p,y]of Object.entries(e))p.startsWith(`${o}.`)&&(l[p.slice(o.length+1)]=y,u=true);if(u){let p=s;for(;;){let y=Z(p);if(y==="ZodOptional"||y==="ZodNullable"||y==="ZodDefault")p=K(p);else break}r[o]=ot(l,p);continue}let m=e[o],c=Array.isArray(m)?m[m.length-1]:m;if(c)try{r[o]=JSON.parse(c);}catch{r[o]=c;}continue}let d=e[o],i=Array.isArray(d)?d[d.length-1]:d;if(e[o+"__isnull"]==="1"){r[o]=null;continue}if(i===void 0||i===""){a==="ZodBoolean"&&(r[o]=false);continue}switch(a){case "ZodBoolean":i==="__null__"?r[o]=null:r[o]=i==="true"||i==="on"||i==="1";break;case "ZodNumber":case "ZodBigInt":r[o]=Number(i);break;case "ZodDate":r[o]=new Date(i);break;case "ZodArray":try{r[o]=JSON.parse(i);}catch{r[o]=i;}break;default:if(i.startsWith("{")||i.startsWith("["))try{r[o]=JSON.parse(i);break}catch{}r[o]=i;}}return r}function Kt(e){let t=null;if(e instanceof Date)t=e;else if(typeof e=="object"&&e!==null&&typeof e.toDate=="function")t=e.toDate();else if(typeof e=="object"&&e!==null&&"_seconds"in e&&"_nanoseconds"in e)t=new Date(e._seconds*1e3+Math.floor(e._nanoseconds/1e6));else if(typeof e=="string"||typeof e=="number"){let r=new Date(e);isNaN(r.getTime())||(t=r);}if(!t||isNaN(t.getTime()))return null;let n=r=>String(r).padStart(2,"0");return `${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`}function at(e){let t=e;for(;;){let n=Z(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=K(t);else return n}}function Zn(e){let t=e;for(;;){let n=Z(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=K(t);else return t}}function Qt(e){let t=e;for(;;){let n=Z(t);if(n==="ZodOptional"||n==="ZodNullable")return true;if(n==="ZodDefault"){t=K(t);continue}return false}}function qt(e){let t=Zn(e),n=Z(t);if(n==="ZodEnum"){let r=be(t);return r.length>0?r:void 0}if(n==="ZodNativeEnum"){let r=xe(t),o=Object.values(r).filter(s=>typeof s=="string");return o.length>0?o:void 0}if(n==="ZodLiteral"){let r=$e(t);return typeof r=="string"?[r]:void 0}}function Ut(e,t,n=""){let r={};for(let o of Object.keys(t.shape)){let s=n?`${n}.${o}`:o,a=e[o];if(a===null){r[s]="__null__";continue}if(a===void 0)continue;let d=t.shape[o];for(;;){let l=Z(d);if(l==="ZodOptional"||l==="ZodNullable"||l==="ZodDefault")d=K(d);else break}let i=Z(d);if(i==="ZodObject"&&typeof a=="object"&&a!==null&&!Array.isArray(a)){let l=Ut(a,d,s);Object.assign(r,l);}else if(i==="ZodDate"){let l=Kt(a);l!==null&&(r[s]=l);}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)&&("_seconds"in a||typeof a.toDate=="function")){let l=Kt(a);r[s]=l??JSON.stringify(a,null,2);}else typeof a=="object"?r[s]=JSON.stringify(a,null,2):r[s]=String(a);}return r}function st(e,t){return e.map(n=>({...n,defaultValue:t[n.name]??n.defaultValue,nested:n.nested?st(n.nested,t):void 0}))}function zn(e,t){let n=new Set(["==","!=","<","<=",">",">=","in","not-in","array-contains","array-contains-any"]),r=[];for(let[o,s]of Object.entries(e)){if(!o.startsWith("fv_"))continue;let a=o.slice(3);if(!t.has(a))continue;let d=(s??"").trim();if(!d)continue;let i=e[`fo_${a}`]??"==",l=n.has(i)?i:"==";r.push({field:a,op:l,value:d});}return r}function jn(e){let t="__null__",n=r=>r===t?null:r==="true"?true:r==="false"?false:r!==""&&!isNaN(Number(r))?Number(r):r;return e.map(r=>{if(r.op==="array-contains-any"||r.op==="in"||r.op==="not-in"){let o=r.value.split(",").map(s=>s.trim()).filter(s=>s!==""&&s!==t).map(s=>n(s));return [r.field,r.op,o]}return [r.field,r.op,n(r.value)]})}function Gt(e,t,n=""){let r=[];for(let o of e){let s=n?`${n}.${o}`:o,a=t.shape[o];if(!a){r.push({name:s,zodType:"ZodString"});continue}let d=at(a);if(d==="ZodObject"){let i=a;for(;;){let u=Z(i);if(u==="ZodOptional"||u==="ZodNullable"||u==="ZodDefault")i=K(i);else break}let l=he(i);r.push(...Gt(Object.keys(l),i,s));}else r.push({name:s,zodType:d,nullable:Qt(a),enumValues:qt(a)});}return r}function Mn(e,t){let n=t.split("."),r=e;for(let o of n){for(;;){let a=Z(r);if(a==="ZodOptional"||a==="ZodNullable"||a==="ZodDefault")r=K(r);else break}let s=he(r);if(!(o in s))return null;r=s[o];}return r}function de(e,t){if(!t||t.length===0)return e;let n=[],r=new Map;for(let s of t){let a=s.indexOf(".");if(a===-1)n.push(s);else {let d=s.slice(0,a),i=s.slice(a+1);r.has(d)||r.set(d,[]),r.get(d).push(i);}}let o={};for(let s of n)s in e.shape&&(o[s]=e.shape[s]);for(let[s,a]of r){if(!(s in e.shape))continue;let d=e.shape[s];for(;;){let i=Z(d);if(i==="ZodOptional"||i==="ZodNullable"||i==="ZodDefault")d=K(d);else break}if(Z(d)!=="ZodObject"){o[s]=e.shape[s];continue}o[s]=de(d,a);}return zod.z.object(o)}function ce(e,t){let n=t==="/"?"":t.replace(/\/$/,"");if(process.env.FUNCTIONS_EMULATOR==="true"){let s=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??"demo-project",a=process.env.FUNCTION_REGION??"us-central1",d=(process.env.FUNCTION_TARGET??"").replace(/\./g,"-");return `/${s}/${a}/${d}${n}`}let r=process.env.K_SERVICE,o=e.hostname??e.headers?.host??"";return r&&o.includes("cloudfunctions.net")?`/${r.toLowerCase()}${n}`:n}function Wt(e,t){return {handleDashboard:(l,u)=>{let m=ce(l,t),c=Object.values(e).map(p=>({name:p.name,path:p.path}));P(u,He(c,m));},handleList:async(l,u)=>{let m=l.params.repoName;if(!m){P(u,"Bad request",400);return}let c=e[m];if(!c){P(u,"Repository not found",404);return}let p=c.pageSize??25,y=l.query??{},g=y.cursor,f=y.dir==="prev"?"prev":"next",b=y.ob??"",x=y.od==="desc"?"desc":"asc",h=b?{field:b,dir:x}:void 0,v=parseInt(y.ps??""),R=Number.isFinite(v)&&v>0?Math.min(v,200):p,w=c.listColumns??Object.keys(c.schema.shape),T=c.documentKey??"docId",$=[T,...w.filter(j=>j!==T)],C=c.filterableFields?(()=>{let j=[];for(let V of c.filterableFields)(V.includes(".")||w.includes(V))&&j.push(V);return j})():w,O=(()=>{let j=[];for(let V of C)if(V.includes(".")){let pe=Mn(c.schema,V);j.push({name:V,zodType:pe?at(pe):"ZodString",nullable:pe?Qt(pe):false,enumValues:pe?qt(pe):void 0});}else j.push(...Gt([V],c.schema));return j})(),D=new Set(O.map(j=>j.name)),N=zn(y,D),U=jn(N),M;if(g)try{let j=c.repo.ref;typeof j.doc=="function"&&(M=await j.doc(g).get());}catch{}let H=await c.repo.query.paginate({pageSize:R,cursor:M,direction:f,...U.length>0?{where:U}:{},...h?{orderBy:[{field:h.field,direction:h.dir}]}:{}}).catch(j=>({queryError:Te(j,{ref:c.repo.ref,path:c.path,isGroup:!!c.isGroup,filters:N,sort:h})})),E="queryError"in H,ue=E?[]:H.data,nn=E?"":H.nextCursor?.id??"",rn=E?"":H.prevCursor?.id??"",on=E?H.queryError:void 0,sn=ce(l,t);P(u,Ve(c.name,ue,$,sn,{hasPrev:E?false:H.hasPrevPage,hasNext:E?false:H.hasNextPage,prevCursor:rn,nextCursor:nn},void 0,O,N,c.allowDelete??false,c.relationalMeta,h,R,on,c.isGroup));},handleCreateForm:(l,u)=>{let m=l.params.repoName;if(!m){P(u,"Bad request",400);return}let c=e[m];if(!c){P(u,"Repository not found",404);return}let p=ce(l,t),y=de(c.schema,c.createFields),g=W(y),f=`${p}/${c.name}/create`,b=ee(g,f,"POST","Create document");P(u,oe(c.name,b,"create",null,p));},handleCreateSubmit:async(l,u)=>{let m=l.params.repoName;if(!m){P(u,"Bad request",400);return}let c=e[m];if(!c){P(u,"Repository not found",404);return}let p=ce(l,t),y=l.body??{},g=ot(y,c.schema),f=de(c.schema,c.createFields),b=f.safeParse(g);if(!b.success){let x=W(f),h=`${p}/${c.name}/create`,v=ee(x,h,"POST","Create document"),R=b.error.issues.map(w=>`${w.path.join(".")}: ${w.message}`).join(", ");P(u,oe(c.name,v,"create",null,p,{type:"error",message:`Validation error: ${R}`}),422);return}try{if(c.isGroup&&c.parentKeys&&c.parentKeys.length>0){let x={...b.data};c.createdKey&&(x[c.createdKey]=new Date);let h=c.parentKeys.filter(T=>!x[T]);if(h.length>0)throw new Error(`Missing parent key(s) for subcollection create: ${h.join(", ")}`);let v=c.parentKeys.map(T=>x[T]),R=c.documentKey??"docId",w=x[R]||Fn();await c.repo.set(...v,w,x);}else await c.repo.create(b.data);rt(u,`${p}/${c.name}?flash=created`);}catch(x){let h=de(c.schema,c.createFields),v=W(h),R=`${p}/${c.name}/create`,w=ee(v,R,"POST","Create document");P(u,oe(c.name,w,"create",null,p,{type:"error",message:`Save error: ${x.message}`}),500);}},handleEditForm:async(l,u)=>{let m=l.params.repoName,c=l.params.id;if(!m||!c){P(u,"Bad request",400);return}let p=e[m];if(!p){P(u,"Repository not found",404);return}let y=ce(l,t),g=null;try{g=await tt(p,c);}catch(R){let w=nt(p,c,R),T=le(R)?424:500;P(u,De("",{title:`Edit ${p.name} / ${c}`,basePath:y,breadcrumb:[{label:"Repositories",href:y},{label:p.name,href:`${y}/${p.name}`},{label:`Edit ${c}`}],flash:w}),T);return}if(!g){P(u,"Document not found",404);return}let f=Ut(g,p.schema),b=de(p.schema,p.mutableFields),x=st(W(b),f),h=`${y}/${p.name}/${encodeURIComponent(c)}/edit`,v=ee(x,h,"POST","Save changes");P(u,oe(p.name,v,"edit",c,y));},handleEditSubmit:async(l,u)=>{let m=l.params.repoName,c=l.params.id;if(!m||!c){P(u,"Bad request",400);return}let p=e[m];if(!p){P(u,"Repository not found",404);return}let y=ce(l,t),g=l.body??{},f=ot(g,p.schema),b=de(p.schema,p.mutableFields),h=b.partial().safeParse(f);if(!h.success){let v=Object.fromEntries(Object.entries(g).map(([C,O])=>[C,Array.isArray(O)?O.join(","):O??""])),R=st(W(b),v),w=`${y}/${p.name}/${encodeURIComponent(c)}/edit`,T=ee(R,w,"POST","Save changes"),$=h.error.issues.map(C=>`${C.path.join(".")}: ${C.message}`).join(", ");P(u,oe(p.name,T,"edit",c,y,{type:"error",message:`Validation error: ${$}`}),422);return}try{let v=await tt(p,c),R=(v&&Bt(v,p.pathKey))??[c];await p.repo.update(...R,h.data),rt(u,`${y}/${p.name}?flash=updated`);}catch(v){let R=de(p.schema,p.mutableFields),w=W(R),T=`${y}/${p.name}/${encodeURIComponent(c)}/edit`,$=ee(w,T,"POST","Save changes"),C=le(v)?nt(p,c,v):{type:"error",message:`Save error: ${v.message}`},O=le(v)?424:500;P(u,oe(p.name,$,"edit",c,y,C),O);}},handleDelete:async(l,u)=>{let m=l.params.repoName,c=l.params.id;if(!m||!c){P(u,"Bad request",400);return}let p=e[m];if(!p){P(u,"Repository not found",404);return}if(!p.allowDelete){P(u,"Delete is not allowed for this repository",403);return}let y=ce(l,t);try{let g=await tt(p,c),f=(g&&Bt(g,p.pathKey))??[c];await p.repo.delete(...f),rt(u,`${y}/${p.name}?flash=deleted`);}catch(g){let f=le(g)?nt(p,c,g):{type:"error",message:`Delete error: ${g.message}`},b=le(g)?424:500;P(u,De("",{title:`Delete ${p.name} / ${c}`,basePath:y,breadcrumb:[{label:"Repositories",href:y},{label:p.name,href:`${y}/${p.name}`},{label:`Delete ${c}`}],flash:f}),b);}}}}function Bn(e){let t=[],n=e.replace(/[.*+?^${}()|[\]\\]/g,r=>r===":"?r:`\\${r}`).replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,(r,o)=>(t.push(o),"([^/]+)"));return {pattern:new RegExp(`^${n}$`),paramNames:t}}function Kn(e){let t=e.path??e.url??"/",n=t.indexOf("?");return n===-1?t:t.slice(0,n)}var X=class{constructor(){this.routes=[];this.middlewares=[];this.notFoundHandler=(t,n)=>{n.status(404).send("Not Found");};this.errorHandler=(t,n,r)=>{console.error("[MiniRouter]",t),r.status(500).send("Internal Server Error");};}use(t){return this.middlewares.push(t),this}get(t,n){return this.addRoute("GET",t,n)}post(t,n){return this.addRoute("POST",t,n)}put(t,n){return this.addRoute("PUT",t,n)}patch(t,n){return this.addRoute("PATCH",t,n)}delete(t,n){return this.addRoute("DELETE",t,n)}onNotFound(t){return this.notFoundHandler=t,this}onError(t){return this.errorHandler=t,this}addRoute(t,n,r){let{pattern:o,paramNames:s}=Bn(n);return this.routes.push({method:t.toUpperCase(),pattern:o,paramNames:s,handler:r}),this}async handle(t,n){let r=(t.method??"GET").toUpperCase(),o=Kn(t),s=null,a={};for(let l of this.routes){if(l.method!==r)continue;let u=o.match(l.pattern);if(u){s=l,a={},l.paramNames.forEach((m,c)=>{a[m]=decodeURIComponent(u[c+1]??"");});break}}let d=Object.assign(t,{params:a}),i=s?s.handler:this.notFoundHandler;try{await this.runMiddlewareChain(d,n,i);}catch(l){this.errorHandler(l,t,n);}}async runMiddlewareChain(t,n,r){let o=0,s=async()=>{if(o<this.middlewares.length){let a=this.middlewares[o++];await a(t,n,s);}else await r(t,n);};await s();}};async function Qn(e){return typeof e.rawBody=="string"?e.rawBody:Buffer.isBuffer(e.rawBody)?e.rawBody.toString("utf8"):""}function qn(e){let t={};if(!e)return t;for(let n of e.split("&")){let r=n.indexOf("=");if(r===-1)continue;let o=decodeURIComponent(n.slice(0,r).replace(/\+/g," ")),s=decodeURIComponent(n.slice(r+1).replace(/\+/g," ")),a=t[o];a===void 0?t[o]=s:Array.isArray(a)?a.push(s):t[o]=[a,s];}return t}function Lt(e){let{basePath:t="/",repos:n,parseBody:r=true,auth:o,middleware:s=[],httpsOptions:a}=e,d=t==="/"?"":t.replace(/\/$/,""),i={};for(let[c,p]of Object.entries(n)){let y=p.schema??p.repo.schema??null;if(!y)throw new Error(`[createAdminServer] Repository "${c}" has no Zod schema. Either use createRepositoryConfig(schema)(config) or pass schema: explicitly.`);let g,f,b;if(p.fieldsConfig){let v=p.fieldsConfig;g=[],f=[],b=[];for(let[R,w]of Object.entries(v))for(let T of w)T==="filterable"?g.push(R):T==="mutable"?f.push(R):T==="create"&&b.push(R);g.length===0&&(g=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 h={name:c,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:g,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[c]=h;}let l=Wt(i,d),u=new X;if(r&&u.use(async(c,p,y)=>{let g=c,f=String(g.headers?.["content-type"]??"");if(f.includes("application/x-www-form-urlencoded")){let b=await Qn(g);c.body=qn(b);}else if(f.includes("application/json")&&typeof g.body=="string")try{c.body=JSON.parse(g.body);}catch{}await y();}),o)if(typeof o=="function")u.use(o);else {let c=o.realm??"Admin",p="Basic "+Buffer.from(`${o.username}:${o.password}`).toString("base64");u.use((y,g,f)=>{if((y.headers?.authorization??"")!==p){g.status(401).set("WWW-Authenticate",`Basic realm="${c}"`).set("Content-Type","text/plain").send("Unauthorized");return}f();});}for(let c of s)u.use(c);u.get(`${d}/`,l.handleDashboard),u.get(`${d}`,l.handleDashboard),u.get(`${d}/:repoName`,l.handleList),u.get(`${d}/:repoName/create`,l.handleCreateForm),u.post(`${d}/:repoName/create`,l.handleCreateSubmit),u.get(`${d}/:repoName/:id/edit`,l.handleEditForm),u.post(`${d}/:repoName/:id/edit`,l.handleEditSubmit),u.post(`${d}/:repoName/:id/delete`,l.handleDelete);let m=async(c,p)=>{await u.handle(c,p);};return a&&(m.httpsOptions=a),m}function lt(e,t,n=200){let r=_(t);e.status(n).set("Content-Type","application/json; charset=utf-8").send(JSON.stringify(r));}function ye(e,t,n,r=200){lt(e,{success:true,data:t,meta:n},r);}function z(e,t,n=400){lt(e,{success:false,error:t},n);}function it(e,t,n,r,o){let s=Te(t,n),a=s.type==="index",d=a?424:500,l={success:false,error:a?s.message:o&&t instanceof Error?t.message:r};a&&(l.errorType="index",s.indexUrl&&(l.indexUrl=s.indexUrl)),lt(e,l,d);}var Ht="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Un(){let e="";for(let t=0;t<20;t++)e+=Ht.charAt(Math.floor(Math.random()*Ht.length));return e}function me(e){let t=e._def??e.def;if(!t)return e;let n=t.typeName??t.type;if(n==="ZodDate"||n==="date")return zod.z.preprocess(r=>ze(r)??r,e);if(n==="ZodObject"||n==="object"){let r=e.shape,o={};for(let[s,a]of Object.entries(r))o[s]=me(a);return zod.z.object(o)}if(n==="ZodArray"||n==="array"){let r=t.element??t.type;if(r)return zod.z.array(me(r))}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(r)return me(r).optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(r)return me(r).nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType,o=t.defaultValue;if(r){let s=me(r);return typeof o=="function"?s.default(o()):s.default(o)}}return e}function Gn(e,t,n=[]){let r=e.shape,o={},s=t&&t.length>0?t:Object.keys(r);for(let a of s){if(n.includes(a))continue;let d=a.split(".")[0];d&&r[d]&&(o[d]=r[d]);}return zod.z.object(o)}function Vt(e,t,n,r=false,o=[]){try{let s=Gn(e,n,o),a=r?s.partial():s;return {success:!0,data:(Ze()==="normalize"?me(a):a).parse(t)}}catch(s){return s instanceof zod.z.ZodError?{success:false,error:`Validation failed: ${s.issues.map(d=>`${d.path.join(".")}: ${d.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}function Wn(e,t){let n=[],r=t?new Set(t):null,o={eq:"==",ne:"!=",lt:"<",lte:"<=",gt:">",gte:">=",in:"in",nin:"not-in",contains:"array-contains",containsAny:"array-contains-any"};for(let[s,a]of Object.entries(e)){if(a===void 0||["cursor","limit","pageSize","orderBy","orderDir","select"].includes(s))continue;let d=Array.isArray(a)?a[0]:a;if(d===void 0||d==="")continue;let i=s.match(/^(\w+)__(\w+)$/),l,u="==";if(i&&i[1]&&i[2]){l=i[1];let c=i[2];if(o[c])u=o[c];else continue}else if(!i)l=s;else continue;if(r&&!r.has(l))continue;let m=d;u==="in"||u==="not-in"||u==="array-contains-any"?m=d.split(",").map(c=>Jt(c.trim())):m=Jt(d),n.push({field:l,op:u,value:m});}return n}function Jt(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 _e(e){return e?{docId:e.id}:null}async function Xt(e,t){if(!t||typeof t!="object")return;let n=t.docId;if(typeof n=="string")try{let r=e.repo.ref;if(typeof r.doc!="function")return;let o=await r.doc(n).get();return o.exists?o:void 0}catch{return}}function Yt(e,t,n){function r(p,y){return !p||!e[p]?(z(y,`Repository "${p}" not found`,404),null):e[p]}function o(p,y){if(!y)return;let g=p[y];if(typeof g!="string"||!g)return;let f=g.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 s(p,y){let g=`by${p.documentKey.charAt(0).toUpperCase()}${p.documentKey.slice(1)}`,f=p.repo.get[g];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 g=p.params||{},f=r(g.repoName,y);if(!f)return;let b=[],x;try{let h=p.query??{},v=Math.min(Number(h.pageSize)||f.pageSize,100),R=h.cursor,w=h.direction?.toLowerCase()==="prev"?"prev":"next",T=h.orderBy,$=h.orderDir?.toLowerCase()==="desc"?"desc":"asc",C=h.select,O=C?C.split(",").map(E=>E.trim()):void 0,D;f.allowedIncludes&&h.includes&&(D=(typeof h.includes=="string"?h.includes.split(",").map(ue=>ue.trim()):Array.isArray(h.includes)?h.includes:[]).filter(ue=>typeof ue=="string"&&f.allowedIncludes.includes(ue)),D?.length===0&&(D=void 0));let N=Wn(h,f.filterableFields);b=N.map(E=>({field:E.field,op:E.op,value:String(E.value??"")})),T&&(x={field:T,dir:$});let U={pageSize:v,direction:w};if(R)try{let E=typeof R=="string"?JSON.parse(R):R;U.cursor=await Xt(f,E);}catch{}T&&(U.orderBy=[{field:T,direction:$}]),N.length>0&&(U.where=N.map(E=>[E.field,E.op,E.value])),O&&(U.select=O),D&&(U.include=D);let M=await f.repo.query.paginate(U),H={items:M.data,hasNextPage:M.hasNextPage,hasPrevPage:M.hasPrevPage,nextCursor:_e(M.nextCursor),prevCursor:_e(M.prevCursor)};ye(y,H,{pageSize:v,hasMore:M.hasNextPage});}catch(h){it(y,h,{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 g=p.params||{},f=r(g.repoName,y);if(!f)return;let b=[],x;try{let h=p.body??{},v=Math.min(h.pageSize||f.pageSize,100),R=h.direction==="prev"?"prev":"next";h.where&&(b=h.where.map(C=>({field:String(C[0]),op:C[1],value:String(C[2]??"")}))),h.orderBy&&h.orderBy[0]&&(x={field:h.orderBy[0].field,dir:h.orderBy[0].direction==="desc"?"desc":"asc"});let w={pageSize:v,direction:R};if(h.cursor)try{let C=typeof h.cursor=="string"?JSON.parse(h.cursor):h.cursor;w.cursor=await Xt(f,C);}catch{}if(f.allowedIncludes&&h.includes&&h.includes.length>0){let C=h.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(h.where&&h.where.length>0){if(f.filterableFields){let C=new Set(f.filterableFields),O=h.where.filter(D=>!C.has(D[0]));if(O.length>0){z(y,`Fields not filterable: ${O.map(D=>D[0]).join(", ")}`,400);return}}w.where=h.where;}if(h.orWhere&&h.orWhere.length>0){if(f.filterableFields){let C=new Set(f.filterableFields),O=h.orWhere.filter(D=>!C.has(D[0]));if(O.length>0){z(y,`Fields not filterable: ${O.map(D=>D[0]).join(", ")}`,400);return}}w.orWhere=h.orWhere;}if(h.orWhereGroups&&h.orWhereGroups.length>0){if(f.filterableFields){let C=new Set(f.filterableFields);for(let O of h.orWhereGroups){let D=O.filter(N=>!C.has(N[0]));if(D.length>0){z(y,`Fields not filterable: ${D.map(N=>N[0]).join(", ")}`,400);return}}}w.orWhereGroups=h.orWhereGroups;}h.orderBy&&h.orderBy.length>0&&(w.orderBy=h.orderBy),h.select&&h.select.length>0&&(w.select=h.select);let T=await f.repo.query.paginate(w),$={items:T.data,hasNextPage:T.hasNextPage,hasPrevPage:T.hasPrevPage,nextCursor:_e(T.nextCursor),prevCursor:_e(T.prevCursor)};ye(y,$,{pageSize:v,hasMore:T.hasNextPage});}catch(h){it(y,h,{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 g=p.params||{},f=r(g.repoName,y);if(!f)return;let b=g.id;if(!b){z(y,"Document ID required",400);return}try{let x=await s(f,b);if(!x){z(y,"Document not found",404);return}ye(y,x);}catch(x){it(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 l(p,y){let g=p.params||{},f=r(g.repoName,y);if(f)try{let b=p.body??{},x=Vt(f.schema,b,f.createFields,!1,f.systemKeys);if(!x.success){z(y,x.error,400);return}if(f.validate){let v=await f.validate(x.data,"create");if(v){z(y,v,400);return}}let h;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){z(y,`Missing parent key(s) for subcollection create: ${R.join(", ")}`,400);return}let w=f.parentKeys.map($=>v[$]),T=v[f.documentKey]||Un();h=await f.repo.set(...w,T,v);}else h=await f.repo.create(x.data);ye(y,h,void 0,201);}catch(b){let x=n&&b instanceof Error?b.message:"Failed to create document";z(y,x,500);}}async function u(p,y,g){let f=p.params||{},b=r(f.repoName,y);if(!b)return;let x=f.id;if(!x){z(y,"Document ID required",400);return}try{let h=p.body??{},v=Vt(b.schema,h,b.mutableFields,g,b.systemKeys);if(!v.success){z(y,v.error,400);return}if(b.validate){let $=await b.validate(v.data,"update");if($){z(y,$,400);return}}let R=await s(b,x),w=(R&&o(R,b.pathKey))??[x],T=await b.repo.update(...w,v.data);ye(y,T);}catch(h){let v=n&&h instanceof Error?h.message:"Failed to update document";z(y,v,500);}}async function m(p,y){let g=p.params||{},f=r(g.repoName,y);if(!f)return;if(!f.allowDelete){z(y,"Delete not allowed for this repository",403);return}let b=g.id;if(!b){z(y,"Document ID required",400);return}try{let x=await s(f,b),h=(x&&o(x,f.pathKey))??[b];await f.repo.delete(...h),ye(y,{deleted:!0});}catch(x){let h=n&&x instanceof Error?x.message:"Failed to delete document";z(y,h,500);}}function c(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:l,handleUpdate:u,handleDelete:m,handleOptions:c}}function ct(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 G(e){return {$ref:`#/components/schemas/${e}`}}function B(e){return {description:e,content:{"application/json":{schema:G("ErrorResponse")}}}}function Ce(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function en(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 Ln(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 Hn(e){let t=e.filterableFields??Object.keys(e.schema.shape),n=["eq","ne","lt","lte","gt","gte","in","nin","contains"],r=[];for(let o of t){r.push({name:o,in:"query",schema:{type:"string"},description:`Filter by ${o} (equality)`});for(let s of n)r.push({name:`${o}__${s}`,in:"query",schema:{type:"string"},description:`Filter ${o} with operator ${s}`});}return r}function Vn(){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 Jn(e,t,n,r,o){let s={},a=e.name,d=`${t}/${e.name}`,i=`${d}/{${e.documentKey}}`,l={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};s[d]={get:{operationId:`list${se(e.name)}`,summary:`List ${e.name} (paginated)`,tags:[a],parameters:[...Ln(e),...Hn(e)],responses:{200:en(G(n)),500:B("Internal server error")}},post:{operationId:`create${se(e.name)}`,summary:`Create a ${L(e.name)}`,tags:[a],requestBody:{required:true,content:{"application/json":{schema:G(r??n)}}},responses:{201:Ce("Document created",G(n)),400:B("Validation error"),500:B("Internal server error")}}},s[`${d}/query`]={post:{operationId:`query${se(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[a],requestBody:{required:true,content:{"application/json":{schema:G("QueryRequestBody")}}},responses:{200:en(G(n)),400:B("Invalid query"),500:B("Internal server error")}}};let u={};return u.get={operationId:`get${se(L(e.name))}`,summary:`Get a single ${L(e.name)}`,tags:[a],parameters:[l],responses:{200:Ce("Document found",G(n)),404:B("Document not found"),500:B("Internal server error")}},u.put={operationId:`update${se(L(e.name))}`,summary:`Update a ${L(e.name)} (full replace)`,tags:[a],parameters:[l],requestBody:{required:true,content:{"application/json":{schema:G(o??n)}}},responses:{200:Ce("Document updated",G(n)),400:B("Validation error"),404:B("Document not found"),500:B("Internal server error")}},u.patch={operationId:`patch${se(L(e.name))}`,summary:`Partially update a ${L(e.name)}`,tags:[a],parameters:[l],requestBody:{required:true,content:{"application/json":{schema:{allOf:[G(o??n)],description:"All fields are optional for partial updates"}}}},responses:{200:Ce("Document patched",G(n)),400:B("Validation error"),404:B("Document not found"),500:B("Internal server error")}},e.allowDelete&&(u.delete={operationId:`delete${se(L(e.name))}`,summary:`Delete a ${L(e.name)}`,tags:[a],parameters:[l],responses:{200:Ce("Document deleted",{type:"object",properties:{id:{type:"string"}}}),404:B("Document not found"),500:B("Internal server error")}}),s[i]=u,s}function ut(e,t,n={}){let{title:r="CRUD API",version:o="1.0.0",description:s,servers:a,auth:d=false}=n,i=t==="/"?"":t.replace(/\/$/,""),l={},u={},m=[];l.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string"}},required:["success","error"]},l.QueryRequestBody=Vn();for(let[g,f]of Object.entries(e)){let b=se(L(g)),x=`${b}Create`,h=`${b}Update`;l[b]=ct(f.schema);let v=O=>{let D=O&&O.length>0?O:Object.keys(f.schema.shape),N={};for(let U of D){let M=U.split(".")[0];M&&f.schema.shape[M]&&!f.systemKeys.includes(M)&&(N[M]=f.schema.shape[M]);}return N},R=null,w=v(f.createFields);Object.keys(w).length>0&&(l[x]=ct(zod.z.object(w)),R=x);let T=null,$=v(f.mutableFields);Object.keys($).length>0&&(l[h]=ct(zod.z.object($)),T=h);let C=Jn(f,i,b,R,T);Object.assign(u,C),m.push({name:g,description:`Operations on ${g} (collection: ${f.path})`});}let c={},p;return d==="basic"?(c.basicAuth={type:"http",scheme:"basic"},p=[{basicAuth:[]}]):d==="bearer"&&(c.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},p=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:r,version:o,...s?{description:s}:{}},...a&&a.length>0?{servers:a}:{},paths:u,components:{schemas:l,...Object.keys(c).length>0?{securitySchemes:c}:{}},...p?{security:p}:{},tags:m}}function se(e){return e.charAt(0).toUpperCase()+e.slice(1)}function L(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 Xn(e,t){return `<!DOCTYPE html>
|
|
555
|
+
`;function Re(){return jsxRuntime.jsx("script",{dangerouslySetInnerHTML:{__html:_t}})}function te(e){return "<!DOCTYPE html>"+server.renderToString(e)}var ne=({opts:e,children:t})=>{let{title:n,breadcrumb:r,flash:o,basePath:s="/"}=e;return jsxRuntime.jsxs("html",{lang:"en","data-theme":"corporate",children:[jsxRuntime.jsxs("head",{children:[jsxRuntime.jsx("meta",{charset:"UTF-8"}),jsxRuntime.jsx("meta",{name:"viewport",content:"width=device-width, initial-scale=1"}),jsxRuntime.jsxs("title",{children:[n," \u2014 FRS Admin"]}),jsxRuntime.jsx("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:s,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:[r&&r.length>0&&jsxRuntime.jsx("div",{class:"text-sm breadcrumbs mb-4",children:jsxRuntime.jsx("ul",{children:r.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}),o&&jsxRuntime.jsxs("div",{role:"alert",class:`alert ${o.type==="success"?"alert-success":o.type==="warning"?"alert-warning":"alert-error"} mb-6`,children:[jsxRuntime.jsx("span",{class:"flex-1",children:o.message}),o.action&&jsxRuntime.jsx("a",{href:o.action.href,...o.action.external?{target:"_blank",rel:"noopener noreferrer"}:{},class:"btn btn-sm btn-outline",children:o.action.label})]}),t]}),jsxRuntime.jsx(Re,{})]})]})};function Qe(e,t){return te(jsxRuntime.jsx(ne,{opts:t,children:jsxRuntime.jsx("div",{dangerouslySetInnerHTML:{__html:e}})}))}function qe(e,t){return te(jsxRuntime.jsx(ne,{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 Nt=[{value:"==",label:"="},{value:"!=",label:"\u2260"},{value:"in",label:"in"},{value:"not-in",label:"not in"}],xn=[{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"}],vn=[{value:"array-contains",label:"contains"},{value:"array-contains-any",label:"contains any"}];function Rn(e){switch(e){case "ZodNumber":case "ZodBigInt":case "ZodDate":return xn;case "ZodBoolean":return Nt;case "ZodArray":return vn;default:return Nt}}var re="__null__";function wn(e){return `(function(cb){var i=document.getElementById('${e}');if(!i)return;if(cb.checked){i.dataset._prev=i.value;if(i.tagName==='SELECT'){var o=i.querySelector('option[value="${re}"]');if(!o){o=document.createElement('option');o.value='${re}';o.textContent='\u2205 null';o.dataset._auto='1';i.appendChild(o);}o.selected=true;}else{if(i.type==='number'||i.type==='datetime-local'){i.dataset._type=i.type;i.type='text';}i.value='${re}';i.readOnly=true;}i.style.opacity='0.55';}else{i.style.opacity='';if(i.tagName==='SELECT'){var o2=i.querySelector('option[value="${re}"][data-_auto="1"]');if(o2)o2.remove();var prev=i.dataset._prev||'';for(var k=0;k<i.options.length;k++)i.options[k].selected=(i.options[k].value===prev);}else{if(i.dataset._type){i.type=i.dataset._type;delete i.dataset._type;}i.readOnly=false;i.value=(i.dataset._prev&&i.dataset._prev!=='${re}')?i.dataset._prev:'';}}})(this)`}function Tn(e,t){return `(function(){var h=document.getElementById('${e}');var boxes=document.querySelectorAll('input[data-enum-group="${t}"]');h.value=Array.from(boxes).filter(function(b){return b.checked;}).map(function(b){return b.value;}).join(',');})()`}function we({inputId:e,active:t}){return jsxRuntime.jsxs("label",{class:"flex items-center gap-1 cursor-pointer select-none text-xs text-base-content/60 hover:text-base-content border border-base-300 rounded-md px-1.5 py-1 shrink-0 leading-none h-8",title:"Filter where field IS NULL",children:[jsxRuntime.jsx("input",{type:"checkbox",class:"checkbox checkbox-xs",checked:t,onchange:wn(e)}),jsxRuntime.jsx("span",{children:"\u2205"})]})}function Sn({col:e,active:t}){let n=t?.value??"",r=n===re,o=`fv_input_${e.name.replace(/\./g,"__")}`,s=t?.op,a=s==="in"||s==="not-in";if(e.enumValues&&e.enumValues.length>0){if(a){let d=new Set(n.split(",").map(l=>l.trim()).filter(Boolean)),i=`eg_${e.name.replace(/\./g,"__")}`;return jsxRuntime.jsxs("div",{class:"flex flex-wrap items-center gap-1 w-full",children:[jsxRuntime.jsx("input",{type:"hidden",id:o,name:`fv_${e.name}`,value:n}),e.enumValues.map(l=>jsxRuntime.jsxs("label",{class:"flex items-center gap-1 text-xs border border-base-300 rounded px-2 cursor-pointer hover:bg-base-200",children:[jsxRuntime.jsx("input",{type:"checkbox",class:"checkbox checkbox-xs",value:l,checked:d.has(l),"data-enum-group":i,onchange:Tn(o,i)}),jsxRuntime.jsx("span",{children:l})]},l))]})}return jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.jsxs("select",{id:o,name:`fv_${e.name}`,class:"select select-sm select-bordered w-full",style:r?"opacity:0.55":void 0,children:[jsxRuntime.jsx("option",{value:"",selected:n===""&&!r,children:"\u2014"}),e.enumValues.map(d=>jsxRuntime.jsx("option",{value:d,selected:n===d,children:d},d)),e.nullable&&jsxRuntime.jsx("option",{value:re,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsxRuntime.jsx(we,{inputId:o,active:r})]})}if(e.zodType==="ZodBoolean")return jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.jsxs("select",{id:o,name:`fv_${e.name}`,class:"select select-sm select-bordered w-full",style:r?"opacity:0.55":void 0,children:[jsxRuntime.jsx("option",{value:"",selected:n===""&&!r,children:"\u2014"}),jsxRuntime.jsx("option",{value:"true",selected:n==="true",children:"true"}),jsxRuntime.jsx("option",{value:"false",selected:n==="false",children:"false"}),e.nullable&&jsxRuntime.jsx("option",{value:re,"data-_auto":"1",selected:r,children:"\u2205 null"})]}),e.nullable&&jsxRuntime.jsx(we,{inputId:o,active:r})]});if(e.zodType==="ZodArray"){let d=t?.op==="array-contains-any";return jsxRuntime.jsx("input",{id:o,type:"text",name:`fv_${e.name}`,value:n,placeholder:d?"val1, val2, \u2026":"value",class:"input input-sm input-bordered w-full"})}return e.zodType==="ZodNumber"||e.zodType==="ZodBigInt"?jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.jsx("input",{id:o,type:r?"text":"number",name:`fv_${e.name}`,value:n,placeholder:"value",class:"input input-sm input-bordered w-full",readOnly:r,style:r?"opacity:0.55":void 0,"data-_type":r?"number":void 0}),e.nullable&&jsxRuntime.jsx(we,{inputId:o,active:r})]}):e.zodType==="ZodDate"?jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.jsx("input",{id:o,type:r?"text":"datetime-local",name:`fv_${e.name}`,value:n,class:"input input-sm input-bordered w-full",readOnly:r,style:r?"opacity:0.55":void 0,"data-_type":r?"datetime-local":void 0}),e.nullable&&jsxRuntime.jsx(we,{inputId:o,active:r})]}):jsxRuntime.jsxs("div",{class:"flex items-center gap-1 w-full",children:[jsxRuntime.jsx("input",{id:o,type:"text",name:`fv_${e.name}`,value:n,placeholder:"value",class:"input input-sm input-bordered w-full",readOnly:r,style:r?"opacity:0.55":void 0}),e.nullable&&jsxRuntime.jsx(we,{inputId:o,active:r})]})}function Ue({action:e,columnMeta:t,activeFilters:n,isGroup:r}){let o=Object.fromEntries(n.map(i=>[i.field,i])),s=n.length>0,a=n.length>=2||r&&s,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:s?true:void 0,children:[jsxRuntime.jsxs("summary",{class:"collapse-title text-sm font-medium py-2 min-h-0",children:["Filters",s&&jsxRuntime.jsxs("span",{class:"badge badge-primary badge-sm ml-2",children:[n.length," active"]})]}),jsxRuntime.jsx("div",{class:"collapse-content pb-4 pt-2",children:jsxRuntime.jsxs("form",{method:"get",action:e,children:[jsxRuntime.jsx("div",{class:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:d.map(i=>{let l=Rn(i.zodType),u=o[i.name],m=u?.op??l[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:[l.length>1?jsxRuntime.jsx("select",{name:`fo_${i.name}`,class:"select select-sm select-bordered w-20 shrink-0",children:l.map(c=>jsxRuntime.jsx("option",{value:c.value,selected:c.value===m,children:c.label},c.value))}):jsxRuntime.jsx("input",{type:"hidden",name:`fo_${i.name}`,value:l[0].value}),jsxRuntime.jsx(Sn,{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"}),s&&jsxRuntime.jsx("a",{href:e,class:"btn btn-sm btn-ghost",children:"Clear"}),a&&jsxRuntime.jsxs("span",{class:"text-xs text-warning ml-auto flex items-center gap-1",children:[jsxRuntime.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-4 w-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:jsxRuntime.jsx("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),r?"Collection group queries require a composite index":"Multiple filters may require a composite index"]})]})]})})]})}function Ge(e,t,n,r,o,s){let a=n==="create"?`Create ${e}`:`Edit ${e} / ${r??""}`,d=n==="create"?[{label:"Repositories",href:o},{label:e,href:`${o}/${e}`},{label:"New document"}]:[{label:"Repositories",href:o},{label:e,href:`${o}/${e}`},{label:`Edit ${r??""}`}];return te(jsxRuntime.jsx(ne,{opts:{title:a,breadcrumb:d,basePath:o,flash:s},children:jsxRuntime.jsx("div",{class:"card bg-base-100 border border-base-300",children:jsxRuntime.jsx("div",{class:"card-body p-6",children:jsxRuntime.jsx("div",{dangerouslySetInnerHTML:{__html:t}})})})}))}function We(e,t,n){let r=new URLSearchParams;for(let o of e)r.set(`fv_${o.field}`,o.value),r.set(`fo_${o.field}`,o.op);return t&&(r.set("ob",t.field),r.set("od",t.dir)),n&&r.set("ps",String(n)),r}function Ft(e,t,n,r,o){let s=We(e,r,o);return s.set("cursor",t),s.set("dir",n),`?${s.toString()}`}function Cn(e,t,n,r){let o=We(n,void 0,r);return t?.field===e?t.dir==="asc"&&(o.set("ob",e),o.set("od","desc")):(o.set("ob",e),o.set("od","asc")),`?${o.toString()}`}function On(e,t,n){return `?${We(t,n,e).toString()}`}function Le(e,t,n,r,o,s,a=[],d=[],i=false,l=[],u,m,c,p){let y=`${r}/${e}`,g=`${y}/create`;return te(jsxRuntime.jsxs(ne,{opts:{title:e,breadcrumb:[{label:"Repositories",href:r},{label:e}],basePath:r,flash:s},children:[a.length>0&&jsxRuntime.jsx(Ue,{action:y,columnMeta:a,activeFilters:d,isGroup:p}),c&&jsxRuntime.jsxs("div",{role:"alert",class:`alert ${c.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:c.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:c.type==="index"?"Composite index required":"Query failed"}),jsxRuntime.jsx("div",{class:"text-sm",children:c.message})]}),c.indexUrl&&jsxRuntime.jsx("a",{href:c.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:On(f,d,u),class:`join-item btn btn-xs ${m===f?"btn-active btn-primary":"btn-outline"}`,children:f},f))})]})]}),jsxRuntime.jsx("a",{href:g,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,h=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,h]})},b)}),l.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+l.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??""),h=`${r}/${e}/${encodeURIComponent(x)}/edit`,v=`${r}/${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(Ke,{val:f[R]})},w)),l.map((R,w)=>{let T=f[R.key];if(T==null||T==="")return jsxRuntime.jsx("td",{class:"py-2"},`rel-${w}`);let k=`${r}/${R.targetRepo}?fv_${R.targetKey}=${encodeURIComponent(String(T))}`;return jsxRuntime.jsx("td",{class:"align-middle py-2",children:jsxRuntime.jsx("a",{href:k,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:h,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)})})]})}),(o.hasPrev||o.hasNext)&&jsxRuntime.jsxs("div",{class:"flex justify-center items-center mt-6 gap-2",children:[o.hasPrev?jsxRuntime.jsx("a",{href:Ft(d,o.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"}),o.hasNext?jsxRuntime.jsx("a",{href:Ft(d,o.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 De(e,t){return Qe(e,t)}function He(e,t){return qe(e,t)}function Ve(e,t,n,r,o,s,a,d,i,l,u,m,c,p){return Le(e,t,n,r,o,s,a,d,i,l,u,m,c,p)}function oe(e,t,n,r,o,s){return Ge(e,t,n,r,o,s)}var An=new Set(["<","<=",">",">=","!="]),$n=new Set(["array-contains","array-contains-any"]);function Je(e){return e==="desc"?"DESCENDING":"ASCENDING"}function kn(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function Pn(e,t,n,r,o){let s=[],a=new Set;for(let i of r)if(i.op==="=="||i.op==="in"||i.op==="not-in"){if(a.has(i.field))continue;a.add(i.field),s.push({fieldPath:i.field,order:"ASCENDING"});}for(let i of r)if($n.has(i.op)){if(a.has(i.field))continue;a.add(i.field),s.push({fieldPath:i.field,arrayConfig:"CONTAINS"});}for(let i of r)if(An.has(i.op)){if(a.has(i.field))continue;a.add(i.field);let l=o?.field===i.field?Je(o.dir):"ASCENDING";s.push({fieldPath:i.field,order:l});}if(o&&!a.has(o.field)&&s.push({fieldPath:o.field,order:Je(o.dir)}),s.length===1&&n)return _n(e,t,s[0]);let d=o&&s.some(i=>i.fieldPath===o.field)?Je(o.dir):"ASCENDING";return s.push({fieldPath:"__name__",order:d}),Dn(e,t,n,s)}function Dn(e,t,n,r,o="(default)"){let s=`projects/${e}/databases/${o}/collectionGroups/${t}/indexes/_`,a=[...et(1,s),...Ee(2,n?2:1)];for(let l of r)a.push(...Zt(3,zt(l)));let d=o==="(default)"?"-default-":o,i=encodeURIComponent(jt(a));return `https://console.firebase.google.com/project/${e}/firestore/databases/${d}/indexes?create_composite=${i}`}function En(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function Xe(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function Ye(e,t){return e<<3|t}function et(e,t){let n=Array.from(new TextEncoder().encode(t));return [Ye(e,2),...Xe(n.length),...n]}function Ee(e,t){return [Ye(e,0),...Xe(t)]}function Zt(e,t){return [Ye(e,2),...Xe(t.length),...t]}function zt(e){let t=[...et(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...Ee(3,1)):t.push(...Ee(2,e.order==="DESCENDING"?2:1)),t}function jt(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 _n(e,t,n,r="(default)"){let o=`projects/${e}/databases/${r}/collectionGroups/${t}/fields/${n.fieldPath}`,s=[...et(1,o),...Ee(2,2),...Zt(3,zt(n))],a=r==="(default)"?"-default-":r,d=encodeURIComponent(jt(s));return `https://console.firebase.google.com/project/${e}/firestore/databases/${a}/indexes/automatic?create_exemption=${d}`}function In(e){let t=e,n=[t?.firestore?.projectId,t?.firestore?.app?.options?.projectId,t?.firestore?._settings?.projectId,t?.firestore?.databaseId?.projectId,t?._firestore?.projectId];for(let o of n)if(typeof o=="string"&&o.length>0)return o;return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.FIREBASE_PROJECT_ID||void 0}function le(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function Te(e,t){let n=e??{},r=le(e),o;if(r&&(o=n.message?En(n.message):void 0,!o)){let s=In(t.ref);if(s){let a=kn(t.path);o=Pn(s,a,t.isGroup,t.filters,t.sort);}}return {type:r?"index":"error",message:r?"This query requires a composite index that does not exist yet.":n.message??"Query failed",indexUrl:o}}var Mt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Fn(){let e="";for(let t=0;t<20;t++)e+=Mt.charAt(Math.floor(Math.random()*Mt.length));return e}function Bt(e,t){if(!t)return;let n=e[t];if(typeof n!="string"||!n)return;let r=n.split("/").filter(Boolean),o=[];for(let s=1;s<r.length;s+=2)o.push(r[s]);return o.length>0?o:void 0}async function tt(e,t){let n=e.documentKey??"docId",r=`by${n.charAt(0).toUpperCase()}${n.slice(1)}`;if(typeof e.repo.get[r]=="function")try{let s=await e.repo.get[r](t);if(s)return s}catch{}return (await e.repo.query.by({where:[[n,"==",t]],limit:1}))[0]??null}function nt(e,t,n){let r=e.documentKey??"docId",o=Te(n,{ref:e.repo.ref,path:e.path,isGroup:!!e.isGroup,filters:[{field:r,op:"==",value:t}]});return o.type==="index"?{type:"warning",message:"Loading this document requires a composite index that does not exist yet.",...o.indexUrl?{action:{href:o.indexUrl,label:"Create Index \u2192",external:true}}:{}}:{type:"error",message:o.message}}function P(e,t,n=200){e.status(n).set("Content-Type","text/html; charset=utf-8").send(t);}function rt(e,t){e.status(302).set("Location",t).send("");}function ot(e,t){let n=t.shape,r={};for(let[o,s]of Object.entries(n)){let a=at(s);if(a==="ZodObject"){if(e[o+"__isnull"]==="1"){r[o]=null;continue}let l={},u=false;for(let[p,y]of Object.entries(e))p.startsWith(`${o}.`)&&(l[p.slice(o.length+1)]=y,u=true);if(u){let p=s;for(;;){let y=Z(p);if(y==="ZodOptional"||y==="ZodNullable"||y==="ZodDefault")p=K(p);else break}r[o]=ot(l,p);continue}let m=e[o],c=Array.isArray(m)?m[m.length-1]:m;if(c)try{r[o]=JSON.parse(c);}catch{r[o]=c;}continue}let d=e[o],i=Array.isArray(d)?d[d.length-1]:d;if(e[o+"__isnull"]==="1"){r[o]=null;continue}if(i===void 0||i===""){a==="ZodBoolean"&&(r[o]=false);continue}switch(a){case "ZodBoolean":i==="__null__"?r[o]=null:r[o]=i==="true"||i==="on"||i==="1";break;case "ZodNumber":case "ZodBigInt":r[o]=Number(i);break;case "ZodDate":r[o]=new Date(i);break;case "ZodArray":try{r[o]=JSON.parse(i);}catch{r[o]=i;}break;default:if(i.startsWith("{")||i.startsWith("["))try{r[o]=JSON.parse(i);break}catch{}r[o]=i;}}return r}function Kt(e){let t=null;if(e instanceof Date)t=e;else if(typeof e=="object"&&e!==null&&typeof e.toDate=="function")t=e.toDate();else if(typeof e=="object"&&e!==null&&"_seconds"in e&&"_nanoseconds"in e)t=new Date(e._seconds*1e3+Math.floor(e._nanoseconds/1e6));else if(typeof e=="string"||typeof e=="number"){let r=new Date(e);isNaN(r.getTime())||(t=r);}if(!t||isNaN(t.getTime()))return null;let n=r=>String(r).padStart(2,"0");return `${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`}function at(e){let t=e;for(;;){let n=Z(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=K(t);else return n}}function Zn(e){let t=e;for(;;){let n=Z(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")t=K(t);else return t}}function Qt(e){let t=e;for(;;){let n=Z(t);if(n==="ZodOptional"||n==="ZodNullable")return true;if(n==="ZodDefault"){t=K(t);continue}return false}}function qt(e){let t=Zn(e),n=Z(t);if(n==="ZodEnum"){let r=be(t);return r.length>0?r:void 0}if(n==="ZodNativeEnum"){let r=xe(t),o=Object.values(r).filter(s=>typeof s=="string");return o.length>0?o:void 0}if(n==="ZodLiteral"){let r=ke(t);return typeof r=="string"?[r]:void 0}}function Ut(e,t,n=""){let r={};for(let o of Object.keys(t.shape)){let s=n?`${n}.${o}`:o,a=e[o];if(a===null){r[s]="__null__";continue}if(a===void 0)continue;let d=t.shape[o];for(;;){let l=Z(d);if(l==="ZodOptional"||l==="ZodNullable"||l==="ZodDefault")d=K(d);else break}let i=Z(d);if(i==="ZodObject"&&typeof a=="object"&&a!==null&&!Array.isArray(a)){let l=Ut(a,d,s);Object.assign(r,l);}else if(i==="ZodDate"){let l=Kt(a);l!==null&&(r[s]=l);}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)&&("_seconds"in a||typeof a.toDate=="function")){let l=Kt(a);r[s]=l??JSON.stringify(a,null,2);}else typeof a=="object"?r[s]=JSON.stringify(a,null,2):r[s]=String(a);}return r}function st(e,t){return e.map(n=>({...n,defaultValue:t[n.name]??n.defaultValue,nested:n.nested?st(n.nested,t):void 0}))}function zn(e,t){let n=new Set(["==","!=","<","<=",">",">=","in","not-in","array-contains","array-contains-any"]),r=[];for(let[o,s]of Object.entries(e)){if(!o.startsWith("fv_"))continue;let a=o.slice(3);if(!t.has(a))continue;let d=(s??"").trim();if(!d)continue;let i=e[`fo_${a}`]??"==",l=n.has(i)?i:"==";r.push({field:a,op:l,value:d});}return r}function jn(e){let t="__null__",n=r=>r===t?null:r==="true"?true:r==="false"?false:r!==""&&!isNaN(Number(r))?Number(r):r;return e.map(r=>{if(r.op==="array-contains-any"||r.op==="in"||r.op==="not-in"){let o=r.value.split(",").map(s=>s.trim()).filter(s=>s!==""&&s!==t).map(s=>n(s));return [r.field,r.op,o]}return [r.field,r.op,n(r.value)]})}function Gt(e,t,n=""){let r=[];for(let o of e){let s=n?`${n}.${o}`:o,a=t.shape[o];if(!a){r.push({name:s,zodType:"ZodString"});continue}let d=at(a);if(d==="ZodObject"){let i=a;for(;;){let u=Z(i);if(u==="ZodOptional"||u==="ZodNullable"||u==="ZodDefault")i=K(i);else break}let l=he(i);r.push(...Gt(Object.keys(l),i,s));}else r.push({name:s,zodType:d,nullable:Qt(a),enumValues:qt(a)});}return r}function Mn(e,t){let n=t.split("."),r=e;for(let o of n){for(;;){let a=Z(r);if(a==="ZodOptional"||a==="ZodNullable"||a==="ZodDefault")r=K(r);else break}let s=he(r);if(!(o in s))return null;r=s[o];}return r}function de(e,t){if(!t||t.length===0)return e;let n=[],r=new Map;for(let s of t){let a=s.indexOf(".");if(a===-1)n.push(s);else {let d=s.slice(0,a),i=s.slice(a+1);r.has(d)||r.set(d,[]),r.get(d).push(i);}}let o={};for(let s of n)s in e.shape&&(o[s]=e.shape[s]);for(let[s,a]of r){if(!(s in e.shape))continue;let d=e.shape[s];for(;;){let i=Z(d);if(i==="ZodOptional"||i==="ZodNullable"||i==="ZodDefault")d=K(d);else break}if(Z(d)!=="ZodObject"){o[s]=e.shape[s];continue}o[s]=de(d,a);}return zod.z.object(o)}function ce(e,t){let n=t==="/"?"":t.replace(/\/$/,"");if(process.env.FUNCTIONS_EMULATOR==="true"){let s=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??"demo-project",a=process.env.FUNCTION_REGION??"us-central1",d=(process.env.FUNCTION_TARGET??"").replace(/\./g,"-");return `/${s}/${a}/${d}${n}`}let r=process.env.K_SERVICE,o=e.hostname??e.headers?.host??"";return r&&o.includes("cloudfunctions.net")?`/${r.toLowerCase()}${n}`:n}function Wt(e,t){return {handleDashboard:(l,u)=>{let m=ce(l,t),c=Object.values(e).map(p=>({name:p.name,path:p.path}));P(u,He(c,m));},handleList:async(l,u)=>{let m=l.params.repoName;if(!m){P(u,"Bad request",400);return}let c=e[m];if(!c){P(u,"Repository not found",404);return}let p=c.pageSize??25,y=l.query??{},g=y.cursor,f=y.dir==="prev"?"prev":"next",b=y.ob??"",x=y.od==="desc"?"desc":"asc",h=b?{field:b,dir:x}:void 0,v=parseInt(y.ps??""),R=Number.isFinite(v)&&v>0?Math.min(v,200):p,w=c.listColumns??Object.keys(c.schema.shape),T=c.documentKey??"docId",k=[T,...w.filter(j=>j!==T)],C=c.filterableFields?(()=>{let j=[];for(let V of c.filterableFields)(V.includes(".")||w.includes(V))&&j.push(V);return j})():w,O=(()=>{let j=[];for(let V of C)if(V.includes(".")){let pe=Mn(c.schema,V);j.push({name:V,zodType:pe?at(pe):"ZodString",nullable:pe?Qt(pe):false,enumValues:pe?qt(pe):void 0});}else j.push(...Gt([V],c.schema));return j})(),D=new Set(O.map(j=>j.name)),N=zn(y,D),U=jn(N),M;if(g)try{let j=c.repo.ref;typeof j.doc=="function"&&(M=await j.doc(g).get());}catch{}let H=await c.repo.query.paginate({pageSize:R,cursor:M,direction:f,...U.length>0?{where:U}:{},...h?{orderBy:[{field:h.field,direction:h.dir}]}:{}}).catch(j=>({queryError:Te(j,{ref:c.repo.ref,path:c.path,isGroup:!!c.isGroup,filters:N,sort:h})})),E="queryError"in H,ue=E?[]:H.data,nn=E?"":H.nextCursor?.id??"",rn=E?"":H.prevCursor?.id??"",on=E?H.queryError:void 0,sn=ce(l,t);P(u,Ve(c.name,ue,k,sn,{hasPrev:E?false:H.hasPrevPage,hasNext:E?false:H.hasNextPage,prevCursor:rn,nextCursor:nn},void 0,O,N,c.allowDelete??false,c.relationalMeta,h,R,on,c.isGroup));},handleCreateForm:(l,u)=>{let m=l.params.repoName;if(!m){P(u,"Bad request",400);return}let c=e[m];if(!c){P(u,"Repository not found",404);return}let p=ce(l,t),y=de(c.schema,c.createFields),g=W(y),f=`${p}/${c.name}/create`,b=ee(g,f,"POST","Create document");P(u,oe(c.name,b,"create",null,p));},handleCreateSubmit:async(l,u)=>{let m=l.params.repoName;if(!m){P(u,"Bad request",400);return}let c=e[m];if(!c){P(u,"Repository not found",404);return}let p=ce(l,t),y=l.body??{},g=ot(y,c.schema),f=de(c.schema,c.createFields),b=f.safeParse(g);if(!b.success){let x=W(f),h=`${p}/${c.name}/create`,v=ee(x,h,"POST","Create document"),R=b.error.issues.map(w=>`${w.path.join(".")}: ${w.message}`).join(", ");P(u,oe(c.name,v,"create",null,p,{type:"error",message:`Validation error: ${R}`}),422);return}try{if(c.isGroup&&c.parentKeys&&c.parentKeys.length>0){let x={...b.data};c.createdKey&&(x[c.createdKey]=new Date);let h=c.parentKeys.filter(T=>!x[T]);if(h.length>0)throw new Error(`Missing parent key(s) for subcollection create: ${h.join(", ")}`);let v=c.parentKeys.map(T=>x[T]),R=c.documentKey??"docId",w=x[R]||Fn();await c.repo.set(...v,w,x);}else await c.repo.create(b.data);rt(u,`${p}/${c.name}?flash=created`);}catch(x){let h=de(c.schema,c.createFields),v=W(h),R=`${p}/${c.name}/create`,w=ee(v,R,"POST","Create document");P(u,oe(c.name,w,"create",null,p,{type:"error",message:`Save error: ${x.message}`}),500);}},handleEditForm:async(l,u)=>{let m=l.params.repoName,c=l.params.id;if(!m||!c){P(u,"Bad request",400);return}let p=e[m];if(!p){P(u,"Repository not found",404);return}let y=ce(l,t),g=null;try{g=await tt(p,c);}catch(R){let w=nt(p,c,R),T=le(R)?424:500;P(u,De("",{title:`Edit ${p.name} / ${c}`,basePath:y,breadcrumb:[{label:"Repositories",href:y},{label:p.name,href:`${y}/${p.name}`},{label:`Edit ${c}`}],flash:w}),T);return}if(!g){P(u,"Document not found",404);return}let f=Ut(g,p.schema),b=de(p.schema,p.mutableFields),x=st(W(b),f),h=`${y}/${p.name}/${encodeURIComponent(c)}/edit`,v=ee(x,h,"POST","Save changes");P(u,oe(p.name,v,"edit",c,y));},handleEditSubmit:async(l,u)=>{let m=l.params.repoName,c=l.params.id;if(!m||!c){P(u,"Bad request",400);return}let p=e[m];if(!p){P(u,"Repository not found",404);return}let y=ce(l,t),g=l.body??{},f=ot(g,p.schema),b=de(p.schema,p.mutableFields),h=b.partial().safeParse(f);if(!h.success){let v=Object.fromEntries(Object.entries(g).map(([C,O])=>[C,Array.isArray(O)?O.join(","):O??""])),R=st(W(b),v),w=`${y}/${p.name}/${encodeURIComponent(c)}/edit`,T=ee(R,w,"POST","Save changes"),k=h.error.issues.map(C=>`${C.path.join(".")}: ${C.message}`).join(", ");P(u,oe(p.name,T,"edit",c,y,{type:"error",message:`Validation error: ${k}`}),422);return}try{let v=await tt(p,c),R=(v&&Bt(v,p.pathKey))??[c];await p.repo.update(...R,h.data),rt(u,`${y}/${p.name}?flash=updated`);}catch(v){let R=de(p.schema,p.mutableFields),w=W(R),T=`${y}/${p.name}/${encodeURIComponent(c)}/edit`,k=ee(w,T,"POST","Save changes"),C=le(v)?nt(p,c,v):{type:"error",message:`Save error: ${v.message}`},O=le(v)?424:500;P(u,oe(p.name,k,"edit",c,y,C),O);}},handleDelete:async(l,u)=>{let m=l.params.repoName,c=l.params.id;if(!m||!c){P(u,"Bad request",400);return}let p=e[m];if(!p){P(u,"Repository not found",404);return}if(!p.allowDelete){P(u,"Delete is not allowed for this repository",403);return}let y=ce(l,t);try{let g=await tt(p,c),f=(g&&Bt(g,p.pathKey))??[c];await p.repo.delete(...f),rt(u,`${y}/${p.name}?flash=deleted`);}catch(g){let f=le(g)?nt(p,c,g):{type:"error",message:`Delete error: ${g.message}`},b=le(g)?424:500;P(u,De("",{title:`Delete ${p.name} / ${c}`,basePath:y,breadcrumb:[{label:"Repositories",href:y},{label:p.name,href:`${y}/${p.name}`},{label:`Delete ${c}`}],flash:f}),b);}}}}function Bn(e){let t=[],n=e.replace(/[.*+?^${}()|[\]\\]/g,r=>r===":"?r:`\\${r}`).replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,(r,o)=>(t.push(o),"([^/]+)"));return {pattern:new RegExp(`^${n}$`),paramNames:t}}function Kn(e){let t=e.path??e.url??"/",n=t.indexOf("?");return n===-1?t:t.slice(0,n)}var X=class{constructor(){this.routes=[];this.middlewares=[];this.notFoundHandler=(t,n)=>{n.status(404).send("Not Found");};this.errorHandler=(t,n,r)=>{console.error("[MiniRouter]",t),r.status(500).send("Internal Server Error");};}use(t){return this.middlewares.push(t),this}get(t,n){return this.addRoute("GET",t,n)}post(t,n){return this.addRoute("POST",t,n)}put(t,n){return this.addRoute("PUT",t,n)}patch(t,n){return this.addRoute("PATCH",t,n)}delete(t,n){return this.addRoute("DELETE",t,n)}onNotFound(t){return this.notFoundHandler=t,this}onError(t){return this.errorHandler=t,this}addRoute(t,n,r){let{pattern:o,paramNames:s}=Bn(n);return this.routes.push({method:t.toUpperCase(),pattern:o,paramNames:s,handler:r}),this}async handle(t,n){let r=(t.method??"GET").toUpperCase(),o=Kn(t),s=null,a={};for(let l of this.routes){if(l.method!==r)continue;let u=o.match(l.pattern);if(u){s=l,a={},l.paramNames.forEach((m,c)=>{a[m]=decodeURIComponent(u[c+1]??"");});break}}let d=Object.assign(t,{params:a}),i=s?s.handler:this.notFoundHandler;try{await this.runMiddlewareChain(d,n,i);}catch(l){this.errorHandler(l,t,n);}}async runMiddlewareChain(t,n,r){let o=0,s=async()=>{if(o<this.middlewares.length){let a=this.middlewares[o++];await a(t,n,s);}else await r(t,n);};await s();}};async function Qn(e){return typeof e.rawBody=="string"?e.rawBody:Buffer.isBuffer(e.rawBody)?e.rawBody.toString("utf8"):""}function qn(e){let t={};if(!e)return t;for(let n of e.split("&")){let r=n.indexOf("=");if(r===-1)continue;let o=decodeURIComponent(n.slice(0,r).replace(/\+/g," ")),s=decodeURIComponent(n.slice(r+1).replace(/\+/g," ")),a=t[o];a===void 0?t[o]=s:Array.isArray(a)?a.push(s):t[o]=[a,s];}return t}function Lt(e){let{basePath:t="/",repos:n,parseBody:r=true,auth:o,middleware:s=[],httpsOptions:a}=e,d=t==="/"?"":t.replace(/\/$/,""),i={};for(let[c,p]of Object.entries(n)){let y=p.schema??p.repo.schema??null;if(!y)throw new Error(`[createAdminServer] Repository "${c}" has no Zod schema. Either use createRepositoryConfig(schema)(config) or pass schema: explicitly.`);let g,f,b;if(p.fieldsConfig){let v=p.fieldsConfig;g=[],f=[],b=[];for(let[R,w]of Object.entries(v))for(let T of w)T==="filterable"?g.push(R):T==="mutable"?f.push(R):T==="create"&&b.push(R);g.length===0&&(g=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 h={name:c,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:g,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[c]=h;}let l=Wt(i,d),u=new X;if(r&&u.use(async(c,p,y)=>{let g=c,f=String(g.headers?.["content-type"]??"");if(f.includes("application/x-www-form-urlencoded")){let b=await Qn(g);c.body=qn(b);}else if(f.includes("application/json")&&typeof g.body=="string")try{c.body=JSON.parse(g.body);}catch{}await y();}),o)if(typeof o=="function")u.use(o);else {let c=o.realm??"Admin",p="Basic "+Buffer.from(`${o.username}:${o.password}`).toString("base64");u.use((y,g,f)=>{if((y.headers?.authorization??"")!==p){g.status(401).set("WWW-Authenticate",`Basic realm="${c}"`).set("Content-Type","text/plain").send("Unauthorized");return}f();});}for(let c of s)u.use(c);u.get(`${d}/`,l.handleDashboard),u.get(`${d}`,l.handleDashboard),u.get(`${d}/:repoName`,l.handleList),u.get(`${d}/:repoName/create`,l.handleCreateForm),u.post(`${d}/:repoName/create`,l.handleCreateSubmit),u.get(`${d}/:repoName/:id/edit`,l.handleEditForm),u.post(`${d}/:repoName/:id/edit`,l.handleEditSubmit),u.post(`${d}/:repoName/:id/delete`,l.handleDelete);let m=async(c,p)=>{await u.handle(c,p);};return a&&(m.httpsOptions=a),m}function lt(e,t,n=200){let r=_(t);e.status(n).set("Content-Type","application/json; charset=utf-8").send(JSON.stringify(r));}function ye(e,t,n,r=200){lt(e,{success:true,data:t,meta:n},r);}function z(e,t,n=400){lt(e,{success:false,error:t},n);}function it(e,t,n,r,o){let s=Te(t,n),a=s.type==="index",d=a?424:500,l={success:false,error:a?s.message:o&&t instanceof Error?t.message:r};a&&(l.errorType="index",s.indexUrl&&(l.indexUrl=s.indexUrl)),lt(e,l,d);}var Ht="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Un(){let e="";for(let t=0;t<20;t++)e+=Ht.charAt(Math.floor(Math.random()*Ht.length));return e}function me(e){let t=e._def??e.def;if(!t)return e;let n=t.typeName??t.type;if(n==="ZodDate"||n==="date")return zod.z.preprocess(r=>ze(r)??r,e);if(n==="ZodObject"||n==="object"){let r=e.shape,o={};for(let[s,a]of Object.entries(r))o[s]=me(a);return zod.z.object(o)}if(n==="ZodArray"||n==="array"){let r=t.element??t.type;if(r)return zod.z.array(me(r))}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(r)return me(r).optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(r)return me(r).nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType,o=t.defaultValue;if(r){let s=me(r);return typeof o=="function"?s.default(o()):s.default(o)}}return e}function Gn(e,t,n=[]){let r=e.shape,o={},s=t&&t.length>0?t:Object.keys(r);for(let a of s){if(n.includes(a))continue;let d=a.split(".")[0];d&&r[d]&&(o[d]=r[d]);}return zod.z.object(o)}function Vt(e,t,n,r=false,o=[]){try{let s=Gn(e,n,o),a=r?s.partial():s;return {success:!0,data:(Ze()==="normalize"?me(a):a).parse(t)}}catch(s){return s instanceof zod.z.ZodError?{success:false,error:`Validation failed: ${s.issues.map(d=>`${d.path.join(".")}: ${d.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}function Wn(e,t){let n=[],r=t?new Set(t):null,o={eq:"==",ne:"!=",lt:"<",lte:"<=",gt:">",gte:">=",in:"in",nin:"not-in",contains:"array-contains",containsAny:"array-contains-any"};for(let[s,a]of Object.entries(e)){if(a===void 0||["cursor","limit","pageSize","orderBy","orderDir","select"].includes(s))continue;let d=Array.isArray(a)?a[0]:a;if(d===void 0||d==="")continue;let i=s.match(/^(\w+)__(\w+)$/),l,u="==";if(i&&i[1]&&i[2]){l=i[1];let c=i[2];if(o[c])u=o[c];else continue}else if(!i)l=s;else continue;if(r&&!r.has(l))continue;let m=d;u==="in"||u==="not-in"||u==="array-contains-any"?m=d.split(",").map(c=>Jt(c.trim())):m=Jt(d),n.push({field:l,op:u,value:m});}return n}function Jt(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 _e(e){return e?{docId:e.id}:null}async function Xt(e,t){if(!t||typeof t!="object")return;let n=t.docId;if(typeof n=="string")try{let r=e.repo.ref;if(typeof r.doc!="function")return;let o=await r.doc(n).get();return o.exists?o:void 0}catch{return}}function Yt(e,t,n){function r(p,y){return !p||!e[p]?(z(y,`Repository "${p}" not found`,404),null):e[p]}function o(p,y){if(!y)return;let g=p[y];if(typeof g!="string"||!g)return;let f=g.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 s(p,y){let g=`by${p.documentKey.charAt(0).toUpperCase()}${p.documentKey.slice(1)}`,f=p.repo.get[g];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 g=p.params||{},f=r(g.repoName,y);if(!f)return;let b=[],x;try{let h=p.query??{},v=Math.min(Number(h.pageSize)||f.pageSize,100),R=h.cursor,w=h.direction?.toLowerCase()==="prev"?"prev":"next",T=h.orderBy,k=h.orderDir?.toLowerCase()==="desc"?"desc":"asc",C=h.select,O=C?C.split(",").map(E=>E.trim()):void 0,D;f.allowedIncludes&&h.includes&&(D=(typeof h.includes=="string"?h.includes.split(",").map(ue=>ue.trim()):Array.isArray(h.includes)?h.includes:[]).filter(ue=>typeof ue=="string"&&f.allowedIncludes.includes(ue)),D?.length===0&&(D=void 0));let N=Wn(h,f.filterableFields);b=N.map(E=>({field:E.field,op:E.op,value:String(E.value??"")})),T&&(x={field:T,dir:k});let U={pageSize:v,direction:w};if(R)try{let E=typeof R=="string"?JSON.parse(R):R;U.cursor=await Xt(f,E);}catch{}T&&(U.orderBy=[{field:T,direction:k}]),N.length>0&&(U.where=N.map(E=>[E.field,E.op,E.value])),O&&(U.select=O),D&&(U.include=D);let M=await f.repo.query.paginate(U),H={items:M.data,hasNextPage:M.hasNextPage,hasPrevPage:M.hasPrevPage,nextCursor:_e(M.nextCursor),prevCursor:_e(M.prevCursor)};ye(y,H,{pageSize:v,hasMore:M.hasNextPage});}catch(h){it(y,h,{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 g=p.params||{},f=r(g.repoName,y);if(!f)return;let b=[],x;try{let h=p.body??{},v=Math.min(h.pageSize||f.pageSize,100),R=h.direction==="prev"?"prev":"next";h.where&&(b=h.where.map(C=>({field:String(C[0]),op:C[1],value:String(C[2]??"")}))),h.orderBy&&h.orderBy[0]&&(x={field:h.orderBy[0].field,dir:h.orderBy[0].direction==="desc"?"desc":"asc"});let w={pageSize:v,direction:R};if(h.cursor)try{let C=typeof h.cursor=="string"?JSON.parse(h.cursor):h.cursor;w.cursor=await Xt(f,C);}catch{}if(f.allowedIncludes&&h.includes&&h.includes.length>0){let C=h.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(h.where&&h.where.length>0){if(f.filterableFields){let C=new Set(f.filterableFields),O=h.where.filter(D=>!C.has(D[0]));if(O.length>0){z(y,`Fields not filterable: ${O.map(D=>D[0]).join(", ")}`,400);return}}w.where=h.where;}if(h.orWhere&&h.orWhere.length>0){if(f.filterableFields){let C=new Set(f.filterableFields),O=h.orWhere.filter(D=>!C.has(D[0]));if(O.length>0){z(y,`Fields not filterable: ${O.map(D=>D[0]).join(", ")}`,400);return}}w.orWhere=h.orWhere;}if(h.orWhereGroups&&h.orWhereGroups.length>0){if(f.filterableFields){let C=new Set(f.filterableFields);for(let O of h.orWhereGroups){let D=O.filter(N=>!C.has(N[0]));if(D.length>0){z(y,`Fields not filterable: ${D.map(N=>N[0]).join(", ")}`,400);return}}}w.orWhereGroups=h.orWhereGroups;}h.orderBy&&h.orderBy.length>0&&(w.orderBy=h.orderBy),h.select&&h.select.length>0&&(w.select=h.select);let T=await f.repo.query.paginate(w),k={items:T.data,hasNextPage:T.hasNextPage,hasPrevPage:T.hasPrevPage,nextCursor:_e(T.nextCursor),prevCursor:_e(T.prevCursor)};ye(y,k,{pageSize:v,hasMore:T.hasNextPage});}catch(h){it(y,h,{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 g=p.params||{},f=r(g.repoName,y);if(!f)return;let b=g.id;if(!b){z(y,"Document ID required",400);return}try{let x=await s(f,b);if(!x){z(y,"Document not found",404);return}ye(y,x);}catch(x){it(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 l(p,y){let g=p.params||{},f=r(g.repoName,y);if(f)try{let b=p.body??{},x=Vt(f.schema,b,f.createFields,!1,f.systemKeys);if(!x.success){z(y,x.error,400);return}if(f.validate){let v=await f.validate(x.data,"create");if(v){z(y,v,400);return}}let h;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(k=>!v[k]);if(R.length>0){z(y,`Missing parent key(s) for subcollection create: ${R.join(", ")}`,400);return}let w=f.parentKeys.map(k=>v[k]),T=v[f.documentKey]||Un();h=await f.repo.set(...w,T,v);}else h=await f.repo.create(x.data);ye(y,h,void 0,201);}catch(b){let x=n&&b instanceof Error?b.message:"Failed to create document";z(y,x,500);}}async function u(p,y,g){let f=p.params||{},b=r(f.repoName,y);if(!b)return;let x=f.id;if(!x){z(y,"Document ID required",400);return}try{let h=p.body??{},v=Vt(b.schema,h,b.mutableFields,g,b.systemKeys);if(!v.success){z(y,v.error,400);return}if(b.validate){let k=await b.validate(v.data,"update");if(k){z(y,k,400);return}}let R=await s(b,x),w=(R&&o(R,b.pathKey))??[x],T=await b.repo.update(...w,v.data);ye(y,T);}catch(h){let v=n&&h instanceof Error?h.message:"Failed to update document";z(y,v,500);}}async function m(p,y){let g=p.params||{},f=r(g.repoName,y);if(!f)return;if(!f.allowDelete){z(y,"Delete not allowed for this repository",403);return}let b=g.id;if(!b){z(y,"Document ID required",400);return}try{let x=await s(f,b),h=(x&&o(x,f.pathKey))??[b];await f.repo.delete(...h),ye(y,{deleted:!0});}catch(x){let h=n&&x instanceof Error?x.message:"Failed to delete document";z(y,h,500);}}function c(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:l,handleUpdate:u,handleDelete:m,handleOptions:c}}function ct(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 G(e){return {$ref:`#/components/schemas/${e}`}}function B(e){return {description:e,content:{"application/json":{schema:G("ErrorResponse")}}}}function Ce(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function en(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 Ln(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 Hn(e){let t=e.filterableFields??Object.keys(e.schema.shape),n=["eq","ne","lt","lte","gt","gte","in","nin","contains"],r=[];for(let o of t){r.push({name:o,in:"query",schema:{type:"string"},description:`Filter by ${o} (equality)`});for(let s of n)r.push({name:`${o}__${s}`,in:"query",schema:{type:"string"},description:`Filter ${o} with operator ${s}`});}return r}function Vn(){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 Jn(e,t,n,r,o){let s={},a=e.name,d=`${t}/${e.name}`,i=`${d}/{${e.documentKey}}`,l={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};s[d]={get:{operationId:`list${se(e.name)}`,summary:`List ${e.name} (paginated)`,tags:[a],parameters:[...Ln(e),...Hn(e)],responses:{200:en(G(n)),500:B("Internal server error")}},post:{operationId:`create${se(e.name)}`,summary:`Create a ${L(e.name)}`,tags:[a],requestBody:{required:true,content:{"application/json":{schema:G(r??n)}}},responses:{201:Ce("Document created",G(n)),400:B("Validation error"),500:B("Internal server error")}}},s[`${d}/query`]={post:{operationId:`query${se(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[a],requestBody:{required:true,content:{"application/json":{schema:G("QueryRequestBody")}}},responses:{200:en(G(n)),400:B("Invalid query"),500:B("Internal server error")}}};let u={};return u.get={operationId:`get${se(L(e.name))}`,summary:`Get a single ${L(e.name)}`,tags:[a],parameters:[l],responses:{200:Ce("Document found",G(n)),404:B("Document not found"),500:B("Internal server error")}},u.put={operationId:`update${se(L(e.name))}`,summary:`Update a ${L(e.name)} (full replace)`,tags:[a],parameters:[l],requestBody:{required:true,content:{"application/json":{schema:G(o??n)}}},responses:{200:Ce("Document updated",G(n)),400:B("Validation error"),404:B("Document not found"),500:B("Internal server error")}},u.patch={operationId:`patch${se(L(e.name))}`,summary:`Partially update a ${L(e.name)}`,tags:[a],parameters:[l],requestBody:{required:true,content:{"application/json":{schema:{allOf:[G(o??n)],description:"All fields are optional for partial updates"}}}},responses:{200:Ce("Document patched",G(n)),400:B("Validation error"),404:B("Document not found"),500:B("Internal server error")}},e.allowDelete&&(u.delete={operationId:`delete${se(L(e.name))}`,summary:`Delete a ${L(e.name)}`,tags:[a],parameters:[l],responses:{200:Ce("Document deleted",{type:"object",properties:{id:{type:"string"}}}),404:B("Document not found"),500:B("Internal server error")}}),s[i]=u,s}function ut(e,t,n={}){let{title:r="CRUD API",version:o="1.0.0",description:s,servers:a,auth:d=false}=n,i=t==="/"?"":t.replace(/\/$/,""),l={},u={},m=[];l.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string"}},required:["success","error"]},l.QueryRequestBody=Vn();for(let[g,f]of Object.entries(e)){let b=se(L(g)),x=`${b}Create`,h=`${b}Update`;l[b]=ct(f.schema);let v=O=>{let D=O&&O.length>0?O:Object.keys(f.schema.shape),N={};for(let U of D){let M=U.split(".")[0];M&&f.schema.shape[M]&&!f.systemKeys.includes(M)&&(N[M]=f.schema.shape[M]);}return N},R=null,w=v(f.createFields);Object.keys(w).length>0&&(l[x]=ct(zod.z.object(w)),R=x);let T=null,k=v(f.mutableFields);Object.keys(k).length>0&&(l[h]=ct(zod.z.object(k)),T=h);let C=Jn(f,i,b,R,T);Object.assign(u,C),m.push({name:g,description:`Operations on ${g} (collection: ${f.path})`});}let c={},p;return d==="basic"?(c.basicAuth={type:"http",scheme:"basic"},p=[{basicAuth:[]}]):d==="bearer"&&(c.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},p=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:r,version:o,...s?{description:s}:{}},...a&&a.length>0?{servers:a}:{},paths:u,components:{schemas:l,...Object.keys(c).length>0?{securitySchemes:c}:{}},...p?{security:p}:{},tags:m}}function se(e){return e.charAt(0).toUpperCase()+e.slice(1)}function L(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 Xn(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 Yn(e,t){let n=t==="/"?"":t.replace(/\/$/,"");if(process.env.FUNCTIONS_EMULATOR==="true"){let s=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??"demo-project",a=process.env.FUNCTION_REGION??"us-central1",d=process.env.FUNCTION_TARGET??"";return `/${s}/${a}/${d}${n}`}let r=process.env.K_SERVICE,o=e?.hostname??e?.headers?.host??"";return r&&o.includes("cloudfunctions.net")?`/${r.toLowerCase()}${n}`:n}async function er(e){return typeof e.rawBody=="string"?e.rawBody:Buffer.isBuffer(e.rawBody)?e.rawBody.toString("utf8"):""}function tn(e){let{basePath:t="/",repos:n,parseBody:r=true,auth:o,middleware:s=[],verbose:a=false,httpsOptions:d}=e,i=t==="/"?"":t.replace(/\/$/,""),l={};for(let[b,x]of Object.entries(n)){let h=x.schema??x.repo.schema??null;if(!h)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[O,D]of Object.entries(C))for(let N of D)N==="filterable"?v.push(O):N==="mutable"?R.push(O):N==="create"&&w.push(O);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
|
|
566
|
+
</html>`}function Yn(e,t){let n=t==="/"?"":t.replace(/\/$/,"");if(process.env.FUNCTIONS_EMULATOR==="true"){let s=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??"demo-project",a=process.env.FUNCTION_REGION??"us-central1",d=process.env.FUNCTION_TARGET??"";return `/${s}/${a}/${d}${n}`}let r=process.env.K_SERVICE,o=e?.hostname??e?.headers?.host??"";return r&&o.includes("cloudfunctions.net")?`/${r.toLowerCase()}${n}`:n}async function er(e){return typeof e.rawBody=="string"?e.rawBody:Buffer.isBuffer(e.rawBody)?e.rawBody.toString("utf8"):""}function tn(e){let{basePath:t="/",repos:n,parseBody:r=true,auth:o,middleware:s=[],verbose:a=false,httpsOptions:d}=e,i=t==="/"?"":t.replace(/\/$/,""),l={};for(let[b,x]of Object.entries(n)){let h=x.schema??x.repo.schema??null;if(!h)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[O,D]of Object.entries(C))for(let N of D)N==="filterable"?v.push(O):N==="mutable"?R.push(O):N==="create"&&w.push(O);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 k={name:b,path:x.path,repo:x.repo,schema:h,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};l[b]=k;}let u=Yt(l,i,a),m=e.openapi,c=m&&typeof m=="object"?m:{},p=null;function y(){if(!p){let b=o&&typeof o!="function"?"basic":o?"bearer":false;p=ut(l,i,{...c,auth:c.auth??b});}return p}let g=new X;if(g.use((b,x,h)=>{x.set("Access-Control-Allow-Origin","*"),x.set("Access-Control-Allow-Credentials","true"),h();}),r&&g.use(async(b,x,h)=>{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 er(v);b.body=JSON.parse(w);}catch{}}await h();}),o)if(typeof o=="function")g.use(o);else {let b=o.realm??"API",x="Basic "+Buffer.from(`${o.username}:${o.password}`).toString("base64");g.use((h,v,R)=>{if((h.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 s)g.use(b);if(m!==false){let b=`${i}/__spec.json`,x=`${i}/__docs`;g.get(b,(h,v)=>{let R=y();v.status(200).set("Content-Type","application/json; charset=utf-8").send(JSON.stringify(R,null,2));}),g.get(x,(h,v)=>{let R=Yn(h,i)+"/__spec.json",w=Xn(c.title??"CRUD API",R);v.status(200).set("Content-Type","text/html; charset=utf-8").send(w);});}g.use((b,x,h)=>{if(b.method==="OPTIONS"){u.handleOptions(b,x);return}h();}),g.get(`${i}/:repoName`,u.handleList),g.post(`${i}/:repoName/query`,u.handleQuery),g.get(`${i}/:repoName/:id`,u.handleGet),g.post(`${i}/:repoName`,u.handleCreate),g.put(`${i}/:repoName/:id`,(b,x)=>u.handleUpdate(b,x,false)),g.patch(`${i}/:repoName/:id`,(b,x)=>u.handleUpdate(b,x,true)),g.delete(`${i}/:repoName/:id`,u.handleDelete);let f=async(b,x)=>{await g.handle(b,x);};return f.spec=y,d&&(f.httpsOptions=d),f}function Jo(e){return t=>({...t,schema:e,type:null,documentRef:null,update:null})}function Xo(e,t){let n={...e};for(let r in t)t[r]&&(n[r]={...e[r],relationalKeys:t[r]});return n}var pt=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]=Me(this.db,this.mapping[t],{});for(let t of Object.keys(this.mapping))this.allRepositories[t]=Me(this.db,this.mapping[t],this.allRepositories);}getRepository(t){return this.allRepositories[t]}};function Yo(e,t){let n=new pt(e,t),r=Object.keys(t);return new Proxy(n,{get(o,s){return typeof s=="string"&&s in t?o.getRepository(s):o[s]},ownKeys(){return r},getOwnPropertyDescriptor(o,s){if(typeof s=="string"&&s in t)return {configurable:true,enumerable:true,writable:false}}})}exports.MiniRouter=X;exports.RepositoryMapping=pt;exports.applyPaginationQueryOptions=Y;exports.buildAndExecuteQuery=ae;exports.buildRepositoryRelations=Xo;exports.coerceToDate=ze;exports.createAdminServer=Lt;exports.createCrudServer=tn;exports.createPaginationIterator=je;exports.createRepositoryConfig=Jo;exports.createRepositoryMapping=Yo;exports.executePaginatedQuery=$e;exports.getDateHandling=Ze;exports.normalizeTimestamps=Ae;exports.setDateHandling=ln;//# sourceMappingURL=index.cjs.map
|
|
567
567
|
//# sourceMappingURL=index.cjs.map
|