hono-crud 0.13.1 → 0.13.2

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/CHANGELOG.md CHANGED
@@ -16,6 +16,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
16
16
  %b
17
17
  %b
18
18
  %b
19
+ %b
19
20
  ## [0.8.0] — 2026-05-03
20
21
 
21
22
  ### Added
@@ -97,3 +98,4 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
97
98
  [0.12.5]: https://github.com/kshdotdev/hono-crud/compare/v0.12.4...v0.12.5
98
99
  [0.13.0]: https://github.com/kshdotdev/hono-crud/compare/v0.12.5...v0.13.0
99
100
  [0.13.1]: https://github.com/kshdotdev/hono-crud/compare/v0.13.0...v0.13.1
101
+ [0.13.2]: https://github.com/kshdotdev/hono-crud/compare/v0.13.1...v0.13.2
@@ -346,6 +346,20 @@ declare abstract class DrizzleDeleteEndpoint<E extends Env = Env, M extends Meta
346
346
  declare abstract class DrizzleListEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends ListEndpoint<E, M> {
347
347
  /** Drizzle database instance */
348
348
  db?: DrizzleDatabase;
349
+ /**
350
+ * SQL dialect of the underlying Drizzle database.
351
+ *
352
+ * Drives the substring-match function emitted on the `?search=` path:
353
+ * `INSTR` for sqlite, `POSITION` for pg, `LOCATE` for mysql — matching
354
+ * how the dedicated search endpoint (`DrizzleSearchEndpoint`) and the
355
+ * export endpoint (`DrizzleExportEndpoint`) emit search SQL. Set via
356
+ * {@link createDrizzleCrud}'s `options.dialect`, or override in your
357
+ * subclass. Defaults to `'sqlite'` for backward compatibility with
358
+ * pre-existing portable behavior.
359
+ *
360
+ * See {@link DrizzleUpsertEndpoint.dialect} for full semantics.
361
+ */
362
+ protected dialect: DrizzleDialect;
349
363
  /** Gets the database instance from property or context */
350
364
  protected getDb(): DrizzleDatabase;
351
365
  protected getTable(): Table;
@@ -1 +1 @@
1
- export{J as DrizzleAdapters,y as DrizzleAggregateEndpoint,n as DrizzleBatchCreateEndpoint,p as DrizzleBatchDeleteEndpoint,q as DrizzleBatchRestoreEndpoint,o as DrizzleBatchUpdateEndpoint,t as DrizzleBatchUpsertEndpoint,C as DrizzleCloneEndpoint,h as DrizzleCreateEndpoint,k as DrizzleDeleteEndpoint,A as DrizzleExportEndpoint,B as DrizzleImportEndpoint,l as DrizzleListEndpoint,i as DrizzleReadEndpoint,m as DrizzleRestoreEndpoint,z as DrizzleSearchEndpoint,j as DrizzleUpdateEndpoint,s as DrizzleUpsertEndpoint,w as DrizzleVersionCompareEndpoint,u as DrizzleVersionHistoryEndpoint,v as DrizzleVersionReadEndpoint,x as DrizzleVersionRollbackEndpoint,f as batchLoadDrizzleRelations,g as buildWhereCondition,a as cast,D as createDrizzleCrud,H as createDrizzleSchemas,F as createInsertSchema,E as createSelectSchema,G as createUpdateSchema,c as getColumn,b as getTable,I as isDrizzleZodAvailable,d as loadDrizzleRelation,e as loadDrizzleRelations,r as substringMatch}from'../../chunk-DJOJGLOT.js';import'../../chunk-ZBCVLQ3W.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-XI7HT5ZM.js';import'../../chunk-NGUMNUOP.js';import'../../chunk-FC56WWPB.js';import'../../chunk-FJCWFB5L.js';import'../../chunk-KUFOENSK.js';import'../../chunk-GBQQ3YQX.js';import'../../chunk-QRXEQTNE.js';import'../../chunk-QXFY6NYI.js';import'../../chunk-DMGP7QDL.js';import'../../chunk-MDHMZPXK.js';import'../../chunk-VJRDAVID.js';
1
+ export{J as DrizzleAdapters,o as DrizzleAggregateEndpoint,z as DrizzleBatchCreateEndpoint,B as DrizzleBatchDeleteEndpoint,C as DrizzleBatchRestoreEndpoint,A as DrizzleBatchUpdateEndpoint,j as DrizzleBatchUpsertEndpoint,s as DrizzleCloneEndpoint,t as DrizzleCreateEndpoint,w as DrizzleDeleteEndpoint,q as DrizzleExportEndpoint,r as DrizzleImportEndpoint,x as DrizzleListEndpoint,u as DrizzleReadEndpoint,y as DrizzleRestoreEndpoint,p as DrizzleSearchEndpoint,v as DrizzleUpdateEndpoint,i as DrizzleUpsertEndpoint,m as DrizzleVersionCompareEndpoint,k as DrizzleVersionHistoryEndpoint,l as DrizzleVersionReadEndpoint,n as DrizzleVersionRollbackEndpoint,f as batchLoadDrizzleRelations,g as buildWhereCondition,a as cast,D as createDrizzleCrud,H as createDrizzleSchemas,F as createInsertSchema,E as createSelectSchema,G as createUpdateSchema,c as getColumn,b as getTable,I as isDrizzleZodAvailable,d as loadDrizzleRelation,e as loadDrizzleRelations,h as substringMatch}from'../../chunk-HRAGVQWS.js';import'../../chunk-V4YEHNEZ.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-XI7HT5ZM.js';import'../../chunk-NGUMNUOP.js';import'../../chunk-FJCWFB5L.js';import'../../chunk-FC56WWPB.js';import'../../chunk-KUFOENSK.js';import'../../chunk-GBQQ3YQX.js';import'../../chunk-QRXEQTNE.js';import'../../chunk-QXFY6NYI.js';import'../../chunk-DMGP7QDL.js';import'../../chunk-MDHMZPXK.js';import'../../chunk-VJRDAVID.js';
@@ -1 +1 @@
1
- export{f as MEMORY_NOOP_TX,x as MemoryAggregateEndpoint,m as MemoryBatchCreateEndpoint,o as MemoryBatchDeleteEndpoint,p as MemoryBatchRestoreEndpoint,n as MemoryBatchUpdateEndpoint,q as MemoryBatchUpsertEndpoint,B as MemoryBulkPatchEndpoint,r as MemoryCloneEndpoint,g as MemoryCreateEndpoint,j as MemoryDeleteEndpoint,z as MemoryExportEndpoint,A as MemoryImportEndpoint,k as MemoryListEndpoint,h as MemoryReadEndpoint,l as MemoryRestoreEndpoint,y as MemorySearchEndpoint,i as MemoryUpdateEndpoint,s as MemoryUpsertEndpoint,v as MemoryVersionCompareEndpoint,t as MemoryVersionHistoryEndpoint,u as MemoryVersionReadEndpoint,w as MemoryVersionRollbackEndpoint,d as clearStorage,e as getStorage,c as getStore,b as storage}from'../../chunk-BXWKFJXP.js';import'../../chunk-ZBCVLQ3W.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-XI7HT5ZM.js';import'../../chunk-NGUMNUOP.js';import'../../chunk-FC56WWPB.js';import'../../chunk-FJCWFB5L.js';import'../../chunk-KUFOENSK.js';import'../../chunk-GBQQ3YQX.js';import'../../chunk-QRXEQTNE.js';import'../../chunk-QXFY6NYI.js';import'../../chunk-DMGP7QDL.js';import'../../chunk-MDHMZPXK.js';import'../../chunk-VJRDAVID.js';
1
+ export{f as MEMORY_NOOP_TX,x as MemoryAggregateEndpoint,m as MemoryBatchCreateEndpoint,o as MemoryBatchDeleteEndpoint,p as MemoryBatchRestoreEndpoint,n as MemoryBatchUpdateEndpoint,q as MemoryBatchUpsertEndpoint,B as MemoryBulkPatchEndpoint,r as MemoryCloneEndpoint,g as MemoryCreateEndpoint,j as MemoryDeleteEndpoint,z as MemoryExportEndpoint,A as MemoryImportEndpoint,k as MemoryListEndpoint,h as MemoryReadEndpoint,l as MemoryRestoreEndpoint,y as MemorySearchEndpoint,i as MemoryUpdateEndpoint,s as MemoryUpsertEndpoint,v as MemoryVersionCompareEndpoint,t as MemoryVersionHistoryEndpoint,u as MemoryVersionReadEndpoint,w as MemoryVersionRollbackEndpoint,d as clearStorage,e as getStorage,c as getStore,b as storage}from'../../chunk-UU7V63VS.js';import'../../chunk-V4YEHNEZ.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-XI7HT5ZM.js';import'../../chunk-NGUMNUOP.js';import'../../chunk-FJCWFB5L.js';import'../../chunk-FC56WWPB.js';import'../../chunk-KUFOENSK.js';import'../../chunk-GBQQ3YQX.js';import'../../chunk-QRXEQTNE.js';import'../../chunk-QXFY6NYI.js';import'../../chunk-DMGP7QDL.js';import'../../chunk-MDHMZPXK.js';import'../../chunk-VJRDAVID.js';
@@ -1 +1 @@
1
- export{y as PrismaAdapters,w as PrismaAggregateEndpoint,j as PrismaBatchCreateEndpoint,l as PrismaBatchDeleteEndpoint,m as PrismaBatchRestoreEndpoint,k as PrismaBatchUpdateEndpoint,n as PrismaBatchUpsertEndpoint,x as PrismaCloneEndpoint,d as PrismaCreateEndpoint,g as PrismaDeleteEndpoint,p as PrismaExportEndpoint,q as PrismaImportEndpoint,h as PrismaListEndpoint,e as PrismaReadEndpoint,i as PrismaRestoreEndpoint,o as PrismaSearchEndpoint,f as PrismaUpdateEndpoint,r as PrismaUpsertEndpoint,u as PrismaVersionCompareEndpoint,s as PrismaVersionHistoryEndpoint,t as PrismaVersionReadEndpoint,v as PrismaVersionRollbackEndpoint,c as clearPrismaModelMappings,a as registerPrismaModelMapping,b as registerPrismaModelMappings}from'../../chunk-FOTF3T22.js';import'../../chunk-ZBCVLQ3W.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-XI7HT5ZM.js';import'../../chunk-NGUMNUOP.js';import'../../chunk-FC56WWPB.js';import'../../chunk-FJCWFB5L.js';import'../../chunk-KUFOENSK.js';import'../../chunk-GBQQ3YQX.js';import'../../chunk-QRXEQTNE.js';import'../../chunk-QXFY6NYI.js';import'../../chunk-DMGP7QDL.js';import'../../chunk-MDHMZPXK.js';import'../../chunk-VJRDAVID.js';
1
+ export{y as PrismaAdapters,w as PrismaAggregateEndpoint,j as PrismaBatchCreateEndpoint,l as PrismaBatchDeleteEndpoint,m as PrismaBatchRestoreEndpoint,k as PrismaBatchUpdateEndpoint,n as PrismaBatchUpsertEndpoint,x as PrismaCloneEndpoint,d as PrismaCreateEndpoint,g as PrismaDeleteEndpoint,p as PrismaExportEndpoint,q as PrismaImportEndpoint,h as PrismaListEndpoint,e as PrismaReadEndpoint,i as PrismaRestoreEndpoint,o as PrismaSearchEndpoint,f as PrismaUpdateEndpoint,r as PrismaUpsertEndpoint,u as PrismaVersionCompareEndpoint,s as PrismaVersionHistoryEndpoint,t as PrismaVersionReadEndpoint,v as PrismaVersionRollbackEndpoint,c as clearPrismaModelMappings,a as registerPrismaModelMapping,b as registerPrismaModelMappings}from'../../chunk-ZAVXHUKP.js';import'../../chunk-V4YEHNEZ.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-XI7HT5ZM.js';import'../../chunk-NGUMNUOP.js';import'../../chunk-FJCWFB5L.js';import'../../chunk-FC56WWPB.js';import'../../chunk-KUFOENSK.js';import'../../chunk-GBQQ3YQX.js';import'../../chunk-QRXEQTNE.js';import'../../chunk-QXFY6NYI.js';import'../../chunk-DMGP7QDL.js';import'../../chunk-MDHMZPXK.js';import'../../chunk-VJRDAVID.js';
@@ -1 +1 @@
1
- export{b as KVCacheStorage,a as RedisCacheStorage}from'../chunk-H3H65KZF.js';export{C as MemoryCacheStorage,y as createInvalidationPattern,z as createRelatedPatterns,x as generateCacheKey,E as getCacheStorage,A as matchesPattern,B as parseCacheKey,D as setCacheStorage,F as withCache,G as withCacheInvalidation}from'../chunk-UANCAA7V.js';import'../chunk-NGUMNUOP.js';import'../chunk-GF2EC5G4.js';import'../chunk-2M5BM4VD.js';import'../chunk-FC56WWPB.js';import'../chunk-FJCWFB5L.js';import'../chunk-KUFOENSK.js';import'../chunk-GBQQ3YQX.js';import'../chunk-DMGP7QDL.js';import'../chunk-MDHMZPXK.js';import'../chunk-VJRDAVID.js';
1
+ export{b as KVCacheStorage,a as RedisCacheStorage}from'../chunk-H3H65KZF.js';export{C as MemoryCacheStorage,y as createInvalidationPattern,z as createRelatedPatterns,x as generateCacheKey,E as getCacheStorage,A as matchesPattern,B as parseCacheKey,D as setCacheStorage,F as withCache,G as withCacheInvalidation}from'../chunk-IPMPKM4J.js';import'../chunk-NGUMNUOP.js';import'../chunk-GF2EC5G4.js';import'../chunk-FJCWFB5L.js';import'../chunk-2M5BM4VD.js';import'../chunk-FC56WWPB.js';import'../chunk-KUFOENSK.js';import'../chunk-GBQQ3YQX.js';import'../chunk-DMGP7QDL.js';import'../chunk-MDHMZPXK.js';import'../chunk-VJRDAVID.js';
@@ -0,0 +1,4 @@
1
+ import {A as A$1,F as F$1,G as G$1,H as H$1,I as I$1,J as J$1,K as K$1,L as L$1,T,U as U$1,ba,ca,y,t,u,v,w,x,z as z$1,B as B$1,C,D as D$1,E}from'./chunk-V4YEHNEZ.js';import {b as b$1}from'./chunk-DMGP7QDL.js';import {getTableColumns,eq,inArray,between,isNull,isNotNull,ilike,like,notInArray,lte,lt as lt$1,gte,gt,ne as ne$1,sql,and,or,desc,asc}from'drizzle-orm';import {z}from'zod';function X(a){return a}function f(a){if(!a.model.table)throw new Error(`Model ${a.model.tableName} does not have a table reference`);return a.model.table}function b(a,e){let t=getTableColumns(a),o=t[e];if(!o)throw new Error(`Column '${e}' not found in table. Available columns: ${Object.keys(t).join(", ")}`);return o}async function Ue(a,e,t,o){if(!o.table)return e;let n=o.table;switch(o.type){case "hasOne":{let r=o.localKey||"id",s=e[r];if(s==null)return e;let i=b(n,o.foreignKey),l=await a.select().from(n).where(eq(i,s)).limit(1);return {...e,[t]:l[0]||null}}case "hasMany":{let r=o.localKey||"id",s=e[r];if(s==null)return {...e,[t]:[]};let i=b(n,o.foreignKey),l=await a.select().from(n).where(eq(i,s));return {...e,[t]:l}}case "belongsTo":{let r=e[o.foreignKey];if(r==null)return {...e,[t]:null};let s=b(n,o.localKey||"id"),i=await a.select().from(n).where(eq(s,r)).limit(1);return {...e,[t]:i[0]||null}}default:return e}}async function ce(a,e,t,o){if(!o?.relations?.length||!t.model.relations)return e;let n={...e};for(let r of o.relations){let s=t.model.relations[r];s&&(n=await Ue(a,n,r,s));}return n}async function S(a,e,t,o){if(!e.length||!o?.relations?.length||!t.model.relations)return e;let n=e.map(r=>({...r}));for(let r of o.relations){let s=t.model.relations[r];if(!s||!s.table)continue;let i=s.table;switch(s.type){case "hasOne":case "hasMany":{let l=s.localKey||"id",d=[...new Set(n.map(p=>p[l]).filter(p=>p!=null))];if(d.length===0){n=n.map(p=>({...p,[r]:s.type==="hasMany"?[]:null}));continue}let u=b(i,s.foreignKey),c=await a.select().from(i).where(inArray(u,d)),m=new Map;for(let p of c){let g=p[s.foreignKey];m.has(g)||m.set(g,[]),m.get(g).push(p);}n=n.map(p=>{let g=p[l],h=m.get(g)||[];return {...p,[r]:s.type==="hasMany"?h:h[0]||null}});break}case "belongsTo":{let l=s.localKey||"id",d=[...new Set(n.map(p=>p[s.foreignKey]).filter(p=>p!=null))];if(d.length===0){n=n.map(p=>({...p,[r]:null}));continue}let u=b(i,l),c=await a.select().from(i).where(inArray(u,d)),m=new Map;for(let p of c){let g=p[l];m.set(g,p);}n=n.map(p=>{let g=p[s.foreignKey];return {...p,[r]:m.get(g)||null}});break}}}return n}function O(a,e){let t=b(a,e.field);switch(e.operator){case "eq":return eq(t,e.value);case "ne":return ne$1(t,e.value);case "gt":return gt(t,e.value);case "gte":return gte(t,e.value);case "lt":return lt$1(t,e.value);case "lte":return lte(t,e.value);case "in":return inArray(t,e.value);case "nin":return notInArray(t,e.value);case "like":return like(t,e.value);case "ilike":return ilike(t,e.value);case "null":return e.value?isNull(t):isNotNull(t);case "between":{let[o,n]=e.value;return between(t,o,n)}default:return}}function D(a){let e=a;if(e._tx)return e._tx;if(e.db)return e.db;let t=e.context?.get?.("db");if(t)return t;throw new Error(`Database not configured. Either:
2
+ 1. Set db property: db = myDb;
3
+ 2. Use middleware: c.set("db", myDb);
4
+ 3. Use factory: createDrizzleCrud(db, meta)`)}function ee(a,e,t){switch(t){case "pg":return sql`POSITION(LOWER(${e}) IN LOWER(${a})) > 0`;case "mysql":return sql`LOCATE(LOWER(${e}), LOWER(${a})) > 0`;default:return sql`INSTR(LOWER(${a}), LOWER(${e})) > 0`}}function lt(a){return a.split(/\s+/).filter(e=>e.length>0)}var j=class extends A$1{db;dialect="sqlite";getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async findExisting(e){let t=this.getTable(),o=this.getUpsertKeys(),n=this.getSoftDeleteConfig(),r=[];for(let i of o){let l=e[i];l!==void 0&&r.push(eq(this.getColumn(i),l));}return n.enabled&&r.push(isNull(this.getColumn(n.field))),r.length===0?null:(await this.getDb().select().from(t).where(and(...r)).limit(1))[0]||null}async create(e){let t=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(t).values(o).returning())[0]}async update(e,t){let o=this.getTable(),n=this._meta.model.primaryKeys[0],r=e[n];return (await this.getDb().update(o).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(n),r)).returning())[0]}async nativeUpsert(e,t){let o=this.getTable(),n=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s=this.getSoftDeleteConfig(),i=this.getTimestampsConfig(),l=this.applyManagedInsertFields(e,"drizzle"),d={};for(let[h,y]of Object.entries(e))!n.includes(h)&&h!==r&&(this.createOnlyFields?.includes(h)||(d[h]=y));i.enabled&&(d[i.updatedAt]=Date.now());let u=n.map(h=>this.getColumn(h)),c;s.enabled&&(c=isNull(this.getColumn(s.field)));let m=Object.keys(d).length>0?d:{[r]:sql`${this.getColumn(r)}`},p=this.getDb().insert(o).values(l);return this.dialect==="mysql"?{data:(await p.onDuplicateKeyUpdate({set:m}).returning())[0],created:false}:{data:(await p.onConflictDoUpdate({target:u,set:m,where:c}).returning())[0],created:false}}},_=class extends F$1{db;dialect="sqlite";getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async findExisting(e){let t=this.getTable(),o=this.getUpsertKeys(),n=[];for(let s of o){let i=e[s];i!==void 0&&n.push(eq(this.getColumn(s),i));}return n.length===0?null:(await this.getDb().select().from(t).where(and(...n)).limit(1))[0]||null}async create(e){let t=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(t).values(o).returning())[0]}async update(e,t){let o=this.getTable(),n=this._meta.model.primaryKeys[0],r=e[n];return (await this.getDb().update(o).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(n),r)).returning())[0]}async nativeBatchUpsert(e,t){if(e.length===0)return {items:[],createdCount:0,updatedCount:0,totalCount:0};let o=this.getTable(),n=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s=this.getTimestampsConfig(),i=e.map(g=>this.applyManagedInsertFields(g,"drizzle")),l={},d=e[0];for(let g of Object.keys(d))!n.includes(g)&&g!==r&&(this.createOnlyFields?.includes(g)||(l[g]=sql`excluded.${sql.identifier(g)}`));s.enabled&&(l[s.updatedAt]=Date.now());let u=n.map(g=>this.getColumn(g)),c=Object.keys(l).length>0?l:{[r]:sql`${this.getColumn(r)}`},m=this.getDb().insert(o).values(i),p=await(this.dialect==="mysql"?m.onDuplicateKeyUpdate({set:c}):m.onConflictDoUpdate({target:u,set:c})).returning();return {items:p.map((g,h)=>({data:g,created:false,index:h})),createdCount:0,updatedCount:p.length,totalCount:p.length}}},Be=class extends G$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async recordExists(e){let t=this.getTable(),o=await this.getDb().select({count:sql`count(*)`}).from(t).where(eq(this.getColumn("id"),e));return Number(o[0]?.count)>0}},Ae=class extends H$1{},Le=class extends I$1{},Ke=class extends J$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async rollback(e,t,o){let n=this.getTable(),r=this.getVersioningConfig().field;return (await this.getDb().update(n).set({...t,[r]:o}).where(eq(this.getColumn("id"),e)).returning())[0]}},G=class extends K$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async aggregate(e){let t=this.getTable(),o=[],n=this.getSoftDeleteConfig();if(n.enabled){let{query:i}=await this.getValidatedData();i?.withDeleted===true||i?.withDeleted==="true"||o.push(isNull(this.getColumn(n.field)));}if(e.filters)for(let[i,l]of Object.entries(e.filters))if(typeof l=="object"&&l!==null)for(let[d,u]of Object.entries(l)){let c=O(t,{field:i,operator:d,value:u});c&&o.push(c);}else o.push(eq(this.getColumn(i),l));let r=o.length>0?and(...o):void 0,s=await this.getDb().select().from(t).where(r);return L$1(s,e)}},I=class extends T{db;dialect="sqlite";getDb(){return D(this)}useNativeSearch=false;vectorColumn;vectorConfig="english";getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async search(e,t){let o=this.getTable(),n=[],r=this.getSoftDeleteConfig();r.enabled&&(t.options.onlyDeleted?n.push(isNotNull(this.getColumn(r.field))):t.options.withDeleted||n.push(isNull(this.getColumn(r.field))));for(let w of t.filters){let M=O(o,w);M&&n.push(M);}let s=this.getSearchableFields(),i=e.fields||Object.keys(s);if(this.useNativeSearch&&this.vectorColumn){let w=this.getColumn(this.vectorColumn),M=e.mode==="phrase"?sql`phraseto_tsquery(${this.vectorConfig}, ${e.query})`:e.mode==="all"?sql`plainto_tsquery(${this.vectorConfig}, ${e.query})`:sql`to_tsquery(${this.vectorConfig}, ${e.query.split(/\s+/).join(" | ")})`;n.push(sql`${w} @@ ${M}`);}else {let w=(M,x)=>{try{let ie=this.getColumn(M);return ee(sql`CAST(${ie} AS TEXT)`,x,this.dialect)}catch{return}};if(e.mode==="all"){let M=lt(e.query);if(M.length>0){let x=[];for(let ie of M){let pe=i.map(ae=>w(ae,ie)).filter(ae=>ae!==void 0);pe.length>0&&x.push(or(...pe));}x.length>0&&n.push(and(...x));}}else {let M=i.map(x=>w(x,e.query)).filter(x=>x!==void 0);M.length>0&&n.push(or(...M));}}let l=n.length>0?and(...n):void 0,d=await this.getDb().select({count:sql`count(*)`}).from(o).where(l),u=Number(d[0]?.count)||0,c=this.getDb().select().from(o).where(l);if(t.options.order_by){let w=this.getColumn(t.options.order_by),M=t.options.order_by_direction==="desc"?desc:asc;c=c.orderBy(M(w));}let m=t.options.page||1,p=t.options.per_page||this.defaultPerPage;c=c.limit(p).offset((m-1)*p);let g=await c,h=e.mode==="all"?{...e,mode:"any"}:e,y=U$1(g,h,s),R={relations:t.options.include||[]},$=y.map(w=>w.item),se=await S(this.getDb(),$,this._meta,R);return {items:y.map((w,M)=>({...w,item:se[M]})),totalCount:u}}},H=class extends ba{db;dialect="sqlite";getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async list(e){let t=this.getTable(),o=[],n=this.getSoftDeleteConfig();if(n.enabled){let h=this.getColumn(n.field);e.options.onlyDeleted?o.push(isNotNull(h)):e.options.withDeleted||o.push(isNull(h));}for(let h of e.filters){let y=O(t,h);y&&o.push(y);}if(e.options.search&&this.searchFields.length>0){let h=e.options.search,y=this.searchFields.map(R=>{let $=this.getColumn(R);return ee($,h,this.dialect)});o.push(or(...y));}let r=o.length>0?and(...o):void 0,s=await this.getDb().select({count:sql`count(*)`}).from(t).where(r),i=Number(s[0]?.count)||0,l=this.getDb().select().from(t).where(r);if(e.options.order_by){let h=this.getColumn(e.options.order_by),y=e.options.order_by_direction==="desc"?desc:asc;l=l.orderBy(y(h));}let d=e.options.page||1,u=e.options.per_page||this.defaultPerPage;l=l.limit(u).offset((d-1)*u);let c=await l,m={relations:e.options.include||[]},p=await S(this.getDb(),c,this._meta,m),g=Math.ceil(i/u);return {result:p,result_info:{page:d,per_page:u,total_count:i,total_pages:g,has_next_page:d<g,has_prev_page:d>1}}}},J=class extends ca{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async findExisting(e){let t=this.getTable(),o=this.getUpsertKeys(),n=this.getSoftDeleteConfig(),r=[];for(let i of o){let l=e[i];l!==void 0&&r.push(eq(this.getColumn(i),l));}return n.enabled&&r.push(isNull(this.getColumn(n.field))),r.length===0?null:(await this.getDb().select().from(t).where(and(...r)).limit(1))[0]||null}async create(e){let t=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(t).values(o).returning())[0]}async update(e,t){let o=this.getTable(),n=this._meta.model.primaryKeys[0],r=e[n];return (await this.getDb().update(o).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(n),r)).returning())[0]}},Y=class extends y{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}generateId(){return crypto.randomUUID()}async findSource(e,t){let o=this.getTable(),n=this.getColumn(this.lookupField),r=this.getSoftDeleteConfig(),s=[eq(n,e)];if(t)for(let[l,d]of Object.entries(t))s.push(eq(this.getColumn(l),d));r.enabled&&s.push(isNull(this.getColumn(r.field)));let i=await this.getDb().select().from(o).where(and(...s)).limit(1);return i[0]?i[0]:null}async createClone(e){let t=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle",()=>this.generateId());return (await this.getDb().insert(t).values(o).returning())[0]}};var U=class extends t{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getRelatedTable(e){return e.table}async create(e,t){let o=t??this.getDb(),n=this.getTable(),r=this.applyManagedInsertFields(e,"drizzle");return (await o.insert(n).values(r).returning())[0]}async createNested(e,t,o,n,r){let s=r??this.getDb(),i=this.getRelatedTable(o);if(!i)return b$1().warn(`Related table not found for ${t}. Add 'table' to the relation config.`),[];let l=Array.isArray(n)?n:[n],d=[];for(let u of l){if(typeof u!="object"||u===null)continue;let c={...u,id:crypto.randomUUID(),[o.foreignKey]:e},m=await s.insert(i).values(c).returning();m[0]&&d.push(m[0]);}return d}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},B=class extends u{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async read(e,t,o){let n=this.getTable(),r=this.getColumn(this.lookupField),s=this.getSoftDeleteConfig(),i=[eq(r,e)];if(t)for(let[u,c]of Object.entries(t))i.push(eq(this.getColumn(u),c));s.enabled&&i.push(isNull(this.getColumn(s.field)));let l=await this.getDb().select().from(n).where(and(...i)).limit(1);return l[0]?await ce(this.getDb(),l[0],this._meta,o):null}},A=class extends v{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}getRelatedTable(e){return e.table}async findExisting(e,t,o){let n=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[u,c]of Object.entries(t))l.push(eq(this.getColumn(u),c));return i.enabled&&l.push(isNull(this.getColumn(i.field))),(await n.select().from(r).where(and(...l)).limit(1))[0]||null}async update(e,t,o,n){let r=n??this.getDb(),s=this.getTable(),i=this.getColumn(this.lookupField),l=this.getSoftDeleteConfig(),d=[eq(i,e)];if(o)for(let[c,m]of Object.entries(o))d.push(eq(this.getColumn(c),m));return l.enabled&&d.push(isNull(this.getColumn(l.field))),(await r.update(s).set(this.applyManagedUpdateFields(t)).where(and(...d)).returning())[0]||null}async processNestedWrites(e,t,o,n,r){let s=r??this.getDb(),i=this.getRelatedTable(o);if(!i)return b$1().warn(`Related table not found for ${t}. Add 'table' to the relation config.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]};let l={created:[],updated:[],deleted:[],connected:[],disconnected:[]},d=b(i,o.foreignKey),u=b(i,"id");if(n.create){let c=Array.isArray(n.create)?n.create:[n.create];for(let m of c){if(typeof m!="object"||m===null)continue;let p={...m,id:crypto.randomUUID(),[o.foreignKey]:e},g=await s.insert(i).values(p).returning();g[0]&&l.created.push(g[0]);}}if(n.update)for(let c of n.update){if(!c.id||!(await s.select().from(i).where(and(eq(u,c.id),eq(d,e))).limit(1))[0])continue;let{id:p,...g}=c,h=await s.update(i).set(g).where(eq(u,p)).returning();h[0]&&l.updated.push(h[0]);}if(n.delete)for(let c of n.delete)(await s.delete(i).where(and(eq(u,c),eq(d,e))).returning())[0]&&l.deleted.push(c);if(n.connect)for(let c of n.connect)(await s.update(i).set({[o.foreignKey]:e}).where(eq(u,c)).returning())[0]&&l.connected.push(c);if(n.disconnect)for(let c of n.disconnect)(await s.update(i).set({[o.foreignKey]:null}).where(and(eq(u,c),eq(d,e))).returning())[0]&&l.disconnected.push(c);return l}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},L=class extends w{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}getRelatedTable(e){return e.table}async findForDelete(e,t,o){let n=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[u,c]of Object.entries(t))l.push(eq(this.getColumn(u),c));return i.enabled&&l.push(isNull(this.getColumn(i.field))),(await n.select().from(r).where(and(...l)).limit(1))[0]||null}async delete(e,t,o){let n=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[d,u]of Object.entries(t))l.push(eq(this.getColumn(d),u));return i.enabled&&l.push(isNull(this.getColumn(i.field))),i.enabled?(await n.update(r).set({[i.field]:new Date}).where(and(...l)).returning())[0]||null:(await n.delete(r).where(and(...l)).returning())[0]||null}async countRelated(e,t,o,n){let r=n??this.getDb(),s=this.getRelatedTable(o);if(!s)return 0;let i=b(s,o.foreignKey),l=await r.select({count:sql`count(*)`}).from(s).where(eq(i,e));return Number(l[0]?.count)||0}async deleteRelated(e,t,o,n){let r=n??this.getDb(),s=this.getRelatedTable(o);if(!s)return 0;let i=b(s,o.foreignKey);return (await r.delete(s).where(eq(i,e)).returning()).length}async nullifyRelated(e,t,o,n){let r=n??this.getDb(),s=this.getRelatedTable(o);if(!s)return 0;let i=b(s,o.foreignKey);return (await r.update(s).set({[o.foreignKey]:null}).where(eq(i,e)).returning()).length}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},K=class extends x{db;dialect="sqlite";getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async list(e){let t=this.getTable(),o=[],n=this.getSoftDeleteConfig();if(n.enabled){let y=this.getColumn(n.field);e.options.onlyDeleted?o.push(isNotNull(y)):e.options.withDeleted||o.push(isNull(y));}for(let y of e.filters){let R=O(t,y);R&&o.push(R);}if(e.options.search&&this.searchFields.length>0){let y=e.options.search,R=this.searchFields.map($=>{let se=this.getColumn($);return ee(se,y,this.dialect)});o.push(or(...R));}let r=o.length>0?and(...o):void 0,s=this.getDb(),i=await s.select({count:sql`count(*)`}).from(t).where(r),l=Number(i[0]?.count)||0,d=s.select().from(t).where(r);if(e.options.order_by){let y=this.getColumn(e.options.order_by),R=e.options.order_by_direction==="desc"?desc:asc;d=d.orderBy(R(y));}let u=e.options.page||1,c=e.options.per_page||this.defaultPerPage;d=d.limit(c).offset((u-1)*c);let m=await d,p={relations:e.options.include||[]},g=await S(this.getDb(),m,this._meta,p),h=Math.ceil(l/c);return {result:g,result_info:{page:u,per_page:c,total_count:l,total_pages:h,has_next_page:u<h,has_prev_page:u>1}}}},Z=class extends z$1{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async restore(e,t,o){let n=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[u,c]of Object.entries(t))l.push(eq(this.getColumn(u),c));return l.push(isNotNull(this.getColumn(i.field))),(await n.update(r).set({[i.field]:null}).where(and(...l)).returning())[0]||null}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}};var F=class extends B$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}async batchCreate(e){let t=this.getTable(),o=e.map(r=>this.applyManagedInsertFields(r,"drizzle"));return await this.getDb().insert(t).values(o).returning()}},Q=class extends C{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async batchUpdate(e){let t=this.getTable(),o=this.getColumn(this.lookupField),n=this.getSoftDeleteConfig(),r=[],s=[];for(let i of e){let l=[eq(o,i.id)];n.enabled&&l.push(isNull(this.getColumn(n.field)));let d=await this.getDb().update(t).set(this.applyManagedUpdateFields(i.data)).where(and(...l)).returning();d[0]?r.push(d[0]):s.push(i.id);}return {updated:r,notFound:s}}},N=class extends D$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async batchDelete(e){let t=this.getTable(),o=this.getColumn(this.lookupField),n=this.getSoftDeleteConfig(),r=[inArray(o,e)];n.enabled&&r.push(isNull(this.getColumn(n.field)));let s;n.enabled?s=await this.getDb().update(t).set({[n.field]:new Date}).where(and(...r)).returning():s=await this.getDb().delete(t).where(and(...r)).returning();let i=s,l=new Set(i.map(u=>String(u[this.lookupField]))),d=e.filter(u=>!l.has(u));return {deleted:i,notFound:d}}},q=class extends E{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async batchRestore(e){let t=this.getTable(),o=this.getColumn(this.lookupField),n=this.getSoftDeleteConfig(),r=[inArray(o,e),isNotNull(this.getColumn(n.field))],i=await this.getDb().update(t).set({[n.field]:null}).where(and(...r)).returning(),l=new Set(i.map(u=>String(u[this.lookupField]))),d=e.filter(u=>!l.has(u));return {restored:i,notFound:d}}};function ln(a,e,t){let o=t?.dialect??"sqlite";return {Create:class extends U{_meta=e;db=a},Read:class extends B{_meta=e;db=a},Update:class extends A{_meta=e;db=a},Delete:class extends L{_meta=e;db=a},List:class extends K{_meta=e;db=a;dialect=o},Restore:class extends Z{_meta=e;db=a},Upsert:class extends j{_meta=e;db=a;dialect=o},Search:class extends I{_meta=e;db=a;dialect=o},BatchCreate:class extends F{_meta=e;db=a},BatchUpdate:class extends Q{_meta=e;db=a},BatchDelete:class extends N{_meta=e;db=a},BatchRestore:class extends q{_meta=e;db=a},BatchUpsert:class extends _{_meta=e;db=a;dialect=o}}}var oe=null,Ve=false,ne=null;async function re(){if(Ve){if(ne)throw ne;return oe}Ve=true;try{return oe=await import('drizzle-zod'),oe}catch{throw ne=new Error("drizzle-zod is not installed. Please install it: npm install drizzle-zod"),ne}}async function mt(a,e){return (await re()).createSelectSchema(a,e)}async function bt(a,e){return (await re()).createInsertSchema(a,e)}async function ht(a,e){let t=await re();return t.createUpdateSchema?t.createUpdateSchema(a,e):t.createInsertSchema(a,e).partial()}async function ft(a,e){let t=await re(),o=e?.coerceDates!==false,n=o?Mt(a):new Set,r=t.createSelectSchema(a,e?.selectRefine),s=t.createInsertSchema(a,e?.insertRefine),i;return t.createUpdateSchema?i=t.createUpdateSchema(a,e?.updateRefine):i=t.createInsertSchema(a,e?.updateRefine).partial(),o&&n.size>0&&(s=Xe(s,n),i=Xe(i,n)),{select:r,insert:s,update:i}}function zt(){return oe!==null}var Dt=z.preprocess(a=>{if(a instanceof Date)return a;if(typeof a=="string"){let e=new Date(a);if(!isNaN(e.getTime()))return e}return a},z.date()),yt=z.preprocess(a=>{if(a==null)return null;if(a instanceof Date)return a;if(typeof a=="string"){let e=new Date(a);if(!isNaN(e.getTime()))return e}return a},z.date().nullable());function Mt(a){let e=new Set,t=a;for(let[o,n]of Object.entries(t)){if(o==="_"||o==="$inferInsert"||o==="$inferSelect")continue;let r=n;if(!r||typeof r!="object")continue;let s=String(r.dataType??"").toLowerCase(),i=String(r.columnType??"").toLowerCase(),l=r.config,d=String(l?.dataType??"").toLowerCase();(s.includes("timestamp")||s.includes("date")||s.includes("datetime")||i.includes("pgtimestamp")||i.includes("pgdate")||i.includes("mysqltimestamp")||i.includes("mysqldate")||i.includes("sqlitetimestamp")||d.includes("timestamp")||d.includes("date"))&&e.add(o);}return e}function Xe(a,e){if(e.size===0)return a;let t=a.shape,o={};for(let[n,r]of Object.entries(t))if(e.has(n)){let s=r.isOptional?.()??false,i=r.isNullable?.()??false,l=Dt;(i||s)&&(l=yt),s&&(l=l.optional()),o[n]=l;}else o[n]=r;return z.object(o)}var kn={CreateEndpoint:U,ListEndpoint:K,ReadEndpoint:B,UpdateEndpoint:A,DeleteEndpoint:L,RestoreEndpoint:Z,BatchCreateEndpoint:F,BatchUpdateEndpoint:Q,BatchDeleteEndpoint:N,BatchRestoreEndpoint:q,BatchUpsertEndpoint:_,SearchEndpoint:I,AggregateEndpoint:G,ExportEndpoint:H,ImportEndpoint:J,UpsertEndpoint:j,CloneEndpoint:Y};export{Q as A,N as B,q as C,ln as D,mt as E,bt as F,ht as G,ft as H,zt as I,kn as J,X as a,f as b,b as c,Ue as d,ce as e,S as f,O as g,ee as h,j as i,_ as j,Be as k,Ae as l,Le as m,Ke as n,G as o,I as p,H as q,J as r,Y as s,U as t,B as u,A as v,L as w,K as x,Z as y,F as z};
@@ -1 +1 @@
1
- import {b as b$4}from'./chunk-NGUMNUOP.js';import {a as a$3}from'./chunk-GF2EC5G4.js';import {a,g}from'./chunk-2M5BM4VD.js';import {a as a$1,i}from'./chunk-FC56WWPB.js';import {b as b$3}from'./chunk-FJCWFB5L.js';import {b,c}from'./chunk-GBQQ3YQX.js';import {b as b$2}from'./chunk-DMGP7QDL.js';import {e,a as a$2,b as b$1}from'./chunk-VJRDAVID.js';function B(e,t={}){let{ipHeader:n="X-Forwarded-For",trustProxy:r=true}=t;if(r){let s=e.req.header(n);if(s){let c=s.split(",")[0]?.trim();if(c)return c}let a=e.req.header("X-Real-IP")?.trim();if(a)return a;let i=e.req.header("CF-Connecting-IP")?.trim();if(i)return i}let o=e.req.raw;if(o&&typeof o.socket=="object"&&o.socket?.remoteAddress)return o.socket.remoteAddress;if(o?.cf?.ip)return o.cf.ip}function $(e){return a$2(e,"userId")}function z(e,t){let n=e.toLowerCase();for(let r of t){if(r instanceof RegExp){if(r.test(e))return true;continue}let o=r.toLowerCase();if(o.includes("*")){let s=o.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");if(new RegExp(`^${s}$`).test(n))return true}else if(n===o)return true}return false}function j(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(r=>j(r,t));if(typeof e!="object")return e;let n={};for(let[r,o]of Object.entries(e))z(r,t)?n[r]="[REDACTED]":typeof o=="object"&&o!==null?n[r]=j(o,t):n[r]=o;return n}function he(e,t){let n={};for(let[r,o]of Object.entries(e))n[r]=z(r,t)?"[REDACTED]":o;return n}function Ye(e,t){return z(e,t)}function ee(e,t){return j(e,t)}function te(e,t){return he(e,t)}function Ze(e,t){return a(e,t)}function ye(e,t,n){for(let r of n)if(a(e,r))return true;if(t.length===0)return false;for(let r of t)if(a(e,r))return false;return true}function xe(e,t="X-Forwarded-For",n=false){return B(e,{ipHeader:t,trustProxy:n||true})}function re(e){let t={};return e.forEach((n,r)=>{t[r.toLowerCase()]=n;}),t}function Ce(e){let t={};return new URL(e.req.url).searchParams.forEach((r,o)=>{t[o]=r;}),t}function D(e,t){if(typeof e=="string")return e.length>t?e.substring(0,t)+"... [TRUNCATED]":e;let n=JSON.stringify(e);return n.length>t?{_truncated:true,_originalSize:n.length,_maxSize:t}:e}function Ee(e,t){if(!e)return false;if(t.length===0)return true;let n=e.toLowerCase();for(let r of t)if(n.includes(r.toLowerCase()))return true;return false}function Se(e){return $(e)}function Re(){return e()}var U=class extends a$1{constructor(t="Too many requests",n=60){super(t,429,"RATE_LIMIT_EXCEEDED",{retryAfter:n}),this.name="RateLimitExceededException";}};function q(e,t="X-Forwarded-For",n=false){return B(e,{ipHeader:t,trustProxy:n})??"unknown"}function ne(e){return $(e)??null}function we(e,t="X-API-Key"){return e.req.header(t)||null}function st(e,t){return a(e,t)}function ve(e,t){return t.some(n=>a(e,n))}function Ie(e,...t){let n=t.filter(r=>r!==void 0&&r!=="");return `${e}:${n.join(":")}`}function V(e){return e instanceof Error?e:new Error(String(e))}function Me(e,t){let n=V(e),r=new Error(`${t}: ${n.message}`);return r.cause=n,r}function Oe(e){return e instanceof Error?e.message:String(e)}var X=b("loggingStorage");function ht(e){X.set(e);}function yt(){return X.get()}var De=["authorization","cookie","x-api-key","x-auth-token"],Fe=["password","token","secret","apiKey","api_key","accessToken","access_token","refreshToken","refresh_token","creditCard","credit_card","ssn","socialSecurityNumber"],_e=["/health","/healthz","/ready","/readyz","/live","/livez","/metrics","/favicon.ico"];function xt(e){return a$2(e,"requestId")}function Ct(e){return a$2(e,"requestStartTime")}function Et(e={}){let t=e.enabled??true,n=e.level??"info",r=e.includePaths??[],o=e.excludePaths??_e,s=e.redactHeaders??De,a=e.redactBodyFields??Fe,i=e.requestBody??{enabled:false},c=e.responseBody??{enabled:false},u=e.includeHeaders??true,d=e.includeQuery??true,g=e.includeClientIp??true,C=e.ipHeader??"X-Forwarded-For",m=e.trustProxy??false,h=e.minResponseTimeMs??0,R=e.generateRequestId??Re;return async(l,P)=>{if(!t)return P();let w=l.req.path;if(ye(w,r,o))return P();let f=R(),T=Date.now();b$1(l,"requestId",f),b$1(l,"requestStartTime",T),l.header("X-Request-ID",f);let Ae=l.req.method,qe=l.req.url,oe;if(u){let E=re(l.req.raw.headers);oe=te(E,s);}let se;d&&(se=Ce(l));let ae;g&&(ae=xe(l,C,m));let Ke=Se(l),Q;if(i.enabled){let E=l.req.header("content-type"),H=i.contentTypes??[];if(Ee(E,H))try{let L=await l.req.raw.clone().text();if(L)try{let x=JSON.parse(L);x=ee(x,a);let y=i.maxSize??10240;Q=D(x,y);}catch{let x=i.maxSize??10240;Q=D(L,x);}}catch{}}let S,Y;try{await P();}catch(E){throw S=E instanceof Error?E:new Error(String(E)),E}finally{let H=Date.now()-T;if(H<h)return;let b=l.res.status,L;if(u){let p=re(l.res.headers);L=te(p,s);}if(c.enabled&&!S){let p=c.statusCodes??[];if(p.length===0||p.includes(b))try{let Z=await l.res.clone().text();if(Z)try{let M=JSON.parse(Z);M=ee(M,a);let He=c.maxSize??10240;Y=D(M,He);}catch{let M=c.maxSize??10240;Y=D(Z,M);}}catch{}}let x=n;e.levelResolver?x=e.levelResolver(l,H,b,S):S||b>=500?x="error":b>=400&&(x="warn");let y={id:f,timestamp:new Date(T).toISOString(),level:x,request:{method:Ae,path:w,url:qe,headers:oe,query:se,body:Q,clientIp:ae,userId:Ke},response:{statusCode:b,headers:L,body:Y,responseTimeMs:H}};if(S&&(y.error={message:S.message,name:S.name,stack:S.stack}),e.metadata){let p=typeof e.metadata=="function"?e.metadata(l):e.metadata;y.metadata=p;}e.formatter&&(y=e.formatter(y));let ie=Pe(l,e.storage);(async()=>{if(ie)try{await ie.store(y);}catch(p){e.onError&&e.onError(p instanceof Error?p:new Error(String(p)),y);}if(e.handlers)for(let p of e.handlers)try{await p(y);}catch(v){e.onError&&e.onError(v instanceof Error?v:new Error(String(v)),y);}})().catch(p=>{let v=V(p);e.onError?e.onError(v,y):b$2().error("Failed to process log entry",{error:v.message});});}}}function Te(e){let{tableName:t,method:n,params:r,query:o,keyFields:s,userId:a,prefix:i}=e,c=[];if(i&&c.push(i),c.push(t),c.push(n),r&&Object.keys(r).length>0){let u=Object.keys(r).sort().map(d=>`${d}=${r[d]}`).join("&");c.push(u);}if(o&&Object.keys(o).length>0){let u=Object.keys(o).filter(d=>o[d]!==void 0&&o[d]!==null&&o[d]!=="");if(s&&s.length>0&&(u=u.filter(d=>s.includes(d))),u.length>0){let d=u.sort().map(g=>`${g}=${String(o[g])}`).join("&");c.push(d);}}return a&&c.push(`user=${a}`),c.join(":")}function K(e,t,n){let r=[];if(n&&r.push(n),r.push(e),!t)return r.push("*"),r.join(":");let{method:o,id:s,userId:a}=t;return o?(r.push(o),r.join(":")+"*"):(s!==void 0?(r.push("*"),r.push(`id=${s}*`)):a?(r.push("*"),r.push(`user=${a}`)):r.push("*"),r.join(":"))}function be(e,t,n){return t.map(r=>K(r,void 0,n))}function Le(e,t){let n=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${n}$`).test(e)}function Rt(e){let t=e.split(":"),n=t.length>2&&!["GET","LIST"].includes(t[1]),r=0,o=n?t[r++]:void 0,s=t[r++],a=t[r++],i={tableName:s,method:a};o&&(i.prefix=o);for(let c=r;c<t.length;c++){let u=t[c];if(u.startsWith("user="))i.userId=u.substring(5);else if(u.includes("=")){let d=u.split("&"),g={};for(let C of d){let[m,h]=C.split("=");m&&h!==void 0&&(g[m]=h);}a==="GET"&&!i.params?i.params=g:a==="LIST"&&!i.query||i.params?i.query=g:i.params=g;}}return i}var W=class{storage=new Map;tagIndex=new Map;stats={hits:0,misses:0,size:0};defaultTtl;maxEntries;constructor(t){this.defaultTtl=t?.defaultTtl??300,this.maxEntries=t?.maxEntries??1e4;}async get(t){let n=this.storage.get(t);return n?n.expiresAt&&n.expiresAt<Date.now()?(await this.delete(t),this.stats.misses++,null):(this.stats.hits++,n):(this.stats.misses++,null)}async set(t,n,r){let o=r?.ttl??this.defaultTtl,s=r?.tags;this.maxEntries>0&&this.storage.size>=this.maxEntries&&!this.storage.has(t)&&this.evictOldest();let a=Date.now(),i={data:n,createdAt:a,expiresAt:o>0?a+o*1e3:null,tags:s},c=this.storage.get(t);if(c?.tags)for(let u of c.tags)this.tagIndex.get(u)?.delete(t);if(c&&this.storage.delete(t),this.storage.set(t,i),this.stats.size=this.storage.size,s)for(let u of s)this.tagIndex.has(u)||this.tagIndex.set(u,new Set),this.tagIndex.get(u).add(t);}async delete(t){let n=this.storage.get(t);if(!n)return false;if(n.tags)for(let r of n.tags)this.tagIndex.get(r)?.delete(t);return this.storage.delete(t),this.stats.size=this.storage.size,true}async deletePattern(t){let n=0,r=[];for(let o of this.storage.keys())Le(o,t)&&r.push(o);for(let o of r)await this.delete(o)&&n++;return n}async deleteByTag(t){let n=this.tagIndex.get(t);if(!n||n.size===0)return 0;let r=0,o=Array.from(n);for(let s of o)await this.delete(s)&&r++;return this.tagIndex.delete(t),r}async has(t){let n=this.storage.get(t);return n?n.expiresAt&&n.expiresAt<Date.now()?(await this.delete(t),false):true:false}async clear(){this.storage.clear(),this.tagIndex.clear(),this.stats.size=0;}getStats(){return {...this.stats}}resetStats(){this.stats.hits=0,this.stats.misses=0;}getKeys(){return Array.from(this.storage.keys())}getTags(){return Array.from(this.tagIndex.keys())}evictOldest(){let t=this.storage.keys().next().value;t!==void 0&&this.delete(t).catch(()=>{});}async cleanup(){let t=Date.now(),n=0,r=[];for(let[o,s]of this.storage.entries())s.expiresAt&&s.expiresAt<t&&r.push(o);for(let o of r)await this.delete(o),n++;return n}};function G(e){let n=e._meta?.model?.tableName;if(!n)throw new i("Cache mixin requires `_meta.model.tableName`. Declare `_meta` on the endpoint or remove the cache mixin.");return n}var J=c("cacheStorage",()=>new W);function qt(e){J.set(e);}function Kt(){return J.getRequired()}function Ht(e){class t extends e{cacheConfig;getCacheConfig(){return {enabled:true,ttl:300,perUser:false,...this.cacheConfig}}async generateCacheKey(){let r=this.getCacheConfig(),o=this.getContext(),s=G(this),a=await this.getValidatedData(),i=a.params,c=a.query,u=i&&Object.keys(i).length>0?"GET":"LIST",d;return r.perUser&&(d=o.var?.userId),Te({tableName:s,method:u,params:i,query:c,keyFields:r.keyFields,userId:d,prefix:r.prefix})}_cacheHit=false;async getCachedResponse(){if(!this.getCacheConfig().enabled)return this._cacheHit=false,null;let o=await this.generateCacheKey(),s=this.getContext(),a=F(s);if(!a)return this._cacheHit=false,null;let i=await a.get(o);return this._cacheHit=i!==null,i?.data??null}getCacheStatus(){return this._cacheHit?"HIT":"MISS"}successWithCache(r,o=200){return new Response(JSON.stringify({success:true,result:r}),{status:o,headers:{"Content-Type":"application/json","X-Cache":this.getCacheStatus()}})}jsonWithCache(r,o=200){return new Response(JSON.stringify(r),{status:o,headers:{"Content-Type":"application/json","X-Cache":this.getCacheStatus()}})}async setCachedResponse(r){let o=this.getCacheConfig();if(!o.enabled)return;let s=await this.generateCacheKey(),a=this.getContext(),i=F(a);if(!i)return;let c=o.tags?[...o.tags]:[],u=this._meta;u?.model?.tableName&&c.push(u.model.tableName),await i.set(s,r,{ttl:o.ttl,tags:c.length>0?c:void 0});}async invalidateCache(r){let o=this.getContext(),s=F(o);if(!s)return;let a=this.getCacheConfig();if(r?.pattern)await s.deletePattern(r.pattern);else if(r?.tags&&s.deleteByTag)for(let i of r.tags)await s.deleteByTag(i);else {let i=G(this),c=K(i,void 0,a.prefix);await s.deletePattern(c);}}}return t}function Mt(e){class t extends e{cacheInvalidation;getCacheInvalidationConfig(){return {strategy:"all",...this.cacheInvalidation}}async performCacheInvalidation(r){let o=this.getCacheInvalidationConfig(),s=this.getContext(),a=F(s);if(!a)return;let i=G(this);switch(o.strategy??"all"){case "single":if(r!==void 0){let g=K(i,{id:r});await a.deletePattern(g);}break;case "list":let u=K(i,{method:"LIST"});await a.deletePattern(u);break;case "all":let d=K(i);await a.deletePattern(d);break;case "pattern":o.pattern&&await a.deletePattern(o.pattern);break;case "tags":if(o.tags&&a.deleteByTag)for(let g of o.tags)await a.deleteByTag(g);break}if(o.relatedModels&&o.relatedModels.length>0){let u=be(i,o.relatedModels);for(let d of u)await a.deletePattern(d);}}async handle(){let r=await super.handle();if(r.status>=200&&r.status<300){let o;try{o=(await r.clone().json())?.result?.id;}catch{}let s=G(this);this.performCacheInvalidation(o).catch(a=>{b$2().error("Cache invalidation failed",{error:a instanceof Error?a.message:String(a),tableName:s,recordId:o});});}return r}}return t}function ke(e,t){return _.resolve(e,t)}function Pe(e,t){return X.resolve(e,t)}function F(e,t){return J.resolve(e,t)}function zt(e,t){return b$3.resolve(e,t)}function Ut(e,t){return b$4.resolve(e,t)}function Vt(e,t){return g.resolve(e,t)}function Xt(e,t){return a$3.resolve(e,t)}var _=b("rateLimitStorage");function tr(e){_.set(e);}function rr(){return _.get()}function Ne(){return {ip:e=>t=>q(t,e.ipHeader,e.trustProxy),user:e=>t=>{let n=ne(t);return n?`user:${n}`:q(t,e.ipHeader,e.trustProxy)},"api-key":e=>t=>{let n=we(t,e.apiKeyHeader);return n?`apikey:${n.substring(0,8)}`:q(t,e.ipHeader,e.trustProxy)},combined:e=>t=>{let n=q(t,e.ipHeader,e.trustProxy),r=ne(t);return r?`${n}:user:${r}`:n}}}function Be(e,t){if(typeof e=="function")return e;let r=Ne()[e];return r?r(t):o=>q(o,t.ipHeader,t.trustProxy)}async function $e(e,t,n,r){let o=await e.increment(t,r),s=Math.ceil((o.windowStart+r)/1e3),a=Math.max(0,n-o.count),i=o.count<=n;return {allowed:i,limit:n,remaining:a,resetAt:s,retryAfter:i?void 0:Math.ceil((o.windowStart+r-Date.now())/1e3)}}async function je(e,t,n,r){let o=Date.now(),s=await e.addTimestamp(t,r,o),a=s.timestamps.length,i=Math.max(0,n-a),c=a<=n,u=s.timestamps.length>0?Math.min(...s.timestamps):o,d=Math.ceil((u+r)/1e3),g;if(!c&&s.timestamps.length>0){let C=[...s.timestamps].sort((h,R)=>h-R),m=a-n;if(m>0&&C.length>=m){let h=C[m-1];g=Math.max(1,Math.ceil((h+r-o)/1e3));}}return {allowed:c,limit:n,remaining:i,resetAt:d,retryAfter:g}}function nr(e={}){let t=e.limit??100,n=e.windowSeconds??60,r=e.algorithm??"sliding-window",o=e.keyStrategy??"ip",s=e.keyPrefix??"rl",a=e.skipPaths??[],i=e.includeHeaders??true,c=e.errorMessage??"Too many requests",u=Be(o,e);return async(d,g)=>{let C=d.req.path;if(a.length>0&&ve(C,a))return g();let m=ke(d,e.storage);if(!m)return b$2().warn("Rate limit storage not configured. Skipping rate limiting."),g();let h=u(d);if(!h)return g();let R=t,l=n;if(e.getTier){let T=await e.getTier(d);R=T.limit,l=T.windowSeconds??n;}let P=l*1e3,w=Ie(s,C,h),f;if(r==="fixed-window"?f=await $e(m,w,R,P):f=await je(m,w,R,P),b$1(d,"rateLimit",f),b$1(d,"rateLimitKey",w),i&&(d.header("X-RateLimit-Limit",String(f.limit)),d.header("X-RateLimit-Remaining",String(f.remaining)),d.header("X-RateLimit-Reset",String(f.resetAt))),!f.allowed)throw f.retryAfter&&d.header("Retry-After",String(f.retryAfter)),e.onRateLimitExceeded&&await e.onRateLimitExceeded(d,f,w),new U(c,f.retryAfter??60);await g();}}async function or(e,t){let n=t??_.get();if(!n)throw new Error("Rate limit storage not configured");await n.reset(e);}export{Le as A,Rt as B,W as C,qt as D,Kt as E,Ht as F,Mt as G,ke as H,Pe as I,F as J,zt as K,Ut as L,Vt as M,Xt as N,V as O,Me as P,Oe as Q,ht as R,yt as S,xt as T,Ct as U,Et as V,Ye as a,ee as b,te as c,Ze as d,ye as e,xe as f,re as g,Ce as h,D as i,Ee as j,Se as k,Re as l,U as m,q as n,ne as o,we as p,st as q,ve as r,Ie as s,tr as t,rr as u,nr as v,or as w,Te as x,K as y,be as z};
1
+ import {b as b$4}from'./chunk-NGUMNUOP.js';import {a as a$3}from'./chunk-GF2EC5G4.js';import {b as b$3}from'./chunk-FJCWFB5L.js';import {a,g}from'./chunk-2M5BM4VD.js';import {a as a$1,i}from'./chunk-FC56WWPB.js';import {b,c}from'./chunk-GBQQ3YQX.js';import {b as b$2}from'./chunk-DMGP7QDL.js';import {e,a as a$2,b as b$1}from'./chunk-VJRDAVID.js';function B(e,t={}){let{ipHeader:n="X-Forwarded-For",trustProxy:r=true}=t;if(r){let s=e.req.header(n);if(s){let c=s.split(",")[0]?.trim();if(c)return c}let a=e.req.header("X-Real-IP")?.trim();if(a)return a;let i=e.req.header("CF-Connecting-IP")?.trim();if(i)return i}let o=e.req.raw;if(o&&typeof o.socket=="object"&&o.socket?.remoteAddress)return o.socket.remoteAddress;if(o?.cf?.ip)return o.cf.ip}function $(e){return a$2(e,"userId")}function z(e,t){let n=e.toLowerCase();for(let r of t){if(r instanceof RegExp){if(r.test(e))return true;continue}let o=r.toLowerCase();if(o.includes("*")){let s=o.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");if(new RegExp(`^${s}$`).test(n))return true}else if(n===o)return true}return false}function j(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(r=>j(r,t));if(typeof e!="object")return e;let n={};for(let[r,o]of Object.entries(e))z(r,t)?n[r]="[REDACTED]":typeof o=="object"&&o!==null?n[r]=j(o,t):n[r]=o;return n}function he(e,t){let n={};for(let[r,o]of Object.entries(e))n[r]=z(r,t)?"[REDACTED]":o;return n}function Ye(e,t){return z(e,t)}function ee(e,t){return j(e,t)}function te(e,t){return he(e,t)}function Ze(e,t){return a(e,t)}function ye(e,t,n){for(let r of n)if(a(e,r))return true;if(t.length===0)return false;for(let r of t)if(a(e,r))return false;return true}function xe(e,t="X-Forwarded-For",n=false){return B(e,{ipHeader:t,trustProxy:n||true})}function re(e){let t={};return e.forEach((n,r)=>{t[r.toLowerCase()]=n;}),t}function Ce(e){let t={};return new URL(e.req.url).searchParams.forEach((r,o)=>{t[o]=r;}),t}function D(e,t){if(typeof e=="string")return e.length>t?e.substring(0,t)+"... [TRUNCATED]":e;let n=JSON.stringify(e);return n.length>t?{_truncated:true,_originalSize:n.length,_maxSize:t}:e}function Ee(e,t){if(!e)return false;if(t.length===0)return true;let n=e.toLowerCase();for(let r of t)if(n.includes(r.toLowerCase()))return true;return false}function Se(e){return $(e)}function Re(){return e()}var U=class extends a$1{constructor(t="Too many requests",n=60){super(t,429,"RATE_LIMIT_EXCEEDED",{retryAfter:n}),this.name="RateLimitExceededException";}};function q(e,t="X-Forwarded-For",n=false){return B(e,{ipHeader:t,trustProxy:n})??"unknown"}function ne(e){return $(e)??null}function we(e,t="X-API-Key"){return e.req.header(t)||null}function st(e,t){return a(e,t)}function ve(e,t){return t.some(n=>a(e,n))}function Ie(e,...t){let n=t.filter(r=>r!==void 0&&r!=="");return `${e}:${n.join(":")}`}function V(e){return e instanceof Error?e:new Error(String(e))}function Me(e,t){let n=V(e),r=new Error(`${t}: ${n.message}`);return r.cause=n,r}function Oe(e){return e instanceof Error?e.message:String(e)}var X=b("loggingStorage");function ht(e){X.set(e);}function yt(){return X.get()}var De=["authorization","cookie","x-api-key","x-auth-token"],Fe=["password","token","secret","apiKey","api_key","accessToken","access_token","refreshToken","refresh_token","creditCard","credit_card","ssn","socialSecurityNumber"],_e=["/health","/healthz","/ready","/readyz","/live","/livez","/metrics","/favicon.ico"];function xt(e){return a$2(e,"requestId")}function Ct(e){return a$2(e,"requestStartTime")}function Et(e={}){let t=e.enabled??true,n=e.level??"info",r=e.includePaths??[],o=e.excludePaths??_e,s=e.redactHeaders??De,a=e.redactBodyFields??Fe,i=e.requestBody??{enabled:false},c=e.responseBody??{enabled:false},u=e.includeHeaders??true,d=e.includeQuery??true,g=e.includeClientIp??true,C=e.ipHeader??"X-Forwarded-For",m=e.trustProxy??false,h=e.minResponseTimeMs??0,R=e.generateRequestId??Re;return async(l,P)=>{if(!t)return P();let w=l.req.path;if(ye(w,r,o))return P();let f=R(),T=Date.now();b$1(l,"requestId",f),b$1(l,"requestStartTime",T),l.header("X-Request-ID",f);let Ae=l.req.method,qe=l.req.url,oe;if(u){let E=re(l.req.raw.headers);oe=te(E,s);}let se;d&&(se=Ce(l));let ae;g&&(ae=xe(l,C,m));let Ke=Se(l),Q;if(i.enabled){let E=l.req.header("content-type"),H=i.contentTypes??[];if(Ee(E,H))try{let L=await l.req.raw.clone().text();if(L)try{let x=JSON.parse(L);x=ee(x,a);let y=i.maxSize??10240;Q=D(x,y);}catch{let x=i.maxSize??10240;Q=D(L,x);}}catch{}}let S,Y;try{await P();}catch(E){throw S=E instanceof Error?E:new Error(String(E)),E}finally{let H=Date.now()-T;if(H<h)return;let b=l.res.status,L;if(u){let p=re(l.res.headers);L=te(p,s);}if(c.enabled&&!S){let p=c.statusCodes??[];if(p.length===0||p.includes(b))try{let Z=await l.res.clone().text();if(Z)try{let M=JSON.parse(Z);M=ee(M,a);let He=c.maxSize??10240;Y=D(M,He);}catch{let M=c.maxSize??10240;Y=D(Z,M);}}catch{}}let x=n;e.levelResolver?x=e.levelResolver(l,H,b,S):S||b>=500?x="error":b>=400&&(x="warn");let y={id:f,timestamp:new Date(T).toISOString(),level:x,request:{method:Ae,path:w,url:qe,headers:oe,query:se,body:Q,clientIp:ae,userId:Ke},response:{statusCode:b,headers:L,body:Y,responseTimeMs:H}};if(S&&(y.error={message:S.message,name:S.name,stack:S.stack}),e.metadata){let p=typeof e.metadata=="function"?e.metadata(l):e.metadata;y.metadata=p;}e.formatter&&(y=e.formatter(y));let ie=Pe(l,e.storage);(async()=>{if(ie)try{await ie.store(y);}catch(p){e.onError&&e.onError(p instanceof Error?p:new Error(String(p)),y);}if(e.handlers)for(let p of e.handlers)try{await p(y);}catch(v){e.onError&&e.onError(v instanceof Error?v:new Error(String(v)),y);}})().catch(p=>{let v=V(p);e.onError?e.onError(v,y):b$2().error("Failed to process log entry",{error:v.message});});}}}function Te(e){let{tableName:t,method:n,params:r,query:o,keyFields:s,userId:a,prefix:i}=e,c=[];if(i&&c.push(i),c.push(t),c.push(n),r&&Object.keys(r).length>0){let u=Object.keys(r).sort().map(d=>`${d}=${r[d]}`).join("&");c.push(u);}if(o&&Object.keys(o).length>0){let u=Object.keys(o).filter(d=>o[d]!==void 0&&o[d]!==null&&o[d]!=="");if(s&&s.length>0&&(u=u.filter(d=>s.includes(d))),u.length>0){let d=u.sort().map(g=>`${g}=${String(o[g])}`).join("&");c.push(d);}}return a&&c.push(`user=${a}`),c.join(":")}function K(e,t,n){let r=[];if(n&&r.push(n),r.push(e),!t)return r.push("*"),r.join(":");let{method:o,id:s,userId:a}=t;return o?(r.push(o),r.join(":")+"*"):(s!==void 0?(r.push("*"),r.push(`id=${s}*`)):a?(r.push("*"),r.push(`user=${a}`)):r.push("*"),r.join(":"))}function be(e,t,n){return t.map(r=>K(r,void 0,n))}function Le(e,t){let n=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${n}$`).test(e)}function Rt(e){let t=e.split(":"),n=t.length>2&&!["GET","LIST"].includes(t[1]),r=0,o=n?t[r++]:void 0,s=t[r++],a=t[r++],i={tableName:s,method:a};o&&(i.prefix=o);for(let c=r;c<t.length;c++){let u=t[c];if(u.startsWith("user="))i.userId=u.substring(5);else if(u.includes("=")){let d=u.split("&"),g={};for(let C of d){let[m,h]=C.split("=");m&&h!==void 0&&(g[m]=h);}a==="GET"&&!i.params?i.params=g:a==="LIST"&&!i.query||i.params?i.query=g:i.params=g;}}return i}var W=class{storage=new Map;tagIndex=new Map;stats={hits:0,misses:0,size:0};defaultTtl;maxEntries;constructor(t){this.defaultTtl=t?.defaultTtl??300,this.maxEntries=t?.maxEntries??1e4;}async get(t){let n=this.storage.get(t);return n?n.expiresAt&&n.expiresAt<Date.now()?(await this.delete(t),this.stats.misses++,null):(this.stats.hits++,n):(this.stats.misses++,null)}async set(t,n,r){let o=r?.ttl??this.defaultTtl,s=r?.tags;this.maxEntries>0&&this.storage.size>=this.maxEntries&&!this.storage.has(t)&&this.evictOldest();let a=Date.now(),i={data:n,createdAt:a,expiresAt:o>0?a+o*1e3:null,tags:s},c=this.storage.get(t);if(c?.tags)for(let u of c.tags)this.tagIndex.get(u)?.delete(t);if(c&&this.storage.delete(t),this.storage.set(t,i),this.stats.size=this.storage.size,s)for(let u of s)this.tagIndex.has(u)||this.tagIndex.set(u,new Set),this.tagIndex.get(u).add(t);}async delete(t){let n=this.storage.get(t);if(!n)return false;if(n.tags)for(let r of n.tags)this.tagIndex.get(r)?.delete(t);return this.storage.delete(t),this.stats.size=this.storage.size,true}async deletePattern(t){let n=0,r=[];for(let o of this.storage.keys())Le(o,t)&&r.push(o);for(let o of r)await this.delete(o)&&n++;return n}async deleteByTag(t){let n=this.tagIndex.get(t);if(!n||n.size===0)return 0;let r=0,o=Array.from(n);for(let s of o)await this.delete(s)&&r++;return this.tagIndex.delete(t),r}async has(t){let n=this.storage.get(t);return n?n.expiresAt&&n.expiresAt<Date.now()?(await this.delete(t),false):true:false}async clear(){this.storage.clear(),this.tagIndex.clear(),this.stats.size=0;}getStats(){return {...this.stats}}resetStats(){this.stats.hits=0,this.stats.misses=0;}getKeys(){return Array.from(this.storage.keys())}getTags(){return Array.from(this.tagIndex.keys())}evictOldest(){let t=this.storage.keys().next().value;t!==void 0&&this.delete(t).catch(()=>{});}async cleanup(){let t=Date.now(),n=0,r=[];for(let[o,s]of this.storage.entries())s.expiresAt&&s.expiresAt<t&&r.push(o);for(let o of r)await this.delete(o),n++;return n}};function G(e){let n=e._meta?.model?.tableName;if(!n)throw new i("Cache mixin requires `_meta.model.tableName`. Declare `_meta` on the endpoint or remove the cache mixin.");return n}var J=c("cacheStorage",()=>new W);function qt(e){J.set(e);}function Kt(){return J.getRequired()}function Ht(e){class t extends e{cacheConfig;getCacheConfig(){return {enabled:true,ttl:300,perUser:false,...this.cacheConfig}}async generateCacheKey(){let r=this.getCacheConfig(),o=this.getContext(),s=G(this),a=await this.getValidatedData(),i=a.params,c=a.query,u=i&&Object.keys(i).length>0?"GET":"LIST",d;return r.perUser&&(d=o.var?.userId),Te({tableName:s,method:u,params:i,query:c,keyFields:r.keyFields,userId:d,prefix:r.prefix})}_cacheHit=false;async getCachedResponse(){if(!this.getCacheConfig().enabled)return this._cacheHit=false,null;let o=await this.generateCacheKey(),s=this.getContext(),a=F(s);if(!a)return this._cacheHit=false,null;let i=await a.get(o);return this._cacheHit=i!==null,i?.data??null}getCacheStatus(){return this._cacheHit?"HIT":"MISS"}successWithCache(r,o=200){return new Response(JSON.stringify({success:true,result:r}),{status:o,headers:{"Content-Type":"application/json","X-Cache":this.getCacheStatus()}})}jsonWithCache(r,o=200){return new Response(JSON.stringify(r),{status:o,headers:{"Content-Type":"application/json","X-Cache":this.getCacheStatus()}})}async setCachedResponse(r){let o=this.getCacheConfig();if(!o.enabled)return;let s=await this.generateCacheKey(),a=this.getContext(),i=F(a);if(!i)return;let c=o.tags?[...o.tags]:[],u=this._meta;u?.model?.tableName&&c.push(u.model.tableName),await i.set(s,r,{ttl:o.ttl,tags:c.length>0?c:void 0});}async invalidateCache(r){let o=this.getContext(),s=F(o);if(!s)return;let a=this.getCacheConfig();if(r?.pattern)await s.deletePattern(r.pattern);else if(r?.tags&&s.deleteByTag)for(let i of r.tags)await s.deleteByTag(i);else {let i=G(this),c=K(i,void 0,a.prefix);await s.deletePattern(c);}}}return t}function Mt(e){class t extends e{cacheInvalidation;getCacheInvalidationConfig(){return {strategy:"all",...this.cacheInvalidation}}async performCacheInvalidation(r){let o=this.getCacheInvalidationConfig(),s=this.getContext(),a=F(s);if(!a)return;let i=G(this);switch(o.strategy??"all"){case "single":if(r!==void 0){let g=K(i,{id:r});await a.deletePattern(g);}break;case "list":let u=K(i,{method:"LIST"});await a.deletePattern(u);break;case "all":let d=K(i);await a.deletePattern(d);break;case "pattern":o.pattern&&await a.deletePattern(o.pattern);break;case "tags":if(o.tags&&a.deleteByTag)for(let g of o.tags)await a.deleteByTag(g);break}if(o.relatedModels&&o.relatedModels.length>0){let u=be(i,o.relatedModels);for(let d of u)await a.deletePattern(d);}}async handle(){let r=await super.handle();if(r.status>=200&&r.status<300){let o;try{o=(await r.clone().json())?.result?.id;}catch{}let s=G(this);this.performCacheInvalidation(o).catch(a=>{b$2().error("Cache invalidation failed",{error:a instanceof Error?a.message:String(a),tableName:s,recordId:o});});}return r}}return t}function ke(e,t){return _.resolve(e,t)}function Pe(e,t){return X.resolve(e,t)}function F(e,t){return J.resolve(e,t)}function zt(e,t){return b$3.resolve(e,t)}function Ut(e,t){return b$4.resolve(e,t)}function Vt(e,t){return g.resolve(e,t)}function Xt(e,t){return a$3.resolve(e,t)}var _=b("rateLimitStorage");function tr(e){_.set(e);}function rr(){return _.get()}function Ne(){return {ip:e=>t=>q(t,e.ipHeader,e.trustProxy),user:e=>t=>{let n=ne(t);return n?`user:${n}`:q(t,e.ipHeader,e.trustProxy)},"api-key":e=>t=>{let n=we(t,e.apiKeyHeader);return n?`apikey:${n.substring(0,8)}`:q(t,e.ipHeader,e.trustProxy)},combined:e=>t=>{let n=q(t,e.ipHeader,e.trustProxy),r=ne(t);return r?`${n}:user:${r}`:n}}}function Be(e,t){if(typeof e=="function")return e;let r=Ne()[e];return r?r(t):o=>q(o,t.ipHeader,t.trustProxy)}async function $e(e,t,n,r){let o=await e.increment(t,r),s=Math.ceil((o.windowStart+r)/1e3),a=Math.max(0,n-o.count),i=o.count<=n;return {allowed:i,limit:n,remaining:a,resetAt:s,retryAfter:i?void 0:Math.ceil((o.windowStart+r-Date.now())/1e3)}}async function je(e,t,n,r){let o=Date.now(),s=await e.addTimestamp(t,r,o),a=s.timestamps.length,i=Math.max(0,n-a),c=a<=n,u=s.timestamps.length>0?Math.min(...s.timestamps):o,d=Math.ceil((u+r)/1e3),g;if(!c&&s.timestamps.length>0){let C=[...s.timestamps].sort((h,R)=>h-R),m=a-n;if(m>0&&C.length>=m){let h=C[m-1];g=Math.max(1,Math.ceil((h+r-o)/1e3));}}return {allowed:c,limit:n,remaining:i,resetAt:d,retryAfter:g}}function nr(e={}){let t=e.limit??100,n=e.windowSeconds??60,r=e.algorithm??"sliding-window",o=e.keyStrategy??"ip",s=e.keyPrefix??"rl",a=e.skipPaths??[],i=e.includeHeaders??true,c=e.errorMessage??"Too many requests",u=Be(o,e);return async(d,g)=>{let C=d.req.path;if(a.length>0&&ve(C,a))return g();let m=ke(d,e.storage);if(!m)return b$2().warn("Rate limit storage not configured. Skipping rate limiting."),g();let h=u(d);if(!h)return g();let R=t,l=n;if(e.getTier){let T=await e.getTier(d);R=T.limit,l=T.windowSeconds??n;}let P=l*1e3,w=Ie(s,C,h),f;if(r==="fixed-window"?f=await $e(m,w,R,P):f=await je(m,w,R,P),b$1(d,"rateLimit",f),b$1(d,"rateLimitKey",w),i&&(d.header("X-RateLimit-Limit",String(f.limit)),d.header("X-RateLimit-Remaining",String(f.remaining)),d.header("X-RateLimit-Reset",String(f.resetAt))),!f.allowed)throw f.retryAfter&&d.header("Retry-After",String(f.retryAfter)),e.onRateLimitExceeded&&await e.onRateLimitExceeded(d,f,w),new U(c,f.retryAfter??60);await g();}}async function or(e,t){let n=t??_.get();if(!n)throw new Error("Rate limit storage not configured");await n.reset(e);}export{Le as A,Rt as B,W as C,qt as D,Kt as E,Ht as F,Mt as G,ke as H,Pe as I,F as J,zt as K,Ut as L,Vt as M,Xt as N,V as O,Me as P,Oe as Q,ht as R,yt as S,xt as T,Ct as U,Et as V,Ye as a,ee as b,te as c,Ze as d,ye as e,xe as f,re as g,Ce as h,D as i,Ee as j,Se as k,Re as l,U as m,q as n,ne as o,we as p,st as q,ve as r,Ie as s,tr as t,rr as u,nr as v,or as w,Te as x,K as y,be as z};
@@ -1 +1 @@
1
- import {d}from'./chunk-UANCAA7V.js';var m=class{entriesById=new Map;entryIds=[];maxEntries;maxAge;cleanupInterval;lastCleanup=0;constructor(e){this.maxEntries=e?.maxEntries??1e4,this.maxAge=e?.maxAge??864e5,this.cleanupInterval=e?.cleanupInterval??3e5;}maybeCleanup(){if(this.cleanupInterval<=0||this.maxAge<=0)return;let e=Date.now();e-this.lastCleanup>=this.cleanupInterval&&(this.lastCleanup=e,this.deleteOlderThanSync(this.maxAge));}deleteOlderThanSync(e){let n=Date.now()-e,a=0;for(let t=this.entryIds.length-1;t>=0;t--){let s=this.entryIds[t],r=this.entriesById.get(s);if(r)if(new Date(r.timestamp).getTime()<n)this.entriesById.delete(s),this.entryIds.splice(t,1),a++;else break}return a}async store(e){for(this.maybeCleanup();this.entryIds.length>=this.maxEntries;){let n=this.entryIds.pop();n&&this.entriesById.delete(n);}this.entriesById.set(e.id,e),this.entryIds.unshift(e.id);}async query(e){this.maybeCleanup();let n=this.getFilteredEntries(e);if(e?.sort){let{field:s,direction:r}=e.sort;n=n.sort((i,o)=>{let g,u;switch(s){case "timestamp":g=new Date(i.timestamp).getTime(),u=new Date(o.timestamp).getTime();break;case "responseTimeMs":g=i.response.responseTimeMs,u=o.response.responseTimeMs;break;case "statusCode":g=i.response.statusCode,u=o.response.statusCode;break;default:return 0}return r==="asc"?g-u:u-g});}let a=e?.offset??0,t=e?.limit??n.length;return n.slice(a,a+t)}async getById(e){return this.entriesById.get(e)??null}async count(e){return this.getFilteredEntries(e).length}async deleteOlderThan(e){return this.deleteOlderThanSync(e)}async clear(){let e=this.entriesById.size;return this.entriesById.clear(),this.entryIds=[],e}destroy(){this.entriesById.clear(),this.entryIds=[];}getSize(){return this.entriesById.size}getFilteredEntries(e){if(!e)return Array.from(this.entriesById.values());let n=[];for(let a of this.entryIds){let t=this.entriesById.get(a);if(t&&!(e.level&&!(Array.isArray(e.level)?e.level:[e.level]).includes(t.level))&&!(e.method&&!(Array.isArray(e.method)?e.method:[e.method]).map(r=>r.toUpperCase()).includes(t.request.method.toUpperCase()))&&!(e.path&&!d(t.request.path,e.path))){if(e.statusCode){let{min:s,max:r}=e.statusCode,i=t.response.statusCode;if(s!==void 0&&i<s||r!==void 0&&i>r)continue}if(e.timeRange){let s=new Date(t.timestamp).getTime(),{start:r,end:i}=e.timeRange;if(r){let o=typeof r=="string"?new Date(r).getTime():r.getTime();if(s<o)continue}if(i){let o=typeof i=="string"?new Date(i).getTime():i.getTime();if(s>o)continue}}e.userId&&t.request.userId!==e.userId||e.clientIp&&t.request.clientIp!==e.clientIp||e.requestId&&t.id!==e.requestId||e.errorMessage&&(!t.error?.message||!t.error.message.toLowerCase().includes(e.errorMessage.toLowerCase()))||n.push(t);}}return n}};export{m as a};
1
+ import {d}from'./chunk-IPMPKM4J.js';var m=class{entriesById=new Map;entryIds=[];maxEntries;maxAge;cleanupInterval;lastCleanup=0;constructor(e){this.maxEntries=e?.maxEntries??1e4,this.maxAge=e?.maxAge??864e5,this.cleanupInterval=e?.cleanupInterval??3e5;}maybeCleanup(){if(this.cleanupInterval<=0||this.maxAge<=0)return;let e=Date.now();e-this.lastCleanup>=this.cleanupInterval&&(this.lastCleanup=e,this.deleteOlderThanSync(this.maxAge));}deleteOlderThanSync(e){let n=Date.now()-e,a=0;for(let t=this.entryIds.length-1;t>=0;t--){let s=this.entryIds[t],r=this.entriesById.get(s);if(r)if(new Date(r.timestamp).getTime()<n)this.entriesById.delete(s),this.entryIds.splice(t,1),a++;else break}return a}async store(e){for(this.maybeCleanup();this.entryIds.length>=this.maxEntries;){let n=this.entryIds.pop();n&&this.entriesById.delete(n);}this.entriesById.set(e.id,e),this.entryIds.unshift(e.id);}async query(e){this.maybeCleanup();let n=this.getFilteredEntries(e);if(e?.sort){let{field:s,direction:r}=e.sort;n=n.sort((i,o)=>{let g,u;switch(s){case "timestamp":g=new Date(i.timestamp).getTime(),u=new Date(o.timestamp).getTime();break;case "responseTimeMs":g=i.response.responseTimeMs,u=o.response.responseTimeMs;break;case "statusCode":g=i.response.statusCode,u=o.response.statusCode;break;default:return 0}return r==="asc"?g-u:u-g});}let a=e?.offset??0,t=e?.limit??n.length;return n.slice(a,a+t)}async getById(e){return this.entriesById.get(e)??null}async count(e){return this.getFilteredEntries(e).length}async deleteOlderThan(e){return this.deleteOlderThanSync(e)}async clear(){let e=this.entriesById.size;return this.entriesById.clear(),this.entryIds=[],e}destroy(){this.entriesById.clear(),this.entryIds=[];}getSize(){return this.entriesById.size}getFilteredEntries(e){if(!e)return Array.from(this.entriesById.values());let n=[];for(let a of this.entryIds){let t=this.entriesById.get(a);if(t&&!(e.level&&!(Array.isArray(e.level)?e.level:[e.level]).includes(t.level))&&!(e.method&&!(Array.isArray(e.method)?e.method:[e.method]).map(r=>r.toUpperCase()).includes(t.request.method.toUpperCase()))&&!(e.path&&!d(t.request.path,e.path))){if(e.statusCode){let{min:s,max:r}=e.statusCode,i=t.response.statusCode;if(s!==void 0&&i<s||r!==void 0&&i>r)continue}if(e.timeRange){let s=new Date(t.timestamp).getTime(),{start:r,end:i}=e.timeRange;if(r){let o=typeof r=="string"?new Date(r).getTime():r.getTime();if(s<o)continue}if(i){let o=typeof i=="string"?new Date(i).getTime():i.getTime();if(s>o)continue}}e.userId&&t.request.userId!==e.userId||e.clientIp&&t.request.clientIp!==e.clientIp||e.requestId&&t.id!==e.requestId||e.errorMessage&&(!t.error?.message||!t.error.message.toLowerCase().includes(e.errorMessage.toLowerCase()))||n.push(t);}}return n}};export{m as a};
@@ -1 +1 @@
1
- import {t,u,v as v$1,w,x,z,B,C,D,E as E$1,F,m as m$1,o,y,A,G,H,I,J,K,L,T,U,ba,ca}from'./chunk-ZBCVLQ3W.js';import {b,a}from'./chunk-KUFOENSK.js';import {z as z$1}from'zod';var E=new Map;function m(u){return E.has(u)||E.set(u,new Map),E.get(u)}function Ee(u,t,a){let n=m(a.model),e=a.localKey||"id",r=u[e];if(r==null)return u;let o=Array.from(n.values()).filter(s=>s[a.foreignKey]===r);switch(a.type){case "hasOne":return {...u,[t]:o[0]||null};case "hasMany":return {...u,[t]:o};case "belongsTo":{let s=u[a.foreignKey];if(s==null)return {...u,[t]:null};let i=Array.from(n.values()).find(d=>d[a.localKey||"id"]===s);return {...u,[t]:i||null}}default:return u}}function v(u,t,a){if(!a?.relations?.length||!t.model.relations)return u;let n={...u};for(let e of a.relations){let r=t.model.relations[e];r&&(n=Ee(n,e,r));}return n}function _e(){E.clear();}function Ie(u){return m(u)}function R(u,t,a){if(u==null||typeof u!="object")return false;let n=u;if(t.enabled){let e=n[t.field];if(e!=null)return false}if(a){for(let[e,r]of Object.entries(a))if(String(n[e])!==r)return false}return true}var P=Object.freeze({__memoryNoopTx:true,rolledBack:false}),se=class extends t{_tx=P;generateId(){return crypto.randomUUID()}async create(t){let a=m(this._meta.model.tableName),n=this._meta.model.primaryKeys[0],e=this.applyManagedInsertFields(t,"memory",()=>this.generateId()),r=String(e[n]);return a.set(r,e),e}async createNested(t,a,n,e){let r=m(n.model),o=[],s=Array.isArray(e)?e:[e];for(let i of s){if(typeof i!="object"||i===null)continue;let d={...i,id:crypto.randomUUID(),[n.foreignKey]:t};r.set(d.id,d),o.push(d);}return o}},ie=class extends u{async read(t,a,n){let r=m(this._meta.model.tableName).get(t),o=this.getSoftDeleteConfig();return !r||!R(r,o,a)?null:v(r,this._meta,n)}},ae=class extends v$1{_tx=P;async findExisting(t,a){let e=m(this._meta.model.tableName).get(t),r=this.getSoftDeleteConfig();return !e||!R(e,r,a)?null:{...e}}async update(t,a,n){let e=m(this._meta.model.tableName),r=e.get(t),o=this.getSoftDeleteConfig();if(!r||!R(r,o,n))return null;let s={...r,...this.applyManagedUpdateFields(a)};return e.set(t,s),s}async processNestedWrites(t,a,n,e){let r=m(n.model),o={created:[],updated:[],deleted:[],connected:[],disconnected:[]};if(e.create){let s=Array.isArray(e.create)?e.create:[e.create];for(let i of s){if(typeof i!="object"||i===null)continue;let d={...i,id:crypto.randomUUID(),[n.foreignKey]:t};r.set(d.id,d),o.created.push(d);}}if(e.update)for(let s of e.update){if(!s.id)continue;let i=r.get(String(s.id));if(!i||i[n.foreignKey]!==t)continue;let d={...i,...s};r.set(String(s.id),d),o.updated.push(d);}if(e.delete)for(let s of e.delete){let i=r.get(String(s));i&&i[n.foreignKey]===t&&(r.delete(String(s)),o.deleted.push(s));}if(e.connect)for(let s of e.connect){let i=r.get(String(s));if(!i)continue;let d={...i,[n.foreignKey]:t};r.set(String(s),d),o.connected.push(s);}if(e.disconnect)for(let s of e.disconnect){let i=r.get(String(s));if(!i||i[n.foreignKey]!==t)continue;let d={...i,[n.foreignKey]:null};r.set(String(s),d),o.disconnected.push(s);}if(e.set!==void 0){let s=Array.from(r.values()).filter(i=>i[n.foreignKey]===t);for(let i of s)if(i.id){let d={...i,[n.foreignKey]:null};r.set(String(i.id),d),o.disconnected.push(i.id);}if(e.set!==null){let i={...e.set,id:crypto.randomUUID(),[n.foreignKey]:t};r.set(i.id,i),o.created.push(i);}}return o}},de=class extends w{_tx=P;async findForDelete(t,a){let e=m(this._meta.model.tableName).get(t),r=this.getSoftDeleteConfig();return !e||!R(e,r,a)?null:e}async countRelated(t,a,n){let e=m(n.model),r=0;for(let o of e.values())o[n.foreignKey]===t&&r++;return r}async deleteRelated(t,a,n){let e=m(n.model),r=0;for(let[o,s]of e.entries())s[n.foreignKey]===t&&(e.delete(o),r++);return r}async nullifyRelated(t,a,n){let e=m(n.model),r=0;for(let[o,s]of e.entries())if(s[n.foreignKey]===t){let i={...s,[n.foreignKey]:null};e.set(o,i),r++;}return r}async delete(t,a){let n=m(this._meta.model.tableName),e=n.get(t),r=this.getSoftDeleteConfig();if(!e||!R(e,r,a))return null;if(r.enabled){let o={...e,[r.field]:new Date};return n.set(t,o),o}else return n.delete(t),e}},le=class extends x{async list(t){let a$1=m(this._meta.model.tableName),n=Array.from(a$1.values()),e=this.getSoftDeleteConfig();e.enabled&&(t.options.onlyDeleted?n=n.filter(l=>{let p=l[e.field];return p!=null}):t.options.withDeleted||(n=n.filter(l=>{let p=l[e.field];return p==null})));for(let l of t.filters)n=n.filter(p=>{let c=p[l.field];switch(l.operator){case "eq":return String(c)===String(l.value);case "ne":return String(c)!==String(l.value);case "gt":return Number(c)>Number(l.value);case "gte":return Number(c)>=Number(l.value);case "lt":return Number(c)<Number(l.value);case "lte":return Number(c)<=Number(l.value);case "in":return l.value.map(String).includes(String(c));case "nin":return !l.value.map(String).includes(String(c));case "like":return String(c).includes(String(l.value).replace(/%/g,""));case "ilike":return String(c).toLowerCase().includes(String(l.value).replace(/%/g,"").toLowerCase());case "null":return l.value?c===null:c!==null;case "between":{let[y,f]=l.value;return Number(c)>=Number(y)&&Number(c)<=Number(f)}default:return true}});if(t.options.search&&this.searchFields.length>0){let l=t.options.search.toLowerCase();n=n.filter(p=>this.searchFields.some(c=>{let y=p[c];return String(y).toLowerCase().includes(l)}));}let r=n.length;if(t.options.order_by){let l=t.options.order_by,p=t.options.order_by_direction==="desc"?-1:1;n.sort((c,y)=>{let f=c[l],b=y[l];return f<b?-1*p:f>b?1*p:0});}if(this.cursorPaginationEnabled&&(t.options.cursor||t.options.limit)){let l=this.cursorField||"id",p=t.options.limit||t.options.per_page||this.defaultPerPage,c=0;if(t.options.cursor){let x=b(t.options.cursor);if(x!==null){let I=n.findIndex(ve=>String(ve[l])===x);I!==-1&&(c=I+1);}}let y=n.slice(c,c+p),f={relations:t.options.include||[]},b$1=y.map(x=>v(x,this._meta,f)),M=c+p<n.length,w=c>0,j,S;if(M&&y.length>0){let x=y[y.length-1];j=a(x[l]);}if(w&&c>0){let x=n[c-1];S=a(x[l]);}return {result:b$1,result_info:{page:0,per_page:p,total_count:r,has_next_page:M,has_prev_page:w,next_cursor:j,prev_cursor:S}}}let o=t.options.page||1,s=t.options.per_page||this.defaultPerPage,i=(o-1)*s,d=n.slice(i,i+s),g={relations:t.options.include||[]},O=d.map(l=>v(l,this._meta,g)),h=Math.ceil(r/s);return {result:O,result_info:{page:o,per_page:s,total_count:r,total_pages:h,has_next_page:o<h,has_prev_page:o>1}}}},ce=class extends z{async restore(t,a){let n=m(this._meta.model.tableName),e=n.get(t),r=this.getSoftDeleteConfig();if(!e)return null;let o=e[r.field];if(o==null)return null;if(a){for(let[i,d]of Object.entries(a))if(String(e[i])!==d)return null}let s={...e,[r.field]:null};return n.set(t,s),s}};var ue=class extends B{generateId(){return crypto.randomUUID()}async batchCreate(t){let a=m(this._meta.model.tableName),n=this._meta.model.primaryKeys[0],e=[];for(let r of t){let o=this.applyManagedInsertFields(r,"memory",()=>this.generateId()),s=String(o[n]);a.set(s,o),e.push(o);}return e}},me=class extends C{async batchUpdate(t){let a=m(this._meta.model.tableName),n=this.getSoftDeleteConfig(),e=[],r=[];for(let o of t){let s=a.get(o.id);if(!s){r.push(o.id);continue}if(!R(s,n)){r.push(o.id);continue}let i={...s,...this.applyManagedUpdateFields(o.data)};a.set(o.id,i),e.push(i);}return {updated:e,notFound:r}}},ge=class extends D{async batchDelete(t){let a=m(this._meta.model.tableName),n=this.getSoftDeleteConfig(),e=[],r=[];for(let o of t){let s=a.get(o);if(!s){r.push(o);continue}if(!R(s,n)){r.push(o);continue}if(n.enabled){let i={...s,[n.field]:new Date};a.set(o,i),e.push(i);}else a.delete(o),e.push(s);}return {deleted:e,notFound:r}}},pe=class extends E$1{async batchRestore(t){let a=m(this._meta.model.tableName),n=this.getSoftDeleteConfig(),e=[],r=[];for(let o of t){let s=a.get(o);if(!s){r.push(o);continue}let i=s[n.field];if(i==null){r.push(o);continue}let d={...s,[n.field]:null};a.set(o,d),e.push(d);}return {restored:e,notFound:r}}},fe=class extends F{generateId(){return crypto.randomUUID()}async findExisting(t){let a=m(this._meta.model.tableName),n=this.getUpsertKeys();for(let e of a.values()){let r=true;for(let o of n){let s=t[o],i=e[o];if(s!==i){r=false;break}}if(r)return e}return null}async create(t){let a=m(this._meta.model.tableName),n=this._meta.model.primaryKeys[0],e=this.applyManagedInsertFields(t,"memory",()=>this.generateId());return a.set(String(e[n]),e),e}async update(t,a){let n=m(this._meta.model.tableName),e=this._meta.model.primaryKeys[0],r=String(t[e]),o={...t,...this.applyManagedUpdateFields(a)};return n.set(r,o),o}async nativeBatchUpsert(t,a){let n=m(this._meta.model.tableName),e=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],o=[],s=0,i=0;for(let d=0;d<t.length;d++){let g=t[d],O=null;for(let h of n.values()){let l=true;for(let p of e){let c=g[p],y=h[p];if(c!==y){l=false;break}}if(l){O=h;break}}if(O){let h={...g};if(this.createOnlyFields)for(let c of this.createOnlyFields)delete h[c];let l=String(O[r]),p={...O,...this.applyManagedUpdateFields(h)};n.set(l,p),o.push({data:p,created:false,index:d}),i++;}else {let h={...g};if(this.updateOnlyFields)for(let c of this.updateOnlyFields)delete h[c];let l=this.applyManagedInsertFields(h,"memory",()=>this.generateId()),p=String(l[r]);n.set(p,l),o.push({data:l,created:true,index:d}),s++;}}return {items:o,createdCount:s,updatedCount:i,totalCount:o.length}}};var _=class extends m$1{maxBulkSize=1e3;confirmThreshold=100;returnRecords=false;hookMode="parallel";filterFields;getSchema(){return {request:{body:{content:{"application/json":{schema:this.getUpdateSchema().partial()}}},query:z$1.object({dryRun:z$1.string().optional()}).passthrough()},responses:{200:{description:"Bulk patch result",content:{"application/json":{schema:z$1.object({success:z$1.boolean(),matched:z$1.number(),updated:z$1.number(),dryRun:z$1.boolean()})}}},400:{description:"Bad request",content:{"application/json":{schema:z$1.object({success:z$1.boolean(),error:z$1.string()})}}}}}}async handle(){let t=this.getContext(),n=(await this.getValidatedData()).body;if(!n||Object.keys(n).length===0)return this.error("Request body is required with at least one field to update","EMPTY_BODY",400);let e=t.req.query("dryRun"),r=e==="true"||e==="1",o$1=o(t.req.query(),{filterFields:this.filterFields,defaultPerPage:this.maxBulkSize,maxPerPage:this.maxBulkSize}),s=await this.countMatching(o$1);if(s===0)return this.json({success:true,matched:0,updated:0,dryRun:r});if(s>this.maxBulkSize)return this.error(`Bulk patch affects ${s} records, exceeding the maximum of ${this.maxBulkSize}. Use more specific filters.`,"BULK_TOO_LARGE",400);if(s>=this.confirmThreshold&&t.req.header("X-Confirm-Bulk")!=="true")return this.error(`This operation will affect ${s} records. Set X-Confirm-Bulk: true header to confirm.`,"CONFIRMATION_REQUIRED",400);if(r)return this.json({success:true,matched:s,updated:0,dryRun:true});let i=n;this.beforeBulkPatch&&(i=await this.beforeBulkPatch(i,o$1,s));let d=await this.applyPatch(i,o$1),g={matched:s,updated:d.updated,dryRun:false,records:this.returnRecords?d.records:void 0};return this.afterBulkPatch&&await this.afterBulkPatch(g),this.json({success:true,matched:g.matched,updated:g.updated,dryRun:false,...this.returnRecords&&g.records?{records:g.records}:{}})}};var Me=class extends y{generateId(){return crypto.randomUUID()}async findSource(t,a){let e=m(this._meta.model.tableName).get(t),r=this.getSoftDeleteConfig();return !e||!R(e,r,a)?null:e}async createClone(t){let a=m(this._meta.model.tableName),n=this._meta.model.primaryKeys[0],e=this.applyManagedInsertFields(t,"memory",()=>this.generateId()),r=String(e[n]);return a.set(r,e),e}},be=class extends A{generateId(){return crypto.randomUUID()}async findExisting(t){let a=m(this._meta.model.tableName),n=this.getUpsertKeys(),e=this.getSoftDeleteConfig();for(let r of a.values()){if(e.enabled){let s=r[e.field];if(s!=null)continue}let o=true;for(let s of n){let i=t[s],d=r[s];if(i!==d){o=false;break}}if(o)return r}return null}async create(t){let a=m(this._meta.model.tableName),n=this._meta.model.primaryKeys[0],e=this.applyManagedInsertFields(t,"memory",()=>this.generateId());return a.set(String(e[n]),e),e}async update(t,a){let n=m(this._meta.model.tableName),e=this._meta.model.primaryKeys[0],r=String(t[e]),o={...t,...this.applyManagedUpdateFields(a)};return n.set(r,o),o}async nativeUpsert(t,a){let n=m(this._meta.model.tableName),e=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],o=this.getSoftDeleteConfig(),s=null;for(let i of n.values()){if(o.enabled){let g=i[o.field];if(g!=null)continue}let d=true;for(let g of e){let O=t[g],h=i[g];if(O!==h){d=false;break}}if(d){s=i;break}}if(s){let i={...t};if(this.createOnlyFields)for(let O of this.createOnlyFields)delete i[O];let d=String(s[r]),g={...s,...this.applyManagedUpdateFields(i)};return n.set(d,g),{data:g,created:false}}else {let i={...t};if(this.updateOnlyFields)for(let O of this.updateOnlyFields)delete i[O];let d=this.applyManagedInsertFields(i,"memory",()=>this.generateId()),g=String(d[r]);return n.set(g,d),{data:d,created:true}}}async processNestedWrites(t,a,n,e){let r=m(n.model),o={created:[],updated:[],deleted:[],connected:[],disconnected:[]};if(e.create){let s=Array.isArray(e.create)?e.create:[e.create];for(let i of s){if(typeof i!="object"||i===null)continue;let d={...i,id:crypto.randomUUID(),[n.foreignKey]:t};r.set(d.id,d),o.created.push(d);}}if(e.update)for(let s of e.update){let i=String(s.id),d=r.get(i);if(d&&d[n.foreignKey]===t){let g={...d,...s};r.set(i,g),o.updated.push(g);}}if(e.delete)for(let s of e.delete){let i=String(s),d=r.get(i);d&&d[n.foreignKey]===t&&(r.delete(i),o.deleted.push(s));}if(e.connect)for(let s of e.connect){let i=String(s),d=r.get(i);if(d){let g={...d,[n.foreignKey]:t};r.set(i,g),o.connected.push(s);}}if(e.disconnect)for(let s of e.disconnect){let i=String(s),d=r.get(i);if(d&&d[n.foreignKey]===t){let g={...d,[n.foreignKey]:null};r.set(i,g),o.disconnected.push(s);}}return o}},he=class extends G{async recordExists(t){return m(this._meta.model.tableName).has(t)}},ye=class extends H{},Oe=class extends I{},xe=class extends J{async rollback(t,a,n){let e=m(this._meta.model.tableName),r=this.getVersioningConfig().field,o={...a,[r]:n};return e.set(t,o),o}},Re=class extends K{async aggregate(t){let a=m(this._meta.model.tableName),n=Array.from(a.values()),e=this.getSoftDeleteConfig();if(e.enabled){let{query:r}=await this.getValidatedData();r?.withDeleted===true||r?.withDeleted==="true"||(n=n.filter(s=>{let i=s[e.field];return i==null}));}if(t.filters)for(let[r,o]of Object.entries(t.filters))n=n.filter(s=>{if(typeof o=="object"&&o!==null){for(let[i,d]of Object.entries(o)){let g=s[r];switch(i){case "eq":return String(g)===String(d);case "ne":return String(g)!==String(d);case "gt":return Number(g)>Number(d);case "gte":return Number(g)>=Number(d);case "lt":return Number(g)<Number(d);case "lte":return Number(g)<=Number(d);case "in":return d.map(String).includes(String(g));default:return true}}return true}return String(s[r])===String(o)});return L(n,t)}},ke=class extends T{async search(t,a){let n=m(this._meta.model.tableName),e=Array.from(n.values()),r=this.getSoftDeleteConfig();r.enabled&&(a.options.onlyDeleted?e=e.filter(f=>{let b=f[r.field];return b!=null}):a.options.withDeleted||(e=e.filter(f=>{let b=f[r.field];return b==null})));for(let f of a.filters)e=e.filter(b=>{let M=b[f.field];switch(f.operator){case "eq":return String(M)===String(f.value);case "ne":return String(M)!==String(f.value);case "gt":return Number(M)>Number(f.value);case "gte":return Number(M)>=Number(f.value);case "lt":return Number(M)<Number(f.value);case "lte":return Number(M)<=Number(f.value);case "in":return f.value.map(String).includes(String(M));case "nin":return !f.value.map(String).includes(String(M));case "like":return String(M).includes(String(f.value).replace(/%/g,""));case "ilike":return String(M).toLowerCase().includes(String(f.value).replace(/%/g,"").toLowerCase());case "null":return f.value?M===null:M!==null;case "between":{let[w,j]=f.value;return Number(M)>=Number(w)&&Number(M)<=Number(j)}default:return true}});let o=this.getSearchableFields(),s=e,i=t;if(t.mode==="all"){let f=t.query.toLowerCase().split(/\s+/).filter(M=>M.length>0),b=t.fields||Object.keys(o);f.length>0&&(s=s.filter(M=>{let w=M;return f.every(j=>b.some(S=>{let x=w[S];return x==null?false:(Array.isArray(x)?x.join(" "):String(x)).toLowerCase().includes(j)}))})),i={...t,mode:"any"};}let d=U(s,i,o),g=d.length;if(a.options.order_by){let f=a.options.order_by,b=a.options.order_by_direction==="desc"?-1:1;d.sort((M,w)=>{let j=M.item[f],S=w.item[f];return j<S?-1*b:j>S?1*b:0});}let O=a.options.page||1,h=a.options.per_page||this.defaultPerPage,l=(O-1)*h,p=d.slice(l,l+h),c={relations:a.options.include||[]};return {items:p.map(f=>({...f,item:v(f.item,this._meta,c)})),totalCount:g}}},je=class extends ba{async list(t){let a=m(this._meta.model.tableName),n=Array.from(a.values()),e=this.getSoftDeleteConfig();e.enabled&&(t.options.onlyDeleted?n=n.filter(l=>{let p=l[e.field];return p!=null}):t.options.withDeleted||(n=n.filter(l=>{let p=l[e.field];return p==null})));for(let l of t.filters)n=n.filter(p=>{let c=p[l.field];switch(l.operator){case "eq":return String(c)===String(l.value);case "ne":return String(c)!==String(l.value);case "gt":return Number(c)>Number(l.value);case "gte":return Number(c)>=Number(l.value);case "lt":return Number(c)<Number(l.value);case "lte":return Number(c)<=Number(l.value);case "in":return l.value.map(String).includes(String(c));case "nin":return !l.value.map(String).includes(String(c));case "like":return String(c).includes(String(l.value).replace(/%/g,""));case "ilike":return String(c).toLowerCase().includes(String(l.value).replace(/%/g,"").toLowerCase());case "null":return l.value?c===null:c!==null;case "between":{let[y,f]=l.value;return Number(c)>=Number(y)&&Number(c)<=Number(f)}default:return true}});if(t.options.search&&this.searchFields.length>0){let l=t.options.search.toLowerCase();n=n.filter(p=>this.searchFields.some(c=>{let y=p[c];return String(y).toLowerCase().includes(l)}));}let r=n.length;if(t.options.order_by){let l=t.options.order_by,p=t.options.order_by_direction==="desc"?-1:1;n.sort((c,y)=>{let f=c[l],b=y[l];return f<b?-1*p:f>b?1*p:0});}let o=t.options.page||1,s=t.options.per_page||this.defaultPerPage,i=(o-1)*s,d=n.slice(i,i+s),g={relations:t.options.include||[]},O=d.map(l=>v(l,this._meta,g)),h=Math.ceil(r/s);return {result:O,result_info:{page:o,per_page:s,total_count:r,total_pages:h,has_next_page:o<h,has_prev_page:o>1}}}},we=class extends ca{generateId(){return crypto.randomUUID()}async findExisting(t){let a=m(this._meta.model.tableName),n=this.getUpsertKeys(),e=this.getSoftDeleteConfig();for(let r of a.values()){if(e.enabled){let s=r[e.field];if(s!=null)continue}let o=true;for(let s of n){let i=t[s],d=r[s];if(i!==d){o=false;break}}if(o)return r}return null}async create(t){let a=m(this._meta.model.tableName),n=this._meta.model.primaryKeys[0],e=this.applyManagedInsertFields(t,"memory",()=>this.generateId());return a.set(String(e[n]),e),e}async update(t,a){let n=m(this._meta.model.tableName),e=this._meta.model.primaryKeys[0],r=String(t[e]),o={...t,...this.applyManagedUpdateFields(a)};return n.set(r,o),o}},Se=class extends _{async countMatching(t){return this.getFilteredItems(t).length}async applyPatch(t,a){let n=m(this._meta.model.tableName),e=this._meta.model.primaryKeys[0],r=this.getFilteredItems(a),o=[];for(let s of r){let i=String(s[e]),d={...s,...t};n.set(i,d),o.push(d);}return {updated:o.length,records:o}}getFilteredItems(t){let a=m(this._meta.model.tableName),n=Array.from(a.values());for(let e of t.filters)n=n.filter(r=>{let o=r[e.field];switch(e.operator){case "eq":return String(o)===String(e.value);case "ne":return String(o)!==String(e.value);case "gt":return Number(o)>Number(e.value);case "gte":return Number(o)>=Number(e.value);case "lt":return Number(o)<Number(e.value);case "lte":return Number(o)<=Number(e.value);case "in":return e.value.map(String).includes(String(o));case "nin":return !e.value.map(String).includes(String(o));case "like":return String(o).includes(String(e.value).replace(/%/g,""));case "ilike":return String(o).toLowerCase().includes(String(e.value).replace(/%/g,"").toLowerCase());case "null":return e.value?o===null:o!==null;default:return true}});return n}};export{we as A,Se as B,_ as a,E as b,m as c,_e as d,Ie as e,P as f,se as g,ie as h,ae as i,de as j,le as k,ce as l,ue as m,me as n,ge as o,pe as p,fe as q,Me as r,be as s,he as t,ye as u,Oe as v,xe as w,Re as x,ke as y,je as z};
1
+ import {t,u,v as v$1,w,x,z,B,C,D,E as E$1,F,m as m$1,o,y,A,G,H,I,J,K,L,T,U,ba,ca}from'./chunk-V4YEHNEZ.js';import {b,a}from'./chunk-KUFOENSK.js';import {z as z$1}from'zod';var E=new Map;function m(u){return E.has(u)||E.set(u,new Map),E.get(u)}function Ee(u,t,a){let n=m(a.model),e=a.localKey||"id",r=u[e];if(r==null)return u;let o=Array.from(n.values()).filter(s=>s[a.foreignKey]===r);switch(a.type){case "hasOne":return {...u,[t]:o[0]||null};case "hasMany":return {...u,[t]:o};case "belongsTo":{let s=u[a.foreignKey];if(s==null)return {...u,[t]:null};let i=Array.from(n.values()).find(d=>d[a.localKey||"id"]===s);return {...u,[t]:i||null}}default:return u}}function v(u,t,a){if(!a?.relations?.length||!t.model.relations)return u;let n={...u};for(let e of a.relations){let r=t.model.relations[e];r&&(n=Ee(n,e,r));}return n}function _e(){E.clear();}function Ie(u){return m(u)}function R(u,t,a){if(u==null||typeof u!="object")return false;let n=u;if(t.enabled){let e=n[t.field];if(e!=null)return false}if(a){for(let[e,r]of Object.entries(a))if(String(n[e])!==r)return false}return true}var P=Object.freeze({__memoryNoopTx:true,rolledBack:false}),se=class extends t{_tx=P;generateId(){return crypto.randomUUID()}async create(t){let a=m(this._meta.model.tableName),n=this._meta.model.primaryKeys[0],e=this.applyManagedInsertFields(t,"memory",()=>this.generateId()),r=String(e[n]);return a.set(r,e),e}async createNested(t,a,n,e){let r=m(n.model),o=[],s=Array.isArray(e)?e:[e];for(let i of s){if(typeof i!="object"||i===null)continue;let d={...i,id:crypto.randomUUID(),[n.foreignKey]:t};r.set(d.id,d),o.push(d);}return o}},ie=class extends u{async read(t,a,n){let r=m(this._meta.model.tableName).get(t),o=this.getSoftDeleteConfig();return !r||!R(r,o,a)?null:v(r,this._meta,n)}},ae=class extends v$1{_tx=P;async findExisting(t,a){let e=m(this._meta.model.tableName).get(t),r=this.getSoftDeleteConfig();return !e||!R(e,r,a)?null:{...e}}async update(t,a,n){let e=m(this._meta.model.tableName),r=e.get(t),o=this.getSoftDeleteConfig();if(!r||!R(r,o,n))return null;let s={...r,...this.applyManagedUpdateFields(a)};return e.set(t,s),s}async processNestedWrites(t,a,n,e){let r=m(n.model),o={created:[],updated:[],deleted:[],connected:[],disconnected:[]};if(e.create){let s=Array.isArray(e.create)?e.create:[e.create];for(let i of s){if(typeof i!="object"||i===null)continue;let d={...i,id:crypto.randomUUID(),[n.foreignKey]:t};r.set(d.id,d),o.created.push(d);}}if(e.update)for(let s of e.update){if(!s.id)continue;let i=r.get(String(s.id));if(!i||i[n.foreignKey]!==t)continue;let d={...i,...s};r.set(String(s.id),d),o.updated.push(d);}if(e.delete)for(let s of e.delete){let i=r.get(String(s));i&&i[n.foreignKey]===t&&(r.delete(String(s)),o.deleted.push(s));}if(e.connect)for(let s of e.connect){let i=r.get(String(s));if(!i)continue;let d={...i,[n.foreignKey]:t};r.set(String(s),d),o.connected.push(s);}if(e.disconnect)for(let s of e.disconnect){let i=r.get(String(s));if(!i||i[n.foreignKey]!==t)continue;let d={...i,[n.foreignKey]:null};r.set(String(s),d),o.disconnected.push(s);}if(e.set!==void 0){let s=Array.from(r.values()).filter(i=>i[n.foreignKey]===t);for(let i of s)if(i.id){let d={...i,[n.foreignKey]:null};r.set(String(i.id),d),o.disconnected.push(i.id);}if(e.set!==null){let i={...e.set,id:crypto.randomUUID(),[n.foreignKey]:t};r.set(i.id,i),o.created.push(i);}}return o}},de=class extends w{_tx=P;async findForDelete(t,a){let e=m(this._meta.model.tableName).get(t),r=this.getSoftDeleteConfig();return !e||!R(e,r,a)?null:e}async countRelated(t,a,n){let e=m(n.model),r=0;for(let o of e.values())o[n.foreignKey]===t&&r++;return r}async deleteRelated(t,a,n){let e=m(n.model),r=0;for(let[o,s]of e.entries())s[n.foreignKey]===t&&(e.delete(o),r++);return r}async nullifyRelated(t,a,n){let e=m(n.model),r=0;for(let[o,s]of e.entries())if(s[n.foreignKey]===t){let i={...s,[n.foreignKey]:null};e.set(o,i),r++;}return r}async delete(t,a){let n=m(this._meta.model.tableName),e=n.get(t),r=this.getSoftDeleteConfig();if(!e||!R(e,r,a))return null;if(r.enabled){let o={...e,[r.field]:new Date};return n.set(t,o),o}else return n.delete(t),e}},le=class extends x{async list(t){let a$1=m(this._meta.model.tableName),n=Array.from(a$1.values()),e=this.getSoftDeleteConfig();e.enabled&&(t.options.onlyDeleted?n=n.filter(l=>{let p=l[e.field];return p!=null}):t.options.withDeleted||(n=n.filter(l=>{let p=l[e.field];return p==null})));for(let l of t.filters)n=n.filter(p=>{let c=p[l.field];switch(l.operator){case "eq":return String(c)===String(l.value);case "ne":return String(c)!==String(l.value);case "gt":return Number(c)>Number(l.value);case "gte":return Number(c)>=Number(l.value);case "lt":return Number(c)<Number(l.value);case "lte":return Number(c)<=Number(l.value);case "in":return l.value.map(String).includes(String(c));case "nin":return !l.value.map(String).includes(String(c));case "like":return String(c).includes(String(l.value).replace(/%/g,""));case "ilike":return String(c).toLowerCase().includes(String(l.value).replace(/%/g,"").toLowerCase());case "null":return l.value?c===null:c!==null;case "between":{let[y,f]=l.value;return Number(c)>=Number(y)&&Number(c)<=Number(f)}default:return true}});if(t.options.search&&this.searchFields.length>0){let l=t.options.search.toLowerCase();n=n.filter(p=>this.searchFields.some(c=>{let y=p[c];return String(y).toLowerCase().includes(l)}));}let r=n.length;if(t.options.order_by){let l=t.options.order_by,p=t.options.order_by_direction==="desc"?-1:1;n.sort((c,y)=>{let f=c[l],b=y[l];return f<b?-1*p:f>b?1*p:0});}if(this.cursorPaginationEnabled&&(t.options.cursor||t.options.limit)){let l=this.cursorField||"id",p=t.options.limit||t.options.per_page||this.defaultPerPage,c=0;if(t.options.cursor){let x=b(t.options.cursor);if(x!==null){let I=n.findIndex(ve=>String(ve[l])===x);I!==-1&&(c=I+1);}}let y=n.slice(c,c+p),f={relations:t.options.include||[]},b$1=y.map(x=>v(x,this._meta,f)),M=c+p<n.length,w=c>0,j,S;if(M&&y.length>0){let x=y[y.length-1];j=a(x[l]);}if(w&&c>0){let x=n[c-1];S=a(x[l]);}return {result:b$1,result_info:{page:0,per_page:p,total_count:r,has_next_page:M,has_prev_page:w,next_cursor:j,prev_cursor:S}}}let o=t.options.page||1,s=t.options.per_page||this.defaultPerPage,i=(o-1)*s,d=n.slice(i,i+s),g={relations:t.options.include||[]},O=d.map(l=>v(l,this._meta,g)),h=Math.ceil(r/s);return {result:O,result_info:{page:o,per_page:s,total_count:r,total_pages:h,has_next_page:o<h,has_prev_page:o>1}}}},ce=class extends z{async restore(t,a){let n=m(this._meta.model.tableName),e=n.get(t),r=this.getSoftDeleteConfig();if(!e)return null;let o=e[r.field];if(o==null)return null;if(a){for(let[i,d]of Object.entries(a))if(String(e[i])!==d)return null}let s={...e,[r.field]:null};return n.set(t,s),s}};var ue=class extends B{generateId(){return crypto.randomUUID()}async batchCreate(t){let a=m(this._meta.model.tableName),n=this._meta.model.primaryKeys[0],e=[];for(let r of t){let o=this.applyManagedInsertFields(r,"memory",()=>this.generateId()),s=String(o[n]);a.set(s,o),e.push(o);}return e}},me=class extends C{async batchUpdate(t){let a=m(this._meta.model.tableName),n=this.getSoftDeleteConfig(),e=[],r=[];for(let o of t){let s=a.get(o.id);if(!s){r.push(o.id);continue}if(!R(s,n)){r.push(o.id);continue}let i={...s,...this.applyManagedUpdateFields(o.data)};a.set(o.id,i),e.push(i);}return {updated:e,notFound:r}}},ge=class extends D{async batchDelete(t){let a=m(this._meta.model.tableName),n=this.getSoftDeleteConfig(),e=[],r=[];for(let o of t){let s=a.get(o);if(!s){r.push(o);continue}if(!R(s,n)){r.push(o);continue}if(n.enabled){let i={...s,[n.field]:new Date};a.set(o,i),e.push(i);}else a.delete(o),e.push(s);}return {deleted:e,notFound:r}}},pe=class extends E$1{async batchRestore(t){let a=m(this._meta.model.tableName),n=this.getSoftDeleteConfig(),e=[],r=[];for(let o of t){let s=a.get(o);if(!s){r.push(o);continue}let i=s[n.field];if(i==null){r.push(o);continue}let d={...s,[n.field]:null};a.set(o,d),e.push(d);}return {restored:e,notFound:r}}},fe=class extends F{generateId(){return crypto.randomUUID()}async findExisting(t){let a=m(this._meta.model.tableName),n=this.getUpsertKeys();for(let e of a.values()){let r=true;for(let o of n){let s=t[o],i=e[o];if(s!==i){r=false;break}}if(r)return e}return null}async create(t){let a=m(this._meta.model.tableName),n=this._meta.model.primaryKeys[0],e=this.applyManagedInsertFields(t,"memory",()=>this.generateId());return a.set(String(e[n]),e),e}async update(t,a){let n=m(this._meta.model.tableName),e=this._meta.model.primaryKeys[0],r=String(t[e]),o={...t,...this.applyManagedUpdateFields(a)};return n.set(r,o),o}async nativeBatchUpsert(t,a){let n=m(this._meta.model.tableName),e=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],o=[],s=0,i=0;for(let d=0;d<t.length;d++){let g=t[d],O=null;for(let h of n.values()){let l=true;for(let p of e){let c=g[p],y=h[p];if(c!==y){l=false;break}}if(l){O=h;break}}if(O){let h={...g};if(this.createOnlyFields)for(let c of this.createOnlyFields)delete h[c];let l=String(O[r]),p={...O,...this.applyManagedUpdateFields(h)};n.set(l,p),o.push({data:p,created:false,index:d}),i++;}else {let h={...g};if(this.updateOnlyFields)for(let c of this.updateOnlyFields)delete h[c];let l=this.applyManagedInsertFields(h,"memory",()=>this.generateId()),p=String(l[r]);n.set(p,l),o.push({data:l,created:true,index:d}),s++;}}return {items:o,createdCount:s,updatedCount:i,totalCount:o.length}}};var _=class extends m$1{maxBulkSize=1e3;confirmThreshold=100;returnRecords=false;hookMode="parallel";filterFields;getSchema(){return {request:{body:{content:{"application/json":{schema:this.getUpdateSchema().partial()}}},query:z$1.object({dryRun:z$1.string().optional()}).passthrough()},responses:{200:{description:"Bulk patch result",content:{"application/json":{schema:z$1.object({success:z$1.boolean(),matched:z$1.number(),updated:z$1.number(),dryRun:z$1.boolean()})}}},400:{description:"Bad request",content:{"application/json":{schema:z$1.object({success:z$1.boolean(),error:z$1.string()})}}}}}}async handle(){let t=this.getContext(),n=(await this.getValidatedData()).body;if(!n||Object.keys(n).length===0)return this.error("Request body is required with at least one field to update","EMPTY_BODY",400);let e=t.req.query("dryRun"),r=e==="true"||e==="1",o$1=o(t.req.query(),{filterFields:this.filterFields,defaultPerPage:this.maxBulkSize,maxPerPage:this.maxBulkSize}),s=await this.countMatching(o$1);if(s===0)return this.json({success:true,matched:0,updated:0,dryRun:r});if(s>this.maxBulkSize)return this.error(`Bulk patch affects ${s} records, exceeding the maximum of ${this.maxBulkSize}. Use more specific filters.`,"BULK_TOO_LARGE",400);if(s>=this.confirmThreshold&&t.req.header("X-Confirm-Bulk")!=="true")return this.error(`This operation will affect ${s} records. Set X-Confirm-Bulk: true header to confirm.`,"CONFIRMATION_REQUIRED",400);if(r)return this.json({success:true,matched:s,updated:0,dryRun:true});let i=n;this.beforeBulkPatch&&(i=await this.beforeBulkPatch(i,o$1,s));let d=await this.applyPatch(i,o$1),g={matched:s,updated:d.updated,dryRun:false,records:this.returnRecords?d.records:void 0};return this.afterBulkPatch&&await this.afterBulkPatch(g),this.json({success:true,matched:g.matched,updated:g.updated,dryRun:false,...this.returnRecords&&g.records?{records:g.records}:{}})}};var Me=class extends y{generateId(){return crypto.randomUUID()}async findSource(t,a){let e=m(this._meta.model.tableName).get(t),r=this.getSoftDeleteConfig();return !e||!R(e,r,a)?null:e}async createClone(t){let a=m(this._meta.model.tableName),n=this._meta.model.primaryKeys[0],e=this.applyManagedInsertFields(t,"memory",()=>this.generateId()),r=String(e[n]);return a.set(r,e),e}},be=class extends A{generateId(){return crypto.randomUUID()}async findExisting(t){let a=m(this._meta.model.tableName),n=this.getUpsertKeys(),e=this.getSoftDeleteConfig();for(let r of a.values()){if(e.enabled){let s=r[e.field];if(s!=null)continue}let o=true;for(let s of n){let i=t[s],d=r[s];if(i!==d){o=false;break}}if(o)return r}return null}async create(t){let a=m(this._meta.model.tableName),n=this._meta.model.primaryKeys[0],e=this.applyManagedInsertFields(t,"memory",()=>this.generateId());return a.set(String(e[n]),e),e}async update(t,a){let n=m(this._meta.model.tableName),e=this._meta.model.primaryKeys[0],r=String(t[e]),o={...t,...this.applyManagedUpdateFields(a)};return n.set(r,o),o}async nativeUpsert(t,a){let n=m(this._meta.model.tableName),e=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],o=this.getSoftDeleteConfig(),s=null;for(let i of n.values()){if(o.enabled){let g=i[o.field];if(g!=null)continue}let d=true;for(let g of e){let O=t[g],h=i[g];if(O!==h){d=false;break}}if(d){s=i;break}}if(s){let i={...t};if(this.createOnlyFields)for(let O of this.createOnlyFields)delete i[O];let d=String(s[r]),g={...s,...this.applyManagedUpdateFields(i)};return n.set(d,g),{data:g,created:false}}else {let i={...t};if(this.updateOnlyFields)for(let O of this.updateOnlyFields)delete i[O];let d=this.applyManagedInsertFields(i,"memory",()=>this.generateId()),g=String(d[r]);return n.set(g,d),{data:d,created:true}}}async processNestedWrites(t,a,n,e){let r=m(n.model),o={created:[],updated:[],deleted:[],connected:[],disconnected:[]};if(e.create){let s=Array.isArray(e.create)?e.create:[e.create];for(let i of s){if(typeof i!="object"||i===null)continue;let d={...i,id:crypto.randomUUID(),[n.foreignKey]:t};r.set(d.id,d),o.created.push(d);}}if(e.update)for(let s of e.update){let i=String(s.id),d=r.get(i);if(d&&d[n.foreignKey]===t){let g={...d,...s};r.set(i,g),o.updated.push(g);}}if(e.delete)for(let s of e.delete){let i=String(s),d=r.get(i);d&&d[n.foreignKey]===t&&(r.delete(i),o.deleted.push(s));}if(e.connect)for(let s of e.connect){let i=String(s),d=r.get(i);if(d){let g={...d,[n.foreignKey]:t};r.set(i,g),o.connected.push(s);}}if(e.disconnect)for(let s of e.disconnect){let i=String(s),d=r.get(i);if(d&&d[n.foreignKey]===t){let g={...d,[n.foreignKey]:null};r.set(i,g),o.disconnected.push(s);}}return o}},he=class extends G{async recordExists(t){return m(this._meta.model.tableName).has(t)}},ye=class extends H{},Oe=class extends I{},xe=class extends J{async rollback(t,a,n){let e=m(this._meta.model.tableName),r=this.getVersioningConfig().field,o={...a,[r]:n};return e.set(t,o),o}},Re=class extends K{async aggregate(t){let a=m(this._meta.model.tableName),n=Array.from(a.values()),e=this.getSoftDeleteConfig();if(e.enabled){let{query:r}=await this.getValidatedData();r?.withDeleted===true||r?.withDeleted==="true"||(n=n.filter(s=>{let i=s[e.field];return i==null}));}if(t.filters)for(let[r,o]of Object.entries(t.filters))n=n.filter(s=>{if(typeof o=="object"&&o!==null){for(let[i,d]of Object.entries(o)){let g=s[r];switch(i){case "eq":return String(g)===String(d);case "ne":return String(g)!==String(d);case "gt":return Number(g)>Number(d);case "gte":return Number(g)>=Number(d);case "lt":return Number(g)<Number(d);case "lte":return Number(g)<=Number(d);case "in":return d.map(String).includes(String(g));default:return true}}return true}return String(s[r])===String(o)});return L(n,t)}},ke=class extends T{async search(t,a){let n=m(this._meta.model.tableName),e=Array.from(n.values()),r=this.getSoftDeleteConfig();r.enabled&&(a.options.onlyDeleted?e=e.filter(f=>{let b=f[r.field];return b!=null}):a.options.withDeleted||(e=e.filter(f=>{let b=f[r.field];return b==null})));for(let f of a.filters)e=e.filter(b=>{let M=b[f.field];switch(f.operator){case "eq":return String(M)===String(f.value);case "ne":return String(M)!==String(f.value);case "gt":return Number(M)>Number(f.value);case "gte":return Number(M)>=Number(f.value);case "lt":return Number(M)<Number(f.value);case "lte":return Number(M)<=Number(f.value);case "in":return f.value.map(String).includes(String(M));case "nin":return !f.value.map(String).includes(String(M));case "like":return String(M).includes(String(f.value).replace(/%/g,""));case "ilike":return String(M).toLowerCase().includes(String(f.value).replace(/%/g,"").toLowerCase());case "null":return f.value?M===null:M!==null;case "between":{let[w,j]=f.value;return Number(M)>=Number(w)&&Number(M)<=Number(j)}default:return true}});let o=this.getSearchableFields(),s=e,i=t;if(t.mode==="all"){let f=t.query.toLowerCase().split(/\s+/).filter(M=>M.length>0),b=t.fields||Object.keys(o);f.length>0&&(s=s.filter(M=>{let w=M;return f.every(j=>b.some(S=>{let x=w[S];return x==null?false:(Array.isArray(x)?x.join(" "):String(x)).toLowerCase().includes(j)}))})),i={...t,mode:"any"};}let d=U(s,i,o),g=d.length;if(a.options.order_by){let f=a.options.order_by,b=a.options.order_by_direction==="desc"?-1:1;d.sort((M,w)=>{let j=M.item[f],S=w.item[f];return j<S?-1*b:j>S?1*b:0});}let O=a.options.page||1,h=a.options.per_page||this.defaultPerPage,l=(O-1)*h,p=d.slice(l,l+h),c={relations:a.options.include||[]};return {items:p.map(f=>({...f,item:v(f.item,this._meta,c)})),totalCount:g}}},je=class extends ba{async list(t){let a=m(this._meta.model.tableName),n=Array.from(a.values()),e=this.getSoftDeleteConfig();e.enabled&&(t.options.onlyDeleted?n=n.filter(l=>{let p=l[e.field];return p!=null}):t.options.withDeleted||(n=n.filter(l=>{let p=l[e.field];return p==null})));for(let l of t.filters)n=n.filter(p=>{let c=p[l.field];switch(l.operator){case "eq":return String(c)===String(l.value);case "ne":return String(c)!==String(l.value);case "gt":return Number(c)>Number(l.value);case "gte":return Number(c)>=Number(l.value);case "lt":return Number(c)<Number(l.value);case "lte":return Number(c)<=Number(l.value);case "in":return l.value.map(String).includes(String(c));case "nin":return !l.value.map(String).includes(String(c));case "like":return String(c).includes(String(l.value).replace(/%/g,""));case "ilike":return String(c).toLowerCase().includes(String(l.value).replace(/%/g,"").toLowerCase());case "null":return l.value?c===null:c!==null;case "between":{let[y,f]=l.value;return Number(c)>=Number(y)&&Number(c)<=Number(f)}default:return true}});if(t.options.search&&this.searchFields.length>0){let l=t.options.search.toLowerCase();n=n.filter(p=>this.searchFields.some(c=>{let y=p[c];return String(y).toLowerCase().includes(l)}));}let r=n.length;if(t.options.order_by){let l=t.options.order_by,p=t.options.order_by_direction==="desc"?-1:1;n.sort((c,y)=>{let f=c[l],b=y[l];return f<b?-1*p:f>b?1*p:0});}let o=t.options.page||1,s=t.options.per_page||this.defaultPerPage,i=(o-1)*s,d=n.slice(i,i+s),g={relations:t.options.include||[]},O=d.map(l=>v(l,this._meta,g)),h=Math.ceil(r/s);return {result:O,result_info:{page:o,per_page:s,total_count:r,total_pages:h,has_next_page:o<h,has_prev_page:o>1}}}},we=class extends ca{generateId(){return crypto.randomUUID()}async findExisting(t){let a=m(this._meta.model.tableName),n=this.getUpsertKeys(),e=this.getSoftDeleteConfig();for(let r of a.values()){if(e.enabled){let s=r[e.field];if(s!=null)continue}let o=true;for(let s of n){let i=t[s],d=r[s];if(i!==d){o=false;break}}if(o)return r}return null}async create(t){let a=m(this._meta.model.tableName),n=this._meta.model.primaryKeys[0],e=this.applyManagedInsertFields(t,"memory",()=>this.generateId());return a.set(String(e[n]),e),e}async update(t,a){let n=m(this._meta.model.tableName),e=this._meta.model.primaryKeys[0],r=String(t[e]),o={...t,...this.applyManagedUpdateFields(a)};return n.set(r,o),o}},Se=class extends _{async countMatching(t){return this.getFilteredItems(t).length}async applyPatch(t,a){let n=m(this._meta.model.tableName),e=this._meta.model.primaryKeys[0],r=this.getFilteredItems(a),o=[];for(let s of r){let i=String(s[e]),d={...s,...t};n.set(i,d),o.push(d);}return {updated:o.length,records:o}}getFilteredItems(t){let a=m(this._meta.model.tableName),n=Array.from(a.values());for(let e of t.filters)n=n.filter(r=>{let o=r[e.field];switch(e.operator){case "eq":return String(o)===String(e.value);case "ne":return String(o)!==String(e.value);case "gt":return Number(o)>Number(e.value);case "gte":return Number(o)>=Number(e.value);case "lt":return Number(o)<Number(e.value);case "lte":return Number(o)<=Number(e.value);case "in":return e.value.map(String).includes(String(o));case "nin":return !e.value.map(String).includes(String(o));case "like":return String(o).includes(String(e.value).replace(/%/g,""));case "ilike":return String(o).toLowerCase().includes(String(e.value).replace(/%/g,"").toLowerCase());case "null":return e.value?o===null:o!==null;default:return true}});return n}};export{we as A,Se as B,_ as a,E as b,m as c,_e as d,Ie as e,P as f,se as g,ie as h,ae as i,de as j,le as k,ce as l,ue as m,me as n,ge as o,pe as p,fe as q,Me as r,be as s,he as t,ye as u,Oe as v,xe as w,Re as x,ke as y,je as z};
@@ -1,4 +1,4 @@
1
- import {a as a$1,b as b$1}from'./chunk-SDNXN7M5.js';import {b,f as f$2}from'./chunk-XI7HT5ZM.js';import {f as f$1}from'./chunk-NGUMNUOP.js';import {i,d,a as a$2,b as b$3,c as c$1}from'./chunk-FC56WWPB.js';import {f}from'./chunk-FJCWFB5L.js';import {e,g,n,o,p,c,j,d as d$3,k,i as i$1,r}from'./chunk-KUFOENSK.js';import {d as d$2,e as e$1}from'./chunk-QRXEQTNE.js';import {d as d$1}from'./chunk-QXFY6NYI.js';import {b as b$4}from'./chunk-DMGP7QDL.js';import {a,b as b$2}from'./chunk-VJRDAVID.js';import {z}from'zod';import {HTTPException}from'hono/http-exception';import {stream}from'hono/streaming';var me="createdAt",he="updatedAt";function se(s){return s?s===true?{enabled:true,createdAt:me,updatedAt:he}:{enabled:true,createdAt:s.createdAt??me,updatedAt:s.updatedAt??he}:{enabled:false,createdAt:me,updatedAt:he}}function Z(s,e={}){let{includePrimaryKeys:t=true}=e,o=new Set;if(t)for(let n of s.primaryKeys)o.add(n);let r=se(s.timestamps);return r.enabled&&(o.add(r.createdAt),o.add(r.updatedAt)),[...o]}function kt(s){return s!=null&&s!==""}function ze(s,e,t,o){let r={...s},n=e.primaryKeys[0];if(!kt(r[n])){let u=e.id;if(typeof u=="function")r[n]=u();else if(u==="database"){if(t==="memory")throw new i("MemoryAdapter does not support id:'database' (no database to generate the key)");delete r[n];}else r[n]=o?o():crypto.randomUUID();}let i$1=se(e.timestamps);if(i$1.enabled){let u=Date.now();i$1.createdAt in s||(r[i$1.createdAt]=u),i$1.updatedAt in s||(r[i$1.updatedAt]=u);}return r}function Le(s,e){let t=se(e.timestamps);return t.enabled?{...s,[t.updatedAt]:Date.now()}:{...s}}function qe(s,e){if(e==="memory"&&s.id==="database")throw new i("MemoryAdapter does not support id:'database' (no database to generate the key)")}function Ue(s,e){let t={...s};for(let o of Z(e))delete t[o];return t}var xt=new Set(["P2002","SQLITE_CONSTRAINT_UNIQUE","SQLITE_CONSTRAINT","23505","ER_DUP_ENTRY",1062,"1062"]),Ft=/UNIQUE constraint failed|duplicate key value violates unique constraint|Duplicate entry/i;function Pt(s){if(!s||typeof s!="object")return false;let{code:e,message:t}=s;return (typeof e=="string"||typeof e=="number")&&xt.has(e)?true:typeof t=="string"&&Ft.test(t)}function*It(s,e=8){for(let t=s,o=0;o<e&&t!=null&&typeof t=="object";o++)yield t,t=t.cause;}function ge(s){for(let e of It(s))if(Pt(e))return new d("Unique constraint violation");return null}function Q(s){throw ge(s)??s}function fe(s){if(s===null||typeof s!="object")return s;if(Array.isArray(s))return s.map(fe);let e={};for(let t of Object.keys(s).sort())e[t]=fe(s[t]);return e}async function oe(s){let e=JSON.stringify(fe(s)),t=new TextEncoder().encode(e),o=await crypto.subtle.digest("SHA-256",t);return `"${Array.from(new Uint8Array(o)).map(i=>i.toString(16).padStart(2,"0")).join("").substring(0,32)}"`}function be(s,e){return s?s==="*"?true:s.split(",").map(t=>t.trim()).includes(e):false}function we(s,e){return !s||s==="*"?true:s.split(",").map(t=>t.trim()).includes(e)}function Be(s,e){return s==="in"||s==="nin"||s==="between"?e.split(",").map(t=>t.trim()):s==="null"?e.toLowerCase()==="true":e}function $t(s){let e=s.match(/^\[([a-z]+)\](.*)$/);if(e){let t=e[1];return {operator:t,value:Be(t,e[2])}}return {operator:"eq",value:s}}function de(s,e){let t=[],o={},{filterFields:r=[],filterConfig:n={},searchFields:i=[],searchFieldName:u="search",sortFields:l=[],defaultSort:p,defaultPerPage:a=20,maxPerPage:c=100,cursorPaginationEnabled:d=false,softDeleteQueryParam:m="withDeleted",allowedIncludes:f=[],fieldSelectionEnabled:g=false,allowedSelectFields:j=[],blockedSelectFields:x=[],alwaysIncludeFields:k=[],defaultSelectFields:y=[]}=e,F={};for(let C of r)F[C]=["eq"];Object.assign(F,n);for(let[C,X]of Object.entries(s)){if(X==null)continue;let V=String(X);if(d&&C==="cursor"){o.cursor=V;continue}if(d&&C==="limit"){o.limit=Math.min(c,Math.max(1,parseInt(V,10)||a));continue}if(C==="page"){o.page=Math.max(1,parseInt(V,10)||1);continue}if(C==="per_page"){o.per_page=Math.min(c,Math.max(1,parseInt(V,10)||a));continue}if(C==="sort"){(l.length===0||l.includes(V))&&(o.order_by=V);continue}if(C==="order"){(V==="asc"||V==="desc")&&(o.order_by_direction=V);continue}if(C===u&&i.length>0){o.search=V;continue}if(C===m){o.withDeleted=V.toLowerCase()==="true";continue}if(C==="onlyDeleted"){o.onlyDeleted=V.toLowerCase()==="true";continue}if(C==="include"){let ee=V.split(",").map(L=>L.trim()).filter(Boolean);f&&f.length>0?o.include=ee.filter(L=>f.includes(L)):o.include=ee;continue}if(C==="fields"&&g){let L=V.split(",").map(re=>re.trim()).filter(Boolean);j.length>0&&(L=L.filter(re=>j.includes(re))),x.length>0&&(L=L.filter(re=>!x.includes(re))),k.length>0&&(L=[...new Set([...k,...L])]),o.fields=L;continue}let pe=C.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([a-z]+)\]$/);if(pe){let ee=pe[1],L=pe[2];F[ee]?.includes(L)&&t.push({field:ee,operator:L,value:Be(L,V)});continue}F[C]&&t.push({field:C,operator:"eq",value:V});}if(o.page||(o.page=1),o.per_page||(o.per_page=a),!o.order_by&&p?.field&&(o.order_by=p.field),o.order_by_direction||(o.order_by_direction=p?.order??"asc"),g&&!o.fields&&y.length>0){let C=[...y];k.length>0&&(C=[...new Set([...k,...C])]),o.fields=C;}return {filters:t,options:o}}function D(s,e=[]){if(e.length===0)return s;let t=new Set(Object.keys(s.shape)),o=e.filter(n=>t.has(n));if(o.length===0)return s;let r=Object.fromEntries(o.map(n=>[n,true]));return s.omit(r)}function Kt(s,e={},t=[],o=[],r=[]){let{allowedFields:n=[],blockedFields:i=[],alwaysIncludeFields:u=[],defaultFields:l=[],allowComputedFields:p=true,allowRelationFields:a=true}=e;if(!s||typeof s!="string"||s.trim()==="")return l.length>0?{fields:[...new Set([...u,...l])],isActive:false}:{fields:[],isActive:false};let c=s.split(",").map(g=>g.trim()).filter(Boolean),d=new Set;for(let g of t)(n.length===0||n.includes(g))&&(i.includes(g)||d.add(g));if(p)for(let g of o)(n.length===0||n.includes(g))&&(i.includes(g)||d.add(g));if(a)for(let g of r)(n.length===0||n.includes(g))&&(i.includes(g)||d.add(g));let m=c.filter(g=>d.has(g));return {fields:[...new Set([...u,...m])],isActive:true}}function ye(s,e){if(!e.isActive||e.fields.length===0)return s;let t={};for(let o of e.fields)o in s&&(t[o]=s[o]);return t}function ce(s,e){return !e.isActive||e.fields.length===0?s:s.map(t=>ye(t,e))}var $e="__honoCrudResolvedSchema:";function Et(s){return typeof s.getBodySchema=="function"}var S=class extends b{_auditLogger;_versionManager;_tx;getAuditLogger(){return this._auditLogger||(this._auditLogger=f(this._meta.model.audit)),this._auditLogger}getAuditConfig(){return e(this._meta.model.audit)}isAuditEnabled(){return this.getAuditConfig().enabled}getAuditUserId(){let e=this.getAuditConfig();return e.getUserId&&this.context?e.getUserId(this.context):this.context?.var?.userId}getVersionManager(){return this._versionManager||(this._versionManager=f$1(this._meta.model.versioning,this._meta.model.tableName)),this._versionManager}getVersioningConfig(){return g(this._meta.model.versioning,this._meta.model.tableName)}isVersioningEnabled(){return this.getVersioningConfig().enabled}getVersioningUserId(){let e=this.getVersioningConfig();return e.getUserId&&this.context?e.getUserId(this.context):this.context?.var?.userId}getSoftDeleteConfig(){return n(this._meta.model.softDelete)}isSoftDeleteEnabled(){return this.getSoftDeleteConfig().enabled}getMultiTenantConfig(){return o(this._meta.model.multiTenant)}isMultiTenantEnabled(){return this.getMultiTenantConfig().enabled}applyManagedInsertFields(e,t,o){return ze(e,this._meta.model,t,o)}applyManagedUpdateFields(e){return Le(e,this._meta.model)}assertIdStrategySupported(e){qe(this._meta.model,e);}getTimestampsConfig(){return se(this._meta.model.timestamps)}getTenantId(){if(!this.context)return;let e=this.getMultiTenantConfig();return p(this.context,e)}validateTenantId(){let e=this.getMultiTenantConfig();if(!e.enabled)return;let t=this.getTenantId();if(!t&&e.required)throw new HTTPException(400,{message:e.errorMessage});return t}injectTenantId(e){let t=this.getMultiTenantConfig();if(!t.enabled)return e;let o=this.getTenantId();return o?{...e,[t.field]:o}:e}async emitEvent(e,t){let o=d$1(this.context??void 0);o&&await o.emit({type:e,table:this._meta.model.tableName,recordId:t.recordId,data:t.data??null,previousData:t.previousData,userId:this.getAuditUserId(),tenantId:this.context?this.getTenantId():void 0,organizationId:this.context?a(this.context,"organizationId"):void 0,timestamp:new Date().toISOString(),metadata:t.metadata});}async encryptOnWrite(e){let t=this._meta.model.fieldEncryption;return t?await d$2(e,t.fields,t.keyProvider):e}async decryptOnRead(e){let t=this._meta.model.fieldEncryption;return t?await e$1(e,t.fields,t.keyProvider):e}applyProfile(e){let t=this._meta.model.serializationProfile;return t?a$1(e,t):e}applyProfileToArray(e){let t=this._meta.model.serializationProfile;return t?b$1(e,t):e}getRecordId(e){if(e===null||typeof e!="object")return null;let t=this._meta.model.primaryKeys[0],o=e[t];return typeof o=="string"||typeof o=="number"?o:null}getParentId(e){return this.getRecordId(e)}getPolicies(){if(this.context){let e=a(this.context,f$2);if(e)return e}return this._meta.model.policies}buildPolicyContext(){let e=this.context;return {user:e?a(e,"user"):void 0,userId:e?a(e,"userId"):void 0,tenantId:e?a(e,"tenantId"):void 0,organizationId:e?a(e,"organizationId"):void 0,request:e?.req?.raw??new Request("http://localhost/")}}async applyReadPolicy(e){let t=this.getPolicies();if(!t)return e;let o=this.buildPolicyContext();if(t.read&&!await t.read(o,e))return null;if(t.fields){let r=t.fields(o,e);return {...e,...r}}return e}async applyReadPolicyToArray(e){if(!this.getPolicies())return e;let o=[];for(let r of e){let n=await this.applyReadPolicy(r);n!==null&&o.push(n);}return o}async applyWritePolicy(e){let t=this.getPolicies();if(!t?.write)return;if(!await t.write(this.buildPolicyContext(),e))throw new HTTPException(403,{message:"Forbidden by policy"})}applyReadPushdown(e){let t=this.getPolicies();if(!t?.readPushdown)return;let o=t.readPushdown(this.buildPolicyContext());o&&o.length>0&&e.filters.push(...o);}buildHookContext(){let e=this.context;return {db:{tx:this._tx},request:e?.req?.raw,tenantId:e?this.getTenantId():void 0,organizationId:e?a(e,"organizationId"):void 0,userId:e?a(e,"userId"):void 0,agentId:e?a(e,"agentId"):void 0,agentRunId:e?a(e,"agentRunId"):void 0}}getModelSchema(){if(this.context&&this._meta.model.resolveSchema){let e=a(this.context,$e+this._meta.model.tableName);if(e)return e}return this._meta.model.schema}async resolveModelSchema(){let e=this._meta.model.resolveSchema;if(!e||!this.context)return this._meta.model.schema;let t=$e+this._meta.model.tableName,o=a(this.context,t);if(o)return o;let r={tenantId:a(this.context,"tenantId"),organizationId:a(this.context,"organizationId"),request:this.context.req?.raw,env:this.context.env},n;try{n=await e(r);}catch(i){throw new a$2(i instanceof Error?i.message:"Schema resolution failed",500,"SCHEMA_RESOLVE_ERROR",i instanceof Error?{cause:i.message}:void 0)}return b$2(this.context,t,n),n}async getValidatedData(){await this.resolveModelSchema();let e=await super.getValidatedData();if(this.context&&e.body!==void 0&&Et(this)){let t=e.body;try{t=await this.context.req.json();}catch{}let r=this.getBodySchema().safeParse(t);if(!r.success)throw b$3.fromZodError(r.error);e.body=r.data;}return e}};var Ke=class extends S{beforeHookMode="sequential";afterHookMode="sequential";allowNestedCreate=[];getBodySchema(){let e,t=Z(this._meta.model),o=this.getMultiTenantConfig();o.enabled&&t.push(o.field),this._meta.fields?e=this._meta.fields:e=D(this.getModelSchema(),t);let r=this.getNestedWritableRelations();if(r.length===0)return e;let n={...e.shape};for(let i of r){let u=this._meta.model.relations?.[i];if(!u?.schema)continue;let l=["id",u.foreignKey],p=D(u.schema,l);u.type==="hasMany"?n[i]=z.array(p).optional():n[i]=p.optional();}return z.object(n)}getNestedWritableRelations(){if(this.allowNestedCreate.length>0)return this.allowNestedCreate;let e=this._meta.model.relations;return e?Object.entries(e).filter(([t,o])=>o.nestedWrites?.allowCreate===true).map(([t])=>t):[]}extractNestedData(e){let t=this.getNestedWritableRelations();return c(e,t)}getSchema(){let e=this.getBodySchema();return {...this.schema,request:{body:{content:{"application/json":{schema:e}},required:true}},responses:{201:{description:"Resource created successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:{description:"Validation error",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.unknown().optional()})})}}}}}}async getObject(){let{body:e}=await this.getValidatedData();return e}async before(e,t){return e}async after(e,t){return e}transform(e){return e}async createNested(e,t,o,r,n){return b$4().warn(`Nested writes not implemented for ${t}. Override createNested() in your adapter.`),[]}async handle(){this.validateTenantId();let e=await this.getObject(),{mainData:t,nestedData:o}=this.extractNestedData(e),r=t;r=this.injectTenantId(r);let n=this.buildHookContext();r=await this.before(r,n),r=await this.encryptOnWrite(r),r=await this.create(r,n.db.tx).catch(Q),r=await this.decryptOnRead(r);let i=this.getParentId(r),u={};if(Object.keys(o).length>0&&i!==null)for(let[c,d]of Object.entries(o)){if(d==null)continue;let m=this._meta.model.relations?.[c];if(!m)continue;let f=await this.createNested(i,c,m,d);u[c]=f;}if(Object.keys(u).length>0){let c={};for(let[d,m]of Object.entries(u)){let f=this._meta.model.relations?.[d];f&&(f.type==="hasMany"?c[d]=m:c[d]=m[0]||null);}r={...r,...c};}if(this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(r,n))):r=await this.after(r,n),this.isAuditEnabled()&&i!==null){let c=this.getAuditLogger();this.runAfterResponse(c.logCreate(this._meta.model.tableName,i,r,this.getAuditUserId()));}i!==null&&this.runAfterResponse(this.emitEvent("created",{recordId:i,data:r})),this._meta.model.computedFields&&(r=await j(r,this._meta.model.computedFields));let l=this._meta.model.serializer?this._meta.model.serializer(r):r,p=this.applyProfile(l),a=this.transform(p);return this.success(a,201)}};var We=class extends S{lookupField="id";lookupFields;additionalFilters;etagEnabled=false;allowedIncludes=[];fieldSelectionEnabled=false;allowedSelectFields=[];blockedSelectFields=[];alwaysIncludeFields=[];defaultSelectFields=[];getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getQuerySchema(){let e={};if(this.additionalFilters?.length)for(let t of this.additionalFilters)e[t]=z.string().optional();if(this.allowedIncludes.length>0&&(e.include=z.string().optional().describe(`Comma-separated list of relations to include. Allowed: ${this.allowedIncludes.join(", ")}`)),this.fieldSelectionEnabled){let t=this.getAvailableSelectFields();e.fields=z.string().optional().describe(`Comma-separated list of fields to return. Available: ${t.join(", ")}`);}if(Object.keys(e).length!==0)return z.object(e)}getAvailableSelectFields(){let e=Object.keys(this.getModelSchema().shape),t=this._meta.model.computedFields?Object.keys(this._meta.model.computedFields):[],o=this._meta.model.relations?Object.keys(this._meta.model.relations):[],r=[...e,...t,...o];return this.allowedSelectFields.length>0&&(r=r.filter(n=>this.allowedSelectFields.includes(n))),this.blockedSelectFields.length>0&&(r=r.filter(n=>!this.blockedSelectFields.includes(n))),r}getSchema(){let e=this.getQuerySchema();return {...this.schema,request:{params:this.getParamsSchema(),...e&&{query:e}},responses:{200:{description:"Resource retrieved successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},404:{description:"Resource not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async getIncludeOptions(){let{query:e}=await this.getValidatedData(),t=e?.include;if(!t||typeof t!="string")return {relations:[]};let o=t.split(",").map(r=>r.trim()).filter(Boolean);return this.allowedIncludes.length>0?{relations:o.filter(r=>this.allowedIncludes.includes(r))}:{relations:o}}async getFieldSelection(){if(!this.fieldSelectionEnabled)return {fields:[],isActive:false};let{query:e}=await this.getValidatedData(),t=e?.fields;if(!t||typeof t!="string"||t.trim()==="")return this.defaultSelectFields.length>0?{fields:[...new Set([...this.alwaysIncludeFields,...this.defaultSelectFields])],isActive:true}:{fields:[],isActive:false};let o=t.split(",").map(i=>i.trim()).filter(Boolean),r=new Set(this.getAvailableSelectFields()),n=o.filter(i=>r.has(i));return this.alwaysIncludeFields.length>0&&(n=[...new Set([...this.alwaysIncludeFields,...n])]),{fields:n,isActive:true}}async after(e){return e}transform(e){return e}async handle(){let e=this.validateTenantId(),t=await this.getLookupValue(),o=await this.getAdditionalFilters(),r=await this.getIncludeOptions(),n=await this.getFieldSelection();if(e){let d=this.getMultiTenantConfig();o[d.field]=e;}let i=await this.read(t,o,r);if(!i)throw new c$1(this._meta.model.tableName,t);i=await this.decryptOnRead(i);let u=await this.applyReadPolicy(i);if(u===null)throw new c$1(this._meta.model.tableName,t);i=u,i=await this.after(i),this._meta.model.computedFields&&(i=await j(i,this._meta.model.computedFields));let l=this._meta.model.serializer?this._meta.model.serializer(i):i,p=this.applyProfile(l),a=this.transform(p),c=n.isActive&&n.fields.length>0?ye(a,n):a;if(this.etagEnabled){let d=await oe(c),m=this.getContext(),f=m.req.header("If-None-Match");if(be(f,d))return new Response(null,{status:304,headers:{ETag:d}});m.header("ETag",d);}return this.success(c)}};var Qe=class extends S{lookupField="id";lookupFields;additionalFilters;allowedUpdateFields;blockedUpdateFields;beforeHookMode="sequential";afterHookMode="sequential";allowNestedWrites=[];etagEnabled=false;getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getBodySchema(){let e;if(this._meta.fields)e=this._meta.fields.partial();else {let r=Z(this._meta.model);this.blockedUpdateFields&&(r=[...r,...this.blockedUpdateFields]);let n=D(this.getModelSchema(),r);if(this.allowedUpdateFields){let i=this.allowedUpdateFields.reduce((u,l)=>({...u,[l]:true}),{});n=n.pick(i);}e=n.partial();}let t=this.getNestedWritableRelations();if(t.length===0)return e;let o={...e.shape};for(let r of t){let n=this._meta.model.relations?.[r];if(!n?.schema)continue;let i=n.schema,u=z.object({create:z.union([i.partial(),z.array(i.partial())]).optional(),update:z.array(i.partial().extend({id:z.union([z.string(),z.number()])})).optional(),delete:z.array(z.union([z.string(),z.number()])).optional(),connect:z.array(z.union([z.string(),z.number()])).optional(),disconnect:z.array(z.union([z.string(),z.number()])).optional(),set:i.partial().nullable().optional()}).optional();o[r]=u;}return z.object(o)}getNestedWritableRelations(){if(this.allowNestedWrites.length>0)return this.allowNestedWrites;let e=this._meta.model.relations;return e?Object.entries(e).filter(([t,o])=>{let r=o.nestedWrites;return r&&(r.allowCreate||r.allowUpdate||r.allowDelete||r.allowConnect||r.allowDisconnect)}).map(([t])=>t):[]}extractNestedData(e){let t=this.getNestedWritableRelations();return c(e,t)}getSchema(){return {...this.schema,request:{params:this.getParamsSchema(),body:{content:{"application/json":{schema:this.getBodySchema()}},required:true}},responses:{200:{description:"Resource updated successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:{description:"Validation error",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.unknown().optional()})})}}},404:{description:"Resource not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getObject(){let{body:e}=await this.getValidatedData();return e}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async before(e,t){return e}async after(e,t,o){return t}transform(e){return e}async findExisting(e,t,o){return null}async processNestedWrites(e,t,o,r,n){return b$4().warn(`Nested writes not implemented for ${t}. Override processNestedWrites() in your adapter.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]}}async handle(){let e=this.validateTenantId(),t=await this.getLookupValue(),o=await this.getAdditionalFilters();if(e){let y=this.getMultiTenantConfig();o[y.field]=e;}let r=await this.getObject(),{mainData:n,nestedData:i}=this.extractNestedData(r),u=this.getPolicies(),l=await this.findExisting(t,o,this._tx);if(l&&u?.write&&await this.applyWritePolicy(l),this.etagEnabled&&l){let y=this.getContext().req.header("If-Match");if(y){let F=await oe(l);if(!we(y,F))return this.error("Resource has been modified by another request","CONFLICT",409)}}let p;if(this.isVersioningEnabled()&&l){let y=this.getVersionManager(),F=this.getParentId(l);F!==null&&(p=await y.saveVersion(F,l,void 0,this.getVersioningUserId()));}let a=n;if(this.isVersioningEnabled()&&p!==void 0){let y=this.getVersioningConfig().field;a[y]=p;}let c=this.buildHookContext();a=await this.before(a,c),a=await this.encryptOnWrite(a);let d=await this.update(t,a,o,c.db.tx);if(!d)throw new c$1(this._meta.model.tableName,t);d=await this.decryptOnRead(d);let m=this.getParentId(d),f={};if(Object.keys(i).length>0&&m!==null)for(let[y,F]of Object.entries(i)){if(F==null)continue;let C=this._meta.model.relations?.[y];if(!C)continue;let X;d$3(F)?X={create:F}:X=F;let V=await this.processNestedWrites(m,y,C,X);f[y]=V;}if(Object.keys(f).length>0)for(let[y,F]of Object.entries(f)){let C=this._meta.model.relations?.[y];C&&(C.type==="hasMany"?d[y]=[...F.created,...F.updated]:d[y]=F.created[0]||F.updated[0]||null);}let g=l??d;if(this.afterHookMode==="fire-and-forget")this.runAfterResponse(Promise.resolve(this.after(g,d,c)));else {let y=await this.after(g,d,c);y!=null&&(d=y);}if(this.isAuditEnabled()&&m!==null&&l){let y=this.getAuditLogger();this.runAfterResponse(y.logUpdate(this._meta.model.tableName,m,l,d,this.getAuditUserId()));}m!==null&&this.runAfterResponse(this.emitEvent("updated",{recordId:m,data:d,previousData:l??void 0})),this._meta.model.computedFields&&(d=await j(d,this._meta.model.computedFields));let j$1=this._meta.model.serializer?this._meta.model.serializer(d):d,x=this.applyProfile(j$1),k=this.transform(x);if(this.etagEnabled){let y=await oe(k);this.getContext().header("ETag",y);}return this.success(k)}};var Ge=class extends S{lookupField="id";lookupFields;additionalFilters;beforeHookMode="sequential";afterHookMode="sequential";includeCascadeResults=false;getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getCascadeRelations(e){let t=this._meta.model.relations;return t?Object.entries(t).filter(([o,r])=>{let n=r.cascade?.[e];return n&&n!=="noAction"}).map(([o,r])=>({name:o,config:r,action:r.cascade[e]})):[]}getSchema(){let e=this.includeCascadeResults?z.object({deleted:z.literal(true),cascade:z.object({deleted:z.record(z.string(),z.number()),nullified:z.record(z.string(),z.number())}).optional()}):z.object({deleted:z.literal(true)});return {...this.schema,request:{params:this.getParamsSchema()},responses:{200:{description:"Resource deleted successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:e})}}},404:{description:"Resource not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}},409:{description:"Cannot delete - related records exist (restrict)",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.object({relation:z.string(),count:z.number()}).optional()})})}}}}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async before(e,t){}async after(e,t){}async countRelated(e,t,o,r){return b$4().warn(`countRelated not implemented for ${t}. Override in your adapter for restrict cascade to work.`),0}async deleteRelated(e,t,o,r){return b$4().warn(`deleteRelated not implemented for ${t}. Override in your adapter for cascade delete to work.`),0}async nullifyRelated(e,t,o,r){return b$4().warn(`nullifyRelated not implemented for ${t}. Override in your adapter for setNull cascade to work.`),0}async processCascade(e,t,o){let r=t?"onSoftDelete":"onDelete",n=this.getCascadeRelations(r),i={deleted:{},nullified:{}};for(let{name:u,config:l,action:p}of n)if(p==="cascade"){let a=await this.deleteRelated(e,u,l,o);a>0&&(i.deleted[u]=a);}else if(p==="setNull"){let a=await this.nullifyRelated(e,u,l,o);a>0&&(i.nullified[u]=a);}return i}async checkRestrictConstraints(e,t,o){let r=t?"onSoftDelete":"onDelete",n=this.getCascadeRelations(r);for(let{name:i,config:u,action:l}of n)if(l==="restrict"){let p=await this.countRelated(e,i,u,o);if(p>0)throw new d(`Cannot delete: ${p} related ${i} record(s) exist. Remove them first or change the cascade configuration.`,{relation:i,count:p})}}async handle(){let e=this.validateTenantId(),t=await this.getLookupValue(),o=await this.getAdditionalFilters();if(e){let c=this.getMultiTenantConfig();o[c.field]=e;}let r=this.isSoftDeleteEnabled(),n=await this.findForDelete(t,o,this._tx);if(!n)throw new c$1(this._meta.model.tableName,t);let i=this.getParentId(n);i!==null&&await this.checkRestrictConstraints(i,r),await this.applyWritePolicy(n);let u=this.buildHookContext();if(await this.before(t,u),!await this.delete(t,o,u.db.tx))throw new c$1(this._meta.model.tableName,t);let p;if(i!==null&&(p=await this.processCascade(i,r)),this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(n,u))):await this.after(n,u),this.isAuditEnabled()&&i!==null){let c=this.getAuditLogger();this.runAfterResponse(c.logDelete(this._meta.model.tableName,i,n,this.getAuditUserId()));}i!==null&&this.runAfterResponse(this.emitEvent("deleted",{recordId:i,previousData:n}));let a={deleted:true};if(this.includeCascadeResults&&p){let c=Object.keys(p.deleted).length>0,d=Object.keys(p.nullified).length>0;(c||d)&&(a.cascade=p);}return this.success(a)}};var ue=class extends S{filterFields=[];filterConfig;searchFields=[];searchFieldName="search";sortFields=[];defaultSort;defaultPerPage=20;maxPerPage=100;cursorPaginationEnabled=false;cursorField;allowedIncludes=[];fieldSelectionEnabled=false;allowedSelectFields=[];blockedSelectFields=[];alwaysIncludeFields=[];defaultSelectFields=[];getQuerySchema(){let e={page:z.string().optional(),per_page:z.string().optional()};this.sortFields.length>0&&(e.sort=z.enum(this.sortFields).optional().describe("Field to sort by"),e.order=z.enum(["asc","desc"]).optional().describe("Sort direction (asc or desc)")),this.searchFields.length>0&&(e[this.searchFieldName]=z.string().optional());for(let o of this.filterFields)e[o]=z.string().optional();if(this.filterConfig)for(let[o,r]of Object.entries(this.filterConfig)){for(let n of r)e[`${o}[${n}]`]=z.string().optional();e[o]=z.string().optional();}let t=this.getSoftDeleteConfig();if(t.enabled&&t.allowQueryDeleted&&(e[t.queryParam]=z.enum(["true","false"]).optional(),e.onlyDeleted=z.enum(["true","false"]).optional()),this.allowedIncludes.length>0&&(e.include=z.string().optional().describe(`Comma-separated list of relations to include. Allowed: ${this.allowedIncludes.join(", ")}`)),this.fieldSelectionEnabled){let o=this.getAvailableSelectFields();e.fields=z.string().optional().describe(`Comma-separated list of fields to return. Available: ${o.join(", ")}`);}return this.cursorPaginationEnabled&&(e.cursor=z.string().optional().describe("Opaque cursor for fetching the next page"),e.limit=z.string().optional().describe("Number of items to return (cursor pagination)")),z.object(e)}getAvailableSelectFields(){let e=Object.keys(this.getModelSchema().shape),t=this._meta.model.computedFields?Object.keys(this._meta.model.computedFields):[],o=this._meta.model.relations?Object.keys(this._meta.model.relations):[],r=[...e,...t,...o];return this.allowedSelectFields.length>0&&(r=r.filter(n=>this.allowedSelectFields.includes(n))),this.blockedSelectFields.length>0&&(r=r.filter(n=>!this.blockedSelectFields.includes(n))),r}getSchema(){return {...this.schema,request:{query:this.getQuerySchema()},responses:{200:{description:"List of resources",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.array(this.getModelSchema()),result_info:z.object({page:z.number(),per_page:z.number(),total_count:z.number().optional(),total_pages:z.number().optional(),has_next_page:z.boolean(),has_prev_page:z.boolean(),next_cursor:z.string().optional(),prev_cursor:z.string().optional()})})}}}}}}async getFilters(){let{query:e}=await this.getValidatedData(),t=this.getSoftDeleteConfig(),o={filterFields:this.filterFields,filterConfig:this.filterConfig,searchFields:this.searchFields,searchFieldName:this.searchFieldName,sortFields:this.sortFields,defaultSort:this.defaultSort,defaultPerPage:this.defaultPerPage,maxPerPage:this.maxPerPage,cursorPaginationEnabled:this.cursorPaginationEnabled,cursorField:this.cursorField,softDeleteQueryParam:t.queryParam,allowedIncludes:this.allowedIncludes,fieldSelectionEnabled:this.fieldSelectionEnabled,allowedSelectFields:this.allowedSelectFields,blockedSelectFields:this.blockedSelectFields,alwaysIncludeFields:this.alwaysIncludeFields,defaultSelectFields:this.defaultSelectFields};return de(e||{},o)}async after(e){return e}transform(e){return e}async handle(){let e=this.validateTenantId(),t=await this.getFilters();if(e){let a=this.getMultiTenantConfig();t.filters.push({field:a.field,operator:"eq",value:e});}this.applyReadPushdown(t);let o=await this.list(t),r=await Promise.all(o.result.map(a=>this.decryptOnRead(a))),n=await this.applyReadPolicyToArray(r),i=await this.after(n);this._meta.model.computedFields&&(i=await k(i,this._meta.model.computedFields)),this._meta.model.serializer&&(i=i.map(a=>this._meta.model.serializer(a)));let l=this.applyProfileToArray(i).map(a=>this.transform(a)),p=this.fieldSelectionEnabled&&t.options.fields&&t.options.fields.length>0?ce(l,{fields:t.options.fields,isActive:true}):l;return this.successPaginated(p,o.result_info)}};var Je=class extends S{lookupField="id";excludeFromClone=[];getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getBodySchema(){let e=[...Z(this._meta.model),...this.excludeFromClone];return D(this.getModelSchema(),e).partial()}getSchema(){return {...this.schema,request:{params:this.getParamsSchema(),body:{content:{"application/json":{schema:this.getBodySchema()}},required:false}},responses:{201:{description:"Resource cloned successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},404:{description:"Source resource not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}},409:{description:"Unique-constraint violation (e.g. natural-key collision)",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getOverrides(){let{body:e}=await this.getValidatedData();return e||{}}async before(e){return e}async after(e){return e}async handle(){let e=this.validateTenantId(),t=await this.getLookupValue(),o=await this.getOverrides(),r={};if(e){let a=this.getMultiTenantConfig();r[a.field]=e;}let n=await this.findSource(t,r);if(!n)throw new c$1(this._meta.model.tableName,t);let i=Ue(n,this._meta.model);for(let a of this.excludeFromClone)delete i[a];Object.assign(i,o);let u=await this.before(i),l=await this.createClone(u).catch(Q);l=await this.after(l),this._meta.model.computedFields&&(l=await j(l,this._meta.model.computedFields));let p=this._meta.model.serializer?this._meta.model.serializer(l):l;return this.success(p,201)}};var Ye=class extends S{lookupField="id";lookupFields;additionalFilters;beforeHookMode="sequential";afterHookMode="sequential";getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema()},responses:{200:{description:"Resource restored successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:{description:"Soft delete not enabled or record not deleted",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}},404:{description:"Resource not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async before(e,t){}async after(e,t){return e}async handle(){if(!this.isSoftDeleteEnabled())throw new a$2("Soft delete is not enabled for this model",400,"SOFT_DELETE_NOT_ENABLED");let e=await this.getLookupValue(),t=await this.getAdditionalFilters();await this.before(e);let o=await this.restore(e,t);if(!o)throw new c$1(this._meta.model.tableName,e);this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(o))):o=await this.after(o);let r=this.getRecordId(o);if(this.isAuditEnabled()&&r!==null){let i=this.getAuditLogger();this.runAfterResponse(i.logRestore(this._meta.model.tableName,r,o,this.getAuditUserId()));}r!==null&&this.runAfterResponse(this.emitEvent("restored",{recordId:r,data:o}));let n=this._meta.model.serializer?this._meta.model.serializer(o):o;return this.success(n)}};var Xe=class extends S{upsertKeys;useNativeUpsert=false;createOnlyFields;updateOnlyFields;beforeHookMode="sequential";afterHookMode="sequential";allowNestedWrites=[];getUpsertKeys(){return this.upsertKeys||this._meta.model.primaryKeys}getBodySchema(){let e;if(this._meta.fields)e=this._meta.fields;else {let r=this.getUpsertKeys(),n=Z(this._meta.model,{includePrimaryKeys:false});for(let l of this._meta.model.primaryKeys)r.includes(l)||n.push(l);let i=D(this.getModelSchema(),n),u={};for(let[l,p]of Object.entries(i.shape))r.includes(l)?u[l]=p:u[l]=p.optional();e=z.object(u);}let t=this.getNestedWritableRelations();if(t.length===0)return e;let o={...e.shape};for(let r of t){let n=this._meta.model.relations?.[r];if(!n?.schema)continue;let i=n.schema,u=z.union([n.type==="hasMany"?z.array(i.partial()):i.partial(),z.object({create:z.union([i.partial(),z.array(i.partial())]).optional(),update:z.array(i.partial().extend({id:z.union([z.string(),z.number()])})).optional(),upsert:z.union([i.partial(),z.array(i.partial())]).optional(),delete:z.array(z.union([z.string(),z.number()])).optional(),connect:z.array(z.union([z.string(),z.number()])).optional(),disconnect:z.array(z.union([z.string(),z.number()])).optional(),set:i.partial().nullable().optional()})]).optional();o[r]=u;}return z.object(o)}getNestedWritableRelations(){if(this.allowNestedWrites.length>0)return this.allowNestedWrites;let e=this._meta.model.relations;return e?Object.entries(e).filter(([t,o])=>{let r=o.nestedWrites;return r&&(r.allowCreate||r.allowUpdate||r.allowDelete||r.allowConnect||r.allowDisconnect)}).map(([t])=>t):[]}extractNestedData(e){let t=this.getNestedWritableRelations();return c(e,t)}getSchema(){return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}},required:true}},responses:{200:{description:"Resource updated (upsert)",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema(),created:z.literal(false)})}}},201:{description:"Resource created (upsert)",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema(),created:z.literal(true)})}}},400:{description:"Validation error",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.unknown().optional()})})}}}}}}async getObject(){let{body:e}=await this.getValidatedData();return e}async before(e,t,o){return e}async beforeCreate(e,t){return e}async beforeUpdate(e,t,o){return e}async after(e,t,o){return e}async nativeUpsert(e,t){return b$4().warn("Native upsert not implemented for this adapter. Falling back to find-then-insert/update pattern."),this.performStandardUpsert(e,t)}async performStandardUpsert(e,t){let o=await this.findExisting(e,t);if(o){let r={...e};if(this.createOnlyFields)for(let i of this.createOnlyFields)delete r[i];return r=await this.beforeUpdate(r,o,t),{data:await this.update(o,r,t),created:false}}else {let r={...e};if(this.updateOnlyFields)for(let i of this.updateOnlyFields)delete r[i];return r=await this.beforeCreate(r,t),{data:await this.create(r,t),created:true}}}async upsert(e,t){return this.useNativeUpsert?this.nativeUpsert(e,t):this.performStandardUpsert(e,t)}async processNestedWrites(e,t,o,r,n){return b$4().warn(`Nested writes not implemented for ${t}. Override processNestedWrites() in your adapter.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]}}async handle(){this.validateTenantId();let e=await this.getObject(),{mainData:t,nestedData:o}=this.extractNestedData(e),r=t;r=this.injectTenantId(r);let n=await this.findExisting(r),i=!n;r=await this.before(r,i);let u=await this.upsert(r).catch(Q),l=u.data,p=this.getParentId(l),a={};if(Object.keys(o).length>0&&p!==null)for(let[d,m]of Object.entries(o)){if(m==null)continue;let f=this._meta.model.relations?.[d];if(!f)continue;let g;d$3(m)?g={create:m}:g=m;let j=await this.processNestedWrites(p,d,f,g);a[d]=j;}if(Object.keys(a).length>0)for(let[d,m]of Object.entries(a)){let f=this._meta.model.relations?.[d];f&&(f.type==="hasMany"?l[d]=[...m.created,...m.updated]:l[d]=m.created[0]||m.updated[0]||null);}if(this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(l,u.created))):l=await this.after(l,u.created),this.isAuditEnabled()&&p!==null){let d=this.getAuditLogger();this.runAfterResponse(d.logUpsert(this._meta.model.tableName,p,l,n,u.created,this.getAuditUserId()));}this._meta.model.computedFields&&(l=await j(l,this._meta.model.computedFields));let c=this._meta.model.serializer?this._meta.model.serializer(l):l;return this.json({success:true,result:c,created:u.created},u.created?201:200)}};var et=class extends S{maxBatchSize=100;stopOnError=true;beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){let e=this._meta.fields?this._meta.fields:D(this.getModelSchema(),Z(this._meta.model));return z.object({items:z.array(e).min(1).max(this.maxBatchSize)})}getSchema(){return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{201:{description:"Resources created successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({created:z.array(this.getModelSchema()),count:z.number()})})}}},207:{description:"Partial success (some items failed)",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({created:z.array(this.getModelSchema()),count:z.number(),errors:z.array(z.object({index:z.number(),error:z.string()})).optional()})})}}},400:{description:"Validation error",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getItems(){let{body:e}=await this.getValidatedData();return e?.items||[]}async before(e,t,o){return e}async after(e,t,o){return e}transform(e){return e}async handle(){let e=await this.getItems(),t=[],o=[];for(let a=0;a<e.length;a++)try{let c=await this.before(e[a],a);o.push(c);}catch(c){if(this.stopOnError)throw c;t.push({index:a,error:c instanceof Error?c.message:String(c)});}let r=await this.batchCreate(o).catch(Q),n=[];for(let a=0;a<r.length;a++)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(r[a],a))),n.push(r[a])):n.push(await this.after(r[a],a));}catch(c){if(this.stopOnError)throw c;t.push({index:a,error:c instanceof Error?c.message:String(c)}),n.push(r[a]);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),c=n.map(d=>{let m=this.getRecordId(d);return m===null?null:{recordId:m,record:d}}).filter(d=>d!==null);c.length>0&&this.runAfterResponse(a.logBatch("batch_create",this._meta.model.tableName,c,this.getAuditUserId()));}let u=(this._meta.model.serializer?n.map(a=>this._meta.model.serializer(a)):n).map(a=>this.transform(a)),l={success:true,result:{created:u,count:u.length,...t.length>0&&{errors:t}}},p=t.length>0?207:201;return this.json(l,p)}};var tt=class extends S{maxBatchSize=100;stopOnError=false;lookupField="id";allowedUpdateFields;blockedUpdateFields;beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){let e=this._meta.fields?this._meta.fields:D(this.getModelSchema(),Z(this._meta.model));return z.object({items:z.array(z.object({id:z.string(),data:e.partial()})).min(1).max(this.maxBatchSize)})}getSchema(){return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{200:{description:"Resources updated successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({updated:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional()})})}}},207:{description:"Partial success (some items failed or not found)",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({updated:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional(),errors:z.array(z.object({id:z.string(),error:z.string()})).optional()})})}}},400:{description:"Validation error",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getItems(){let{body:e}=await this.getValidatedData();return e?.items||[]}filterUpdateData(e){let t={...e};if(this.allowedUpdateFields){let o=new Set(this.allowedUpdateFields);t=Object.fromEntries(Object.entries(t).filter(([r])=>o.has(r)));}if(this.blockedUpdateFields)for(let o of this.blockedUpdateFields)delete t[o];for(let o of this._meta.model.primaryKeys)delete t[o];return t}async before(e,t,o){return t}async after(e,t){return e}async handle(){let e=await this.getItems(),t=[],o=[];for(let a of e)try{let c=this.filterUpdateData(a.data),d=await this.before(a.id,c);o.push({id:a.id,data:d});}catch(c){if(this.stopOnError)throw c;t.push({id:a.id,error:c instanceof Error?c.message:String(c)});}let{updated:r,notFound:n}=await this.batchUpdate(o),i=[];for(let a of r)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(a))),i.push(a)):i.push(await this.after(a));}catch(c){let d=String(a[this.lookupField]);if(this.stopOnError)throw c;t.push({id:d,error:c instanceof Error?c.message:String(c)}),i.push(a);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),c=i.map(d=>{let m=this.getRecordId(d);return m===null?null:{recordId:m,record:d}}).filter(d=>d!==null);c.length>0&&this.runAfterResponse(a.logBatch("batch_update",this._meta.model.tableName,c,this.getAuditUserId()));}let u=this._meta.model.serializer?i.map(a=>this._meta.model.serializer(a)):i,l={success:true,result:{updated:u,count:u.length,...n.length>0&&{notFound:n},...t.length>0&&{errors:t}}},p=t.length>0||n.length>0?207:200;return this.json(l,p)}};var ot=class extends S{maxBatchSize=100;stopOnError=false;lookupField="id";beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){return z.object({ids:z.array(z.string()).min(1).max(this.maxBatchSize)})}getSchema(){let e=this.isSoftDeleteEnabled();return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{200:{description:e?"Resources soft-deleted successfully":"Resources deleted successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({deleted:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional()})})}}},207:{description:"Partial success (some items failed or not found)",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({deleted:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional(),errors:z.array(z.object({id:z.string(),error:z.string()})).optional()})})}}},400:{description:"Validation error",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getIds(){let{body:e}=await this.getValidatedData();return e?.ids||[]}async before(e,t){}async after(e,t){return e}async handle(){let e=await this.getIds(),t=[],o=[];for(let a of e)try{await this.before(a),o.push(a);}catch(c){if(this.stopOnError)throw c;t.push({id:a,error:c instanceof Error?c.message:String(c)});}let{deleted:r,notFound:n}=await this.batchDelete(o),i=[];for(let a of r)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(a))),i.push(a)):i.push(await this.after(a));}catch(c){let d=String(a[this.lookupField]);if(this.stopOnError)throw c;t.push({id:d,error:c instanceof Error?c.message:String(c)}),i.push(a);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),c=i.map(d=>{let m=this.getRecordId(d);return m===null?null:{recordId:m,previousRecord:d}}).filter(d=>d!==null);c.length>0&&this.runAfterResponse(a.logBatch("batch_delete",this._meta.model.tableName,c,this.getAuditUserId()));}let u=this._meta.model.serializer?i.map(a=>this._meta.model.serializer(a)):i,l={success:true,result:{deleted:u,count:u.length,...n.length>0&&{notFound:n},...t.length>0&&{errors:t}}},p=t.length>0||n.length>0?207:200;return this.json(l,p)}};var rt=class extends S{maxBatchSize=100;stopOnError=false;lookupField="id";beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){return z.object({ids:z.array(z.string()).min(1).max(this.maxBatchSize)})}getSchema(){return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{200:{description:"Resources restored successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({restored:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional()})})}}},207:{description:"Partial success (some items failed or not found)",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({restored:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional(),errors:z.array(z.object({id:z.string(),error:z.string()})).optional()})})}}},400:{description:"Soft delete not enabled or validation error",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getIds(){let{body:e}=await this.getValidatedData();return e?.ids||[]}async before(e,t){}async after(e,t){return e}async handle(){if(!this.isSoftDeleteEnabled())throw new a$2("Soft delete is not enabled for this model",400,"SOFT_DELETE_NOT_ENABLED");let e=await this.getIds(),t=[],o=[];for(let a of e)try{await this.before(a),o.push(a);}catch(c){if(this.stopOnError)throw c;t.push({id:a,error:c instanceof Error?c.message:String(c)});}let{restored:r,notFound:n}=await this.batchRestore(o),i=[];for(let a of r)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(a))),i.push(a)):i.push(await this.after(a));}catch(c){let d=String(a[this.lookupField]);if(this.stopOnError)throw c;t.push({id:d,error:c instanceof Error?c.message:String(c)}),i.push(a);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),c=i.map(d=>{let m=this.getRecordId(d);return m===null?null:{recordId:m,record:d}}).filter(d=>d!==null);c.length>0&&this.runAfterResponse(a.logBatch("batch_restore",this._meta.model.tableName,c,this.getAuditUserId()));}let u=this._meta.model.serializer?i.map(a=>this._meta.model.serializer(a)):i,l={success:true,result:{restored:u,count:u.length,...n.length>0&&{notFound:n},...t.length>0&&{errors:t}}},p=t.length>0||n.length>0?207:200;return this.json(l,p)}};var nt=class extends S{upsertKeys;createOnlyFields;updateOnlyFields;maxBatchSize=100;continueOnError=false;useNativeUpsert=false;beforeHookMode="sequential";afterHookMode="sequential";getUpsertKeys(){return this.upsertKeys||this._meta.model.primaryKeys}getItemSchema(){if(this._meta.fields)return this._meta.fields;let e=this.getUpsertKeys(),t=Z(this._meta.model,{includePrimaryKeys:false});for(let n of this._meta.model.primaryKeys)e.includes(n)||t.push(n);let o=D(this.getModelSchema(),t),r={};for(let[n,i]of Object.entries(o.shape))e.includes(n)?r[n]=i:r[n]=i.optional();return z.object(r)}getBodySchema(){return z.array(this.getItemSchema()).max(this.maxBatchSize)}getSchema(){let e=z.object({data:this.getModelSchema(),created:z.boolean(),index:z.number()});return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}},required:true}},responses:{200:{description:"Batch upsert completed",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({items:z.array(e),createdCount:z.number(),updatedCount:z.number(),totalCount:z.number(),errors:z.array(z.object({index:z.number(),error:z.string()})).optional()})})}}},400:{description:"Validation error",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.unknown().optional()})})}}}}}}async getItems(){let{body:e}=await this.getValidatedData();return e}async beforeItem(e,t,o,r){return e}async afterItem(e,t,o,r){return e}async beforeBatch(e,t){return e}async afterBatch(e,t){return e}async upsertOne(e,t,o){let r=await this.findExisting(e,o),n=!r,i=await this.beforeItem(e,t,n,o),u;if(r){if(this.createOnlyFields)for(let l of this.createOnlyFields)delete i[l];u=await this.update(r,i,o);}else {if(this.updateOnlyFields)for(let l of this.updateOnlyFields)delete i[l];u=await this.create(i,o);}return u=await this.afterItem(u,t,n,o),{data:u,created:n,index:t}}async nativeBatchUpsert(e,t){return b$4().warn("Native batch upsert not implemented for this adapter. Falling back to item-by-item pattern."),this.performStandardBatchUpsert(e,t)}async performStandardBatchUpsert(e,t){let o=[],r=[],n=0,i=0;for(let l=0;l<e.length;l++)try{let p=await this.upsertOne(e[l],l,t);o.push(p),p.created?n++:i++;}catch(p){if(this.continueOnError)r.push({index:l,error:p instanceof Error?p.message:String(p)});else throw p}let u={items:o,createdCount:n,updatedCount:i,totalCount:o.length};return r.length>0&&(u.errors=r),u}async batchUpsert(e,t){return this.useNativeUpsert?this.nativeBatchUpsert(e,t):this.performStandardBatchUpsert(e,t)}async handle(){let e=await this.getItems();e=await this.beforeBatch(e);let t=await this.batchUpsert(e).catch(Q);if(t=await this.afterBatch(t),this._meta.model.computedFields&&(t.items=await Promise.all(t.items.map(async o=>({...o,data:await j(o.data,this._meta.model.computedFields)})))),this.isAuditEnabled()){let o=this.getAuditLogger(),r=t.items.map(n=>{let i=this.getRecordId(n.data);return i===null?null:{recordId:i,record:n.data}}).filter(n=>n!==null);r.length>0&&this.runAfterResponse(o.logBatch("batch_upsert",this._meta.model.tableName,r,this.getAuditUserId()));}return this._meta.model.serializer&&(t.items=t.items.map(o=>({...o,data:this._meta.model.serializer(o.data)}))),this.success(t)}};var dt=z.object({id:z.string(),recordId:z.union([z.string(),z.number()]),version:z.number(),data:z.record(z.string(),z.unknown()),createdAt:z.date(),changedBy:z.string().optional(),changeReason:z.string().optional(),changes:z.array(z.object({field:z.string(),oldValue:z.unknown().optional(),newValue:z.unknown().optional()})).optional()}),st=class extends S{lookupField="id";defaultLimit=20;maxLimit=100;getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getQuerySchema(){return z.object({limit:z.coerce.number().min(1).max(this.maxLimit).optional(),offset:z.coerce.number().min(0).optional()})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema(),query:this.getQuerySchema()},responses:{200:{description:"Version history retrieved successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({versions:z.array(dt),totalVersions:z.number()})})}}},400:{description:"Versioning not enabled",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}},404:{description:"Record not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getPaginationOptions(){let{query:e}=await this.getValidatedData();return {limit:e?.limit?Number(e.limit):this.defaultLimit,offset:e?.offset?Number(e.offset):0}}async recordExists(e){return true}async handle(){if(!this.isVersioningEnabled())throw new a$2("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),{limit:t,offset:o}=await this.getPaginationOptions();if(!await this.recordExists(e))throw new c$1(this._meta.model.tableName,e);let n=this.getVersionManager(),i=await n.getVersions(e,{limit:t,offset:o}),u=await n.getLatestVersion(e);return this.success({versions:i,totalVersions:u})}},it=class extends S{lookupField="id";getParamsSchema(){return z.object({[this.lookupField]:z.string(),version:z.coerce.number().min(1)})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema()},responses:{200:{description:"Version retrieved successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:dt})}}},400:{description:"Versioning not enabled",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}},404:{description:"Version not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getVersionNumber(){let{params:e}=await this.getValidatedData();return e?.version?Number(e.version):0}async handle(){if(!this.isVersioningEnabled())throw new a$2("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),t=await this.getVersionNumber(),r=await this.getVersionManager().getVersion(e,t);if(!r)throw new c$1(`version ${t}`,e);return this.success(r)}},at=class extends S{lookupField="id";getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getQuerySchema(){return z.object({from:z.coerce.number().min(1),to:z.coerce.number().min(1)})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema(),query:this.getQuerySchema()},responses:{200:{description:"Version comparison completed",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({from:z.number(),to:z.number(),changes:z.array(z.object({field:z.string(),oldValue:z.unknown().optional(),newValue:z.unknown().optional()}))})})}}},400:{description:"Versioning not enabled or invalid parameters",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}},404:{description:"Version not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getVersionNumbers(){let{query:e}=await this.getValidatedData();return {from:e?.from?Number(e.from):0,to:e?.to?Number(e.to):0}}async handle(){if(!this.isVersioningEnabled())throw new a$2("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),{from:t,to:o}=await this.getVersionNumbers(),n=await this.getVersionManager().compareVersions(e,t,o);return this.success({from:t,to:o,changes:n})}},lt=class extends S{lookupField="id";getParamsSchema(){return z.object({[this.lookupField]:z.string(),version:z.coerce.number().min(1)})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema()},responses:{200:{description:"Record rolled back successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:{description:"Versioning not enabled",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}},404:{description:"Version not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getVersionNumber(){let{params:e}=await this.getValidatedData();return e?.version?Number(e.version):0}async handle(){if(!this.isVersioningEnabled())throw new a$2("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),t=await this.getVersionNumber(),o=this.getVersionManager(),r=await o.getVersion(e,t);if(!r)throw new c$1(`version ${t}`,e);let i=await o.getLatestVersion(e)+1,u=await this.rollback(e,r.data,i),l=this._meta.model.serializer?this._meta.model.serializer(u):u;return this.success(l)}};var Ct={sumFields:[],avgFields:[],minMaxFields:[],countDistinctFields:[],groupByFields:[],defaultLimit:100,maxLimit:1e3},ct=class extends S{aggregateConfig={};maxGroupByFields=5;filterFields=[];getAggregateConfig(){return {...Ct,...this.aggregateConfig}}getQuerySchema(){return z.object({count:z.union([z.string(),z.array(z.string())]).optional(),sum:z.union([z.string(),z.array(z.string())]).optional(),avg:z.union([z.string(),z.array(z.string())]).optional(),min:z.union([z.string(),z.array(z.string())]).optional(),max:z.union([z.string(),z.array(z.string())]).optional(),countDistinct:z.union([z.string(),z.array(z.string())]).optional(),groupBy:z.string().optional(),orderBy:z.string().optional(),orderDirection:z.enum(["asc","desc"]).optional(),limit:z.coerce.number().optional(),offset:z.coerce.number().optional(),withDeleted:z.coerce.boolean().optional()}).passthrough()}getSchema(){let e=z.object({key:z.record(z.string(),z.unknown()),values:z.record(z.string(),z.number().nullable())});return {...this.schema,request:{query:this.getQuerySchema()},responses:{200:{description:"Aggregation result",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({values:z.record(z.string(),z.number().nullable()).optional(),groups:z.array(e).optional(),totalGroups:z.number().optional()})})}}},400:{description:"Invalid aggregation request",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.unknown().optional()})})}}}}}}async getAggregateOptions(){let{query:e}=await this.getValidatedData();return i$1(e||{})}validateAggregations(e){let t=this.getAggregateConfig();for(let o of e.aggregations)if(!(o.operation==="count"&&o.field==="*"))switch(o.operation){case "sum":if(t.sumFields.length>0&&!t.sumFields.includes(o.field))throw new Error(`Field '${o.field}' is not allowed for SUM aggregation`);break;case "avg":if(t.avgFields.length>0&&!t.avgFields.includes(o.field))throw new Error(`Field '${o.field}' is not allowed for AVG aggregation`);break;case "min":case "max":if(t.minMaxFields.length>0&&!t.minMaxFields.includes(o.field))throw new Error(`Field '${o.field}' is not allowed for MIN/MAX aggregation`);break;case "countDistinct":if(t.countDistinctFields.length>0&&!t.countDistinctFields.includes(o.field))throw new Error(`Field '${o.field}' is not allowed for COUNT DISTINCT aggregation`);break}if(e.groupBy){if(e.groupBy.length>this.maxGroupByFields)throw new b$3(`Maximum ${this.maxGroupByFields} GROUP BY fields allowed`);for(let o of e.groupBy)if(t.groupByFields.length>0&&!t.groupByFields.includes(o))throw new Error(`Field '${o}' is not allowed for GROUP BY`)}if(e.limit!==void 0&&e.limit>t.maxLimit)throw new Error(`Limit cannot exceed ${t.maxLimit}`)}getAggregateAlias(e){return e.alias?e.alias:e.field==="*"?e.operation:`${e.operation}${e.field.charAt(0).toUpperCase()}${e.field.slice(1)}`}async handle(){let e=await this.getAggregateOptions();e.aggregations.length===0&&e.aggregations.push({operation:"count",field:"*"}),this.validateAggregations(e);let t=this.getAggregateConfig();e.groupBy&&e.groupBy.length>0&&e.limit===void 0&&(e.limit=t.defaultLimit);let o=await this.aggregate(e);return this.success(o)}},vt={eq:(s,e)=>s===e,ne:(s,e)=>s!==e,gt:(s,e)=>s>e,gte:(s,e)=>s>=e,lt:(s,e)=>s<e,lte:(s,e)=>s<=e};function At(s,e){let t=s.get(e);if(t)return t;let o=[];return s.set(e,o),o}function zr(s,e){let{aggregations:t,groupBy:o,having:r,orderBy:n,orderDirection:i,limit:u,offset:l}=e;if(!o||o.length===0){let d={};for(let m of t){let f=pt(m);d[f]=ut(s,m);}return {values:d}}let p=new Map;for(let d of s){let f=o.map(g=>String(d[g]??"null")).join("|");At(p,f).push(d);}let a=[];for(let[d,m]of p){let f=d.split("|"),g={};o.forEach((x,k)=>{g[x]=f[k]==="null"?null:f[k];});let j={};for(let x of t){let k=pt(x);j[k]=ut(m,x);}a.push({key:g,values:j});}r&&(a=a.filter(d=>{for(let[m,f]of Object.entries(r)){let g=d.values[m];if(g!==null)for(let[j,x]of Object.entries(f)){let k=vt[j];if(k&&!k(g,Number(x)))return false}}return true}));let c=a.length;if(n){let d=i==="desc"?-1:1;a.sort((m,f)=>{if(n in m.values){let g=m.values[n]??0,j=f.values[n]??0;return (g-j)*d}if(n in m.key){let g=String(m.key[n]??""),j=String(f.key[n]??"");return g.localeCompare(j)*d}return 0});}if(l!==void 0||u!==void 0){let d=l||0,m=u?d+u:void 0;a=a.slice(d,m);}return {groups:a,totalGroups:c}}function Me(s,e){return s.map(t=>t[e]).filter(t=>typeof t=="number")}var _t={count:(s,e)=>e==="*"?s.length:s.filter(t=>t[e]!==null&&t[e]!==void 0).length,countDistinct:(s,e)=>new Set(s.map(o=>o[e]).filter(o=>o!=null).map(o=>String(o))).size,sum:(s,e)=>{let t=0;for(let o of s){let r=o[e];typeof r=="number"&&(t+=r);}return t},avg:(s,e)=>{let t=Me(s,e);return t.length===0?null:t.reduce((r,n)=>r+n,0)/t.length},min:(s,e)=>{let t=Me(s,e);return t.length===0?null:Math.min(...t)},max:(s,e)=>{let t=Me(s,e);return t.length===0?null:Math.max(...t)}};function ut(s,e){if(s.length===0)return e.operation==="count"?0:null;let t=_t[e.operation];return t?t(s,e.field):null}function pt(s){return s.alias?s.alias:s.field==="*"?s.operation:`${s.operation}${s.field.charAt(0).toUpperCase()}${s.field.slice(1)}`}var Tt=new Set(["a","an","and","are","as","at","be","by","for","from","has","he","in","is","it","its","of","on","or","that","the","to","was","were","will","with"]);function ht(s,e=true){if(!s||typeof s!="string")return [];let t=s.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter(Boolean);return e?t.filter(o=>!Tt.has(o)&&o.length>1):t}function gt(s,e){return e==="phrase"?[s.toLowerCase().trim()]:ht(s)}function Nt(s,e){return e.length===0?0:e.filter(o=>o===s||o.includes(s)).length/e.length}function ft(s,e,t,o){if(e.length===0)return {score:0,matchedFields:[]};let r=0,n=0,i=[];for(let[l,p]of Object.entries(t)){let a=s[l];if(a==null)continue;let c=p.weight??1;n+=c;let d;p.type==="array"&&Array.isArray(a)?d=a.join(" "):d=String(a);let m=ht(d,false),f=d.toLowerCase(),g=0,j=0;if(o==="phrase"){let x=e[0];f.includes(x)&&(g=1,j=1);}else {for(let x of e){let k=Nt(x,m);k>0?(j++,g+=k):f.includes(x)&&(j++,g+=.5/e.length);}e.length>0&&(g=g/e.length);}o==="all"&&j<e.length&&(g=0),g>0&&(i.push(l),r+=g*c);}return {score:n>0?Math.min(1,r/n):0,matchedFields:i}}function bt(s,e,t,o="mark",r=150){if(s==null)return [];let n;if(Array.isArray(s)?n=s.join(" "):n=String(s),!n||e.length===0)return [];let i=[],u=n.toLowerCase();if(t==="phrase"){let l=e[0],p=u.indexOf(l);if(p!==-1){let a=mt(n,p,l.length,r,o);a&&i.push(a);}}else {let l=[];for(let a of e){let c=0;for(;c<u.length;){let d=u.indexOf(a,c);if(d===-1)break;l.push({start:d,length:a.length}),c=d+1;}}l.sort((a,c)=>a.start-c.start);let p=new Set;for(let a of l){if(Array.from(p).some(m=>Math.abs(m-a.start)<r))continue;let d=mt(n,a.start,a.length,r,o);if(d&&(i.push(d),p.add(a.start)),i.length>=3)break}}return i}function mt(s,e,t,o,r){let n=Math.floor(o/2),i=Math.max(0,e-n),u=Math.min(s.length,e+t+n);if(i>0){let a=s.indexOf(" ",i);a!==-1&&a<e&&(i=a+1);}if(u<s.length){let a=s.lastIndexOf(" ",u);a!==-1&&a>e+t&&(u=a);}let l=s.slice(i,u);return i>0&&(l="..."+l),u<s.length&&(l=l+"..."),Vt(l,[s.slice(e,e+t)],r)}function Vt(s,e,t){let o=s,r=s.toLowerCase(),n=[...e].sort((i,u)=>u.length-i.length);for(let i of n){let u=i.toLowerCase(),l=0,p="",a=0;for(;a<r.length;){let c=r.indexOf(u,a);if(c===-1)break;p+=o.slice(l,c),p+=`<${t}>${o.slice(c,c+i.length)}</${t}>`,l=c+i.length,a=l;}p&&(p+=o.slice(l),o=p);}return o}function wt(s,e){if(!s)return Object.keys(e);let t=s.split(",").map(r=>r.trim()).filter(Boolean),o=Object.keys(e);return t.filter(r=>o.includes(r))}function yt(s,e){let t={};for(let o of s)t[o]={weight:e?.[o]??1};return t}function Zt(s){if(s instanceof z.ZodString)return true;let e=s;return e?e._def?.type==="string"||e._def?.typeName==="ZodString"||e.def?.type==="string":false}var Mt=class extends S{searchableFields={};searchFields=[];fieldWeights={};defaultMode="any";minQueryLength=2;maxQueryLength=500;highlightTag="mark";snippetLength=150;defaultMinScore=0;searchParamName="q";filterFields=[];filterConfig;sortFields=[];defaultSort;defaultPerPage=20;maxPerPage=100;allowedIncludes=[];fieldSelectionEnabled=false;allowedSelectFields=[];blockedSelectFields=[];alwaysIncludeFields=[];defaultSelectFields=[];getSearchableFields(){if(Object.keys(this.searchableFields).length>0)return this.searchableFields;if(this.searchFields.length>0)return yt(this.searchFields,this.fieldWeights);let e=this.getModelSchema().shape,t={};for(let[o,r]of Object.entries(e))Zt(r)&&(t[o]={weight:1});return t}getQuerySchema(){let t={[this.searchParamName||"q"]:z.string().min(this.minQueryLength).max(this.maxQueryLength).describe("Search query"),fields:z.string().optional().describe(`Comma-separated fields to search. Available: ${Object.keys(this.getSearchableFields()).join(", ")}`),mode:z.enum(["any","all","phrase"]).optional().describe("Search mode: any (OR), all (AND), phrase (exact)"),highlight:z.enum(["true","false"]).optional().describe("Include highlighted snippets"),minScore:z.string().optional().describe("Minimum relevance score threshold (0-1)"),page:z.string().optional(),per_page:z.string().optional()};this.sortFields.length>0&&(t.sort=z.enum(this.sortFields).optional().describe("Field to sort by"),t.order=z.enum(["asc","desc"]).optional().describe("Sort direction (asc or desc)"));for(let r of this.filterFields)t[r]=z.string().optional();if(this.filterConfig)for(let[r,n]of Object.entries(this.filterConfig)){for(let i of n)t[`${r}[${i}]`]=z.string().optional();t[r]=z.string().optional();}let o=this.getSoftDeleteConfig();if(o.enabled&&o.allowQueryDeleted&&(t[o.queryParam]=z.enum(["true","false"]).optional(),t.onlyDeleted=z.enum(["true","false"]).optional()),this.allowedIncludes.length>0&&(t.include=z.string().optional().describe(`Comma-separated list of relations to include. Allowed: ${this.allowedIncludes.join(", ")}`)),this.fieldSelectionEnabled){let r=this.getAvailableSelectFields();t.fields=z.string().optional().describe(`Comma-separated list of fields to return. Available: ${r.join(", ")}`);}return z.object(t)}getAvailableSelectFields(){let e=Object.keys(this.getModelSchema().shape),t=this._meta.model.computedFields?Object.keys(this._meta.model.computedFields):[],o=this._meta.model.relations?Object.keys(this._meta.model.relations):[],r=[...e,...t,...o];return this.allowedSelectFields.length>0&&(r=r.filter(n=>this.allowedSelectFields.includes(n))),this.blockedSelectFields.length>0&&(r=r.filter(n=>!this.blockedSelectFields.includes(n))),r}getSchema(){let e=z.object({item:this.getModelSchema(),score:z.number().min(0).max(1),highlights:z.record(z.string(),z.array(z.string())).optional(),matchedFields:z.array(z.string())});return {...this.schema,request:{query:this.getQuerySchema()},responses:{200:{description:"Search results",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.array(e),result_info:z.object({page:z.number(),per_page:z.number(),total_count:z.number().optional(),total_pages:z.number().optional(),query:z.string(),searchedFields:z.array(z.string())})})}}},400:{description:"Invalid search request",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.unknown().optional()})})}}}}}}async getSearchOptions(){let{query:e}=await this.getValidatedData(),t=this.searchParamName||"q",o=e?.[t],r$1=e?.fields,n=r(e?.mode),i=e?.highlight==="true",u=e?.minScore?Math.max(0,Math.min(1,parseFloat(e.minScore)||0)):this.defaultMinScore,l=this.getSearchableFields(),p=wt(r$1,l);return {query:o,fields:p.length>0?p:Object.keys(l),mode:n??this.defaultMode,highlight:i,minScore:u}}async getFilters(){let{query:e}=await this.getValidatedData(),t=this.getSoftDeleteConfig(),o={filterFields:this.filterFields,filterConfig:this.filterConfig,searchFields:[],searchFieldName:"q",sortFields:this.sortFields,defaultSort:this.defaultSort,defaultPerPage:this.defaultPerPage,maxPerPage:this.maxPerPage,softDeleteQueryParam:t.queryParam,allowedIncludes:this.allowedIncludes,fieldSelectionEnabled:this.fieldSelectionEnabled,allowedSelectFields:this.allowedSelectFields,blockedSelectFields:this.blockedSelectFields,alwaysIncludeFields:this.alwaysIncludeFields,defaultSelectFields:this.defaultSelectFields};return de(e||{},o)}async beforeSearch(e){return e}async afterSearch(e){return e}async handle(){let e=await this.getSearchOptions(),t=await this.getFilters();if(!e.query||e.query.length<this.minQueryLength)return this.json({success:false,error:{code:"INVALID_QUERY",message:`Search query must be at least ${this.minQueryLength} characters`}},400);e=await this.beforeSearch(e);let o=await this.search(e,t),r=await this.afterSearch(o.items);if(this._meta.model.computedFields){let a=r.map(d=>d.item),c=await k(a,this._meta.model.computedFields);r=r.map((d,m)=>({...d,item:c[m]}));}this._meta.model.serializer&&(r=r.map(a=>({...a,item:this._meta.model.serializer(a.item)})));let n=r;this.fieldSelectionEnabled&&t.options.fields&&t.options.fields.length>0&&(n=r.map(a=>({...a,item:ce([a.item],{fields:t.options.fields,isActive:true})[0]})));let i=o.postFilteredCount??o.totalCount,u=t.options.page||1,l=t.options.per_page||this.defaultPerPage,p=Math.ceil(i/l);return this.successPaginated(n,{page:u,per_page:l,total_count:i,total_pages:p,query:e.query,searchedFields:e.fields||Object.keys(this.getSearchableFields())})}};function Qr(s,e,t){let o=gt(e.query,e.mode),r={},n=e.fields||Object.keys(t);for(let u of n)t[u]&&(r[u]=t[u]);let i=[];for(let u of s){let{score:l,matchedFields:p}=ft(u,o,r,e.mode);if(l<e.minScore||p.length===0)continue;let a;if(e.highlight){a={};for(let c of p){let d=bt(u[c],o,e.mode);d.length>0&&(a[c]=d);}}i.push({item:u,score:l,highlights:a&&Object.keys(a).length>0?a:void 0,matchedFields:p});}return i.sort((u,l)=>l.score-u.score),i}function J(s,e={}){let{delimiter:t=",",nullValue:o="",dateFormat:r="iso"}=e;if(s==null)return o;if(s instanceof Date)switch(r){case "timestamp":return String(s.getTime());case "locale":return s.toLocaleString();default:return s.toISOString()}if(typeof s=="object")return J(JSON.stringify(s),e);if(typeof s=="boolean")return s?"true":"false";let n=String(s),i=n.charAt(0);return i==="="||i==="+"||i==="-"||i==="@"||i===" "||i==="\r"?`" ${n.replace(/"/g,'""')}"`:n.includes(t)||n.includes('"')||n.includes(`
1
+ import {a as a$1,b as b$1}from'./chunk-SDNXN7M5.js';import {b,f as f$2}from'./chunk-XI7HT5ZM.js';import {f as f$1}from'./chunk-NGUMNUOP.js';import {f}from'./chunk-FJCWFB5L.js';import {i,d,a as a$2,b as b$3,c as c$1}from'./chunk-FC56WWPB.js';import {e,g,n,o,p,c,j,d as d$3,k,i as i$1,r}from'./chunk-KUFOENSK.js';import {d as d$2,e as e$1}from'./chunk-QRXEQTNE.js';import {d as d$1}from'./chunk-QXFY6NYI.js';import {b as b$4}from'./chunk-DMGP7QDL.js';import {a,b as b$2}from'./chunk-VJRDAVID.js';import {z}from'zod';import {HTTPException}from'hono/http-exception';import {stream}from'hono/streaming';var me="createdAt",he="updatedAt";function se(s){return s?s===true?{enabled:true,createdAt:me,updatedAt:he}:{enabled:true,createdAt:s.createdAt??me,updatedAt:s.updatedAt??he}:{enabled:false,createdAt:me,updatedAt:he}}function Z(s,e={}){let{includePrimaryKeys:t=true}=e,o=new Set;if(t)for(let n of s.primaryKeys)o.add(n);let r=se(s.timestamps);return r.enabled&&(o.add(r.createdAt),o.add(r.updatedAt)),[...o]}function kt(s){return s!=null&&s!==""}function ze(s,e,t,o){let r={...s},n=e.primaryKeys[0];if(!kt(r[n])){let u=e.id;if(typeof u=="function")r[n]=u();else if(u==="database"){if(t==="memory")throw new i("MemoryAdapter does not support id:'database' (no database to generate the key)");delete r[n];}else r[n]=o?o():crypto.randomUUID();}let i$1=se(e.timestamps);if(i$1.enabled){let u=Date.now();i$1.createdAt in s||(r[i$1.createdAt]=u),i$1.updatedAt in s||(r[i$1.updatedAt]=u);}return r}function Le(s,e){let t=se(e.timestamps);return t.enabled?{...s,[t.updatedAt]:Date.now()}:{...s}}function qe(s,e){if(e==="memory"&&s.id==="database")throw new i("MemoryAdapter does not support id:'database' (no database to generate the key)")}function Ue(s,e){let t={...s};for(let o of Z(e))delete t[o];return t}var xt=new Set(["P2002","SQLITE_CONSTRAINT_UNIQUE","SQLITE_CONSTRAINT","23505","ER_DUP_ENTRY",1062,"1062"]),Ft=/UNIQUE constraint failed|duplicate key value violates unique constraint|Duplicate entry/i;function Pt(s){if(!s||typeof s!="object")return false;let{code:e,message:t}=s;return (typeof e=="string"||typeof e=="number")&&xt.has(e)?true:typeof t=="string"&&Ft.test(t)}function*It(s,e=8){for(let t=s,o=0;o<e&&t!=null&&typeof t=="object";o++)yield t,t=t.cause;}function ge(s){for(let e of It(s))if(Pt(e))return new d("Unique constraint violation");return null}function Q(s){throw ge(s)??s}function fe(s){if(s===null||typeof s!="object")return s;if(Array.isArray(s))return s.map(fe);let e={};for(let t of Object.keys(s).sort())e[t]=fe(s[t]);return e}async function oe(s){let e=JSON.stringify(fe(s)),t=new TextEncoder().encode(e),o=await crypto.subtle.digest("SHA-256",t);return `"${Array.from(new Uint8Array(o)).map(i=>i.toString(16).padStart(2,"0")).join("").substring(0,32)}"`}function be(s,e){return s?s==="*"?true:s.split(",").map(t=>t.trim()).includes(e):false}function we(s,e){return !s||s==="*"?true:s.split(",").map(t=>t.trim()).includes(e)}function Be(s,e){return s==="in"||s==="nin"||s==="between"?e.split(",").map(t=>t.trim()):s==="null"?e.toLowerCase()==="true":e}function $t(s){let e=s.match(/^\[([a-z]+)\](.*)$/);if(e){let t=e[1];return {operator:t,value:Be(t,e[2])}}return {operator:"eq",value:s}}function de(s,e){let t=[],o={},{filterFields:r=[],filterConfig:n={},searchFields:i=[],searchFieldName:u="search",sortFields:l=[],defaultSort:p,defaultPerPage:a=20,maxPerPage:c=100,cursorPaginationEnabled:d=false,softDeleteQueryParam:m="withDeleted",allowedIncludes:f=[],fieldSelectionEnabled:g=false,allowedSelectFields:j=[],blockedSelectFields:x=[],alwaysIncludeFields:k=[],defaultSelectFields:y=[]}=e,F={};for(let C of r)F[C]=["eq"];Object.assign(F,n);for(let[C,X]of Object.entries(s)){if(X==null)continue;let V=String(X);if(d&&C==="cursor"){o.cursor=V;continue}if(d&&C==="limit"){o.limit=Math.min(c,Math.max(1,parseInt(V,10)||a));continue}if(C==="page"){o.page=Math.max(1,parseInt(V,10)||1);continue}if(C==="per_page"){o.per_page=Math.min(c,Math.max(1,parseInt(V,10)||a));continue}if(C==="sort"){(l.length===0||l.includes(V))&&(o.order_by=V);continue}if(C==="order"){(V==="asc"||V==="desc")&&(o.order_by_direction=V);continue}if(C===u&&i.length>0){o.search=V;continue}if(C===m){o.withDeleted=V.toLowerCase()==="true";continue}if(C==="onlyDeleted"){o.onlyDeleted=V.toLowerCase()==="true";continue}if(C==="include"){let ee=V.split(",").map(L=>L.trim()).filter(Boolean);f&&f.length>0?o.include=ee.filter(L=>f.includes(L)):o.include=ee;continue}if(C==="fields"&&g){let L=V.split(",").map(re=>re.trim()).filter(Boolean);j.length>0&&(L=L.filter(re=>j.includes(re))),x.length>0&&(L=L.filter(re=>!x.includes(re))),k.length>0&&(L=[...new Set([...k,...L])]),o.fields=L;continue}let pe=C.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([a-z]+)\]$/);if(pe){let ee=pe[1],L=pe[2];F[ee]?.includes(L)&&t.push({field:ee,operator:L,value:Be(L,V)});continue}F[C]&&t.push({field:C,operator:"eq",value:V});}if(o.page||(o.page=1),o.per_page||(o.per_page=a),!o.order_by&&p?.field&&(o.order_by=p.field),o.order_by_direction||(o.order_by_direction=p?.order??"asc"),g&&!o.fields&&y.length>0){let C=[...y];k.length>0&&(C=[...new Set([...k,...C])]),o.fields=C;}return {filters:t,options:o}}function D(s,e=[]){if(e.length===0)return s;let t=new Set(Object.keys(s.shape)),o=e.filter(n=>t.has(n));if(o.length===0)return s;let r=Object.fromEntries(o.map(n=>[n,true]));return s.omit(r)}function Kt(s,e={},t=[],o=[],r=[]){let{allowedFields:n=[],blockedFields:i=[],alwaysIncludeFields:u=[],defaultFields:l=[],allowComputedFields:p=true,allowRelationFields:a=true}=e;if(!s||typeof s!="string"||s.trim()==="")return l.length>0?{fields:[...new Set([...u,...l])],isActive:false}:{fields:[],isActive:false};let c=s.split(",").map(g=>g.trim()).filter(Boolean),d=new Set;for(let g of t)(n.length===0||n.includes(g))&&(i.includes(g)||d.add(g));if(p)for(let g of o)(n.length===0||n.includes(g))&&(i.includes(g)||d.add(g));if(a)for(let g of r)(n.length===0||n.includes(g))&&(i.includes(g)||d.add(g));let m=c.filter(g=>d.has(g));return {fields:[...new Set([...u,...m])],isActive:true}}function ye(s,e){if(!e.isActive||e.fields.length===0)return s;let t={};for(let o of e.fields)o in s&&(t[o]=s[o]);return t}function ce(s,e){return !e.isActive||e.fields.length===0?s:s.map(t=>ye(t,e))}var $e="__honoCrudResolvedSchema:";function Et(s){return typeof s.getBodySchema=="function"}var S=class extends b{_auditLogger;_versionManager;_tx;getAuditLogger(){return this._auditLogger||(this._auditLogger=f(this._meta.model.audit)),this._auditLogger}getAuditConfig(){return e(this._meta.model.audit)}isAuditEnabled(){return this.getAuditConfig().enabled}getAuditUserId(){let e=this.getAuditConfig();return e.getUserId&&this.context?e.getUserId(this.context):this.context?.var?.userId}getVersionManager(){return this._versionManager||(this._versionManager=f$1(this._meta.model.versioning,this._meta.model.tableName)),this._versionManager}getVersioningConfig(){return g(this._meta.model.versioning,this._meta.model.tableName)}isVersioningEnabled(){return this.getVersioningConfig().enabled}getVersioningUserId(){let e=this.getVersioningConfig();return e.getUserId&&this.context?e.getUserId(this.context):this.context?.var?.userId}getSoftDeleteConfig(){return n(this._meta.model.softDelete)}isSoftDeleteEnabled(){return this.getSoftDeleteConfig().enabled}getMultiTenantConfig(){return o(this._meta.model.multiTenant)}isMultiTenantEnabled(){return this.getMultiTenantConfig().enabled}applyManagedInsertFields(e,t,o){return ze(e,this._meta.model,t,o)}applyManagedUpdateFields(e){return Le(e,this._meta.model)}assertIdStrategySupported(e){qe(this._meta.model,e);}getTimestampsConfig(){return se(this._meta.model.timestamps)}getTenantId(){if(!this.context)return;let e=this.getMultiTenantConfig();return p(this.context,e)}validateTenantId(){let e=this.getMultiTenantConfig();if(!e.enabled)return;let t=this.getTenantId();if(!t&&e.required)throw new HTTPException(400,{message:e.errorMessage});return t}injectTenantId(e){let t=this.getMultiTenantConfig();if(!t.enabled)return e;let o=this.getTenantId();return o?{...e,[t.field]:o}:e}async emitEvent(e,t){let o=d$1(this.context??void 0);o&&await o.emit({type:e,table:this._meta.model.tableName,recordId:t.recordId,data:t.data??null,previousData:t.previousData,userId:this.getAuditUserId(),tenantId:this.context?this.getTenantId():void 0,organizationId:this.context?a(this.context,"organizationId"):void 0,timestamp:new Date().toISOString(),metadata:t.metadata});}async encryptOnWrite(e){let t=this._meta.model.fieldEncryption;return t?await d$2(e,t.fields,t.keyProvider):e}async decryptOnRead(e){let t=this._meta.model.fieldEncryption;return t?await e$1(e,t.fields,t.keyProvider):e}applyProfile(e){let t=this._meta.model.serializationProfile;return t?a$1(e,t):e}applyProfileToArray(e){let t=this._meta.model.serializationProfile;return t?b$1(e,t):e}getRecordId(e){if(e===null||typeof e!="object")return null;let t=this._meta.model.primaryKeys[0],o=e[t];return typeof o=="string"||typeof o=="number"?o:null}getParentId(e){return this.getRecordId(e)}getPolicies(){if(this.context){let e=a(this.context,f$2);if(e)return e}return this._meta.model.policies}buildPolicyContext(){let e=this.context;return {user:e?a(e,"user"):void 0,userId:e?a(e,"userId"):void 0,tenantId:e?a(e,"tenantId"):void 0,organizationId:e?a(e,"organizationId"):void 0,request:e?.req?.raw??new Request("http://localhost/")}}async applyReadPolicy(e){let t=this.getPolicies();if(!t)return e;let o=this.buildPolicyContext();if(t.read&&!await t.read(o,e))return null;if(t.fields){let r=t.fields(o,e);return {...e,...r}}return e}async applyReadPolicyToArray(e){if(!this.getPolicies())return e;let o=[];for(let r of e){let n=await this.applyReadPolicy(r);n!==null&&o.push(n);}return o}async applyWritePolicy(e){let t=this.getPolicies();if(!t?.write)return;if(!await t.write(this.buildPolicyContext(),e))throw new HTTPException(403,{message:"Forbidden by policy"})}applyReadPushdown(e){let t=this.getPolicies();if(!t?.readPushdown)return;let o=t.readPushdown(this.buildPolicyContext());o&&o.length>0&&e.filters.push(...o);}buildHookContext(){let e=this.context;return {db:{tx:this._tx},request:e?.req?.raw,tenantId:e?this.getTenantId():void 0,organizationId:e?a(e,"organizationId"):void 0,userId:e?a(e,"userId"):void 0,agentId:e?a(e,"agentId"):void 0,agentRunId:e?a(e,"agentRunId"):void 0}}getModelSchema(){if(this.context&&this._meta.model.resolveSchema){let e=a(this.context,$e+this._meta.model.tableName);if(e)return e}return this._meta.model.schema}async resolveModelSchema(){let e=this._meta.model.resolveSchema;if(!e||!this.context)return this._meta.model.schema;let t=$e+this._meta.model.tableName,o=a(this.context,t);if(o)return o;let r={tenantId:a(this.context,"tenantId"),organizationId:a(this.context,"organizationId"),request:this.context.req?.raw,env:this.context.env},n;try{n=await e(r);}catch(i){throw new a$2(i instanceof Error?i.message:"Schema resolution failed",500,"SCHEMA_RESOLVE_ERROR",i instanceof Error?{cause:i.message}:void 0)}return b$2(this.context,t,n),n}async getValidatedData(){await this.resolveModelSchema();let e=await super.getValidatedData();if(this.context&&e.body!==void 0&&Et(this)){let t=e.body;try{t=await this.context.req.json();}catch{}let r=this.getBodySchema().safeParse(t);if(!r.success)throw b$3.fromZodError(r.error);e.body=r.data;}return e}};var Ke=class extends S{beforeHookMode="sequential";afterHookMode="sequential";allowNestedCreate=[];getBodySchema(){let e,t=Z(this._meta.model),o=this.getMultiTenantConfig();o.enabled&&t.push(o.field),this._meta.fields?e=this._meta.fields:e=D(this.getModelSchema(),t);let r=this.getNestedWritableRelations();if(r.length===0)return e;let n={...e.shape};for(let i of r){let u=this._meta.model.relations?.[i];if(!u?.schema)continue;let l=["id",u.foreignKey],p=D(u.schema,l);u.type==="hasMany"?n[i]=z.array(p).optional():n[i]=p.optional();}return z.object(n)}getNestedWritableRelations(){if(this.allowNestedCreate.length>0)return this.allowNestedCreate;let e=this._meta.model.relations;return e?Object.entries(e).filter(([t,o])=>o.nestedWrites?.allowCreate===true).map(([t])=>t):[]}extractNestedData(e){let t=this.getNestedWritableRelations();return c(e,t)}getSchema(){let e=this.getBodySchema();return {...this.schema,request:{body:{content:{"application/json":{schema:e}},required:true}},responses:{201:{description:"Resource created successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:{description:"Validation error",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.unknown().optional()})})}}}}}}async getObject(){let{body:e}=await this.getValidatedData();return e}async before(e,t){return e}async after(e,t){return e}transform(e){return e}async createNested(e,t,o,r,n){return b$4().warn(`Nested writes not implemented for ${t}. Override createNested() in your adapter.`),[]}async handle(){this.validateTenantId();let e=await this.getObject(),{mainData:t,nestedData:o}=this.extractNestedData(e),r=t;r=this.injectTenantId(r);let n=this.buildHookContext();r=await this.before(r,n),r=await this.encryptOnWrite(r),r=await this.create(r,n.db.tx).catch(Q),r=await this.decryptOnRead(r);let i=this.getParentId(r),u={};if(Object.keys(o).length>0&&i!==null)for(let[c,d]of Object.entries(o)){if(d==null)continue;let m=this._meta.model.relations?.[c];if(!m)continue;let f=await this.createNested(i,c,m,d);u[c]=f;}if(Object.keys(u).length>0){let c={};for(let[d,m]of Object.entries(u)){let f=this._meta.model.relations?.[d];f&&(f.type==="hasMany"?c[d]=m:c[d]=m[0]||null);}r={...r,...c};}if(this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(r,n))):r=await this.after(r,n),this.isAuditEnabled()&&i!==null){let c=this.getAuditLogger();this.runAfterResponse(c.logCreate(this._meta.model.tableName,i,r,this.getAuditUserId()));}i!==null&&this.runAfterResponse(this.emitEvent("created",{recordId:i,data:r})),this._meta.model.computedFields&&(r=await j(r,this._meta.model.computedFields));let l=this._meta.model.serializer?this._meta.model.serializer(r):r,p=this.applyProfile(l),a=this.transform(p);return this.success(a,201)}};var We=class extends S{lookupField="id";lookupFields;additionalFilters;etagEnabled=false;allowedIncludes=[];fieldSelectionEnabled=false;allowedSelectFields=[];blockedSelectFields=[];alwaysIncludeFields=[];defaultSelectFields=[];getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getQuerySchema(){let e={};if(this.additionalFilters?.length)for(let t of this.additionalFilters)e[t]=z.string().optional();if(this.allowedIncludes.length>0&&(e.include=z.string().optional().describe(`Comma-separated list of relations to include. Allowed: ${this.allowedIncludes.join(", ")}`)),this.fieldSelectionEnabled){let t=this.getAvailableSelectFields();e.fields=z.string().optional().describe(`Comma-separated list of fields to return. Available: ${t.join(", ")}`);}if(Object.keys(e).length!==0)return z.object(e)}getAvailableSelectFields(){let e=Object.keys(this.getModelSchema().shape),t=this._meta.model.computedFields?Object.keys(this._meta.model.computedFields):[],o=this._meta.model.relations?Object.keys(this._meta.model.relations):[],r=[...e,...t,...o];return this.allowedSelectFields.length>0&&(r=r.filter(n=>this.allowedSelectFields.includes(n))),this.blockedSelectFields.length>0&&(r=r.filter(n=>!this.blockedSelectFields.includes(n))),r}getSchema(){let e=this.getQuerySchema();return {...this.schema,request:{params:this.getParamsSchema(),...e&&{query:e}},responses:{200:{description:"Resource retrieved successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},404:{description:"Resource not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async getIncludeOptions(){let{query:e}=await this.getValidatedData(),t=e?.include;if(!t||typeof t!="string")return {relations:[]};let o=t.split(",").map(r=>r.trim()).filter(Boolean);return this.allowedIncludes.length>0?{relations:o.filter(r=>this.allowedIncludes.includes(r))}:{relations:o}}async getFieldSelection(){if(!this.fieldSelectionEnabled)return {fields:[],isActive:false};let{query:e}=await this.getValidatedData(),t=e?.fields;if(!t||typeof t!="string"||t.trim()==="")return this.defaultSelectFields.length>0?{fields:[...new Set([...this.alwaysIncludeFields,...this.defaultSelectFields])],isActive:true}:{fields:[],isActive:false};let o=t.split(",").map(i=>i.trim()).filter(Boolean),r=new Set(this.getAvailableSelectFields()),n=o.filter(i=>r.has(i));return this.alwaysIncludeFields.length>0&&(n=[...new Set([...this.alwaysIncludeFields,...n])]),{fields:n,isActive:true}}async after(e){return e}transform(e){return e}async handle(){let e=this.validateTenantId(),t=await this.getLookupValue(),o=await this.getAdditionalFilters(),r=await this.getIncludeOptions(),n=await this.getFieldSelection();if(e){let d=this.getMultiTenantConfig();o[d.field]=e;}let i=await this.read(t,o,r);if(!i)throw new c$1(this._meta.model.tableName,t);i=await this.decryptOnRead(i);let u=await this.applyReadPolicy(i);if(u===null)throw new c$1(this._meta.model.tableName,t);i=u,i=await this.after(i),this._meta.model.computedFields&&(i=await j(i,this._meta.model.computedFields));let l=this._meta.model.serializer?this._meta.model.serializer(i):i,p=this.applyProfile(l),a=this.transform(p),c=n.isActive&&n.fields.length>0?ye(a,n):a;if(this.etagEnabled){let d=await oe(c),m=this.getContext(),f=m.req.header("If-None-Match");if(be(f,d))return new Response(null,{status:304,headers:{ETag:d}});m.header("ETag",d);}return this.success(c)}};var Qe=class extends S{lookupField="id";lookupFields;additionalFilters;allowedUpdateFields;blockedUpdateFields;beforeHookMode="sequential";afterHookMode="sequential";allowNestedWrites=[];etagEnabled=false;getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getBodySchema(){let e;if(this._meta.fields)e=this._meta.fields.partial();else {let r=Z(this._meta.model);this.blockedUpdateFields&&(r=[...r,...this.blockedUpdateFields]);let n=D(this.getModelSchema(),r);if(this.allowedUpdateFields){let i=this.allowedUpdateFields.reduce((u,l)=>({...u,[l]:true}),{});n=n.pick(i);}e=n.partial();}let t=this.getNestedWritableRelations();if(t.length===0)return e;let o={...e.shape};for(let r of t){let n=this._meta.model.relations?.[r];if(!n?.schema)continue;let i=n.schema,u=z.object({create:z.union([i.partial(),z.array(i.partial())]).optional(),update:z.array(i.partial().extend({id:z.union([z.string(),z.number()])})).optional(),delete:z.array(z.union([z.string(),z.number()])).optional(),connect:z.array(z.union([z.string(),z.number()])).optional(),disconnect:z.array(z.union([z.string(),z.number()])).optional(),set:i.partial().nullable().optional()}).optional();o[r]=u;}return z.object(o)}getNestedWritableRelations(){if(this.allowNestedWrites.length>0)return this.allowNestedWrites;let e=this._meta.model.relations;return e?Object.entries(e).filter(([t,o])=>{let r=o.nestedWrites;return r&&(r.allowCreate||r.allowUpdate||r.allowDelete||r.allowConnect||r.allowDisconnect)}).map(([t])=>t):[]}extractNestedData(e){let t=this.getNestedWritableRelations();return c(e,t)}getSchema(){return {...this.schema,request:{params:this.getParamsSchema(),body:{content:{"application/json":{schema:this.getBodySchema()}},required:true}},responses:{200:{description:"Resource updated successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:{description:"Validation error",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.unknown().optional()})})}}},404:{description:"Resource not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getObject(){let{body:e}=await this.getValidatedData();return e}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async before(e,t){return e}async after(e,t,o){return t}transform(e){return e}async findExisting(e,t,o){return null}async processNestedWrites(e,t,o,r,n){return b$4().warn(`Nested writes not implemented for ${t}. Override processNestedWrites() in your adapter.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]}}async handle(){let e=this.validateTenantId(),t=await this.getLookupValue(),o=await this.getAdditionalFilters();if(e){let y=this.getMultiTenantConfig();o[y.field]=e;}let r=await this.getObject(),{mainData:n,nestedData:i}=this.extractNestedData(r),u=this.getPolicies(),l=await this.findExisting(t,o,this._tx);if(l&&u?.write&&await this.applyWritePolicy(l),this.etagEnabled&&l){let y=this.getContext().req.header("If-Match");if(y){let F=await oe(l);if(!we(y,F))return this.error("Resource has been modified by another request","CONFLICT",409)}}let p;if(this.isVersioningEnabled()&&l){let y=this.getVersionManager(),F=this.getParentId(l);F!==null&&(p=await y.saveVersion(F,l,void 0,this.getVersioningUserId()));}let a=n;if(this.isVersioningEnabled()&&p!==void 0){let y=this.getVersioningConfig().field;a[y]=p;}let c=this.buildHookContext();a=await this.before(a,c),a=await this.encryptOnWrite(a);let d=await this.update(t,a,o,c.db.tx);if(!d)throw new c$1(this._meta.model.tableName,t);d=await this.decryptOnRead(d);let m=this.getParentId(d),f={};if(Object.keys(i).length>0&&m!==null)for(let[y,F]of Object.entries(i)){if(F==null)continue;let C=this._meta.model.relations?.[y];if(!C)continue;let X;d$3(F)?X={create:F}:X=F;let V=await this.processNestedWrites(m,y,C,X);f[y]=V;}if(Object.keys(f).length>0)for(let[y,F]of Object.entries(f)){let C=this._meta.model.relations?.[y];C&&(C.type==="hasMany"?d[y]=[...F.created,...F.updated]:d[y]=F.created[0]||F.updated[0]||null);}let g=l??d;if(this.afterHookMode==="fire-and-forget")this.runAfterResponse(Promise.resolve(this.after(g,d,c)));else {let y=await this.after(g,d,c);y!=null&&(d=y);}if(this.isAuditEnabled()&&m!==null&&l){let y=this.getAuditLogger();this.runAfterResponse(y.logUpdate(this._meta.model.tableName,m,l,d,this.getAuditUserId()));}m!==null&&this.runAfterResponse(this.emitEvent("updated",{recordId:m,data:d,previousData:l??void 0})),this._meta.model.computedFields&&(d=await j(d,this._meta.model.computedFields));let j$1=this._meta.model.serializer?this._meta.model.serializer(d):d,x=this.applyProfile(j$1),k=this.transform(x);if(this.etagEnabled){let y=await oe(k);this.getContext().header("ETag",y);}return this.success(k)}};var Ge=class extends S{lookupField="id";lookupFields;additionalFilters;beforeHookMode="sequential";afterHookMode="sequential";includeCascadeResults=false;getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getCascadeRelations(e){let t=this._meta.model.relations;return t?Object.entries(t).filter(([o,r])=>{let n=r.cascade?.[e];return n&&n!=="noAction"}).map(([o,r])=>({name:o,config:r,action:r.cascade[e]})):[]}getSchema(){let e=this.includeCascadeResults?z.object({deleted:z.literal(true),cascade:z.object({deleted:z.record(z.string(),z.number()),nullified:z.record(z.string(),z.number())}).optional()}):z.object({deleted:z.literal(true)});return {...this.schema,request:{params:this.getParamsSchema()},responses:{200:{description:"Resource deleted successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:e})}}},404:{description:"Resource not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}},409:{description:"Cannot delete - related records exist (restrict)",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.object({relation:z.string(),count:z.number()}).optional()})})}}}}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async before(e,t){}async after(e,t){}async countRelated(e,t,o,r){return b$4().warn(`countRelated not implemented for ${t}. Override in your adapter for restrict cascade to work.`),0}async deleteRelated(e,t,o,r){return b$4().warn(`deleteRelated not implemented for ${t}. Override in your adapter for cascade delete to work.`),0}async nullifyRelated(e,t,o,r){return b$4().warn(`nullifyRelated not implemented for ${t}. Override in your adapter for setNull cascade to work.`),0}async processCascade(e,t,o){let r=t?"onSoftDelete":"onDelete",n=this.getCascadeRelations(r),i={deleted:{},nullified:{}};for(let{name:u,config:l,action:p}of n)if(p==="cascade"){let a=await this.deleteRelated(e,u,l,o);a>0&&(i.deleted[u]=a);}else if(p==="setNull"){let a=await this.nullifyRelated(e,u,l,o);a>0&&(i.nullified[u]=a);}return i}async checkRestrictConstraints(e,t,o){let r=t?"onSoftDelete":"onDelete",n=this.getCascadeRelations(r);for(let{name:i,config:u,action:l}of n)if(l==="restrict"){let p=await this.countRelated(e,i,u,o);if(p>0)throw new d(`Cannot delete: ${p} related ${i} record(s) exist. Remove them first or change the cascade configuration.`,{relation:i,count:p})}}async handle(){let e=this.validateTenantId(),t=await this.getLookupValue(),o=await this.getAdditionalFilters();if(e){let c=this.getMultiTenantConfig();o[c.field]=e;}let r=this.isSoftDeleteEnabled(),n=await this.findForDelete(t,o,this._tx);if(!n)throw new c$1(this._meta.model.tableName,t);let i=this.getParentId(n);i!==null&&await this.checkRestrictConstraints(i,r),await this.applyWritePolicy(n);let u=this.buildHookContext();if(await this.before(t,u),!await this.delete(t,o,u.db.tx))throw new c$1(this._meta.model.tableName,t);let p;if(i!==null&&(p=await this.processCascade(i,r)),this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(n,u))):await this.after(n,u),this.isAuditEnabled()&&i!==null){let c=this.getAuditLogger();this.runAfterResponse(c.logDelete(this._meta.model.tableName,i,n,this.getAuditUserId()));}i!==null&&this.runAfterResponse(this.emitEvent("deleted",{recordId:i,previousData:n}));let a={deleted:true};if(this.includeCascadeResults&&p){let c=Object.keys(p.deleted).length>0,d=Object.keys(p.nullified).length>0;(c||d)&&(a.cascade=p);}return this.success(a)}};var ue=class extends S{filterFields=[];filterConfig;searchFields=[];searchFieldName="search";sortFields=[];defaultSort;defaultPerPage=20;maxPerPage=100;cursorPaginationEnabled=false;cursorField;allowedIncludes=[];fieldSelectionEnabled=false;allowedSelectFields=[];blockedSelectFields=[];alwaysIncludeFields=[];defaultSelectFields=[];getQuerySchema(){let e={page:z.string().optional(),per_page:z.string().optional()};this.sortFields.length>0&&(e.sort=z.enum(this.sortFields).optional().describe("Field to sort by"),e.order=z.enum(["asc","desc"]).optional().describe("Sort direction (asc or desc)")),this.searchFields.length>0&&(e[this.searchFieldName]=z.string().optional());for(let o of this.filterFields)e[o]=z.string().optional();if(this.filterConfig)for(let[o,r]of Object.entries(this.filterConfig)){for(let n of r)e[`${o}[${n}]`]=z.string().optional();e[o]=z.string().optional();}let t=this.getSoftDeleteConfig();if(t.enabled&&t.allowQueryDeleted&&(e[t.queryParam]=z.enum(["true","false"]).optional(),e.onlyDeleted=z.enum(["true","false"]).optional()),this.allowedIncludes.length>0&&(e.include=z.string().optional().describe(`Comma-separated list of relations to include. Allowed: ${this.allowedIncludes.join(", ")}`)),this.fieldSelectionEnabled){let o=this.getAvailableSelectFields();e.fields=z.string().optional().describe(`Comma-separated list of fields to return. Available: ${o.join(", ")}`);}return this.cursorPaginationEnabled&&(e.cursor=z.string().optional().describe("Opaque cursor for fetching the next page"),e.limit=z.string().optional().describe("Number of items to return (cursor pagination)")),z.object(e)}getAvailableSelectFields(){let e=Object.keys(this.getModelSchema().shape),t=this._meta.model.computedFields?Object.keys(this._meta.model.computedFields):[],o=this._meta.model.relations?Object.keys(this._meta.model.relations):[],r=[...e,...t,...o];return this.allowedSelectFields.length>0&&(r=r.filter(n=>this.allowedSelectFields.includes(n))),this.blockedSelectFields.length>0&&(r=r.filter(n=>!this.blockedSelectFields.includes(n))),r}getSchema(){return {...this.schema,request:{query:this.getQuerySchema()},responses:{200:{description:"List of resources",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.array(this.getModelSchema()),result_info:z.object({page:z.number(),per_page:z.number(),total_count:z.number().optional(),total_pages:z.number().optional(),has_next_page:z.boolean(),has_prev_page:z.boolean(),next_cursor:z.string().optional(),prev_cursor:z.string().optional()})})}}}}}}async getFilters(){let{query:e}=await this.getValidatedData(),t=this.getSoftDeleteConfig(),o={filterFields:this.filterFields,filterConfig:this.filterConfig,searchFields:this.searchFields,searchFieldName:this.searchFieldName,sortFields:this.sortFields,defaultSort:this.defaultSort,defaultPerPage:this.defaultPerPage,maxPerPage:this.maxPerPage,cursorPaginationEnabled:this.cursorPaginationEnabled,cursorField:this.cursorField,softDeleteQueryParam:t.queryParam,allowedIncludes:this.allowedIncludes,fieldSelectionEnabled:this.fieldSelectionEnabled,allowedSelectFields:this.allowedSelectFields,blockedSelectFields:this.blockedSelectFields,alwaysIncludeFields:this.alwaysIncludeFields,defaultSelectFields:this.defaultSelectFields};return de(e||{},o)}async after(e){return e}transform(e){return e}async handle(){let e=this.validateTenantId(),t=await this.getFilters();if(e){let a=this.getMultiTenantConfig();t.filters.push({field:a.field,operator:"eq",value:e});}this.applyReadPushdown(t);let o=await this.list(t),r=await Promise.all(o.result.map(a=>this.decryptOnRead(a))),n=await this.applyReadPolicyToArray(r),i=await this.after(n);this._meta.model.computedFields&&(i=await k(i,this._meta.model.computedFields)),this._meta.model.serializer&&(i=i.map(a=>this._meta.model.serializer(a)));let l=this.applyProfileToArray(i).map(a=>this.transform(a)),p=this.fieldSelectionEnabled&&t.options.fields&&t.options.fields.length>0?ce(l,{fields:t.options.fields,isActive:true}):l;return this.successPaginated(p,o.result_info)}};var Je=class extends S{lookupField="id";excludeFromClone=[];getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getBodySchema(){let e=[...Z(this._meta.model),...this.excludeFromClone];return D(this.getModelSchema(),e).partial()}getSchema(){return {...this.schema,request:{params:this.getParamsSchema(),body:{content:{"application/json":{schema:this.getBodySchema()}},required:false}},responses:{201:{description:"Resource cloned successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},404:{description:"Source resource not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}},409:{description:"Unique-constraint violation (e.g. natural-key collision)",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getOverrides(){let{body:e}=await this.getValidatedData();return e||{}}async before(e){return e}async after(e){return e}async handle(){let e=this.validateTenantId(),t=await this.getLookupValue(),o=await this.getOverrides(),r={};if(e){let a=this.getMultiTenantConfig();r[a.field]=e;}let n=await this.findSource(t,r);if(!n)throw new c$1(this._meta.model.tableName,t);let i=Ue(n,this._meta.model);for(let a of this.excludeFromClone)delete i[a];Object.assign(i,o);let u=await this.before(i),l=await this.createClone(u).catch(Q);l=await this.after(l),this._meta.model.computedFields&&(l=await j(l,this._meta.model.computedFields));let p=this._meta.model.serializer?this._meta.model.serializer(l):l;return this.success(p,201)}};var Ye=class extends S{lookupField="id";lookupFields;additionalFilters;beforeHookMode="sequential";afterHookMode="sequential";getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema()},responses:{200:{description:"Resource restored successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:{description:"Soft delete not enabled or record not deleted",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}},404:{description:"Resource not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async before(e,t){}async after(e,t){return e}async handle(){if(!this.isSoftDeleteEnabled())throw new a$2("Soft delete is not enabled for this model",400,"SOFT_DELETE_NOT_ENABLED");let e=await this.getLookupValue(),t=await this.getAdditionalFilters();await this.before(e);let o=await this.restore(e,t);if(!o)throw new c$1(this._meta.model.tableName,e);this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(o))):o=await this.after(o);let r=this.getRecordId(o);if(this.isAuditEnabled()&&r!==null){let i=this.getAuditLogger();this.runAfterResponse(i.logRestore(this._meta.model.tableName,r,o,this.getAuditUserId()));}r!==null&&this.runAfterResponse(this.emitEvent("restored",{recordId:r,data:o}));let n=this._meta.model.serializer?this._meta.model.serializer(o):o;return this.success(n)}};var Xe=class extends S{upsertKeys;useNativeUpsert=false;createOnlyFields;updateOnlyFields;beforeHookMode="sequential";afterHookMode="sequential";allowNestedWrites=[];getUpsertKeys(){return this.upsertKeys||this._meta.model.primaryKeys}getBodySchema(){let e;if(this._meta.fields)e=this._meta.fields;else {let r=this.getUpsertKeys(),n=Z(this._meta.model,{includePrimaryKeys:false});for(let l of this._meta.model.primaryKeys)r.includes(l)||n.push(l);let i=D(this.getModelSchema(),n),u={};for(let[l,p]of Object.entries(i.shape))r.includes(l)?u[l]=p:u[l]=p.optional();e=z.object(u);}let t=this.getNestedWritableRelations();if(t.length===0)return e;let o={...e.shape};for(let r of t){let n=this._meta.model.relations?.[r];if(!n?.schema)continue;let i=n.schema,u=z.union([n.type==="hasMany"?z.array(i.partial()):i.partial(),z.object({create:z.union([i.partial(),z.array(i.partial())]).optional(),update:z.array(i.partial().extend({id:z.union([z.string(),z.number()])})).optional(),upsert:z.union([i.partial(),z.array(i.partial())]).optional(),delete:z.array(z.union([z.string(),z.number()])).optional(),connect:z.array(z.union([z.string(),z.number()])).optional(),disconnect:z.array(z.union([z.string(),z.number()])).optional(),set:i.partial().nullable().optional()})]).optional();o[r]=u;}return z.object(o)}getNestedWritableRelations(){if(this.allowNestedWrites.length>0)return this.allowNestedWrites;let e=this._meta.model.relations;return e?Object.entries(e).filter(([t,o])=>{let r=o.nestedWrites;return r&&(r.allowCreate||r.allowUpdate||r.allowDelete||r.allowConnect||r.allowDisconnect)}).map(([t])=>t):[]}extractNestedData(e){let t=this.getNestedWritableRelations();return c(e,t)}getSchema(){return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}},required:true}},responses:{200:{description:"Resource updated (upsert)",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema(),created:z.literal(false)})}}},201:{description:"Resource created (upsert)",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema(),created:z.literal(true)})}}},400:{description:"Validation error",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.unknown().optional()})})}}}}}}async getObject(){let{body:e}=await this.getValidatedData();return e}async before(e,t,o){return e}async beforeCreate(e,t){return e}async beforeUpdate(e,t,o){return e}async after(e,t,o){return e}async nativeUpsert(e,t){return b$4().warn("Native upsert not implemented for this adapter. Falling back to find-then-insert/update pattern."),this.performStandardUpsert(e,t)}async performStandardUpsert(e,t){let o=await this.findExisting(e,t);if(o){let r={...e};if(this.createOnlyFields)for(let i of this.createOnlyFields)delete r[i];return r=await this.beforeUpdate(r,o,t),{data:await this.update(o,r,t),created:false}}else {let r={...e};if(this.updateOnlyFields)for(let i of this.updateOnlyFields)delete r[i];return r=await this.beforeCreate(r,t),{data:await this.create(r,t),created:true}}}async upsert(e,t){return this.useNativeUpsert?this.nativeUpsert(e,t):this.performStandardUpsert(e,t)}async processNestedWrites(e,t,o,r,n){return b$4().warn(`Nested writes not implemented for ${t}. Override processNestedWrites() in your adapter.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]}}async handle(){this.validateTenantId();let e=await this.getObject(),{mainData:t,nestedData:o}=this.extractNestedData(e),r=t;r=this.injectTenantId(r);let n=await this.findExisting(r),i=!n;r=await this.before(r,i);let u=await this.upsert(r).catch(Q),l=u.data,p=this.getParentId(l),a={};if(Object.keys(o).length>0&&p!==null)for(let[d,m]of Object.entries(o)){if(m==null)continue;let f=this._meta.model.relations?.[d];if(!f)continue;let g;d$3(m)?g={create:m}:g=m;let j=await this.processNestedWrites(p,d,f,g);a[d]=j;}if(Object.keys(a).length>0)for(let[d,m]of Object.entries(a)){let f=this._meta.model.relations?.[d];f&&(f.type==="hasMany"?l[d]=[...m.created,...m.updated]:l[d]=m.created[0]||m.updated[0]||null);}if(this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(l,u.created))):l=await this.after(l,u.created),this.isAuditEnabled()&&p!==null){let d=this.getAuditLogger();this.runAfterResponse(d.logUpsert(this._meta.model.tableName,p,l,n,u.created,this.getAuditUserId()));}this._meta.model.computedFields&&(l=await j(l,this._meta.model.computedFields));let c=this._meta.model.serializer?this._meta.model.serializer(l):l;return this.json({success:true,result:c,created:u.created},u.created?201:200)}};var et=class extends S{maxBatchSize=100;stopOnError=true;beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){let e=this._meta.fields?this._meta.fields:D(this.getModelSchema(),Z(this._meta.model));return z.object({items:z.array(e).min(1).max(this.maxBatchSize)})}getSchema(){return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{201:{description:"Resources created successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({created:z.array(this.getModelSchema()),count:z.number()})})}}},207:{description:"Partial success (some items failed)",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({created:z.array(this.getModelSchema()),count:z.number(),errors:z.array(z.object({index:z.number(),error:z.string()})).optional()})})}}},400:{description:"Validation error",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getItems(){let{body:e}=await this.getValidatedData();return e?.items||[]}async before(e,t,o){return e}async after(e,t,o){return e}transform(e){return e}async handle(){let e=await this.getItems(),t=[],o=[];for(let a=0;a<e.length;a++)try{let c=await this.before(e[a],a);o.push(c);}catch(c){if(this.stopOnError)throw c;t.push({index:a,error:c instanceof Error?c.message:String(c)});}let r=await this.batchCreate(o).catch(Q),n=[];for(let a=0;a<r.length;a++)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(r[a],a))),n.push(r[a])):n.push(await this.after(r[a],a));}catch(c){if(this.stopOnError)throw c;t.push({index:a,error:c instanceof Error?c.message:String(c)}),n.push(r[a]);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),c=n.map(d=>{let m=this.getRecordId(d);return m===null?null:{recordId:m,record:d}}).filter(d=>d!==null);c.length>0&&this.runAfterResponse(a.logBatch("batch_create",this._meta.model.tableName,c,this.getAuditUserId()));}let u=(this._meta.model.serializer?n.map(a=>this._meta.model.serializer(a)):n).map(a=>this.transform(a)),l={success:true,result:{created:u,count:u.length,...t.length>0&&{errors:t}}},p=t.length>0?207:201;return this.json(l,p)}};var tt=class extends S{maxBatchSize=100;stopOnError=false;lookupField="id";allowedUpdateFields;blockedUpdateFields;beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){let e=this._meta.fields?this._meta.fields:D(this.getModelSchema(),Z(this._meta.model));return z.object({items:z.array(z.object({id:z.string(),data:e.partial()})).min(1).max(this.maxBatchSize)})}getSchema(){return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{200:{description:"Resources updated successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({updated:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional()})})}}},207:{description:"Partial success (some items failed or not found)",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({updated:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional(),errors:z.array(z.object({id:z.string(),error:z.string()})).optional()})})}}},400:{description:"Validation error",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getItems(){let{body:e}=await this.getValidatedData();return e?.items||[]}filterUpdateData(e){let t={...e};if(this.allowedUpdateFields){let o=new Set(this.allowedUpdateFields);t=Object.fromEntries(Object.entries(t).filter(([r])=>o.has(r)));}if(this.blockedUpdateFields)for(let o of this.blockedUpdateFields)delete t[o];for(let o of this._meta.model.primaryKeys)delete t[o];return t}async before(e,t,o){return t}async after(e,t){return e}async handle(){let e=await this.getItems(),t=[],o=[];for(let a of e)try{let c=this.filterUpdateData(a.data),d=await this.before(a.id,c);o.push({id:a.id,data:d});}catch(c){if(this.stopOnError)throw c;t.push({id:a.id,error:c instanceof Error?c.message:String(c)});}let{updated:r,notFound:n}=await this.batchUpdate(o),i=[];for(let a of r)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(a))),i.push(a)):i.push(await this.after(a));}catch(c){let d=String(a[this.lookupField]);if(this.stopOnError)throw c;t.push({id:d,error:c instanceof Error?c.message:String(c)}),i.push(a);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),c=i.map(d=>{let m=this.getRecordId(d);return m===null?null:{recordId:m,record:d}}).filter(d=>d!==null);c.length>0&&this.runAfterResponse(a.logBatch("batch_update",this._meta.model.tableName,c,this.getAuditUserId()));}let u=this._meta.model.serializer?i.map(a=>this._meta.model.serializer(a)):i,l={success:true,result:{updated:u,count:u.length,...n.length>0&&{notFound:n},...t.length>0&&{errors:t}}},p=t.length>0||n.length>0?207:200;return this.json(l,p)}};var ot=class extends S{maxBatchSize=100;stopOnError=false;lookupField="id";beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){return z.object({ids:z.array(z.string()).min(1).max(this.maxBatchSize)})}getSchema(){let e=this.isSoftDeleteEnabled();return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{200:{description:e?"Resources soft-deleted successfully":"Resources deleted successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({deleted:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional()})})}}},207:{description:"Partial success (some items failed or not found)",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({deleted:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional(),errors:z.array(z.object({id:z.string(),error:z.string()})).optional()})})}}},400:{description:"Validation error",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getIds(){let{body:e}=await this.getValidatedData();return e?.ids||[]}async before(e,t){}async after(e,t){return e}async handle(){let e=await this.getIds(),t=[],o=[];for(let a of e)try{await this.before(a),o.push(a);}catch(c){if(this.stopOnError)throw c;t.push({id:a,error:c instanceof Error?c.message:String(c)});}let{deleted:r,notFound:n}=await this.batchDelete(o),i=[];for(let a of r)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(a))),i.push(a)):i.push(await this.after(a));}catch(c){let d=String(a[this.lookupField]);if(this.stopOnError)throw c;t.push({id:d,error:c instanceof Error?c.message:String(c)}),i.push(a);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),c=i.map(d=>{let m=this.getRecordId(d);return m===null?null:{recordId:m,previousRecord:d}}).filter(d=>d!==null);c.length>0&&this.runAfterResponse(a.logBatch("batch_delete",this._meta.model.tableName,c,this.getAuditUserId()));}let u=this._meta.model.serializer?i.map(a=>this._meta.model.serializer(a)):i,l={success:true,result:{deleted:u,count:u.length,...n.length>0&&{notFound:n},...t.length>0&&{errors:t}}},p=t.length>0||n.length>0?207:200;return this.json(l,p)}};var rt=class extends S{maxBatchSize=100;stopOnError=false;lookupField="id";beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){return z.object({ids:z.array(z.string()).min(1).max(this.maxBatchSize)})}getSchema(){return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{200:{description:"Resources restored successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({restored:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional()})})}}},207:{description:"Partial success (some items failed or not found)",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({restored:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional(),errors:z.array(z.object({id:z.string(),error:z.string()})).optional()})})}}},400:{description:"Soft delete not enabled or validation error",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getIds(){let{body:e}=await this.getValidatedData();return e?.ids||[]}async before(e,t){}async after(e,t){return e}async handle(){if(!this.isSoftDeleteEnabled())throw new a$2("Soft delete is not enabled for this model",400,"SOFT_DELETE_NOT_ENABLED");let e=await this.getIds(),t=[],o=[];for(let a of e)try{await this.before(a),o.push(a);}catch(c){if(this.stopOnError)throw c;t.push({id:a,error:c instanceof Error?c.message:String(c)});}let{restored:r,notFound:n}=await this.batchRestore(o),i=[];for(let a of r)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(a))),i.push(a)):i.push(await this.after(a));}catch(c){let d=String(a[this.lookupField]);if(this.stopOnError)throw c;t.push({id:d,error:c instanceof Error?c.message:String(c)}),i.push(a);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),c=i.map(d=>{let m=this.getRecordId(d);return m===null?null:{recordId:m,record:d}}).filter(d=>d!==null);c.length>0&&this.runAfterResponse(a.logBatch("batch_restore",this._meta.model.tableName,c,this.getAuditUserId()));}let u=this._meta.model.serializer?i.map(a=>this._meta.model.serializer(a)):i,l={success:true,result:{restored:u,count:u.length,...n.length>0&&{notFound:n},...t.length>0&&{errors:t}}},p=t.length>0||n.length>0?207:200;return this.json(l,p)}};var nt=class extends S{upsertKeys;createOnlyFields;updateOnlyFields;maxBatchSize=100;continueOnError=false;useNativeUpsert=false;beforeHookMode="sequential";afterHookMode="sequential";getUpsertKeys(){return this.upsertKeys||this._meta.model.primaryKeys}getItemSchema(){if(this._meta.fields)return this._meta.fields;let e=this.getUpsertKeys(),t=Z(this._meta.model,{includePrimaryKeys:false});for(let n of this._meta.model.primaryKeys)e.includes(n)||t.push(n);let o=D(this.getModelSchema(),t),r={};for(let[n,i]of Object.entries(o.shape))e.includes(n)?r[n]=i:r[n]=i.optional();return z.object(r)}getBodySchema(){return z.array(this.getItemSchema()).max(this.maxBatchSize)}getSchema(){let e=z.object({data:this.getModelSchema(),created:z.boolean(),index:z.number()});return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}},required:true}},responses:{200:{description:"Batch upsert completed",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({items:z.array(e),createdCount:z.number(),updatedCount:z.number(),totalCount:z.number(),errors:z.array(z.object({index:z.number(),error:z.string()})).optional()})})}}},400:{description:"Validation error",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.unknown().optional()})})}}}}}}async getItems(){let{body:e}=await this.getValidatedData();return e}async beforeItem(e,t,o,r){return e}async afterItem(e,t,o,r){return e}async beforeBatch(e,t){return e}async afterBatch(e,t){return e}async upsertOne(e,t,o){let r=await this.findExisting(e,o),n=!r,i=await this.beforeItem(e,t,n,o),u;if(r){if(this.createOnlyFields)for(let l of this.createOnlyFields)delete i[l];u=await this.update(r,i,o);}else {if(this.updateOnlyFields)for(let l of this.updateOnlyFields)delete i[l];u=await this.create(i,o);}return u=await this.afterItem(u,t,n,o),{data:u,created:n,index:t}}async nativeBatchUpsert(e,t){return b$4().warn("Native batch upsert not implemented for this adapter. Falling back to item-by-item pattern."),this.performStandardBatchUpsert(e,t)}async performStandardBatchUpsert(e,t){let o=[],r=[],n=0,i=0;for(let l=0;l<e.length;l++)try{let p=await this.upsertOne(e[l],l,t);o.push(p),p.created?n++:i++;}catch(p){if(this.continueOnError)r.push({index:l,error:p instanceof Error?p.message:String(p)});else throw p}let u={items:o,createdCount:n,updatedCount:i,totalCount:o.length};return r.length>0&&(u.errors=r),u}async batchUpsert(e,t){return this.useNativeUpsert?this.nativeBatchUpsert(e,t):this.performStandardBatchUpsert(e,t)}async handle(){let e=await this.getItems();e=await this.beforeBatch(e);let t=await this.batchUpsert(e).catch(Q);if(t=await this.afterBatch(t),this._meta.model.computedFields&&(t.items=await Promise.all(t.items.map(async o=>({...o,data:await j(o.data,this._meta.model.computedFields)})))),this.isAuditEnabled()){let o=this.getAuditLogger(),r=t.items.map(n=>{let i=this.getRecordId(n.data);return i===null?null:{recordId:i,record:n.data}}).filter(n=>n!==null);r.length>0&&this.runAfterResponse(o.logBatch("batch_upsert",this._meta.model.tableName,r,this.getAuditUserId()));}return this._meta.model.serializer&&(t.items=t.items.map(o=>({...o,data:this._meta.model.serializer(o.data)}))),this.success(t)}};var dt=z.object({id:z.string(),recordId:z.union([z.string(),z.number()]),version:z.number(),data:z.record(z.string(),z.unknown()),createdAt:z.date(),changedBy:z.string().optional(),changeReason:z.string().optional(),changes:z.array(z.object({field:z.string(),oldValue:z.unknown().optional(),newValue:z.unknown().optional()})).optional()}),st=class extends S{lookupField="id";defaultLimit=20;maxLimit=100;getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getQuerySchema(){return z.object({limit:z.coerce.number().min(1).max(this.maxLimit).optional(),offset:z.coerce.number().min(0).optional()})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema(),query:this.getQuerySchema()},responses:{200:{description:"Version history retrieved successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({versions:z.array(dt),totalVersions:z.number()})})}}},400:{description:"Versioning not enabled",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}},404:{description:"Record not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getPaginationOptions(){let{query:e}=await this.getValidatedData();return {limit:e?.limit?Number(e.limit):this.defaultLimit,offset:e?.offset?Number(e.offset):0}}async recordExists(e){return true}async handle(){if(!this.isVersioningEnabled())throw new a$2("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),{limit:t,offset:o}=await this.getPaginationOptions();if(!await this.recordExists(e))throw new c$1(this._meta.model.tableName,e);let n=this.getVersionManager(),i=await n.getVersions(e,{limit:t,offset:o}),u=await n.getLatestVersion(e);return this.success({versions:i,totalVersions:u})}},it=class extends S{lookupField="id";getParamsSchema(){return z.object({[this.lookupField]:z.string(),version:z.coerce.number().min(1)})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema()},responses:{200:{description:"Version retrieved successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:dt})}}},400:{description:"Versioning not enabled",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}},404:{description:"Version not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getVersionNumber(){let{params:e}=await this.getValidatedData();return e?.version?Number(e.version):0}async handle(){if(!this.isVersioningEnabled())throw new a$2("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),t=await this.getVersionNumber(),r=await this.getVersionManager().getVersion(e,t);if(!r)throw new c$1(`version ${t}`,e);return this.success(r)}},at=class extends S{lookupField="id";getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getQuerySchema(){return z.object({from:z.coerce.number().min(1),to:z.coerce.number().min(1)})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema(),query:this.getQuerySchema()},responses:{200:{description:"Version comparison completed",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({from:z.number(),to:z.number(),changes:z.array(z.object({field:z.string(),oldValue:z.unknown().optional(),newValue:z.unknown().optional()}))})})}}},400:{description:"Versioning not enabled or invalid parameters",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}},404:{description:"Version not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getVersionNumbers(){let{query:e}=await this.getValidatedData();return {from:e?.from?Number(e.from):0,to:e?.to?Number(e.to):0}}async handle(){if(!this.isVersioningEnabled())throw new a$2("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),{from:t,to:o}=await this.getVersionNumbers(),n=await this.getVersionManager().compareVersions(e,t,o);return this.success({from:t,to:o,changes:n})}},lt=class extends S{lookupField="id";getParamsSchema(){return z.object({[this.lookupField]:z.string(),version:z.coerce.number().min(1)})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema()},responses:{200:{description:"Record rolled back successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:{description:"Versioning not enabled",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}},404:{description:"Version not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getVersionNumber(){let{params:e}=await this.getValidatedData();return e?.version?Number(e.version):0}async handle(){if(!this.isVersioningEnabled())throw new a$2("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),t=await this.getVersionNumber(),o=this.getVersionManager(),r=await o.getVersion(e,t);if(!r)throw new c$1(`version ${t}`,e);let i=await o.getLatestVersion(e)+1,u=await this.rollback(e,r.data,i),l=this._meta.model.serializer?this._meta.model.serializer(u):u;return this.success(l)}};var Ct={sumFields:[],avgFields:[],minMaxFields:[],countDistinctFields:[],groupByFields:[],defaultLimit:100,maxLimit:1e3},ct=class extends S{aggregateConfig={};maxGroupByFields=5;filterFields=[];getAggregateConfig(){return {...Ct,...this.aggregateConfig}}getQuerySchema(){return z.object({count:z.union([z.string(),z.array(z.string())]).optional(),sum:z.union([z.string(),z.array(z.string())]).optional(),avg:z.union([z.string(),z.array(z.string())]).optional(),min:z.union([z.string(),z.array(z.string())]).optional(),max:z.union([z.string(),z.array(z.string())]).optional(),countDistinct:z.union([z.string(),z.array(z.string())]).optional(),groupBy:z.string().optional(),orderBy:z.string().optional(),orderDirection:z.enum(["asc","desc"]).optional(),limit:z.coerce.number().optional(),offset:z.coerce.number().optional(),withDeleted:z.coerce.boolean().optional()}).passthrough()}getSchema(){let e=z.object({key:z.record(z.string(),z.unknown()),values:z.record(z.string(),z.number().nullable())});return {...this.schema,request:{query:this.getQuerySchema()},responses:{200:{description:"Aggregation result",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({values:z.record(z.string(),z.number().nullable()).optional(),groups:z.array(e).optional(),totalGroups:z.number().optional()})})}}},400:{description:"Invalid aggregation request",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.unknown().optional()})})}}}}}}async getAggregateOptions(){let{query:e}=await this.getValidatedData();return i$1(e||{})}validateAggregations(e){let t=this.getAggregateConfig();for(let o of e.aggregations)if(!(o.operation==="count"&&o.field==="*"))switch(o.operation){case "sum":if(t.sumFields.length>0&&!t.sumFields.includes(o.field))throw new Error(`Field '${o.field}' is not allowed for SUM aggregation`);break;case "avg":if(t.avgFields.length>0&&!t.avgFields.includes(o.field))throw new Error(`Field '${o.field}' is not allowed for AVG aggregation`);break;case "min":case "max":if(t.minMaxFields.length>0&&!t.minMaxFields.includes(o.field))throw new Error(`Field '${o.field}' is not allowed for MIN/MAX aggregation`);break;case "countDistinct":if(t.countDistinctFields.length>0&&!t.countDistinctFields.includes(o.field))throw new Error(`Field '${o.field}' is not allowed for COUNT DISTINCT aggregation`);break}if(e.groupBy){if(e.groupBy.length>this.maxGroupByFields)throw new b$3(`Maximum ${this.maxGroupByFields} GROUP BY fields allowed`);for(let o of e.groupBy)if(t.groupByFields.length>0&&!t.groupByFields.includes(o))throw new Error(`Field '${o}' is not allowed for GROUP BY`)}if(e.limit!==void 0&&e.limit>t.maxLimit)throw new Error(`Limit cannot exceed ${t.maxLimit}`)}getAggregateAlias(e){return e.alias?e.alias:e.field==="*"?e.operation:`${e.operation}${e.field.charAt(0).toUpperCase()}${e.field.slice(1)}`}async handle(){let e=await this.getAggregateOptions();e.aggregations.length===0&&e.aggregations.push({operation:"count",field:"*"}),this.validateAggregations(e);let t=this.getAggregateConfig();e.groupBy&&e.groupBy.length>0&&e.limit===void 0&&(e.limit=t.defaultLimit);let o=await this.aggregate(e);return this.success(o)}},vt={eq:(s,e)=>s===e,ne:(s,e)=>s!==e,gt:(s,e)=>s>e,gte:(s,e)=>s>=e,lt:(s,e)=>s<e,lte:(s,e)=>s<=e};function At(s,e){let t=s.get(e);if(t)return t;let o=[];return s.set(e,o),o}function zr(s,e){let{aggregations:t,groupBy:o,having:r,orderBy:n,orderDirection:i,limit:u,offset:l}=e;if(!o||o.length===0){let d={};for(let m of t){let f=pt(m);d[f]=ut(s,m);}return {values:d}}let p=new Map;for(let d of s){let f=o.map(g=>String(d[g]??"null")).join("|");At(p,f).push(d);}let a=[];for(let[d,m]of p){let f=d.split("|"),g={};o.forEach((x,k)=>{g[x]=f[k]==="null"?null:f[k];});let j={};for(let x of t){let k=pt(x);j[k]=ut(m,x);}a.push({key:g,values:j});}r&&(a=a.filter(d=>{for(let[m,f]of Object.entries(r)){let g=d.values[m];if(g!==null)for(let[j,x]of Object.entries(f)){let k=vt[j];if(k&&!k(g,Number(x)))return false}}return true}));let c=a.length;if(n){let d=i==="desc"?-1:1;a.sort((m,f)=>{if(n in m.values){let g=m.values[n]??0,j=f.values[n]??0;return (g-j)*d}if(n in m.key){let g=String(m.key[n]??""),j=String(f.key[n]??"");return g.localeCompare(j)*d}return 0});}if(l!==void 0||u!==void 0){let d=l||0,m=u?d+u:void 0;a=a.slice(d,m);}return {groups:a,totalGroups:c}}function Me(s,e){return s.map(t=>t[e]).filter(t=>typeof t=="number")}var _t={count:(s,e)=>e==="*"?s.length:s.filter(t=>t[e]!==null&&t[e]!==void 0).length,countDistinct:(s,e)=>new Set(s.map(o=>o[e]).filter(o=>o!=null).map(o=>String(o))).size,sum:(s,e)=>{let t=0;for(let o of s){let r=o[e];typeof r=="number"&&(t+=r);}return t},avg:(s,e)=>{let t=Me(s,e);return t.length===0?null:t.reduce((r,n)=>r+n,0)/t.length},min:(s,e)=>{let t=Me(s,e);return t.length===0?null:Math.min(...t)},max:(s,e)=>{let t=Me(s,e);return t.length===0?null:Math.max(...t)}};function ut(s,e){if(s.length===0)return e.operation==="count"?0:null;let t=_t[e.operation];return t?t(s,e.field):null}function pt(s){return s.alias?s.alias:s.field==="*"?s.operation:`${s.operation}${s.field.charAt(0).toUpperCase()}${s.field.slice(1)}`}var Tt=new Set(["a","an","and","are","as","at","be","by","for","from","has","he","in","is","it","its","of","on","or","that","the","to","was","were","will","with"]);function ht(s,e=true){if(!s||typeof s!="string")return [];let t=s.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter(Boolean);return e?t.filter(o=>!Tt.has(o)&&o.length>1):t}function gt(s,e){return e==="phrase"?[s.toLowerCase().trim()]:ht(s)}function Nt(s,e){return e.length===0?0:e.filter(o=>o===s||o.includes(s)).length/e.length}function ft(s,e,t,o){if(e.length===0)return {score:0,matchedFields:[]};let r=0,n=0,i=[];for(let[l,p]of Object.entries(t)){let a=s[l];if(a==null)continue;let c=p.weight??1;n+=c;let d;p.type==="array"&&Array.isArray(a)?d=a.join(" "):d=String(a);let m=ht(d,false),f=d.toLowerCase(),g=0,j=0;if(o==="phrase"){let x=e[0];f.includes(x)&&(g=1,j=1);}else {for(let x of e){let k=Nt(x,m);k>0?(j++,g+=k):f.includes(x)&&(j++,g+=.5/e.length);}e.length>0&&(g=g/e.length);}o==="all"&&j<e.length&&(g=0),g>0&&(i.push(l),r+=g*c);}return {score:n>0?Math.min(1,r/n):0,matchedFields:i}}function bt(s,e,t,o="mark",r=150){if(s==null)return [];let n;if(Array.isArray(s)?n=s.join(" "):n=String(s),!n||e.length===0)return [];let i=[],u=n.toLowerCase();if(t==="phrase"){let l=e[0],p=u.indexOf(l);if(p!==-1){let a=mt(n,p,l.length,r,o);a&&i.push(a);}}else {let l=[];for(let a of e){let c=0;for(;c<u.length;){let d=u.indexOf(a,c);if(d===-1)break;l.push({start:d,length:a.length}),c=d+1;}}l.sort((a,c)=>a.start-c.start);let p=new Set;for(let a of l){if(Array.from(p).some(m=>Math.abs(m-a.start)<r))continue;let d=mt(n,a.start,a.length,r,o);if(d&&(i.push(d),p.add(a.start)),i.length>=3)break}}return i}function mt(s,e,t,o,r){let n=Math.floor(o/2),i=Math.max(0,e-n),u=Math.min(s.length,e+t+n);if(i>0){let a=s.indexOf(" ",i);a!==-1&&a<e&&(i=a+1);}if(u<s.length){let a=s.lastIndexOf(" ",u);a!==-1&&a>e+t&&(u=a);}let l=s.slice(i,u);return i>0&&(l="..."+l),u<s.length&&(l=l+"..."),Vt(l,[s.slice(e,e+t)],r)}function Vt(s,e,t){let o=s,r=s.toLowerCase(),n=[...e].sort((i,u)=>u.length-i.length);for(let i of n){let u=i.toLowerCase(),l=0,p="",a=0;for(;a<r.length;){let c=r.indexOf(u,a);if(c===-1)break;p+=o.slice(l,c),p+=`<${t}>${o.slice(c,c+i.length)}</${t}>`,l=c+i.length,a=l;}p&&(p+=o.slice(l),o=p);}return o}function wt(s,e){if(!s)return Object.keys(e);let t=s.split(",").map(r=>r.trim()).filter(Boolean),o=Object.keys(e);return t.filter(r=>o.includes(r))}function yt(s,e){let t={};for(let o of s)t[o]={weight:e?.[o]??1};return t}function Zt(s){if(s instanceof z.ZodString)return true;let e=s;return e?e._def?.type==="string"||e._def?.typeName==="ZodString"||e.def?.type==="string":false}var Mt=class extends S{searchableFields={};searchFields=[];fieldWeights={};defaultMode="any";minQueryLength=2;maxQueryLength=500;highlightTag="mark";snippetLength=150;defaultMinScore=0;searchParamName="q";filterFields=[];filterConfig;sortFields=[];defaultSort;defaultPerPage=20;maxPerPage=100;allowedIncludes=[];fieldSelectionEnabled=false;allowedSelectFields=[];blockedSelectFields=[];alwaysIncludeFields=[];defaultSelectFields=[];getSearchableFields(){if(Object.keys(this.searchableFields).length>0)return this.searchableFields;if(this.searchFields.length>0)return yt(this.searchFields,this.fieldWeights);let e=this.getModelSchema().shape,t={};for(let[o,r]of Object.entries(e))Zt(r)&&(t[o]={weight:1});return t}getQuerySchema(){let t={[this.searchParamName||"q"]:z.string().min(this.minQueryLength).max(this.maxQueryLength).describe("Search query"),fields:z.string().optional().describe(`Comma-separated fields to search. Available: ${Object.keys(this.getSearchableFields()).join(", ")}`),mode:z.enum(["any","all","phrase"]).optional().describe("Search mode: any (OR), all (AND), phrase (exact)"),highlight:z.enum(["true","false"]).optional().describe("Include highlighted snippets"),minScore:z.string().optional().describe("Minimum relevance score threshold (0-1)"),page:z.string().optional(),per_page:z.string().optional()};this.sortFields.length>0&&(t.sort=z.enum(this.sortFields).optional().describe("Field to sort by"),t.order=z.enum(["asc","desc"]).optional().describe("Sort direction (asc or desc)"));for(let r of this.filterFields)t[r]=z.string().optional();if(this.filterConfig)for(let[r,n]of Object.entries(this.filterConfig)){for(let i of n)t[`${r}[${i}]`]=z.string().optional();t[r]=z.string().optional();}let o=this.getSoftDeleteConfig();if(o.enabled&&o.allowQueryDeleted&&(t[o.queryParam]=z.enum(["true","false"]).optional(),t.onlyDeleted=z.enum(["true","false"]).optional()),this.allowedIncludes.length>0&&(t.include=z.string().optional().describe(`Comma-separated list of relations to include. Allowed: ${this.allowedIncludes.join(", ")}`)),this.fieldSelectionEnabled){let r=this.getAvailableSelectFields();t.fields=z.string().optional().describe(`Comma-separated list of fields to return. Available: ${r.join(", ")}`);}return z.object(t)}getAvailableSelectFields(){let e=Object.keys(this.getModelSchema().shape),t=this._meta.model.computedFields?Object.keys(this._meta.model.computedFields):[],o=this._meta.model.relations?Object.keys(this._meta.model.relations):[],r=[...e,...t,...o];return this.allowedSelectFields.length>0&&(r=r.filter(n=>this.allowedSelectFields.includes(n))),this.blockedSelectFields.length>0&&(r=r.filter(n=>!this.blockedSelectFields.includes(n))),r}getSchema(){let e=z.object({item:this.getModelSchema(),score:z.number().min(0).max(1),highlights:z.record(z.string(),z.array(z.string())).optional(),matchedFields:z.array(z.string())});return {...this.schema,request:{query:this.getQuerySchema()},responses:{200:{description:"Search results",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.array(e),result_info:z.object({page:z.number(),per_page:z.number(),total_count:z.number().optional(),total_pages:z.number().optional(),query:z.string(),searchedFields:z.array(z.string())})})}}},400:{description:"Invalid search request",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.unknown().optional()})})}}}}}}async getSearchOptions(){let{query:e}=await this.getValidatedData(),t=this.searchParamName||"q",o=e?.[t],r$1=e?.fields,n=r(e?.mode),i=e?.highlight==="true",u=e?.minScore?Math.max(0,Math.min(1,parseFloat(e.minScore)||0)):this.defaultMinScore,l=this.getSearchableFields(),p=wt(r$1,l);return {query:o,fields:p.length>0?p:Object.keys(l),mode:n??this.defaultMode,highlight:i,minScore:u}}async getFilters(){let{query:e}=await this.getValidatedData(),t=this.getSoftDeleteConfig(),o={filterFields:this.filterFields,filterConfig:this.filterConfig,searchFields:[],searchFieldName:"q",sortFields:this.sortFields,defaultSort:this.defaultSort,defaultPerPage:this.defaultPerPage,maxPerPage:this.maxPerPage,softDeleteQueryParam:t.queryParam,allowedIncludes:this.allowedIncludes,fieldSelectionEnabled:this.fieldSelectionEnabled,allowedSelectFields:this.allowedSelectFields,blockedSelectFields:this.blockedSelectFields,alwaysIncludeFields:this.alwaysIncludeFields,defaultSelectFields:this.defaultSelectFields};return de(e||{},o)}async beforeSearch(e){return e}async afterSearch(e){return e}async handle(){let e=await this.getSearchOptions(),t=await this.getFilters();if(!e.query||e.query.length<this.minQueryLength)return this.json({success:false,error:{code:"INVALID_QUERY",message:`Search query must be at least ${this.minQueryLength} characters`}},400);e=await this.beforeSearch(e);let o=await this.search(e,t),r=await this.afterSearch(o.items);if(this._meta.model.computedFields){let a=r.map(d=>d.item),c=await k(a,this._meta.model.computedFields);r=r.map((d,m)=>({...d,item:c[m]}));}this._meta.model.serializer&&(r=r.map(a=>({...a,item:this._meta.model.serializer(a.item)})));let n=r;this.fieldSelectionEnabled&&t.options.fields&&t.options.fields.length>0&&(n=r.map(a=>({...a,item:ce([a.item],{fields:t.options.fields,isActive:true})[0]})));let i=o.postFilteredCount??o.totalCount,u=t.options.page||1,l=t.options.per_page||this.defaultPerPage,p=Math.ceil(i/l);return this.successPaginated(n,{page:u,per_page:l,total_count:i,total_pages:p,query:e.query,searchedFields:e.fields||Object.keys(this.getSearchableFields())})}};function Qr(s,e,t){let o=gt(e.query,e.mode),r={},n=e.fields||Object.keys(t);for(let u of n)t[u]&&(r[u]=t[u]);let i=[];for(let u of s){let{score:l,matchedFields:p}=ft(u,o,r,e.mode);if(l<e.minScore||p.length===0)continue;let a;if(e.highlight){a={};for(let c of p){let d=bt(u[c],o,e.mode);d.length>0&&(a[c]=d);}}i.push({item:u,score:l,highlights:a&&Object.keys(a).length>0?a:void 0,matchedFields:p});}return i.sort((u,l)=>l.score-u.score),i}function J(s,e={}){let{delimiter:t=",",nullValue:o="",dateFormat:r="iso"}=e;if(s==null)return o;if(s instanceof Date)switch(r){case "timestamp":return String(s.getTime());case "locale":return s.toLocaleString();default:return s.toISOString()}if(typeof s=="object")return J(JSON.stringify(s),e);if(typeof s=="boolean")return s?"true":"false";let n=String(s),i=n.charAt(0);return i==="="||i==="+"||i==="-"||i==="@"||i===" "||i==="\r"?`" ${n.replace(/"/g,'""')}"`:n.includes(t)||n.includes('"')||n.includes(`
2
2
  `)||n.includes("\r")?`"${n.replace(/"/g,'""')}"`:n}function je(s,e={}){let{delimiter:t=",",rowDelimiter:o=`\r
3
3
  `,includeHeader:r=true,formatters:n={},excludeFields:i=[],headerLabels:u={},nullValue:l="",dateFormat:p="iso"}=e;if(s.length===0)return "";let a=e.headers;a?a=a.filter(d=>!i.includes(d)):a=Object.keys(s[0]).filter(d=>!i.includes(d));let c=[];if(r){let d=a.map(m=>{let f=u[m]||m;return J(f,{delimiter:t,nullValue:l,dateFormat:p})});c.push(d.join(t));}for(let d of s){let m=a.map(f=>{let g=d[f];return n[f]&&(g=n[f](g)),J(g,{delimiter:t,nullValue:l,dateFormat:p})});c.push(m.join(t));}return c.join(o)}function Jr(s,e={}){let{delimiter:t=",",rowDelimiter:o=`\r
4
4
  `,includeHeader:r=true,formatters:n={},excludeFields:i=[],headerLabels:u={},nullValue:l="",dateFormat:p="iso"}=e,a=new TextEncoder,c=0,d=false,m=e.headers;return !m&&s.length>0?m=Object.keys(s[0]).filter(f=>!i.includes(f)):m?m=m.filter(f=>!i.includes(f)):m=[],new ReadableStream({pull(f){if(r&&!d&&m.length>0){let x=m.map(k=>{let y=u[k]||k;return J(y,{delimiter:t,nullValue:l,dateFormat:p})});f.enqueue(a.encode(x.join(t)+o)),d=true;return}let g=100,j=[];for(;c<s.length&&j.length<g;){let x=s[c],k=m.map(y=>{let F=x[y];return n[y]&&(F=n[y](F)),J(F,{delimiter:t,nullValue:l,dateFormat:p})});j.push(k.join(t)),c++;}j.length>0&&f.enqueue(a.encode(j.join(o)+o)),c>=s.length&&f.close();}})}function jt(s,e){let t=[],o="",r=false,n=0;for(;n<s.length;){let i=s[n];if(r){if(i==='"'){if(n+1<s.length&&s[n+1]==='"'){o+='"',n+=2;continue}r=false,n++;continue}o+=i,n++;}else {if(i==='"'){r=true,n++;continue}if(i===e){t.push(o),o="",n++;continue}o+=i,n++;}}return t.push(o),t}function Dt(s){let e=[],t="",o=false;for(let r=0;r<s.length;r++){let n=s[r];if(n==='"'){if(o&&r+1<s.length&&s[r+1]==='"'){t+='""',r++;continue}o=!o,t+=n;continue}if(!o&&(n===`
@@ -1 +1 @@
1
- import {t,u,v as v$1,w as w$1,x as x$1,z as z$1,B as B$1,C as C$1,D as D$1,E,F as F$1,T as T$1,U as U$1,ba,ca,A as A$1,G as G$1,H as H$1,I as I$1,J as J$1,K as K$1,L as L$1,y as y$1}from'./chunk-ZBCVLQ3W.js';var v,_;async function Ce(){if(v)return v;try{return v=(await import('pluralize')).default,v}catch{throw new Error('The "pluralize" package is required. Install it with: npm install pluralize')}}async function Fe(){if(_)return _;try{return _=(await import('fastest-levenshtein')).distance,_}catch{throw new Error('The "fastest-levenshtein" package is required. Install it with: npm install fastest-levenshtein')}}async function G(a){return (await Ce()).singular(a)}async function H(a,t){return (await Fe())(a,t)}function ke(a,t){return a[t]}function Ie(a){return typeof a=="object"&&a!==null&&"create"in a&&typeof a.create=="function"}function h(a,t){let e=ke(a,t);return Ie(e)?e:void 0}function X(a){if(typeof a.$transaction!="function")throw new Error("Prisma client does not support $transaction");return a.$transaction.bind(a)}function x(a){if(typeof a=="string"){if(/^-?\d+$/.test(a))return parseInt(a,10);if(/^-?\d+\.\d+$/.test(a))return parseFloat(a);if(a==="true")return true;if(a==="false")return false}return a}function Y(a){let t={};for(let e of a){let o=x(e.value);switch(e.operator){case "eq":t[e.field]=o;break;case "ne":t[e.field]={not:o};break;case "gt":t[e.field]={gt:o};break;case "gte":t[e.field]={gte:o};break;case "lt":t[e.field]={lt:o};break;case "lte":t[e.field]={lte:o};break;case "in":{let n=Array.isArray(e.value)?e.value:[e.value];t[e.field]={in:n.map(x)};break}case "nin":{let n=Array.isArray(e.value)?e.value:[e.value];t[e.field]={notIn:n.map(x)};break}case "like":t[e.field]={contains:String(e.value).replace(/%/g,"")};break;case "ilike":t[e.field]={contains:String(e.value).replace(/%/g,""),mode:"insensitive"};break;case "null":t[e.field]=e.value?null:{not:null};break;case "between":{let[n,s]=e.value;t[e.field]={gte:x(n),lte:x(s)};break}}}return t}var De=500,y=new Map;function Pe(a,t){if(y.size>=De){let e=y.keys().next().value;e!==void 0&&y.delete(e);}y.set(a,t);}var J=new Map;function xe(a,t){J.set(a.toLowerCase(),t),y.delete(a);}function Ae(a){for(let[t,e]of Object.entries(a))xe(t,e);}function Ke(){J.clear(),y.clear();}async function w(a){let t=y.get(a);if(t)return t;let e=J.get(a.toLowerCase());if(e)return Pe(a,e),e;let o=a.replace(/[-_](.)/g,(n,s)=>s.toUpperCase()).replace(/^./,n=>n.toLowerCase());return o=await G(o),Pe(a,o),o}function Ne(a){let t=[];for(let e of Object.keys(a)){if(e.startsWith("$")||e.startsWith("_"))continue;let o=ke(a,e);o&&typeof o=="object"&&"create"in o&&t.push(e);}return t}async function Ue(a,t,e=3){if(t.length===0)return [];let o=a.toLowerCase();return (await Promise.all(t.map(async s=>({name:s,distance:await H(o,s.toLowerCase())})))).filter(s=>s.distance<=Math.max(3,a.length/2)).sort((s,r)=>s.distance-r.distance).slice(0,e).map(s=>s.name)}async function M(a,t){let e=await w(t),o=h(a,e);if(!o){let n=Ne(a),s=await Ue(e,n),r=`Model '${e}' not found in Prisma client. Table name: '${t}'. `;throw s.length>0&&(r+=`Did you mean: ${s.map(i=>`'${i}'`).join(", ")}? `),n.length>0&&n.length<=10&&(r+=`Available models: ${n.join(", ")}. `),r+=`You can register a custom mapping with: registerPrismaModelMapping('${t}', 'yourModelName')`,new Error(r)}return o}async function Se(a,t,e,o){let n=await w(o.model),s=h(a,n);if(!s)return t;switch(o.type){case "hasOne":{let r=o.localKey||"id",i=t[r];if(i==null)return {...t,[e]:null};let l=await s.findFirst({where:{[o.foreignKey]:i}});return {...t,[e]:l||null}}case "hasMany":{let r=o.localKey||"id",i=t[r];if(i==null)return {...t,[e]:[]};let l=await s.findMany({where:{[o.foreignKey]:i}});return {...t,[e]:l}}case "belongsTo":{let r=t[o.foreignKey];if(r==null)return {...t,[e]:null};let i=o.localKey||"id",l=await s.findFirst({where:{[i]:r}});return {...t,[e]:l||null}}default:return t}}async function Oe(a,t,e,o){if(!o?.relations?.length||!e.model.relations)return t;let n={...t};for(let s of o.relations){let r=e.model.relations[s];r&&(n=await Se(a,n,s,r));}return n}async function O(a,t,e,o){if(!t.length||!o?.relations?.length||!e.model.relations)return t;let n=t.map(s=>({...s}));for(let s of o.relations){let r=e.model.relations[s];if(!r)continue;let i=await w(r.model),l=h(a,i);if(l)switch(r.type){case "hasOne":case "hasMany":{let c=r.localKey||"id",u=[...new Set(n.map(m=>m[c]).filter(m=>m!=null))];if(u.length===0){n=n.map(m=>({...m,[s]:r.type==="hasMany"?[]:null}));continue}let d=await l.findMany({where:{[r.foreignKey]:{in:u}}}),g=new Map;for(let m of d){let p=m[r.foreignKey];g.has(p)||g.set(p,[]),g.get(p).push(m);}n=n.map(m=>{let p=m[c],f=g.get(p)||[];return {...m,[s]:r.type==="hasMany"?f:f[0]||null}});break}case "belongsTo":{let c=r.localKey||"id",u=[...new Set(n.map(m=>m[r.foreignKey]).filter(m=>m!=null))];if(u.length===0){n=n.map(m=>({...m,[s]:null}));continue}let d=await l.findMany({where:{[c]:{in:u}}}),g=new Map;for(let m of d){let p=m[c];g.set(p,m);}n=n.map(m=>{let p=m[r.foreignKey];return {...m,[s]:g.get(p)||null}});break}}}return n}async function j(a){let{model:t,filters:e,searchFields:o=[],softDeleteConfig:n,defaultPerPage:s=20,additionalWhere:r={}}=a,i={...Y(e.filters),...r};if(n?.enabled){let{withDeleted:p,onlyDeleted:f}=e.options;f?i[n.field]={not:null}:p||(i[n.field]=null);}if(e.options.search&&o.length>0){let p=o.map(f=>({[f]:{contains:e.options.search,mode:"insensitive"}}));i={...i,OR:p};}let l=await t.count({where:i}),c;e.options.order_by&&(c={[e.options.order_by]:e.options.order_by_direction||"asc"});let u=e.options.page||1,d=e.options.per_page||s,g=await t.findMany({where:i,orderBy:c,skip:(u-1)*d,take:d}),m=Math.ceil(l/d);return {records:g,where:i,totalCount:l,page:u,perPage:d,totalPages:m}}function C(a,t){return {result:a,result_info:{page:t.page,per_page:t.perPage,total_count:t.totalCount,total_pages:t.totalPages,has_next_page:t.page<t.totalPages,has_prev_page:t.page>1}}}var F=class extends t{useTransaction=false;async getModel(){return M(this.prisma,this._meta.model.tableName)}async create(t){let e=await this.getModel(),o=this.applyManagedInsertFields(t,"prisma");return await e.create({data:o})}},I=class extends u{async getModel(){return M(this.prisma,this._meta.model.tableName)}async read(t,e,o){let n=await this.getModel(),s={[this.lookupField]:t,...e},r=await n.findFirst({where:s});return r?await Oe(this.prisma,r,this._meta,o):null}},D=class extends v$1{useTransaction=false;async getModel(){return M(this.prisma,this._meta.model.tableName)}async update(t,e,o){let n=await this.getModel(),s={[this.lookupField]:t,...o},r=await n.findFirst({where:s});if(!r)return null;let i=this._meta.model.primaryKeys[0];return await n.update({where:{[i]:r[i]},data:this.applyManagedUpdateFields(e)})}},A=class extends w$1{useTransaction=false;async getModel(){return M(this.prisma,this._meta.model.tableName)}async findForDelete(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),s={[this.lookupField]:t,...e};return n.enabled&&(s[n.field]=null),await o.findFirst({where:s})}async delete(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),s={[this.lookupField]:t,...e};n.enabled&&(s[n.field]=null);let r=await o.findFirst({where:s});if(!r)return null;let i=this._meta.model.primaryKeys[0],l=r[i];return n.enabled?await o.update({where:{[i]:l},data:{[n.field]:new Date}}):await o.delete({where:{[i]:l}})}},K=class extends x$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}async list(t){let e=await j({model:await this.getModel(),filters:t,searchFields:this.searchFields,softDeleteConfig:this.getSoftDeleteConfig(),defaultPerPage:this.defaultPerPage}),o={relations:t.options.include||[]},n=await O(this.prisma,e.records,this._meta,o);return C(n,e)}};var N=class extends z$1{useTransaction=false;async getModel(){return M(this.prisma,this._meta.model.tableName)}async restore(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),s={[this.lookupField]:t,[n.field]:{not:null},...e},r=await o.findFirst({where:s});if(!r)return null;let i=this._meta.model.primaryKeys[0];return await o.update({where:{[i]:r[i]},data:{[n.field]:null}})}},U=class extends B$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}async batchCreate(t){let e=t.map(n=>this.applyManagedInsertFields(n,"prisma")),o=[];return await X(this.prisma)(async n=>{let s=h(n,await w(this._meta.model.tableName));if(!s)throw new Error(`Model '${this._meta.model.tableName}' not found in Prisma transaction client`);for(let r of e){let i=await s.create({data:r});o.push(i);}}),o}},S=class extends C$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}async batchUpdate(t){let e=await this.getModel(),o=this.getSoftDeleteConfig(),n=this._meta.model.primaryKeys[0],s=[],r=[],i=t.map(d=>d.id),l={[this.lookupField]:{in:i}};o.enabled&&(l[o.field]=null);let c=await e.findMany({where:l}),u=new Map;for(let d of c){let g=d[this.lookupField];u.set(g,d);}for(let d of t){let g=u.get(d.id);if(!g){r.push(d.id);continue}let m=await e.update({where:{[n]:g[n]},data:this.applyManagedUpdateFields(d.data)});s.push(m);}return {updated:s,notFound:r}}},B=class extends D$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}async batchDelete(t){let e=await this.getModel(),o=this.getSoftDeleteConfig(),n=this._meta.model.primaryKeys[0],s=[],r=[],i={[this.lookupField]:{in:t}};o.enabled&&(i[o.field]=null);let l=await e.findMany({where:i}),c=new Map;for(let u of l){let d=u[this.lookupField];c.set(d,u);}for(let u of t)c.has(u)||r.push(u);for(let u of t){let d=c.get(u);if(d)if(o.enabled){let g=await e.update({where:{[n]:d[n]},data:{[o.field]:new Date}});s.push(g);}else {let g=await e.delete({where:{[n]:d[n]}});s.push(g);}}return {deleted:s,notFound:r}}},T=class extends E{async getModel(){return M(this.prisma,this._meta.model.tableName)}async batchRestore(t){let e=await this.getModel(),o=this.getSoftDeleteConfig(),n=this._meta.model.primaryKeys[0],s=[],r=[],i={[this.lookupField]:{in:t},[o.field]:{not:null}},l=await e.findMany({where:i}),c=new Map;for(let u of l){let d=u[this.lookupField];c.set(d,u);}for(let u of t){let d=c.get(u);if(!d){r.push(u);continue}let g=await e.update({where:{[n]:d[n]},data:{[o.field]:null}});s.push(g);}return {restored:s,notFound:r}}},$=class extends F$1{useTransaction=true;async getModel(){return M(this.prisma,this._meta.model.tableName)}async findExisting(t){let e=await this.getModel(),o=this.getUpsertKeys(),n={};for(let r of o){let i=t[r];i!==void 0&&(n[r]=i);}return Object.keys(n).length===0?null:await e.findFirst({where:n})||null}async create(t){let e=await this.getModel(),o=this.applyManagedInsertFields(t,"prisma");return await e.create({data:o})}async update(t,e){let o=await this.getModel(),n=this._meta.model.primaryKeys[0];return await o.update({where:{[n]:t[n]},data:this.applyManagedUpdateFields(e)})}async nativeBatchUpsert(t,e){if(t.length===0)return {items:[],createdCount:0,updatedCount:0,totalCount:0};let o=this.getUpsertKeys(),n=this._meta.model.primaryKeys[0],s=this.getTimestampsConfig(),r=async c=>{let u=h(c,await w(this._meta.model.tableName));if(!u)throw new Error(`Model '${this._meta.model.tableName}' not found in Prisma client`);let d=[],g=[];for(let m=0;m<t.length;m++){let p=t[m];try{let f={};for(let b of o){let R=p[b];R!==void 0&&(f[b]=R);}let k=this.applyManagedInsertFields(p,"prisma"),P={};for(let[b,R]of Object.entries(p))!o.includes(b)&&b!==n&&(this.createOnlyFields?.includes(b)||(P[b]=R));s.enabled&&(P[s.updatedAt]=Date.now());let je=await u.upsert({where:f,create:k,update:Object.keys(P).length>0?P:{}});d.push({data:je,created:!1,index:m});}catch(f){if(this.continueOnError)g.push({index:m,error:f instanceof Error?f.message:String(f)});else throw f}}return {results:d,errors:g}},i;this.useTransaction?i=await X(this.prisma)(r):i=await r(this.prisma);let l={items:i.results,createdCount:0,updatedCount:i.results.length,totalCount:i.results.length};return i.errors.length>0&&(l.errors=i.errors),l}};var L=class extends T$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}buildSearchWhere(t,e){let o=Y(e.filters),n=this.getSoftDeleteConfig();if(n.enabled){let{withDeleted:l,onlyDeleted:c}=e.options;c?o[n.field]={not:null}:l||(o[n.field]=null);}let s=this.getSearchableFields(),r=t.fields||Object.keys(s),i=(l,c)=>({[l]:{contains:c,mode:"insensitive"}});if(r.length>0)if(t.mode==="all"){let l=t.query.split(/\s+/).filter(c=>c.length>0);l.length>0&&(o={...o,AND:l.map(c=>({OR:r.map(u=>i(u,c))}))});}else o={...o,OR:r.map(l=>i(l,t.query))};return o}async search(t,e){let o=await this.getModel(),n=this.buildSearchWhere(t,e),s=await o.count({where:n}),r=e.options.order_by?{[e.options.order_by]:e.options.order_by_direction||"asc"}:void 0,i=e.options.page||1,l=e.options.per_page||this.defaultPerPage,c=await o.findMany({where:n,orderBy:r,skip:(i-1)*l,take:l}),u=t.mode==="all"?{...t,mode:"any"}:t,d=U$1(c,u,this.getSearchableFields()),g={relations:e.options.include||[]},m=d.map(k=>k.item),p=await O(this.prisma,m,this._meta,g);return {items:d.map((k,P)=>({...k,item:p[P]})),totalCount:s}}},W=class extends ba{async getModel(){return M(this.prisma,this._meta.model.tableName)}async list(t){let e=await j({model:await this.getModel(),filters:t,searchFields:this.searchFields,softDeleteConfig:this.getSoftDeleteConfig(),defaultPerPage:this.defaultPerPage}),o={relations:t.options.include||[]},n=await O(this.prisma,e.records,this._meta,o);return C(n,e)}},V=class extends ca{async getModel(){return M(this.prisma,this._meta.model.tableName)}async findExisting(t){let e=await this.getModel(),o=this.getUpsertKeys(),n={};for(let r of o){let i=t[r];i!==void 0&&(n[r]=i);}return Object.keys(n).length===0?null:await e.findFirst({where:n})||null}async create(t){let e=await this.getModel(),o=this.applyManagedInsertFields(t,"prisma");return await e.create({data:o})}async update(t,e){let o=await this.getModel(),n=this._meta.model.primaryKeys[0];return await o.update({where:{[n]:t[n]},data:this.applyManagedUpdateFields(e)})}},Q=class extends A$1{useTransaction=false;async getModel(){return M(this.prisma,this._meta.model.tableName)}async findExisting(t){let e=await this.getModel(),o=this.getUpsertKeys(),n={};for(let r of o){let i=t[r];i!==void 0&&(n[r]=i);}return Object.keys(n).length===0?null:await e.findFirst({where:n})||null}async create(t){let e=await this.getModel(),o=this.applyManagedInsertFields(t,"prisma");return await e.create({data:o})}async update(t,e){let o=await this.getModel(),n=this._meta.model.primaryKeys[0];return await o.update({where:{[n]:t[n]},data:this.applyManagedUpdateFields(e)})}async nativeUpsert(t,e){let o=await this.getModel(),n=this.getUpsertKeys(),s=this._meta.model.primaryKeys[0],r=this.getTimestampsConfig(),i={};for(let d of n){let g=t[d];g!==void 0&&(i[d]=g);}let l=this.applyManagedInsertFields(t,"prisma"),c={};for(let[d,g]of Object.entries(t))!n.includes(d)&&d!==s&&(this.createOnlyFields?.includes(d)||(c[d]=g));return r.enabled&&(c[r.updatedAt]=Date.now()),{data:await o.upsert({where:i,create:l,update:Object.keys(c).length>0?c:{}}),created:false}}},Re=class extends G$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}async recordExists(t){return await(await this.getModel()).count({where:{[this.lookupField]:t}})>0}},Ee=class extends H$1{},ve=class extends I$1{},_e=class extends J$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}async rollback(t,e,o){let n=await this.getModel(),s=this.getVersioningConfig().field,r=this._meta.model.primaryKeys[0],i=await n.findFirst({where:{[this.lookupField]:t}});if(!i)throw new Error(`Record not found: ${t}`);return await n.update({where:{[r]:i[r]},data:{...e,[s]:o}})}},z=class extends K$1{useNativeAggregation=true;async getModel(){return M(this.prisma,this._meta.model.tableName)}async buildAggregateWhere(t){let e={},o=this.getSoftDeleteConfig();if(o.enabled){let{query:n}=await this.getValidatedData();n?.withDeleted===true||n?.withDeleted==="true"||(e[o.field]=null);}if(t.filters)for(let[n,s]of Object.entries(t.filters))if(typeof s=="object"&&s!==null){let r={};for(let[i,l]of Object.entries(s))switch(i){case "eq":r.equals=l;break;case "ne":r.not=l;break;case "gt":r.gt=l;break;case "gte":r.gte=l;break;case "lt":r.lt=l;break;case "lte":r.lte=l;break;case "in":r.in=l;break;case "nin":r.notIn=l;break;default:r[i]=l;}e[n]=r;}else e[n]=s;return e}async aggregate(t){let e=await this.getModel(),o=await this.buildAggregateWhere(t);if(!this.useNativeAggregation||t.having){let n=await e.findMany({where:o});return L$1(n,t)}return t.groupBy?.length?this.aggregateWithGroupBy(e,o,t):this.aggregateSimple(e,o,t)}groupAggregationsByOperation(t){let e={sum:[],avg:[],min:[],max:[],count:[],countDistinct:[]};for(let o of t)switch(o.operation){case "sum":e.sum.push(o.field);break;case "avg":e.avg.push(o.field);break;case "min":e.min.push(o.field);break;case "max":e.max.push(o.field);break;case "count":e.count.push(o.field);break;case "countDistinct":e.countDistinct.push(o.field);break}return e}async aggregateSimple(t,e,o){let n={where:e},s={},r=this.groupAggregationsByOperation(o.aggregations);if(n._count=true,r.sum.length){n._sum={};for(let c of r.sum)n._sum[c]=true;}if(r.avg.length){n._avg={};for(let c of r.avg)n._avg[c]=true;}if(r.min.length){n._min={};for(let c of r.min)n._min[c]=true;}if(r.max.length){n._max={};for(let c of r.max)n._max[c]=true;}let i=await w(this._meta.model.tableName),l=h(this.prisma,i);if(!l)throw new Error(`Model '${i}' not found in Prisma client`);try{let c=await l.aggregate(n);if(c._count!==void 0&&(s.count=typeof c._count=="object"?c._count._all??0:c._count),c._sum&&r.sum.length)for(let u of r.sum){let d=u.charAt(0).toUpperCase()+u.slice(1);s[`sum${d}`]=c._sum[u]??0;}if(c._avg&&r.avg.length)for(let u of r.avg){let d=u.charAt(0).toUpperCase()+u.slice(1);s[`avg${d}`]=c._avg[u]??0;}if(c._min&&r.min.length)for(let u of r.min){let d=u.charAt(0).toUpperCase()+u.slice(1);s[`min${d}`]=c._min[u];}if(c._max&&r.max.length)for(let u of r.max){let d=u.charAt(0).toUpperCase()+u.slice(1);s[`max${d}`]=c._max[u];}return {values:s,groups:[]}}catch{let u=await t.findMany({where:e});return L$1(u,o)}}async aggregateWithGroupBy(t,e,o){let n={by:o.groupBy,where:e},s=this.groupAggregationsByOperation(o.aggregations);if(n._count=true,s.sum.length){n._sum={};for(let l of s.sum)n._sum[l]=true;}if(s.avg.length){n._avg={};for(let l of s.avg)n._avg[l]=true;}if(s.min.length){n._min={};for(let l of s.min)n._min[l]=true;}if(s.max.length){n._max={};for(let l of s.max)n._max[l]=true;}let r=await w(this._meta.model.tableName),i=h(this.prisma,r);if(!i)throw new Error(`Model '${r}' not found in Prisma client`);try{let c=(await i.groupBy(n)).map(d=>{let g={},m={};for(let p of o.groupBy)g[p]=d[p];if(m.count=typeof d._count=="object"?d._count._all??0:d._count??0,d._sum&&s.sum.length)for(let p of s.sum){let f=p.charAt(0).toUpperCase()+p.slice(1);m[`sum${f}`]=d._sum[p]??0;}if(d._avg&&s.avg.length)for(let p of s.avg){let f=p.charAt(0).toUpperCase()+p.slice(1);m[`avg${f}`]=d._avg[p]??0;}if(d._min&&s.min.length)for(let p of s.min){let f=p.charAt(0).toUpperCase()+p.slice(1);m[`min${f}`]=d._min[p];}if(d._max&&s.max.length)for(let p of s.max){let f=p.charAt(0).toUpperCase()+p.slice(1);m[`max${f}`]=d._max[p];}return {key:g,values:m}});return {values:{count:c.reduce((d,g)=>d+(g.values.count||0),0)},groups:c}}catch{let c=await t.findMany({where:e});return L$1(c,o)}}},q=class extends y$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}generateId(){return crypto.randomUUID()}async findSource(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),s={[this.lookupField]:t,...e};n.enabled&&(s[n.field]=null);let r=await o.findFirst({where:s});return r||null}async createClone(t){let e=await this.getModel(),o=this.applyManagedInsertFields(t,"prisma",()=>this.generateId());return await e.create({data:o})}};var ht={CreateEndpoint:F,ListEndpoint:K,ReadEndpoint:I,UpdateEndpoint:D,DeleteEndpoint:A,RestoreEndpoint:N,BatchCreateEndpoint:U,BatchUpdateEndpoint:S,BatchDeleteEndpoint:B,BatchRestoreEndpoint:T,BatchUpsertEndpoint:$,SearchEndpoint:L,AggregateEndpoint:z,ExportEndpoint:W,ImportEndpoint:V,UpsertEndpoint:Q,CloneEndpoint:q};export{xe as a,Ae as b,Ke as c,F as d,I as e,D as f,A as g,K as h,N as i,U as j,S as k,B as l,T as m,$ as n,L as o,W as p,V as q,Q as r,Re as s,Ee as t,ve as u,_e as v,z as w,q as x,ht as y};
1
+ import {t,u,v as v$1,w as w$1,x as x$1,z as z$1,B as B$1,C as C$1,D as D$1,E,F as F$1,T as T$1,U as U$1,ba,ca,A as A$1,G as G$1,H as H$1,I as I$1,J as J$1,K as K$1,L as L$1,y as y$1}from'./chunk-V4YEHNEZ.js';var v,_;async function Ce(){if(v)return v;try{return v=(await import('pluralize')).default,v}catch{throw new Error('The "pluralize" package is required. Install it with: npm install pluralize')}}async function Fe(){if(_)return _;try{return _=(await import('fastest-levenshtein')).distance,_}catch{throw new Error('The "fastest-levenshtein" package is required. Install it with: npm install fastest-levenshtein')}}async function G(a){return (await Ce()).singular(a)}async function H(a,t){return (await Fe())(a,t)}function ke(a,t){return a[t]}function Ie(a){return typeof a=="object"&&a!==null&&"create"in a&&typeof a.create=="function"}function h(a,t){let e=ke(a,t);return Ie(e)?e:void 0}function X(a){if(typeof a.$transaction!="function")throw new Error("Prisma client does not support $transaction");return a.$transaction.bind(a)}function x(a){if(typeof a=="string"){if(/^-?\d+$/.test(a))return parseInt(a,10);if(/^-?\d+\.\d+$/.test(a))return parseFloat(a);if(a==="true")return true;if(a==="false")return false}return a}function Y(a){let t={};for(let e of a){let o=x(e.value);switch(e.operator){case "eq":t[e.field]=o;break;case "ne":t[e.field]={not:o};break;case "gt":t[e.field]={gt:o};break;case "gte":t[e.field]={gte:o};break;case "lt":t[e.field]={lt:o};break;case "lte":t[e.field]={lte:o};break;case "in":{let n=Array.isArray(e.value)?e.value:[e.value];t[e.field]={in:n.map(x)};break}case "nin":{let n=Array.isArray(e.value)?e.value:[e.value];t[e.field]={notIn:n.map(x)};break}case "like":t[e.field]={contains:String(e.value).replace(/%/g,"")};break;case "ilike":t[e.field]={contains:String(e.value).replace(/%/g,""),mode:"insensitive"};break;case "null":t[e.field]=e.value?null:{not:null};break;case "between":{let[n,s]=e.value;t[e.field]={gte:x(n),lte:x(s)};break}}}return t}var De=500,y=new Map;function Pe(a,t){if(y.size>=De){let e=y.keys().next().value;e!==void 0&&y.delete(e);}y.set(a,t);}var J=new Map;function xe(a,t){J.set(a.toLowerCase(),t),y.delete(a);}function Ae(a){for(let[t,e]of Object.entries(a))xe(t,e);}function Ke(){J.clear(),y.clear();}async function w(a){let t=y.get(a);if(t)return t;let e=J.get(a.toLowerCase());if(e)return Pe(a,e),e;let o=a.replace(/[-_](.)/g,(n,s)=>s.toUpperCase()).replace(/^./,n=>n.toLowerCase());return o=await G(o),Pe(a,o),o}function Ne(a){let t=[];for(let e of Object.keys(a)){if(e.startsWith("$")||e.startsWith("_"))continue;let o=ke(a,e);o&&typeof o=="object"&&"create"in o&&t.push(e);}return t}async function Ue(a,t,e=3){if(t.length===0)return [];let o=a.toLowerCase();return (await Promise.all(t.map(async s=>({name:s,distance:await H(o,s.toLowerCase())})))).filter(s=>s.distance<=Math.max(3,a.length/2)).sort((s,r)=>s.distance-r.distance).slice(0,e).map(s=>s.name)}async function M(a,t){let e=await w(t),o=h(a,e);if(!o){let n=Ne(a),s=await Ue(e,n),r=`Model '${e}' not found in Prisma client. Table name: '${t}'. `;throw s.length>0&&(r+=`Did you mean: ${s.map(i=>`'${i}'`).join(", ")}? `),n.length>0&&n.length<=10&&(r+=`Available models: ${n.join(", ")}. `),r+=`You can register a custom mapping with: registerPrismaModelMapping('${t}', 'yourModelName')`,new Error(r)}return o}async function Se(a,t,e,o){let n=await w(o.model),s=h(a,n);if(!s)return t;switch(o.type){case "hasOne":{let r=o.localKey||"id",i=t[r];if(i==null)return {...t,[e]:null};let l=await s.findFirst({where:{[o.foreignKey]:i}});return {...t,[e]:l||null}}case "hasMany":{let r=o.localKey||"id",i=t[r];if(i==null)return {...t,[e]:[]};let l=await s.findMany({where:{[o.foreignKey]:i}});return {...t,[e]:l}}case "belongsTo":{let r=t[o.foreignKey];if(r==null)return {...t,[e]:null};let i=o.localKey||"id",l=await s.findFirst({where:{[i]:r}});return {...t,[e]:l||null}}default:return t}}async function Oe(a,t,e,o){if(!o?.relations?.length||!e.model.relations)return t;let n={...t};for(let s of o.relations){let r=e.model.relations[s];r&&(n=await Se(a,n,s,r));}return n}async function O(a,t,e,o){if(!t.length||!o?.relations?.length||!e.model.relations)return t;let n=t.map(s=>({...s}));for(let s of o.relations){let r=e.model.relations[s];if(!r)continue;let i=await w(r.model),l=h(a,i);if(l)switch(r.type){case "hasOne":case "hasMany":{let c=r.localKey||"id",u=[...new Set(n.map(m=>m[c]).filter(m=>m!=null))];if(u.length===0){n=n.map(m=>({...m,[s]:r.type==="hasMany"?[]:null}));continue}let d=await l.findMany({where:{[r.foreignKey]:{in:u}}}),g=new Map;for(let m of d){let p=m[r.foreignKey];g.has(p)||g.set(p,[]),g.get(p).push(m);}n=n.map(m=>{let p=m[c],f=g.get(p)||[];return {...m,[s]:r.type==="hasMany"?f:f[0]||null}});break}case "belongsTo":{let c=r.localKey||"id",u=[...new Set(n.map(m=>m[r.foreignKey]).filter(m=>m!=null))];if(u.length===0){n=n.map(m=>({...m,[s]:null}));continue}let d=await l.findMany({where:{[c]:{in:u}}}),g=new Map;for(let m of d){let p=m[c];g.set(p,m);}n=n.map(m=>{let p=m[r.foreignKey];return {...m,[s]:g.get(p)||null}});break}}}return n}async function j(a){let{model:t,filters:e,searchFields:o=[],softDeleteConfig:n,defaultPerPage:s=20,additionalWhere:r={}}=a,i={...Y(e.filters),...r};if(n?.enabled){let{withDeleted:p,onlyDeleted:f}=e.options;f?i[n.field]={not:null}:p||(i[n.field]=null);}if(e.options.search&&o.length>0){let p=o.map(f=>({[f]:{contains:e.options.search,mode:"insensitive"}}));i={...i,OR:p};}let l=await t.count({where:i}),c;e.options.order_by&&(c={[e.options.order_by]:e.options.order_by_direction||"asc"});let u=e.options.page||1,d=e.options.per_page||s,g=await t.findMany({where:i,orderBy:c,skip:(u-1)*d,take:d}),m=Math.ceil(l/d);return {records:g,where:i,totalCount:l,page:u,perPage:d,totalPages:m}}function C(a,t){return {result:a,result_info:{page:t.page,per_page:t.perPage,total_count:t.totalCount,total_pages:t.totalPages,has_next_page:t.page<t.totalPages,has_prev_page:t.page>1}}}var F=class extends t{useTransaction=false;async getModel(){return M(this.prisma,this._meta.model.tableName)}async create(t){let e=await this.getModel(),o=this.applyManagedInsertFields(t,"prisma");return await e.create({data:o})}},I=class extends u{async getModel(){return M(this.prisma,this._meta.model.tableName)}async read(t,e,o){let n=await this.getModel(),s={[this.lookupField]:t,...e},r=await n.findFirst({where:s});return r?await Oe(this.prisma,r,this._meta,o):null}},D=class extends v$1{useTransaction=false;async getModel(){return M(this.prisma,this._meta.model.tableName)}async update(t,e,o){let n=await this.getModel(),s={[this.lookupField]:t,...o},r=await n.findFirst({where:s});if(!r)return null;let i=this._meta.model.primaryKeys[0];return await n.update({where:{[i]:r[i]},data:this.applyManagedUpdateFields(e)})}},A=class extends w$1{useTransaction=false;async getModel(){return M(this.prisma,this._meta.model.tableName)}async findForDelete(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),s={[this.lookupField]:t,...e};return n.enabled&&(s[n.field]=null),await o.findFirst({where:s})}async delete(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),s={[this.lookupField]:t,...e};n.enabled&&(s[n.field]=null);let r=await o.findFirst({where:s});if(!r)return null;let i=this._meta.model.primaryKeys[0],l=r[i];return n.enabled?await o.update({where:{[i]:l},data:{[n.field]:new Date}}):await o.delete({where:{[i]:l}})}},K=class extends x$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}async list(t){let e=await j({model:await this.getModel(),filters:t,searchFields:this.searchFields,softDeleteConfig:this.getSoftDeleteConfig(),defaultPerPage:this.defaultPerPage}),o={relations:t.options.include||[]},n=await O(this.prisma,e.records,this._meta,o);return C(n,e)}};var N=class extends z$1{useTransaction=false;async getModel(){return M(this.prisma,this._meta.model.tableName)}async restore(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),s={[this.lookupField]:t,[n.field]:{not:null},...e},r=await o.findFirst({where:s});if(!r)return null;let i=this._meta.model.primaryKeys[0];return await o.update({where:{[i]:r[i]},data:{[n.field]:null}})}},U=class extends B$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}async batchCreate(t){let e=t.map(n=>this.applyManagedInsertFields(n,"prisma")),o=[];return await X(this.prisma)(async n=>{let s=h(n,await w(this._meta.model.tableName));if(!s)throw new Error(`Model '${this._meta.model.tableName}' not found in Prisma transaction client`);for(let r of e){let i=await s.create({data:r});o.push(i);}}),o}},S=class extends C$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}async batchUpdate(t){let e=await this.getModel(),o=this.getSoftDeleteConfig(),n=this._meta.model.primaryKeys[0],s=[],r=[],i=t.map(d=>d.id),l={[this.lookupField]:{in:i}};o.enabled&&(l[o.field]=null);let c=await e.findMany({where:l}),u=new Map;for(let d of c){let g=d[this.lookupField];u.set(g,d);}for(let d of t){let g=u.get(d.id);if(!g){r.push(d.id);continue}let m=await e.update({where:{[n]:g[n]},data:this.applyManagedUpdateFields(d.data)});s.push(m);}return {updated:s,notFound:r}}},B=class extends D$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}async batchDelete(t){let e=await this.getModel(),o=this.getSoftDeleteConfig(),n=this._meta.model.primaryKeys[0],s=[],r=[],i={[this.lookupField]:{in:t}};o.enabled&&(i[o.field]=null);let l=await e.findMany({where:i}),c=new Map;for(let u of l){let d=u[this.lookupField];c.set(d,u);}for(let u of t)c.has(u)||r.push(u);for(let u of t){let d=c.get(u);if(d)if(o.enabled){let g=await e.update({where:{[n]:d[n]},data:{[o.field]:new Date}});s.push(g);}else {let g=await e.delete({where:{[n]:d[n]}});s.push(g);}}return {deleted:s,notFound:r}}},T=class extends E{async getModel(){return M(this.prisma,this._meta.model.tableName)}async batchRestore(t){let e=await this.getModel(),o=this.getSoftDeleteConfig(),n=this._meta.model.primaryKeys[0],s=[],r=[],i={[this.lookupField]:{in:t},[o.field]:{not:null}},l=await e.findMany({where:i}),c=new Map;for(let u of l){let d=u[this.lookupField];c.set(d,u);}for(let u of t){let d=c.get(u);if(!d){r.push(u);continue}let g=await e.update({where:{[n]:d[n]},data:{[o.field]:null}});s.push(g);}return {restored:s,notFound:r}}},$=class extends F$1{useTransaction=true;async getModel(){return M(this.prisma,this._meta.model.tableName)}async findExisting(t){let e=await this.getModel(),o=this.getUpsertKeys(),n={};for(let r of o){let i=t[r];i!==void 0&&(n[r]=i);}return Object.keys(n).length===0?null:await e.findFirst({where:n})||null}async create(t){let e=await this.getModel(),o=this.applyManagedInsertFields(t,"prisma");return await e.create({data:o})}async update(t,e){let o=await this.getModel(),n=this._meta.model.primaryKeys[0];return await o.update({where:{[n]:t[n]},data:this.applyManagedUpdateFields(e)})}async nativeBatchUpsert(t,e){if(t.length===0)return {items:[],createdCount:0,updatedCount:0,totalCount:0};let o=this.getUpsertKeys(),n=this._meta.model.primaryKeys[0],s=this.getTimestampsConfig(),r=async c=>{let u=h(c,await w(this._meta.model.tableName));if(!u)throw new Error(`Model '${this._meta.model.tableName}' not found in Prisma client`);let d=[],g=[];for(let m=0;m<t.length;m++){let p=t[m];try{let f={};for(let b of o){let R=p[b];R!==void 0&&(f[b]=R);}let k=this.applyManagedInsertFields(p,"prisma"),P={};for(let[b,R]of Object.entries(p))!o.includes(b)&&b!==n&&(this.createOnlyFields?.includes(b)||(P[b]=R));s.enabled&&(P[s.updatedAt]=Date.now());let je=await u.upsert({where:f,create:k,update:Object.keys(P).length>0?P:{}});d.push({data:je,created:!1,index:m});}catch(f){if(this.continueOnError)g.push({index:m,error:f instanceof Error?f.message:String(f)});else throw f}}return {results:d,errors:g}},i;this.useTransaction?i=await X(this.prisma)(r):i=await r(this.prisma);let l={items:i.results,createdCount:0,updatedCount:i.results.length,totalCount:i.results.length};return i.errors.length>0&&(l.errors=i.errors),l}};var L=class extends T$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}buildSearchWhere(t,e){let o=Y(e.filters),n=this.getSoftDeleteConfig();if(n.enabled){let{withDeleted:l,onlyDeleted:c}=e.options;c?o[n.field]={not:null}:l||(o[n.field]=null);}let s=this.getSearchableFields(),r=t.fields||Object.keys(s),i=(l,c)=>({[l]:{contains:c,mode:"insensitive"}});if(r.length>0)if(t.mode==="all"){let l=t.query.split(/\s+/).filter(c=>c.length>0);l.length>0&&(o={...o,AND:l.map(c=>({OR:r.map(u=>i(u,c))}))});}else o={...o,OR:r.map(l=>i(l,t.query))};return o}async search(t,e){let o=await this.getModel(),n=this.buildSearchWhere(t,e),s=await o.count({where:n}),r=e.options.order_by?{[e.options.order_by]:e.options.order_by_direction||"asc"}:void 0,i=e.options.page||1,l=e.options.per_page||this.defaultPerPage,c=await o.findMany({where:n,orderBy:r,skip:(i-1)*l,take:l}),u=t.mode==="all"?{...t,mode:"any"}:t,d=U$1(c,u,this.getSearchableFields()),g={relations:e.options.include||[]},m=d.map(k=>k.item),p=await O(this.prisma,m,this._meta,g);return {items:d.map((k,P)=>({...k,item:p[P]})),totalCount:s}}},W=class extends ba{async getModel(){return M(this.prisma,this._meta.model.tableName)}async list(t){let e=await j({model:await this.getModel(),filters:t,searchFields:this.searchFields,softDeleteConfig:this.getSoftDeleteConfig(),defaultPerPage:this.defaultPerPage}),o={relations:t.options.include||[]},n=await O(this.prisma,e.records,this._meta,o);return C(n,e)}},V=class extends ca{async getModel(){return M(this.prisma,this._meta.model.tableName)}async findExisting(t){let e=await this.getModel(),o=this.getUpsertKeys(),n={};for(let r of o){let i=t[r];i!==void 0&&(n[r]=i);}return Object.keys(n).length===0?null:await e.findFirst({where:n})||null}async create(t){let e=await this.getModel(),o=this.applyManagedInsertFields(t,"prisma");return await e.create({data:o})}async update(t,e){let o=await this.getModel(),n=this._meta.model.primaryKeys[0];return await o.update({where:{[n]:t[n]},data:this.applyManagedUpdateFields(e)})}},Q=class extends A$1{useTransaction=false;async getModel(){return M(this.prisma,this._meta.model.tableName)}async findExisting(t){let e=await this.getModel(),o=this.getUpsertKeys(),n={};for(let r of o){let i=t[r];i!==void 0&&(n[r]=i);}return Object.keys(n).length===0?null:await e.findFirst({where:n})||null}async create(t){let e=await this.getModel(),o=this.applyManagedInsertFields(t,"prisma");return await e.create({data:o})}async update(t,e){let o=await this.getModel(),n=this._meta.model.primaryKeys[0];return await o.update({where:{[n]:t[n]},data:this.applyManagedUpdateFields(e)})}async nativeUpsert(t,e){let o=await this.getModel(),n=this.getUpsertKeys(),s=this._meta.model.primaryKeys[0],r=this.getTimestampsConfig(),i={};for(let d of n){let g=t[d];g!==void 0&&(i[d]=g);}let l=this.applyManagedInsertFields(t,"prisma"),c={};for(let[d,g]of Object.entries(t))!n.includes(d)&&d!==s&&(this.createOnlyFields?.includes(d)||(c[d]=g));return r.enabled&&(c[r.updatedAt]=Date.now()),{data:await o.upsert({where:i,create:l,update:Object.keys(c).length>0?c:{}}),created:false}}},Re=class extends G$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}async recordExists(t){return await(await this.getModel()).count({where:{[this.lookupField]:t}})>0}},Ee=class extends H$1{},ve=class extends I$1{},_e=class extends J$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}async rollback(t,e,o){let n=await this.getModel(),s=this.getVersioningConfig().field,r=this._meta.model.primaryKeys[0],i=await n.findFirst({where:{[this.lookupField]:t}});if(!i)throw new Error(`Record not found: ${t}`);return await n.update({where:{[r]:i[r]},data:{...e,[s]:o}})}},z=class extends K$1{useNativeAggregation=true;async getModel(){return M(this.prisma,this._meta.model.tableName)}async buildAggregateWhere(t){let e={},o=this.getSoftDeleteConfig();if(o.enabled){let{query:n}=await this.getValidatedData();n?.withDeleted===true||n?.withDeleted==="true"||(e[o.field]=null);}if(t.filters)for(let[n,s]of Object.entries(t.filters))if(typeof s=="object"&&s!==null){let r={};for(let[i,l]of Object.entries(s))switch(i){case "eq":r.equals=l;break;case "ne":r.not=l;break;case "gt":r.gt=l;break;case "gte":r.gte=l;break;case "lt":r.lt=l;break;case "lte":r.lte=l;break;case "in":r.in=l;break;case "nin":r.notIn=l;break;default:r[i]=l;}e[n]=r;}else e[n]=s;return e}async aggregate(t){let e=await this.getModel(),o=await this.buildAggregateWhere(t);if(!this.useNativeAggregation||t.having){let n=await e.findMany({where:o});return L$1(n,t)}return t.groupBy?.length?this.aggregateWithGroupBy(e,o,t):this.aggregateSimple(e,o,t)}groupAggregationsByOperation(t){let e={sum:[],avg:[],min:[],max:[],count:[],countDistinct:[]};for(let o of t)switch(o.operation){case "sum":e.sum.push(o.field);break;case "avg":e.avg.push(o.field);break;case "min":e.min.push(o.field);break;case "max":e.max.push(o.field);break;case "count":e.count.push(o.field);break;case "countDistinct":e.countDistinct.push(o.field);break}return e}async aggregateSimple(t,e,o){let n={where:e},s={},r=this.groupAggregationsByOperation(o.aggregations);if(n._count=true,r.sum.length){n._sum={};for(let c of r.sum)n._sum[c]=true;}if(r.avg.length){n._avg={};for(let c of r.avg)n._avg[c]=true;}if(r.min.length){n._min={};for(let c of r.min)n._min[c]=true;}if(r.max.length){n._max={};for(let c of r.max)n._max[c]=true;}let i=await w(this._meta.model.tableName),l=h(this.prisma,i);if(!l)throw new Error(`Model '${i}' not found in Prisma client`);try{let c=await l.aggregate(n);if(c._count!==void 0&&(s.count=typeof c._count=="object"?c._count._all??0:c._count),c._sum&&r.sum.length)for(let u of r.sum){let d=u.charAt(0).toUpperCase()+u.slice(1);s[`sum${d}`]=c._sum[u]??0;}if(c._avg&&r.avg.length)for(let u of r.avg){let d=u.charAt(0).toUpperCase()+u.slice(1);s[`avg${d}`]=c._avg[u]??0;}if(c._min&&r.min.length)for(let u of r.min){let d=u.charAt(0).toUpperCase()+u.slice(1);s[`min${d}`]=c._min[u];}if(c._max&&r.max.length)for(let u of r.max){let d=u.charAt(0).toUpperCase()+u.slice(1);s[`max${d}`]=c._max[u];}return {values:s,groups:[]}}catch{let u=await t.findMany({where:e});return L$1(u,o)}}async aggregateWithGroupBy(t,e,o){let n={by:o.groupBy,where:e},s=this.groupAggregationsByOperation(o.aggregations);if(n._count=true,s.sum.length){n._sum={};for(let l of s.sum)n._sum[l]=true;}if(s.avg.length){n._avg={};for(let l of s.avg)n._avg[l]=true;}if(s.min.length){n._min={};for(let l of s.min)n._min[l]=true;}if(s.max.length){n._max={};for(let l of s.max)n._max[l]=true;}let r=await w(this._meta.model.tableName),i=h(this.prisma,r);if(!i)throw new Error(`Model '${r}' not found in Prisma client`);try{let c=(await i.groupBy(n)).map(d=>{let g={},m={};for(let p of o.groupBy)g[p]=d[p];if(m.count=typeof d._count=="object"?d._count._all??0:d._count??0,d._sum&&s.sum.length)for(let p of s.sum){let f=p.charAt(0).toUpperCase()+p.slice(1);m[`sum${f}`]=d._sum[p]??0;}if(d._avg&&s.avg.length)for(let p of s.avg){let f=p.charAt(0).toUpperCase()+p.slice(1);m[`avg${f}`]=d._avg[p]??0;}if(d._min&&s.min.length)for(let p of s.min){let f=p.charAt(0).toUpperCase()+p.slice(1);m[`min${f}`]=d._min[p];}if(d._max&&s.max.length)for(let p of s.max){let f=p.charAt(0).toUpperCase()+p.slice(1);m[`max${f}`]=d._max[p];}return {key:g,values:m}});return {values:{count:c.reduce((d,g)=>d+(g.values.count||0),0)},groups:c}}catch{let c=await t.findMany({where:e});return L$1(c,o)}}},q=class extends y$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}generateId(){return crypto.randomUUID()}async findSource(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),s={[this.lookupField]:t,...e};n.enabled&&(s[n.field]=null);let r=await o.findFirst({where:s});return r||null}async createClone(t){let e=await this.getModel(),o=this.applyManagedInsertFields(t,"prisma",()=>this.generateId());return await e.create({data:o})}};var ht={CreateEndpoint:F,ListEndpoint:K,ReadEndpoint:I,UpdateEndpoint:D,DeleteEndpoint:A,RestoreEndpoint:N,BatchCreateEndpoint:U,BatchUpdateEndpoint:S,BatchDeleteEndpoint:B,BatchRestoreEndpoint:T,BatchUpsertEndpoint:$,SearchEndpoint:L,AggregateEndpoint:z,ExportEndpoint:W,ImportEndpoint:V,UpsertEndpoint:Q,CloneEndpoint:q};export{xe as a,Ae as b,Ke as c,F as d,I as e,D as f,A as g,K as h,N as i,U as j,S as k,B as l,T as m,$ as n,L as o,W as p,V as q,Q as r,Re as s,Ee as t,ve as u,_e as v,z as w,q as x,ht as y};
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import {r,s,A as A$1,z as z$1,q as q$1,p,o,n,m,l,x,y as y$1,j as j$1,i,h,k,g}from'./chunk-BXWKFJXP.js';export{a as BulkPatchEndpoint}from'./chunk-BXWKFJXP.js';export{J as DrizzleAdapters}from'./chunk-DJOJGLOT.js';export{y as PrismaAdapters}from'./chunk-FOTF3T22.js';export{K as AggregateEndpoint,B as BatchCreateEndpoint,D as BatchDeleteEndpoint,E as BatchRestoreEndpoint,C as BatchUpdateEndpoint,F as BatchUpsertEndpoint,y as CloneEndpoint,t as CreateEndpoint,w as DeleteEndpoint,ba as ExportEndpoint,ca as ImportEndpoint,x as ListEndpoint,u as ReadEndpoint,z as RestoreEndpoint,T as SearchEndpoint,v as UpdateEndpoint,A as UpsertEndpoint,I as VersionCompareEndpoint,G as VersionHistoryEndpoint,H as VersionReadEndpoint,J as VersionRollbackEndpoint,r as applyFieldSelection,s as applyFieldSelectionToArray,c as applyManagedInsertFields,d as applyManagedUpdateFields,e as assertIdStrategySupported,S as buildSearchConfig,P as calculateScore,g as causeChain,L as computeAggregations,X as createCsvStream,aa as csvToJson,V as escapeCsvValue,W as generateCsv,j as generateETag,Q as generateHighlights,b as getManagedInputExclusions,p as getSchemaFields,a as getTimestampsConfig,_ as inferCsvContentType,$ as jsonToCsv,h as mapUniqueViolation,l as matchesIfMatch,k as matchesIfNoneMatch,Y as parseCsv,q as parseFieldSelection,n as parseFilterValue,o as parseListFilters,R as parseSearchFields,i as rethrowAsConstraintError,U as searchInMemory,f as stripManagedInsertFields,O as termFrequency,M as tokenize,N as tokenizeQuery,Z as validateCsvHeaders}from'./chunk-ZBCVLQ3W.js';export{a as createHealthEndpoints,b as createHealthHandler}from'./chunk-XH7DEPW2.js';export{a as MemoryIdempotencyStorage}from'./chunk-FXIMMYFV.js';export{a as MemoryLoggingStorage}from'./chunk-3UHTK7SB.js';export{a as multiTenant}from'./chunk-L4X7KFWN.js';export{c as KVRateLimitStorage,a as MemoryRateLimitStorage,b as RedisRateLimitStorage}from'./chunk-EWKQ6BPV.js';import'./chunk-BJTWQHEV.js';export{a as applyProfile,b as applyProfileToArray,e as createArraySerializer,d as createSerializer,c as resolveProfile}from'./chunk-SDNXN7M5.js';export{g as createAPIKeyStorageMiddleware,e as createAuditStorageMiddleware,d as createCacheStorageMiddleware,c as createLoggingStorageMiddleware,b as createRateLimitStorageMiddleware,a as createStorageMiddleware,f as createVersioningStorageMiddleware}from'./chunk-R3WESU6C.js';export{a as scalarUI,e as setupDocs,f as setupDocsIndex,d as setupReDoc,b as setupScalar,c as setupSwaggerUI}from'./chunk-SPICOFUM.js';export{a as apiVersion,b as getApiVersion,c as getApiVersionConfig,d as versionedResponse}from'./chunk-KKLMXJY4.js';export{o as AuthenticatedEndpoint,a as JWTClaimsSchema,j as createAPIKeyMiddleware,l as createAuthMiddleware,e as createJWTMiddleware,g as decodeJWT,i as defaultHashAPIKey,m as optionalAuth,b as parseJWTClaims,n as requireAuthentication,c as safeParseJWTClaims,k as validateAPIKey,h as validateAPIKeyEntry,d as validateJWTClaims,f as verifyJWT,p as withAuth}from'./chunk-7ZUZICKI.js';import {a as a$1,c}from'./chunk-XI7HT5ZM.js';export{e as MemoryApprovalStorage,b as OpenAPIRoute,f as POLICIES_CONTEXT_KEY,n as allOf,q as allowAll,o as anyOf,p as denyAll,c as isRouteClass,d as parseIso8601Duration,h as requireAllRoles,j as requireAnyPermission,t as requireApproval,k as requireAuth,r as requireAuthenticated,l as requireOwnership,m as requireOwnershipOrRole,i as requirePermissions,s as requirePolicy,g as requireRoles}from'./chunk-XI7HT5ZM.js';export{b as KVCacheStorage,a as RedisCacheStorage}from'./chunk-H3H65KZF.js';import {T}from'./chunk-UANCAA7V.js';export{C as MemoryCacheStorage,m as RateLimitExceededException,y as createInvalidationPattern,V as createLoggingMiddleware,v as createRateLimitMiddleware,z as createRelatedPatterns,p as extractAPIKey,f as extractClientIp,g as extractHeaders,n as extractIP,k as extractLoggingUserId,h as extractQuery,o as extractUserId,x as generateCacheKey,s as generateKey,l as generateRequestId,E as getCacheStorage,Q as getErrorMessage,S as getLoggingStorage,u as getRateLimitStorage,T as getRequestId,U as getRequestStartTime,j as isAllowedContentType,d as matchLoggingPath,q as matchPath,A as matchesPattern,B as parseCacheKey,c as redactHeaders,b as redactObject,w as resetRateLimit,M as resolveAPIKeyStorage,K as resolveAuditStorage,J as resolveCacheStorage,N as resolveIdempotencyStorage,I as resolveLoggingStorage,H as resolveRateLimitStorage,L as resolveVersioningStorage,D as setCacheStorage,R as setLoggingStorage,t as setRateLimitStorage,e as shouldExcludePath,a as shouldRedact,r as shouldSkipPath,O as toError,i as truncateBody,F as withCache,G as withCacheInvalidation,P as wrapError}from'./chunk-UANCAA7V.js';export{a as MemoryVersioningStorage,e as VersionManager,f as createVersionManager,d as getVersioningStorage,c as setVersioningStorage}from'./chunk-NGUMNUOP.js';export{c as getIdempotencyStorage,d as idempotency,b as setIdempotencyStorage}from'./chunk-GF2EC5G4.js';export{c as MemoryAPIKeyStorage,d as generateAPIKey,h as getAPIKeyStorage,e as hashAPIKey,f as isValidAPIKeyFormat,i as setAPIKeyStorage}from'./chunk-2M5BM4VD.js';import {a,b}from'./chunk-FC56WWPB.js';export{g as AggregationException,a as ApiException,h as CacheException,i as ConfigurationException,d as ConflictException,f as ForbiddenException,b as InputValidationException,c as NotFoundException,e as UnauthorizedException}from'./chunk-FC56WWPB.js';export{e as AuditLogger,a as MemoryAuditLogStorage,f as createAuditLogger,d as getAuditStorage,c as setAuditStorage}from'./chunk-FJCWFB5L.js';import {q as q$2}from'./chunk-KUFOENSK.js';export{q as RESPONSE_ENVELOPE_CONTEXT_KEY,j as applyComputedFields,k as applyComputedFieldsToArray,f as calculateChanges,b as decodeCursor,m as defineMeta,l as defineModel,a as encodeCursor,c as extractNestedData,p as extractTenantId,e as getAuditConfig,o as getMultiTenantConfig,n as getSoftDeleteConfig,g as getVersioningConfig,d as isDirectNestedData,h as parseAggregateField,i as parseAggregateQuery,r as parseSearchMode}from'./chunk-KUFOENSK.js';export{a as StorageRegistry,b as createNullableRegistry,c as createRegistryWithDefault}from'./chunk-GBQQ3YQX.js';import'./chunk-CCGZ5UPB.js';export{f as StaticKeyProvider,e as decryptFields,b as decryptValue,d as encryptFields,a as encryptValue,c as isEncryptedValue}from'./chunk-QRXEQTNE.js';export{a as registerWebhooks}from'./chunk-7DDNX2F2.js';import {d as d$1}from'./chunk-QXFY6NYI.js';export{a as CrudEventEmitter,b as getEventEmitter,d as resolveEventEmitter,c as setEventEmitter}from'./chunk-QXFY6NYI.js';import {b as b$1}from'./chunk-DMGP7QDL.js';export{b as getLogger,a as setLogger}from'./chunk-DMGP7QDL.js';export{e as getAuthType,b as getUser,a as getUserId,d as getUserPermissions,c as getUserRoles,j as hasAllPermissions,h as hasAllRoles,i as hasAnyRole,g as hasPermission,f as hasRole}from'./chunk-MDHMZPXK.js';import {b as b$2}from'./chunk-VJRDAVID.js';export{c as getContextRequestId,a as getContextVar,d as getTenantId,b as setContextVar}from'./chunk-VJRDAVID.js';import {OpenAPIHono,createRoute}from'@hono/zod-openapi';import {z,ZodError}from'zod';import {HTTPException}from'hono/http-exception';import {streamSSE}from'hono/streaming';var pe=new WeakMap;function V(o){return pe.get(o)}var P=class{app;options;routes=new Map;constructor(e,n={}){this.app=e,this.options={docs_url:"/docs",redoc_url:"/redoc",openapi_url:"/openapi.json",...n};}registerRoute(e,n,t,r=[]){let m=`${e.toUpperCase()} ${n}`,f=t,c=new f().getSchema();this.routes.set(m,{method:e,path:n,schema:c,routeClass:t});let i=createRoute({method:e,path:this.convertPath(n),...c,responses:c.responses||{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}});if(r.length>0)for(let u of r)this.app.use(n,async(a,s)=>{if(a.req.method.toLowerCase()===e)return u(a,s);await s();});this.app.openapi(i,async u=>{let a$2=new f;a$2.setContext(u);try{return await a$2.handle()}catch(s){if(s instanceof a){let p=s.toJSON(),g=u?.var?.[q$2];return g?a$1(u,g.error(p.error),s.status):a$1(u,p,s.status)}throw s}});}convertPath(e){return e.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,"{$1}")}setupDocs(e,n){let t=e??this.options.openapi_url??"/openapi.json";this.app.doc(t,{openapi:n.openapi||"3.1.0",info:n.info,servers:n.servers,security:n.security});}getApp(){return this.app}getRegisteredRoutes(){return this.routes}toOpenApiPath(e){return this.convertPath(e)}};function qr(o=new OpenAPIHono,e={}){let n="openAPIRegistry"in o?o:new OpenAPIHono,t=new P(n,e),r=["get","post","put","patch","delete","options","head"],m=new Proxy(n,{get(f,h){if(r.includes(h))return (i,...u)=>{let a=u[u.length-1];if(c(a)){let s=u.slice(0,-1);return t.registerRoute(h,i,a,s),m}return f[h](i,...u)};if(h==="doc")return (i,u)=>{t.setupDocs(i,u);};if(h==="use")return (...i)=>(f[h](...i),m);let c$1=f[h];return typeof c$1=="function"?c$1.bind(f):c$1}});return pe.set(m,t),m}var $r=6e4,Gr={openapi:"3.1.0",info:{title:"API",version:"1.0.0"}};async function Jr(o,e,n={}){let t=V(o);if(!t)throw new Error("buildPerTenantOpenApi: app was not produced by fromHono(...). Cannot find route registry.");let r=n.config??Gr,m=`openapi:${e.tenantId??"global"}:${r.info.version}`;if(n.cache){let i=await n.cache.get(m);if(i!=null)return i}let f=new OpenAPIHono;for(let i of t.getRegisteredRoutes().values()){let u=i.routeClass,a=new u,s=Yr(e);a.setContext(s),typeof a.resolveModelSchema=="function"&&await a.resolveModelSchema();let p=a.getSchema(),g=createRoute({...p,method:i.method,path:t.toOpenApiPath(i.path),responses:p.responses??{200:{description:"Success",content:{"application/json":{schema:z.unknown()}}}}});f.openapi(g,()=>new Response);}let h={openapi:r.openapi??"3.1.0",info:r.info,servers:r.servers,security:r.security},c=n.spec==="3.0"?f.getOpenAPIDocument(h):f.getOpenAPI31Document(h);return n.cache&&await n.cache.set(m,c,n.cacheTtlMs??$r),c}function Yr(o){let e={};o.tenantId!==void 0&&(e.tenantId=o.tenantId),o.organizationId!==void 0&&(e.organizationId=o.organizationId);let n=o.request??new Request("http://localhost/");return {var:e,env:o.env,req:{raw:n,header:()=>{},query:()=>{},param:()=>{}},set(t,r){e[t]=r;},get(t){return e[t]},executionCtx:void 0}}function Xr(o){return {async get(e){let n=await o.get(e);return n?n.data:void 0},async set(e,n,t){let r=t?Math.ceil(t/1e3):void 0;await o.set(e,n,r?{ttl:r}:void 0);}}}var oa=[["create","post",""],["list","get",""],["batchCreate","post","/batch"],["batchUpdate","patch","/batch"],["batchDelete","delete","/batch"],["batchRestore","post","/batch/restore"],["batchUpsert","post","/batch/upsert"],["search","get","/search"],["aggregate","get","/aggregate"],["export","get","/export"],["import","post","/import"],["upsert","post","/upsert"],["read","get","/:id"],["update","patch","/:id"],["delete","delete","/:id"],["restore","post","/:id/restore"],["clone","post","/:id/clone"]];function na(o){return o.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,"{$1}")}function ra(o,e){let t=`/${o}/${e}`.replace(/\/{2,}/g,"/");return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}function aa(o,e={}){let n=e.basePath??"",t=e.tag,r=new OpenAPIHono,m=0;for(let[c,i,u]of oa){let a=o[c];if(!a)continue;let p=new a().getSchema(),g=t!==void 0?{...p,tags:[t]}:p,M=ra(n,na(u)),w=createRoute({...g,method:i,path:M,responses:g.responses??{200:{description:"Success",content:{"application/json":{schema:z.unknown()}}}}});r.openapi(w,()=>new Response),m+=1;}return m===0?{}:r.getOpenAPI31Document({openapi:"3.1.0",info:{title:"hono-crud",version:"1.0.0"}}).paths??{}}var ce=o=>{if(o instanceof ZodError)return b.fromZodError(o)};function da(o={}){let{mappers:e=[],hooks:n=[],includeRequestId:t=true,includeStackTrace:r=false,defaultErrorCode:m="INTERNAL_ERROR",defaultErrorMessage:f="An internal error occurred",logUnmappedErrors:h=true,onHookError:c,responseEnvelope:i}=o,u=[...e,ce];return async(a$2,s)=>{let p,g=false;if(a$2 instanceof a)p=a$2,g=true;else if(a$2 instanceof HTTPException)p=new a(a$2.message,a$2.status,"HTTP_ERROR"),g=true;else {for(let l of u)try{let k=await l(a$2,s);if(k){p=k,g=!0;break}}catch{}g||(h&&b$1().error("Unmapped error",{error:a$2 instanceof Error?a$2.message:String(a$2)}),p=new a(f,500,m));}for(let l of n)try{let k=l(a$2,s,p);k instanceof Promise&&k.catch(B=>{c&&c(B,a$2,s);});}catch(k){c&&c(k,a$2,s);}let M=p.toJSON();if(t){let l=T(s);l&&(M.error.requestId=l);}r&&a$2.stack&&(M.error.stack=a$2.stack);let w=ue(s,i),C=w?w.error(M.error):M;return a$1(s,C,p.status)}}function ue(o,e){return o?.var?.[q$2]??e}var O=new Map,pa=["password","token","secret","apiKey","creditCard","ssn"];function I(o,e){if(o==null||typeof o!="object")return o;if(Array.isArray(o))return o.map(t=>I(t,e));let n={};for(let[t,r]of Object.entries(o))e.includes(t)||(n[t]=typeof r=="object"&&r!==null?I(r,e):r);return n}function ca(o){let{table:e,events:n,emitter:t,filter:r,heartbeatInterval:m=3e4,maxConnections:f=1e3,connectionTimeout:h=3e5,excludeFields:c=pa}=o;return i=>{let u=d$1(i,t);if(!u)return i.json({success:false,error:{code:"EVENT_EMITTER_NOT_CONFIGURED",message:"Event emitter not configured"}},500);let a=O.get(e)||0;return a>=f?i.json({success:false,error:{code:"TOO_MANY_CONNECTIONS",message:"Too many SSE connections"}},503):(O.set(e,a+1),streamSSE(i,async s=>{let p,g=async l=>{if(n&&n.length>0&&!n.includes(l.type)||r&&!r(l,i))return;let k=c.length>0?I(l.data,c):l.data,B=l.previousData&&c.length>0?I(l.previousData,c):l.previousData;try{await s.writeSSE({event:`${l.table}.${l.type}`,data:JSON.stringify({type:l.type,table:l.table,recordId:l.recordId,data:k,previousData:B,timestamp:l.timestamp}),id:`${l.table}-${l.recordId}-${Date.now()}`});}catch{}};p=u.onTable(e,g);let M=()=>{p.unsubscribe();let l=O.get(e)||1;l<=1?O.delete(e):O.set(e,l-1);};s.onAbort(()=>{M();});let w=Date.now(),C=w;for(;!s.closed;){await s.sleep(1e3);let l=Date.now();if(l-w>=h){s.abort();break}if(l-C>=m){C=l;try{await s.writeSSE({event:"heartbeat",data:JSON.stringify({timestamp:new Date().toISOString()})});}catch{break}}}}))}}function ua(o,e,n,t={}){let r=e.endsWith("/")?e.slice(0,-1):e,m=o,{middlewares:f=[],endpointMiddlewares:h={},responseEnvelope:c}=t,i=c?async(s,p)=>{b$2(s,q$2,c),await p();}:void 0,u=s=>{let p=n[s],g=p&&"_middlewares"in p?p._middlewares||[]:[];return [...i?[i]:[],...f,...h[s]||[],...g]},a=(s,p,g,M)=>{let w=u(g),C=m[s];w.length>0?C(p,...w,M):C(p,M);};n.create&&a("post",r,"create",n.create),n.list&&a("get",r,"list",n.list),n.batchCreate&&a("post",`${r}/batch`,"batchCreate",n.batchCreate),n.batchUpdate&&a("patch",`${r}/batch`,"batchUpdate",n.batchUpdate),n.batchDelete&&a("delete",`${r}/batch`,"batchDelete",n.batchDelete),n.batchRestore&&a("post",`${r}/batch/restore`,"batchRestore",n.batchRestore),n.batchUpsert&&a("post",`${r}/batch/upsert`,"batchUpsert",n.batchUpsert),n.search&&a("get",`${r}/search`,"search",n.search),n.aggregate&&a("get",`${r}/aggregate`,"aggregate",n.aggregate),n.export&&a("get",`${r}/export`,"export",n.export),n.import&&a("post",`${r}/import`,"import",n.import),n.upsert&&a("post",`${r}/upsert`,"upsert",n.upsert),n.read&&a("get",`${r}/:id`,"read",n.read),n.update&&a("patch",`${r}/:id`,"update",n.update),n.delete&&a("delete",`${r}/:id`,"delete",n.delete),n.restore&&a("post",`${r}/:id/restore`,"restore",n.restore),n.clone&&a("post",`${r}/:id/clone`,"clone",n.clone);}function q(o){return {content:{"application/json":{schema:o}}}}function ma(o){return {description:"Success",...q({type:"object",properties:{success:{type:"boolean",enum:[true]},result:o},required:["success","result"]})}}function fa(o="Error"){return {description:o,...q({type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"object",properties:{code:{type:"string"},message:{type:"string"},details:{}},required:["code","message"]}},required:["success","error"]})}}function Z(o,e){return {content:{"application/json":{schema:o}},description:e}}function ha(o,e){return {content:{"application/json":{schema:o}},description:e,required:true}}var me=z.object({code:z.string(),path:z.array(z.union([z.string(),z.number()])),message:z.string()}),v=z.object({success:z.literal(false),error:z.object({name:z.literal("ZodError"),issues:z.array(me)})});function ga(o){return v}function Ea(...o){return v}var Ma=(o,e)=>{if(!o.success)return e.json({success:false,error:{name:"ZodError",issues:o.error.issues}},422)};function wa(o,e=422){return (n,t)=>{if(!n.success)return t.json(o(n.error),e)}}var fe=z.object({success:z.literal(false),error:z.object({message:z.string(),code:z.string().optional()})});function y(o){return Z(fe,o)}var ka={badRequest:y("Bad request"),unauthorized:y("Unauthorized"),forbidden:y("Forbidden"),notFound:y("Resource not found"),conflict:y("Resource conflict"),validationError:Z(v,"Validation error"),internalError:y("Internal server error")};function Ca(o){return async(e,n)=>{o.cache&&e.set("cacheStorage",o.cache),o.rateLimit&&e.set("rateLimitStorage",o.rateLimit),o.audit&&e.set("auditStorage",o.audit),o.versioning&&e.set("versioningStorage",o.versioning),o.logging&&e.set("loggingStorage",o.logging),o.idempotency&&e.set("idempotencyStorage",o.idempotency),o.events&&e.set("eventEmitter",o.events),await n();}}function d(o,e){let n=e.middlewares??[],t=e.extras,r=e.schema??{},m=Array.isArray(r.tags)&&r.tags.length>0,f=e.meta.model.tag??e.meta.model.tableName,h=m?r:{...r,tags:[f]};return class extends o{static _middlewares=n;constructor(){super(),t&&Object.assign(this,t);}_meta=e.meta;schema=h;beforeHookMode=e.beforeHookMode??"sequential";afterHookMode=e.afterHookMode??"sequential";allowNestedCreate=e.allowNestedCreate??[];lookupField=e.lookupField??"id";additionalFilters=e.additionalFilters;allowedUpdateFields=e.allowedUpdateFields;blockedUpdateFields=e.blockedUpdateFields;allowNestedWrites=e.allowNestedWrites??[];includeCascadeResults=e.includeCascadeResults??false;filterFields=e.filterFields??[];filterConfig=e.filterConfig;searchFields=e.searchFields??[];searchFieldName=e.searchFieldName??"search";sortFields=e.sortFields??[];defaultSort=e.defaultSort;defaultPerPage=e.defaultPerPage??20;maxPerPage=e.maxPerPage??100;allowedIncludes=e.allowedIncludes??[];fieldSelectionEnabled=e.fieldSelectionEnabled??false;allowedSelectFields=e.allowedSelectFields??[];blockedSelectFields=e.blockedSelectFields??[];alwaysIncludeFields=e.alwaysIncludeFields??[];defaultSelectFields=e.defaultSelectFields??[];getBodySchema(){return e.bodySchema?e.bodySchema:super.getBodySchema()}async before(...i){return e.before?e.before(...i):super.before(...i)}async after(...i){return e.after?e.after(...i):super.after(...i)}transform(i){return e.transform?e.transform(i):super.transform(i)}}}function ba(o,e){return d(e,{meta:o.meta,schema:o.schema,middlewares:o.middlewares,before:o.before,after:o.after,beforeHookMode:o.beforeHookMode,afterHookMode:o.afterHookMode,allowNestedCreate:o.allowNestedCreate})}function xa(o,e){let n=o.defaultSort??(o.defaultOrderBy?{field:o.defaultOrderBy,order:o.defaultOrderDirection??"asc"}:void 0);return d(e,{meta:o.meta,schema:o.schema,middlewares:o.middlewares,after:o.after,transform:o.transform,filterFields:o.filterFields,filterConfig:o.filterConfig,searchFields:o.searchFields,searchFieldName:o.searchFieldName,sortFields:o.sortFields??o.orderByFields,defaultSort:n,defaultPerPage:o.defaultPerPage,maxPerPage:o.maxPerPage,allowedIncludes:o.allowedIncludes,fieldSelectionEnabled:o.fieldSelectionEnabled,allowedSelectFields:o.allowedSelectFields,blockedSelectFields:o.blockedSelectFields,alwaysIncludeFields:o.alwaysIncludeFields,defaultSelectFields:o.defaultSelectFields})}function ya(o,e){return d(e,{meta:o.meta,schema:o.schema,middlewares:o.middlewares,after:o.after,transform:o.transform,lookupField:o.lookupField,additionalFilters:o.additionalFilters,allowedIncludes:o.allowedIncludes,fieldSelectionEnabled:o.fieldSelectionEnabled,allowedSelectFields:o.allowedSelectFields,blockedSelectFields:o.blockedSelectFields,alwaysIncludeFields:o.alwaysIncludeFields,defaultSelectFields:o.defaultSelectFields})}function Sa(o,e){return d(e,{meta:o.meta,schema:o.schema,middlewares:o.middlewares,before:o.before,after:o.after,transform:o.transform,beforeHookMode:o.beforeHookMode,afterHookMode:o.afterHookMode,lookupField:o.lookupField,additionalFilters:o.additionalFilters,allowedUpdateFields:o.allowedUpdateFields,blockedUpdateFields:o.blockedUpdateFields,allowNestedWrites:o.allowNestedWrites})}function Oa(o,e){return d(e,{meta:o.meta,schema:o.schema,middlewares:o.middlewares,before:o.before,after:o.after,beforeHookMode:o.beforeHookMode,afterHookMode:o.afterHookMode,lookupField:o.lookupField,additionalFilters:o.additionalFilters,includeCascadeResults:o.includeCascadeResults})}var R=class{constructor(e){this.meta=e;}_schema={};_before;_after;_beforeHookMode="sequential";_afterHookMode="sequential";_allowNestedCreate=[];_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}before(e){return this._before=e,this}after(e){return this._after=e,this}beforeMode(e){return this._beforeHookMode=e,this}afterMode(e){return this._afterHookMode=e,this}nestedCreate(...e){return this._allowNestedCreate=e,this}build(e){return d(e,{meta:this.meta,schema:this._schema,before:this._before,after:this._after,beforeHookMode:this._beforeHookMode,afterHookMode:this._afterHookMode,allowNestedCreate:this._allowNestedCreate,middlewares:this._middlewares})}},A=class{constructor(e){this.meta=e;}_schema={};_filterFields=[];_filterConfig;_searchFields=[];_searchFieldName="search";_sortFields=[];_defaultSort;_defaultPerPage=20;_maxPerPage=100;_allowedIncludes=[];_fieldSelectionEnabled=false;_allowedSelectFields=[];_blockedSelectFields=[];_alwaysIncludeFields=[];_defaultSelectFields=[];_after;_transform;_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}filter(...e){return this._filterFields=e,this}filterWith(e){return this._filterConfig=e,this}search(...e){return this._searchFields=e,this}searchParam(e){return this._searchFieldName=e,this}sortable(...e){return this._sortFields=e,this}orderBy(...e){return this.sortable(...e)}defaultSort(e,n="asc"){return this._defaultSort={field:e,order:n},this}defaultOrder(e,n="asc"){return this.defaultSort(e,n)}pagination(e,n){return this._defaultPerPage=e,n!==void 0&&(this._maxPerPage=n),this}include(...e){return this._allowedIncludes=e,this}fieldSelection(e){return this._fieldSelectionEnabled=true,e?.allowed&&(this._allowedSelectFields=e.allowed),e?.blocked&&(this._blockedSelectFields=e.blocked),e?.alwaysInclude&&(this._alwaysIncludeFields=e.alwaysInclude),e?.defaults&&(this._defaultSelectFields=e.defaults),this}after(e){return this._after=e,this}transform(e){return this._transform=e,this}build(e){return d(e,{meta:this.meta,schema:this._schema,filterFields:this._filterFields,filterConfig:this._filterConfig,searchFields:this._searchFields,searchFieldName:this._searchFieldName,sortFields:this._sortFields,defaultSort:this._defaultSort,defaultPerPage:this._defaultPerPage,maxPerPage:this._maxPerPage,allowedIncludes:this._allowedIncludes,fieldSelectionEnabled:this._fieldSelectionEnabled,allowedSelectFields:this._allowedSelectFields,blockedSelectFields:this._blockedSelectFields,alwaysIncludeFields:this._alwaysIncludeFields,defaultSelectFields:this._defaultSelectFields,after:this._after,transform:this._transform,middlewares:this._middlewares})}},H=class{constructor(e){this.meta=e;}_schema={};_lookupField="id";_additionalFilters;_allowedIncludes=[];_fieldSelectionEnabled=false;_allowedSelectFields=[];_blockedSelectFields=[];_alwaysIncludeFields=[];_defaultSelectFields=[];_after;_transform;_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}lookupField(e){return this._lookupField=e,this}additionalFilters(...e){return this._additionalFilters=e,this}include(...e){return this._allowedIncludes=e,this}fieldSelection(e){return this._fieldSelectionEnabled=true,e?.allowed&&(this._allowedSelectFields=e.allowed),e?.blocked&&(this._blockedSelectFields=e.blocked),e?.alwaysInclude&&(this._alwaysIncludeFields=e.alwaysInclude),e?.defaults&&(this._defaultSelectFields=e.defaults),this}after(e){return this._after=e,this}transform(e){return this._transform=e,this}build(e){return d(e,{meta:this.meta,schema:this._schema,lookupField:this._lookupField,additionalFilters:this._additionalFilters,allowedIncludes:this._allowedIncludes,fieldSelectionEnabled:this._fieldSelectionEnabled,allowedSelectFields:this._allowedSelectFields,blockedSelectFields:this._blockedSelectFields,alwaysIncludeFields:this._alwaysIncludeFields,defaultSelectFields:this._defaultSelectFields,after:this._after,transform:this._transform,middlewares:this._middlewares})}},F=class{constructor(e){this.meta=e;}_schema={};_lookupField="id";_additionalFilters;_allowedUpdateFields;_blockedUpdateFields;_allowNestedWrites=[];_before;_after;_beforeHookMode="sequential";_afterHookMode="sequential";_transform;_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}lookupField(e){return this._lookupField=e,this}additionalFilters(...e){return this._additionalFilters=e,this}allowedFields(...e){return this._allowedUpdateFields=e,this}blockedFields(...e){return this._blockedUpdateFields=e,this}nestedWrites(...e){return this._allowNestedWrites=e,this}before(e){return this._before=e,this}after(e){return this._after=e,this}beforeMode(e){return this._beforeHookMode=e,this}afterMode(e){return this._afterHookMode=e,this}transform(e){return this._transform=e,this}build(e){return d(e,{meta:this.meta,schema:this._schema,lookupField:this._lookupField,additionalFilters:this._additionalFilters,allowedUpdateFields:this._allowedUpdateFields,blockedUpdateFields:this._blockedUpdateFields,allowNestedWrites:this._allowNestedWrites,before:this._before,after:this._after,beforeHookMode:this._beforeHookMode,afterHookMode:this._afterHookMode,transform:this._transform,middlewares:this._middlewares})}},_=class{constructor(e){this.meta=e;}_schema={};_lookupField="id";_additionalFilters;_includeCascadeResults=false;_before;_after;_beforeHookMode="sequential";_afterHookMode="sequential";_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}lookupField(e){return this._lookupField=e,this}additionalFilters(...e){return this._additionalFilters=e,this}includeCascade(e=true){return this._includeCascadeResults=e,this}before(e){return this._before=e,this}after(e){return this._after=e,this}beforeMode(e){return this._beforeHookMode=e,this}afterMode(e){return this._afterHookMode=e,this}build(e){return d(e,{meta:this.meta,schema:this._schema,lookupField:this._lookupField,additionalFilters:this._additionalFilters,includeCascadeResults:this._includeCascadeResults,before:this._before,after:this._after,beforeHookMode:this._beforeHookMode,afterHookMode:this._afterHookMode,middlewares:this._middlewares})}},j=class{constructor(e){this.meta=e;}create(){return new R(this.meta)}list(){return new A(this.meta)}read(){return new H(this.meta)}update(){return new F(this.meta)}delete(){return new _(this.meta)}};function Pa(o){return new j(o)}var Ia={CreateEndpoint:g,ListEndpoint:k,ReadEndpoint:h,UpdateEndpoint:i,DeleteEndpoint:j$1,SearchEndpoint:y$1,AggregateEndpoint:x,RestoreEndpoint:l,BatchCreateEndpoint:m,BatchUpdateEndpoint:n,BatchDeleteEndpoint:o,BatchRestoreEndpoint:p,BatchUpsertEndpoint:q$1,ExportEndpoint:z$1,ImportEndpoint:A$1,UpsertEndpoint:s,CloneEndpoint:r};function va(o,e){let n={};if(o.create!==void 0){let t=o.create;n.create=d(e.CreateEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,allowNestedCreate:t.nestedCreate,before:t.hooks?.before,after:t.hooks?.after});}if(o.list!==void 0){let t=o.list;n.list=d(e.ListEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,filterFields:t.filtering?.fields,filterConfig:t.filtering?.config,searchFields:t.search?.fields,searchFieldName:t.search?.paramName,sortFields:t.sorting?.fields,defaultSort:t.sorting?.default?{field:t.sorting.default,order:t.sorting.defaultOrder??t.sorting.defaultDirection??"asc"}:void 0,defaultPerPage:t.pagination?.defaultPerPage,maxPerPage:t.pagination?.maxPerPage,allowedIncludes:t.includes,fieldSelectionEnabled:t.fieldSelection?.enabled,allowedSelectFields:t.fieldSelection?.allowed,blockedSelectFields:t.fieldSelection?.blocked,alwaysIncludeFields:t.fieldSelection?.alwaysInclude,defaultSelectFields:t.fieldSelection?.defaults,after:t.hooks?.after,transform:t.hooks?.transform});}if(o.read!==void 0){let t=o.read;n.read=d(e.ReadEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,lookupField:t.lookupField,additionalFilters:t.additionalFilters,allowedIncludes:t.includes,fieldSelectionEnabled:t.fieldSelection?.enabled,allowedSelectFields:t.fieldSelection?.allowed,blockedSelectFields:t.fieldSelection?.blocked,alwaysIncludeFields:t.fieldSelection?.alwaysInclude,defaultSelectFields:t.fieldSelection?.defaults,after:t.hooks?.after,transform:t.hooks?.transform});}if(o.update!==void 0){let t=o.update;n.update=d(e.UpdateEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,lookupField:t.lookupField,additionalFilters:t.additionalFilters,allowedUpdateFields:t.fields?.allowed,blockedUpdateFields:t.fields?.blocked,allowNestedWrites:t.nestedWrites,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,transform:t.hooks?.transform});}if(o.delete!==void 0){let t=o.delete;n.delete=d(e.DeleteEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,lookupField:t.lookupField,additionalFilters:t.additionalFilters,includeCascadeResults:t.includeCascadeResults,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after});}if(o.search!==void 0&&e.SearchEndpoint){let t=o.search;n.search=d(e.SearchEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,after:t.hooks?.after,extras:{...t.fields!==void 0?{searchFields:t.fields}:{},...t.mode!==void 0?{defaultMode:t.mode}:{},...t.paramName!==void 0?{searchParamName:t.paramName}:{}}});}if(o.aggregate!==void 0&&e.AggregateEndpoint){let t=o.aggregate;n.aggregate=d(e.AggregateEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,after:t.hooks?.after,extras:{...t.fields!==void 0?{filterFields:t.fields}:{}}});}if(o.restore!==void 0&&e.RestoreEndpoint){let t=o.restore;n.restore=d(e.RestoreEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after});}if(o.batchCreate!==void 0&&e.BatchCreateEndpoint){let t=o.batchCreate;n.batchCreate=d(e.BatchCreateEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{}}});}if(o.batchUpdate!==void 0&&e.BatchUpdateEndpoint){let t=o.batchUpdate;n.batchUpdate=d(e.BatchUpdateEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{}}});}if(o.batchDelete!==void 0&&e.BatchDeleteEndpoint){let t=o.batchDelete;n.batchDelete=d(e.BatchDeleteEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{}}});}if(o.batchRestore!==void 0&&e.BatchRestoreEndpoint){let t=o.batchRestore;n.batchRestore=d(e.BatchRestoreEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{}}});}if(o.batchUpsert!==void 0&&e.BatchUpsertEndpoint){let t=o.batchUpsert,r=typeof t.conflictTarget=="string"?[t.conflictTarget]:t.conflictTarget;n.batchUpsert=d(e.BatchUpsertEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{},...r!==void 0?{upsertKeys:r}:{}}});}if(o.export!==void 0&&e.ExportEndpoint){let t=o.export;n.export=d(e.ExportEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,extras:{...t.maxRows!==void 0?{maxExportRecords:t.maxRows}:{},...t.formats!==void 0&&t.formats.length>0?{defaultFormat:t.formats[0]}:{}}});}if(o.import!==void 0&&e.ImportEndpoint){let t=o.import;n.import=d(e.ImportEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxRows!==void 0?{maxBatchSize:t.maxRows}:{}}});}if(o.upsert!==void 0&&e.UpsertEndpoint){let t=o.upsert,r=typeof t.conflictTarget=="string"?[t.conflictTarget]:t.conflictTarget;n.upsert=d(e.UpsertEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...r!==void 0?{upsertKeys:r}:{}}});}if(o.clone!==void 0&&e.CloneEndpoint){let t=o.clone;n.clone=d(e.CloneEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.fieldsToReset!==void 0?{excludeFromClone:t.fieldsToReset}:{}}});}return n}
1
+ export{J as DrizzleAdapters}from'./chunk-HRAGVQWS.js';import {r,s,A as A$1,z as z$1,q as q$1,p,o,n,m,l,x,y as y$1,j as j$1,i,h,k,g}from'./chunk-UU7V63VS.js';export{a as BulkPatchEndpoint}from'./chunk-UU7V63VS.js';export{y as PrismaAdapters}from'./chunk-ZAVXHUKP.js';export{K as AggregateEndpoint,B as BatchCreateEndpoint,D as BatchDeleteEndpoint,E as BatchRestoreEndpoint,C as BatchUpdateEndpoint,F as BatchUpsertEndpoint,y as CloneEndpoint,t as CreateEndpoint,w as DeleteEndpoint,ba as ExportEndpoint,ca as ImportEndpoint,x as ListEndpoint,u as ReadEndpoint,z as RestoreEndpoint,T as SearchEndpoint,v as UpdateEndpoint,A as UpsertEndpoint,I as VersionCompareEndpoint,G as VersionHistoryEndpoint,H as VersionReadEndpoint,J as VersionRollbackEndpoint,r as applyFieldSelection,s as applyFieldSelectionToArray,c as applyManagedInsertFields,d as applyManagedUpdateFields,e as assertIdStrategySupported,S as buildSearchConfig,P as calculateScore,g as causeChain,L as computeAggregations,X as createCsvStream,aa as csvToJson,V as escapeCsvValue,W as generateCsv,j as generateETag,Q as generateHighlights,b as getManagedInputExclusions,p as getSchemaFields,a as getTimestampsConfig,_ as inferCsvContentType,$ as jsonToCsv,h as mapUniqueViolation,l as matchesIfMatch,k as matchesIfNoneMatch,Y as parseCsv,q as parseFieldSelection,n as parseFilterValue,o as parseListFilters,R as parseSearchFields,i as rethrowAsConstraintError,U as searchInMemory,f as stripManagedInsertFields,O as termFrequency,M as tokenize,N as tokenizeQuery,Z as validateCsvHeaders}from'./chunk-V4YEHNEZ.js';export{a as createHealthEndpoints,b as createHealthHandler}from'./chunk-XH7DEPW2.js';export{a as MemoryIdempotencyStorage}from'./chunk-FXIMMYFV.js';export{a as MemoryLoggingStorage}from'./chunk-PCPU5A2Q.js';export{a as multiTenant}from'./chunk-L4X7KFWN.js';export{c as KVRateLimitStorage,a as MemoryRateLimitStorage,b as RedisRateLimitStorage}from'./chunk-EWKQ6BPV.js';import'./chunk-BJTWQHEV.js';export{a as applyProfile,b as applyProfileToArray,e as createArraySerializer,d as createSerializer,c as resolveProfile}from'./chunk-SDNXN7M5.js';export{g as createAPIKeyStorageMiddleware,e as createAuditStorageMiddleware,d as createCacheStorageMiddleware,c as createLoggingStorageMiddleware,b as createRateLimitStorageMiddleware,a as createStorageMiddleware,f as createVersioningStorageMiddleware}from'./chunk-R3WESU6C.js';export{a as scalarUI,e as setupDocs,f as setupDocsIndex,d as setupReDoc,b as setupScalar,c as setupSwaggerUI}from'./chunk-SPICOFUM.js';export{a as apiVersion,b as getApiVersion,c as getApiVersionConfig,d as versionedResponse}from'./chunk-KKLMXJY4.js';export{o as AuthenticatedEndpoint,a as JWTClaimsSchema,j as createAPIKeyMiddleware,l as createAuthMiddleware,e as createJWTMiddleware,g as decodeJWT,i as defaultHashAPIKey,m as optionalAuth,b as parseJWTClaims,n as requireAuthentication,c as safeParseJWTClaims,k as validateAPIKey,h as validateAPIKeyEntry,d as validateJWTClaims,f as verifyJWT,p as withAuth}from'./chunk-7ZUZICKI.js';import {a as a$1,c}from'./chunk-XI7HT5ZM.js';export{e as MemoryApprovalStorage,b as OpenAPIRoute,f as POLICIES_CONTEXT_KEY,n as allOf,q as allowAll,o as anyOf,p as denyAll,c as isRouteClass,d as parseIso8601Duration,h as requireAllRoles,j as requireAnyPermission,t as requireApproval,k as requireAuth,r as requireAuthenticated,l as requireOwnership,m as requireOwnershipOrRole,i as requirePermissions,s as requirePolicy,g as requireRoles}from'./chunk-XI7HT5ZM.js';export{b as KVCacheStorage,a as RedisCacheStorage}from'./chunk-H3H65KZF.js';import {T}from'./chunk-IPMPKM4J.js';export{C as MemoryCacheStorage,m as RateLimitExceededException,y as createInvalidationPattern,V as createLoggingMiddleware,v as createRateLimitMiddleware,z as createRelatedPatterns,p as extractAPIKey,f as extractClientIp,g as extractHeaders,n as extractIP,k as extractLoggingUserId,h as extractQuery,o as extractUserId,x as generateCacheKey,s as generateKey,l as generateRequestId,E as getCacheStorage,Q as getErrorMessage,S as getLoggingStorage,u as getRateLimitStorage,T as getRequestId,U as getRequestStartTime,j as isAllowedContentType,d as matchLoggingPath,q as matchPath,A as matchesPattern,B as parseCacheKey,c as redactHeaders,b as redactObject,w as resetRateLimit,M as resolveAPIKeyStorage,K as resolveAuditStorage,J as resolveCacheStorage,N as resolveIdempotencyStorage,I as resolveLoggingStorage,H as resolveRateLimitStorage,L as resolveVersioningStorage,D as setCacheStorage,R as setLoggingStorage,t as setRateLimitStorage,e as shouldExcludePath,a as shouldRedact,r as shouldSkipPath,O as toError,i as truncateBody,F as withCache,G as withCacheInvalidation,P as wrapError}from'./chunk-IPMPKM4J.js';export{a as MemoryVersioningStorage,e as VersionManager,f as createVersionManager,d as getVersioningStorage,c as setVersioningStorage}from'./chunk-NGUMNUOP.js';export{c as getIdempotencyStorage,d as idempotency,b as setIdempotencyStorage}from'./chunk-GF2EC5G4.js';export{e as AuditLogger,a as MemoryAuditLogStorage,f as createAuditLogger,d as getAuditStorage,c as setAuditStorage}from'./chunk-FJCWFB5L.js';export{c as MemoryAPIKeyStorage,d as generateAPIKey,h as getAPIKeyStorage,e as hashAPIKey,f as isValidAPIKeyFormat,i as setAPIKeyStorage}from'./chunk-2M5BM4VD.js';import {a,b}from'./chunk-FC56WWPB.js';export{g as AggregationException,a as ApiException,h as CacheException,i as ConfigurationException,d as ConflictException,f as ForbiddenException,b as InputValidationException,c as NotFoundException,e as UnauthorizedException}from'./chunk-FC56WWPB.js';import {q as q$2}from'./chunk-KUFOENSK.js';export{q as RESPONSE_ENVELOPE_CONTEXT_KEY,j as applyComputedFields,k as applyComputedFieldsToArray,f as calculateChanges,b as decodeCursor,m as defineMeta,l as defineModel,a as encodeCursor,c as extractNestedData,p as extractTenantId,e as getAuditConfig,o as getMultiTenantConfig,n as getSoftDeleteConfig,g as getVersioningConfig,d as isDirectNestedData,h as parseAggregateField,i as parseAggregateQuery,r as parseSearchMode}from'./chunk-KUFOENSK.js';export{a as StorageRegistry,b as createNullableRegistry,c as createRegistryWithDefault}from'./chunk-GBQQ3YQX.js';import'./chunk-CCGZ5UPB.js';export{f as StaticKeyProvider,e as decryptFields,b as decryptValue,d as encryptFields,a as encryptValue,c as isEncryptedValue}from'./chunk-QRXEQTNE.js';export{a as registerWebhooks}from'./chunk-7DDNX2F2.js';import {d as d$1}from'./chunk-QXFY6NYI.js';export{a as CrudEventEmitter,b as getEventEmitter,d as resolveEventEmitter,c as setEventEmitter}from'./chunk-QXFY6NYI.js';import {b as b$1}from'./chunk-DMGP7QDL.js';export{b as getLogger,a as setLogger}from'./chunk-DMGP7QDL.js';export{e as getAuthType,b as getUser,a as getUserId,d as getUserPermissions,c as getUserRoles,j as hasAllPermissions,h as hasAllRoles,i as hasAnyRole,g as hasPermission,f as hasRole}from'./chunk-MDHMZPXK.js';import {b as b$2}from'./chunk-VJRDAVID.js';export{c as getContextRequestId,a as getContextVar,d as getTenantId,b as setContextVar}from'./chunk-VJRDAVID.js';import {OpenAPIHono,createRoute}from'@hono/zod-openapi';import {z,ZodError}from'zod';import {HTTPException}from'hono/http-exception';import {streamSSE}from'hono/streaming';var pe=new WeakMap;function V(o){return pe.get(o)}var P=class{app;options;routes=new Map;constructor(e,n={}){this.app=e,this.options={docs_url:"/docs",redoc_url:"/redoc",openapi_url:"/openapi.json",...n};}registerRoute(e,n,t,r=[]){let m=`${e.toUpperCase()} ${n}`,f=t,c=new f().getSchema();this.routes.set(m,{method:e,path:n,schema:c,routeClass:t});let i=createRoute({method:e,path:this.convertPath(n),...c,responses:c.responses||{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}});if(r.length>0)for(let u of r)this.app.use(n,async(a,s)=>{if(a.req.method.toLowerCase()===e)return u(a,s);await s();});this.app.openapi(i,async u=>{let a$2=new f;a$2.setContext(u);try{return await a$2.handle()}catch(s){if(s instanceof a){let p=s.toJSON(),g=u?.var?.[q$2];return g?a$1(u,g.error(p.error),s.status):a$1(u,p,s.status)}throw s}});}convertPath(e){return e.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,"{$1}")}setupDocs(e,n){let t=e??this.options.openapi_url??"/openapi.json";this.app.doc(t,{openapi:n.openapi||"3.1.0",info:n.info,servers:n.servers,security:n.security});}getApp(){return this.app}getRegisteredRoutes(){return this.routes}toOpenApiPath(e){return this.convertPath(e)}};function qr(o=new OpenAPIHono,e={}){let n="openAPIRegistry"in o?o:new OpenAPIHono,t=new P(n,e),r=["get","post","put","patch","delete","options","head"],m=new Proxy(n,{get(f,h){if(r.includes(h))return (i,...u)=>{let a=u[u.length-1];if(c(a)){let s=u.slice(0,-1);return t.registerRoute(h,i,a,s),m}return f[h](i,...u)};if(h==="doc")return (i,u)=>{t.setupDocs(i,u);};if(h==="use")return (...i)=>(f[h](...i),m);let c$1=f[h];return typeof c$1=="function"?c$1.bind(f):c$1}});return pe.set(m,t),m}var $r=6e4,Gr={openapi:"3.1.0",info:{title:"API",version:"1.0.0"}};async function Jr(o,e,n={}){let t=V(o);if(!t)throw new Error("buildPerTenantOpenApi: app was not produced by fromHono(...). Cannot find route registry.");let r=n.config??Gr,m=`openapi:${e.tenantId??"global"}:${r.info.version}`;if(n.cache){let i=await n.cache.get(m);if(i!=null)return i}let f=new OpenAPIHono;for(let i of t.getRegisteredRoutes().values()){let u=i.routeClass,a=new u,s=Yr(e);a.setContext(s),typeof a.resolveModelSchema=="function"&&await a.resolveModelSchema();let p=a.getSchema(),g=createRoute({...p,method:i.method,path:t.toOpenApiPath(i.path),responses:p.responses??{200:{description:"Success",content:{"application/json":{schema:z.unknown()}}}}});f.openapi(g,()=>new Response);}let h={openapi:r.openapi??"3.1.0",info:r.info,servers:r.servers,security:r.security},c=n.spec==="3.0"?f.getOpenAPIDocument(h):f.getOpenAPI31Document(h);return n.cache&&await n.cache.set(m,c,n.cacheTtlMs??$r),c}function Yr(o){let e={};o.tenantId!==void 0&&(e.tenantId=o.tenantId),o.organizationId!==void 0&&(e.organizationId=o.organizationId);let n=o.request??new Request("http://localhost/");return {var:e,env:o.env,req:{raw:n,header:()=>{},query:()=>{},param:()=>{}},set(t,r){e[t]=r;},get(t){return e[t]},executionCtx:void 0}}function Xr(o){return {async get(e){let n=await o.get(e);return n?n.data:void 0},async set(e,n,t){let r=t?Math.ceil(t/1e3):void 0;await o.set(e,n,r?{ttl:r}:void 0);}}}var oa=[["create","post",""],["list","get",""],["batchCreate","post","/batch"],["batchUpdate","patch","/batch"],["batchDelete","delete","/batch"],["batchRestore","post","/batch/restore"],["batchUpsert","post","/batch/upsert"],["search","get","/search"],["aggregate","get","/aggregate"],["export","get","/export"],["import","post","/import"],["upsert","post","/upsert"],["read","get","/:id"],["update","patch","/:id"],["delete","delete","/:id"],["restore","post","/:id/restore"],["clone","post","/:id/clone"]];function na(o){return o.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,"{$1}")}function ra(o,e){let t=`/${o}/${e}`.replace(/\/{2,}/g,"/");return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}function aa(o,e={}){let n=e.basePath??"",t=e.tag,r=new OpenAPIHono,m=0;for(let[c,i,u]of oa){let a=o[c];if(!a)continue;let p=new a().getSchema(),g=t!==void 0?{...p,tags:[t]}:p,M=ra(n,na(u)),w=createRoute({...g,method:i,path:M,responses:g.responses??{200:{description:"Success",content:{"application/json":{schema:z.unknown()}}}}});r.openapi(w,()=>new Response),m+=1;}return m===0?{}:r.getOpenAPI31Document({openapi:"3.1.0",info:{title:"hono-crud",version:"1.0.0"}}).paths??{}}var ce=o=>{if(o instanceof ZodError)return b.fromZodError(o)};function da(o={}){let{mappers:e=[],hooks:n=[],includeRequestId:t=true,includeStackTrace:r=false,defaultErrorCode:m="INTERNAL_ERROR",defaultErrorMessage:f="An internal error occurred",logUnmappedErrors:h=true,onHookError:c,responseEnvelope:i}=o,u=[...e,ce];return async(a$2,s)=>{let p,g=false;if(a$2 instanceof a)p=a$2,g=true;else if(a$2 instanceof HTTPException)p=new a(a$2.message,a$2.status,"HTTP_ERROR"),g=true;else {for(let l of u)try{let k=await l(a$2,s);if(k){p=k,g=!0;break}}catch{}g||(h&&b$1().error("Unmapped error",{error:a$2 instanceof Error?a$2.message:String(a$2)}),p=new a(f,500,m));}for(let l of n)try{let k=l(a$2,s,p);k instanceof Promise&&k.catch(B=>{c&&c(B,a$2,s);});}catch(k){c&&c(k,a$2,s);}let M=p.toJSON();if(t){let l=T(s);l&&(M.error.requestId=l);}r&&a$2.stack&&(M.error.stack=a$2.stack);let w=ue(s,i),C=w?w.error(M.error):M;return a$1(s,C,p.status)}}function ue(o,e){return o?.var?.[q$2]??e}var O=new Map,pa=["password","token","secret","apiKey","creditCard","ssn"];function I(o,e){if(o==null||typeof o!="object")return o;if(Array.isArray(o))return o.map(t=>I(t,e));let n={};for(let[t,r]of Object.entries(o))e.includes(t)||(n[t]=typeof r=="object"&&r!==null?I(r,e):r);return n}function ca(o){let{table:e,events:n,emitter:t,filter:r,heartbeatInterval:m=3e4,maxConnections:f=1e3,connectionTimeout:h=3e5,excludeFields:c=pa}=o;return i=>{let u=d$1(i,t);if(!u)return i.json({success:false,error:{code:"EVENT_EMITTER_NOT_CONFIGURED",message:"Event emitter not configured"}},500);let a=O.get(e)||0;return a>=f?i.json({success:false,error:{code:"TOO_MANY_CONNECTIONS",message:"Too many SSE connections"}},503):(O.set(e,a+1),streamSSE(i,async s=>{let p,g=async l=>{if(n&&n.length>0&&!n.includes(l.type)||r&&!r(l,i))return;let k=c.length>0?I(l.data,c):l.data,B=l.previousData&&c.length>0?I(l.previousData,c):l.previousData;try{await s.writeSSE({event:`${l.table}.${l.type}`,data:JSON.stringify({type:l.type,table:l.table,recordId:l.recordId,data:k,previousData:B,timestamp:l.timestamp}),id:`${l.table}-${l.recordId}-${Date.now()}`});}catch{}};p=u.onTable(e,g);let M=()=>{p.unsubscribe();let l=O.get(e)||1;l<=1?O.delete(e):O.set(e,l-1);};s.onAbort(()=>{M();});let w=Date.now(),C=w;for(;!s.closed;){await s.sleep(1e3);let l=Date.now();if(l-w>=h){s.abort();break}if(l-C>=m){C=l;try{await s.writeSSE({event:"heartbeat",data:JSON.stringify({timestamp:new Date().toISOString()})});}catch{break}}}}))}}function ua(o,e,n,t={}){let r=e.endsWith("/")?e.slice(0,-1):e,m=o,{middlewares:f=[],endpointMiddlewares:h={},responseEnvelope:c}=t,i=c?async(s,p)=>{b$2(s,q$2,c),await p();}:void 0,u=s=>{let p=n[s],g=p&&"_middlewares"in p?p._middlewares||[]:[];return [...i?[i]:[],...f,...h[s]||[],...g]},a=(s,p,g,M)=>{let w=u(g),C=m[s];w.length>0?C(p,...w,M):C(p,M);};n.create&&a("post",r,"create",n.create),n.list&&a("get",r,"list",n.list),n.batchCreate&&a("post",`${r}/batch`,"batchCreate",n.batchCreate),n.batchUpdate&&a("patch",`${r}/batch`,"batchUpdate",n.batchUpdate),n.batchDelete&&a("delete",`${r}/batch`,"batchDelete",n.batchDelete),n.batchRestore&&a("post",`${r}/batch/restore`,"batchRestore",n.batchRestore),n.batchUpsert&&a("post",`${r}/batch/upsert`,"batchUpsert",n.batchUpsert),n.search&&a("get",`${r}/search`,"search",n.search),n.aggregate&&a("get",`${r}/aggregate`,"aggregate",n.aggregate),n.export&&a("get",`${r}/export`,"export",n.export),n.import&&a("post",`${r}/import`,"import",n.import),n.upsert&&a("post",`${r}/upsert`,"upsert",n.upsert),n.read&&a("get",`${r}/:id`,"read",n.read),n.update&&a("patch",`${r}/:id`,"update",n.update),n.delete&&a("delete",`${r}/:id`,"delete",n.delete),n.restore&&a("post",`${r}/:id/restore`,"restore",n.restore),n.clone&&a("post",`${r}/:id/clone`,"clone",n.clone);}function q(o){return {content:{"application/json":{schema:o}}}}function ma(o){return {description:"Success",...q({type:"object",properties:{success:{type:"boolean",enum:[true]},result:o},required:["success","result"]})}}function fa(o="Error"){return {description:o,...q({type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"object",properties:{code:{type:"string"},message:{type:"string"},details:{}},required:["code","message"]}},required:["success","error"]})}}function Z(o,e){return {content:{"application/json":{schema:o}},description:e}}function ha(o,e){return {content:{"application/json":{schema:o}},description:e,required:true}}var me=z.object({code:z.string(),path:z.array(z.union([z.string(),z.number()])),message:z.string()}),v=z.object({success:z.literal(false),error:z.object({name:z.literal("ZodError"),issues:z.array(me)})});function ga(o){return v}function Ea(...o){return v}var Ma=(o,e)=>{if(!o.success)return e.json({success:false,error:{name:"ZodError",issues:o.error.issues}},422)};function wa(o,e=422){return (n,t)=>{if(!n.success)return t.json(o(n.error),e)}}var fe=z.object({success:z.literal(false),error:z.object({message:z.string(),code:z.string().optional()})});function y(o){return Z(fe,o)}var ka={badRequest:y("Bad request"),unauthorized:y("Unauthorized"),forbidden:y("Forbidden"),notFound:y("Resource not found"),conflict:y("Resource conflict"),validationError:Z(v,"Validation error"),internalError:y("Internal server error")};function Ca(o){return async(e,n)=>{o.cache&&e.set("cacheStorage",o.cache),o.rateLimit&&e.set("rateLimitStorage",o.rateLimit),o.audit&&e.set("auditStorage",o.audit),o.versioning&&e.set("versioningStorage",o.versioning),o.logging&&e.set("loggingStorage",o.logging),o.idempotency&&e.set("idempotencyStorage",o.idempotency),o.events&&e.set("eventEmitter",o.events),await n();}}function d(o,e){let n=e.middlewares??[],t=e.extras,r=e.schema??{},m=Array.isArray(r.tags)&&r.tags.length>0,f=e.meta.model.tag??e.meta.model.tableName,h=m?r:{...r,tags:[f]};return class extends o{static _middlewares=n;constructor(){super(),t&&Object.assign(this,t);}_meta=e.meta;schema=h;beforeHookMode=e.beforeHookMode??"sequential";afterHookMode=e.afterHookMode??"sequential";allowNestedCreate=e.allowNestedCreate??[];lookupField=e.lookupField??"id";additionalFilters=e.additionalFilters;allowedUpdateFields=e.allowedUpdateFields;blockedUpdateFields=e.blockedUpdateFields;allowNestedWrites=e.allowNestedWrites??[];includeCascadeResults=e.includeCascadeResults??false;filterFields=e.filterFields??[];filterConfig=e.filterConfig;searchFields=e.searchFields??[];searchFieldName=e.searchFieldName??"search";sortFields=e.sortFields??[];defaultSort=e.defaultSort;defaultPerPage=e.defaultPerPage??20;maxPerPage=e.maxPerPage??100;allowedIncludes=e.allowedIncludes??[];fieldSelectionEnabled=e.fieldSelectionEnabled??false;allowedSelectFields=e.allowedSelectFields??[];blockedSelectFields=e.blockedSelectFields??[];alwaysIncludeFields=e.alwaysIncludeFields??[];defaultSelectFields=e.defaultSelectFields??[];getBodySchema(){return e.bodySchema?e.bodySchema:super.getBodySchema()}async before(...i){return e.before?e.before(...i):super.before(...i)}async after(...i){return e.after?e.after(...i):super.after(...i)}transform(i){return e.transform?e.transform(i):super.transform(i)}}}function ba(o,e){return d(e,{meta:o.meta,schema:o.schema,middlewares:o.middlewares,before:o.before,after:o.after,beforeHookMode:o.beforeHookMode,afterHookMode:o.afterHookMode,allowNestedCreate:o.allowNestedCreate})}function xa(o,e){let n=o.defaultSort??(o.defaultOrderBy?{field:o.defaultOrderBy,order:o.defaultOrderDirection??"asc"}:void 0);return d(e,{meta:o.meta,schema:o.schema,middlewares:o.middlewares,after:o.after,transform:o.transform,filterFields:o.filterFields,filterConfig:o.filterConfig,searchFields:o.searchFields,searchFieldName:o.searchFieldName,sortFields:o.sortFields??o.orderByFields,defaultSort:n,defaultPerPage:o.defaultPerPage,maxPerPage:o.maxPerPage,allowedIncludes:o.allowedIncludes,fieldSelectionEnabled:o.fieldSelectionEnabled,allowedSelectFields:o.allowedSelectFields,blockedSelectFields:o.blockedSelectFields,alwaysIncludeFields:o.alwaysIncludeFields,defaultSelectFields:o.defaultSelectFields})}function ya(o,e){return d(e,{meta:o.meta,schema:o.schema,middlewares:o.middlewares,after:o.after,transform:o.transform,lookupField:o.lookupField,additionalFilters:o.additionalFilters,allowedIncludes:o.allowedIncludes,fieldSelectionEnabled:o.fieldSelectionEnabled,allowedSelectFields:o.allowedSelectFields,blockedSelectFields:o.blockedSelectFields,alwaysIncludeFields:o.alwaysIncludeFields,defaultSelectFields:o.defaultSelectFields})}function Sa(o,e){return d(e,{meta:o.meta,schema:o.schema,middlewares:o.middlewares,before:o.before,after:o.after,transform:o.transform,beforeHookMode:o.beforeHookMode,afterHookMode:o.afterHookMode,lookupField:o.lookupField,additionalFilters:o.additionalFilters,allowedUpdateFields:o.allowedUpdateFields,blockedUpdateFields:o.blockedUpdateFields,allowNestedWrites:o.allowNestedWrites})}function Oa(o,e){return d(e,{meta:o.meta,schema:o.schema,middlewares:o.middlewares,before:o.before,after:o.after,beforeHookMode:o.beforeHookMode,afterHookMode:o.afterHookMode,lookupField:o.lookupField,additionalFilters:o.additionalFilters,includeCascadeResults:o.includeCascadeResults})}var R=class{constructor(e){this.meta=e;}_schema={};_before;_after;_beforeHookMode="sequential";_afterHookMode="sequential";_allowNestedCreate=[];_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}before(e){return this._before=e,this}after(e){return this._after=e,this}beforeMode(e){return this._beforeHookMode=e,this}afterMode(e){return this._afterHookMode=e,this}nestedCreate(...e){return this._allowNestedCreate=e,this}build(e){return d(e,{meta:this.meta,schema:this._schema,before:this._before,after:this._after,beforeHookMode:this._beforeHookMode,afterHookMode:this._afterHookMode,allowNestedCreate:this._allowNestedCreate,middlewares:this._middlewares})}},A=class{constructor(e){this.meta=e;}_schema={};_filterFields=[];_filterConfig;_searchFields=[];_searchFieldName="search";_sortFields=[];_defaultSort;_defaultPerPage=20;_maxPerPage=100;_allowedIncludes=[];_fieldSelectionEnabled=false;_allowedSelectFields=[];_blockedSelectFields=[];_alwaysIncludeFields=[];_defaultSelectFields=[];_after;_transform;_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}filter(...e){return this._filterFields=e,this}filterWith(e){return this._filterConfig=e,this}search(...e){return this._searchFields=e,this}searchParam(e){return this._searchFieldName=e,this}sortable(...e){return this._sortFields=e,this}orderBy(...e){return this.sortable(...e)}defaultSort(e,n="asc"){return this._defaultSort={field:e,order:n},this}defaultOrder(e,n="asc"){return this.defaultSort(e,n)}pagination(e,n){return this._defaultPerPage=e,n!==void 0&&(this._maxPerPage=n),this}include(...e){return this._allowedIncludes=e,this}fieldSelection(e){return this._fieldSelectionEnabled=true,e?.allowed&&(this._allowedSelectFields=e.allowed),e?.blocked&&(this._blockedSelectFields=e.blocked),e?.alwaysInclude&&(this._alwaysIncludeFields=e.alwaysInclude),e?.defaults&&(this._defaultSelectFields=e.defaults),this}after(e){return this._after=e,this}transform(e){return this._transform=e,this}build(e){return d(e,{meta:this.meta,schema:this._schema,filterFields:this._filterFields,filterConfig:this._filterConfig,searchFields:this._searchFields,searchFieldName:this._searchFieldName,sortFields:this._sortFields,defaultSort:this._defaultSort,defaultPerPage:this._defaultPerPage,maxPerPage:this._maxPerPage,allowedIncludes:this._allowedIncludes,fieldSelectionEnabled:this._fieldSelectionEnabled,allowedSelectFields:this._allowedSelectFields,blockedSelectFields:this._blockedSelectFields,alwaysIncludeFields:this._alwaysIncludeFields,defaultSelectFields:this._defaultSelectFields,after:this._after,transform:this._transform,middlewares:this._middlewares})}},H=class{constructor(e){this.meta=e;}_schema={};_lookupField="id";_additionalFilters;_allowedIncludes=[];_fieldSelectionEnabled=false;_allowedSelectFields=[];_blockedSelectFields=[];_alwaysIncludeFields=[];_defaultSelectFields=[];_after;_transform;_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}lookupField(e){return this._lookupField=e,this}additionalFilters(...e){return this._additionalFilters=e,this}include(...e){return this._allowedIncludes=e,this}fieldSelection(e){return this._fieldSelectionEnabled=true,e?.allowed&&(this._allowedSelectFields=e.allowed),e?.blocked&&(this._blockedSelectFields=e.blocked),e?.alwaysInclude&&(this._alwaysIncludeFields=e.alwaysInclude),e?.defaults&&(this._defaultSelectFields=e.defaults),this}after(e){return this._after=e,this}transform(e){return this._transform=e,this}build(e){return d(e,{meta:this.meta,schema:this._schema,lookupField:this._lookupField,additionalFilters:this._additionalFilters,allowedIncludes:this._allowedIncludes,fieldSelectionEnabled:this._fieldSelectionEnabled,allowedSelectFields:this._allowedSelectFields,blockedSelectFields:this._blockedSelectFields,alwaysIncludeFields:this._alwaysIncludeFields,defaultSelectFields:this._defaultSelectFields,after:this._after,transform:this._transform,middlewares:this._middlewares})}},F=class{constructor(e){this.meta=e;}_schema={};_lookupField="id";_additionalFilters;_allowedUpdateFields;_blockedUpdateFields;_allowNestedWrites=[];_before;_after;_beforeHookMode="sequential";_afterHookMode="sequential";_transform;_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}lookupField(e){return this._lookupField=e,this}additionalFilters(...e){return this._additionalFilters=e,this}allowedFields(...e){return this._allowedUpdateFields=e,this}blockedFields(...e){return this._blockedUpdateFields=e,this}nestedWrites(...e){return this._allowNestedWrites=e,this}before(e){return this._before=e,this}after(e){return this._after=e,this}beforeMode(e){return this._beforeHookMode=e,this}afterMode(e){return this._afterHookMode=e,this}transform(e){return this._transform=e,this}build(e){return d(e,{meta:this.meta,schema:this._schema,lookupField:this._lookupField,additionalFilters:this._additionalFilters,allowedUpdateFields:this._allowedUpdateFields,blockedUpdateFields:this._blockedUpdateFields,allowNestedWrites:this._allowNestedWrites,before:this._before,after:this._after,beforeHookMode:this._beforeHookMode,afterHookMode:this._afterHookMode,transform:this._transform,middlewares:this._middlewares})}},_=class{constructor(e){this.meta=e;}_schema={};_lookupField="id";_additionalFilters;_includeCascadeResults=false;_before;_after;_beforeHookMode="sequential";_afterHookMode="sequential";_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}lookupField(e){return this._lookupField=e,this}additionalFilters(...e){return this._additionalFilters=e,this}includeCascade(e=true){return this._includeCascadeResults=e,this}before(e){return this._before=e,this}after(e){return this._after=e,this}beforeMode(e){return this._beforeHookMode=e,this}afterMode(e){return this._afterHookMode=e,this}build(e){return d(e,{meta:this.meta,schema:this._schema,lookupField:this._lookupField,additionalFilters:this._additionalFilters,includeCascadeResults:this._includeCascadeResults,before:this._before,after:this._after,beforeHookMode:this._beforeHookMode,afterHookMode:this._afterHookMode,middlewares:this._middlewares})}},j=class{constructor(e){this.meta=e;}create(){return new R(this.meta)}list(){return new A(this.meta)}read(){return new H(this.meta)}update(){return new F(this.meta)}delete(){return new _(this.meta)}};function Pa(o){return new j(o)}var Ia={CreateEndpoint:g,ListEndpoint:k,ReadEndpoint:h,UpdateEndpoint:i,DeleteEndpoint:j$1,SearchEndpoint:y$1,AggregateEndpoint:x,RestoreEndpoint:l,BatchCreateEndpoint:m,BatchUpdateEndpoint:n,BatchDeleteEndpoint:o,BatchRestoreEndpoint:p,BatchUpsertEndpoint:q$1,ExportEndpoint:z$1,ImportEndpoint:A$1,UpsertEndpoint:s,CloneEndpoint:r};function va(o,e){let n={};if(o.create!==void 0){let t=o.create;n.create=d(e.CreateEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,allowNestedCreate:t.nestedCreate,before:t.hooks?.before,after:t.hooks?.after});}if(o.list!==void 0){let t=o.list;n.list=d(e.ListEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,filterFields:t.filtering?.fields,filterConfig:t.filtering?.config,searchFields:t.search?.fields,searchFieldName:t.search?.paramName,sortFields:t.sorting?.fields,defaultSort:t.sorting?.default?{field:t.sorting.default,order:t.sorting.defaultOrder??t.sorting.defaultDirection??"asc"}:void 0,defaultPerPage:t.pagination?.defaultPerPage,maxPerPage:t.pagination?.maxPerPage,allowedIncludes:t.includes,fieldSelectionEnabled:t.fieldSelection?.enabled,allowedSelectFields:t.fieldSelection?.allowed,blockedSelectFields:t.fieldSelection?.blocked,alwaysIncludeFields:t.fieldSelection?.alwaysInclude,defaultSelectFields:t.fieldSelection?.defaults,after:t.hooks?.after,transform:t.hooks?.transform});}if(o.read!==void 0){let t=o.read;n.read=d(e.ReadEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,lookupField:t.lookupField,additionalFilters:t.additionalFilters,allowedIncludes:t.includes,fieldSelectionEnabled:t.fieldSelection?.enabled,allowedSelectFields:t.fieldSelection?.allowed,blockedSelectFields:t.fieldSelection?.blocked,alwaysIncludeFields:t.fieldSelection?.alwaysInclude,defaultSelectFields:t.fieldSelection?.defaults,after:t.hooks?.after,transform:t.hooks?.transform});}if(o.update!==void 0){let t=o.update;n.update=d(e.UpdateEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,lookupField:t.lookupField,additionalFilters:t.additionalFilters,allowedUpdateFields:t.fields?.allowed,blockedUpdateFields:t.fields?.blocked,allowNestedWrites:t.nestedWrites,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,transform:t.hooks?.transform});}if(o.delete!==void 0){let t=o.delete;n.delete=d(e.DeleteEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,lookupField:t.lookupField,additionalFilters:t.additionalFilters,includeCascadeResults:t.includeCascadeResults,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after});}if(o.search!==void 0&&e.SearchEndpoint){let t=o.search;n.search=d(e.SearchEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,after:t.hooks?.after,extras:{...t.fields!==void 0?{searchFields:t.fields}:{},...t.mode!==void 0?{defaultMode:t.mode}:{},...t.paramName!==void 0?{searchParamName:t.paramName}:{}}});}if(o.aggregate!==void 0&&e.AggregateEndpoint){let t=o.aggregate;n.aggregate=d(e.AggregateEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,after:t.hooks?.after,extras:{...t.fields!==void 0?{filterFields:t.fields}:{}}});}if(o.restore!==void 0&&e.RestoreEndpoint){let t=o.restore;n.restore=d(e.RestoreEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after});}if(o.batchCreate!==void 0&&e.BatchCreateEndpoint){let t=o.batchCreate;n.batchCreate=d(e.BatchCreateEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{}}});}if(o.batchUpdate!==void 0&&e.BatchUpdateEndpoint){let t=o.batchUpdate;n.batchUpdate=d(e.BatchUpdateEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{}}});}if(o.batchDelete!==void 0&&e.BatchDeleteEndpoint){let t=o.batchDelete;n.batchDelete=d(e.BatchDeleteEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{}}});}if(o.batchRestore!==void 0&&e.BatchRestoreEndpoint){let t=o.batchRestore;n.batchRestore=d(e.BatchRestoreEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{}}});}if(o.batchUpsert!==void 0&&e.BatchUpsertEndpoint){let t=o.batchUpsert,r=typeof t.conflictTarget=="string"?[t.conflictTarget]:t.conflictTarget;n.batchUpsert=d(e.BatchUpsertEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{},...r!==void 0?{upsertKeys:r}:{}}});}if(o.export!==void 0&&e.ExportEndpoint){let t=o.export;n.export=d(e.ExportEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,extras:{...t.maxRows!==void 0?{maxExportRecords:t.maxRows}:{},...t.formats!==void 0&&t.formats.length>0?{defaultFormat:t.formats[0]}:{}}});}if(o.import!==void 0&&e.ImportEndpoint){let t=o.import;n.import=d(e.ImportEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxRows!==void 0?{maxBatchSize:t.maxRows}:{}}});}if(o.upsert!==void 0&&e.UpsertEndpoint){let t=o.upsert,r=typeof t.conflictTarget=="string"?[t.conflictTarget]:t.conflictTarget;n.upsert=d(e.UpsertEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...r!==void 0?{upsertKeys:r}:{}}});}if(o.clone!==void 0&&e.CloneEndpoint){let t=o.clone;n.clone=d(e.CloneEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.fieldsToReset!==void 0?{excludeFromClone:t.fieldsToReset}:{}}});}return n}
2
2
  export{R as CreateBuilder,j as CrudBuilder,_ as DeleteBuilder,P as HonoOpenAPIHandler,fe as HttpErrorSchema,A as ListBuilder,Ia as MemoryAdapters,H as ReadBuilder,F as UpdateBuilder,v as ZodErrorSchema,me as ZodIssueSchema,Jr as buildPerTenantOpenApi,ka as commonResponses,q as contentJson,ba as createCreate,Ca as createCrudMiddleware,Oa as createDelete,da as createErrorHandler,ga as createErrorSchema,xa as createList,Ea as createOneOfErrorSchema,ya as createRead,ca as createSubscribeHandler,Sa as createUpdate,wa as createValidationHook,Pa as crud,va as defineEndpoints,fa as errorResponse,qr as fromHono,V as getHandlerForApp,y as httpErrorContent,Z as jsonContent,ha as jsonContentRequired,Ma as openApiValidationHook,ua as registerCrud,ue as resolveErrorEnvelope,ma as successResponse,aa as toOpenApiPaths,Xr as wrapCacheStorageForOpenApi,ce as zodErrorMapper};
@@ -1 +1 @@
1
- export{a as MemoryLoggingStorage}from'../chunk-3UHTK7SB.js';export{V as createLoggingMiddleware,f as extractClientIp,g as extractHeaders,h as extractQuery,k as extractUserId,l as generateRequestId,S as getLoggingStorage,T as getRequestId,U as getRequestStartTime,j as isAllowedContentType,d as matchPath,c as redactHeaders,b as redactObject,R as setLoggingStorage,e as shouldExcludePath,a as shouldRedact,i as truncateBody}from'../chunk-UANCAA7V.js';import'../chunk-NGUMNUOP.js';import'../chunk-GF2EC5G4.js';import'../chunk-2M5BM4VD.js';import'../chunk-FC56WWPB.js';import'../chunk-FJCWFB5L.js';import'../chunk-KUFOENSK.js';import'../chunk-GBQQ3YQX.js';import'../chunk-DMGP7QDL.js';import'../chunk-MDHMZPXK.js';import'../chunk-VJRDAVID.js';
1
+ export{a as MemoryLoggingStorage}from'../chunk-PCPU5A2Q.js';export{V as createLoggingMiddleware,f as extractClientIp,g as extractHeaders,h as extractQuery,k as extractUserId,l as generateRequestId,S as getLoggingStorage,T as getRequestId,U as getRequestStartTime,j as isAllowedContentType,d as matchPath,c as redactHeaders,b as redactObject,R as setLoggingStorage,e as shouldExcludePath,a as shouldRedact,i as truncateBody}from'../chunk-IPMPKM4J.js';import'../chunk-NGUMNUOP.js';import'../chunk-GF2EC5G4.js';import'../chunk-FJCWFB5L.js';import'../chunk-2M5BM4VD.js';import'../chunk-FC56WWPB.js';import'../chunk-KUFOENSK.js';import'../chunk-GBQQ3YQX.js';import'../chunk-DMGP7QDL.js';import'../chunk-MDHMZPXK.js';import'../chunk-VJRDAVID.js';
@@ -1 +1 @@
1
- export{c as KVRateLimitStorage,a as MemoryRateLimitStorage,b as RedisRateLimitStorage}from'../chunk-EWKQ6BPV.js';export{m as RateLimitExceededException,v as createRateLimitMiddleware,p as extractAPIKey,n as extractIP,o as extractUserId,s as generateKey,u as getRateLimitStorage,q as matchPath,w as resetRateLimit,t as setRateLimitStorage,r as shouldSkipPath}from'../chunk-UANCAA7V.js';import'../chunk-NGUMNUOP.js';import'../chunk-GF2EC5G4.js';import'../chunk-2M5BM4VD.js';import'../chunk-FC56WWPB.js';import'../chunk-FJCWFB5L.js';import'../chunk-KUFOENSK.js';import'../chunk-GBQQ3YQX.js';import'../chunk-DMGP7QDL.js';import'../chunk-MDHMZPXK.js';import'../chunk-VJRDAVID.js';
1
+ export{c as KVRateLimitStorage,a as MemoryRateLimitStorage,b as RedisRateLimitStorage}from'../chunk-EWKQ6BPV.js';export{m as RateLimitExceededException,v as createRateLimitMiddleware,p as extractAPIKey,n as extractIP,o as extractUserId,s as generateKey,u as getRateLimitStorage,q as matchPath,w as resetRateLimit,t as setRateLimitStorage,r as shouldSkipPath}from'../chunk-IPMPKM4J.js';import'../chunk-NGUMNUOP.js';import'../chunk-GF2EC5G4.js';import'../chunk-FJCWFB5L.js';import'../chunk-2M5BM4VD.js';import'../chunk-FC56WWPB.js';import'../chunk-KUFOENSK.js';import'../chunk-GBQQ3YQX.js';import'../chunk-DMGP7QDL.js';import'../chunk-MDHMZPXK.js';import'../chunk-VJRDAVID.js';
@@ -1 +1 @@
1
- export{g as createAPIKeyStorageMiddleware,e as createAuditStorageMiddleware,d as createCacheStorageMiddleware,c as createLoggingStorageMiddleware,b as createRateLimitStorageMiddleware,a as createStorageMiddleware,f as createVersioningStorageMiddleware}from'../chunk-R3WESU6C.js';export{M as resolveAPIKeyStorage,K as resolveAuditStorage,J as resolveCacheStorage,N as resolveIdempotencyStorage,I as resolveLoggingStorage,H as resolveRateLimitStorage,L as resolveVersioningStorage}from'../chunk-UANCAA7V.js';import'../chunk-NGUMNUOP.js';import'../chunk-GF2EC5G4.js';import'../chunk-2M5BM4VD.js';import'../chunk-FC56WWPB.js';import'../chunk-FJCWFB5L.js';import'../chunk-KUFOENSK.js';export{a as StorageRegistry,b as createNullableRegistry,c as createRegistryWithDefault}from'../chunk-GBQQ3YQX.js';import'../chunk-DMGP7QDL.js';import'../chunk-MDHMZPXK.js';import'../chunk-VJRDAVID.js';
1
+ export{g as createAPIKeyStorageMiddleware,e as createAuditStorageMiddleware,d as createCacheStorageMiddleware,c as createLoggingStorageMiddleware,b as createRateLimitStorageMiddleware,a as createStorageMiddleware,f as createVersioningStorageMiddleware}from'../chunk-R3WESU6C.js';export{M as resolveAPIKeyStorage,K as resolveAuditStorage,J as resolveCacheStorage,N as resolveIdempotencyStorage,I as resolveLoggingStorage,H as resolveRateLimitStorage,L as resolveVersioningStorage}from'../chunk-IPMPKM4J.js';import'../chunk-NGUMNUOP.js';import'../chunk-GF2EC5G4.js';import'../chunk-FJCWFB5L.js';import'../chunk-2M5BM4VD.js';import'../chunk-FC56WWPB.js';import'../chunk-KUFOENSK.js';export{a as StorageRegistry,b as createNullableRegistry,c as createRegistryWithDefault}from'../chunk-GBQQ3YQX.js';import'../chunk-DMGP7QDL.js';import'../chunk-MDHMZPXK.js';import'../chunk-VJRDAVID.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hono-crud",
3
- "version": "0.13.1",
3
+ "version": "0.13.2",
4
4
  "description": "CRUD generator for Hono with Zod validation and OpenAPI generation",
5
5
  "author": "Kauan Guesser <contato@kauan.net>",
6
6
  "license": "MIT",
@@ -1,4 +0,0 @@
1
- import {t,u,v,w,x,z as z$1,B as B$1,C,D as D$1,E,A as A$1,F as F$1,G,H as H$1,I as I$1,J as J$1,K as K$1,L as L$1,T,U as U$1,ba,ca,y}from'./chunk-ZBCVLQ3W.js';import {b as b$1}from'./chunk-DMGP7QDL.js';import {getTableColumns,eq,inArray,between,isNull,isNotNull,ilike,like,notInArray,lte,lt,gte,gt as gt$1,ne as ne$1,and,sql,or,desc,asc}from'drizzle-orm';import {z}from'zod';function X(a){return a}function f(a){if(!a.model.table)throw new Error(`Model ${a.model.tableName} does not have a table reference`);return a.model.table}function b(a,e){let t=getTableColumns(a),o=t[e];if(!o)throw new Error(`Column '${e}' not found in table. Available columns: ${Object.keys(t).join(", ")}`);return o}async function Pe(a,e,t,o){if(!o.table)return e;let n=o.table;switch(o.type){case "hasOne":{let r=o.localKey||"id",s=e[r];if(s==null)return e;let i=b(n,o.foreignKey),l=await a.select().from(n).where(eq(i,s)).limit(1);return {...e,[t]:l[0]||null}}case "hasMany":{let r=o.localKey||"id",s=e[r];if(s==null)return {...e,[t]:[]};let i=b(n,o.foreignKey),l=await a.select().from(n).where(eq(i,s));return {...e,[t]:l}}case "belongsTo":{let r=e[o.foreignKey];if(r==null)return {...e,[t]:null};let s=b(n,o.localKey||"id"),i=await a.select().from(n).where(eq(s,r)).limit(1);return {...e,[t]:i[0]||null}}default:return e}}async function le(a,e,t,o){if(!o?.relations?.length||!t.model.relations)return e;let n={...e};for(let r of o.relations){let s=t.model.relations[r];s&&(n=await Pe(a,n,r,s));}return n}async function S(a,e,t,o){if(!e.length||!o?.relations?.length||!t.model.relations)return e;let n=e.map(r=>({...r}));for(let r of o.relations){let s=t.model.relations[r];if(!s||!s.table)continue;let i=s.table;switch(s.type){case "hasOne":case "hasMany":{let l=s.localKey||"id",d=[...new Set(n.map(p=>p[l]).filter(p=>p!=null))];if(d.length===0){n=n.map(p=>({...p,[r]:s.type==="hasMany"?[]:null}));continue}let u=b(i,s.foreignKey),c=await a.select().from(i).where(inArray(u,d)),m=new Map;for(let p of c){let g=p[s.foreignKey];m.has(g)||m.set(g,[]),m.get(g).push(p);}n=n.map(p=>{let g=p[l],h=m.get(g)||[];return {...p,[r]:s.type==="hasMany"?h:h[0]||null}});break}case "belongsTo":{let l=s.localKey||"id",d=[...new Set(n.map(p=>p[s.foreignKey]).filter(p=>p!=null))];if(d.length===0){n=n.map(p=>({...p,[r]:null}));continue}let u=b(i,l),c=await a.select().from(i).where(inArray(u,d)),m=new Map;for(let p of c){let g=p[l];m.set(g,p);}n=n.map(p=>{let g=p[s.foreignKey];return {...p,[r]:m.get(g)||null}});break}}}return n}function O(a,e){let t=b(a,e.field);switch(e.operator){case "eq":return eq(t,e.value);case "ne":return ne$1(t,e.value);case "gt":return gt$1(t,e.value);case "gte":return gte(t,e.value);case "lt":return lt(t,e.value);case "lte":return lte(t,e.value);case "in":return inArray(t,e.value);case "nin":return notInArray(t,e.value);case "like":return like(t,e.value);case "ilike":return ilike(t,e.value);case "null":return e.value?isNull(t):isNotNull(t);case "between":{let[o,n]=e.value;return between(t,o,n)}default:return}}function D(a){let e=a;if(e._tx)return e._tx;if(e.db)return e.db;let t=e.context?.get?.("db");if(t)return t;throw new Error(`Database not configured. Either:
2
- 1. Set db property: db = myDb;
3
- 2. Use middleware: c.set("db", myDb);
4
- 3. Use factory: createDrizzleCrud(db, meta)`)}var _=class extends t{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getRelatedTable(e){return e.table}async create(e,t){let o=t??this.getDb(),n=this.getTable(),r=this.applyManagedInsertFields(e,"drizzle");return (await o.insert(n).values(r).returning())[0]}async createNested(e,t,o,n,r){let s=r??this.getDb(),i=this.getRelatedTable(o);if(!i)return b$1().warn(`Related table not found for ${t}. Add 'table' to the relation config.`),[];let l=Array.isArray(n)?n:[n],d=[];for(let u of l){if(typeof u!="object"||u===null)continue;let c={...u,id:crypto.randomUUID(),[o.foreignKey]:e},m=await s.insert(i).values(c).returning();m[0]&&d.push(m[0]);}return d}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},I=class extends u{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async read(e,t,o){let n=this.getTable(),r=this.getColumn(this.lookupField),s=this.getSoftDeleteConfig(),i=[eq(r,e)];if(t)for(let[u,c]of Object.entries(t))i.push(eq(this.getColumn(u),c));s.enabled&&i.push(isNull(this.getColumn(s.field)));let l=await this.getDb().select().from(n).where(and(...i)).limit(1);return l[0]?await le(this.getDb(),l[0],this._meta,o):null}},P=class extends v{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}getRelatedTable(e){return e.table}async findExisting(e,t,o){let n=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[u,c]of Object.entries(t))l.push(eq(this.getColumn(u),c));return i.enabled&&l.push(isNull(this.getColumn(i.field))),(await n.select().from(r).where(and(...l)).limit(1))[0]||null}async update(e,t,o,n){let r=n??this.getDb(),s=this.getTable(),i=this.getColumn(this.lookupField),l=this.getSoftDeleteConfig(),d=[eq(i,e)];if(o)for(let[c,m]of Object.entries(o))d.push(eq(this.getColumn(c),m));return l.enabled&&d.push(isNull(this.getColumn(l.field))),(await r.update(s).set(this.applyManagedUpdateFields(t)).where(and(...d)).returning())[0]||null}async processNestedWrites(e,t,o,n,r){let s=r??this.getDb(),i=this.getRelatedTable(o);if(!i)return b$1().warn(`Related table not found for ${t}. Add 'table' to the relation config.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]};let l={created:[],updated:[],deleted:[],connected:[],disconnected:[]},d=b(i,o.foreignKey),u=b(i,"id");if(n.create){let c=Array.isArray(n.create)?n.create:[n.create];for(let m of c){if(typeof m!="object"||m===null)continue;let p={...m,id:crypto.randomUUID(),[o.foreignKey]:e},g=await s.insert(i).values(p).returning();g[0]&&l.created.push(g[0]);}}if(n.update)for(let c of n.update){if(!c.id||!(await s.select().from(i).where(and(eq(u,c.id),eq(d,e))).limit(1))[0])continue;let{id:p,...g}=c,h=await s.update(i).set(g).where(eq(u,p)).returning();h[0]&&l.updated.push(h[0]);}if(n.delete)for(let c of n.delete)(await s.delete(i).where(and(eq(u,c),eq(d,e))).returning())[0]&&l.deleted.push(c);if(n.connect)for(let c of n.connect)(await s.update(i).set({[o.foreignKey]:e}).where(eq(u,c)).returning())[0]&&l.connected.push(c);if(n.disconnect)for(let c of n.disconnect)(await s.update(i).set({[o.foreignKey]:null}).where(and(eq(u,c),eq(d,e))).returning())[0]&&l.disconnected.push(c);return l}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},U=class extends w{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}getRelatedTable(e){return e.table}async findForDelete(e,t,o){let n=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[u,c]of Object.entries(t))l.push(eq(this.getColumn(u),c));return i.enabled&&l.push(isNull(this.getColumn(i.field))),(await n.select().from(r).where(and(...l)).limit(1))[0]||null}async delete(e,t,o){let n=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[d,u]of Object.entries(t))l.push(eq(this.getColumn(d),u));return i.enabled&&l.push(isNull(this.getColumn(i.field))),i.enabled?(await n.update(r).set({[i.field]:new Date}).where(and(...l)).returning())[0]||null:(await n.delete(r).where(and(...l)).returning())[0]||null}async countRelated(e,t,o,n){let r=n??this.getDb(),s=this.getRelatedTable(o);if(!s)return 0;let i=b(s,o.foreignKey),l=await r.select({count:sql`count(*)`}).from(s).where(eq(i,e));return Number(l[0]?.count)||0}async deleteRelated(e,t,o,n){let r=n??this.getDb(),s=this.getRelatedTable(o);if(!s)return 0;let i=b(s,o.foreignKey);return (await r.delete(s).where(eq(i,e)).returning()).length}async nullifyRelated(e,t,o,n){let r=n??this.getDb(),s=this.getRelatedTable(o);if(!s)return 0;let i=b(s,o.foreignKey);return (await r.update(s).set({[o.foreignKey]:null}).where(eq(i,e)).returning()).length}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},B=class extends x{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async list(e){let t=this.getTable(),o=[],n=this.getSoftDeleteConfig();if(n.enabled){let y=this.getColumn(n.field);e.options.onlyDeleted?o.push(isNotNull(y)):e.options.withDeleted||o.push(isNull(y));}for(let y of e.filters){let R=O(t,y);R&&o.push(R);}if(e.options.search&&this.searchFields.length>0){let y=this.searchFields.map(R=>{let $=this.getColumn(R);return sql`LOWER(${$}) LIKE LOWER(${`%${e.options.search}%`})`});o.push(or(...y));}let r=o.length>0?and(...o):void 0,s=this.getDb(),i=await s.select({count:sql`count(*)`}).from(t).where(r),l=Number(i[0]?.count)||0,d=s.select().from(t).where(r);if(e.options.order_by){let y=this.getColumn(e.options.order_by),R=e.options.order_by_direction==="desc"?desc:asc;d=d.orderBy(R(y));}let u=e.options.page||1,c=e.options.per_page||this.defaultPerPage;d=d.limit(c).offset((u-1)*c);let m=await d,p={relations:e.options.include||[]},g=await S(this.getDb(),m,this._meta,p),h=Math.ceil(l/c);return {result:g,result_info:{page:u,per_page:c,total_count:l,total_pages:h,has_next_page:u<h,has_prev_page:u>1}}}},L=class extends z$1{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async restore(e,t,o){let n=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[u,c]of Object.entries(t))l.push(eq(this.getColumn(u),c));return l.push(isNotNull(this.getColumn(i.field))),(await n.update(r).set({[i.field]:null}).where(and(...l)).returning())[0]||null}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}};var A=class extends B$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}async batchCreate(e){let t=this.getTable(),o=e.map(r=>this.applyManagedInsertFields(r,"drizzle"));return await this.getDb().insert(t).values(o).returning()}},K=class extends C{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async batchUpdate(e){let t=this.getTable(),o=this.getColumn(this.lookupField),n=this.getSoftDeleteConfig(),r=[],s=[];for(let i of e){let l=[eq(o,i.id)];n.enabled&&l.push(isNull(this.getColumn(n.field)));let d=await this.getDb().update(t).set(this.applyManagedUpdateFields(i.data)).where(and(...l)).returning();d[0]?r.push(d[0]):s.push(i.id);}return {updated:r,notFound:s}}},Z=class extends D$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async batchDelete(e){let t=this.getTable(),o=this.getColumn(this.lookupField),n=this.getSoftDeleteConfig(),r=[inArray(o,e)];n.enabled&&r.push(isNull(this.getColumn(n.field)));let s;n.enabled?s=await this.getDb().update(t).set({[n.field]:new Date}).where(and(...r)).returning():s=await this.getDb().delete(t).where(and(...r)).returning();let i=s,l=new Set(i.map(u=>String(u[this.lookupField]))),d=e.filter(u=>!l.has(u));return {deleted:i,notFound:d}}},F=class extends E{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async batchRestore(e){let t=this.getTable(),o=this.getColumn(this.lookupField),n=this.getSoftDeleteConfig(),r=[inArray(o,e),isNotNull(this.getColumn(n.field))],i=await this.getDb().update(t).set({[n.field]:null}).where(and(...r)).returning(),l=new Set(i.map(u=>String(u[this.lookupField]))),d=e.filter(u=>!l.has(u));return {restored:i,notFound:d}}};function $e(a,e,t){switch(t){case "pg":return sql`POSITION(LOWER(${e}) IN LOWER(${a})) > 0`;case "mysql":return sql`LOCATE(LOWER(${e}), LOWER(${a})) > 0`;default:return sql`INSTR(LOWER(${a}), LOWER(${e})) > 0`}}function gt(a){return a.split(/\s+/).filter(e=>e.length>0)}var Q=class extends A$1{db;dialect="sqlite";getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async findExisting(e){let t=this.getTable(),o=this.getUpsertKeys(),n=this.getSoftDeleteConfig(),r=[];for(let i of o){let l=e[i];l!==void 0&&r.push(eq(this.getColumn(i),l));}return n.enabled&&r.push(isNull(this.getColumn(n.field))),r.length===0?null:(await this.getDb().select().from(t).where(and(...r)).limit(1))[0]||null}async create(e){let t=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(t).values(o).returning())[0]}async update(e,t){let o=this.getTable(),n=this._meta.model.primaryKeys[0],r=e[n];return (await this.getDb().update(o).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(n),r)).returning())[0]}async nativeUpsert(e,t){let o=this.getTable(),n=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s=this.getSoftDeleteConfig(),i=this.getTimestampsConfig(),l=this.applyManagedInsertFields(e,"drizzle"),d={};for(let[h,y]of Object.entries(e))!n.includes(h)&&h!==r&&(this.createOnlyFields?.includes(h)||(d[h]=y));i.enabled&&(d[i.updatedAt]=Date.now());let u=n.map(h=>this.getColumn(h)),c;s.enabled&&(c=isNull(this.getColumn(s.field)));let m=Object.keys(d).length>0?d:{[r]:sql`${this.getColumn(r)}`},p=this.getDb().insert(o).values(l);return this.dialect==="mysql"?{data:(await p.onDuplicateKeyUpdate({set:m}).returning())[0],created:false}:{data:(await p.onConflictDoUpdate({target:u,set:m,where:c}).returning())[0],created:false}}},N=class extends F$1{db;dialect="sqlite";getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async findExisting(e){let t=this.getTable(),o=this.getUpsertKeys(),n=[];for(let s of o){let i=e[s];i!==void 0&&n.push(eq(this.getColumn(s),i));}return n.length===0?null:(await this.getDb().select().from(t).where(and(...n)).limit(1))[0]||null}async create(e){let t=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(t).values(o).returning())[0]}async update(e,t){let o=this.getTable(),n=this._meta.model.primaryKeys[0],r=e[n];return (await this.getDb().update(o).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(n),r)).returning())[0]}async nativeBatchUpsert(e,t){if(e.length===0)return {items:[],createdCount:0,updatedCount:0,totalCount:0};let o=this.getTable(),n=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s=this.getTimestampsConfig(),i=e.map(g=>this.applyManagedInsertFields(g,"drizzle")),l={},d=e[0];for(let g of Object.keys(d))!n.includes(g)&&g!==r&&(this.createOnlyFields?.includes(g)||(l[g]=sql`excluded.${sql.identifier(g)}`));s.enabled&&(l[s.updatedAt]=Date.now());let u=n.map(g=>this.getColumn(g)),c=Object.keys(l).length>0?l:{[r]:sql`${this.getColumn(r)}`},m=this.getDb().insert(o).values(i),p=await(this.dialect==="mysql"?m.onDuplicateKeyUpdate({set:c}):m.onConflictDoUpdate({target:u,set:c})).returning();return {items:p.map((g,h)=>({data:g,created:false,index:h})),createdCount:0,updatedCount:p.length,totalCount:p.length}}},Ae=class extends G{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async recordExists(e){let t=this.getTable(),o=await this.getDb().select({count:sql`count(*)`}).from(t).where(eq(this.getColumn("id"),e));return Number(o[0]?.count)>0}},Ke=class extends H$1{},Ze=class extends I$1{},Fe=class extends J$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async rollback(e,t,o){let n=this.getTable(),r=this.getVersioningConfig().field;return (await this.getDb().update(n).set({...t,[r]:o}).where(eq(this.getColumn("id"),e)).returning())[0]}},H=class extends K$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async aggregate(e){let t=this.getTable(),o=[],n=this.getSoftDeleteConfig();if(n.enabled){let{query:i}=await this.getValidatedData();i?.withDeleted===true||i?.withDeleted==="true"||o.push(isNull(this.getColumn(n.field)));}if(e.filters)for(let[i,l]of Object.entries(e.filters))if(typeof l=="object"&&l!==null)for(let[d,u]of Object.entries(l)){let c=O(t,{field:i,operator:d,value:u});c&&o.push(c);}else o.push(eq(this.getColumn(i),l));let r=o.length>0?and(...o):void 0,s=await this.getDb().select().from(t).where(r);return L$1(s,e)}},q=class extends T{db;dialect="sqlite";getDb(){return D(this)}useNativeSearch=false;vectorColumn;vectorConfig="english";getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async search(e,t){let o=this.getTable(),n=[],r=this.getSoftDeleteConfig();r.enabled&&(t.options.onlyDeleted?n.push(isNotNull(this.getColumn(r.field))):t.options.withDeleted||n.push(isNull(this.getColumn(r.field))));for(let w of t.filters){let M=O(o,w);M&&n.push(M);}let s=this.getSearchableFields(),i=e.fields||Object.keys(s);if(this.useNativeSearch&&this.vectorColumn){let w=this.getColumn(this.vectorColumn),M=e.mode==="phrase"?sql`phraseto_tsquery(${this.vectorConfig}, ${e.query})`:e.mode==="all"?sql`plainto_tsquery(${this.vectorConfig}, ${e.query})`:sql`to_tsquery(${this.vectorConfig}, ${e.query.split(/\s+/).join(" | ")})`;n.push(sql`${w} @@ ${M}`);}else {let w=(M,x)=>{try{let re=this.getColumn(M);return $e(sql`CAST(${re} AS TEXT)`,x,this.dialect)}catch{return}};if(e.mode==="all"){let M=gt(e.query);if(M.length>0){let x=[];for(let re of M){let ue=i.map(se=>w(se,re)).filter(se=>se!==void 0);ue.length>0&&x.push(or(...ue));}x.length>0&&n.push(and(...x));}}else {let M=i.map(x=>w(x,e.query)).filter(x=>x!==void 0);M.length>0&&n.push(or(...M));}}let l=n.length>0?and(...n):void 0,d=await this.getDb().select({count:sql`count(*)`}).from(o).where(l),u=Number(d[0]?.count)||0,c=this.getDb().select().from(o).where(l);if(t.options.order_by){let w=this.getColumn(t.options.order_by),M=t.options.order_by_direction==="desc"?desc:asc;c=c.orderBy(M(w));}let m=t.options.page||1,p=t.options.per_page||this.defaultPerPage;c=c.limit(p).offset((m-1)*p);let g=await c,h=e.mode==="all"?{...e,mode:"any"}:e,y=U$1(g,h,s),R={relations:t.options.include||[]},$=y.map(w=>w.item),Xe=await S(this.getDb(),$,this._meta,R);return {items:y.map((w,M)=>({...w,item:Xe[M]})),totalCount:u}}},J=class extends ba{db;dialect="sqlite";getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async list(e){let t=this.getTable(),o=[],n=this.getSoftDeleteConfig();if(n.enabled){let h=this.getColumn(n.field);e.options.onlyDeleted?o.push(isNotNull(h)):e.options.withDeleted||o.push(isNull(h));}for(let h of e.filters){let y=O(t,h);y&&o.push(y);}if(e.options.search&&this.searchFields.length>0){let h=e.options.search,y=this.searchFields.map(R=>{let $=this.getColumn(R);return $e($,h,this.dialect)});o.push(or(...y));}let r=o.length>0?and(...o):void 0,s=await this.getDb().select({count:sql`count(*)`}).from(t).where(r),i=Number(s[0]?.count)||0,l=this.getDb().select().from(t).where(r);if(e.options.order_by){let h=this.getColumn(e.options.order_by),y=e.options.order_by_direction==="desc"?desc:asc;l=l.orderBy(y(h));}let d=e.options.page||1,u=e.options.per_page||this.defaultPerPage;l=l.limit(u).offset((d-1)*u);let c=await l,m={relations:e.options.include||[]},p=await S(this.getDb(),c,this._meta,m),g=Math.ceil(i/u);return {result:p,result_info:{page:d,per_page:u,total_count:i,total_pages:g,has_next_page:d<g,has_prev_page:d>1}}}},Y=class extends ca{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async findExisting(e){let t=this.getTable(),o=this.getUpsertKeys(),n=this.getSoftDeleteConfig(),r=[];for(let i of o){let l=e[i];l!==void 0&&r.push(eq(this.getColumn(i),l));}return n.enabled&&r.push(isNull(this.getColumn(n.field))),r.length===0?null:(await this.getDb().select().from(t).where(and(...r)).limit(1))[0]||null}async create(e){let t=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(t).values(o).returning())[0]}async update(e,t){let o=this.getTable(),n=this._meta.model.primaryKeys[0],r=e[n];return (await this.getDb().update(o).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(n),r)).returning())[0]}},ee=class extends y{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}generateId(){return crypto.randomUUID()}async findSource(e,t){let o=this.getTable(),n=this.getColumn(this.lookupField),r=this.getSoftDeleteConfig(),s=[eq(n,e)];if(t)for(let[l,d]of Object.entries(t))s.push(eq(this.getColumn(l),d));r.enabled&&s.push(isNull(this.getColumn(r.field)));let i=await this.getDb().select().from(o).where(and(...s)).limit(1);return i[0]?i[0]:null}async createClone(e){let t=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle",()=>this.generateId());return (await this.getDb().insert(t).values(o).returning())[0]}};function an(a,e,t){let o=t?.dialect??"sqlite";return {Create:class extends _{_meta=e;db=a},Read:class extends I{_meta=e;db=a},Update:class extends P{_meta=e;db=a},Delete:class extends U{_meta=e;db=a},List:class extends B{_meta=e;db=a},Restore:class extends L{_meta=e;db=a},Upsert:class extends Q{_meta=e;db=a;dialect=o},Search:class extends q{_meta=e;db=a;dialect=o},BatchCreate:class extends A{_meta=e;db=a},BatchUpdate:class extends K{_meta=e;db=a},BatchDelete:class extends Z{_meta=e;db=a},BatchRestore:class extends F{_meta=e;db=a},BatchUpsert:class extends N{_meta=e;db=a;dialect=o}}}var ne=null,We=false,te=null;async function oe(){if(We){if(te)throw te;return ne}We=true;try{return ne=await import('drizzle-zod'),ne}catch{throw te=new Error("drizzle-zod is not installed. Please install it: npm install drizzle-zod"),te}}async function mt(a,e){return (await oe()).createSelectSchema(a,e)}async function bt(a,e){return (await oe()).createInsertSchema(a,e)}async function ht(a,e){let t=await oe();return t.createUpdateSchema?t.createUpdateSchema(a,e):t.createInsertSchema(a,e).partial()}async function ft(a,e){let t=await oe(),o=e?.coerceDates!==false,n=o?Mt(a):new Set,r=t.createSelectSchema(a,e?.selectRefine),s=t.createInsertSchema(a,e?.insertRefine),i;return t.createUpdateSchema?i=t.createUpdateSchema(a,e?.updateRefine):i=t.createInsertSchema(a,e?.updateRefine).partial(),o&&n.size>0&&(s=Ve(s,n),i=Ve(i,n)),{select:r,insert:s,update:i}}function zt(){return ne!==null}var Dt=z.preprocess(a=>{if(a instanceof Date)return a;if(typeof a=="string"){let e=new Date(a);if(!isNaN(e.getTime()))return e}return a},z.date()),yt=z.preprocess(a=>{if(a==null)return null;if(a instanceof Date)return a;if(typeof a=="string"){let e=new Date(a);if(!isNaN(e.getTime()))return e}return a},z.date().nullable());function Mt(a){let e=new Set,t=a;for(let[o,n]of Object.entries(t)){if(o==="_"||o==="$inferInsert"||o==="$inferSelect")continue;let r=n;if(!r||typeof r!="object")continue;let s=String(r.dataType??"").toLowerCase(),i=String(r.columnType??"").toLowerCase(),l=r.config,d=String(l?.dataType??"").toLowerCase();(s.includes("timestamp")||s.includes("date")||s.includes("datetime")||i.includes("pgtimestamp")||i.includes("pgdate")||i.includes("mysqltimestamp")||i.includes("mysqldate")||i.includes("sqlitetimestamp")||d.includes("timestamp")||d.includes("date"))&&e.add(o);}return e}function Ve(a,e){if(e.size===0)return a;let t=a.shape,o={};for(let[n,r]of Object.entries(t))if(e.has(n)){let s=r.isOptional?.()??false,i=r.isNullable?.()??false,l=Dt;(i||s)&&(l=yt),s&&(l=l.optional()),o[n]=l;}else o[n]=r;return z.object(o)}var xn={CreateEndpoint:_,ListEndpoint:B,ReadEndpoint:I,UpdateEndpoint:P,DeleteEndpoint:U,RestoreEndpoint:L,BatchCreateEndpoint:A,BatchUpdateEndpoint:K,BatchDeleteEndpoint:Z,BatchRestoreEndpoint:F,BatchUpsertEndpoint:N,SearchEndpoint:q,AggregateEndpoint:H,ExportEndpoint:J,ImportEndpoint:Y,UpsertEndpoint:Q,CloneEndpoint:ee};export{J as A,Y as B,ee as C,an as D,mt as E,bt as F,ht as G,ft as H,zt as I,xn as J,X as a,f as b,b as c,Pe as d,le as e,S as f,O as g,_ as h,I as i,P as j,U as k,B as l,L as m,A as n,K as o,Z as p,F as q,$e as r,Q as s,N as t,Ae as u,Ke as v,Ze as w,Fe as x,H as y,q as z};