@lpdjs/firestore-repo-service 3.0.12 → 3.0.13
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 +27 -14
- package/dist/{create-servers-BaCe3x4U.d.ts → create-servers-Db1xUY2N.d.ts} +4 -4
- package/dist/{create-servers-C_UOfc_Z.d.cts → create-servers-LyRLAOh3.d.cts} +4 -4
- package/dist/history/index.cjs +1 -1
- package/dist/history/index.cjs.map +1 -1
- package/dist/history/index.js +1 -1
- package/dist/history/index.js.map +1 -1
- package/dist/index.cjs +62 -62
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +19 -15
- package/dist/index.d.ts +19 -15
- package/dist/index.js +62 -62
- package/dist/index.js.map +1 -1
- package/dist/llms-full.txt +36 -23
- package/dist/llms.txt +2 -2
- package/dist/{openapi-BJdsB8kh.d.ts → openapi-CNIA7QRw.d.ts} +1 -1
- package/dist/{openapi-D4xT2ilq.d.cts → openapi-QVpqnnes.d.cts} +1 -1
- package/dist/{queue-CVnFz30E.d.ts → queue-BEB-ujA3.d.ts} +1 -1
- package/dist/{queue-z04IR_Jq.d.cts → queue-CpHe6M5j.d.cts} +1 -1
- package/dist/{rules-CEYrlE4J.d.cts → rules-Bu2NB7Eb.d.cts} +1 -1
- package/dist/{rules-Dw-Pz8p3.d.ts → rules-Cafrkb9v.d.ts} +1 -1
- package/dist/servers/admin/index.cjs +26 -26
- package/dist/servers/admin/index.cjs.map +1 -1
- package/dist/servers/admin/index.d.cts +3 -1
- package/dist/servers/admin/index.d.ts +3 -1
- package/dist/servers/admin/index.js +26 -26
- package/dist/servers/admin/index.js.map +1 -1
- package/dist/servers/crud/index.cjs +2 -2
- package/dist/servers/crud/index.cjs.map +1 -1
- package/dist/servers/crud/index.d.cts +6 -6
- package/dist/servers/crud/index.d.ts +6 -6
- package/dist/servers/crud/index.js +2 -2
- package/dist/servers/crud/index.js.map +1 -1
- package/dist/servers/index.cjs +55 -55
- package/dist/servers/index.cjs.map +1 -1
- package/dist/servers/index.d.cts +8 -8
- package/dist/servers/index.d.ts +8 -8
- package/dist/servers/index.js +55 -55
- package/dist/servers/index.js.map +1 -1
- package/dist/sync/bigquery.d.cts +1 -1
- package/dist/sync/bigquery.d.ts +1 -1
- package/dist/sync/index.cjs +41 -41
- package/dist/sync/index.cjs.map +1 -1
- package/dist/sync/index.d.cts +5 -5
- package/dist/sync/index.d.ts +5 -5
- package/dist/sync/index.js +41 -41
- package/dist/sync/index.js.map +1 -1
- package/dist/sync/meilisearch.d.cts +1 -1
- package/dist/sync/meilisearch.d.ts +1 -1
- package/dist/{types-BFbzLuFf.d.cts → types-B51LYvQZ.d.cts} +48 -5
- package/dist/{types-DsTJZOfr.d.cts → types-CNseHqF7.d.cts} +4 -2
- package/dist/{types-Ds9DUc21.d.ts → types-Ci0dGbuW.d.ts} +48 -5
- package/dist/{types-fY1XOBeT.d.ts → types-DGQURFSq.d.ts} +1 -1
- package/dist/{types-YP53OtiU.d.ts → types-DmXW_fVz.d.ts} +4 -2
- package/dist/{types-_lql12Ez.d.cts → types-VVuLlmfc.d.cts} +1 -1
- package/package.json +1 -1
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { HttpsOptions } from 'firebase-functions/v2/https';
|
|
2
|
-
import { a as CrudServerOptions } from '../../types-
|
|
2
|
+
import { a as CrudServerOptions } from '../../types-CNseHqF7.cjs';
|
|
3
3
|
import { ConfiguredRepository } from '../../index.cjs';
|
|
4
|
-
export { A as ApiResponse, b as CrudRepoConfig, c as CrudRepoEntry, d as CrudRepoRegistry, e as CrudRules, f as CrudUpdateRuleContext, D as DeepDiffReturn, F as FieldRole, I as IndexErrorCallback, g as IndexErrorContext, L as ListResponseData, O as OpenAPISpecOptions, Q as QueryRequestBody, R as RepoFieldPath, h as RepoRelationKeys, i as Rule, j as RuleResult, k as RulesMap, U as UserFieldPath } from '../../types-
|
|
5
|
-
import { O as OpenAPIDocument } from '../../openapi-
|
|
6
|
-
export { g as generateOpenAPISpec } from '../../openapi-
|
|
7
|
-
export { a as applyRules, c as computeDeepDiff, b as createBeforeRules, d as createRules } from '../../rules-
|
|
4
|
+
export { A as ApiResponse, b as CrudRepoConfig, c as CrudRepoEntry, d as CrudRepoRegistry, e as CrudRules, f as CrudUpdateRuleContext, D as DeepDiffReturn, F as FieldRole, I as IndexErrorCallback, g as IndexErrorContext, L as ListResponseData, O as OpenAPISpecOptions, Q as QueryRequestBody, R as RepoFieldPath, h as RepoRelationKeys, i as Rule, j as RuleResult, k as RulesMap, U as UserFieldPath } from '../../types-CNseHqF7.cjs';
|
|
5
|
+
import { O as OpenAPIDocument } from '../../openapi-QVpqnnes.cjs';
|
|
6
|
+
export { g as generateOpenAPISpec } from '../../openapi-QVpqnnes.cjs';
|
|
7
|
+
export { a as applyRules, c as computeDeepDiff, b as createBeforeRules, d as createRules } from '../../rules-Bu2NB7Eb.cjs';
|
|
8
8
|
import '../../firebase-auth-nG3prKoj.cjs';
|
|
9
9
|
import '../../types-o-9qoExc.cjs';
|
|
10
10
|
import 'zod';
|
|
@@ -13,7 +13,7 @@ import '../../read-B15YaPyR.cjs';
|
|
|
13
13
|
import 'firebase-admin/firestore';
|
|
14
14
|
import '../../types--RamYGF1.cjs';
|
|
15
15
|
import 'firebase-functions/v2/firestore';
|
|
16
|
-
import '../../types-
|
|
16
|
+
import '../../types-B51LYvQZ.cjs';
|
|
17
17
|
|
|
18
18
|
/**
|
|
19
19
|
* @module servers/crud
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { HttpsOptions } from 'firebase-functions/v2/https';
|
|
2
|
-
import { a as CrudServerOptions } from '../../types-
|
|
2
|
+
import { a as CrudServerOptions } from '../../types-DmXW_fVz.js';
|
|
3
3
|
import { ConfiguredRepository } from '../../index.js';
|
|
4
|
-
export { A as ApiResponse, b as CrudRepoConfig, c as CrudRepoEntry, d as CrudRepoRegistry, e as CrudRules, f as CrudUpdateRuleContext, D as DeepDiffReturn, F as FieldRole, I as IndexErrorCallback, g as IndexErrorContext, L as ListResponseData, O as OpenAPISpecOptions, Q as QueryRequestBody, R as RepoFieldPath, h as RepoRelationKeys, i as Rule, j as RuleResult, k as RulesMap, U as UserFieldPath } from '../../types-
|
|
5
|
-
import { O as OpenAPIDocument } from '../../openapi-
|
|
6
|
-
export { g as generateOpenAPISpec } from '../../openapi-
|
|
7
|
-
export { a as applyRules, c as computeDeepDiff, b as createBeforeRules, d as createRules } from '../../rules-
|
|
4
|
+
export { A as ApiResponse, b as CrudRepoConfig, c as CrudRepoEntry, d as CrudRepoRegistry, e as CrudRules, f as CrudUpdateRuleContext, D as DeepDiffReturn, F as FieldRole, I as IndexErrorCallback, g as IndexErrorContext, L as ListResponseData, O as OpenAPISpecOptions, Q as QueryRequestBody, R as RepoFieldPath, h as RepoRelationKeys, i as Rule, j as RuleResult, k as RulesMap, U as UserFieldPath } from '../../types-DmXW_fVz.js';
|
|
5
|
+
import { O as OpenAPIDocument } from '../../openapi-CNIA7QRw.js';
|
|
6
|
+
export { g as generateOpenAPISpec } from '../../openapi-CNIA7QRw.js';
|
|
7
|
+
export { a as applyRules, c as computeDeepDiff, b as createBeforeRules, d as createRules } from '../../rules-Cafrkb9v.js';
|
|
8
8
|
import '../../firebase-auth-nG3prKoj.js';
|
|
9
9
|
import '../../types-D3W_RaDA.js';
|
|
10
10
|
import 'zod';
|
|
@@ -13,7 +13,7 @@ import '../../read-15-TcgCz.js';
|
|
|
13
13
|
import 'firebase-admin/firestore';
|
|
14
14
|
import '../../types--RamYGF1.js';
|
|
15
15
|
import 'firebase-functions/v2/firestore';
|
|
16
|
-
import '../../types-
|
|
16
|
+
import '../../types-Ci0dGbuW.js';
|
|
17
17
|
|
|
18
18
|
/**
|
|
19
19
|
* @module servers/crud
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {randomBytes}from'crypto';import {z}from'zod';import {Timestamp}from'firebase-admin/firestore';import {extendZodWithOpenApi,getOpenApiMetadata,OpenAPIRegistry,OpenApiGeneratorV31}from'@asteasolutions/zod-to-openapi';import {Hono}from'hono';import {getRequestListener}from'@hono/node-server';import {AsyncLocalStorage}from'async_hooks';var he=Object.defineProperty;var ft=Object.getOwnPropertyDescriptor;var yt=Object.getOwnPropertyNames;var mt=Object.prototype.hasOwnProperty;var ht=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var gt=(e,t)=>{for(var n in t)he(e,n,{get:t[n],enumerable:true});},wt=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of yt(t))!mt.call(e,r)&&r!==n&&he(e,r,{get:()=>t[r],enumerable:!(o=ft(t,r))||o.enumerable});return e};var bt=e=>wt(he({},"__esModule",{value:true}),e);var ut={};gt(ut,{DEFAULT_HTML_CSP:()=>dt,securityHeaders:()=>pn});function pn(e={}){let t=e.csp===void 0?dt: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 at,ct,dt,pt=ht(()=>{"use strict";at="https://cdn.jsdelivr.net",ct="https://www.gstatic.com",dt=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${at} ${ct}`,`style-src 'self' 'unsafe-inline' ${at}`,`connect-src 'self' ${ct} 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 je="preserve";function we(){return je}function xt(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function De(e){if(e==null)return null;if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(e instanceof Timestamp)return e.toDate();if(xt(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 ze(e){return e}function _e(e){let t=e;if(t._zod?.def?.element)return t._zod.def.element;if(t._def?.type)return t._def.type}var St=new Set(["<","<=",">",">=","!="]),Tt=new Set(["array-contains","array-contains-any"]);function be(e){return e==="desc"?"DESCENDING":"ASCENDING"}function At(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function kt(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(Tt.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(St.has(p.op)){if(a.has(p.field))continue;a.add(p.field);let f=r?.field===p.field?be(r.dir):"ASCENDING";c.push({fieldPath:p.field,order:f});}if(r&&!a.has(r.field)&&c.push({fieldPath:r.field,order:be(r.dir)}),c.length===1&&n)return Ct(e,t,c[0]);let d=r&&c.some(p=>p.fieldPath===r.field)?be(r.dir):"ASCENDING";return c.push({fieldPath:"__name__",order:d}),Ot(e,t,n,c)}function Ot(e,t,n,o,r="(default)"){let c=`projects/${e}/databases/${r}/collectionGroups/${t}/indexes/_`,a=[...Se(1,c),...ae(2,n?2:1)];for(let f of o)a.push(...qe(3,Ne(f)));let d=r==="(default)"?"-default-":r,p=encodeURIComponent(Ze(a));return `https://console.firebase.google.com/project/${e}/firestore/databases/${d}/indexes?create_composite=${p}`}function vt(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function xe(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function Re(e,t){return e<<3|t}function Se(e,t){let n=Array.from(new TextEncoder().encode(t));return [Re(e,2),...xe(n.length),...n]}function ae(e,t){return [Re(e,0),...xe(t)]}function qe(e,t){return [Re(e,2),...xe(t.length),...t]}function Ne(e){let t=[...Se(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...ae(3,1)):t.push(...ae(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 Ct(e,t,n,o="(default)"){let r=`projects/${e}/databases/${o}/collectionGroups/${t}/fields/${n.fieldPath}`,c=[...Se(1,r),...ae(2,2),...qe(3,Ne(n))],a=o==="(default)"?"-default-":o,d=encodeURIComponent(Ze(c));return `https://console.firebase.google.com/project/${e}/firestore/databases/${a}/indexes/automatic?create_exemption=${d}`}function Et(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 It(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??{},o=It(e),r;if(o&&(r=n.message?vt(n.message):void 0,!r)){let c=Et(t.ref);if(c){let a=At(t.path);r=kt(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 de(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 Timestamp&&t instanceof 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(!de(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 Timestamp||t instanceof 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)||!de(e[c],t[c],n))return false;return true}return false}function ue(e,t){let n=e||{},o={},r={...n};for(let[c,a]of Object.entries(t||{})){let d=n[c];de(d,a)||(o[c]=a,r[c]=a);}return {before:n,after:r,changes:o}}function Pt(e){return e}async function Fe(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 jt(e){return async t=>Fe(t.diff,e,t.user)}function Oe(e,t,n=200){let o=ze(t);return e.json(o,n)}function G(e,t,n,o=200){return Oe(e,{success:true,data:t,meta:n},o)}function w(e,t,n=400){return Oe(e,{success:false,error:t},n)}async function Te(e,t,n,o,r,c){let a=$e(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 Oe(e,b,p)}var Ae="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function He(){let e="";for(;e.length<20;){let t=randomBytes(20);for(let n=0;n<t.length&&e.length<20;n++){let o=t[n];o>=Ae.length*4||(e+=Ae.charAt(o%Ae.length));}}return e}function V(e){let t=e._def??e.def;if(!t)return e;let n=t.typeName??t.type;if(n==="ZodDate"||n==="date")return z.preprocess(o=>De(o)??o,e);if(n==="ZodObject"||n==="object"){let o=e.shape,r={};for(let[c,a]of Object.entries(o))r[c]=V(a);return z.object(r)}if(n==="ZodArray"||n==="array"){let o=t.element??t.type;if(o)return z.array(V(o))}if(n==="ZodOptional"||n==="optional"){let o=t.innerType;if(o)return V(o).optional()}if(n==="ZodNullable"||n==="nullable"){let o=t.innerType;if(o)return V(o).nullable()}if(n==="ZodDefault"||n==="default"){let o=t.innerType,r=t.defaultValue;if(o){let c=V(o);return typeof r=="function"?c.default(r()):c.default(r)}}return e}function zt(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 z.object(r)}function ke(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 Ue(e,t){let n=t.split("."),o=ke(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=ke(d);}return o}function J(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]=J(a);return z.object(r).partial()}if(n==="ZodOptional"||n==="optional"){let o=t.innerType;if(!o)return e;let r=J(o);return r===o?e:r.optional()}if(n==="ZodNullable"||n==="nullable"){let o=t.innerType;if(!o)return e;let r=J(o);return r===o?e:r.nullable()}if(n==="ZodDefault"||n==="default"){let o=t.innerType;return o?J(o).optional():e}if(n==="ZodUnion"||n==="union"){let o=t.options;if(!o||o.length<2)return e;let r=o.map(a=>J(a));return r.some((a,d)=>a!==o[d])?z.union(r):e}return e}function pe(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=Ue(e,p);if(!g)return {success:!1,error:`Field '${p}' does not exist in schema`};let S=o?J(g):g,Z=(we()==="normalize"?V(S):S).parse(f);a[p]=Z;}else d[p]=f;if(Object.keys(d).length>0||Object.keys(a).length===0){let p=zt(e,n,r),f=o?J(p):p,g=(we()==="normalize"?V(f):f).parse(d);Object.assign(a,g);}return {success:!0,data:a}}catch(c){return c instanceof z.ZodError?{success:false,error:`Validation failed: ${c.issues.map(d=>`${d.path.join(".")}: ${d.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}var Le={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 ne(e){return Le[e]??e}function _t(e){return e in Le}function le(e,t,n,o){let r=Ue(e,t);if(!r||typeof r.safeParse!="function")return {success:true,data:n};let c=o?ne(o):void 0,a=ke(r),d=_e(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(D=>D.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 S of n)if(typeof b.safeParse=="function"){let D=b.safeParse(S);if(D.success)g.push(D.data);else return {success:false,error:D.error.issues.map(v=>v.message).join(", ")}}else g.push(S);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 S of n)if(typeof b.safeParse=="function"){let D=b.safeParse(S);if(D.success)g.push(D.data);else return {success:false,error:D.error.issues.map(v=>v.message).join(", ")}}else g.push(S);return {success:true,data:g}}return {success:false,error:p.error.issues.map(b=>b.message).join(", ")}}function qt(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),S=r.slice(d+2);_t(S)?(p=g,f=ne(S)):(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=>Me(g.trim())):b=Me(a),n.push({field:p,op:f,value:b});}return n}function Me(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 fe(e){return e?{docId:e.id,docPath:e.ref?.path??void 0}:null}async function Be(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 Ke(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(),R=Math.min(Number(u.pageSize)||s.pageSize,100),C=u.cursor,q=u.direction?.toLowerCase()==="prev"?"prev":"next",O=u.orderBy,z=u.orderDir?.toLowerCase()==="desc"?"desc":"asc",N=u.select,L=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(K=>K.trim()):Array.isArray(u.includes)?u.includes:[]).filter(K=>typeof K=="string"&&s.allowedIncludes.includes(K)),I?.length===0&&(I=void 0));let E=qt(u,s.filterableFields);x=E.map(H=>({field:H.field,op:H.op,value:String(H.value??"")})),O&&(A={field:O,dir:z});let B={pageSize:R,direction:q,...T?{withTotal:!0}:{}};if(C)try{let H=typeof C=="string"?JSON.parse(C):C;B.cursor=await Be(s,H);}catch{}if(O){if(s.orderableFields&&!s.orderableFields.includes(O))return w(i,`Field not orderable: ${O}`,400);B.orderBy=[{field:O,direction:z}];}if(E.length>0){B.where=[];for(let H of E){let K=le(s.schema,H.field,H.value,H.op);if(!K.success)return w(i,`Invalid filter value for '${H.field}': ${K.error}`,400);B.where.push([H.field,H.op,K.data]);}}L&&(B.select=L),I&&(B.include=I);let $=await s.repo.query.paginate(B),lt={items:await c(s,a(i),y,$.data),hasNextPage:$.hasNextPage,hasPrevPage:$.hasPrevPage,nextCursor:fe($.nextCursor),prevCursor:fe($.prevCursor),...$.totalCount!==void 0?{totalCount:$.totalCount,totalCountIsExact:$.totalCountIsExact}:{}};return G(i,lt,{pageSize:R,hasMore:$.hasNextPage,...$.totalCount!==void 0?{totalCount:$.totalCount,totalCountIsExact:$.totalCountIsExact}:{}})}catch(u){return await Te(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||{},R=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",O={pageSize:R,direction:C,...q?{withTotal:!0}:{}};if(u.cursor)try{let _=typeof u.cursor=="string"?JSON.parse(u.cursor):u.cursor;O.cursor=await Be(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&&(O.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=ne(T[1]),E=le(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]);}O.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=ne(T[1]),E=le(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]);}O.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(B=>!T.has(B[0]));if(E.length>0){w(i,`Fields not filterable: ${E.map(B=>B[0]).join(", ")}`,400);return}}}let _=[];for(let T of u.orWhereGroups){let I=[];for(let E of T){let B=ne(E[1]),$=le(s.schema,E[0],E[2],B);if(!$.success){w(i,`Invalid filter value for '${E[0]}': ${$.error}`,400);return}I.push([E[0],B,$.data]);}_.push(I);}O.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}}O.orderBy=u.orderBy;}u.select&&u.select.length>0&&(O.select=u.select);let z=await s.repo.query.paginate(O),L={items:await c(s,a(i),y,z.data),hasNextPage:z.hasNextPage,hasPrevPage:z.hasPrevPage,nextCursor:fe(z.nextCursor),prevCursor:fe(z.prevCursor),...z.totalCount!==void 0?{totalCount:z.totalCount,totalCountIsExact:z.totalCountIsExact}:{}};return G(i,L,{pageSize:R,hasMore:z.hasNextPage,...z.totalCount!==void 0?{totalCount:z.totalCount,totalCountIsExact:z.totalCountIsExact}:{}})}catch(u){return await Te(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 S(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 G(i,m)}catch(m){return await Te(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 D(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=pe(s.schema,h,s.createFields,!1,s.systemKeys);if(!A.success)return w(i,A.error,400);if(s.validate){let R=await s.validate(A.data,"create");if(R)return w(i,R,400)}let u;if(s.isGroup&&s.parentKeys&&s.parentKeys.length>0){let R={...A.data};s.createdKey&&(R[s.createdKey]=new Date);let C=s.parentKeys.filter(z=>!R[z]);if(C.length>0){w(i,`Missing parent key(s) for subcollection create: ${C.join(", ")}`,400);return}let q=s.parentKeys.map(z=>R[z]),O=R[s.documentKey]||He();u=await s.repo.set(...q,O,R);}else u=await s.repo.create(A.data);return G(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=pe(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 R=ue(A,u.data),C=a(y),q=await r(y,h,"update",{user:C,doc:A,body:u.data,diff:R,params:s});if(!q.allowed)return q.errorResponse;let O=p(A,h.pathKey)??[m],z=await h.repo.update(...O,u.data);return G(y,z)}catch(x){let A=n&&x instanceof Error?x.message:"Failed to update document";return w(y,A,500)}}async function v(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),G(i,{deleted:!0})}catch(m){let x=n&&m instanceof Error?m.message:"Failed to delete document";return w(i,x,500)}}function k(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 R=await r(i,s,"create",{user:m,body:u.data,params:y});if(!R.allowed)return R.errorResponse;let C=pe(s.schema,u.data,s.createFields,!1,s.systemKeys);if(!C.success)return w(i,C.error,400);let q=u.data[s.documentKey]||He(),O={...C.data};if(s.createdKey&&(O[s.createdKey]=new Date),s.isGroup&&s.parentKeys){let z=s.parentKeys.map(N=>O[N]);x.set(...z,q,O);}else x.set(q,O);A.push({op:"create",id:q});}else if(u.type==="update"){if(!u.id)return w(i,"id required for update",400);let R=await f(s,u.id);if(!R)return w(i,`Document ${u.id} not found`,404);let C=pe(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=ue(R,C.data),O=await r(i,s,"update",{user:m,doc:R,body:C.data,diff:q,params:y});if(!O.allowed)return O.errorResponse;let z=p(R,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 R=await f(s,u.id);if(!R)return w(i,`Document ${u.id} not found`,404);let C=await r(i,s,"delete",{user:m,doc:R,params:y});if(!C.allowed)return C.errorResponse;let q=p(R,s.pathKey)??[u.id];x.delete(...q),A.push({op:"delete",id:u.id});}}return await x.commit(),G(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:S,handleCreate:D,handleUpdate:Z,handleDelete:v,handleBatch:P,handleOptions:k}}function ee(e){try{return z.toJSONSchema(e,{target:"openapi-3.1",unrepresentable:"any",override:t=>{let n=getOpenApiMetadata(t.zodSchema);n&&(Object.assign(t.jsonSchema,n),(t.jsonSchema.anyOf||t.jsonSchema.oneOf)&&delete t.jsonSchema.type);let 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 j(e){return {description:e,content:{"application/json":{schema:F("ErrorResponse")}}}}function Y(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function Nt(e){return {description:"Paginated list of documents",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:{type:"object",properties:{items:{type:"array",items:e},nextCursor:{oneOf:[{type:"object"},{type:"null"}]},prevCursor:{oneOf:[{type:"object"},{type:"null"}]},hasNextPage:{type:"boolean"},hasPrevPage:{type:"boolean"},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 oe(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("."),o=oe(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=oe(d);}return o}function X(e){let t=e?._zod?.def??e?._def,n=t?.typeName??t?.type,o=r=>{let c=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]=X(d);return o(z.object(c).partial())}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(!r)return e;let c=X(r);return c===r?e:o(c.optional())}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(!r)return e;let c=X(r);return c===r?e:o(c.nullable())}if(n==="ZodDefault"||n==="default"){let r=t.innerType;return r?o(X(r).optional()):e}if(n==="ZodUnion"||n==="union"){let r=t.options;if(!r||r.length<2)return e;let c=r.map(d=>X(d));return c.some((d,p)=>d!==r[p])?o(z.union(c)):e}return e}function ve(e,t="",n=0){if(n>5)return [];let r=oe(e)?.shape;if(!r)return [];let c=[];for(let[a,d]of Object.entries(r)){let p=t?`${t}.${a}`:a,f=oe(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 $t(e){return e.filterableFields&&e.filterableFields.length>0?e.filterableFields.map(t=>({path:t,zodSchema:Zt(e.schema,t)})):ve(e.schema)}function We(e){if(!e)return {type:"string"};let t=ee(e);return delete t.$schema,delete t.title,t}function Ve(){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 Ft(e){let t=$t(e),n=e.orderableFields??t.map(a=>a.path),o=t.map(a=>a.path);if(t.length===0)return Ve();let r=[];for(let{path:a,zodSchema:d}of t){let p=We(d),f=oe(d),g=f?._zod?.def?.type==="array"||f?._def?.typeName==="ZodArray"||f?._def?.type==="array"?We(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 Ht(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${W(e.name)}`,summary:`Create a ${U(e.name)}`,tags:[p],requestBody:{required:true,content:{"application/json":{schema:F(o??n)}}},responses:{201:Y("Document created",F(n)),400:j("Validation error"),403:j("Forbidden"),500:j("Internal server error")}}},d[`${f}/query`]={post:{operationId:`query${W(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[p],requestBody:{required:true,content:{"application/json":{schema:F(a)}}},responses:{200:Nt(F(n)),400:j("Invalid query"),403:j("Forbidden"),424:j("Missing composite index (includes indexUrl in response)"),500:j("Internal server error")}}},d[`${f}/batch`]={post:{operationId:`batch${W(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[p],requestBody:{required:true,content:{"application/json":{schema:F(`${n}BatchRequest`)}}},responses:{200:Y("Batch operations completed",{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{op:{type:"string"},id:{type:"string"}}}}}}),400:j("Validation error"),403:j("Forbidden"),404:j("Document not found"),500:j("Internal server error")}}};let S={};return S.get={operationId:`get${W(U(e.name))}`,summary:`Get a single ${U(e.name)}`,tags:[p],parameters:[g],responses:{200:Y("Document found",F(n)),400:j("Document ID required"),403:j("Forbidden"),404:j("Document not found"),424:j("Missing composite index (includes indexUrl in response)"),500:j("Internal server error")}},S.put={operationId:`update${W(U(e.name))}`,summary:`Update a ${U(e.name)} (full replace)`,tags:[p],parameters:[g],requestBody:{required:true,content:{"application/json":{schema:F(r??n)}}},responses:{200:Y("Document updated",F(n)),400:j("Validation error"),403:j("Forbidden"),404:j("Document not found"),500:j("Internal server error")}},S.patch={operationId:`patch${W(U(e.name))}`,summary:`Partially update a ${U(e.name)}`,tags:[p],parameters:[g],requestBody:{required:true,content:{"application/json":{schema:F(c??r??n)}}},responses:{200:Y("Document patched",F(n)),400:j("Validation error"),403:j("Forbidden"),404:j("Document not found"),500:j("Internal server error")}},e.allowDelete&&(S.delete={operationId:`delete${W(U(e.name))}`,summary:`Delete a ${U(e.name)}`,tags:[p],parameters:[g],responses:{200:Y("Document deleted",{type:"object",properties:{id:{type:"string"}}}),400:j("Document ID required"),403:j("Forbidden"),404:j("Document not found"),500:j("Internal server error")}}),d[b]=S,d}function Ce(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=Ve();for(let[v,k]of Object.entries(e)){let P=W(U(v)),l=`${P}Create`,i=`${P}Update`,y=`${P}Patch`,s=`${P}QueryRequestBody`;f[P]=ee(k.schema),f[s]=Ft(k);let h=N=>{let L={},_=ve(k.schema);for(let{path:T,zodSchema:I}of _){let E=T.split(".")[0];k.systemKeys.includes(E)||k.systemKeys.includes(T)||N&&N.length>0&&!N.includes(T)&&!N.includes(E)||(T.includes(".")?L[T]=I.optional():L[T]=I);}return L},m=null,x=h(k.createFields);Object.keys(x).length>0&&(f[l]=ee(z.object(x)),m=l);let A=null,u=null,R=h(k.mutableFields);if(Object.keys(R).length>0){let N=z.object(R);f[i]=ee(N),A=i,f[y]=ee(X(N)),u=y;}else f[y]=ee(X(k.schema)),u=y;let C=`${P}BatchCreateOperation`,q=`${P}BatchUpdateOperation`,O=`${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"]},k.allowDelete&&(f[O]={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),...k.allowDelete?[F(O)]:[]],discriminator:{propertyName:"type"}}}},required:["operations"]};let z$1=Ht(k,p,P,m,A,u,s);Object.assign(b,z$1),g.push({name:v,description:`Operations on ${v} (collection: ${k.path})`});}let S={},D;return d==="basic"?(S.basicAuth={type:"http",scheme:"basic"},D=[{basicAuth:[]}]):d==="bearer"&&(S.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},D=[{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(S).length>0?{securitySchemes:S}:{}},...D?{security:D}:{},tags:g}}function W(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 te=class extends Error{constructor(n,o){super("Request validation failed");this.zodError=n;this.source=o;this.statusCode=400;this.name="ValidationError";}};var se=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},ie=class extends Error{constructor(n){super("Output validation failed");this.zodError=n;this.statusCode=500;this.name="OutputValidationError";}};function Je(e){return e.issues.map(t=>({path:t.path.join("."),code:t.code,message:t.message}))}function Qe(e,t){return t instanceof te?e.json({success:false,error:"Validation failed",issues:Je(t.zodError)},400):t instanceof se?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof ie?e.json({success:false,error:"Output validation failed",issues:Je(t.zodError)},500):null}extendZodWithOpenApi(z);var Xe="Successful response",Ye="Error response";function M(e,t=new Set){if(!e||typeof e!="object"||t.has(e))return;t.add(e);let n=e,o=n._zod?.def??n.def;if(!o)return;if(o.type==="custom"){let c=getOpenApiMetadata(n);c?.type||z.globalRegistry.add(n,{...c??{},type:"object"});return}if(o.innerType&&M(o.innerType,t),o.element&&M(o.element,t),o.valueType&&M(o.valueType,t),o.keyType&&M(o.keyType,t),o.left&&M(o.left,t),o.right&&M(o.right,t),o.in&&M(o.in,t),o.out&&M(o.out,t),typeof o.getter=="function")try{M(o.getter(),t);}catch{}if(Array.isArray(o.options))for(let c of o.options)M(c,t);if(Array.isArray(o.items))for(let c of o.items)M(c,t);let r=typeof o.shape=="function"?o.shape():o.shape;if(r&&typeof r=="object")for(let c of Object.values(r))M(c,t);}function Ee(e){if(!e||typeof e!="object")return;if(Array.isArray(e)){for(let n of e)Ee(n);return}let t=e;(Array.isArray(t.anyOf)||Array.isArray(t.oneOf))&&"type"in t&&delete t.type;for(let n of Object.values(t))Ee(n);}function Kt(e){return e==="get"?"query":"json"}function Wt(e,t){let n=t?.output;return n?typeof n=="function"?n(e):n:e}function Gt(e){if(typeof e.safeParse=="function")return {description:Ye,schema:e};let t=e;return {description:t.description??Ye,schema:t.schema}}function nt(e,t,n,o){let r=new 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??Kt(p),b=Qt(t,d.path??"/"),g=d.status??200;d.input&&M(d.input);let S=Vt(p,f,d.input),D=et(f,d.input,"query"),Z=et(f,d.input,"param"),v=Xt(p,b),k=Wt(d.output,o);k&&M(k);let P={[g]:k?{description:Xe,content:{"application/json":{schema:k}}}:{description:Xe}};if(o?.errors)for(let[l,i]of Object.entries(o.errors)){let{description:y,schema:s}=Gt(i);s&&M(s),P[l]=s?{description:y,content:{"application/json":{schema:s}}}:{description:y};}r.registerPath({method:p,path:Jt(b),operationId:v,summary:d.summary,description:d.description,tags:d.tags,deprecated:d.deprecated,security:d.security,request:{...D?{query:D}:{},...Z?{params:Z}:{},...S?{body:S}:{}},responses:P});}let a=new OpenApiGeneratorV31(r.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security});return Ee(a),a}function Vt(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 et(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function Jt(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function Qt(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,o=t.startsWith("/")?t:`/${t}`,r=`${n}${o}`;return r===""?"/":r}function Xt(e,t){let n=t.replace(/[{}]/g,"").replace(/\/+/g,"_").replace(/[^A-Za-z0-9_]/g,"").replace(/^_+|_+$/g,"");return `${e}_${n||"root"}`}function rt(e,t){let n=e.replace(/"/g,""");return `<!doctype html>
|
|
1
|
+
import {z}from'zod';import {Timestamp}from'firebase-admin/firestore';import {randomBytes}from'crypto';import {extendZodWithOpenApi,getOpenApiMetadata,OpenAPIRegistry,OpenApiGeneratorV31}from'@asteasolutions/zod-to-openapi';import {Hono}from'hono';import {getRequestListener}from'@hono/node-server';import {AsyncLocalStorage}from'async_hooks';var he=Object.defineProperty;var ht=Object.getOwnPropertyDescriptor;var gt=Object.getOwnPropertyNames;var wt=Object.prototype.hasOwnProperty;var bt=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var xt=(e,t)=>{for(var n in t)he(e,n,{get:t[n],enumerable:true});},St=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of gt(t))!wt.call(e,r)&&r!==n&&he(e,r,{get:()=>t[r],enumerable:!(o=ht(t,r))||o.enumerable});return e};var Rt=e=>St(he({},"__esModule",{value:true}),e);var ft={};xt(ft,{DEFAULT_HTML_CSP:()=>lt,securityHeaders:()=>yn});function yn(e={}){let t=e.csp===void 0?lt: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(a,c,d)=>{typeof c?.setHeader=="function"&&(c.setHeader("X-Content-Type-Options","nosniff"),n&&c.setHeader("X-Frame-Options",n),o&&c.setHeader("Referrer-Policy",o),r&&c.setHeader("Cache-Control",r),t&&c.setHeader("Content-Security-Policy",t)),await d();}}var ut,pt,lt,yt=bt(()=>{"use strict";ut="https://cdn.jsdelivr.net",pt="https://www.gstatic.com",lt=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${ut} ${pt}`,`style-src 'self' 'unsafe-inline' ${ut}`,`connect-src 'self' ${pt} 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 je="preserve";function we(){return je}function Tt(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function ze(e){if(e==null)return null;if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(e instanceof Timestamp)return e.toDate();if(Tt(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 _e(e){return e}var be="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function xe(){let e="";for(;e.length<20;){let t=randomBytes(20);for(let n=0;n<t.length&&e.length<20;n++){let o=t[n];o>=be.length*4||(e+=be.charAt(o%be.length));}}return e}function qe(e){return e.match(/^\{([^}]+)\}$/)?.[1]?.trim()||null}function $e(e,t="docId",n=false){if(typeof e!="string"||!e.trim())return {rawPath:e??"",collectionId:"",collectionPath:"",parentKeys:[],documentPathTemplate:null,hasTemplate:false};let o=e.split("/").map(y=>y.trim()).filter(Boolean);if(o.length===0)return {rawPath:e,collectionId:e,collectionPath:e,parentKeys:[],documentPathTemplate:null,hasTemplate:false};if(o.length===1){let y=o[0];return {rawPath:e,collectionId:y,collectionPath:y,parentKeys:[],documentPathTemplate:n?null:`${y}/{${t}}`,hasTemplate:e.includes("{")&&e.includes("}")}}let r=o.length%2===0,a=r?o.slice(0,-1):o,c=a[a.length-1],d=a.join("/"),l=a.slice(0,-1).map(qe).filter(y=>y!==null),g=r?o.join("/"):`${d}/{${t}}`;return {rawPath:e,collectionId:c,collectionPath:d,parentKeys:l,documentPathTemplate:g,hasTemplate:true}}function Fe(e,t={}){if(!e||typeof e!="object")return;let{pathKey:n,documentKey:o="docId",parentKeys:r,documentPathTemplate:a,isGroup:c}=t,d=n&&typeof e[n]=="string"&&e[n]?e[n]:void 0;if(d&&a){let u=d.split("/").filter(Boolean),l=a.split("/").filter(Boolean);if(u.length===l.length){let g=[];for(let y=0;y<l.length;y++)qe(l[y])!==null&&g.push(u[y]);if(g.length>0)return g}}if(r&&r.length>0){let u=r.length+1;if(d){let g=d.split("/").filter(Boolean),y=[];for(let S=1;S<g.length;S+=2)y.push(g[S]);if(y.length>=u)return y.slice(y.length-u)}let l=o?e[o]:void 0;if(typeof l=="string"&&l.trim()!==""){let g=[],y=true;for(let S of r){let E=e[S];if(typeof E=="string"&&E.trim()!=="")g.push(E);else {y=false;break}}if(y)return [...g,l]}}if(d){let u=d.split("/").filter(Boolean),l=[];for(let g=1;g<u.length;g+=2)l.push(u[g]);if(l.length>0)return !c&&(!r||r.length===0)?[l[l.length-1]]:l}}function Ne(e){let t=e;if(t._zod?.def?.element)return t._zod.def.element;if(t._def?.type)return t._def.type}var Ot=new Set(["<","<=",">",">=","!="]),vt=new Set(["array-contains","array-contains-any"]);function Se(e){return e==="desc"?"DESCENDING":"ASCENDING"}function Ct(e){return $e(e).collectionId||e}function Et(e,t,n,o,r){let a=[],c=new Set;for(let u of o)if(u.op==="=="||u.op==="in"||u.op==="not-in"){if(c.has(u.field))continue;c.add(u.field),a.push({fieldPath:u.field,order:"ASCENDING"});}for(let u of o)if(vt.has(u.op)){if(c.has(u.field))continue;c.add(u.field),a.push({fieldPath:u.field,arrayConfig:"CONTAINS"});}for(let u of o)if(Ot.has(u.op)){if(c.has(u.field))continue;c.add(u.field);let l=r?.field===u.field?Se(r.dir):"ASCENDING";a.push({fieldPath:u.field,order:l});}if(r&&!c.has(r.field)&&a.push({fieldPath:r.field,order:Se(r.dir)}),a.length===1&&n)return Dt(e,t,a[0]);let d=r&&a.some(u=>u.fieldPath===r.field)?Se(r.dir):"ASCENDING";return a.push({fieldPath:"__name__",order:d}),It(e,t,n,a)}function It(e,t,n,o,r="(default)"){let a=`projects/${e}/databases/${r}/collectionGroups/${t}/indexes/_`,c=[...Ae(1,a),...ae(2,n?2:1)];for(let l of o)c.push(...Ze(3,He(l)));let d=r==="(default)"?"-default-":r,u=encodeURIComponent(Me(c));return `https://console.firebase.google.com/project/${e}/firestore/databases/${d}/indexes?create_composite=${u}`}function Pt(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function Re(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function Te(e,t){return e<<3|t}function Ae(e,t){let n=Array.from(new TextEncoder().encode(t));return [Te(e,2),...Re(n.length),...n]}function ae(e,t){return [Te(e,0),...Re(t)]}function Ze(e,t){return [Te(e,2),...Re(t.length),...t]}function He(e){let t=[...Ae(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...ae(3,1)):t.push(...ae(2,e.order==="DESCENDING"?2:1)),t}function Me(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 Dt(e,t,n,o="(default)"){let r=`projects/${e}/databases/${o}/collectionGroups/${t}/fields/${n.fieldPath}`,a=[...Ae(1,r),...ae(2,2),...Ze(3,He(n))],c=o==="(default)"?"-default-":o,d=encodeURIComponent(Me(a));return `https://console.firebase.google.com/project/${e}/firestore/databases/${c}/indexes/automatic?create_exemption=${d}`}function jt(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 zt(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function Be(e,t){let n=e??{},o=zt(e),r;if(o&&(r=n.message?Pt(n.message):void 0,!r)){let a=jt(t.ref);if(a){let c=Ct(t.path);r=Et(a,c,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 de(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 Timestamp&&t instanceof 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(!de(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 Timestamp||t instanceof 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 a of o)if(!Object.prototype.hasOwnProperty.call(t,a)||!de(e[a],t[a],n))return false;return true}return false}function ue(e,t){let n=e||{},o={},r={...n};for(let[a,c]of Object.entries(t||{})){let d=n[a];de(d,c)||(o[a]=c,r[a]=c);}return {before:n,after:r,changes:o}}function _t(e){return e}async function Ue(e,t,n){let o=e.changes||{};for(let r of Object.keys(o)){let a=t[r];if(a&&a.length>0){for(let c of a)if(await c.rule({diff:e,key:r,user:n,authenticatedUser:n})===false)return {allowed:false,reason:c.description}}}return {allowed:true}}function qt(e){return async t=>Ue(t.diff,e,t.user)}function ve(e,t,n=200){let o=_e(t);return e.json(o,n)}function W(e,t,n,o=200){return ve(e,{success:true,data:t,meta:n},o)}function b(e,t,n=400){return ve(e,{success:false,error:t},n)}async function ke(e,t,n,o,r,a){let c=Be(t,n),d=c.type==="index",u=d?424:500,g={success:false,error:d?c.message:r&&t instanceof Error?t.message:o};if(d&&(g.errorType="index",c.indexUrl&&(g.indexUrl=c.indexUrl,a)))try{let y=a({indexUrl:c.indexUrl,repoName:n.repoName??"",path:n.path,isGroup:n.isGroup,filters:n.filters,sort:n.sort,error:t,c:e});y instanceof Promise&&await y;}catch(y){r&&console.error("[crudServer] Error in indexesError callback:",y);}return ve(e,g,u)}function V(e){let t=e._def??e.def;if(!t)return e;let n=t.typeName??t.type;if(n==="ZodDate"||n==="date")return z.preprocess(o=>ze(o)??o,e);if(n==="ZodObject"||n==="object"){let o=e.shape,r={};for(let[a,c]of Object.entries(o))r[a]=V(c);return z.object(r)}if(n==="ZodArray"||n==="array"){let o=t.element??t.type;if(o)return z.array(V(o))}if(n==="ZodOptional"||n==="optional"){let o=t.innerType;if(o)return V(o).optional()}if(n==="ZodNullable"||n==="nullable"){let o=t.innerType;if(o)return V(o).nullable()}if(n==="ZodDefault"||n==="default"){let o=t.innerType,r=t.defaultValue;if(o){let a=V(o);return typeof r=="function"?a.default(r()):a.default(r)}}return e}function $t(e,t,n=[]){let o=e.shape,r={},a=t&&t.length>0?t:Object.keys(o);for(let c of a){if(n.includes(c))continue;let d=c.split(".")[0];d&&o[d]&&(r[d]=o[d]);}return z.object(r)}function Oe(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 Ge(e,t){let n=t.split("."),o=Oe(e);for(let r=0;r<n.length;r++){let a=n[r];if(!a)continue;let c=o?.shape;if(!c||!c[a])return;let d=c[a];if(r===n.length-1)return d;o=Oe(d);}return o}function J(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[a,c]of Object.entries(o))r[a]=J(c);return z.object(r).partial()}if(n==="ZodOptional"||n==="optional"){let o=t.innerType;if(!o)return e;let r=J(o);return r===o?e:r.optional()}if(n==="ZodNullable"||n==="nullable"){let o=t.innerType;if(!o)return e;let r=J(o);return r===o?e:r.nullable()}if(n==="ZodDefault"||n==="default"){let o=t.innerType;return o?J(o).optional():e}if(n==="ZodUnion"||n==="union"){let o=t.options;if(!o||o.length<2)return e;let r=o.map(c=>J(c));return r.some((c,d)=>c!==o[d])?z.union(r):e}return e}function pe(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 a=t,c={},d={};for(let[u,l]of Object.entries(a))if(u.includes(".")){let g=u.split(".")[0];if(r.includes(u)||r.includes(g))continue;if(n&&n.length>0&&!n.includes(u)&&!n.includes(g))return {success:!1,error:`Field '${u}' is not allowed for this operation`};let y=Ge(e,u);if(!y)return {success:!1,error:`Field '${u}' does not exist in schema`};let S=o?J(y):y,F=(we()==="normalize"?V(S):S).parse(l);c[u]=F;}else d[u]=l;if(Object.keys(d).length>0||Object.keys(c).length===0){let u=$t(e,n,r),l=o?J(u):u,y=(we()==="normalize"?V(l):l).parse(d);Object.assign(c,y);}return {success:!0,data:c}}catch(a){return a instanceof z.ZodError?{success:false,error:`Validation failed: ${a.issues.map(d=>`${d.path.join(".")}: ${d.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}var We={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 ne(e){return We[e]??e}function Ft(e){return e in We}function le(e,t,n,o){let r=Ge(e,t);if(!r||typeof r.safeParse!="function")return {success:true,data:n};let a=o?ne(o):void 0,c=Oe(r),d=Ne(c);if(a==="array-contains"){let g=d??r;if(typeof g.safeParse=="function"){let y=g.safeParse(n);return y.success?{success:true,data:y.data}:{success:false,error:y.error.issues.map(E=>E.message).join(", ")}}return {success:true,data:n}}if(a==="array-contains-any"){if(!Array.isArray(n))return {success:false,error:"Expected array value for array-contains-any"};let g=d??r,y=[];for(let S of n)if(typeof g.safeParse=="function"){let E=g.safeParse(S);if(E.success)y.push(E.data);else return {success:false,error:E.error.issues.map(v=>v.message).join(", ")}}else y.push(S);return {success:true,data:y}}let u=r.safeParse(n);if(u.success)return {success:true,data:u.data};if(Array.isArray(n)){let g=d??r,y=[];for(let S of n)if(typeof g.safeParse=="function"){let E=g.safeParse(S);if(E.success)y.push(E.data);else return {success:false,error:E.error.issues.map(v=>v.message).join(", ")}}else y.push(S);return {success:true,data:y}}return {success:false,error:u.error.issues.map(g=>g.message).join(", ")}}function Nt(e,t){let n=[],o=t?new Set(t):null;for(let[r,a]of Object.entries(e)){if(a===void 0||["cursor","direction","limit","pageSize","orderBy","orderDir","select","includes","withTotal"].includes(r))continue;let c=Array.isArray(a)?a[0]:a;if(c===void 0||c==="")continue;let d=r.lastIndexOf("__"),u,l="==";if(d!==-1){let y=r.slice(0,d),S=r.slice(d+2);Ft(S)?(u=y,l=ne(S)):(u=r,l="==");}else u=r;if(o&&!o.has(u))continue;let g=c;l==="in"||l==="not-in"||l==="array-contains-any"?g=c.split(",").map(y=>Ke(y.trim())):g=Ke(c),n.push({field:u,op:l,value:g});}return n}function Ke(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 fe(e){return e?{docId:e.id,docPath:e.ref?.path??void 0}:null}async function Le(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 a=e.repo.ref,c=a?.firestore;if(o&&c&&typeof c.doc=="function"){let d=await c.doc(o).get();if(d.exists)return d}if(r&&r.includes("/")&&c&&typeof c.doc=="function"){let d=await c.doc(r).get();if(d.exists)return d}if(r&&typeof a.doc=="function"){let d=await a.doc(r).get();if(d.exists)return d}return}catch{return}}function Ve(e,t,n,o){async function r(f,i,m,s){if(!i.rules)return {allowed:true};let w=i.rules?.[m];if(!w)return {allowed:false,errorResponse:b(f,`Operation "${m}" is not allowed for this repository`,403)};try{let h=await w(s);return h===!1?{allowed:!1,errorResponse:b(f,"Forbidden",403)}:typeof h=="string"?{allowed:!1,errorResponse:b(f,h,403)}:typeof h=="object"&&h!==null&&!h.allowed?{allowed:!1,errorResponse:b(f,h.reason||"Forbidden",403)}:{allowed:!0}}catch(h){let x=n&&h instanceof Error?h.message:"Forbidden";return {allowed:false,errorResponse:b(f,x,403)}}}async function a(f,i,m,s){if(!f.rules)return s;let w=f.rules?.filter;if(!w)return s;let h=[];for(let x of s)try{await w({user:i,doc:x,params:m})&&h.push(x);}catch{}return h}function c(f){return f.get("user")??f.get("docsUser")??null}function d(f,i){if(!f){let m=i.req.path.split("/");for(let s of m)if(e[s]){f=s;break}}return !f||!e[f]?null:e[f]??null}function u(f,i){return Fe(f,{pathKey:i.pathKey,documentKey:i.documentKey,parentKeys:i.parentKeys,documentPathTemplate:i.documentPathTemplate,isGroup:i.isGroup})}async function l(f,i){let m=`by${f.documentKey.charAt(0).toUpperCase()}${f.documentKey.slice(1)}`,s=f.repo.get[m];if(typeof s=="function")try{let h=await s(i);if(h)return h}catch{}return (await f.repo.query.by({where:[[f.documentKey,"==",i]],limit:1}))[0]??null}async function g(f){let i=f.c,m=i.req.param(),s=d(m.repoName,i);if(!s)return b(i,"Repository not found",404);let w=c(i),h=await r(i,s,"list",{user:w,query:i.req.query(),params:m});if(!h.allowed)return h.errorResponse;let x=[],k;try{let p=i.req.query(),T=Math.min(Number(p.pageSize)||s.pageSize,100),C=p.cursor,q=p.direction?.toLowerCase()==="prev"?"prev":"next",O=p.orderBy,$=p.orderDir?.toLowerCase()==="desc"?"desc":"asc",j=p.select,N=j?j.split(",").map(M=>M.trim()):void 0,z=p.withTotal,A=z==="true"||z==="1"||z===!0,P;s.allowedIncludes&&p.includes&&(P=(typeof p.includes=="string"?p.includes.split(",").map(L=>L.trim()):Array.isArray(p.includes)?p.includes:[]).filter(L=>typeof L=="string"&&s.allowedIncludes.includes(L)),P?.length===0&&(P=void 0));let I=Nt(p,s.filterableFields);x=I.map(M=>({field:M.field,op:M.op,value:String(M.value??"")})),O&&(k={field:O,dir:$});let U={pageSize:T,direction:q,...A?{withTotal:!0}:{}};if(C)try{let M=typeof C=="string"?JSON.parse(C):C;U.cursor=await Le(s,M);}catch{}if(O){if(s.orderableFields&&!s.orderableFields.includes(O))return b(i,`Field not orderable: ${O}`,400);U.orderBy=[{field:O,direction:$}];}if(I.length>0){U.where=[];for(let M of I){let L=le(s.schema,M.field,M.value,M.op);if(!L.success)return b(i,`Invalid filter value for '${M.field}': ${L.error}`,400);U.where.push([M.field,M.op,L.data]);}}N&&(U.select=N),P&&(U.include=P);let Z=await s.repo.query.paginate(U),mt={items:await a(s,c(i),m,Z.data),hasNextPage:Z.hasNextPage,hasPrevPage:Z.hasPrevPage,nextCursor:fe(Z.nextCursor),prevCursor:fe(Z.prevCursor),...Z.totalCount!==void 0?{totalCount:Z.totalCount,totalCountIsExact:Z.totalCountIsExact}:{}};return W(i,mt,{pageSize:T,hasMore:Z.hasNextPage,...Z.totalCount!==void 0?{totalCount:Z.totalCount,totalCountIsExact:Z.totalCountIsExact}:{}})}catch(p){return await ke(i,p,{repoName:m.repoName||s.name,ref:s.repo.ref,path:s.path,isGroup:!!s.isGroup,filters:x,sort:k},"Failed to fetch documents",n,o)}}async function y(f){let i=f.c,m=i.req.param(),s=d(m.repoName,i);if(!s)return b(i,"Repository not found",404);let w=c(i),h=await r(i,s,"list",{user:w,query:f.input||{},params:m});if(!h.allowed)return h.errorResponse;let x=[],k;try{let p=f.input||{},T=Math.min(p.pageSize||s.pageSize,100),C=p.direction==="prev"?"prev":"next";p.where&&(x=p.where.map(z=>({field:String(z[0]),op:z[1],value:String(z[2]??"")}))),p.orderBy&&p.orderBy[0]&&(k={field:p.orderBy[0].field,dir:p.orderBy[0].direction==="desc"?"desc":"asc"});let q=p.withTotal===!0||String(p.withTotal)==="true",O={pageSize:T,direction:C,...q?{withTotal:!0}:{}};if(p.cursor)try{let z=typeof p.cursor=="string"?JSON.parse(p.cursor):p.cursor;O.cursor=await Le(s,z);}catch{}if(s.allowedIncludes&&p.includes&&p.includes.length>0){let z=p.includes.filter(A=>typeof A=="string"?s.allowedIncludes.includes(A):typeof A=="object"&&A!==null&&"relation"in A&&typeof A.relation=="string"?s.allowedIncludes.includes(A.relation):!1);z.length>0&&(O.include=z);}if(p.where&&p.where.length>0){if(s.filterableFields){let A=new Set(s.filterableFields),P=p.where.filter(I=>!A.has(I[0]));if(P.length>0){b(i,`Fields not filterable: ${P.map(I=>I[0]).join(", ")}`,400);return}}let z=[];for(let A of p.where){let P=ne(A[1]),I=le(s.schema,A[0],A[2],P);if(!I.success){b(i,`Invalid filter value for '${A[0]}': ${I.error}`,400);return}z.push([A[0],P,I.data]);}O.where=z;}if(p.orWhere&&p.orWhere.length>0){if(s.filterableFields){let A=new Set(s.filterableFields),P=p.orWhere.filter(I=>!A.has(I[0]));if(P.length>0){b(i,`Fields not filterable: ${P.map(I=>I[0]).join(", ")}`,400);return}}let z=[];for(let A of p.orWhere){let P=ne(A[1]),I=le(s.schema,A[0],A[2],P);if(!I.success){b(i,`Invalid filter value for '${A[0]}': ${I.error}`,400);return}z.push([A[0],P,I.data]);}O.orWhere=z;}if(p.orWhereGroups&&p.orWhereGroups.length>0){if(s.filterableFields){let A=new Set(s.filterableFields);for(let P of p.orWhereGroups){let I=P.filter(U=>!A.has(U[0]));if(I.length>0){b(i,`Fields not filterable: ${I.map(U=>U[0]).join(", ")}`,400);return}}}let z=[];for(let A of p.orWhereGroups){let P=[];for(let I of A){let U=ne(I[1]),Z=le(s.schema,I[0],I[2],U);if(!Z.success){b(i,`Invalid filter value for '${I[0]}': ${Z.error}`,400);return}P.push([I[0],U,Z.data]);}z.push(P);}O.orWhereGroups=z;}if(p.orderBy&&p.orderBy.length>0){if(s.orderableFields){let z=new Set(s.orderableFields),A=p.orderBy.filter(P=>!z.has(P.field));if(A.length>0){b(i,`Fields not orderable: ${A.map(P=>P.field).join(", ")}`,400);return}}O.orderBy=p.orderBy;}p.select&&p.select.length>0&&(O.select=p.select);let $=await s.repo.query.paginate(O),N={items:await a(s,c(i),m,$.data),hasNextPage:$.hasNextPage,hasPrevPage:$.hasPrevPage,nextCursor:fe($.nextCursor),prevCursor:fe($.prevCursor),...$.totalCount!==void 0?{totalCount:$.totalCount,totalCountIsExact:$.totalCountIsExact}:{}};return W(i,N,{pageSize:T,hasMore:$.hasNextPage,...$.totalCount!==void 0?{totalCount:$.totalCount,totalCountIsExact:$.totalCountIsExact}:{}})}catch(p){return await ke(i,p,{repoName:m.repoName||s.name,ref:s.repo.ref,path:s.path,isGroup:!!s.isGroup,filters:x,sort:k},"Failed to query documents",n,o)}}async function S(f){let i=f.c,m=i.req.param(),s=d(m.repoName,i);if(!s)return b(i,"Repository not found",404);let w=m.id;if(!w)return b(i,"Document ID required",400);try{let h=await l(s,w);if(!h)return b(i,"Document not found",404);let x=c(i),k=await r(i,s,"get",{user:x,doc:h,params:m});if(!k.allowed)return k.errorResponse;if(s.rules?.filter)try{if(!await s.rules.filter({user:x,doc:h,params:m}))return b(i,"Document not found",404)}catch{return b(i,"Document not found",404)}return W(i,h)}catch(h){return await ke(i,h,{repoName:m.repoName||s.name,ref:s.repo.ref,path:s.path,isGroup:!!s.isGroup,filters:[{field:s.documentKey,op:"==",value:w}]},"Failed to fetch document",n,o)}}async function E(f){let i=f.c,m=i.req.param(),s=d(m.repoName,i);if(!s)return b(i,"Repository not found",404);try{let w=f.input||{},h=c(i),x=await r(i,s,"create",{user:h,body:w,params:m});if(!x.allowed)return x.errorResponse;let k=pe(s.schema,w,s.createFields,!1,s.systemKeys);if(!k.success)return b(i,k.error,400);if(s.validate){let T=await s.validate(k.data,"create");if(T)return b(i,T,400)}let p;if(s.isGroup&&s.parentKeys&&s.parentKeys.length>0){let T={...k.data},C=s.parentKeys.filter(q=>T[q]===void 0||T[q]===null||typeof T[q]=="string"&&T[q].trim()==="");if(C.length>0){b(i,`Missing parent key(s) for subcollection create: ${C.join(", ")}`,400);return}if(typeof s.repo.create=="function")p=await s.repo.create(T);else {let q=s.parentKeys.map($=>String(T[$])),O=T[s.documentKey]||xe();p=await s.repo.set(...q,O,T);}}else p=await s.repo.create(k.data);return W(i,p,void 0,201)}catch(w){let h=n&&w instanceof Error?w.message:"Failed to create document";return b(i,h,500)}}async function F(f,i){let m=f.c,s=m.req.param(),w=d(s.repoName,m);if(!w)return b(m,"Repository not found",404);let h=s.id;if(!h)return b(m,"Document ID required",400);try{let x=f.input||{},k=await l(w,h);if(!k)return b(m,"Document not found",404);let p=pe(w.schema,x,w.mutableFields,i,w.systemKeys);if(!p.success)return b(m,p.error,400);if(w.validate){let j=await w.validate(p.data,"update");if(j)return b(m,j,400)}let T=ue(k,p.data),C=c(m),q=await r(m,w,"update",{user:C,doc:k,body:p.data,diff:T,params:s});if(!q.allowed)return q.errorResponse;let O=u(k,w)??[h],$=await w.repo.update(...O,p.data);return W(m,$)}catch(x){let k=n&&x instanceof Error?x.message:"Failed to update document";return b(m,k,500)}}async function v(f){let i=f.c,m=i.req.param(),s=d(m.repoName,i);if(!s)return b(i,"Repository not found",404);if(!s.allowDelete)return b(i,"Delete not allowed for this repository",403);let w=m.id;if(!w)return b(i,"Document ID required",400);try{let h=await l(s,w);if(!h)return b(i,"Document not found",404);let x=c(i),k=await r(i,s,"delete",{user:x,doc:h,params:m});if(!k.allowed)return k.errorResponse;let p=u(h,s)??[w];return await s.repo.delete(...p),W(i,{deleted:!0})}catch(h){let x=n&&h instanceof Error?h.message:"Failed to delete document";return b(i,x,500)}}function R(f){return f.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 D(f){let i=f.c,m=i.req.param(),s=d(m.repoName,i);if(!s)return b(i,"Repository not found",404);try{let w=f.input||{};if(!Array.isArray(w.operations))return b(i,"operations array is required",400);let h=c(i),x=s.repo.batch.create(),k=[];for(let p of w.operations){if(!p.type||!["create","update","delete"].includes(p.type))return b(i,"Invalid operation type",400);if(p.type==="create"){let T=await r(i,s,"create",{user:h,body:p.data,params:m});if(!T.allowed)return T.errorResponse;let C=pe(s.schema,p.data,s.createFields,!1,s.systemKeys);if(!C.success)return b(i,C.error,400);let q=p.data[s.documentKey]||xe(),O={...C.data};if(s.createdKey&&O[s.createdKey]===void 0&&(O[s.createdKey]=new Date),s.isGroup&&s.parentKeys){let $=s.parentKeys.map(j=>O[j]);x.set(...$,q,O);}else x.set(q,O);k.push({op:"create",id:q});}else if(p.type==="update"){if(!p.id)return b(i,"id required for update",400);let T=await l(s,p.id);if(!T)return b(i,`Document ${p.id} not found`,404);let C=pe(s.schema,p.data,s.mutableFields,!0,s.systemKeys);if(!C.success)return b(i,C.error,400);if(s.validate){let j=await s.validate(C.data,"update");if(j)return b(i,j,400)}let q=ue(T,C.data),O=await r(i,s,"update",{user:h,doc:T,body:C.data,diff:q,params:m});if(!O.allowed)return O.errorResponse;let $=u(T,s)??[p.id];x.update(...$,C.data),k.push({op:"update",id:p.id});}else if(p.type==="delete"){if(!s.allowDelete)return b(i,"Delete not allowed",403);if(!p.id)return b(i,"id required for delete",400);let T=await l(s,p.id);if(!T)return b(i,`Document ${p.id} not found`,404);let C=await r(i,s,"delete",{user:h,doc:T,params:m});if(!C.allowed)return C.errorResponse;let q=u(T,s)??[p.id];x.delete(...q),k.push({op:"delete",id:p.id});}}return await x.commit(),W(i,{results:k})}catch(w){let h=n&&w instanceof Error?w.message:"Batch operation failed";return b(i,h,500)}}return {handleList:g,handleQuery:y,handleGet:S,handleCreate:E,handleUpdate:F,handleDelete:v,handleBatch:D,handleOptions:R}}function ee(e){try{return z.toJSONSchema(e,{target:"openapi-3.1",unrepresentable:"any",override:t=>{let n=getOpenApiMetadata(t.zodSchema);n&&(Object.assign(t.jsonSchema,n),(t.jsonSchema.anyOf||t.jsonSchema.oneOf)&&delete t.jsonSchema.type);let 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 H(e){return {$ref:`#/components/schemas/${e}`}}function _(e){return {description:e,content:{"application/json":{schema:H("ErrorResponse")}}}}function Y(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 oe(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 Ht(e,t){let n=t.split("."),o=oe(e);for(let r=0;r<n.length;r++){let a=n[r];if(!a)continue;let c=o?.shape;if(!c||!c[a])return;let d=c[a];if(r===n.length-1)return d;o=oe(d);}return o}function X(e){let t=e?._zod?.def??e?._def,n=t?.typeName??t?.type,o=r=>{let a=getOpenApiMetadata(e);return a&&typeof r.openapi=="function"?r.openapi(a):r};if(n==="ZodObject"||n==="object"){let r=e.shape,a={};for(let[c,d]of Object.entries(r))a[c]=X(d);return o(z.object(a).partial())}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(!r)return e;let a=X(r);return a===r?e:o(a.optional())}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(!r)return e;let a=X(r);return a===r?e:o(a.nullable())}if(n==="ZodDefault"||n==="default"){let r=t.innerType;return r?o(X(r).optional()):e}if(n==="ZodUnion"||n==="union"){let r=t.options;if(!r||r.length<2)return e;let a=r.map(d=>X(d));return a.some((d,u)=>d!==r[u])?o(z.union(a)):e}return e}function Ce(e,t="",n=0){if(n>5)return [];let r=oe(e)?.shape;if(!r)return [];let a=[];for(let[c,d]of Object.entries(r)){let u=t?`${t}.${c}`:c,l=oe(d);l?.shape&&typeof l.shape=="object"?(a.push({path:u,zodSchema:d}),a.push(...Ce(l,u,n+1))):a.push({path:u,zodSchema:d});}return a}function Mt(e){return e.filterableFields&&e.filterableFields.length>0?e.filterableFields.map(t=>({path:t,zodSchema:Ht(e.schema,t)})):Ce(e.schema)}function Je(e){if(!e)return {type:"string"};let t=ee(e);return delete t.$schema,delete t.title,t}function Xe(){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 Bt(e){let t=Mt(e),n=e.orderableFields??t.map(c=>c.path),o=t.map(c=>c.path);if(t.length===0)return Xe();let r=[];for(let{path:c,zodSchema:d}of t){let u=Je(d),l=oe(d),y=l?._zod?.def?.type==="array"||l?._def?.typeName==="ZodArray"||l?._def?.type==="array"?Je(l?._zod?.def?.element??l?._def?.type??l?._def?.element):u;r.push({type:"array",description:`Condition on '${c}'`,prefixItems:[{type:"string",enum:[c]},{type:"string",enum:["==","!=","<","<=",">",">=","eq","ne","lt","lte","gt","gte"]},u],minItems:3,maxItems:3}),r.push({type:"array",description:`List condition on '${c}' (in, not-in)`,prefixItems:[{type:"string",enum:[c]},{type:"string",enum:["in","not-in","nin"]},{type:"array",items:u}],minItems:3,maxItems:3}),r.push({type:"array",description:`Array contains condition on '${c}'`,prefixItems:[{type:"string",enum:[c]},{type:"string",enum:["array-contains","contains"]},y],minItems:3,maxItems:3}),r.push({type:"array",description:`Array contains-any condition on '${c}'`,prefixItems:[{type:"string",enum:[c]},{type:"string",enum:["array-contains-any","containsAny"]},{type:"array",items:y}],minItems:3,maxItems:3});}let a={oneOf:r};return {type:"object",properties:{where:{type:"array",items:a,description:"AND conditions: [field, operator, value][]"},orWhere:{type:"array",items:a,description:"Simple OR conditions (each independently OR'd)"},orWhereGroups:{type:"array",items:{type:"array",items:a},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 Ut(e,t,n,o,r,a=null,c="QueryRequestBody"){let d={},u=e.name,l=`${t}/${e.name}`,g=`${l}/{${e.documentKey}}`,y={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};d[l]={post:{operationId:`create${G(e.name)}`,summary:`Create a ${K(e.name)}`,tags:[u],requestBody:{required:true,content:{"application/json":{schema:H(o??n)}}},responses:{201:Y("Document created",H(n)),400:_("Validation error"),403:_("Forbidden"),500:_("Internal server error")}}},d[`${l}/query`]={post:{operationId:`query${G(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[u],requestBody:{required:true,content:{"application/json":{schema:H(c)}}},responses:{200:Zt(H(n)),400:_("Invalid query"),403:_("Forbidden"),424:_("Missing composite index (includes indexUrl in response)"),500:_("Internal server error")}}},d[`${l}/batch`]={post:{operationId:`batch${G(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[u],requestBody:{required:true,content:{"application/json":{schema:H(`${n}BatchRequest`)}}},responses:{200:Y("Batch operations completed",{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{op:{type:"string"},id:{type:"string"}}}}}}),400:_("Validation error"),403:_("Forbidden"),404:_("Document not found"),500:_("Internal server error")}}};let S={};return S.get={operationId:`get${G(K(e.name))}`,summary:`Get a single ${K(e.name)}`,tags:[u],parameters:[y],responses:{200:Y("Document found",H(n)),400:_("Document ID required"),403:_("Forbidden"),404:_("Document not found"),424:_("Missing composite index (includes indexUrl in response)"),500:_("Internal server error")}},S.put={operationId:`update${G(K(e.name))}`,summary:`Update a ${K(e.name)} (full replace)`,tags:[u],parameters:[y],requestBody:{required:true,content:{"application/json":{schema:H(r??n)}}},responses:{200:Y("Document updated",H(n)),400:_("Validation error"),403:_("Forbidden"),404:_("Document not found"),500:_("Internal server error")}},S.patch={operationId:`patch${G(K(e.name))}`,summary:`Partially update a ${K(e.name)}`,tags:[u],parameters:[y],requestBody:{required:true,content:{"application/json":{schema:H(a??r??n)}}},responses:{200:Y("Document patched",H(n)),400:_("Validation error"),403:_("Forbidden"),404:_("Document not found"),500:_("Internal server error")}},e.allowDelete&&(S.delete={operationId:`delete${G(K(e.name))}`,summary:`Delete a ${K(e.name)}`,tags:[u],parameters:[y],responses:{200:Y("Document deleted",{type:"object",properties:{id:{type:"string"}}}),400:_("Document ID required"),403:_("Forbidden"),404:_("Document not found"),500:_("Internal server error")}}),d[g]=S,d}function Ee(e,t,n={}){let{title:o="CRUD API",version:r="1.0.0",description:a,servers:c,auth:d=false}=n,u=t==="/"?"":t.replace(/\/$/,""),l={},g={},y=[];l.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"]},l.QueryRequestBody=Xe();for(let[v,R]of Object.entries(e)){let D=G(K(v)),f=`${D}Create`,i=`${D}Update`,m=`${D}Patch`,s=`${D}QueryRequestBody`;l[D]=ee(R.schema),l[s]=Bt(R);let w=j=>{let N={},z=Ce(R.schema);for(let{path:A,zodSchema:P}of z){let I=A.split(".")[0];R.systemKeys.includes(I)||R.systemKeys.includes(A)||j&&j.length>0&&!j.includes(A)&&!j.includes(I)||(A.includes(".")?N[A]=P.optional():N[A]=P);}return N},h=null,x=w(R.createFields);if(R.isGroup&&R.parentKeys&&R.parentKeys.length>0){let j=R.schema?.shape??{};for(let N of R.parentKeys)!x[N]&&j[N]&&(x[N]=j[N]);}if(Object.keys(x).length>0){let j=ee(z.object(x));if(R.isGroup&&R.parentKeys&&R.parentKeys.length>0){let N=new Set(Array.isArray(j.required)?j.required:[]);for(let z of R.parentKeys)j.properties?.[z]&&N.add(z);N.size>0&&(j.required=Array.from(N));}l[f]=j,h=f;}let k=null,p=null,T=w(R.mutableFields);if(Object.keys(T).length>0){let j=z.object(T);l[i]=ee(j),k=i,l[m]=ee(X(j)),p=m;}else l[m]=ee(X(R.schema)),p=m;let C=`${D}BatchCreateOperation`,q=`${D}BatchUpdateOperation`,O=`${D}BatchDeleteOperation`;l[C]={type:"object",title:`${D} Create Operation`,properties:{type:{type:"string",enum:["create"],const:"create"},data:H(h??D)},required:["type","data"]},l[q]={type:"object",title:`${D} Update Operation`,properties:{type:{type:"string",enum:["update"],const:"update"},id:{type:"string"},data:H(p??k??D)},required:["type","id","data"]},R.allowDelete&&(l[O]={type:"object",title:`${D} Delete Operation`,properties:{type:{type:"string",enum:["delete"],const:"delete"},id:{type:"string"}},required:["type","id"]}),l[`${D}BatchRequest`]={type:"object",properties:{operations:{type:"array",items:{oneOf:[H(C),H(q),...R.allowDelete?[H(O)]:[]],discriminator:{propertyName:"type"}}}},required:["operations"]};let $=Ut(R,u,D,h,k,p,s);Object.assign(g,$),y.push({name:v,description:`Operations on ${v} (collection: ${R.path})`});}let S={},E;return d==="basic"?(S.basicAuth={type:"http",scheme:"basic"},E=[{basicAuth:[]}]):d==="bearer"&&(S.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},E=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:o,version:r,...a?{description:a}:{}},...c&&c.length>0?{servers:c}:{},paths:g,components:{schemas:l,...Object.keys(S).length>0?{securitySchemes:S}:{}},...E?{security:E}:{},tags:y}}function G(e){return e.charAt(0).toUpperCase()+e.slice(1)}function K(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 te=class extends Error{constructor(n,o){super("Request validation failed");this.zodError=n;this.source=o;this.statusCode=400;this.name="ValidationError";}};var se=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},ie=class extends Error{constructor(n){super("Output validation failed");this.zodError=n;this.statusCode=500;this.name="OutputValidationError";}};function Ye(e){return e.issues.map(t=>({path:t.path.join("."),code:t.code,message:t.message}))}function et(e,t){return t instanceof te?e.json({success:false,error:"Validation failed",issues:Ye(t.zodError)},400):t instanceof se?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof ie?e.json({success:false,error:"Output validation failed",issues:Ye(t.zodError)},500):null}extendZodWithOpenApi(z);var tt="Successful response",nt="Error response";function B(e,t=new Set){if(!e||typeof e!="object"||t.has(e))return;t.add(e);let n=e,o=n._zod?.def??n.def;if(!o)return;if(o.type==="custom"){let a=getOpenApiMetadata(n);a?.type||z.globalRegistry.add(n,{...a??{},type:"object"});return}if(o.innerType&&B(o.innerType,t),o.element&&B(o.element,t),o.valueType&&B(o.valueType,t),o.keyType&&B(o.keyType,t),o.left&&B(o.left,t),o.right&&B(o.right,t),o.in&&B(o.in,t),o.out&&B(o.out,t),typeof o.getter=="function")try{B(o.getter(),t);}catch{}if(Array.isArray(o.options))for(let a of o.options)B(a,t);if(Array.isArray(o.items))for(let a of o.items)B(a,t);let r=typeof o.shape=="function"?o.shape():o.shape;if(r&&typeof r=="object")for(let a of Object.values(r))B(a,t);}function Ie(e){if(!e||typeof e!="object")return;if(Array.isArray(e)){for(let n of e)Ie(n);return}let t=e;(Array.isArray(t.anyOf)||Array.isArray(t.oneOf))&&"type"in t&&delete t.type;for(let n of Object.values(t))Ie(n);}function Vt(e){return e==="get"?"query":"json"}function Jt(e,t){let n=t?.output;return n?typeof n=="function"?n(e):n:e}function Qt(e){if(typeof e.safeParse=="function")return {description:nt,schema:e};let t=e;return {description:t.description??nt,schema:t.schema}}function st(e,t,n,o){let r=new OpenAPIRegistry;if(n.securitySchemes)for(let[d,u]of Object.entries(n.securitySchemes))r.registerComponent("securitySchemes",d,u);for(let d of e){let u=d.method,l=d.source??Vt(u),g=en(t,d.path??"/"),y=d.status??200;d.input&&B(d.input);let S=Xt(u,l,d.input),E=rt(l,d.input,"query"),F=rt(l,d.input,"param"),v=tn(u,g),R=Jt(d.output,o);R&&B(R);let D={[y]:R?{description:tt,content:{"application/json":{schema:R}}}:{description:tt}};if(o?.errors)for(let[f,i]of Object.entries(o.errors)){let{description:m,schema:s}=Qt(i);s&&B(s),D[f]=s?{description:m,content:{"application/json":{schema:s}}}:{description:m};}r.registerPath({method:u,path:Yt(g),operationId:v,summary:d.summary,description:d.description,tags:d.tags,deprecated:d.deprecated,security:d.security,request:{...E?{query:E}:{},...F?{params:F}:{},...S?{body:S}:{}},responses:D});}let c=new OpenApiGeneratorV31(r.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security});return Ie(c),c}function Xt(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 rt(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function Yt(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function en(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,o=t.startsWith("/")?t:`/${t}`,r=`${n}${o}`;return r===""?"/":r}function tn(e,t){let n=t.replace(/[{}]/g,"").replace(/\/+/g,"_").replace(/[^A-Za-z0-9_]/g,"").replace(/^_+|_+$/g,"");return `${e}_${n||"root"}`}function it(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 @@ import {randomBytes}from'crypto';import {z}from'zod';import {Timestamp}from'fire
|
|
|
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 at(e){return typeof e=="object"&&e!==null&&e.__docsAuthExtension===true}var Pe=new AsyncLocalStorage;function ct(){return async(e,t)=>{await Pe.run({c:e},async()=>{await t();});}}var sn=Object.freeze({}),me=class{constructor(t){this.cachedSpec=null;this.options=t,this.app=new Hono,this.mountedRoutes=dn(t.routes,t.api),t.services&&this.app.use("*",ct());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 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=st(this.mountedRoutes,this.options.basePath??"",this.options.openapi,cn(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 a=ye(t,r.path),c=r.middlewares??[],d=r.source??(r.method==="get"?"query":"json"),u=ln(r,d,n,an(this.options.interceptor),this.options.services,this.options.errorHandler,this.options.logger),l=r.method.toUpperCase();this.app.on(l,[a],...c,u),o&&console.log(`[HonoServer] ${r.method.toUpperCase().padEnd(6)} ${a}`);}}mountOpenApi(){let t=this.options.openapi;if(!t)return;let n=t.path??"/openapi.json",o=t.docsPath===void 0?"/docs":t.docsPath,r=ye(this.options.basePath??"",n),a=o===false?null:ye(this.options.basePath??"",o),c;if(at(t.docsAuth)){let d=t.docsAuth;c=[d.middleware];let u=un(a??r);for(let l of d.routes)this.app.on(l.method,[ye(u,l.name)],l.handler);}else c=t.docsAuth?Array.isArray(t.docsAuth)?t.docsAuth:[t.docsAuth]:[];if(this.app.on("GET",[r],...c,d=>d.json(this.buildOpenApiSpec())),a){let d=pn(a,r);this.app.on("GET",[a],...c,u=>u.html(it(d,t.info.title)));}}};function dt(e){return typeof e=="object"&&e!==null&&typeof e.handler=="function"}function an(e){if(e)return dt(e)?e.handler:e}function cn(e){return dt(e)?e:void 0}function dn(e,t){return t?e.filter(n=>Array.isArray(n.api)?n.api.includes(t):n.api===t):e.slice()}function ye(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,o=t.startsWith("/")?t:`/${t}`,r=`${n}${o}`;return r===""?"/":r}function un(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function pn(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 a=n.length-r;return [...Array(a).fill(".."),...o.slice(r)].join("/")||"./"}function ln(e,t,n,o,r,a,c){let d=e.input,u=e.output,l=e.status??200,g=r??sn;return async y=>{let S=async v=>{if(a){let R=await a.handle({error:v,c:y,route:e,services:g,logger:c});if(R)return R}return et(y,v)},E=async()=>{let v,R;try{R=await fn(y,t,e.method);}catch(f){throw new se(f instanceof Error?f.message:String(f))}if(d){let f=d.safeParse(R);if(!f.success)throw new te(f.error,t);v=f.data;}else v=R;let D=await e.handler({input:v,c:y,services:g,errorHandler:a,logger:c});if(n&&u&&!(D instanceof Response)){let f=u.safeParse(D);if(!f.success)throw new ie(f.error);return f.data}return D},F;if(o)try{F=await o({next:E,route:e,c:y,services:g,errorHandler:a,logger:c});}catch(v){let R=await S(v);if(R)return R;throw v}else try{F=await E();}catch(v){let R=await S(v);if(R)return R;throw v}return F instanceof Response?F:y.json(F,l)}}async function fn(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 pr(e){let{basePath:t="/",repos:n,parseBody:o=true,securityHeaders:r,verbose:a=false,httpsOptions:c}=e,d=t==="/"?"":t.replace(/\/$/,""),u={};for(let[f,i]of Object.entries(n)){if(!i.repo)throw new Error(`[createCrudServer] Repository "${f}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let m=i.schema??i.repo.schema??null;if(!m)throw new Error(`[createCrudServer] Repository "${f}" has no Zod schema.`);let s,w,h,x;if(i.fieldsConfig){let T=i.fieldsConfig;s=[],w=[],h=[],x=[];for(let[C,q]of Object.entries(T))for(let O of q)O==="filterable"?s.push(C):O==="orderable"?w.push(C):O==="mutable"?h.push(C):O==="create"&&x.push(C);w.length===0&&(w=s),s.length===0&&(s=void 0),w&&w.length===0&&(w=void 0),h.length===0&&(h=void 0),x.length===0&&(x=void 0);}let k=(()=>{let T=i.repo._parentKeys;return T&&T.length>0?T:void 0})();if(k&&x)for(let T of k)x.includes(T)||x.push(T);let p={name:f,path:i.path,repo:i.repo,schema:m,systemKeys:i.repo._systemKeys??[i.documentKey??"docId"],documentKey:i.documentKey??"docId",pathKey:i.repo._pathKey??void 0,isGroup:!!i.repo._isGroup,parentKeys:k,documentPathTemplate:i.repo._documentPathTemplate??void 0,createdKey:i.repo._createdKey??void 0,pageSize:i.pageSize??25,filterableFields:s,orderableFields:w,mutableFields:h,createFields:x,allowDelete:i.allowDelete??false,allowedIncludes:i.allowedIncludes,validate:i.validate,rules:i.rules};u[f]=p;}let l=e.indexesError??e.onIndexError,g=Ve(u,d,a,l),y=e.openapi,S=y&&typeof y=="object"?y:{},E=null;function F(){return E||(E=Ee(u,d,{...S,auth:S.auth??false})),E}let v=[];for(let f of Object.keys(u))v.push({api:"crud",method:"post",path:`/${f}/query`,source:"json",handler:g.handleQuery}),v.push({api:"crud",method:"get",path:`/${f}/:id`,source:"query",handler:g.handleGet}),v.push({api:"crud",method:"post",path:`/${f}`,source:"json",handler:g.handleCreate}),v.push({api:"crud",method:"put",path:`/${f}/:id`,source:"json",handler:i=>g.handleUpdate(i,false)}),v.push({api:"crud",method:"patch",path:`/${f}/:id`,source:"json",handler:i=>g.handleUpdate(i,true)}),v.push({api:"crud",method:"delete",path:`/${f}/:id`,source:"query",handler:g.handleDelete}),v.push({api:"crud",method:"post",path:`/${f}/batch`,source:"json",handler:g.handleBatch});let R=new me({...e,openapi:y!==false?{path:S.path??"/openapi.json",docsPath:S.docsPath??"/docs",info:{title:S.title??"CRUD API",version:S.version??"1.0.0"},docsAuth:S.docsAuth}:void 0,basePath:t,api:"crud",routes:v,middlewares:[async(f,i)=>{if(f.req.method==="OPTIONS")return f.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"});f.header("Access-Control-Allow-Origin","*"),f.header("Access-Control-Allow-Credentials","true"),await i();},...e.middlewares||[]]});if(y!==false&&(R.buildOpenApiSpec=F),r!==false){let{securityHeaders:f}=(yt(),Rt(ft)),i=r===void 0?{csp:false}:r;R.hono.use("*",async(m,s)=>{let w=f(i);await new Promise(h=>{let x=m.req.raw;w(x,{setHeader:(p,T)=>m.header(p,T),removeHeader:p=>m.res.headers.delete(p)},()=>h());}),await s();});}let D=R.nodeHandler;return D.spec=F,c&&(D.httpsOptions=c),D}export{Ue as applyRules,ue as computeDeepDiff,qt as createBeforeRules,pr as createCrudServer,_t as createRules,Ee as generateOpenAPISpec};//# sourceMappingURL=index.js.map
|
|
13
13
|
//# sourceMappingURL=index.js.map
|