@lpdjs/firestore-repo-service 2.6.49 → 2.6.52
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{create-servers-rVXsgSQE.d.cts → create-servers-BlkEoNpP.d.cts} +3 -3
- package/dist/{create-servers-CwNxQQQ1.d.ts → create-servers-Cj3GnkyB.d.ts} +3 -3
- package/dist/{index-D0clYX8B.d.ts → index-BiPDgqCE.d.ts} +1 -1
- package/dist/{index-CsuESJ5D.d.cts → index-DY0lmoPn.d.cts} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +5 -5
- package/dist/index.d.ts +5 -5
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/llms-full.txt +1 -1
- package/dist/llms.txt +1 -1
- package/dist/{openapi-BEBoB0y3.d.cts → openapi-DA2HQTaL.d.cts} +1 -1
- package/dist/{openapi-ltqn60oy.d.ts → openapi-b7qM1WGb.d.ts} +1 -1
- package/dist/servers/admin/index.d.cts +2 -2
- package/dist/servers/admin/index.d.ts +2 -2
- package/dist/servers/crud/index.cjs +1 -1
- package/dist/servers/crud/index.cjs.map +1 -1
- package/dist/servers/crud/index.d.cts +4 -4
- package/dist/servers/crud/index.d.ts +4 -4
- package/dist/servers/crud/index.js +1 -1
- package/dist/servers/crud/index.js.map +1 -1
- package/dist/servers/index.cjs +19 -19
- package/dist/servers/index.cjs.map +1 -1
- package/dist/servers/index.d.cts +5 -5
- package/dist/servers/index.d.ts +5 -5
- package/dist/servers/index.js +19 -19
- package/dist/servers/index.js.map +1 -1
- package/dist/{types-DG5Ys5AM.d.ts → types-BBV7SbAk.d.ts} +3 -3
- package/dist/{types-DQwhnE4-.d.cts → types-T6CFn4gs.d.cts} +3 -3
- package/package.json +1 -1
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { HttpsOptions } from 'firebase-functions/v2/https';
|
|
2
|
-
import { C as ConfiguredRepository, a as CrudServerOptions } from '../../types-
|
|
3
|
-
export { A as ApiResponse, b as CrudRepoConfig, c as CrudRepoEntry, d as CrudRepoRegistry, F as FieldRole, L as ListResponseData, O as OpenAPISpecOptions, Q as QueryRequestBody, R as RepoFieldPath, e as RepoRelationKeys, U as UserFieldPath } from '../../types-
|
|
4
|
-
import { O as OpenAPIDocument } from '../../openapi-
|
|
5
|
-
export { g as generateOpenAPISpec } from '../../openapi-
|
|
2
|
+
import { C as ConfiguredRepository, a as CrudServerOptions } from '../../types-T6CFn4gs.cjs';
|
|
3
|
+
export { A as ApiResponse, b as CrudRepoConfig, c as CrudRepoEntry, d as CrudRepoRegistry, F as FieldRole, L as ListResponseData, O as OpenAPISpecOptions, Q as QueryRequestBody, R as RepoFieldPath, e as RepoRelationKeys, U as UserFieldPath } from '../../types-T6CFn4gs.cjs';
|
|
4
|
+
import { O as OpenAPIDocument } from '../../openapi-DA2HQTaL.cjs';
|
|
5
|
+
export { g as generateOpenAPISpec } from '../../openapi-DA2HQTaL.cjs';
|
|
6
6
|
import '../../firebase-auth-DZ8lb2Ec.cjs';
|
|
7
7
|
import '../../types-B4dMmfet.cjs';
|
|
8
8
|
import 'zod';
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { HttpsOptions } from 'firebase-functions/v2/https';
|
|
2
|
-
import { C as ConfiguredRepository, a as CrudServerOptions } from '../../types-
|
|
3
|
-
export { A as ApiResponse, b as CrudRepoConfig, c as CrudRepoEntry, d as CrudRepoRegistry, F as FieldRole, L as ListResponseData, O as OpenAPISpecOptions, Q as QueryRequestBody, R as RepoFieldPath, e as RepoRelationKeys, U as UserFieldPath } from '../../types-
|
|
4
|
-
import { O as OpenAPIDocument } from '../../openapi-
|
|
5
|
-
export { g as generateOpenAPISpec } from '../../openapi-
|
|
2
|
+
import { C as ConfiguredRepository, a as CrudServerOptions } from '../../types-BBV7SbAk.js';
|
|
3
|
+
export { A as ApiResponse, b as CrudRepoConfig, c as CrudRepoEntry, d as CrudRepoRegistry, F as FieldRole, L as ListResponseData, O as OpenAPISpecOptions, Q as QueryRequestBody, R as RepoFieldPath, e as RepoRelationKeys, U as UserFieldPath } from '../../types-BBV7SbAk.js';
|
|
4
|
+
import { O as OpenAPIDocument } from '../../openapi-b7qM1WGb.js';
|
|
5
|
+
export { g as generateOpenAPISpec } from '../../openapi-b7qM1WGb.js';
|
|
6
6
|
import '../../firebase-auth-DZ8lb2Ec.js';
|
|
7
7
|
import '../../types-DyKJJ9UQ.js';
|
|
8
8
|
import 'zod';
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {randomBytes}from'crypto';import {z}from'zod';import {Timestamp}from'firebase-admin/firestore';import {extendZodWithOpenApi,getOpenApiMetadata,OpenAPIRegistry,OpenApiGeneratorV31}from'@asteasolutions/zod-to-openapi';import {Hono}from'hono';import {getRequestListener}from'@hono/node-server';import {AsyncLocalStorage}from'async_hooks';var ie=Object.defineProperty;var et=Object.getOwnPropertyDescriptor;var tt=Object.getOwnPropertyNames;var nt=Object.prototype.hasOwnProperty;var rt=(e,t)=>()=>(e&&(t=e(e=0)),t);var ot=(e,t)=>{for(var n in t)ie(e,n,{get:t[n],enumerable:true});},st=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of tt(t))!nt.call(e,o)&&o!==n&&ie(e,o,{get:()=>t[o],enumerable:!(s=et(t,o))||s.enumerable});return e};var it=e=>st(ie({},"__esModule",{value:true}),e);var Ve={};ot(Ve,{DEFAULT_HTML_CSP:()=>Qe,securityHeaders:()=>Qt});function Qt(e={}){let t=e.csp===void 0?Qe:e.csp,n=e.frameOptions===void 0?"DENY":e.frameOptions,s=e.referrerPolicy===void 0?"no-referrer":e.referrerPolicy,o=e.cacheControl===void 0?"private, no-store":e.cacheControl;return async(d,a,c)=>{typeof a?.setHeader=="function"&&(a.setHeader("X-Content-Type-Options","nosniff"),n&&a.setHeader("X-Frame-Options",n),s&&a.setHeader("Referrer-Policy",s),o&&a.setHeader("Cache-Control",o),t&&a.setHeader("Content-Security-Policy",t)),await c();}}var We,Je,Qe,Xe=rt(()=>{We="https://cdn.jsdelivr.net",Je="https://www.gstatic.com",Qe=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${We} ${Je}`,`style-src 'self' 'unsafe-inline' ${We}`,`connect-src 'self' ${Je} https://*.googleapis.com https://*.firebaseio.com https://identitytoolkit.googleapis.com`,"img-src 'self' data:","font-src 'self' data:","frame-ancestors 'none'","base-uri 'self'","form-action 'self'"].join("; ");});var Ae="preserve";function ce(){return Ae}function at(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function Te(e){if(e==null)return null;if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(e instanceof Timestamp)return e.toDate();if(at(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 Oe(e){return e}var dt=new Set(["<","<=",">",">=","!="]),ut=new Set(["array-contains","array-contains-any"]);function de(e){return e==="desc"?"DESCENDING":"ASCENDING"}function pt(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function lt(e,t,n,s,o){let d=[],a=new Set;for(let u of s)if(u.op==="=="||u.op==="in"||u.op==="not-in"){if(a.has(u.field))continue;a.add(u.field),d.push({fieldPath:u.field,order:"ASCENDING"});}for(let u of s)if(ut.has(u.op)){if(a.has(u.field))continue;a.add(u.field),d.push({fieldPath:u.field,arrayConfig:"CONTAINS"});}for(let u of s)if(dt.has(u.op)){if(a.has(u.field))continue;a.add(u.field);let f=o?.field===u.field?de(o.dir):"ASCENDING";d.push({fieldPath:u.field,order:f});}if(o&&!a.has(o.field)&&d.push({fieldPath:o.field,order:de(o.dir)}),d.length===1&&n)return mt(e,t,d[0]);let c=o&&d.some(u=>u.fieldPath===o.field)?de(o.dir):"ASCENDING";return d.push({fieldPath:"__name__",order:c}),ft(e,t,n,d)}function ft(e,t,n,s,o="(default)"){let d=`projects/${e}/databases/${o}/collectionGroups/${t}/indexes/_`,a=[...le(1,d),...Y(2,n?2:1)];for(let f of s)a.push(...ke(3,Ce(f)));let c=o==="(default)"?"-default-":o,u=encodeURIComponent(Ee(a));return `https://console.firebase.google.com/project/${e}/firestore/databases/${c}/indexes?create_composite=${u}`}function yt(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function ue(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function pe(e,t){return e<<3|t}function le(e,t){let n=Array.from(new TextEncoder().encode(t));return [pe(e,2),...ue(n.length),...n]}function Y(e,t){return [pe(e,0),...ue(t)]}function ke(e,t){return [pe(e,2),...ue(t.length),...t]}function Ce(e){let t=[...le(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...Y(3,1)):t.push(...Y(2,e.order==="DESCENDING"?2:1)),t}function Ee(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 mt(e,t,n,s="(default)"){let o=`projects/${e}/databases/${s}/collectionGroups/${t}/fields/${n.fieldPath}`,d=[...le(1,o),...Y(2,2),...ke(3,Ce(n))],a=s==="(default)"?"-default-":s,c=encodeURIComponent(Ee(d));return `https://console.firebase.google.com/project/${e}/firestore/databases/${a}/indexes/automatic?create_exemption=${c}`}function ht(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 gt(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function Ie(e,t){let n=e??{},s=gt(e),o;if(s&&(o=n.message?yt(n.message):void 0,!o)){let d=ht(t.ref);if(d){let a=pt(t.path);o=lt(d,a,t.isGroup,t.filters,t.sort);}}return {type:s?"index":"error",message:s?"This query requires a composite index that does not exist yet.":n.message??"Query failed",indexUrl:o}}function he(e,t,n=200){let s=Oe(t);return e.json(s,n)}function Z(e,t,n,s=200){return he(e,{success:true,data:t,meta:n},s)}function b(e,t,n=400){return he(e,{success:false,error:t},n)}function fe(e,t,n,s,o){let d=Ie(t,n),a=d.type==="index",c=a?424:500,f={success:false,error:a?d.message:o&&t instanceof Error?t.message:s};return a&&(f.errorType="index",d.indexUrl&&(f.indexUrl=d.indexUrl)),he(e,f,c)}var ye="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Pe(){let e="";for(;e.length<20;){let t=randomBytes(20);for(let n=0;n<t.length&&e.length<20;n++){let s=t[n];s>=ye.length*4||(e+=ye.charAt(s%ye.length));}}return e}function K(e){let t=e._def??e.def;if(!t)return e;let n=t.typeName??t.type;if(n==="ZodDate"||n==="date")return z.preprocess(s=>Te(s)??s,e);if(n==="ZodObject"||n==="object"){let s=e.shape,o={};for(let[d,a]of Object.entries(s))o[d]=K(a);return z.object(o)}if(n==="ZodArray"||n==="array"){let s=t.element??t.type;if(s)return z.array(K(s))}if(n==="ZodOptional"||n==="optional"){let s=t.innerType;if(s)return K(s).optional()}if(n==="ZodNullable"||n==="nullable"){let s=t.innerType;if(s)return K(s).nullable()}if(n==="ZodDefault"||n==="default"){let s=t.innerType,o=t.defaultValue;if(s){let d=K(s);return typeof o=="function"?d.default(o()):d.default(o)}}return e}function bt(e,t,n=[]){let s=e.shape,o={},d=t&&t.length>0?t:Object.keys(s);for(let a of d){if(n.includes(a))continue;let c=a.split(".")[0];c&&s[c]&&(o[c]=s[c]);}return z.object(o)}function me(e){let t=e;for(;t;){let n=t._zod?.def??t._def;if(!n)break;if(n.innerType)t=n.innerType;else if(n.schema)t=n.schema;else if(n.type==="optional"||n.type==="nullable"||n.type==="default"||n.type==="catch"||n.type==="effects")t=n.innerType??n.schema;else break}return t}function St(e,t){let n=t.split("."),s=me(e);for(let o=0;o<n.length;o++){let d=n[o];if(!d)continue;let a=s?.shape;if(!a||!a[d])return;let c=a[d];if(o===n.length-1)return c;s=me(c);}return s}function qe(e){let t=me(e),n=t?._zod?.def??t?._def,s=n?.typeName??n?.type;if(s==="ZodObject"||s==="object"){let o=t.shape,d={};for(let[a,c]of Object.entries(o))d[a]=qe(c);return z.object(d).partial()}return e}function ee(e,t,n,s=false,o=[]){if(typeof t!="object"||t===null||Array.isArray(t))return {success:false,error:"Data payload must be an object"};try{let d=t,a={},c={};for(let[u,f]of Object.entries(d))if(u.includes(".")){let R=u.split(".")[0];if(o.includes(u)||o.includes(R))continue;if(n&&n.length>0&&!n.includes(u)&&!n.includes(R))return {success:!1,error:`Field '${u}' is not allowed for this operation`};let S=St(e,u);if(!S)return {success:!1,error:`Field '${u}' does not exist in schema`};let $=(ce()==="normalize"?K(S):S).parse(f);a[u]=$;}else c[u]=f;if(Object.keys(c).length>0||Object.keys(a).length===0){let u=bt(e,n,o),f=s?qe(u):u,S=(ce()==="normalize"?K(f):f).parse(c);Object.assign(a,S);}return {success:!0,data:a}}catch(d){return d instanceof z.ZodError?{success:false,error:`Validation failed: ${d.issues.map(c=>`${c.path.join(".")}: ${c.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}function te(e,t,n){let s=e?.shape?.[t];if(!s||typeof s.safeParse!="function")return {success:true,data:n};let o=s.safeParse(n);if(o.success)return {success:true,data:o.data};if(Array.isArray(n)){let a=[];for(let c of n){let u=s.safeParse(c);if(u.success)a.push(u.data);else return {success:false,error:u.error.issues.map(R=>R.message).join(", ")}}return {success:true,data:a}}return {success:false,error:o.error.issues.map(a=>a.message).join(", ")}}function xt(e,t){let n=[],s=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[d,a]of Object.entries(e)){if(a===void 0||["cursor","limit","pageSize","orderBy","orderDir","select"].includes(d))continue;let c=Array.isArray(a)?a[0]:a;if(c===void 0||c==="")continue;let u=d.match(/^(\w+)__(\w+)$/),f,R="==";if(u&&u[1]&&u[2]){f=u[1];let P=u[2];if(o[P])R=o[P];else continue}else if(!u)f=d;else continue;if(s&&!s.has(f))continue;let S=c;R==="in"||R==="not-in"||R==="array-contains-any"?S=c.split(",").map(P=>je(P.trim())):S=je(c),n.push({field:f,op:R,value:S});}return n}function je(e){if(e==="true")return true;if(e==="false")return false;if(e==="null"||e==="__null__")return null;let t=Number(e);return !isNaN(t)&&e!==""?t:e}function ne(e){return e?{docId:e.id,docPath:e.ref?.path??void 0}:null}async function De(e,t){if(!t)return;let n;if(typeof t=="string")try{n=JSON.parse(t);}catch{n=t.includes("/")?{docPath:t}:{docId:t};}else typeof t=="object"&&(n=t);if(!n)return;let s=typeof n.docPath=="string"?n.docPath:void 0,o=typeof n.docId=="string"?n.docId:void 0;try{let d=e.repo.ref,a=d?.firestore;if(s&&a&&typeof a.doc=="function"){let c=await a.doc(s).get();if(c.exists)return c}if(o&&o.includes("/")&&a&&typeof a.doc=="function"){let c=await a.doc(o).get();if(c.exists)return c}if(o&&typeof d.doc=="function"){let c=await d.doc(o).get();if(c.exists)return c}return}catch{return}}function $e(e,t,n){async function s(p,r,m,i){if(!r.rules)return true;let y=r.rules?.[m];if(!y)return b(p,`Operation "${m}" is not allowed for this repository`,403),false;try{return await y(i)?!0:b(p,"Forbidden",403)}catch(h){let g=n&&h instanceof Error?h.message:"Forbidden";return b(p,g,403)}}async function o(p,r,m,i){if(!p.rules)return i;let y=p.rules?.filter;if(!y)return i;let h=[];for(let g of i)try{await y({user:r,doc:g,params:m})&&h.push(g);}catch{}return h}function d(p){return p.get("user")??p.get("docsUser")??null}function a(p,r){if(!p){let m=r.req.path.split("/");for(let i of m)if(e[i]){p=i;break}}return !p||!e[p]?null:e[p]??null}function c(p,r){if(!r)return;let m=p[r];if(typeof m!="string"||!m)return;let i=m.split("/").filter(Boolean),y=[];for(let h=1;h<i.length;h+=2)y.push(i[h]);return y.length>0?y:void 0}async function u(p,r){let m=`by${p.documentKey.charAt(0).toUpperCase()}${p.documentKey.slice(1)}`,i=p.repo.get[m];if(typeof i=="function")try{let h=await i(r);if(h)return h}catch{}return (await p.repo.query.by({where:[[p.documentKey,"==",r]],limit:1}))[0]??null}async function f(p){let r=p.c,m=r.req.param(),i=a(m.repoName,r);if(!i)return b(r,"Repository not found",404);let y=d(r);if(!await s(r,i,"list",{user:y,query:r.req.query(),params:m}))return;let h=[],g;try{let l=r.req.query(),w=Math.min(Number(l.pageSize)||i.pageSize,100),x=l.cursor,C=l.direction?.toLowerCase()==="prev"?"prev":"next",A=l.orderBy,O=l.orderDir?.toLowerCase()==="desc"?"desc":"asc",H=l.select,U=H?H.split(",").map(F=>F.trim()):void 0,E=l.withTotal,T=E==="true"||E==="1"||E===!0,k;i.allowedIncludes&&l.includes&&(k=(typeof l.includes=="string"?l.includes.split(",").map(L=>L.trim()):Array.isArray(l.includes)?l.includes:[]).filter(L=>typeof L=="string"&&i.allowedIncludes.includes(L)),k?.length===0&&(k=void 0));let D=xt(l,i.filterableFields);h=D.map(F=>({field:F.field,op:F.op,value:String(F.value??"")})),A&&(g={field:A,dir:O});let z={pageSize:w,direction:C,...T?{withTotal:!0}:{}};if(x)try{let F=typeof x=="string"?JSON.parse(x):x;z.cursor=await De(i,F);}catch{}if(A){if(i.orderableFields&&!i.orderableFields.includes(A))return b(r,`Field not orderable: ${A}`,400);z.orderBy=[{field:A,direction:O}];}if(D.length>0){z.where=[];for(let F of D){let L=te(i.schema,F.field,F.value);if(!L.success)return b(r,`Invalid filter value for '${F.field}': ${L.error}`,400);z.where.push([F.field,F.op,L.data]);}}U&&(z.select=U),k&&(z.include=k);let N=await i.repo.query.paginate(z),Ye={items:await o(i,d(r),m,N.data),hasNextPage:N.hasNextPage,hasPrevPage:N.hasPrevPage,nextCursor:ne(N.nextCursor),prevCursor:ne(N.prevCursor),...N.totalCount!==void 0?{totalCount:N.totalCount,totalCountIsExact:N.totalCountIsExact}:{}};return Z(r,Ye,{pageSize:w,hasMore:N.hasNextPage,...N.totalCount!==void 0?{totalCount:N.totalCount,totalCountIsExact:N.totalCountIsExact}:{}})}catch(l){fe(r,l,{ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:h,sort:g},"Failed to fetch documents",n);}}async function R(p){let r=p.c,m=r.req.param(),i=a(m.repoName,r);if(!i)return b(r,"Repository not found",404);let y=d(r);if(!await s(r,i,"list",{user:y,query:p.input||{},params:m}))return;let h=[],g;try{let l=p.input||{},w=Math.min(l.pageSize||i.pageSize,100),x=l.direction==="prev"?"prev":"next";l.where&&(h=l.where.map(E=>({field:String(E[0]),op:E[1],value:String(E[2]??"")}))),l.orderBy&&l.orderBy[0]&&(g={field:l.orderBy[0].field,dir:l.orderBy[0].direction==="desc"?"desc":"asc"});let C=l.withTotal===!0||String(l.withTotal)==="true",A={pageSize:w,direction:x,...C?{withTotal:!0}:{}};if(l.cursor)try{let E=typeof l.cursor=="string"?JSON.parse(l.cursor):l.cursor;A.cursor=await De(i,E);}catch{}if(i.allowedIncludes&&l.includes&&l.includes.length>0){let E=l.includes.filter(T=>typeof T=="string"?i.allowedIncludes.includes(T):typeof T=="object"&&T!==null&&"relation"in T&&typeof T.relation=="string"?i.allowedIncludes.includes(T.relation):!1);E.length>0&&(A.include=E);}if(l.where&&l.where.length>0){if(i.filterableFields){let T=new Set(i.filterableFields),k=l.where.filter(D=>!T.has(D[0]));if(k.length>0){b(r,`Fields not filterable: ${k.map(D=>D[0]).join(", ")}`,400);return}}let E=[];for(let T of l.where){let k=te(i.schema,T[0],T[2]);if(!k.success){b(r,`Invalid filter value for '${T[0]}': ${k.error}`,400);return}E.push([T[0],T[1],k.data]);}A.where=E;}if(l.orWhere&&l.orWhere.length>0){if(i.filterableFields){let T=new Set(i.filterableFields),k=l.orWhere.filter(D=>!T.has(D[0]));if(k.length>0){b(r,`Fields not filterable: ${k.map(D=>D[0]).join(", ")}`,400);return}}let E=[];for(let T of l.orWhere){let k=te(i.schema,T[0],T[2]);if(!k.success){b(r,`Invalid filter value for '${T[0]}': ${k.error}`,400);return}E.push([T[0],T[1],k.data]);}A.orWhere=E;}if(l.orWhereGroups&&l.orWhereGroups.length>0){if(i.filterableFields){let T=new Set(i.filterableFields);for(let k of l.orWhereGroups){let D=k.filter(z=>!T.has(z[0]));if(D.length>0){b(r,`Fields not filterable: ${D.map(z=>z[0]).join(", ")}`,400);return}}}let E=[];for(let T of l.orWhereGroups){let k=[];for(let D of T){let z=te(i.schema,D[0],D[2]);if(!z.success){b(r,`Invalid filter value for '${D[0]}': ${z.error}`,400);return}k.push([D[0],D[1],z.data]);}E.push(k);}A.orWhereGroups=E;}if(l.orderBy&&l.orderBy.length>0){if(i.orderableFields){let E=new Set(i.orderableFields),T=l.orderBy.filter(k=>!E.has(k.field));if(T.length>0){b(r,`Fields not orderable: ${T.map(k=>k.field).join(", ")}`,400);return}}A.orderBy=l.orderBy;}l.select&&l.select.length>0&&(A.select=l.select);let O=await i.repo.query.paginate(A),U={items:await o(i,d(r),m,O.data),hasNextPage:O.hasNextPage,hasPrevPage:O.hasPrevPage,nextCursor:ne(O.nextCursor),prevCursor:ne(O.prevCursor),...O.totalCount!==void 0?{totalCount:O.totalCount,totalCountIsExact:O.totalCountIsExact}:{}};return Z(r,U,{pageSize:w,hasMore:O.hasNextPage,...O.totalCount!==void 0?{totalCount:O.totalCount,totalCountIsExact:O.totalCountIsExact}:{}})}catch(l){fe(r,l,{ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:h,sort:g},"Failed to query documents",n);}}async function S(p){let r=p.c,m=r.req.param(),i=a(m.repoName,r);if(!i)return b(r,"Repository not found",404);let y=m.id;if(!y)return b(r,"Document ID required",400);try{let h=await u(i,y);if(!h)return b(r,"Document not found",404);let g=d(r);if(!await s(r,i,"get",{user:g,doc:h,params:m}))return;if(i.rules?.filter)try{if(!await i.rules.filter({user:g,doc:h,params:m}))return b(r,"Document not found",404)}catch{return b(r,"Document not found",404)}return Z(r,h)}catch(h){fe(r,h,{ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:[{field:i.documentKey,op:"==",value:y}]},"Failed to fetch document",n);}}async function P(p){let r=p.c,m=r.req.param(),i=a(m.repoName,r);if(!i)return b(r,"Repository not found",404);try{let y=p.input||{},h=d(r);if(!await s(r,i,"create",{user:h,body:y,params:m}))return;let g=ee(i.schema,y,i.createFields,!1,i.systemKeys);if(!g.success)return b(r,g.error,400);if(i.validate){let w=await i.validate(g.data,"create");if(w)return b(r,w,400)}let l;if(i.isGroup&&i.parentKeys&&i.parentKeys.length>0){let w={...g.data};i.createdKey&&(w[i.createdKey]=new Date);let x=i.parentKeys.filter(O=>!w[O]);if(x.length>0){b(r,`Missing parent key(s) for subcollection create: ${x.join(", ")}`,400);return}let C=i.parentKeys.map(O=>w[O]),A=w[i.documentKey]||Pe();l=await i.repo.set(...C,A,w);}else l=await i.repo.create(g.data);return Z(r,l,void 0,201)}catch(y){let h=n&&y instanceof Error?y.message:"Failed to create document";return b(r,h,500)}}async function $(p,r){let m=p.c,i=m.req.param(),y=a(i.repoName,m);if(!y)return b(m,"Repository not found",404);let h=i.id;if(!h)return b(m,"Document ID required",400);try{let g=p.input||{},l=await u(y,h);if(!l)return b(m,"Document not found",404);let w=d(m);if(!await s(m,y,"update",{user:w,doc:l,body:g,params:i}))return;let x=ee(y.schema,g,y.mutableFields,r,y.systemKeys);if(!x.success)return b(m,x.error,400);if(y.validate){let O=await y.validate(x.data,"update");if(O)return b(m,O,400)}let C=c(l,y.pathKey)??[h],A=await y.repo.update(...C,x.data);return Z(m,A)}catch(g){let l=n&&g instanceof Error?g.message:"Failed to update document";return b(m,l,500)}}async function j(p){let r=p.c,m=r.req.param(),i=a(m.repoName,r);if(!i)return b(r,"Repository not found",404);if(!i.allowDelete)return b(r,"Delete not allowed for this repository",403);let y=m.id;if(!y)return b(r,"Document ID required",400);try{let h=await u(i,y);if(!h)return b(r,"Document not found",404);let g=d(r);if(!await s(r,i,"delete",{user:g,doc:h,params:m}))return;let l=c(h,i.pathKey)??[y];return await i.repo.delete(...l),Z(r,{deleted:!0})}catch(h){let g=n&&h instanceof Error?h.message:"Failed to delete document";return b(r,g,500)}}function I(p){return p.c.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization","Access-Control-Max-Age":"86400"})}async function v(p){let r=p.c,m=r.req.param(),i=a(m.repoName,r);if(!i)return b(r,"Repository not found",404);try{let y=p.input||{};if(!Array.isArray(y.operations))return b(r,"operations array is required",400);let h=d(r),g=i.repo.batch.create(),l=[];for(let w of y.operations){if(!w.type||!["create","update","delete"].includes(w.type))return b(r,"Invalid operation type",400);if(w.type==="create"){if(!await s(r,i,"create",{user:h,body:w.data,params:m}))return;let x=ee(i.schema,w.data,i.createFields,!1,i.systemKeys);if(!x.success)return b(r,x.error,400);let C=w.data[i.documentKey]||Pe(),A={...x.data};if(i.createdKey&&(A[i.createdKey]=new Date),i.isGroup&&i.parentKeys){let O=i.parentKeys.map(H=>A[H]);g.set(...O,C,A);}else g.set(C,A);l.push({op:"create",id:C});}else if(w.type==="update"){if(!w.id)return b(r,"id required for update",400);let x=await u(i,w.id);if(!x)return b(r,`Document ${w.id} not found`,404);if(!await s(r,i,"update",{user:h,doc:x,body:w.data,params:m}))return;let C=ee(i.schema,w.data,i.mutableFields,!0,i.systemKeys);if(!C.success)return b(r,C.error,400);let A=c(x,i.pathKey)??[w.id];g.update(...A,C.data),l.push({op:"update",id:w.id});}else if(w.type==="delete"){if(!i.allowDelete)return b(r,"Delete not allowed",403);if(!w.id)return b(r,"id required for delete",400);let x=await u(i,w.id);if(!x)return b(r,`Document ${w.id} not found`,404);if(!await s(r,i,"delete",{user:h,doc:x,params:m}))return;let C=c(x,i.pathKey)??[w.id];g.delete(...C),l.push({op:"delete",id:w.id});}}return await g.commit(),Z(r,{results:l})}catch(y){let h=n&&y instanceof Error?y.message:"Batch operation failed";return b(r,h,500)}}return {handleList:f,handleQuery:R,handleGet:S,handleCreate:P,handleUpdate:$,handleDelete:j,handleBatch:v,handleOptions:I}}function re(e){try{return z.toJSONSchema(e,{target:"openapi-3.1",unrepresentable:"any",override:t=>{let n=getOpenApiMetadata(t.zodSchema);n&&(Object.assign(t.jsonSchema,n),(t.jsonSchema.anyOf||t.jsonSchema.oneOf)&&delete t.jsonSchema.type);let s=t.zodSchema?._zod?.def;s&&(s.type==="date"&&!t.jsonSchema.type&&!t.jsonSchema.anyOf?(t.jsonSchema.type="string",t.jsonSchema.format="date-time"):s.type==="bigint"&&!t.jsonSchema.type&&!t.jsonSchema.anyOf&&(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 _(e){return {$ref:`#/components/schemas/${e}`}}function q(e){return {description:e,content:{"application/json":{schema:_("ErrorResponse")}}}}function W(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function ze(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"},totalCount:{type:"integer",description:"Total count of matching documents (when requested with withTotal=true)"},totalCountIsExact:{type:"boolean",description:"Whether totalCount is exact (true) or estimated due to OR conditions (false)"}},required:["items","hasNextPage","hasPrevPage"]},meta:{type:"object",properties:{pageSize:{type:"integer"},hasMore:{type:"boolean"},totalCount:{type:"integer"},totalCountIsExact:{type:"boolean"},cursor:{oneOf:[{type:"string"},{type:"null"}]}}}},required:["success","data"]}}}}}function Q(e){let t=e;for(;t;){let n=t._zod?.def??t._def;if(!n)break;if(n.innerType)t=n.innerType;else if(n.schema)t=n.schema;else if(n.type==="optional"||n.type==="nullable"||n.type==="default"||n.type==="catch"||n.type==="effects")t=n.innerType??n.schema;else break}return t}function vt(e,t){let n=t.split("."),s=Q(e);for(let o=0;o<n.length;o++){let d=n[o];if(!d)continue;let a=s?.shape;if(!a||!a[d])return;let c=a[d];if(o===n.length-1)return c;s=Q(c);}return s}function be(e,t="",n=0){if(n>5)return [];let o=Q(e)?.shape;if(!o)return [];let d=[];for(let[a,c]of Object.entries(o)){let u=t?`${t}.${a}`:a,f=Q(c);f?.shape&&typeof f.shape=="object"?(d.push({path:u,zodSchema:c}),d.push(...be(f,u,n+1))):d.push({path:u,zodSchema:c});}return d}function Se(e){return e.filterableFields&&e.filterableFields.length>0?e.filterableFields.map(t=>({path:t,zodSchema:vt(e.schema,t)})):be(e.schema)}function we(e){if(!e)return {type:"string"};let t=re(e);return delete t.$schema,delete t.title,t}function At(e){let t=Se(e),n=e.orderableFields??t.map(s=>s.path);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",...n.length>0?{enum:n}:{}},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${t.length>0?` (${t.map(s=>s.path).join(", ")})`:""}`},{name:"withTotal",in:"query",schema:{type:"boolean"},description:"Include total document count (totalCount and totalCountIsExact) in response"}]}function Tt(e){let t=Se(e),n=["eq","ne","lt","lte","gt","gte","in","nin","contains","containsAny"],s={eq:"equals. Use 'null' or '__null__' to match null values",ne:"not equals. Use 'null' or '__null__' to match non-null values",lt:"less than",lte:"less than or equal",gt:"greater than",gte:"greater than or equal",in:"in list (comma-separated values). Supports 'null' and '__null__' (e.g. val1,val2,__null__)",nin:"not in list (comma-separated values). Supports 'null' and '__null__'",contains:"array-contains",containsAny:"array-contains-any (comma-separated values). Supports 'null' and '__null__'"},o=[];for(let{path:d,zodSchema:a}of t){let c=we(a);o.push({name:d,in:"query",schema:c,description:`Filter by ${d} (equality). Use 'null' or '__null__' for null values`});for(let u of n){let f=s[u]?` (${s[u]})`:"",R=u==="in"||u==="nin"||u==="containsAny";o.push({name:`${d}__${u}`,in:"query",schema:R?{type:"string",description:"Comma-separated list of values"}:c,description:`Filter ${d} with operator ${u}${f}`});}}return o}function Fe(){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)"},withTotal:{type:"boolean",description:"Include total document count (totalCount and totalCountIsExact) in response"}}}}function Ot(e){let t=Se(e),n=e.orderableFields??t.map(a=>a.path),s=t.map(a=>a.path);if(t.length===0)return Fe();let o=[];for(let{path:a,zodSchema:c}of t){let u=we(c),f=Q(c),S=f?._zod?.def?.type==="array"||f?._def?.typeName==="ZodArray"||f?._def?.type==="array"?we(f?._zod?.def?.element??f?._def?.type??f?._def?.element):u;o.push({type:"array",description:`Condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["==","!=","<","<=",">",">=","eq","ne","lt","lte","gt","gte"]},u],minItems:3,maxItems:3}),o.push({type:"array",description:`List condition on '${a}' (in, not-in)`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["in","not-in","nin"]},{type:"array",items:u}],minItems:3,maxItems:3}),o.push({type:"array",description:`Array contains condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["array-contains","contains"]},S],minItems:3,maxItems:3}),o.push({type:"array",description:`Array contains-any condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["array-contains-any","containsAny"]},{type:"array",items:S}],minItems:3,maxItems:3});}let d={oneOf:o};return {type:"object",properties:{where:{type:"array",items:d,description:"AND conditions: [field, operator, value][]"},orWhere:{type:"array",items:d,description:"Simple OR conditions (each independently OR'd)"},orWhereGroups:{type:"array",items:{type:"array",items:d},description:"Advanced OR groups (AND within, OR across groups)"},orderBy:{type:"array",items:{type:"object",properties:{field:{type:"string",enum:n},direction:{type:"string",enum:["asc","desc"]}},required:["field"]}},select:{type:"array",items:{type:"string",enum:s},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:e.allowedIncludes&&e.allowedIncludes.length>0?{oneOf:[{type:"string",enum:e.allowedIncludes},{type:"object",properties:{relation:{type:"string",enum:e.allowedIncludes},select:{type:"array",items:{type:"string"}}},required:["relation"]}]}:{oneOf:[{type:"string"},{type:"object",properties:{relation:{type:"string"},select:{type:"array",items:{type:"string"}}},required:["relation"]}]},description:"Relations to include (populate)"},withTotal:{type:"boolean",description:"Include total document count (totalCount and totalCountIsExact) in response"}}}}function kt(e,t,n,s,o,d="QueryRequestBody"){let a={},c=e.name,u=`${t}/${e.name}`,f=`${u}/{${e.documentKey}}`,R={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};a[u]={get:{operationId:`list${M(e.name)}`,summary:`List ${e.name} (paginated)`,tags:[c],parameters:[...At(e),...Tt(e)],responses:{200:ze(_(n)),500:q("Internal server error")}},post:{operationId:`create${M(e.name)}`,summary:`Create a ${B(e.name)}`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:_(s??n)}}},responses:{201:W("Document created",_(n)),400:q("Validation error"),500:q("Internal server error")}}},a[`${u}/query`]={post:{operationId:`query${M(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:_(d)}}},responses:{200:ze(_(n)),400:q("Invalid query"),500:q("Internal server error")}}},a[`${u}/batch`]={post:{operationId:`batch${M(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:_(`${n}BatchRequest`)}}},responses:{200:W("Batch operations completed",{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{op:{type:"string"},id:{type:"string"}}}}}}),400:q("Validation error"),403:q("Forbidden"),404:q("Document not found"),500:q("Internal server error")}}};let S={};return S.get={operationId:`get${M(B(e.name))}`,summary:`Get a single ${B(e.name)}`,tags:[c],parameters:[R],responses:{200:W("Document found",_(n)),404:q("Document not found"),500:q("Internal server error")}},S.put={operationId:`update${M(B(e.name))}`,summary:`Update a ${B(e.name)} (full replace)`,tags:[c],parameters:[R],requestBody:{required:true,content:{"application/json":{schema:_(o??n)}}},responses:{200:W("Document updated",_(n)),400:q("Validation error"),404:q("Document not found"),500:q("Internal server error")}},S.patch={operationId:`patch${M(B(e.name))}`,summary:`Partially update a ${B(e.name)}`,tags:[c],parameters:[R],requestBody:{required:true,content:{"application/json":{schema:{allOf:[_(o??n)],description:"All fields are optional for partial updates"}}}},responses:{200:W("Document patched",_(n)),400:q("Validation error"),404:q("Document not found"),500:q("Internal server error")}},e.allowDelete&&(S.delete={operationId:`delete${M(B(e.name))}`,summary:`Delete a ${B(e.name)}`,tags:[c],parameters:[R],responses:{200:W("Document deleted",{type:"object",properties:{id:{type:"string"}}}),404:q("Document not found"),500:q("Internal server error")}}),a[f]=S,a}function xe(e,t,n={}){let{title:s="CRUD API",version:o="1.0.0",description:d,servers:a,auth:c=false}=n,u=t==="/"?"":t.replace(/\/$/,""),f={},R={},S=[];f.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string"}},required:["success","error"]},f.QueryRequestBody=Fe();for(let[I,v]of Object.entries(e)){let p=M(B(I)),r=`${p}Create`,m=`${p}Update`,i=`${p}QueryRequestBody`;f[p]=re(v.schema),f[i]=Ot(v);let y=C=>{let A={},O=be(v.schema);for(let{path:H,zodSchema:U}of O){let E=H.split(".")[0];v.systemKeys.includes(E)||v.systemKeys.includes(H)||C&&C.length>0&&!C.includes(H)&&!C.includes(E)||(H.includes(".")?A[H]=U.optional():A[H]=U);}return A},h=null,g=y(v.createFields);Object.keys(g).length>0&&(f[r]=re(z.object(g)),h=r);let l=null,w=y(v.mutableFields);Object.keys(w).length>0&&(f[m]=re(z.object(w)),l=m),f[`${p}BatchRequest`]={type:"object",properties:{operations:{type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",enum:["create"]},data:_(h??p)},required:["type","data"]},{type:"object",properties:{type:{type:"string",enum:["update"]},id:{type:"string"},data:{allOf:[_(l??p)],description:"Partial updates allowed"}},required:["type","id","data"]},...v.allowDelete?[{type:"object",properties:{type:{type:"string",enum:["delete"]},id:{type:"string"}},required:["type","id"]}]:[]]}}},required:["operations"]};let x=kt(v,u,p,h,l,i);Object.assign(R,x),S.push({name:I,description:`Operations on ${I} (collection: ${v.path})`});}let P={},$;return c==="basic"?(P.basicAuth={type:"http",scheme:"basic"},$=[{basicAuth:[]}]):c==="bearer"&&(P.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},$=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:s,version:o,...d?{description:d}:{}},...a&&a.length>0?{servers:a}:{},paths:R,components:{schemas:f,...Object.keys(P).length>0?{securitySchemes:P}:{}},...$?{security:$}:{},tags:S}}function M(e){return e.charAt(0).toUpperCase()+e.slice(1)}function B(e){return e.endsWith("ies")?e.slice(0,-3)+"y":e.endsWith("ses")||e.endsWith("xes")||e.endsWith("zes")?e.slice(0,-2):e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e}var J=class extends Error{constructor(n,s){super("Request validation failed");this.zodError=n;this.source=s;this.statusCode=400;this.name="ValidationError";}};var V=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},X=class extends Error{constructor(n){super("Output validation failed");this.zodError=n;this.statusCode=500;this.name="OutputValidationError";}};function _e(e){return e.issues.map(t=>({path:t.path.join("."),code:t.code,message:t.message}))}function He(e,t){return t instanceof J?e.json({success:false,error:"Validation failed",issues:_e(t.zodError)},400):t instanceof V?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof X?e.json({success:false,error:"Output validation failed",issues:_e(t.zodError)},500):null}extendZodWithOpenApi(z);var Ne="Successful response",Be="Error response";function jt(e){return e==="get"?"query":"json"}function Dt(e,t){let n=t?.output;return n?typeof n=="function"?n(e):n:e}function qt(e){if(typeof e.safeParse=="function")return {description:Be,schema:e};let t=e;return {description:t.description??Be,schema:t.schema}}function Le(e,t,n,s){let o=new OpenAPIRegistry;if(n.securitySchemes)for(let[c,u]of Object.entries(n.securitySchemes))o.registerComponent("securitySchemes",c,u);for(let c of e){let u=c.method,f=c.source??jt(u),R=Ft(t,c.path??"/"),S=c.status??200,P=$t(u,f,c.input),$=Me(f,c.input,"query"),j=Me(f,c.input,"param"),I=_t(u,R),v=Dt(c.output,s),p={[S]:v?{description:Ne,content:{"application/json":{schema:v}}}:{description:Ne}};if(s?.errors)for(let[r,m]of Object.entries(s.errors)){let{description:i,schema:y}=qt(m);p[r]=y?{description:i,content:{"application/json":{schema:y}}}:{description:i};}o.registerPath({method:u,path:zt(R),operationId:I,summary:c.summary,description:c.description,tags:c.tags,deprecated:c.deprecated,security:c.security,request:{...$?{query:$}:{},...j?{params:j}:{},...P?{body:P}:{}},responses:p});}return new OpenApiGeneratorV31(o.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security})}function $t(e,t,n){return !n||e==="get"?null:t==="json"?{content:{"application/json":{schema:n}}}:t==="form"?{content:{"application/x-www-form-urlencoded":{schema:n}}}:null}function Me(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function zt(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function Ft(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,s=t.startsWith("/")?t:`/${t}`,o=`${n}${s}`;return o===""?"/":o}function _t(e,t){let n=t.replace(/[{}]/g,"").replace(/\/+/g,"_").replace(/[^A-Za-z0-9_]/g,"").replace(/^_+|_+$/g,"");return `${e}_${n||"root"}`}function Ue(e,t){let n=e.replace(/"/g,""");return `<!doctype html>
|
|
1
|
+
import {randomBytes}from'crypto';import {z}from'zod';import {Timestamp}from'firebase-admin/firestore';import {extendZodWithOpenApi,getOpenApiMetadata,OpenAPIRegistry,OpenApiGeneratorV31}from'@asteasolutions/zod-to-openapi';import {Hono}from'hono';import {getRequestListener}from'@hono/node-server';import {AsyncLocalStorage}from'async_hooks';var ie=Object.defineProperty;var et=Object.getOwnPropertyDescriptor;var tt=Object.getOwnPropertyNames;var nt=Object.prototype.hasOwnProperty;var rt=(e,t)=>()=>(e&&(t=e(e=0)),t);var ot=(e,t)=>{for(var n in t)ie(e,n,{get:t[n],enumerable:true});},st=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of tt(t))!nt.call(e,o)&&o!==n&&ie(e,o,{get:()=>t[o],enumerable:!(s=et(t,o))||s.enumerable});return e};var it=e=>st(ie({},"__esModule",{value:true}),e);var Ve={};ot(Ve,{DEFAULT_HTML_CSP:()=>Qe,securityHeaders:()=>Qt});function Qt(e={}){let t=e.csp===void 0?Qe:e.csp,n=e.frameOptions===void 0?"DENY":e.frameOptions,s=e.referrerPolicy===void 0?"no-referrer":e.referrerPolicy,o=e.cacheControl===void 0?"private, no-store":e.cacheControl;return async(d,a,c)=>{typeof a?.setHeader=="function"&&(a.setHeader("X-Content-Type-Options","nosniff"),n&&a.setHeader("X-Frame-Options",n),s&&a.setHeader("Referrer-Policy",s),o&&a.setHeader("Cache-Control",o),t&&a.setHeader("Content-Security-Policy",t)),await c();}}var We,Je,Qe,Xe=rt(()=>{We="https://cdn.jsdelivr.net",Je="https://www.gstatic.com",Qe=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${We} ${Je}`,`style-src 'self' 'unsafe-inline' ${We}`,`connect-src 'self' ${Je} https://*.googleapis.com https://*.firebaseio.com https://identitytoolkit.googleapis.com`,"img-src 'self' data:","font-src 'self' data:","frame-ancestors 'none'","base-uri 'self'","form-action 'self'"].join("; ");});var Ae="preserve";function ce(){return Ae}function at(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function Te(e){if(e==null)return null;if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(e instanceof Timestamp)return e.toDate();if(at(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 Oe(e){return e}var dt=new Set(["<","<=",">",">=","!="]),ut=new Set(["array-contains","array-contains-any"]);function de(e){return e==="desc"?"DESCENDING":"ASCENDING"}function pt(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function lt(e,t,n,s,o){let d=[],a=new Set;for(let u of s)if(u.op==="=="||u.op==="in"||u.op==="not-in"){if(a.has(u.field))continue;a.add(u.field),d.push({fieldPath:u.field,order:"ASCENDING"});}for(let u of s)if(ut.has(u.op)){if(a.has(u.field))continue;a.add(u.field),d.push({fieldPath:u.field,arrayConfig:"CONTAINS"});}for(let u of s)if(dt.has(u.op)){if(a.has(u.field))continue;a.add(u.field);let f=o?.field===u.field?de(o.dir):"ASCENDING";d.push({fieldPath:u.field,order:f});}if(o&&!a.has(o.field)&&d.push({fieldPath:o.field,order:de(o.dir)}),d.length===1&&n)return mt(e,t,d[0]);let c=o&&d.some(u=>u.fieldPath===o.field)?de(o.dir):"ASCENDING";return d.push({fieldPath:"__name__",order:c}),ft(e,t,n,d)}function ft(e,t,n,s,o="(default)"){let d=`projects/${e}/databases/${o}/collectionGroups/${t}/indexes/_`,a=[...le(1,d),...Y(2,n?2:1)];for(let f of s)a.push(...ke(3,Ce(f)));let c=o==="(default)"?"-default-":o,u=encodeURIComponent(Ee(a));return `https://console.firebase.google.com/project/${e}/firestore/databases/${c}/indexes?create_composite=${u}`}function yt(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function ue(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function pe(e,t){return e<<3|t}function le(e,t){let n=Array.from(new TextEncoder().encode(t));return [pe(e,2),...ue(n.length),...n]}function Y(e,t){return [pe(e,0),...ue(t)]}function ke(e,t){return [pe(e,2),...ue(t.length),...t]}function Ce(e){let t=[...le(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...Y(3,1)):t.push(...Y(2,e.order==="DESCENDING"?2:1)),t}function Ee(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 mt(e,t,n,s="(default)"){let o=`projects/${e}/databases/${s}/collectionGroups/${t}/fields/${n.fieldPath}`,d=[...le(1,o),...Y(2,2),...ke(3,Ce(n))],a=s==="(default)"?"-default-":s,c=encodeURIComponent(Ee(d));return `https://console.firebase.google.com/project/${e}/firestore/databases/${a}/indexes/automatic?create_exemption=${c}`}function ht(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 gt(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function Ie(e,t){let n=e??{},s=gt(e),o;if(s&&(o=n.message?yt(n.message):void 0,!o)){let d=ht(t.ref);if(d){let a=pt(t.path);o=lt(d,a,t.isGroup,t.filters,t.sort);}}return {type:s?"index":"error",message:s?"This query requires a composite index that does not exist yet.":n.message??"Query failed",indexUrl:o}}function he(e,t,n=200){let s=Oe(t);return e.json(s,n)}function Z(e,t,n,s=200){return he(e,{success:true,data:t,meta:n},s)}function b(e,t,n=400){return he(e,{success:false,error:t},n)}function fe(e,t,n,s,o){let d=Ie(t,n),a=d.type==="index",c=a?424:500,f={success:false,error:a?d.message:o&&t instanceof Error?t.message:s};return a&&(f.errorType="index",d.indexUrl&&(f.indexUrl=d.indexUrl)),he(e,f,c)}var ye="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Pe(){let e="";for(;e.length<20;){let t=randomBytes(20);for(let n=0;n<t.length&&e.length<20;n++){let s=t[n];s>=ye.length*4||(e+=ye.charAt(s%ye.length));}}return e}function K(e){let t=e._def??e.def;if(!t)return e;let n=t.typeName??t.type;if(n==="ZodDate"||n==="date")return z.preprocess(s=>Te(s)??s,e);if(n==="ZodObject"||n==="object"){let s=e.shape,o={};for(let[d,a]of Object.entries(s))o[d]=K(a);return z.object(o)}if(n==="ZodArray"||n==="array"){let s=t.element??t.type;if(s)return z.array(K(s))}if(n==="ZodOptional"||n==="optional"){let s=t.innerType;if(s)return K(s).optional()}if(n==="ZodNullable"||n==="nullable"){let s=t.innerType;if(s)return K(s).nullable()}if(n==="ZodDefault"||n==="default"){let s=t.innerType,o=t.defaultValue;if(s){let d=K(s);return typeof o=="function"?d.default(o()):d.default(o)}}return e}function bt(e,t,n=[]){let s=e.shape,o={},d=t&&t.length>0?t:Object.keys(s);for(let a of d){if(n.includes(a))continue;let c=a.split(".")[0];c&&s[c]&&(o[c]=s[c]);}return z.object(o)}function me(e){let t=e;for(;t;){let n=t._zod?.def??t._def;if(!n)break;if(n.innerType)t=n.innerType;else if(n.schema)t=n.schema;else if(n.type==="optional"||n.type==="nullable"||n.type==="default"||n.type==="catch"||n.type==="effects")t=n.innerType??n.schema;else break}return t}function St(e,t){let n=t.split("."),s=me(e);for(let o=0;o<n.length;o++){let d=n[o];if(!d)continue;let a=s?.shape;if(!a||!a[d])return;let c=a[d];if(o===n.length-1)return c;s=me(c);}return s}function qe(e){let t=me(e),n=t?._zod?.def??t?._def,s=n?.typeName??n?.type;if(s==="ZodObject"||s==="object"){let o=t.shape,d={};for(let[a,c]of Object.entries(o))d[a]=qe(c);return z.object(d).partial()}return e}function ee(e,t,n,s=false,o=[]){if(typeof t!="object"||t===null||Array.isArray(t))return {success:false,error:"Data payload must be an object"};try{let d=t,a={},c={};for(let[u,f]of Object.entries(d))if(u.includes(".")){let R=u.split(".")[0];if(o.includes(u)||o.includes(R))continue;if(n&&n.length>0&&!n.includes(u)&&!n.includes(R))return {success:!1,error:`Field '${u}' is not allowed for this operation`};let S=St(e,u);if(!S)return {success:!1,error:`Field '${u}' does not exist in schema`};let $=(ce()==="normalize"?K(S):S).parse(f);a[u]=$;}else c[u]=f;if(Object.keys(c).length>0||Object.keys(a).length===0){let u=bt(e,n,o),f=s?qe(u):u,S=(ce()==="normalize"?K(f):f).parse(c);Object.assign(a,S);}return {success:!0,data:a}}catch(d){return d instanceof z.ZodError?{success:false,error:`Validation failed: ${d.issues.map(c=>`${c.path.join(".")}: ${c.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}function te(e,t,n){let s=e?.shape?.[t];if(!s||typeof s.safeParse!="function")return {success:true,data:n};let o=s.safeParse(n);if(o.success)return {success:true,data:o.data};if(Array.isArray(n)){let a=[];for(let c of n){let u=s.safeParse(c);if(u.success)a.push(u.data);else return {success:false,error:u.error.issues.map(R=>R.message).join(", ")}}return {success:true,data:a}}return {success:false,error:o.error.issues.map(a=>a.message).join(", ")}}function xt(e,t){let n=[],s=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[d,a]of Object.entries(e)){if(a===void 0||["cursor","direction","limit","pageSize","orderBy","orderDir","select","includes","withTotal"].includes(d))continue;let c=Array.isArray(a)?a[0]:a;if(c===void 0||c==="")continue;let u=d.match(/^(\w+)__(\w+)$/),f,R="==";if(u&&u[1]&&u[2]){f=u[1];let P=u[2];if(o[P])R=o[P];else continue}else if(!u)f=d;else continue;if(s&&!s.has(f))continue;let S=c;R==="in"||R==="not-in"||R==="array-contains-any"?S=c.split(",").map(P=>je(P.trim())):S=je(c),n.push({field:f,op:R,value:S});}return n}function je(e){if(e==="true")return true;if(e==="false")return false;if(e==="null"||e==="__null__")return null;let t=Number(e);return !isNaN(t)&&e!==""?t:e}function ne(e){return e?{docId:e.id,docPath:e.ref?.path??void 0}:null}async function De(e,t){if(!t)return;let n;if(typeof t=="string")try{n=JSON.parse(t);}catch{n=t.includes("/")?{docPath:t}:{docId:t};}else typeof t=="object"&&(n=t);if(!n)return;let s=typeof n.docPath=="string"?n.docPath:void 0,o=typeof n.docId=="string"?n.docId:void 0;try{let d=e.repo.ref,a=d?.firestore;if(s&&a&&typeof a.doc=="function"){let c=await a.doc(s).get();if(c.exists)return c}if(o&&o.includes("/")&&a&&typeof a.doc=="function"){let c=await a.doc(o).get();if(c.exists)return c}if(o&&typeof d.doc=="function"){let c=await d.doc(o).get();if(c.exists)return c}return}catch{return}}function $e(e,t,n){async function s(p,r,m,i){if(!r.rules)return true;let y=r.rules?.[m];if(!y)return b(p,`Operation "${m}" is not allowed for this repository`,403),false;try{return await y(i)?!0:b(p,"Forbidden",403)}catch(h){let g=n&&h instanceof Error?h.message:"Forbidden";return b(p,g,403)}}async function o(p,r,m,i){if(!p.rules)return i;let y=p.rules?.filter;if(!y)return i;let h=[];for(let g of i)try{await y({user:r,doc:g,params:m})&&h.push(g);}catch{}return h}function d(p){return p.get("user")??p.get("docsUser")??null}function a(p,r){if(!p){let m=r.req.path.split("/");for(let i of m)if(e[i]){p=i;break}}return !p||!e[p]?null:e[p]??null}function c(p,r){if(!r)return;let m=p[r];if(typeof m!="string"||!m)return;let i=m.split("/").filter(Boolean),y=[];for(let h=1;h<i.length;h+=2)y.push(i[h]);return y.length>0?y:void 0}async function u(p,r){let m=`by${p.documentKey.charAt(0).toUpperCase()}${p.documentKey.slice(1)}`,i=p.repo.get[m];if(typeof i=="function")try{let h=await i(r);if(h)return h}catch{}return (await p.repo.query.by({where:[[p.documentKey,"==",r]],limit:1}))[0]??null}async function f(p){let r=p.c,m=r.req.param(),i=a(m.repoName,r);if(!i)return b(r,"Repository not found",404);let y=d(r);if(!await s(r,i,"list",{user:y,query:r.req.query(),params:m}))return;let h=[],g;try{let l=r.req.query(),w=Math.min(Number(l.pageSize)||i.pageSize,100),x=l.cursor,C=l.direction?.toLowerCase()==="prev"?"prev":"next",A=l.orderBy,O=l.orderDir?.toLowerCase()==="desc"?"desc":"asc",H=l.select,U=H?H.split(",").map(F=>F.trim()):void 0,E=l.withTotal,T=E==="true"||E==="1"||E===!0,k;i.allowedIncludes&&l.includes&&(k=(typeof l.includes=="string"?l.includes.split(",").map(L=>L.trim()):Array.isArray(l.includes)?l.includes:[]).filter(L=>typeof L=="string"&&i.allowedIncludes.includes(L)),k?.length===0&&(k=void 0));let D=xt(l,i.filterableFields);h=D.map(F=>({field:F.field,op:F.op,value:String(F.value??"")})),A&&(g={field:A,dir:O});let z={pageSize:w,direction:C,...T?{withTotal:!0}:{}};if(x)try{let F=typeof x=="string"?JSON.parse(x):x;z.cursor=await De(i,F);}catch{}if(A){if(i.orderableFields&&!i.orderableFields.includes(A))return b(r,`Field not orderable: ${A}`,400);z.orderBy=[{field:A,direction:O}];}if(D.length>0){z.where=[];for(let F of D){let L=te(i.schema,F.field,F.value);if(!L.success)return b(r,`Invalid filter value for '${F.field}': ${L.error}`,400);z.where.push([F.field,F.op,L.data]);}}U&&(z.select=U),k&&(z.include=k);let N=await i.repo.query.paginate(z),Ye={items:await o(i,d(r),m,N.data),hasNextPage:N.hasNextPage,hasPrevPage:N.hasPrevPage,nextCursor:ne(N.nextCursor),prevCursor:ne(N.prevCursor),...N.totalCount!==void 0?{totalCount:N.totalCount,totalCountIsExact:N.totalCountIsExact}:{}};return Z(r,Ye,{pageSize:w,hasMore:N.hasNextPage,...N.totalCount!==void 0?{totalCount:N.totalCount,totalCountIsExact:N.totalCountIsExact}:{}})}catch(l){fe(r,l,{ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:h,sort:g},"Failed to fetch documents",n);}}async function R(p){let r=p.c,m=r.req.param(),i=a(m.repoName,r);if(!i)return b(r,"Repository not found",404);let y=d(r);if(!await s(r,i,"list",{user:y,query:p.input||{},params:m}))return;let h=[],g;try{let l=p.input||{},w=Math.min(l.pageSize||i.pageSize,100),x=l.direction==="prev"?"prev":"next";l.where&&(h=l.where.map(E=>({field:String(E[0]),op:E[1],value:String(E[2]??"")}))),l.orderBy&&l.orderBy[0]&&(g={field:l.orderBy[0].field,dir:l.orderBy[0].direction==="desc"?"desc":"asc"});let C=l.withTotal===!0||String(l.withTotal)==="true",A={pageSize:w,direction:x,...C?{withTotal:!0}:{}};if(l.cursor)try{let E=typeof l.cursor=="string"?JSON.parse(l.cursor):l.cursor;A.cursor=await De(i,E);}catch{}if(i.allowedIncludes&&l.includes&&l.includes.length>0){let E=l.includes.filter(T=>typeof T=="string"?i.allowedIncludes.includes(T):typeof T=="object"&&T!==null&&"relation"in T&&typeof T.relation=="string"?i.allowedIncludes.includes(T.relation):!1);E.length>0&&(A.include=E);}if(l.where&&l.where.length>0){if(i.filterableFields){let T=new Set(i.filterableFields),k=l.where.filter(D=>!T.has(D[0]));if(k.length>0){b(r,`Fields not filterable: ${k.map(D=>D[0]).join(", ")}`,400);return}}let E=[];for(let T of l.where){let k=te(i.schema,T[0],T[2]);if(!k.success){b(r,`Invalid filter value for '${T[0]}': ${k.error}`,400);return}E.push([T[0],T[1],k.data]);}A.where=E;}if(l.orWhere&&l.orWhere.length>0){if(i.filterableFields){let T=new Set(i.filterableFields),k=l.orWhere.filter(D=>!T.has(D[0]));if(k.length>0){b(r,`Fields not filterable: ${k.map(D=>D[0]).join(", ")}`,400);return}}let E=[];for(let T of l.orWhere){let k=te(i.schema,T[0],T[2]);if(!k.success){b(r,`Invalid filter value for '${T[0]}': ${k.error}`,400);return}E.push([T[0],T[1],k.data]);}A.orWhere=E;}if(l.orWhereGroups&&l.orWhereGroups.length>0){if(i.filterableFields){let T=new Set(i.filterableFields);for(let k of l.orWhereGroups){let D=k.filter(z=>!T.has(z[0]));if(D.length>0){b(r,`Fields not filterable: ${D.map(z=>z[0]).join(", ")}`,400);return}}}let E=[];for(let T of l.orWhereGroups){let k=[];for(let D of T){let z=te(i.schema,D[0],D[2]);if(!z.success){b(r,`Invalid filter value for '${D[0]}': ${z.error}`,400);return}k.push([D[0],D[1],z.data]);}E.push(k);}A.orWhereGroups=E;}if(l.orderBy&&l.orderBy.length>0){if(i.orderableFields){let E=new Set(i.orderableFields),T=l.orderBy.filter(k=>!E.has(k.field));if(T.length>0){b(r,`Fields not orderable: ${T.map(k=>k.field).join(", ")}`,400);return}}A.orderBy=l.orderBy;}l.select&&l.select.length>0&&(A.select=l.select);let O=await i.repo.query.paginate(A),U={items:await o(i,d(r),m,O.data),hasNextPage:O.hasNextPage,hasPrevPage:O.hasPrevPage,nextCursor:ne(O.nextCursor),prevCursor:ne(O.prevCursor),...O.totalCount!==void 0?{totalCount:O.totalCount,totalCountIsExact:O.totalCountIsExact}:{}};return Z(r,U,{pageSize:w,hasMore:O.hasNextPage,...O.totalCount!==void 0?{totalCount:O.totalCount,totalCountIsExact:O.totalCountIsExact}:{}})}catch(l){fe(r,l,{ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:h,sort:g},"Failed to query documents",n);}}async function S(p){let r=p.c,m=r.req.param(),i=a(m.repoName,r);if(!i)return b(r,"Repository not found",404);let y=m.id;if(!y)return b(r,"Document ID required",400);try{let h=await u(i,y);if(!h)return b(r,"Document not found",404);let g=d(r);if(!await s(r,i,"get",{user:g,doc:h,params:m}))return;if(i.rules?.filter)try{if(!await i.rules.filter({user:g,doc:h,params:m}))return b(r,"Document not found",404)}catch{return b(r,"Document not found",404)}return Z(r,h)}catch(h){fe(r,h,{ref:i.repo.ref,path:i.path,isGroup:!!i.isGroup,filters:[{field:i.documentKey,op:"==",value:y}]},"Failed to fetch document",n);}}async function P(p){let r=p.c,m=r.req.param(),i=a(m.repoName,r);if(!i)return b(r,"Repository not found",404);try{let y=p.input||{},h=d(r);if(!await s(r,i,"create",{user:h,body:y,params:m}))return;let g=ee(i.schema,y,i.createFields,!1,i.systemKeys);if(!g.success)return b(r,g.error,400);if(i.validate){let w=await i.validate(g.data,"create");if(w)return b(r,w,400)}let l;if(i.isGroup&&i.parentKeys&&i.parentKeys.length>0){let w={...g.data};i.createdKey&&(w[i.createdKey]=new Date);let x=i.parentKeys.filter(O=>!w[O]);if(x.length>0){b(r,`Missing parent key(s) for subcollection create: ${x.join(", ")}`,400);return}let C=i.parentKeys.map(O=>w[O]),A=w[i.documentKey]||Pe();l=await i.repo.set(...C,A,w);}else l=await i.repo.create(g.data);return Z(r,l,void 0,201)}catch(y){let h=n&&y instanceof Error?y.message:"Failed to create document";return b(r,h,500)}}async function $(p,r){let m=p.c,i=m.req.param(),y=a(i.repoName,m);if(!y)return b(m,"Repository not found",404);let h=i.id;if(!h)return b(m,"Document ID required",400);try{let g=p.input||{},l=await u(y,h);if(!l)return b(m,"Document not found",404);let w=d(m);if(!await s(m,y,"update",{user:w,doc:l,body:g,params:i}))return;let x=ee(y.schema,g,y.mutableFields,r,y.systemKeys);if(!x.success)return b(m,x.error,400);if(y.validate){let O=await y.validate(x.data,"update");if(O)return b(m,O,400)}let C=c(l,y.pathKey)??[h],A=await y.repo.update(...C,x.data);return Z(m,A)}catch(g){let l=n&&g instanceof Error?g.message:"Failed to update document";return b(m,l,500)}}async function j(p){let r=p.c,m=r.req.param(),i=a(m.repoName,r);if(!i)return b(r,"Repository not found",404);if(!i.allowDelete)return b(r,"Delete not allowed for this repository",403);let y=m.id;if(!y)return b(r,"Document ID required",400);try{let h=await u(i,y);if(!h)return b(r,"Document not found",404);let g=d(r);if(!await s(r,i,"delete",{user:g,doc:h,params:m}))return;let l=c(h,i.pathKey)??[y];return await i.repo.delete(...l),Z(r,{deleted:!0})}catch(h){let g=n&&h instanceof Error?h.message:"Failed to delete document";return b(r,g,500)}}function I(p){return p.c.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization","Access-Control-Max-Age":"86400"})}async function v(p){let r=p.c,m=r.req.param(),i=a(m.repoName,r);if(!i)return b(r,"Repository not found",404);try{let y=p.input||{};if(!Array.isArray(y.operations))return b(r,"operations array is required",400);let h=d(r),g=i.repo.batch.create(),l=[];for(let w of y.operations){if(!w.type||!["create","update","delete"].includes(w.type))return b(r,"Invalid operation type",400);if(w.type==="create"){if(!await s(r,i,"create",{user:h,body:w.data,params:m}))return;let x=ee(i.schema,w.data,i.createFields,!1,i.systemKeys);if(!x.success)return b(r,x.error,400);let C=w.data[i.documentKey]||Pe(),A={...x.data};if(i.createdKey&&(A[i.createdKey]=new Date),i.isGroup&&i.parentKeys){let O=i.parentKeys.map(H=>A[H]);g.set(...O,C,A);}else g.set(C,A);l.push({op:"create",id:C});}else if(w.type==="update"){if(!w.id)return b(r,"id required for update",400);let x=await u(i,w.id);if(!x)return b(r,`Document ${w.id} not found`,404);if(!await s(r,i,"update",{user:h,doc:x,body:w.data,params:m}))return;let C=ee(i.schema,w.data,i.mutableFields,!0,i.systemKeys);if(!C.success)return b(r,C.error,400);let A=c(x,i.pathKey)??[w.id];g.update(...A,C.data),l.push({op:"update",id:w.id});}else if(w.type==="delete"){if(!i.allowDelete)return b(r,"Delete not allowed",403);if(!w.id)return b(r,"id required for delete",400);let x=await u(i,w.id);if(!x)return b(r,`Document ${w.id} not found`,404);if(!await s(r,i,"delete",{user:h,doc:x,params:m}))return;let C=c(x,i.pathKey)??[w.id];g.delete(...C),l.push({op:"delete",id:w.id});}}return await g.commit(),Z(r,{results:l})}catch(y){let h=n&&y instanceof Error?y.message:"Batch operation failed";return b(r,h,500)}}return {handleList:f,handleQuery:R,handleGet:S,handleCreate:P,handleUpdate:$,handleDelete:j,handleBatch:v,handleOptions:I}}function re(e){try{return z.toJSONSchema(e,{target:"openapi-3.1",unrepresentable:"any",override:t=>{let n=getOpenApiMetadata(t.zodSchema);n&&(Object.assign(t.jsonSchema,n),(t.jsonSchema.anyOf||t.jsonSchema.oneOf)&&delete t.jsonSchema.type);let s=t.zodSchema?._zod?.def;s&&(s.type==="date"&&!t.jsonSchema.type&&!t.jsonSchema.anyOf?(t.jsonSchema.type="string",t.jsonSchema.format="date-time"):s.type==="bigint"&&!t.jsonSchema.type&&!t.jsonSchema.anyOf&&(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 _(e){return {$ref:`#/components/schemas/${e}`}}function q(e){return {description:e,content:{"application/json":{schema:_("ErrorResponse")}}}}function W(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function ze(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"},totalCount:{type:"integer",description:"Total count of matching documents (when requested with withTotal=true)"},totalCountIsExact:{type:"boolean",description:"Whether totalCount is exact (true) or estimated due to OR conditions (false)"}},required:["items","hasNextPage","hasPrevPage"]},meta:{type:"object",properties:{pageSize:{type:"integer"},hasMore:{type:"boolean"},totalCount:{type:"integer"},totalCountIsExact:{type:"boolean"},cursor:{oneOf:[{type:"string"},{type:"null"}]}}}},required:["success","data"]}}}}}function Q(e){let t=e;for(;t;){let n=t._zod?.def??t._def;if(!n)break;if(n.innerType)t=n.innerType;else if(n.schema)t=n.schema;else if(n.type==="optional"||n.type==="nullable"||n.type==="default"||n.type==="catch"||n.type==="effects")t=n.innerType??n.schema;else break}return t}function vt(e,t){let n=t.split("."),s=Q(e);for(let o=0;o<n.length;o++){let d=n[o];if(!d)continue;let a=s?.shape;if(!a||!a[d])return;let c=a[d];if(o===n.length-1)return c;s=Q(c);}return s}function be(e,t="",n=0){if(n>5)return [];let o=Q(e)?.shape;if(!o)return [];let d=[];for(let[a,c]of Object.entries(o)){let u=t?`${t}.${a}`:a,f=Q(c);f?.shape&&typeof f.shape=="object"?(d.push({path:u,zodSchema:c}),d.push(...be(f,u,n+1))):d.push({path:u,zodSchema:c});}return d}function Se(e){return e.filterableFields&&e.filterableFields.length>0?e.filterableFields.map(t=>({path:t,zodSchema:vt(e.schema,t)})):be(e.schema)}function we(e){if(!e)return {type:"string"};let t=re(e);return delete t.$schema,delete t.title,t}function At(e){let t=Se(e),n=e.orderableFields??t.map(s=>s.path);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",...n.length>0?{enum:n}:{}},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${t.length>0?` (${t.map(s=>s.path).join(", ")})`:""}`},{name:"withTotal",in:"query",schema:{type:"boolean"},description:"Include total document count (totalCount and totalCountIsExact) in response"}]}function Tt(e){let t=Se(e),n=["eq","ne","lt","lte","gt","gte","in","nin","contains","containsAny"],s={eq:"equals. Use 'null' or '__null__' to match null values",ne:"not equals. Use 'null' or '__null__' to match non-null values",lt:"less than",lte:"less than or equal",gt:"greater than",gte:"greater than or equal",in:"in list (comma-separated values). Supports 'null' and '__null__' (e.g. val1,val2,__null__)",nin:"not in list (comma-separated values). Supports 'null' and '__null__'",contains:"array-contains",containsAny:"array-contains-any (comma-separated values). Supports 'null' and '__null__'"},o=[];for(let{path:d,zodSchema:a}of t){let c=we(a);o.push({name:d,in:"query",schema:c,description:`Filter by ${d} (equality). Use 'null' or '__null__' for null values`});for(let u of n){let f=s[u]?` (${s[u]})`:"",R=u==="in"||u==="nin"||u==="containsAny";o.push({name:`${d}__${u}`,in:"query",schema:R?{type:"string",description:"Comma-separated list of values"}:c,description:`Filter ${d} with operator ${u}${f}`});}}return o}function Fe(){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)"},withTotal:{type:"boolean",description:"Include total document count (totalCount and totalCountIsExact) in response"}}}}function Ot(e){let t=Se(e),n=e.orderableFields??t.map(a=>a.path),s=t.map(a=>a.path);if(t.length===0)return Fe();let o=[];for(let{path:a,zodSchema:c}of t){let u=we(c),f=Q(c),S=f?._zod?.def?.type==="array"||f?._def?.typeName==="ZodArray"||f?._def?.type==="array"?we(f?._zod?.def?.element??f?._def?.type??f?._def?.element):u;o.push({type:"array",description:`Condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["==","!=","<","<=",">",">=","eq","ne","lt","lte","gt","gte"]},u],minItems:3,maxItems:3}),o.push({type:"array",description:`List condition on '${a}' (in, not-in)`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["in","not-in","nin"]},{type:"array",items:u}],minItems:3,maxItems:3}),o.push({type:"array",description:`Array contains condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["array-contains","contains"]},S],minItems:3,maxItems:3}),o.push({type:"array",description:`Array contains-any condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["array-contains-any","containsAny"]},{type:"array",items:S}],minItems:3,maxItems:3});}let d={oneOf:o};return {type:"object",properties:{where:{type:"array",items:d,description:"AND conditions: [field, operator, value][]"},orWhere:{type:"array",items:d,description:"Simple OR conditions (each independently OR'd)"},orWhereGroups:{type:"array",items:{type:"array",items:d},description:"Advanced OR groups (AND within, OR across groups)"},orderBy:{type:"array",items:{type:"object",properties:{field:{type:"string",enum:n},direction:{type:"string",enum:["asc","desc"]}},required:["field"]}},select:{type:"array",items:{type:"string",enum:s},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:e.allowedIncludes&&e.allowedIncludes.length>0?{oneOf:[{type:"string",enum:e.allowedIncludes},{type:"object",properties:{relation:{type:"string",enum:e.allowedIncludes},select:{type:"array",items:{type:"string"}}},required:["relation"]}]}:{oneOf:[{type:"string"},{type:"object",properties:{relation:{type:"string"},select:{type:"array",items:{type:"string"}}},required:["relation"]}]},description:"Relations to include (populate)"},withTotal:{type:"boolean",description:"Include total document count (totalCount and totalCountIsExact) in response"}}}}function kt(e,t,n,s,o,d="QueryRequestBody"){let a={},c=e.name,u=`${t}/${e.name}`,f=`${u}/{${e.documentKey}}`,R={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};a[u]={get:{operationId:`list${M(e.name)}`,summary:`List ${e.name} (paginated)`,tags:[c],parameters:[...At(e),...Tt(e)],responses:{200:ze(_(n)),500:q("Internal server error")}},post:{operationId:`create${M(e.name)}`,summary:`Create a ${B(e.name)}`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:_(s??n)}}},responses:{201:W("Document created",_(n)),400:q("Validation error"),500:q("Internal server error")}}},a[`${u}/query`]={post:{operationId:`query${M(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:_(d)}}},responses:{200:ze(_(n)),400:q("Invalid query"),500:q("Internal server error")}}},a[`${u}/batch`]={post:{operationId:`batch${M(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:_(`${n}BatchRequest`)}}},responses:{200:W("Batch operations completed",{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{op:{type:"string"},id:{type:"string"}}}}}}),400:q("Validation error"),403:q("Forbidden"),404:q("Document not found"),500:q("Internal server error")}}};let S={};return S.get={operationId:`get${M(B(e.name))}`,summary:`Get a single ${B(e.name)}`,tags:[c],parameters:[R],responses:{200:W("Document found",_(n)),404:q("Document not found"),500:q("Internal server error")}},S.put={operationId:`update${M(B(e.name))}`,summary:`Update a ${B(e.name)} (full replace)`,tags:[c],parameters:[R],requestBody:{required:true,content:{"application/json":{schema:_(o??n)}}},responses:{200:W("Document updated",_(n)),400:q("Validation error"),404:q("Document not found"),500:q("Internal server error")}},S.patch={operationId:`patch${M(B(e.name))}`,summary:`Partially update a ${B(e.name)}`,tags:[c],parameters:[R],requestBody:{required:true,content:{"application/json":{schema:{allOf:[_(o??n)],description:"All fields are optional for partial updates"}}}},responses:{200:W("Document patched",_(n)),400:q("Validation error"),404:q("Document not found"),500:q("Internal server error")}},e.allowDelete&&(S.delete={operationId:`delete${M(B(e.name))}`,summary:`Delete a ${B(e.name)}`,tags:[c],parameters:[R],responses:{200:W("Document deleted",{type:"object",properties:{id:{type:"string"}}}),404:q("Document not found"),500:q("Internal server error")}}),a[f]=S,a}function xe(e,t,n={}){let{title:s="CRUD API",version:o="1.0.0",description:d,servers:a,auth:c=false}=n,u=t==="/"?"":t.replace(/\/$/,""),f={},R={},S=[];f.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string"}},required:["success","error"]},f.QueryRequestBody=Fe();for(let[I,v]of Object.entries(e)){let p=M(B(I)),r=`${p}Create`,m=`${p}Update`,i=`${p}QueryRequestBody`;f[p]=re(v.schema),f[i]=Ot(v);let y=C=>{let A={},O=be(v.schema);for(let{path:H,zodSchema:U}of O){let E=H.split(".")[0];v.systemKeys.includes(E)||v.systemKeys.includes(H)||C&&C.length>0&&!C.includes(H)&&!C.includes(E)||(H.includes(".")?A[H]=U.optional():A[H]=U);}return A},h=null,g=y(v.createFields);Object.keys(g).length>0&&(f[r]=re(z.object(g)),h=r);let l=null,w=y(v.mutableFields);Object.keys(w).length>0&&(f[m]=re(z.object(w)),l=m),f[`${p}BatchRequest`]={type:"object",properties:{operations:{type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",enum:["create"]},data:_(h??p)},required:["type","data"]},{type:"object",properties:{type:{type:"string",enum:["update"]},id:{type:"string"},data:{allOf:[_(l??p)],description:"Partial updates allowed"}},required:["type","id","data"]},...v.allowDelete?[{type:"object",properties:{type:{type:"string",enum:["delete"]},id:{type:"string"}},required:["type","id"]}]:[]]}}},required:["operations"]};let x=kt(v,u,p,h,l,i);Object.assign(R,x),S.push({name:I,description:`Operations on ${I} (collection: ${v.path})`});}let P={},$;return c==="basic"?(P.basicAuth={type:"http",scheme:"basic"},$=[{basicAuth:[]}]):c==="bearer"&&(P.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},$=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:s,version:o,...d?{description:d}:{}},...a&&a.length>0?{servers:a}:{},paths:R,components:{schemas:f,...Object.keys(P).length>0?{securitySchemes:P}:{}},...$?{security:$}:{},tags:S}}function M(e){return e.charAt(0).toUpperCase()+e.slice(1)}function B(e){return e.endsWith("ies")?e.slice(0,-3)+"y":e.endsWith("ses")||e.endsWith("xes")||e.endsWith("zes")?e.slice(0,-2):e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e}var J=class extends Error{constructor(n,s){super("Request validation failed");this.zodError=n;this.source=s;this.statusCode=400;this.name="ValidationError";}};var V=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},X=class extends Error{constructor(n){super("Output validation failed");this.zodError=n;this.statusCode=500;this.name="OutputValidationError";}};function _e(e){return e.issues.map(t=>({path:t.path.join("."),code:t.code,message:t.message}))}function He(e,t){return t instanceof J?e.json({success:false,error:"Validation failed",issues:_e(t.zodError)},400):t instanceof V?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof X?e.json({success:false,error:"Output validation failed",issues:_e(t.zodError)},500):null}extendZodWithOpenApi(z);var Ne="Successful response",Be="Error response";function jt(e){return e==="get"?"query":"json"}function Dt(e,t){let n=t?.output;return n?typeof n=="function"?n(e):n:e}function qt(e){if(typeof e.safeParse=="function")return {description:Be,schema:e};let t=e;return {description:t.description??Be,schema:t.schema}}function Le(e,t,n,s){let o=new OpenAPIRegistry;if(n.securitySchemes)for(let[c,u]of Object.entries(n.securitySchemes))o.registerComponent("securitySchemes",c,u);for(let c of e){let u=c.method,f=c.source??jt(u),R=Ft(t,c.path??"/"),S=c.status??200,P=$t(u,f,c.input),$=Me(f,c.input,"query"),j=Me(f,c.input,"param"),I=_t(u,R),v=Dt(c.output,s),p={[S]:v?{description:Ne,content:{"application/json":{schema:v}}}:{description:Ne}};if(s?.errors)for(let[r,m]of Object.entries(s.errors)){let{description:i,schema:y}=qt(m);p[r]=y?{description:i,content:{"application/json":{schema:y}}}:{description:i};}o.registerPath({method:u,path:zt(R),operationId:I,summary:c.summary,description:c.description,tags:c.tags,deprecated:c.deprecated,security:c.security,request:{...$?{query:$}:{},...j?{params:j}:{},...P?{body:P}:{}},responses:p});}return new OpenApiGeneratorV31(o.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security})}function $t(e,t,n){return !n||e==="get"?null:t==="json"?{content:{"application/json":{schema:n}}}:t==="form"?{content:{"application/x-www-form-urlencoded":{schema:n}}}:null}function Me(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function zt(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function Ft(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,s=t.startsWith("/")?t:`/${t}`,o=`${n}${s}`;return o===""?"/":o}function _t(e,t){let n=t.replace(/[{}]/g,"").replace(/\/+/g,"_").replace(/[^A-Za-z0-9_]/g,"").replace(/^_+|_+$/g,"");return `${e}_${n||"root"}`}function Ue(e,t){let n=e.replace(/"/g,""");return `<!doctype html>
|
|
2
2
|
<html lang="en">
|
|
3
3
|
<head>
|
|
4
4
|
<meta charset="utf-8" />
|