@lpdjs/firestore-repo-service 3.0.9 → 3.0.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -0
- package/dist/{create-servers-6tpqVsSh.d.cts → create-servers-DQBvtkBM.d.cts} +26 -14
- package/dist/{create-servers-U8q943yf.d.ts → create-servers-KRf2J2fi.d.ts} +26 -14
- package/dist/{firebase-auth-Ds5P0kXT.d.cts → firebase-auth-nG3prKoj.d.cts} +2 -1
- package/dist/{firebase-auth-Ds5P0kXT.d.ts → firebase-auth-nG3prKoj.d.ts} +2 -1
- package/dist/history/index.cjs +1 -1
- package/dist/history/index.cjs.map +1 -1
- package/dist/history/index.d.cts +3 -3
- package/dist/history/index.d.ts +3 -3
- package/dist/history/index.js +1 -1
- package/dist/history/index.js.map +1 -1
- package/dist/index.cjs +71 -71
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +14 -13
- package/dist/index.d.ts +14 -13
- package/dist/index.js +71 -71
- package/dist/index.js.map +1 -1
- package/dist/llms-full.txt +30 -15
- package/dist/llms.txt +1 -1
- package/dist/{openapi-Bp4vtku3.d.cts → openapi-CzrvqcOE.d.ts} +3 -2
- package/dist/{openapi-D6hEI2lq.d.ts → openapi-DK7pS1zN.d.cts} +3 -2
- package/dist/{queue-CrH-eNEN.d.ts → queue-CdmBSUNN.d.cts} +3 -2
- package/dist/{queue-CiZNShPZ.d.cts → queue-HoGBozpD.d.ts} +3 -2
- package/dist/{read-DWUsiHcw.d.cts → read-15-TcgCz.d.ts} +3 -2
- package/dist/{read-_6UEFCDw.d.ts → read-B15YaPyR.d.cts} +3 -2
- package/dist/{rules-BB0w7PlS.d.cts → rules-Bu2WJoLI.d.cts} +2 -2
- package/dist/{rules-6LZ9KkR6.d.ts → rules-gKR5VFhO.d.ts} +2 -2
- package/dist/servers/admin/index.cjs +1 -1
- package/dist/servers/admin/index.cjs.map +1 -1
- package/dist/servers/admin/index.d.cts +12 -8
- package/dist/servers/admin/index.d.ts +12 -8
- package/dist/servers/admin/index.js +1 -1
- package/dist/servers/admin/index.js.map +1 -1
- package/dist/servers/auth/index.d.cts +1 -1
- package/dist/servers/auth/index.d.ts +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 +11 -10
- package/dist/servers/crud/index.d.ts +11 -10
- package/dist/servers/crud/index.js +2 -2
- package/dist/servers/crud/index.js.map +1 -1
- package/dist/servers/hono/index.d.cts +5 -4
- package/dist/servers/hono/index.d.ts +5 -4
- package/dist/servers/index.cjs +41 -41
- package/dist/servers/index.cjs.map +1 -1
- package/dist/servers/index.d.cts +14 -13
- package/dist/servers/index.d.ts +14 -13
- package/dist/servers/index.js +41 -41
- package/dist/servers/index.js.map +1 -1
- package/dist/sync/bigquery.d.cts +6 -5
- package/dist/sync/bigquery.d.ts +6 -5
- package/dist/sync/index.cjs +45 -45
- package/dist/sync/index.cjs.map +1 -1
- package/dist/sync/index.d.cts +9 -8
- package/dist/sync/index.d.ts +9 -8
- package/dist/sync/index.js +45 -45
- package/dist/sync/index.js.map +1 -1
- package/dist/sync/meilisearch.d.cts +6 -5
- package/dist/sync/meilisearch.d.ts +6 -5
- package/dist/{types-BwucrwN0.d.cts → types--RamYGF1.d.cts} +24 -2
- package/dist/{types-BwucrwN0.d.ts → types--RamYGF1.d.ts} +24 -2
- package/dist/{types-D9Nm-4pg.d.cts → types-8Yoacm2k.d.cts} +9 -7
- package/dist/{types-DSMiiOrU.d.ts → types-D3W_RaDA.d.ts} +3 -2
- package/dist/{types-CXQeSrhO.d.ts → types-DRKB8gTA.d.ts} +9 -7
- package/dist/{types-D_snvgmB.d.cts → types-DZoEAKT7.d.cts} +24 -5
- package/dist/{types-DgtfcerG.d.ts → types-DiGFAWPA.d.ts} +24 -5
- package/dist/{types-HZG1KlML.d.ts → types-DzJ9WrcY.d.ts} +28 -4
- package/dist/{types-C5qxru8j.d.cts → types-KEVZXCF4.d.cts} +28 -4
- package/dist/{types-BIZz3sxN.d.cts → types-o-9qoExc.d.cts} +3 -2
- package/package.json +20 -20
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { A as AuthExtension, a as AuthRoute, b as AuthUser, D as DecodedIdTokenLike, F as FirebaseAdminAuthLike, c as FirebaseAuthConfig, d as FirebaseAuthLoginPageConfig, e as FirebaseAuthMode, f as allowAll, g as firebaseAuth, i as isAuthExtension } from '../../firebase-auth-nG3prKoj.cjs';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Session cookie + logout handlers for `firebaseAuth`.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { A as AuthExtension, a as AuthRoute, b as AuthUser, D as DecodedIdTokenLike, F as FirebaseAdminAuthLike, c as FirebaseAuthConfig, d as FirebaseAuthLoginPageConfig, e as FirebaseAuthMode, f as allowAll, g as firebaseAuth, i as isAuthExtension } from '../../firebase-auth-nG3prKoj.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Session cookie + logout handlers for `firebaseAuth`.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';var crypto=require('crypto'),zod=require('zod'),firestore=require('firebase-admin/firestore'),zodToOpenapi=require('@asteasolutions/zod-to-openapi'),hono=require('hono'),nodeServer=require('@hono/node-server'),async_hooks=require('async_hooks');var fe=Object.defineProperty;var ct=Object.getOwnPropertyDescriptor;var dt=Object.getOwnPropertyNames;var ut=Object.prototype.hasOwnProperty;var pt=(e,t)=>()=>(e&&(t=e(e=0)),t);var lt=(e,t)=>{for(var n in t)fe(e,n,{get:t[n],enumerable:true});},ft=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of dt(t))!ut.call(e,r)&&r!==n&&fe(e,r,{get:()=>t[r],enumerable:!(s=ct(t,r))||s.enumerable});return e};var yt=e=>ft(fe({},"__esModule",{value:true}),e);var st={};lt(st,{DEFAULT_HTML_CSP:()=>ot,securityHeaders:()=>an});function an(e={}){let t=e.csp===void 0?ot:e.csp,n=e.frameOptions===void 0?"DENY":e.frameOptions,s=e.referrerPolicy===void 0?"no-referrer":e.referrerPolicy,r=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),r&&a.setHeader("Cache-Control",r),t&&a.setHeader("Content-Security-Policy",t)),await c();}}var nt,rt,ot,it=pt(()=>{nt="https://cdn.jsdelivr.net",rt="https://www.gstatic.com",ot=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${nt} ${rt}`,`style-src 'self' 'unsafe-inline' ${nt}`,`connect-src 'self' ${rt} 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 Ce="preserve";function me(){return Ce}function mt(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function Ee(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(mt(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 Ie(e){return e}function Pe(e){let t=e;if(t._zod?.def?.element)return t._zod.def.element;if(t._def?.type)return t._def.type}var gt=new Set(["<","<=",">",">=","!="]),wt=new Set(["array-contains","array-contains-any"]);function he(e){return e==="desc"?"DESCENDING":"ASCENDING"}function bt(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function xt(e,t,n,s,r){let d=[],a=new Set;for(let p of s)if(p.op==="=="||p.op==="in"||p.op==="not-in"){if(a.has(p.field))continue;a.add(p.field),d.push({fieldPath:p.field,order:"ASCENDING"});}for(let p of s)if(wt.has(p.op)){if(a.has(p.field))continue;a.add(p.field),d.push({fieldPath:p.field,arrayConfig:"CONTAINS"});}for(let p of s)if(gt.has(p.op)){if(a.has(p.field))continue;a.add(p.field);let m=r?.field===p.field?he(r.dir):"ASCENDING";d.push({fieldPath:p.field,order:m});}if(r&&!a.has(r.field)&&d.push({fieldPath:r.field,order:he(r.dir)}),d.length===1&&n)return Tt(e,t,d[0]);let c=r&&d.some(p=>p.fieldPath===r.field)?he(r.dir):"ASCENDING";return d.push({fieldPath:"__name__",order:c}),Rt(e,t,n,d)}function Rt(e,t,n,s,r="(default)"){let d=`projects/${e}/databases/${r}/collectionGroups/${t}/indexes/_`,a=[...be(1,d),...ne(2,n?2:1)];for(let m of s)a.push(...De(3,je(m)));let c=r==="(default)"?"-default-":r,p=encodeURIComponent(ze(a));return `https://console.firebase.google.com/project/${e}/firestore/databases/${c}/indexes?create_composite=${p}`}function St(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function ge(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function we(e,t){return e<<3|t}function be(e,t){let n=Array.from(new TextEncoder().encode(t));return [we(e,2),...ge(n.length),...n]}function ne(e,t){return [we(e,0),...ge(t)]}function De(e,t){return [we(e,2),...ge(t.length),...t]}function je(e){let t=[...be(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...ne(3,1)):t.push(...ne(2,e.order==="DESCENDING"?2:1)),t}function ze(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 Tt(e,t,n,s="(default)"){let r=`projects/${e}/databases/${s}/collectionGroups/${t}/fields/${n.fieldPath}`,d=[...be(1,r),...ne(2,2),...De(3,je(n))],a=s==="(default)"?"-default-":s,c=encodeURIComponent(ze(d));return `https://console.firebase.google.com/project/${e}/firestore/databases/${a}/indexes/automatic?create_exemption=${c}`}function At(e){let t=e,n=[t?.firestore?.projectId,t?.firestore?.app?.options?.projectId,t?.firestore?._settings?.projectId,t?.firestore?.databaseId?.projectId,t?._firestore?.projectId];for(let r of n)if(typeof r=="string"&&r.length>0)return r;return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.FIREBASE_PROJECT_ID||void 0}function kt(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function _e(e,t){let n=e??{},s=kt(e),r;if(s&&(r=n.message?St(n.message):void 0,!r)){let d=At(t.ref);if(d){let a=bt(t.path);r=xt(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:r}}function oe(e,t,n=new WeakMap){if(e===t)return true;if(e===null||t===null||e===void 0||t===void 0)return e===t;if(e instanceof firestore.Timestamp&&t instanceof firestore.Timestamp)return e.isEqual(t);if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return false;if(n.get(e)===t)return true;n.set(e,t);for(let s=0;s<e.length;s++)if(!oe(e[s],t[s],n))return false;return true}if(typeof e=="object"&&typeof t=="object"){if(e instanceof Date||t instanceof Date||e instanceof firestore.Timestamp||t instanceof firestore.Timestamp)return false;if(n.get(e)===t)return true;n.set(e,t);let s=Object.keys(e),r=Object.keys(t);if(s.length!==r.length)return false;for(let d of s)if(!Object.prototype.hasOwnProperty.call(t,d)||!oe(e[d],t[d],n))return false;return true}return false}function se(e,t){let n=e||{},s={},r={...n};for(let[d,a]of Object.entries(t||{})){let c=n[d];oe(c,a)||(s[d]=a,r[d]=a);}return {before:n,after:r,changes:s}}function vt(e){return e}async function qe(e,t,n){let s=e.changes||{};for(let r of Object.keys(s)){let d=t[r];if(d&&d.length>0){for(let a of d)if(await a.rule({diff:e,key:r,user:n,authenticatedUser:n})===false)return {allowed:false,reason:a.description}}}return {allowed:true}}function Ot(e){return async t=>qe(t.diff,e,t.user)}function Se(e,t,n=200){let s=Ie(t);return e.json(s,n)}function W(e,t,n,s=200){return Se(e,{success:true,data:t,meta:n},s)}function w(e,t,n=400){return Se(e,{success:false,error:t},n)}async function xe(e,t,n,s,r,d){let a=_e(t,n),c=a.type==="index",p=c?424:500,b={success:false,error:c?a.message:r&&t instanceof Error?t.message:s};if(c&&(b.errorType="index",a.indexUrl&&(b.indexUrl=a.indexUrl,d)))try{let g=d({indexUrl:a.indexUrl,repoName:n.repoName??"",path:n.path,isGroup:n.isGroup,filters:n.filters,sort:n.sort,error:t,c:e});g instanceof Promise&&await g;}catch(g){r&&console.error("[crudServer] Error in indexesError callback:",g);}return Se(e,b,p)}var Re="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function $e(){let e="";for(;e.length<20;){let t=crypto.randomBytes(20);for(let n=0;n<t.length&&e.length<20;n++){let s=t[n];s>=Re.length*4||(e+=Re.charAt(s%Re.length));}}return e}function G(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(s=>Ee(s)??s,e);if(n==="ZodObject"||n==="object"){let s=e.shape,r={};for(let[d,a]of Object.entries(s))r[d]=G(a);return zod.z.object(r)}if(n==="ZodArray"||n==="array"){let s=t.element??t.type;if(s)return zod.z.array(G(s))}if(n==="ZodOptional"||n==="optional"){let s=t.innerType;if(s)return G(s).optional()}if(n==="ZodNullable"||n==="nullable"){let s=t.innerType;if(s)return G(s).nullable()}if(n==="ZodDefault"||n==="default"){let s=t.innerType,r=t.defaultValue;if(s){let d=G(s);return typeof r=="function"?d.default(r()):d.default(r)}}return e}function Et(e,t,n=[]){let s=e.shape,r={},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]&&(r[c]=s[c]);}return zod.z.object(r)}function de(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 Ze(e,t){let n=t.split("."),s=de(e);for(let r=0;r<n.length;r++){let d=n[r];if(!d)continue;let a=s?.shape;if(!a||!a[d])return;let c=a[d];if(r===n.length-1)return c;s=de(c);}return s}function He(e){let t=de(e),n=t?._zod?.def??t?._def,s=n?.typeName??n?.type;if(s==="ZodObject"||s==="object"){let r=t.shape,d={};for(let[a,c]of Object.entries(r))d[a]=He(c);return zod.z.object(d).partial()}return e}function ie(e,t,n,s=false,r=[]){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[p,m]of Object.entries(d))if(p.includes(".")){let b=p.split(".")[0];if(r.includes(p)||r.includes(b))continue;if(n&&n.length>0&&!n.includes(p)&&!n.includes(b))return {success:!1,error:`Field '${p}' is not allowed for this operation`};let g=Ze(e,p);if(!g)return {success:!1,error:`Field '${p}' does not exist in schema`};let I=(me()==="normalize"?G(g):g).parse(m);a[p]=I;}else c[p]=m;if(Object.keys(c).length>0||Object.keys(a).length===0){let p=Et(e,n,r),m=s?He(p):p,g=(me()==="normalize"?G(m):m).parse(c);Object.assign(a,g);}return {success:!0,data:a}}catch(d){return d instanceof zod.z.ZodError?{success:false,error:`Validation failed: ${d.issues.map(c=>`${c.path.join(".")}: ${c.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}var Me={eq:"==","==":"==",ne:"!=","!=":"!=",lt:"<","<":"<",lte:"<=","<=":"<=",gt:">",">":">",gte:">=",">=":">=",in:"in",nin:"not-in","not-in":"not-in",not_in:"not-in",contains:"array-contains","array-contains":"array-contains",array_contains:"array-contains",arrayContains:"array-contains",containsAny:"array-contains-any","array-contains-any":"array-contains-any",array_contains_any:"array-contains-any",arrayContainsAny:"array-contains-any"};function X(e){return Me[e]??e}function It(e){return e in Me}function ae(e,t,n,s){let r=Ze(e,t);if(!r||typeof r.safeParse!="function")return {success:true,data:n};let d=s?X(s):void 0,a=de(r),c=Pe(a);if(d==="array-contains"){let b=c??r;if(typeof b.safeParse=="function"){let g=b.safeParse(n);return g.success?{success:true,data:g.data}:{success:false,error:g.error.issues.map(I=>I.message).join(", ")}}return {success:true,data:n}}if(d==="array-contains-any"){if(!Array.isArray(n))return {success:false,error:"Expected array value for array-contains-any"};let b=c??r,g=[];for(let C of n)if(typeof b.safeParse=="function"){let I=b.safeParse(C);if(I.success)g.push(I.data);else return {success:false,error:I.error.issues.map(k=>k.message).join(", ")}}else g.push(C);return {success:true,data:g}}let p=r.safeParse(n);if(p.success)return {success:true,data:p.data};if(Array.isArray(n)){let b=c??r,g=[];for(let C of n)if(typeof b.safeParse=="function"){let I=b.safeParse(C);if(I.success)g.push(I.data);else return {success:false,error:I.error.issues.map(k=>k.message).join(", ")}}else g.push(C);return {success:true,data:g}}return {success:false,error:p.error.issues.map(b=>b.message).join(", ")}}function Pt(e,t){let n=[],s=t?new Set(t):null;for(let[r,d]of Object.entries(e)){if(d===void 0||["cursor","direction","limit","pageSize","orderBy","orderDir","select","includes","withTotal"].includes(r))continue;let a=Array.isArray(d)?d[0]:d;if(a===void 0||a==="")continue;let c=r.lastIndexOf("__"),p,m="==";if(c!==-1){let g=r.slice(0,c),C=r.slice(c+2);It(C)?(p=g,m=X(C)):(p=r,m="==");}else p=r;if(s&&!s.has(p))continue;let b=a;m==="in"||m==="not-in"||m==="array-contains-any"?b=a.split(",").map(g=>Fe(g.trim())):b=Fe(a),n.push({field:p,op:m,value:b});}return n}function Fe(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 ce(e){return e?{docId:e.id,docPath:e.ref?.path??void 0}:null}async function Ne(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,r=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(r&&r.includes("/")&&a&&typeof a.doc=="function"){let c=await a.doc(r).get();if(c.exists)return c}if(r&&typeof d.doc=="function"){let c=await d.doc(r).get();if(c.exists)return c}return}catch{return}}function Be(e,t,n,s){async function r(l,i,f,o){if(!i.rules)return {allowed:true};let h=i.rules?.[f];if(!h)return {allowed:false,errorResponse:w(l,`Operation "${f}" is not allowed for this repository`,403)};try{let y=await h(o);return y===!1?{allowed:!1,errorResponse:w(l,"Forbidden",403)}:typeof y=="string"?{allowed:!1,errorResponse:w(l,y,403)}:typeof y=="object"&&y!==null&&!y.allowed?{allowed:!1,errorResponse:w(l,y.reason||"Forbidden",403)}:{allowed:!0}}catch(y){let x=n&&y instanceof Error?y.message:"Forbidden";return {allowed:false,errorResponse:w(l,x,403)}}}async function d(l,i,f,o){if(!l.rules)return o;let h=l.rules?.filter;if(!h)return o;let y=[];for(let x of o)try{await h({user:i,doc:x,params:f})&&y.push(x);}catch{}return y}function a(l){return l.get("user")??l.get("docsUser")??null}function c(l,i){if(!l){let f=i.req.path.split("/");for(let o of f)if(e[o]){l=o;break}}return !l||!e[l]?null:e[l]??null}function p(l,i){if(!i)return;let f=l[i];if(typeof f!="string"||!f)return;let o=f.split("/").filter(Boolean),h=[];for(let y=1;y<o.length;y+=2)h.push(o[y]);return h.length>0?h:void 0}async function m(l,i){let f=`by${l.documentKey.charAt(0).toUpperCase()}${l.documentKey.slice(1)}`,o=l.repo.get[f];if(typeof o=="function")try{let y=await o(i);if(y)return y}catch{}return (await l.repo.query.by({where:[[l.documentKey,"==",i]],limit:1}))[0]??null}async function b(l){let i=l.c,f=i.req.param(),o=c(f.repoName,i);if(!o)return w(i,"Repository not found",404);let h=a(i),y=await r(i,o,"list",{user:h,query:i.req.query(),params:f});if(!y.allowed)return y.errorResponse;let x=[],S;try{let u=i.req.query(),R=Math.min(Number(u.pageSize)||o.pageSize,100),O=u.cursor,q=u.direction?.toLowerCase()==="prev"?"prev":"next",T=u.orderBy,E=u.orderDir?.toLowerCase()==="desc"?"desc":"asc",M=u.select,B=M?M.split(",").map(Z=>Z.trim()):void 0,z=u.withTotal,A=z==="true"||z==="1"||z===!0,_;o.allowedIncludes&&u.includes&&(_=(typeof u.includes=="string"?u.includes.split(",").map(L=>L.trim()):Array.isArray(u.includes)?u.includes:[]).filter(L=>typeof L=="string"&&o.allowedIncludes.includes(L)),_?.length===0&&(_=void 0));let P=Pt(u,o.filterableFields);x=P.map(Z=>({field:Z.field,op:Z.op,value:String(Z.value??"")})),T&&(S={field:T,dir:E});let H={pageSize:R,direction:q,...A?{withTotal:!0}:{}};if(O)try{let Z=typeof O=="string"?JSON.parse(O):O;H.cursor=await Ne(o,Z);}catch{}if(T){if(o.orderableFields&&!o.orderableFields.includes(T))return w(i,`Field not orderable: ${T}`,400);H.orderBy=[{field:T,direction:E}];}if(P.length>0){H.where=[];for(let Z of P){let L=ae(o.schema,Z.field,Z.value,Z.op);if(!L.success)return w(i,`Invalid filter value for '${Z.field}': ${L.error}`,400);H.where.push([Z.field,Z.op,L.data]);}}B&&(H.select=B),_&&(H.include=_);let F=await o.repo.query.paginate(H),at={items:await d(o,a(i),f,F.data),hasNextPage:F.hasNextPage,hasPrevPage:F.hasPrevPage,nextCursor:ce(F.nextCursor),prevCursor:ce(F.prevCursor),...F.totalCount!==void 0?{totalCount:F.totalCount,totalCountIsExact:F.totalCountIsExact}:{}};return W(i,at,{pageSize:R,hasMore:F.hasNextPage,...F.totalCount!==void 0?{totalCount:F.totalCount,totalCountIsExact:F.totalCountIsExact}:{}})}catch(u){return await xe(i,u,{repoName:f.repoName||o.name,ref:o.repo.ref,path:o.path,isGroup:!!o.isGroup,filters:x,sort:S},"Failed to fetch documents",n,s)}}async function g(l){let i=l.c,f=i.req.param(),o=c(f.repoName,i);if(!o)return w(i,"Repository not found",404);let h=a(i),y=await r(i,o,"list",{user:h,query:l.input||{},params:f});if(!y.allowed)return y.errorResponse;let x=[],S;try{let u=l.input||{},R=Math.min(u.pageSize||o.pageSize,100),O=u.direction==="prev"?"prev":"next";u.where&&(x=u.where.map(z=>({field:String(z[0]),op:z[1],value:String(z[2]??"")}))),u.orderBy&&u.orderBy[0]&&(S={field:u.orderBy[0].field,dir:u.orderBy[0].direction==="desc"?"desc":"asc"});let q=u.withTotal===!0||String(u.withTotal)==="true",T={pageSize:R,direction:O,...q?{withTotal:!0}:{}};if(u.cursor)try{let z=typeof u.cursor=="string"?JSON.parse(u.cursor):u.cursor;T.cursor=await Ne(o,z);}catch{}if(o.allowedIncludes&&u.includes&&u.includes.length>0){let z=u.includes.filter(A=>typeof A=="string"?o.allowedIncludes.includes(A):typeof A=="object"&&A!==null&&"relation"in A&&typeof A.relation=="string"?o.allowedIncludes.includes(A.relation):!1);z.length>0&&(T.include=z);}if(u.where&&u.where.length>0){if(o.filterableFields){let A=new Set(o.filterableFields),_=u.where.filter(P=>!A.has(P[0]));if(_.length>0){w(i,`Fields not filterable: ${_.map(P=>P[0]).join(", ")}`,400);return}}let z=[];for(let A of u.where){let _=X(A[1]),P=ae(o.schema,A[0],A[2],_);if(!P.success){w(i,`Invalid filter value for '${A[0]}': ${P.error}`,400);return}z.push([A[0],_,P.data]);}T.where=z;}if(u.orWhere&&u.orWhere.length>0){if(o.filterableFields){let A=new Set(o.filterableFields),_=u.orWhere.filter(P=>!A.has(P[0]));if(_.length>0){w(i,`Fields not filterable: ${_.map(P=>P[0]).join(", ")}`,400);return}}let z=[];for(let A of u.orWhere){let _=X(A[1]),P=ae(o.schema,A[0],A[2],_);if(!P.success){w(i,`Invalid filter value for '${A[0]}': ${P.error}`,400);return}z.push([A[0],_,P.data]);}T.orWhere=z;}if(u.orWhereGroups&&u.orWhereGroups.length>0){if(o.filterableFields){let A=new Set(o.filterableFields);for(let _ of u.orWhereGroups){let P=_.filter(H=>!A.has(H[0]));if(P.length>0){w(i,`Fields not filterable: ${P.map(H=>H[0]).join(", ")}`,400);return}}}let z=[];for(let A of u.orWhereGroups){let _=[];for(let P of A){let H=X(P[1]),F=ae(o.schema,P[0],P[2],H);if(!F.success){w(i,`Invalid filter value for '${P[0]}': ${F.error}`,400);return}_.push([P[0],H,F.data]);}z.push(_);}T.orWhereGroups=z;}if(u.orderBy&&u.orderBy.length>0){if(o.orderableFields){let z=new Set(o.orderableFields),A=u.orderBy.filter(_=>!z.has(_.field));if(A.length>0){w(i,`Fields not orderable: ${A.map(_=>_.field).join(", ")}`,400);return}}T.orderBy=u.orderBy;}u.select&&u.select.length>0&&(T.select=u.select);let E=await o.repo.query.paginate(T),B={items:await d(o,a(i),f,E.data),hasNextPage:E.hasNextPage,hasPrevPage:E.hasPrevPage,nextCursor:ce(E.nextCursor),prevCursor:ce(E.prevCursor),...E.totalCount!==void 0?{totalCount:E.totalCount,totalCountIsExact:E.totalCountIsExact}:{}};return W(i,B,{pageSize:R,hasMore:E.hasNextPage,...E.totalCount!==void 0?{totalCount:E.totalCount,totalCountIsExact:E.totalCountIsExact}:{}})}catch(u){return await xe(i,u,{repoName:f.repoName||o.name,ref:o.repo.ref,path:o.path,isGroup:!!o.isGroup,filters:x,sort:S},"Failed to query documents",n,s)}}async function C(l){let i=l.c,f=i.req.param(),o=c(f.repoName,i);if(!o)return w(i,"Repository not found",404);let h=f.id;if(!h)return w(i,"Document ID required",400);try{let y=await m(o,h);if(!y)return w(i,"Document not found",404);let x=a(i),S=await r(i,o,"get",{user:x,doc:y,params:f});if(!S.allowed)return S.errorResponse;if(o.rules?.filter)try{if(!await o.rules.filter({user:x,doc:y,params:f}))return w(i,"Document not found",404)}catch{return w(i,"Document not found",404)}return W(i,y)}catch(y){return await xe(i,y,{repoName:f.repoName||o.name,ref:o.repo.ref,path:o.path,isGroup:!!o.isGroup,filters:[{field:o.documentKey,op:"==",value:h}]},"Failed to fetch document",n,s)}}async function I(l){let i=l.c,f=i.req.param(),o=c(f.repoName,i);if(!o)return w(i,"Repository not found",404);try{let h=l.input||{},y=a(i),x=await r(i,o,"create",{user:y,body:h,params:f});if(!x.allowed)return x.errorResponse;let S=ie(o.schema,h,o.createFields,!1,o.systemKeys);if(!S.success)return w(i,S.error,400);if(o.validate){let R=await o.validate(S.data,"create");if(R)return w(i,R,400)}let u;if(o.isGroup&&o.parentKeys&&o.parentKeys.length>0){let R={...S.data};o.createdKey&&(R[o.createdKey]=new Date);let O=o.parentKeys.filter(E=>!R[E]);if(O.length>0){w(i,`Missing parent key(s) for subcollection create: ${O.join(", ")}`,400);return}let q=o.parentKeys.map(E=>R[E]),T=R[o.documentKey]||$e();u=await o.repo.set(...q,T,R);}else u=await o.repo.create(S.data);return W(i,u,void 0,201)}catch(h){let y=n&&h instanceof Error?h.message:"Failed to create document";return w(i,y,500)}}async function $(l,i){let f=l.c,o=f.req.param(),h=c(o.repoName,f);if(!h)return w(f,"Repository not found",404);let y=o.id;if(!y)return w(f,"Document ID required",400);try{let x=l.input||{},S=await m(h,y);if(!S)return w(f,"Document not found",404);let u=ie(h.schema,x,h.mutableFields,i,h.systemKeys);if(!u.success)return w(f,u.error,400);if(h.validate){let M=await h.validate(u.data,"update");if(M)return w(f,M,400)}let R=se(S,u.data),O=a(f),q=await r(f,h,"update",{user:O,doc:S,body:u.data,diff:R,params:o});if(!q.allowed)return q.errorResponse;let T=p(S,h.pathKey)??[y],E=await h.repo.update(...T,u.data);return W(f,E)}catch(x){let S=n&&x instanceof Error?x.message:"Failed to update document";return w(f,S,500)}}async function k(l){let i=l.c,f=i.req.param(),o=c(f.repoName,i);if(!o)return w(i,"Repository not found",404);if(!o.allowDelete)return w(i,"Delete not allowed for this repository",403);let h=f.id;if(!h)return w(i,"Document ID required",400);try{let y=await m(o,h);if(!y)return w(i,"Document not found",404);let x=a(i),S=await r(i,o,"delete",{user:x,doc:y,params:f});if(!S.allowed)return S.errorResponse;let u=p(y,o.pathKey)??[h];return await o.repo.delete(...u),W(i,{deleted:!0})}catch(y){let x=n&&y instanceof Error?y.message:"Failed to delete document";return w(i,x,500)}}function v(l){return l.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 j(l){let i=l.c,f=i.req.param(),o=c(f.repoName,i);if(!o)return w(i,"Repository not found",404);try{let h=l.input||{};if(!Array.isArray(h.operations))return w(i,"operations array is required",400);let y=a(i),x=o.repo.batch.create(),S=[];for(let u of h.operations){if(!u.type||!["create","update","delete"].includes(u.type))return w(i,"Invalid operation type",400);if(u.type==="create"){let R=await r(i,o,"create",{user:y,body:u.data,params:f});if(!R.allowed)return R.errorResponse;let O=ie(o.schema,u.data,o.createFields,!1,o.systemKeys);if(!O.success)return w(i,O.error,400);let q=u.data[o.documentKey]||$e(),T={...O.data};if(o.createdKey&&(T[o.createdKey]=new Date),o.isGroup&&o.parentKeys){let E=o.parentKeys.map(M=>T[M]);x.set(...E,q,T);}else x.set(q,T);S.push({op:"create",id:q});}else if(u.type==="update"){if(!u.id)return w(i,"id required for update",400);let R=await m(o,u.id);if(!R)return w(i,`Document ${u.id} not found`,404);let O=ie(o.schema,u.data,o.mutableFields,!0,o.systemKeys);if(!O.success)return w(i,O.error,400);if(o.validate){let M=await o.validate(O.data,"update");if(M)return w(i,M,400)}let q=se(R,O.data),T=await r(i,o,"update",{user:y,doc:R,body:O.data,diff:q,params:f});if(!T.allowed)return T.errorResponse;let E=p(R,o.pathKey)??[u.id];x.update(...E,O.data),S.push({op:"update",id:u.id});}else if(u.type==="delete"){if(!o.allowDelete)return w(i,"Delete not allowed",403);if(!u.id)return w(i,"id required for delete",400);let R=await m(o,u.id);if(!R)return w(i,`Document ${u.id} not found`,404);let O=await r(i,o,"delete",{user:y,doc:R,params:f});if(!O.allowed)return O.errorResponse;let q=p(R,o.pathKey)??[u.id];x.delete(...q),S.push({op:"delete",id:u.id});}}return await x.commit(),W(i,{results:S})}catch(h){let y=n&&h instanceof Error?h.message:"Batch operation failed";return w(i,y,500)}}return {handleList:b,handleQuery:g,handleGet:C,handleCreate:I,handleUpdate:$,handleDelete:k,handleBatch:j,handleOptions:v}}function ue(e){try{return zod.z.toJSONSchema(e,{target:"openapi-3.1",unrepresentable:"any",override:t=>{let n=zodToOpenapi.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 N(e){return {$ref:`#/components/schemas/${e}`}}function D(e){return {description:e,content:{"application/json":{schema:N("ErrorResponse")}}}}function J(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function jt(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 Y(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 zt(e,t){let n=t.split("."),s=Y(e);for(let r=0;r<n.length;r++){let d=n[r];if(!d)continue;let a=s?.shape;if(!a||!a[d])return;let c=a[d];if(r===n.length-1)return c;s=Y(c);}return s}function Ae(e,t="",n=0){if(n>5)return [];let r=Y(e)?.shape;if(!r)return [];let d=[];for(let[a,c]of Object.entries(r)){let p=t?`${t}.${a}`:a,m=Y(c);m?.shape&&typeof m.shape=="object"?(d.push({path:p,zodSchema:c}),d.push(...Ae(m,p,n+1))):d.push({path:p,zodSchema:c});}return d}function _t(e){return e.filterableFields&&e.filterableFields.length>0?e.filterableFields.map(t=>({path:t,zodSchema:zt(e.schema,t)})):Ae(e.schema)}function Ue(e){if(!e)return {type:"string"};let t=ue(e);return delete t.$schema,delete t.title,t}function Le(){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 qt(e){let t=_t(e),n=e.orderableFields??t.map(a=>a.path),s=t.map(a=>a.path);if(t.length===0)return Le();let r=[];for(let{path:a,zodSchema:c}of t){let p=Ue(c),m=Y(c),g=m?._zod?.def?.type==="array"||m?._def?.typeName==="ZodArray"||m?._def?.type==="array"?Ue(m?._zod?.def?.element??m?._def?.type??m?._def?.element):p;r.push({type:"array",description:`Condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["==","!=","<","<=",">",">=","eq","ne","lt","lte","gt","gte"]},p],minItems:3,maxItems:3}),r.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:p}],minItems:3,maxItems:3}),r.push({type:"array",description:`Array contains condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["array-contains","contains"]},g],minItems:3,maxItems:3}),r.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:g}],minItems:3,maxItems:3});}let d={oneOf:r};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 $t(e,t,n,s,r,d="QueryRequestBody"){let a={},c=e.name,p=`${t}/${e.name}`,m=`${p}/{${e.documentKey}}`,b={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};a[p]={post:{operationId:`create${K(e.name)}`,summary:`Create a ${U(e.name)}`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:N(s??n)}}},responses:{201:J("Document created",N(n)),400:D("Validation error"),403:D("Forbidden"),500:D("Internal server error")}}},a[`${p}/query`]={post:{operationId:`query${K(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:N(d)}}},responses:{200:jt(N(n)),400:D("Invalid query"),403:D("Forbidden"),424:D("Missing composite index (includes indexUrl in response)"),500:D("Internal server error")}}},a[`${p}/batch`]={post:{operationId:`batch${K(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:N(`${n}BatchRequest`)}}},responses:{200:J("Batch operations completed",{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{op:{type:"string"},id:{type:"string"}}}}}}),400:D("Validation error"),403:D("Forbidden"),404:D("Document not found"),500:D("Internal server error")}}};let g={};return g.get={operationId:`get${K(U(e.name))}`,summary:`Get a single ${U(e.name)}`,tags:[c],parameters:[b],responses:{200:J("Document found",N(n)),400:D("Document ID required"),403:D("Forbidden"),404:D("Document not found"),424:D("Missing composite index (includes indexUrl in response)"),500:D("Internal server error")}},g.put={operationId:`update${K(U(e.name))}`,summary:`Update a ${U(e.name)} (full replace)`,tags:[c],parameters:[b],requestBody:{required:true,content:{"application/json":{schema:N(r??n)}}},responses:{200:J("Document updated",N(n)),400:D("Validation error"),403:D("Forbidden"),404:D("Document not found"),500:D("Internal server error")}},g.patch={operationId:`patch${K(U(e.name))}`,summary:`Partially update a ${U(e.name)}`,tags:[c],parameters:[b],requestBody:{required:true,content:{"application/json":{schema:{allOf:[N(r??n)],description:"All fields are optional for partial updates"}}}},responses:{200:J("Document patched",N(n)),400:D("Validation error"),403:D("Forbidden"),404:D("Document not found"),500:D("Internal server error")}},e.allowDelete&&(g.delete={operationId:`delete${K(U(e.name))}`,summary:`Delete a ${U(e.name)}`,tags:[c],parameters:[b],responses:{200:J("Document deleted",{type:"object",properties:{id:{type:"string"}}}),400:D("Document ID required"),403:D("Forbidden"),404:D("Document not found"),500:D("Internal server error")}}),a[m]=g,a}function ke(e,t,n={}){let{title:s="CRUD API",version:r="1.0.0",description:d,servers:a,auth:c=false}=n,p=t==="/"?"":t.replace(/\/$/,""),m={},b={},g=[];m.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string",description:"Human-readable error description"},errorType:{type:"string",enum:["index"],description:"Error category discriminator. Set to 'index' when a Firestore composite index is missing."},indexUrl:{type:"string",format:"uri",description:"Direct Firebase Console URL to create the required composite index (when errorType is 'index')."}},required:["success","error"]},m.QueryRequestBody=Le();for(let[k,v]of Object.entries(e)){let j=K(U(k)),l=`${j}Create`,i=`${j}Update`,f=`${j}QueryRequestBody`;m[j]=ue(v.schema),m[f]=qt(v);let o=T=>{let E={},M=Ae(v.schema);for(let{path:B,zodSchema:z}of M){let A=B.split(".")[0];v.systemKeys.includes(A)||v.systemKeys.includes(B)||T&&T.length>0&&!T.includes(B)&&!T.includes(A)||(B.includes(".")?E[B]=z.optional():E[B]=z);}return E},h=null,y=o(v.createFields);Object.keys(y).length>0&&(m[l]=ue(zod.z.object(y)),h=l);let x=null,S=o(v.mutableFields);Object.keys(S).length>0&&(m[i]=ue(zod.z.object(S)),x=i);let u=`${j}BatchCreateOperation`,R=`${j}BatchUpdateOperation`,O=`${j}BatchDeleteOperation`;m[u]={type:"object",title:`${j} Create Operation`,properties:{type:{type:"string",enum:["create"],const:"create"},data:N(h??j)},required:["type","data"]},m[R]={type:"object",title:`${j} Update Operation`,properties:{type:{type:"string",enum:["update"],const:"update"},id:{type:"string"},data:{allOf:[N(x??j)],description:"Partial updates allowed"}},required:["type","id","data"]},v.allowDelete&&(m[O]={type:"object",title:`${j} Delete Operation`,properties:{type:{type:"string",enum:["delete"],const:"delete"},id:{type:"string"}},required:["type","id"]}),m[`${j}BatchRequest`]={type:"object",properties:{operations:{type:"array",items:{oneOf:[N(u),N(R),...v.allowDelete?[N(O)]:[]],discriminator:{propertyName:"type"}}}},required:["operations"]};let q=$t(v,p,j,h,x,f);Object.assign(b,q),g.push({name:k,description:`Operations on ${k} (collection: ${v.path})`});}let C={},I;return c==="basic"?(C.basicAuth={type:"http",scheme:"basic"},I=[{basicAuth:[]}]):c==="bearer"&&(C.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},I=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:s,version:r,...d?{description:d}:{}},...a&&a.length>0?{servers:a}:{},paths:b,components:{schemas:m,...Object.keys(C).length>0?{securitySchemes:C}:{}},...I?{security:I}:{},tags:g}}function K(e){return e.charAt(0).toUpperCase()+e.slice(1)}function U(e){return e.endsWith("ies")?e.slice(0,-3)+"y":e.endsWith("ses")||e.endsWith("xes")||e.endsWith("zes")?e.slice(0,-2):e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e}var Q=class extends Error{constructor(n,s){super("Request validation failed");this.zodError=n;this.source=s;this.statusCode=400;this.name="ValidationError";}};var ee=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},te=class extends Error{constructor(n){super("Output validation failed");this.zodError=n;this.statusCode=500;this.name="OutputValidationError";}};function Ke(e){return e.issues.map(t=>({path:t.path.join("."),code:t.code,message:t.message}))}function We(e,t){return t instanceof Q?e.json({success:false,error:"Validation failed",issues:Ke(t.zodError)},400):t instanceof ee?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof te?e.json({success:false,error:"Output validation failed",issues:Ke(t.zodError)},500):null}zodToOpenapi.extendZodWithOpenApi(zod.z);var Ge="Successful response",Ve="Error response";function Mt(e){return e==="get"?"query":"json"}function Bt(e,t){let n=t?.output;return n?typeof n=="function"?n(e):n:e}function Ut(e){if(typeof e.safeParse=="function")return {description:Ve,schema:e};let t=e;return {description:t.description??Ve,schema:t.schema}}function Qe(e,t,n,s){let r=new zodToOpenapi.OpenAPIRegistry;if(n.securitySchemes)for(let[c,p]of Object.entries(n.securitySchemes))r.registerComponent("securitySchemes",c,p);for(let c of e){let p=c.method,m=c.source??Mt(p),b=Wt(t,c.path??"/"),g=c.status??200,C=Lt(p,m,c.input),I=Je(m,c.input,"query"),$=Je(m,c.input,"param"),k=Gt(p,b),v=Bt(c.output,s),j={[g]:v?{description:Ge,content:{"application/json":{schema:v}}}:{description:Ge}};if(s?.errors)for(let[l,i]of Object.entries(s.errors)){let{description:f,schema:o}=Ut(i);j[l]=o?{description:f,content:{"application/json":{schema:o}}}:{description:f};}r.registerPath({method:p,path:Kt(b),operationId:k,summary:c.summary,description:c.description,tags:c.tags,deprecated:c.deprecated,security:c.security,request:{...I?{query:I}:{},...$?{params:$}:{},...C?{body:C}:{}},responses:j});}return new zodToOpenapi.OpenApiGeneratorV31(r.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security})}function Lt(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 Je(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function Kt(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function Wt(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,s=t.startsWith("/")?t:`/${t}`,r=`${n}${s}`;return r===""?"/":r}function Gt(e,t){let n=t.replace(/[{}]/g,"").replace(/\/+/g,"_").replace(/[^A-Za-z0-9_]/g,"").replace(/^_+|_+$/g,"");return `${e}_${n||"root"}`}function Xe(e,t){let n=e.replace(/"/g,""");return `<!doctype html>
|
|
1
|
+
'use strict';var crypto=require('crypto'),zod=require('zod'),firestore=require('firebase-admin/firestore'),zodToOpenapi=require('@asteasolutions/zod-to-openapi'),hono=require('hono'),nodeServer=require('@hono/node-server'),async_hooks=require('async_hooks');var me=Object.defineProperty;var ut=Object.getOwnPropertyDescriptor;var pt=Object.getOwnPropertyNames;var lt=Object.prototype.hasOwnProperty;var ft=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var yt=(e,t)=>{for(var n in t)me(e,n,{get:t[n],enumerable:true});},mt=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of pt(t))!lt.call(e,r)&&r!==n&&me(e,r,{get:()=>t[r],enumerable:!(o=ut(t,r))||o.enumerable});return e};var ht=e=>mt(me({},"__esModule",{value:true}),e);var at={};yt(at,{DEFAULT_HTML_CSP:()=>it,securityHeaders:()=>cn});function cn(e={}){let t=e.csp===void 0?it:e.csp,n=e.frameOptions===void 0?"DENY":e.frameOptions,o=e.referrerPolicy===void 0?"no-referrer":e.referrerPolicy,r=e.cacheControl===void 0?"private, no-store":e.cacheControl;return async(c,a,d)=>{typeof a?.setHeader=="function"&&(a.setHeader("X-Content-Type-Options","nosniff"),n&&a.setHeader("X-Frame-Options",n),o&&a.setHeader("Referrer-Policy",o),r&&a.setHeader("Cache-Control",r),t&&a.setHeader("Content-Security-Policy",t)),await d();}}var ot,st,it,ct=ft(()=>{"use strict";ot="https://cdn.jsdelivr.net",st="https://www.gstatic.com",it=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${ot} ${st}`,`style-src 'self' 'unsafe-inline' ${ot}`,`connect-src 'self' ${st} 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 Ie="preserve";function ge(){return Ie}function gt(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function Pe(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(gt(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 De(e){return e}function je(e){let t=e;if(t._zod?.def?.element)return t._zod.def.element;if(t._def?.type)return t._def.type}var bt=new Set(["<","<=",">",">=","!="]),xt=new Set(["array-contains","array-contains-any"]);function we(e){return e==="desc"?"DESCENDING":"ASCENDING"}function St(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function Rt(e,t,n,o,r){let c=[],a=new Set;for(let p of o)if(p.op==="=="||p.op==="in"||p.op==="not-in"){if(a.has(p.field))continue;a.add(p.field),c.push({fieldPath:p.field,order:"ASCENDING"});}for(let p of o)if(xt.has(p.op)){if(a.has(p.field))continue;a.add(p.field),c.push({fieldPath:p.field,arrayConfig:"CONTAINS"});}for(let p of o)if(bt.has(p.op)){if(a.has(p.field))continue;a.add(p.field);let f=r?.field===p.field?we(r.dir):"ASCENDING";c.push({fieldPath:p.field,order:f});}if(r&&!a.has(r.field)&&c.push({fieldPath:r.field,order:we(r.dir)}),c.length===1&&n)return kt(e,t,c[0]);let d=r&&c.some(p=>p.fieldPath===r.field)?we(r.dir):"ASCENDING";return c.push({fieldPath:"__name__",order:d}),Tt(e,t,n,c)}function Tt(e,t,n,o,r="(default)"){let c=`projects/${e}/databases/${r}/collectionGroups/${t}/indexes/_`,a=[...Se(1,c),...ie(2,n?2:1)];for(let f of o)a.push(...ze(3,_e(f)));let d=r==="(default)"?"-default-":r,p=encodeURIComponent(qe(a));return `https://console.firebase.google.com/project/${e}/firestore/databases/${d}/indexes?create_composite=${p}`}function At(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function be(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function xe(e,t){return e<<3|t}function Se(e,t){let n=Array.from(new TextEncoder().encode(t));return [xe(e,2),...be(n.length),...n]}function ie(e,t){return [xe(e,0),...be(t)]}function ze(e,t){return [xe(e,2),...be(t.length),...t]}function _e(e){let t=[...Se(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...ie(3,1)):t.push(...ie(2,e.order==="DESCENDING"?2:1)),t}function qe(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 kt(e,t,n,o="(default)"){let r=`projects/${e}/databases/${o}/collectionGroups/${t}/fields/${n.fieldPath}`,c=[...Se(1,r),...ie(2,2),...ze(3,_e(n))],a=o==="(default)"?"-default-":o,d=encodeURIComponent(qe(c));return `https://console.firebase.google.com/project/${e}/firestore/databases/${a}/indexes/automatic?create_exemption=${d}`}function vt(e){let t=e,n=[t?.firestore?.projectId,t?.firestore?.app?.options?.projectId,t?.firestore?._settings?.projectId,t?.firestore?.databaseId?.projectId,t?._firestore?.projectId];for(let r of n)if(typeof r=="string"&&r.length>0)return r;return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.FIREBASE_PROJECT_ID||void 0}function Ot(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function Ne(e,t){let n=e??{},o=Ot(e),r;if(o&&(r=n.message?At(n.message):void 0,!r)){let c=vt(t.ref);if(c){let a=St(t.path);r=Rt(c,a,t.isGroup,t.filters,t.sort);}}return {type:o?"index":"error",message:o?"This query requires a composite index that does not exist yet.":n.message??"Query failed",indexUrl:r}}function ce(e,t,n=new WeakMap){if(e===t)return true;if(e===null||t===null||e===void 0||t===void 0)return e===t;if(e instanceof firestore.Timestamp&&t instanceof firestore.Timestamp)return e.isEqual(t);if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return false;if(n.get(e)===t)return true;n.set(e,t);for(let o=0;o<e.length;o++)if(!ce(e[o],t[o],n))return false;return true}if(typeof e=="object"&&typeof t=="object"){if(e instanceof Date||t instanceof Date||e instanceof firestore.Timestamp||t instanceof firestore.Timestamp)return false;if(n.get(e)===t)return true;n.set(e,t);let o=Object.keys(e),r=Object.keys(t);if(o.length!==r.length)return false;for(let c of o)if(!Object.prototype.hasOwnProperty.call(t,c)||!ce(e[c],t[c],n))return false;return true}return false}function de(e,t){let n=e||{},o={},r={...n};for(let[c,a]of Object.entries(t||{})){let d=n[c];ce(d,a)||(o[c]=a,r[c]=a);}return {before:n,after:r,changes:o}}function Ct(e){return e}async function Ze(e,t,n){let o=e.changes||{};for(let r of Object.keys(o)){let c=t[r];if(c&&c.length>0){for(let a of c)if(await a.rule({diff:e,key:r,user:n,authenticatedUser:n})===false)return {allowed:false,reason:a.description}}}return {allowed:true}}function Et(e){return async t=>Ze(t.diff,e,t.user)}function ke(e,t,n=200){let o=De(t);return e.json(o,n)}function W(e,t,n,o=200){return ke(e,{success:true,data:t,meta:n},o)}function w(e,t,n=400){return ke(e,{success:false,error:t},n)}async function Re(e,t,n,o,r,c){let a=Ne(t,n),d=a.type==="index",p=d?424:500,b={success:false,error:d?a.message:r&&t instanceof Error?t.message:o};if(d&&(b.errorType="index",a.indexUrl&&(b.indexUrl=a.indexUrl,c)))try{let g=c({indexUrl:a.indexUrl,repoName:n.repoName??"",path:n.path,isGroup:n.isGroup,filters:n.filters,sort:n.sort,error:t,c:e});g instanceof Promise&&await g;}catch(g){r&&console.error("[crudServer] Error in indexesError callback:",g);}return ke(e,b,p)}var Te="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function $e(){let e="";for(;e.length<20;){let t=crypto.randomBytes(20);for(let n=0;n<t.length&&e.length<20;n++){let o=t[n];o>=Te.length*4||(e+=Te.charAt(o%Te.length));}}return e}function G(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(o=>Pe(o)??o,e);if(n==="ZodObject"||n==="object"){let o=e.shape,r={};for(let[c,a]of Object.entries(o))r[c]=G(a);return zod.z.object(r)}if(n==="ZodArray"||n==="array"){let o=t.element??t.type;if(o)return zod.z.array(G(o))}if(n==="ZodOptional"||n==="optional"){let o=t.innerType;if(o)return G(o).optional()}if(n==="ZodNullable"||n==="nullable"){let o=t.innerType;if(o)return G(o).nullable()}if(n==="ZodDefault"||n==="default"){let o=t.innerType,r=t.defaultValue;if(o){let c=G(o);return typeof r=="function"?c.default(r()):c.default(r)}}return e}function Pt(e,t,n=[]){let o=e.shape,r={},c=t&&t.length>0?t:Object.keys(o);for(let a of c){if(n.includes(a))continue;let d=a.split(".")[0];d&&o[d]&&(r[d]=o[d]);}return zod.z.object(r)}function Ae(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 Me(e,t){let n=t.split("."),o=Ae(e);for(let r=0;r<n.length;r++){let c=n[r];if(!c)continue;let a=o?.shape;if(!a||!a[c])return;let d=a[c];if(r===n.length-1)return d;o=Ae(d);}return o}function V(e){let t=e?._zod?.def??e?._def,n=t?.typeName??t?.type;if(n==="ZodObject"||n==="object"){let o=e.shape,r={};for(let[c,a]of Object.entries(o))r[c]=V(a);return zod.z.object(r).partial()}if(n==="ZodOptional"||n==="optional"){let o=t.innerType;if(!o)return e;let r=V(o);return r===o?e:r.optional()}if(n==="ZodNullable"||n==="nullable"){let o=t.innerType;if(!o)return e;let r=V(o);return r===o?e:r.nullable()}if(n==="ZodDefault"||n==="default"){let o=t.innerType;return o?V(o).optional():e}if(n==="ZodUnion"||n==="union"){let o=t.options;if(!o||o.length<2)return e;let r=o.map(a=>V(a));return r.some((a,d)=>a!==o[d])?zod.z.union(r):e}return e}function ue(e,t,n,o=false,r=[]){if(typeof t!="object"||t===null||Array.isArray(t))return {success:false,error:"Data payload must be an object"};try{let c=t,a={},d={};for(let[p,f]of Object.entries(c))if(p.includes(".")){let b=p.split(".")[0];if(r.includes(p)||r.includes(b))continue;if(n&&n.length>0&&!n.includes(p)&&!n.includes(b))return {success:!1,error:`Field '${p}' is not allowed for this operation`};let g=Me(e,p);if(!g)return {success:!1,error:`Field '${p}' does not exist in schema`};let R=o?V(g):g,Z=(ge()==="normalize"?G(R):R).parse(f);a[p]=Z;}else d[p]=f;if(Object.keys(d).length>0||Object.keys(a).length===0){let p=Pt(e,n,r),f=o?V(p):p,g=(ge()==="normalize"?G(f):f).parse(d);Object.assign(a,g);}return {success:!0,data:a}}catch(c){return c instanceof zod.z.ZodError?{success:false,error:`Validation failed: ${c.issues.map(d=>`${d.path.join(".")}: ${d.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}var Be={eq:"==","==":"==",ne:"!=","!=":"!=",lt:"<","<":"<",lte:"<=","<=":"<=",gt:">",">":">",gte:">=",">=":">=",in:"in",nin:"not-in","not-in":"not-in",not_in:"not-in",contains:"array-contains","array-contains":"array-contains",array_contains:"array-contains",arrayContains:"array-contains",containsAny:"array-contains-any","array-contains-any":"array-contains-any",array_contains_any:"array-contains-any",arrayContainsAny:"array-contains-any"};function te(e){return Be[e]??e}function Dt(e){return e in Be}function pe(e,t,n,o){let r=Me(e,t);if(!r||typeof r.safeParse!="function")return {success:true,data:n};let c=o?te(o):void 0,a=Ae(r),d=je(a);if(c==="array-contains"){let b=d??r;if(typeof b.safeParse=="function"){let g=b.safeParse(n);return g.success?{success:true,data:g.data}:{success:false,error:g.error.issues.map(j=>j.message).join(", ")}}return {success:true,data:n}}if(c==="array-contains-any"){if(!Array.isArray(n))return {success:false,error:"Expected array value for array-contains-any"};let b=d??r,g=[];for(let R of n)if(typeof b.safeParse=="function"){let j=b.safeParse(R);if(j.success)g.push(j.data);else return {success:false,error:j.error.issues.map(O=>O.message).join(", ")}}else g.push(R);return {success:true,data:g}}let p=r.safeParse(n);if(p.success)return {success:true,data:p.data};if(Array.isArray(n)){let b=d??r,g=[];for(let R of n)if(typeof b.safeParse=="function"){let j=b.safeParse(R);if(j.success)g.push(j.data);else return {success:false,error:j.error.issues.map(O=>O.message).join(", ")}}else g.push(R);return {success:true,data:g}}return {success:false,error:p.error.issues.map(b=>b.message).join(", ")}}function jt(e,t){let n=[],o=t?new Set(t):null;for(let[r,c]of Object.entries(e)){if(c===void 0||["cursor","direction","limit","pageSize","orderBy","orderDir","select","includes","withTotal"].includes(r))continue;let a=Array.isArray(c)?c[0]:c;if(a===void 0||a==="")continue;let d=r.lastIndexOf("__"),p,f="==";if(d!==-1){let g=r.slice(0,d),R=r.slice(d+2);Dt(R)?(p=g,f=te(R)):(p=r,f="==");}else p=r;if(o&&!o.has(p))continue;let b=a;f==="in"||f==="not-in"||f==="array-contains-any"?b=a.split(",").map(g=>Fe(g.trim())):b=Fe(a),n.push({field:p,op:f,value:b});}return n}function Fe(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 le(e){return e?{docId:e.id,docPath:e.ref?.path??void 0}:null}async function He(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 o=typeof n.docPath=="string"?n.docPath:void 0,r=typeof n.docId=="string"?n.docId:void 0;try{let c=e.repo.ref,a=c?.firestore;if(o&&a&&typeof a.doc=="function"){let d=await a.doc(o).get();if(d.exists)return d}if(r&&r.includes("/")&&a&&typeof a.doc=="function"){let d=await a.doc(r).get();if(d.exists)return d}if(r&&typeof c.doc=="function"){let d=await c.doc(r).get();if(d.exists)return d}return}catch{return}}function Ue(e,t,n,o){async function r(l,i,y,s){if(!i.rules)return {allowed:true};let h=i.rules?.[y];if(!h)return {allowed:false,errorResponse:w(l,`Operation "${y}" is not allowed for this repository`,403)};try{let m=await h(s);return m===!1?{allowed:!1,errorResponse:w(l,"Forbidden",403)}:typeof m=="string"?{allowed:!1,errorResponse:w(l,m,403)}:typeof m=="object"&&m!==null&&!m.allowed?{allowed:!1,errorResponse:w(l,m.reason||"Forbidden",403)}:{allowed:!0}}catch(m){let x=n&&m instanceof Error?m.message:"Forbidden";return {allowed:false,errorResponse:w(l,x,403)}}}async function c(l,i,y,s){if(!l.rules)return s;let h=l.rules?.filter;if(!h)return s;let m=[];for(let x of s)try{await h({user:i,doc:x,params:y})&&m.push(x);}catch{}return m}function a(l){return l.get("user")??l.get("docsUser")??null}function d(l,i){if(!l){let y=i.req.path.split("/");for(let s of y)if(e[s]){l=s;break}}return !l||!e[l]?null:e[l]??null}function p(l,i){if(!i)return;let y=l[i];if(typeof y!="string"||!y)return;let s=y.split("/").filter(Boolean),h=[];for(let m=1;m<s.length;m+=2)h.push(s[m]);return h.length>0?h:void 0}async function f(l,i){let y=`by${l.documentKey.charAt(0).toUpperCase()}${l.documentKey.slice(1)}`,s=l.repo.get[y];if(typeof s=="function")try{let m=await s(i);if(m)return m}catch{}return (await l.repo.query.by({where:[[l.documentKey,"==",i]],limit:1}))[0]??null}async function b(l){let i=l.c,y=i.req.param(),s=d(y.repoName,i);if(!s)return w(i,"Repository not found",404);let h=a(i),m=await r(i,s,"list",{user:h,query:i.req.query(),params:y});if(!m.allowed)return m.errorResponse;let x=[],A;try{let u=i.req.query(),S=Math.min(Number(u.pageSize)||s.pageSize,100),C=u.cursor,q=u.direction?.toLowerCase()==="prev"?"prev":"next",k=u.orderBy,z=u.orderDir?.toLowerCase()==="desc"?"desc":"asc",N=u.select,U=N?N.split(",").map(H=>H.trim()):void 0,_=u.withTotal,T=_==="true"||_==="1"||_===!0,I;s.allowedIncludes&&u.includes&&(I=(typeof u.includes=="string"?u.includes.split(",").map(L=>L.trim()):Array.isArray(u.includes)?u.includes:[]).filter(L=>typeof L=="string"&&s.allowedIncludes.includes(L)),I?.length===0&&(I=void 0));let E=jt(u,s.filterableFields);x=E.map(H=>({field:H.field,op:H.op,value:String(H.value??"")})),k&&(A={field:k,dir:z});let M={pageSize:S,direction:q,...T?{withTotal:!0}:{}};if(C)try{let H=typeof C=="string"?JSON.parse(C):C;M.cursor=await He(s,H);}catch{}if(k){if(s.orderableFields&&!s.orderableFields.includes(k))return w(i,`Field not orderable: ${k}`,400);M.orderBy=[{field:k,direction:z}];}if(E.length>0){M.where=[];for(let H of E){let L=pe(s.schema,H.field,H.value,H.op);if(!L.success)return w(i,`Invalid filter value for '${H.field}': ${L.error}`,400);M.where.push([H.field,H.op,L.data]);}}U&&(M.select=U),I&&(M.include=I);let $=await s.repo.query.paginate(M),dt={items:await c(s,a(i),y,$.data),hasNextPage:$.hasNextPage,hasPrevPage:$.hasPrevPage,nextCursor:le($.nextCursor),prevCursor:le($.prevCursor),...$.totalCount!==void 0?{totalCount:$.totalCount,totalCountIsExact:$.totalCountIsExact}:{}};return W(i,dt,{pageSize:S,hasMore:$.hasNextPage,...$.totalCount!==void 0?{totalCount:$.totalCount,totalCountIsExact:$.totalCountIsExact}:{}})}catch(u){return await Re(i,u,{repoName:y.repoName||s.name,ref:s.repo.ref,path:s.path,isGroup:!!s.isGroup,filters:x,sort:A},"Failed to fetch documents",n,o)}}async function g(l){let i=l.c,y=i.req.param(),s=d(y.repoName,i);if(!s)return w(i,"Repository not found",404);let h=a(i),m=await r(i,s,"list",{user:h,query:l.input||{},params:y});if(!m.allowed)return m.errorResponse;let x=[],A;try{let u=l.input||{},S=Math.min(u.pageSize||s.pageSize,100),C=u.direction==="prev"?"prev":"next";u.where&&(x=u.where.map(_=>({field:String(_[0]),op:_[1],value:String(_[2]??"")}))),u.orderBy&&u.orderBy[0]&&(A={field:u.orderBy[0].field,dir:u.orderBy[0].direction==="desc"?"desc":"asc"});let q=u.withTotal===!0||String(u.withTotal)==="true",k={pageSize:S,direction:C,...q?{withTotal:!0}:{}};if(u.cursor)try{let _=typeof u.cursor=="string"?JSON.parse(u.cursor):u.cursor;k.cursor=await He(s,_);}catch{}if(s.allowedIncludes&&u.includes&&u.includes.length>0){let _=u.includes.filter(T=>typeof T=="string"?s.allowedIncludes.includes(T):typeof T=="object"&&T!==null&&"relation"in T&&typeof T.relation=="string"?s.allowedIncludes.includes(T.relation):!1);_.length>0&&(k.include=_);}if(u.where&&u.where.length>0){if(s.filterableFields){let T=new Set(s.filterableFields),I=u.where.filter(E=>!T.has(E[0]));if(I.length>0){w(i,`Fields not filterable: ${I.map(E=>E[0]).join(", ")}`,400);return}}let _=[];for(let T of u.where){let I=te(T[1]),E=pe(s.schema,T[0],T[2],I);if(!E.success){w(i,`Invalid filter value for '${T[0]}': ${E.error}`,400);return}_.push([T[0],I,E.data]);}k.where=_;}if(u.orWhere&&u.orWhere.length>0){if(s.filterableFields){let T=new Set(s.filterableFields),I=u.orWhere.filter(E=>!T.has(E[0]));if(I.length>0){w(i,`Fields not filterable: ${I.map(E=>E[0]).join(", ")}`,400);return}}let _=[];for(let T of u.orWhere){let I=te(T[1]),E=pe(s.schema,T[0],T[2],I);if(!E.success){w(i,`Invalid filter value for '${T[0]}': ${E.error}`,400);return}_.push([T[0],I,E.data]);}k.orWhere=_;}if(u.orWhereGroups&&u.orWhereGroups.length>0){if(s.filterableFields){let T=new Set(s.filterableFields);for(let I of u.orWhereGroups){let E=I.filter(M=>!T.has(M[0]));if(E.length>0){w(i,`Fields not filterable: ${E.map(M=>M[0]).join(", ")}`,400);return}}}let _=[];for(let T of u.orWhereGroups){let I=[];for(let E of T){let M=te(E[1]),$=pe(s.schema,E[0],E[2],M);if(!$.success){w(i,`Invalid filter value for '${E[0]}': ${$.error}`,400);return}I.push([E[0],M,$.data]);}_.push(I);}k.orWhereGroups=_;}if(u.orderBy&&u.orderBy.length>0){if(s.orderableFields){let _=new Set(s.orderableFields),T=u.orderBy.filter(I=>!_.has(I.field));if(T.length>0){w(i,`Fields not orderable: ${T.map(I=>I.field).join(", ")}`,400);return}}k.orderBy=u.orderBy;}u.select&&u.select.length>0&&(k.select=u.select);let z=await s.repo.query.paginate(k),U={items:await c(s,a(i),y,z.data),hasNextPage:z.hasNextPage,hasPrevPage:z.hasPrevPage,nextCursor:le(z.nextCursor),prevCursor:le(z.prevCursor),...z.totalCount!==void 0?{totalCount:z.totalCount,totalCountIsExact:z.totalCountIsExact}:{}};return W(i,U,{pageSize:S,hasMore:z.hasNextPage,...z.totalCount!==void 0?{totalCount:z.totalCount,totalCountIsExact:z.totalCountIsExact}:{}})}catch(u){return await Re(i,u,{repoName:y.repoName||s.name,ref:s.repo.ref,path:s.path,isGroup:!!s.isGroup,filters:x,sort:A},"Failed to query documents",n,o)}}async function R(l){let i=l.c,y=i.req.param(),s=d(y.repoName,i);if(!s)return w(i,"Repository not found",404);let h=y.id;if(!h)return w(i,"Document ID required",400);try{let m=await f(s,h);if(!m)return w(i,"Document not found",404);let x=a(i),A=await r(i,s,"get",{user:x,doc:m,params:y});if(!A.allowed)return A.errorResponse;if(s.rules?.filter)try{if(!await s.rules.filter({user:x,doc:m,params:y}))return w(i,"Document not found",404)}catch{return w(i,"Document not found",404)}return W(i,m)}catch(m){return await Re(i,m,{repoName:y.repoName||s.name,ref:s.repo.ref,path:s.path,isGroup:!!s.isGroup,filters:[{field:s.documentKey,op:"==",value:h}]},"Failed to fetch document",n,o)}}async function j(l){let i=l.c,y=i.req.param(),s=d(y.repoName,i);if(!s)return w(i,"Repository not found",404);try{let h=l.input||{},m=a(i),x=await r(i,s,"create",{user:m,body:h,params:y});if(!x.allowed)return x.errorResponse;let A=ue(s.schema,h,s.createFields,!1,s.systemKeys);if(!A.success)return w(i,A.error,400);if(s.validate){let S=await s.validate(A.data,"create");if(S)return w(i,S,400)}let u;if(s.isGroup&&s.parentKeys&&s.parentKeys.length>0){let S={...A.data};s.createdKey&&(S[s.createdKey]=new Date);let C=s.parentKeys.filter(z=>!S[z]);if(C.length>0){w(i,`Missing parent key(s) for subcollection create: ${C.join(", ")}`,400);return}let q=s.parentKeys.map(z=>S[z]),k=S[s.documentKey]||$e();u=await s.repo.set(...q,k,S);}else u=await s.repo.create(A.data);return W(i,u,void 0,201)}catch(h){let m=n&&h instanceof Error?h.message:"Failed to create document";return w(i,m,500)}}async function Z(l,i){let y=l.c,s=y.req.param(),h=d(s.repoName,y);if(!h)return w(y,"Repository not found",404);let m=s.id;if(!m)return w(y,"Document ID required",400);try{let x=l.input||{},A=await f(h,m);if(!A)return w(y,"Document not found",404);let u=ue(h.schema,x,h.mutableFields,i,h.systemKeys);if(!u.success)return w(y,u.error,400);if(h.validate){let N=await h.validate(u.data,"update");if(N)return w(y,N,400)}let S=de(A,u.data),C=a(y),q=await r(y,h,"update",{user:C,doc:A,body:u.data,diff:S,params:s});if(!q.allowed)return q.errorResponse;let k=p(A,h.pathKey)??[m],z=await h.repo.update(...k,u.data);return W(y,z)}catch(x){let A=n&&x instanceof Error?x.message:"Failed to update document";return w(y,A,500)}}async function O(l){let i=l.c,y=i.req.param(),s=d(y.repoName,i);if(!s)return w(i,"Repository not found",404);if(!s.allowDelete)return w(i,"Delete not allowed for this repository",403);let h=y.id;if(!h)return w(i,"Document ID required",400);try{let m=await f(s,h);if(!m)return w(i,"Document not found",404);let x=a(i),A=await r(i,s,"delete",{user:x,doc:m,params:y});if(!A.allowed)return A.errorResponse;let u=p(m,s.pathKey)??[h];return await s.repo.delete(...u),W(i,{deleted:!0})}catch(m){let x=n&&m instanceof Error?m.message:"Failed to delete document";return w(i,x,500)}}function v(l){return l.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 P(l){let i=l.c,y=i.req.param(),s=d(y.repoName,i);if(!s)return w(i,"Repository not found",404);try{let h=l.input||{};if(!Array.isArray(h.operations))return w(i,"operations array is required",400);let m=a(i),x=s.repo.batch.create(),A=[];for(let u of h.operations){if(!u.type||!["create","update","delete"].includes(u.type))return w(i,"Invalid operation type",400);if(u.type==="create"){let S=await r(i,s,"create",{user:m,body:u.data,params:y});if(!S.allowed)return S.errorResponse;let C=ue(s.schema,u.data,s.createFields,!1,s.systemKeys);if(!C.success)return w(i,C.error,400);let q=u.data[s.documentKey]||$e(),k={...C.data};if(s.createdKey&&(k[s.createdKey]=new Date),s.isGroup&&s.parentKeys){let z=s.parentKeys.map(N=>k[N]);x.set(...z,q,k);}else x.set(q,k);A.push({op:"create",id:q});}else if(u.type==="update"){if(!u.id)return w(i,"id required for update",400);let S=await f(s,u.id);if(!S)return w(i,`Document ${u.id} not found`,404);let C=ue(s.schema,u.data,s.mutableFields,!0,s.systemKeys);if(!C.success)return w(i,C.error,400);if(s.validate){let N=await s.validate(C.data,"update");if(N)return w(i,N,400)}let q=de(S,C.data),k=await r(i,s,"update",{user:m,doc:S,body:C.data,diff:q,params:y});if(!k.allowed)return k.errorResponse;let z=p(S,s.pathKey)??[u.id];x.update(...z,C.data),A.push({op:"update",id:u.id});}else if(u.type==="delete"){if(!s.allowDelete)return w(i,"Delete not allowed",403);if(!u.id)return w(i,"id required for delete",400);let S=await f(s,u.id);if(!S)return w(i,`Document ${u.id} not found`,404);let C=await r(i,s,"delete",{user:m,doc:S,params:y});if(!C.allowed)return C.errorResponse;let q=p(S,s.pathKey)??[u.id];x.delete(...q),A.push({op:"delete",id:u.id});}}return await x.commit(),W(i,{results:A})}catch(h){let m=n&&h instanceof Error?h.message:"Batch operation failed";return w(i,m,500)}}return {handleList:b,handleQuery:g,handleGet:R,handleCreate:j,handleUpdate:Z,handleDelete:O,handleBatch:P,handleOptions:v}}function Y(e){try{return zod.z.toJSONSchema(e,{target:"openapi-3.1",unrepresentable:"any",override:t=>{let n=zodToOpenapi.getOpenApiMetadata(t.zodSchema);n&&(Object.assign(t.jsonSchema,n),(t.jsonSchema.anyOf||t.jsonSchema.oneOf)&&delete t.jsonSchema.type);let o=t.zodSchema?._zod?.def;o&&(o.type==="date"&&!t.jsonSchema.type&&!t.jsonSchema.anyOf?(t.jsonSchema.type="string",t.jsonSchema.format="date-time"):o.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 F(e){return {$ref:`#/components/schemas/${e}`}}function D(e){return {description:e,content:{"application/json":{schema:F("ErrorResponse")}}}}function X(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function zt(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 re(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 _t(e,t){let n=t.split("."),o=re(e);for(let r=0;r<n.length;r++){let c=n[r];if(!c)continue;let a=o?.shape;if(!a||!a[c])return;let d=a[c];if(r===n.length-1)return d;o=re(d);}return o}function Q(e){let t=e?._zod?.def??e?._def,n=t?.typeName??t?.type,o=r=>{let c=zodToOpenapi.getOpenApiMetadata(e);return c&&typeof r.openapi=="function"?r.openapi(c):r};if(n==="ZodObject"||n==="object"){let r=e.shape,c={};for(let[a,d]of Object.entries(r))c[a]=Q(d);return o(zod.z.object(c).partial())}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(!r)return e;let c=Q(r);return c===r?e:o(c.optional())}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(!r)return e;let c=Q(r);return c===r?e:o(c.nullable())}if(n==="ZodDefault"||n==="default"){let r=t.innerType;return r?o(Q(r).optional()):e}if(n==="ZodUnion"||n==="union"){let r=t.options;if(!r||r.length<2)return e;let c=r.map(d=>Q(d));return c.some((d,p)=>d!==r[p])?o(zod.z.union(c)):e}return e}function ve(e,t="",n=0){if(n>5)return [];let r=re(e)?.shape;if(!r)return [];let c=[];for(let[a,d]of Object.entries(r)){let p=t?`${t}.${a}`:a,f=re(d);f?.shape&&typeof f.shape=="object"?(c.push({path:p,zodSchema:d}),c.push(...ve(f,p,n+1))):c.push({path:p,zodSchema:d});}return c}function qt(e){return e.filterableFields&&e.filterableFields.length>0?e.filterableFields.map(t=>({path:t,zodSchema:_t(e.schema,t)})):ve(e.schema)}function Le(e){if(!e)return {type:"string"};let t=Y(e);return delete t.$schema,delete t.title,t}function We(){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 Nt(e){let t=qt(e),n=e.orderableFields??t.map(a=>a.path),o=t.map(a=>a.path);if(t.length===0)return We();let r=[];for(let{path:a,zodSchema:d}of t){let p=Le(d),f=re(d),g=f?._zod?.def?.type==="array"||f?._def?.typeName==="ZodArray"||f?._def?.type==="array"?Le(f?._zod?.def?.element??f?._def?.type??f?._def?.element):p;r.push({type:"array",description:`Condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["==","!=","<","<=",">",">=","eq","ne","lt","lte","gt","gte"]},p],minItems:3,maxItems:3}),r.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:p}],minItems:3,maxItems:3}),r.push({type:"array",description:`Array contains condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["array-contains","contains"]},g],minItems:3,maxItems:3}),r.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:g}],minItems:3,maxItems:3});}let c={oneOf:r};return {type:"object",properties:{where:{type:"array",items:c,description:"AND conditions: [field, operator, value][]"},orWhere:{type:"array",items:c,description:"Simple OR conditions (each independently OR'd)"},orWhereGroups:{type:"array",items:{type:"array",items:c},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:o},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 Zt(e,t,n,o,r,c=null,a="QueryRequestBody"){let d={},p=e.name,f=`${t}/${e.name}`,b=`${f}/{${e.documentKey}}`,g={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};d[f]={post:{operationId:`create${K(e.name)}`,summary:`Create a ${B(e.name)}`,tags:[p],requestBody:{required:true,content:{"application/json":{schema:F(o??n)}}},responses:{201:X("Document created",F(n)),400:D("Validation error"),403:D("Forbidden"),500:D("Internal server error")}}},d[`${f}/query`]={post:{operationId:`query${K(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[p],requestBody:{required:true,content:{"application/json":{schema:F(a)}}},responses:{200:zt(F(n)),400:D("Invalid query"),403:D("Forbidden"),424:D("Missing composite index (includes indexUrl in response)"),500:D("Internal server error")}}},d[`${f}/batch`]={post:{operationId:`batch${K(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[p],requestBody:{required:true,content:{"application/json":{schema:F(`${n}BatchRequest`)}}},responses:{200:X("Batch operations completed",{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{op:{type:"string"},id:{type:"string"}}}}}}),400:D("Validation error"),403:D("Forbidden"),404:D("Document not found"),500:D("Internal server error")}}};let R={};return R.get={operationId:`get${K(B(e.name))}`,summary:`Get a single ${B(e.name)}`,tags:[p],parameters:[g],responses:{200:X("Document found",F(n)),400:D("Document ID required"),403:D("Forbidden"),404:D("Document not found"),424:D("Missing composite index (includes indexUrl in response)"),500:D("Internal server error")}},R.put={operationId:`update${K(B(e.name))}`,summary:`Update a ${B(e.name)} (full replace)`,tags:[p],parameters:[g],requestBody:{required:true,content:{"application/json":{schema:F(r??n)}}},responses:{200:X("Document updated",F(n)),400:D("Validation error"),403:D("Forbidden"),404:D("Document not found"),500:D("Internal server error")}},R.patch={operationId:`patch${K(B(e.name))}`,summary:`Partially update a ${B(e.name)}`,tags:[p],parameters:[g],requestBody:{required:true,content:{"application/json":{schema:F(c??r??n)}}},responses:{200:X("Document patched",F(n)),400:D("Validation error"),403:D("Forbidden"),404:D("Document not found"),500:D("Internal server error")}},e.allowDelete&&(R.delete={operationId:`delete${K(B(e.name))}`,summary:`Delete a ${B(e.name)}`,tags:[p],parameters:[g],responses:{200:X("Document deleted",{type:"object",properties:{id:{type:"string"}}}),400:D("Document ID required"),403:D("Forbidden"),404:D("Document not found"),500:D("Internal server error")}}),d[b]=R,d}function Oe(e,t,n={}){let{title:o="CRUD API",version:r="1.0.0",description:c,servers:a,auth:d=false}=n,p=t==="/"?"":t.replace(/\/$/,""),f={},b={},g=[];f.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string",description:"Human-readable error description"},errorType:{type:"string",enum:["index"],description:"Error category discriminator. Set to 'index' when a Firestore composite index is missing."},indexUrl:{type:"string",format:"uri",description:"Direct Firebase Console URL to create the required composite index (when errorType is 'index')."}},required:["success","error"]},f.QueryRequestBody=We();for(let[O,v]of Object.entries(e)){let P=K(B(O)),l=`${P}Create`,i=`${P}Update`,y=`${P}Patch`,s=`${P}QueryRequestBody`;f[P]=Y(v.schema),f[s]=Nt(v);let h=N=>{let U={},_=ve(v.schema);for(let{path:T,zodSchema:I}of _){let E=T.split(".")[0];v.systemKeys.includes(E)||v.systemKeys.includes(T)||N&&N.length>0&&!N.includes(T)&&!N.includes(E)||(T.includes(".")?U[T]=I.optional():U[T]=I);}return U},m=null,x=h(v.createFields);Object.keys(x).length>0&&(f[l]=Y(zod.z.object(x)),m=l);let A=null,u=null,S=h(v.mutableFields);if(Object.keys(S).length>0){let N=zod.z.object(S);f[i]=Y(N),A=i,f[y]=Y(Q(N)),u=y;}else f[y]=Y(Q(v.schema)),u=y;let C=`${P}BatchCreateOperation`,q=`${P}BatchUpdateOperation`,k=`${P}BatchDeleteOperation`;f[C]={type:"object",title:`${P} Create Operation`,properties:{type:{type:"string",enum:["create"],const:"create"},data:F(m??P)},required:["type","data"]},f[q]={type:"object",title:`${P} Update Operation`,properties:{type:{type:"string",enum:["update"],const:"update"},id:{type:"string"},data:F(u??A??P)},required:["type","id","data"]},v.allowDelete&&(f[k]={type:"object",title:`${P} Delete Operation`,properties:{type:{type:"string",enum:["delete"],const:"delete"},id:{type:"string"}},required:["type","id"]}),f[`${P}BatchRequest`]={type:"object",properties:{operations:{type:"array",items:{oneOf:[F(C),F(q),...v.allowDelete?[F(k)]:[]],discriminator:{propertyName:"type"}}}},required:["operations"]};let z=Zt(v,p,P,m,A,u,s);Object.assign(b,z),g.push({name:O,description:`Operations on ${O} (collection: ${v.path})`});}let R={},j;return d==="basic"?(R.basicAuth={type:"http",scheme:"basic"},j=[{basicAuth:[]}]):d==="bearer"&&(R.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},j=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:o,version:r,...c?{description:c}:{}},...a&&a.length>0?{servers:a}:{},paths:b,components:{schemas:f,...Object.keys(R).length>0?{securitySchemes:R}:{}},...j?{security:j}:{},tags:g}}function K(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 ee=class extends Error{constructor(n,o){super("Request validation failed");this.zodError=n;this.source=o;this.statusCode=400;this.name="ValidationError";}};var oe=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},se=class extends Error{constructor(n){super("Output validation failed");this.zodError=n;this.statusCode=500;this.name="OutputValidationError";}};function Ge(e){return e.issues.map(t=>({path:t.path.join("."),code:t.code,message:t.message}))}function Ve(e,t){return t instanceof ee?e.json({success:false,error:"Validation failed",issues:Ge(t.zodError)},400):t instanceof oe?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof se?e.json({success:false,error:"Output validation failed",issues:Ge(t.zodError)},500):null}zodToOpenapi.extendZodWithOpenApi(zod.z);var Je="Successful response",Qe="Error response";function Bt(e){return e==="get"?"query":"json"}function Ut(e,t){let n=t?.output;return n?typeof n=="function"?n(e):n:e}function Lt(e){if(typeof e.safeParse=="function")return {description:Qe,schema:e};let t=e;return {description:t.description??Qe,schema:t.schema}}function Ye(e,t,n,o){let r=new zodToOpenapi.OpenAPIRegistry;if(n.securitySchemes)for(let[d,p]of Object.entries(n.securitySchemes))r.registerComponent("securitySchemes",d,p);for(let d of e){let p=d.method,f=d.source??Bt(p),b=Gt(t,d.path??"/"),g=d.status??200,R=Kt(p,f,d.input),j=Xe(f,d.input,"query"),Z=Xe(f,d.input,"param"),O=Vt(p,b),v=Ut(d.output,o),P={[g]:v?{description:Je,content:{"application/json":{schema:v}}}:{description:Je}};if(o?.errors)for(let[l,i]of Object.entries(o.errors)){let{description:y,schema:s}=Lt(i);P[l]=s?{description:y,content:{"application/json":{schema:s}}}:{description:y};}r.registerPath({method:p,path:Wt(b),operationId:O,summary:d.summary,description:d.description,tags:d.tags,deprecated:d.deprecated,security:d.security,request:{...j?{query:j}:{},...Z?{params:Z}:{},...R?{body:R}:{}},responses:P});}return new zodToOpenapi.OpenApiGeneratorV31(r.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security})}function Kt(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 Xe(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function Wt(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function Gt(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,o=t.startsWith("/")?t:`/${t}`,r=`${n}${o}`;return r===""?"/":r}function Vt(e,t){let n=t.replace(/[{}]/g,"").replace(/\/+/g,"_").replace(/[^A-Za-z0-9_]/g,"").replace(/^_+|_+$/g,"");return `${e}_${n||"root"}`}function et(e,t){let n=e.replace(/"/g,""");return `<!doctype html>
|
|
2
2
|
<html lang="en">
|
|
3
3
|
<head>
|
|
4
4
|
<meta charset="utf-8" />
|
|
@@ -9,5 +9,5 @@
|
|
|
9
9
|
<script id="api-reference" data-url="${n}"></script>
|
|
10
10
|
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
|
|
11
11
|
</body>
|
|
12
|
-
</html>`}function
|
|
12
|
+
</html>`}function tt(e){return typeof e=="object"&&e!==null&&e.__docsAuthExtension===true}var Ce=new async_hooks.AsyncLocalStorage;function nt(){return async(e,t)=>{await Ce.run({c:e},async()=>{await t();});}}var Yt=Object.freeze({}),ye=class{constructor(t){this.cachedSpec=null;this.options=t,this.app=new hono.Hono,this.mountedRoutes=nn(t.routes,t.api),t.services&&this.app.use("*",nt());let n=[...t.middlewares??[],...t.globalMiddlewares??[]];for(let o of n)this.app.use("*",o);this.mountRoutes(),this.mountOpenApi(),t.notFound&&this.app.notFound(t.notFound),t.onError&&this.app.onError(t.onError);}get hono(){return this.app}get nodeHandler(){return nodeServer.getRequestListener(this.app.fetch,{overrideGlobalObjects:false})}toFunction(t,n){let o=this.nodeHandler;return n?t(n,o):t(o)}buildOpenApiSpec(){if(this.cachedSpec)return this.cachedSpec;if(!this.options.openapi)throw new Error("[HonoServer] openapi config not set");return this.cachedSpec=Ye(this.mountedRoutes,this.options.basePath??"",this.options.openapi,tn(this.options.interceptor)),this.cachedSpec}mountRoutes(){let t=this.options.basePath??"",n=this.options.validateOutput??false,o=this.options.verbose??false;for(let r of this.mountedRoutes){if(!r.path)throw new Error(`[HonoServer] route "${r.method.toUpperCase()} (no path)" \u2014 missing \`path\`. Run the codegen so the path is derived from the file location, or set it explicitly.`);let c=fe(t,r.path),a=r.middlewares??[],d=r.source??(r.method==="get"?"query":"json"),p=sn(r,d,n,en(this.options.interceptor),this.options.services,this.options.errorHandler,this.options.logger),f=r.method.toUpperCase();this.app.on(f,[c],...a,p),o&&console.log(`[HonoServer] ${r.method.toUpperCase().padEnd(6)} ${c}`);}}mountOpenApi(){let t=this.options.openapi;if(!t)return;let n=t.path??"/openapi.json",o=t.docsPath===void 0?"/docs":t.docsPath,r=fe(this.options.basePath??"",n),c=o===false?null:fe(this.options.basePath??"",o),a;if(tt(t.docsAuth)){let d=t.docsAuth;a=[d.middleware];let p=rn(c??r);for(let f of d.routes)this.app.on(f.method,[fe(p,f.name)],f.handler);}else a=t.docsAuth?Array.isArray(t.docsAuth)?t.docsAuth:[t.docsAuth]:[];if(this.app.on("GET",[r],...a,d=>d.json(this.buildOpenApiSpec())),c){let d=on(c,r);this.app.on("GET",[c],...a,p=>p.html(et(d,t.info.title)));}}};function rt(e){return typeof e=="object"&&e!==null&&typeof e.handler=="function"}function en(e){if(e)return rt(e)?e.handler:e}function tn(e){return rt(e)?e:void 0}function nn(e,t){return t?e.filter(n=>Array.isArray(n.api)?n.api.includes(t):n.api===t):e.slice()}function fe(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,o=t.startsWith("/")?t:`/${t}`,r=`${n}${o}`;return r===""?"/":r}function rn(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function on(e,t){let n=e.split("/").filter(Boolean),o=t.split("/").filter(Boolean);n.pop();let r=0;for(;r<n.length&&r<o.length&&n[r]===o[r];)r++;let c=n.length-r;return [...Array(c).fill(".."),...o.slice(r)].join("/")||"./"}function sn(e,t,n,o,r,c,a){let d=e.input,p=e.output,f=e.status??200,b=r??Yt;return async g=>{let R=async O=>{if(c){let v=await c.handle({error:O,c:g,route:e,services:b,logger:a});if(v)return v}return Ve(g,O)},j=async()=>{let O,v;try{v=await an(g,t,e.method);}catch(l){throw new oe(l instanceof Error?l.message:String(l))}if(d){let l=d.safeParse(v);if(!l.success)throw new ee(l.error,t);O=l.data;}else O=v;let P=await e.handler({input:O,c:g,services:b,errorHandler:c,logger:a});if(n&&p&&!(P instanceof Response)){let l=p.safeParse(P);if(!l.success)throw new se(l.error);return l.data}return P},Z;if(o)try{Z=await o({next:j,route:e,c:g,services:b,errorHandler:c,logger:a});}catch(O){let v=await R(O);if(v)return v;throw O}else try{Z=await j();}catch(O){let v=await R(O);if(v)return v;throw O}return Z instanceof Response?Z:g.json(Z,f)}}async function an(e,t,n){switch(t){case "json":{if(n==="get")return e.req.query();let o=await e.req.text();if(!o)return {};try{return JSON.parse(o)}catch(r){throw new Error(`Invalid JSON body: ${r instanceof Error?r.message:String(r)}`)}}case "query":return e.req.query();case "form":return await e.req.parseBody();case "param":return e.req.param();default:return {}}}function nr(e){let{basePath:t="/",repos:n,parseBody:o=true,securityHeaders:r,verbose:c=false,httpsOptions:a}=e,d=t==="/"?"":t.replace(/\/$/,""),p={};for(let[l,i]of Object.entries(n)){if(!i.repo)throw new Error(`[createCrudServer] Repository "${l}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let y=i.schema??i.repo.schema??null;if(!y)throw new Error(`[createCrudServer] Repository "${l}" has no Zod schema.`);let s,h,m,x;if(i.fieldsConfig){let S=i.fieldsConfig;s=[],h=[],m=[],x=[];for(let[C,q]of Object.entries(S))for(let k of q)k==="filterable"?s.push(C):k==="orderable"?h.push(C):k==="mutable"?m.push(C):k==="create"&&x.push(C);h.length===0&&(h=s),s.length===0&&(s=void 0),h&&h.length===0&&(h=void 0),m.length===0&&(m=void 0),x.length===0&&(x=void 0);}let A=(()=>{let S=i.repo._parentKeys;return S&&S.length>0?S:void 0})();if(A&&x)for(let S of A)x.includes(S)||x.push(S);let u={name:l,path:i.path,repo:i.repo,schema:y,systemKeys:i.repo._systemKeys??[i.documentKey??"docId"],documentKey:i.documentKey??"docId",pathKey:i.repo._pathKey??void 0,isGroup:!!i.repo._isGroup,parentKeys:A,createdKey:i.repo._createdKey??void 0,pageSize:i.pageSize??25,filterableFields:s,orderableFields:h,mutableFields:m,createFields:x,allowDelete:i.allowDelete??false,allowedIncludes:i.allowedIncludes,validate:i.validate,rules:i.rules};p[l]=u;}let f=e.indexesError??e.onIndexError,b=Ue(p,d,c,f),g=e.openapi,R=g&&typeof g=="object"?g:{},j=null;function Z(){return j||(j=Oe(p,d,{...R,auth:R.auth??false})),j}let O=[];for(let l of Object.keys(p))O.push({api:"crud",method:"post",path:`/${l}/query`,source:"json",handler:b.handleQuery}),O.push({api:"crud",method:"get",path:`/${l}/:id`,source:"query",handler:b.handleGet}),O.push({api:"crud",method:"post",path:`/${l}`,source:"json",handler:b.handleCreate}),O.push({api:"crud",method:"put",path:`/${l}/:id`,source:"json",handler:i=>b.handleUpdate(i,false)}),O.push({api:"crud",method:"patch",path:`/${l}/:id`,source:"json",handler:i=>b.handleUpdate(i,true)}),O.push({api:"crud",method:"delete",path:`/${l}/:id`,source:"query",handler:b.handleDelete}),O.push({api:"crud",method:"post",path:`/${l}/batch`,source:"json",handler:b.handleBatch});let v=new ye({...e,openapi:g!==false?{path:R.path??"/openapi.json",docsPath:R.docsPath??"/docs",info:{title:R.title??"CRUD API",version:R.version??"1.0.0"},docsAuth:R.docsAuth}:void 0,basePath:t,api:"crud",routes:O,middlewares:[async(l,i)=>{if(l.req.method==="OPTIONS")return l.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization","Access-Control-Max-Age":"86400","Access-Control-Allow-Origin":"*","Access-Control-Allow-Credentials":"true"});l.header("Access-Control-Allow-Origin","*"),l.header("Access-Control-Allow-Credentials","true"),await i();},...e.middlewares||[]]});if(g!==false&&(v.buildOpenApiSpec=Z),r!==false){let{securityHeaders:l}=(ct(),ht(at)),i=r===void 0?{csp:false}:r;v.hono.use("*",async(y,s)=>{let h=l(i);await new Promise(m=>{let x=y.req.raw;h(x,{setHeader:(u,S)=>y.header(u,S),removeHeader:u=>y.res.headers.delete(u)},()=>m());}),await s();});}let P=v.nodeHandler;return P.spec=Z,a&&(P.httpsOptions=a),P}exports.applyRules=Ze;exports.computeDeepDiff=de;exports.createBeforeRules=Et;exports.createCrudServer=nr;exports.createRules=Ct;exports.generateOpenAPISpec=Oe;//# sourceMappingURL=index.cjs.map
|
|
13
13
|
//# sourceMappingURL=index.cjs.map
|