hono-crud 0.6.0 → 0.7.0
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 +2 -0
- package/dist/adapters/drizzle/index.d.ts +46 -28
- package/dist/adapters/drizzle/index.js +1 -4
- package/dist/adapters/memory/index.d.ts +2 -2
- package/dist/adapters/memory/index.js +1 -1
- package/dist/adapters/prisma/index.d.ts +41 -2
- package/dist/adapters/prisma/index.js +1 -1
- package/dist/bulk-patch-DG_5emFi.d.ts +57 -0
- package/dist/cache/index.js +1 -1
- package/dist/{chunk-3PFSX6M2.js → chunk-2U5ZQ7XQ.js} +1 -1
- package/dist/chunk-5UBOPX6O.js +4 -0
- package/dist/chunk-6P4Z6G35.js +1 -0
- package/dist/chunk-DLD4TRHM.js +1 -0
- package/dist/{chunk-K3XR44EH.js → chunk-QS6NQZH3.js} +1 -1
- package/dist/chunk-TP6RZ5RR.js +11 -0
- package/dist/{import-JN0uu97B.d.ts → import-D8nboMpT.d.ts} +76 -1
- package/dist/{index-KkWX8bsI.d.ts → index-EYmyKrzX.d.ts} +258 -3
- package/dist/index.d.ts +7 -4
- package/dist/index.js +2 -2
- package/dist/logging/index.js +1 -1
- package/dist/rate-limit/index.js +1 -1
- package/dist/storage/index.js +1 -1
- package/package.json +1 -1
- package/dist/bulk-patch-C9PIpw4R.d.ts +0 -132
- package/dist/chunk-2I6G2Q6U.js +0 -11
- package/dist/chunk-HCFP7RM6.js +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -22,6 +22,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
22
22
|
%b
|
|
23
23
|
%b
|
|
24
24
|
%b
|
|
25
|
+
%b
|
|
25
26
|
## [0.1.0] - 2025-01-29
|
|
26
27
|
|
|
27
28
|
### Added
|
|
@@ -61,3 +62,4 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
61
62
|
[0.5.2]: https://github.com/kshdotdev/hono-crud/compare/v0.5.1...v0.5.2
|
|
62
63
|
[0.5.3]: https://github.com/kshdotdev/hono-crud/compare/v0.5.2...v0.5.3
|
|
63
64
|
[0.6.0]: https://github.com/kshdotdev/hono-crud/compare/v0.5.3...v0.6.0
|
|
65
|
+
[0.7.0]: https://github.com/kshdotdev/hono-crud/compare/v0.6.0...v0.7.0
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { Table, SQL, Column } from 'drizzle-orm';
|
|
2
2
|
import { M as MetaInput, I as IncludeOptions, l as FilterCondition, f as RelationConfig, N as NestedUpdateInput, g as NestedWriteResult, L as ListFilters, P as PaginatedResult, h as AggregateOptions, i as AggregateResult, S as SearchOptions, j as SearchResult } from '../../types-tpG0M7Va.js';
|
|
3
3
|
import { Env } from 'hono';
|
|
4
|
-
import { a as CreateEndpoint, M as ModelObject, R as ReadEndpoint, U as UpdateEndpoint, D as DeleteEndpoint, L as ListEndpoint, b as RestoreEndpoint, B as BatchCreateEndpoint, c as BatchDeleteEndpoint, d as BatchRestoreEndpoint, e as BatchUpdateEndpoint, f as BatchUpdateItem, A as AggregateEndpoint, g as BatchUpsertEndpoint, h as UpsertEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint, V as VersionCompareEndpoint,
|
|
5
|
-
import { A as AdapterBundle } from '../../index-KkWX8bsI.js';
|
|
4
|
+
import { a as CreateEndpoint, M as ModelObject, R as ReadEndpoint, U as UpdateEndpoint, D as DeleteEndpoint, L as ListEndpoint, b as RestoreEndpoint, B as BatchCreateEndpoint, c as BatchDeleteEndpoint, d as BatchRestoreEndpoint, e as BatchUpdateEndpoint, f as BatchUpdateItem, A as AggregateEndpoint, g as BatchUpsertEndpoint, h as CloneEndpoint, i as UpsertEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint, V as VersionCompareEndpoint, j as VersionHistoryEndpoint, k as VersionReadEndpoint, l as VersionRollbackEndpoint } from '../../import-D8nboMpT.js';
|
|
6
5
|
import { z } from 'zod';
|
|
6
|
+
import { A as AdapterBundle } from '../../index-EYmyKrzX.js';
|
|
7
7
|
import '../../types-B5wq2iKZ.js';
|
|
8
8
|
import '../../types-BAcN7U0B.js';
|
|
9
9
|
import '@hono/zod-openapi';
|
|
@@ -642,6 +642,36 @@ declare abstract class DrizzleImportEndpoint<E extends Env = Env, M extends Meta
|
|
|
642
642
|
*/
|
|
643
643
|
update(existing: ModelObject<M['model']>, data: Partial<ModelObject<M['model']>>): Promise<ModelObject<M['model']>>;
|
|
644
644
|
}
|
|
645
|
+
/**
|
|
646
|
+
* Drizzle Clone endpoint.
|
|
647
|
+
*
|
|
648
|
+
* Reads the source row by `lookupField`, lets the base `CloneEndpoint`
|
|
649
|
+
* strip primary keys + `excludeFromClone` fields and apply body overrides,
|
|
650
|
+
* then inserts the result with a freshly-generated primary key.
|
|
651
|
+
*
|
|
652
|
+
* Soft-deleted source rows are not cloneable — the SELECT predicate adds
|
|
653
|
+
* `IS NULL` on the soft-delete column when the model has soft-delete
|
|
654
|
+
* configured.
|
|
655
|
+
*
|
|
656
|
+
* Composite-PK note: the base class strips ALL primary keys but this
|
|
657
|
+
* implementation only fills `primaryKeys[0]` via `generateId()`. Models with
|
|
658
|
+
* composite primary keys must subclass and override `createClone` to fill the
|
|
659
|
+
* remaining columns.
|
|
660
|
+
*
|
|
661
|
+
* Override `generateId()` to swap UUIDv4 for ULID/snowflake/etc.
|
|
662
|
+
*/
|
|
663
|
+
declare abstract class DrizzleCloneEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends CloneEndpoint<E, M> {
|
|
664
|
+
/** Drizzle database instance. Can be undefined if using context injection. */
|
|
665
|
+
db?: DrizzleDatabase;
|
|
666
|
+
/** Gets the database instance from property or context. */
|
|
667
|
+
protected getDb(): DrizzleDatabase;
|
|
668
|
+
protected getTable(): Table;
|
|
669
|
+
protected getColumn(field: string): Column;
|
|
670
|
+
/** Generates the primary-key value for the cloned row. Defaults to UUIDv4. */
|
|
671
|
+
protected generateId(): string;
|
|
672
|
+
findSource(lookupValue: string, additionalFilters?: Record<string, string>): Promise<ModelObject<M['model']> | null>;
|
|
673
|
+
createClone(data: ModelObject<M['model']>): Promise<ModelObject<M['model']>>;
|
|
674
|
+
}
|
|
645
675
|
|
|
646
676
|
/**
|
|
647
677
|
* Return type of createDrizzleCrud factory function.
|
|
@@ -693,31 +723,6 @@ interface DrizzleCrudClasses<M extends MetaInput, E extends Env = Env> {
|
|
|
693
723
|
* ```
|
|
694
724
|
*/
|
|
695
725
|
declare function createDrizzleCrud<M extends MetaInput, E extends Env = Env>(db: DrizzleDatabaseConstraint, meta: M): DrizzleCrudClasses<M, E>;
|
|
696
|
-
/**
|
|
697
|
-
* Drizzle adapter bundle for use with defineEndpoints.
|
|
698
|
-
*
|
|
699
|
-
* Note: When using DrizzleAdapters with defineEndpoints, you need to provide
|
|
700
|
-
* your own base classes that extend the Drizzle endpoint classes and include
|
|
701
|
-
* the `db` property. The config-based API cannot inject the database instance.
|
|
702
|
-
*
|
|
703
|
-
* @example
|
|
704
|
-
* ```ts
|
|
705
|
-
* import { defineEndpoints } from 'hono-crud';
|
|
706
|
-
* import { DrizzleAdapters } from 'hono-crud/adapters/drizzle';
|
|
707
|
-
*
|
|
708
|
-
* // Create custom adapters with db injected
|
|
709
|
-
* const MyDrizzleAdapters = {
|
|
710
|
-
* CreateEndpoint: class extends DrizzleCreateEndpoint { db = myDb; },
|
|
711
|
-
* ListEndpoint: class extends DrizzleListEndpoint { db = myDb; },
|
|
712
|
-
* ReadEndpoint: class extends DrizzleReadEndpoint { db = myDb; },
|
|
713
|
-
* UpdateEndpoint: class extends DrizzleUpdateEndpoint { db = myDb; },
|
|
714
|
-
* DeleteEndpoint: class extends DrizzleDeleteEndpoint { db = myDb; },
|
|
715
|
-
* };
|
|
716
|
-
*
|
|
717
|
-
* const userEndpoints = defineEndpoints({ meta: userMeta, ... }, MyDrizzleAdapters);
|
|
718
|
-
* ```
|
|
719
|
-
*/
|
|
720
|
-
declare const DrizzleAdapters: AdapterBundle;
|
|
721
726
|
|
|
722
727
|
/**
|
|
723
728
|
* Drizzle-Zod schema utilities.
|
|
@@ -883,4 +888,17 @@ declare function createDrizzleSchemas<T extends DrizzleTable>(table: T, options?
|
|
|
883
888
|
*/
|
|
884
889
|
declare function isDrizzleZodAvailable(): boolean;
|
|
885
890
|
|
|
886
|
-
|
|
891
|
+
/**
|
|
892
|
+
* Drizzle adapter bundle for use with `defineEndpoints`.
|
|
893
|
+
*
|
|
894
|
+
* Populates the 11 verbs Drizzle implements natively plus a stub
|
|
895
|
+
* `CloneEndpoint` (throws on request — subclass to implement).
|
|
896
|
+
*
|
|
897
|
+
* @example
|
|
898
|
+
* ```ts
|
|
899
|
+
* const endpoints = defineEndpoints({ meta, create: {}, search: { fields: ['name'] } }, DrizzleAdapters);
|
|
900
|
+
* ```
|
|
901
|
+
*/
|
|
902
|
+
declare const DrizzleAdapters: AdapterBundle;
|
|
903
|
+
|
|
904
|
+
export { type Database, DrizzleAdapters, DrizzleAggregateEndpoint, DrizzleBatchCreateEndpoint, DrizzleBatchDeleteEndpoint, DrizzleBatchRestoreEndpoint, DrizzleBatchUpdateEndpoint, DrizzleBatchUpsertEndpoint, DrizzleCloneEndpoint, DrizzleCreateEndpoint, type DrizzleCrudClasses, type DrizzleDB, type DrizzleDatabase, type DrizzleDatabaseConstraint, DrizzleDeleteEndpoint, type DrizzleEnv, DrizzleExportEndpoint, DrizzleImportEndpoint, DrizzleListEndpoint, DrizzleReadEndpoint, DrizzleRestoreEndpoint, type DrizzleSchemas, DrizzleSearchEndpoint, DrizzleUpdateEndpoint, DrizzleUpsertEndpoint, DrizzleVersionCompareEndpoint, DrizzleVersionHistoryEndpoint, DrizzleVersionReadEndpoint, DrizzleVersionRollbackEndpoint, type QueryBuilder, batchLoadDrizzleRelations, buildWhereCondition, cast, createDrizzleCrud, createDrizzleSchemas, createInsertSchema, createSelectSchema, createUpdateSchema, getColumn, getTable, isDrizzleZodAvailable, loadDrizzleRelation, loadDrizzleRelations };
|
|
@@ -1,4 +1 @@
|
|
|
1
|
-
|
|
2
|
-
1. Set db property: db = myDb;
|
|
3
|
-
2. Use middleware: c.set("db", myDb);
|
|
4
|
-
3. Use factory: createDrizzleCrud(db, meta)`)}var S=class extends k{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getRelatedTable(e){return e.table}async create(e,o){let n=o??this.getDb(),t=this.getTable(),r=this._meta.model.primaryKeys[0],s={...e,[r]:e[r]||crypto.randomUUID()};return (await n.insert(t).values(s).returning())[0]}async createNested(e,o,n,t,r){let s=r??this.getDb(),a=this.getRelatedTable(n);if(!a)return b().warn(`Related table not found for ${o}. Add 'table' to the relation config.`),[];let i=Array.isArray(t)?t:[t],u=[];for(let d of i){if(typeof d!="object"||d===null)continue;let c={...d,id:crypto.randomUUID(),[n.foreignKey]:e},g=await s.insert(a).values(c).returning();g[0]&&u.push(g[0]);}return u}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()}},_=class extends l{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async read(e,o,n){let t=this.getTable(),r=this.getColumn(this.lookupField),s=this.getSoftDeleteConfig(),a=[eq(r,e)];if(o)for(let[d,c]of Object.entries(o))a.push(eq(this.getColumn(d),c));s.enabled&&a.push(isNull(this.getColumn(s.field)));let i=await this.getDb().select().from(t).where(and(...a)).limit(1);return i[0]?await ee(this.getDb(),i[0],this._meta,n):null}},I=class extends m$1{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}getRelatedTable(e){return e.table}async findExisting(e,o,n){let t=n??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),i=[eq(s,e)];if(o)for(let[d,c]of Object.entries(o))i.push(eq(this.getColumn(d),c));return a.enabled&&i.push(isNull(this.getColumn(a.field))),(await t.select().from(r).where(and(...i)).limit(1))[0]||null}async update(e,o,n,t){let r=t??this.getDb(),s=this.getTable(),a=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),u=[eq(a,e)];if(n)for(let[c,g]of Object.entries(n))u.push(eq(this.getColumn(c),g));return i.enabled&&u.push(isNull(this.getColumn(i.field))),(await r.update(s).set(o).where(and(...u)).returning())[0]||null}async processNestedWrites(e,o,n,t,r){let s=r??this.getDb(),a=this.getRelatedTable(n);if(!a)return b().warn(`Related table not found for ${o}. Add 'table' to the relation config.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]};let i={created:[],updated:[],deleted:[],connected:[],disconnected:[]},u=m(a,n.foreignKey),d=m(a,"id");if(t.create){let c=Array.isArray(t.create)?t.create:[t.create];for(let g of c){if(typeof g!="object"||g===null)continue;let p={...g,id:crypto.randomUUID(),[n.foreignKey]:e},b=await s.insert(a).values(p).returning();b[0]&&i.created.push(b[0]);}}if(t.update)for(let c of t.update){if(!c.id||!(await s.select().from(a).where(and(eq(d,c.id),eq(u,e))).limit(1))[0])continue;let{id:p,...b}=c,y=await s.update(a).set(b).where(eq(d,p)).returning();y[0]&&i.updated.push(y[0]);}if(t.delete)for(let c of t.delete)(await s.delete(a).where(and(eq(d,c),eq(u,e))).returning())[0]&&i.deleted.push(c);if(t.connect)for(let c of t.connect)(await s.update(a).set({[n.foreignKey]:e}).where(eq(d,c)).returning())[0]&&i.connected.push(c);if(t.disconnect)for(let c of t.disconnect)(await s.update(a).set({[n.foreignKey]:null}).where(and(eq(d,c),eq(u,e))).returning())[0]&&i.disconnected.push(c);return i}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()}},P=class extends n{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}getRelatedTable(e){return e.table}async findForDelete(e,o,n){let t=n??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),i=[eq(s,e)];if(o)for(let[d,c]of Object.entries(o))i.push(eq(this.getColumn(d),c));return a.enabled&&i.push(isNull(this.getColumn(a.field))),(await t.select().from(r).where(and(...i)).limit(1))[0]||null}async delete(e,o,n){let t=n??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),i=[eq(s,e)];if(o)for(let[u,d]of Object.entries(o))i.push(eq(this.getColumn(u),d));return a.enabled&&i.push(isNull(this.getColumn(a.field))),a.enabled?(await t.update(r).set({[a.field]:new Date}).where(and(...i)).returning())[0]||null:(await t.delete(r).where(and(...i)).returning())[0]||null}async countRelated(e,o,n,t){let r=t??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let a=m(s,n.foreignKey),i=await r.select({count:sql`count(*)`}).from(s).where(eq(a,e));return Number(i[0]?.count)||0}async deleteRelated(e,o,n,t){let r=t??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let a=m(s,n.foreignKey);return (await r.delete(s).where(eq(a,e)).returning()).length}async nullifyRelated(e,o,n,t){let r=t??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let a=m(s,n.foreignKey);return (await r.update(s).set({[n.foreignKey]:null}).where(eq(a,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()}},U=class extends o{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async list(e){let o=this.getTable(),n=[],t=this.getSoftDeleteConfig();if(t.enabled){let z=this.getColumn(t.field);e.options.onlyDeleted?n.push(isNotNull(z)):e.options.withDeleted||n.push(isNull(z));}for(let z of e.filters){let R=x(o,z);R&&n.push(R);}if(e.options.search&&this.searchFields.length>0){let z=this.searchFields.map(R=>{let H=this.getColumn(R);return sql`LOWER(${H}) LIKE LOWER(${`%${e.options.search}%`})`});n.push(or(...z));}let r=n.length>0?and(...n):void 0,s=this.getDb(),a=await s.select({count:sql`count(*)`}).from(o).where(r),i=Number(a[0]?.count)||0,u=s.select().from(o).where(r);if(e.options.order_by){let z=this.getColumn(e.options.order_by),R=e.options.order_by_direction==="desc"?desc:asc;u=u.orderBy(R(z));}let d=e.options.page||1,c=e.options.per_page||this.defaultPerPage;u=u.limit(c).offset((d-1)*c);let g=await u,p={relations:e.options.include||[]},b=await O(this.getDb(),g,this._meta,p),y=Math.ceil(i/c);return {result:b,result_info:{page:d,per_page:c,total_count:i,total_pages:y,has_next_page:d<y,has_prev_page:d>1}}}},B=class extends p{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async restore(e,o,n){let t=n??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),i=[eq(s,e)];if(o)for(let[d,c]of Object.entries(o))i.push(eq(this.getColumn(d),c));return i.push(isNotNull(this.getColumn(a.field))),(await t.update(r).set({[a.field]:null}).where(and(...i)).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 Q=class extends r{db;getDb(){return D(this)}getTable(){return f(this._meta)}async batchCreate(e){let o=this.getTable(),n=this._meta.model.primaryKeys[0],t=e.map(s=>({...s,[n]:s[n]||crypto.randomUUID()}));return await this.getDb().insert(o).values(t).returning()}},N=class extends s{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async batchUpdate(e){let o=this.getTable(),n=this.getColumn(this.lookupField),t=this.getSoftDeleteConfig(),r=[],s=[];for(let a of e){let i=[eq(n,a.id)];t.enabled&&i.push(isNull(this.getColumn(t.field)));let u=await this.getDb().update(o).set(a.data).where(and(...i)).returning();u[0]?r.push(u[0]):s.push(a.id);}return {updated:r,notFound:s}}},F=class extends t{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async batchDelete(e){let o=this.getTable(),n=this.getColumn(this.lookupField),t=this.getSoftDeleteConfig(),r=[inArray(n,e)];t.enabled&&r.push(isNull(this.getColumn(t.field)));let s;t.enabled?s=await this.getDb().update(o).set({[t.field]:new Date}).where(and(...r)).returning():s=await this.getDb().delete(o).where(and(...r)).returning();let a=s,i=new Set(a.map(d=>String(d[this.lookupField]))),u=e.filter(d=>!i.has(d));return {deleted:a,notFound:u}}},$=class extends u{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async batchRestore(e){let o=this.getTable(),n=this.getColumn(this.lookupField),t=this.getSoftDeleteConfig(),r=[inArray(n,e),isNotNull(this.getColumn(t.field))],a=await this.getDb().update(o).set({[t.field]:null}).where(and(...r)).returning(),i=new Set(a.map(d=>String(d[this.lookupField]))),u=e.filter(d=>!i.has(d));return {restored:a,notFound:u}}};var q=class extends q$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async findExisting(e){let o=this.getTable(),n=this.getUpsertKeys(),t=this.getSoftDeleteConfig(),r=[];for(let a of n){let i=e[a];i!==void 0&&r.push(eq(this.getColumn(a),i));}return t.enabled&&r.push(isNull(this.getColumn(t.field))),r.length===0?null:(await this.getDb().select().from(o).where(and(...r)).limit(1))[0]||null}async create(e){let o=this.getTable(),n=this._meta.model.primaryKeys[0],t={...e,[n]:e[n]||crypto.randomUUID()};return (await this.getDb().insert(o).values(t).returning())[0]}async update(e,o){let n=this.getTable(),t=this._meta.model.primaryKeys[0],r=e[t];return (await this.getDb().update(n).set(o).where(eq(this.getColumn(t),r)).returning())[0]}async nativeUpsert(e,o){let n=this.getTable(),t=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s=this.getSoftDeleteConfig(),a={...e,[r]:e[r]||crypto.randomUUID()},i={};for(let[c,g]of Object.entries(e))!t.includes(c)&&c!==r&&(this.createOnlyFields?.includes(c)||(i[c]=g));let u=t.map(c=>this.getColumn(c)),d;s.enabled&&(d=isNull(this.getColumn(s.field)));try{return {data:(await this.getDb().insert(n).values(a).onConflictDoUpdate({target:u,set:Object.keys(i).length>0?i:{[r]:sql`${this.getColumn(r)}`},where:d}).returning())[0],created:!1}}catch(c){if(c instanceof Error&&c.message.includes("onConflictDoUpdate"))try{return {data:(await this.getDb().insert(n).values(a).onDuplicateKeyUpdate({set:Object.keys(i).length>0?i:{[r]:sql`${this.getColumn(r)}`}}).returning())[0],created:!1}}catch{return this.performStandardUpsert(e,o)}throw c}}},W=class extends v{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async findExisting(e){let o=this.getTable(),n=this.getUpsertKeys(),t=[];for(let s of n){let a=e[s];a!==void 0&&t.push(eq(this.getColumn(s),a));}return t.length===0?null:(await this.getDb().select().from(o).where(and(...t)).limit(1))[0]||null}async create(e){let o=this.getTable(),n=this._meta.model.primaryKeys[0],t={...e,[n]:e[n]||crypto.randomUUID()};return (await this.getDb().insert(o).values(t).returning())[0]}async update(e,o){let n=this.getTable(),t=this._meta.model.primaryKeys[0],r=e[t];return (await this.getDb().update(n).set(o).where(eq(this.getColumn(t),r)).returning())[0]}async nativeBatchUpsert(e,o){if(e.length===0)return {items:[],createdCount:0,updatedCount:0,totalCount:0};let n=this.getTable(),t=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s=e.map(d=>({...d,[r]:d[r]||crypto.randomUUID()})),a={},i=e[0];for(let d of Object.keys(i))!t.includes(d)&&d!==r&&(this.createOnlyFields?.includes(d)||(a[d]=sql`excluded.${sql.identifier(d)}`));let u=t.map(d=>this.getColumn(d));try{let c=await this.getDb().insert(n).values(s).onConflictDoUpdate({target:u,set:Object.keys(a).length>0?a:{[r]:sql`${this.getColumn(r)}`}}).returning();return {items:c.map((g,p)=>({data:g,created:!1,index:p})),createdCount:0,updatedCount:c.length,totalCount:c.length}}catch(d){if(d instanceof Error&&d.message.includes("onConflictDoUpdate"))try{let g=await this.getDb().insert(n).values(s).onDuplicateKeyUpdate({set:Object.keys(a).length>0?a:{[r]:sql`${this.getColumn(r)}`}}).returning();return {items:g.map((p,b)=>({data:p,created:!1,index:b})),createdCount:0,updatedCount:g.length,totalCount:g.length}}catch{return this.performStandardBatchUpsert(e,o)}throw d}}},ke=class extends w{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async recordExists(e){let o=this.getTable(),n=await this.getDb().select({count:sql`count(*)`}).from(o).where(eq(this.getColumn("id"),e));return Number(n[0]?.count)>0}},Oe=class extends x$1{},ve=class extends y{},je=class extends z$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async rollback(e,o,n){let t=this.getTable(),r=this.getVersioningConfig().field;return (await this.getDb().update(t).set({...o,[r]:n}).where(eq(this.getColumn("id"),e)).returning())[0]}},Se=class extends A{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async aggregate(e){let o=this.getTable(),n=[],t=this.getSoftDeleteConfig();if(t.enabled){let{query:a}=await this.getValidatedData();a?.withDeleted===true||a?.withDeleted==="true"||n.push(isNull(this.getColumn(t.field)));}if(e.filters)for(let[a,i]of Object.entries(e.filters))if(typeof i=="object"&&i!==null)for(let[u,d]of Object.entries(i)){let c=x(o,{field:a,operator:u,value:d});c&&n.push(c);}else n.push(eq(this.getColumn(a),i));let r=n.length>0?and(...n):void 0,s=await this.getDb().select().from(o).where(r);return B$1(s,e)}},_e=class extends J{db;getDb(){return D(this)}useNativeSearch=false;vectorColumn;vectorConfig="english";getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async search(e,o){let n=this.getTable(),t=[],r=this.getSoftDeleteConfig();r.enabled&&(o.options.onlyDeleted?t.push(isNotNull(this.getColumn(r.field))):o.options.withDeleted||t.push(isNull(this.getColumn(r.field))));for(let w of o.filters){let C=x(n,w);C&&t.push(C);}let s=this.getSearchableFields(),a=e.fields||Object.keys(s);if(this.useNativeSearch&&this.vectorColumn){let w=this.getColumn(this.vectorColumn),C=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(" | ")})`;t.push(sql`${w} @@ ${C}`);}else {let w=a.map(C=>{try{let Qe=this.getColumn(C);return sql`LOWER(CAST(${Qe} AS TEXT)) LIKE LOWER(${`%${e.query}%`})`}catch{return}}).filter(C=>C!==void 0);w.length>0&&(e.mode==="all"?t.push(and(...w)):t.push(or(...w)));}let i=t.length>0?and(...t):void 0,u=await this.getDb().select({count:sql`count(*)`}).from(n).where(i),d=Number(u[0]?.count)||0,c=this.getDb().select().from(n).where(i);if(o.options.order_by){let w=this.getColumn(o.options.order_by),C=o.options.order_by_direction==="desc"?desc:asc;c=c.orderBy(C(w));}let g=o.options.page||1,p=o.options.per_page||this.defaultPerPage;c=c.limit(p).offset((g-1)*p);let b=await c,y=K(b,e,s),z={relations:o.options.include||[]},R=y.map(w=>w.item),H=await O(this.getDb(),R,this._meta,z);return {items:y.map((w,C)=>({...w,item:H[C]})),totalCount:d}}},Ie=class extends T{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async list(e){let o=this.getTable(),n=[],t=this.getSoftDeleteConfig();if(t.enabled){let y=this.getColumn(t.field);e.options.onlyDeleted?n.push(isNotNull(y)):e.options.withDeleted||n.push(isNull(y));}for(let y of e.filters){let z=x(o,y);z&&n.push(z);}if(e.options.search&&this.searchFields.length>0){let y=this.searchFields.map(z=>{let R=this.getColumn(z);return sql`LOWER(${R}) LIKE LOWER(${`%${e.options.search}%`})`});n.push(or(...y));}let r=n.length>0?and(...n):void 0,s=await this.getDb().select({count:sql`count(*)`}).from(o).where(r),a=Number(s[0]?.count)||0,i=this.getDb().select().from(o).where(r);if(e.options.order_by){let y=this.getColumn(e.options.order_by),z=e.options.order_by_direction==="desc"?desc:asc;i=i.orderBy(z(y));}let u=e.options.page||1,d=e.options.per_page||this.defaultPerPage;i=i.limit(d).offset((u-1)*d);let c=await i,g={relations:e.options.include||[]},p=await O(this.getDb(),c,this._meta,g),b=Math.ceil(a/d);return {result:p,result_info:{page:u,per_page:d,total_count:a,total_pages:b,has_next_page:u<b,has_prev_page:u>1}}}},Pe=class extends U$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async findExisting(e){let o=this.getTable(),n=this.getUpsertKeys(),t=this.getSoftDeleteConfig(),r=[];for(let a of n){let i=e[a];i!==void 0&&r.push(eq(this.getColumn(a),i));}return t.enabled&&r.push(isNull(this.getColumn(t.field))),r.length===0?null:(await this.getDb().select().from(o).where(and(...r)).limit(1))[0]||null}async create(e){let o=this.getTable(),n=this._meta.model.primaryKeys[0],t={...e,[n]:e[n]||crypto.randomUUID()};return (await this.getDb().insert(o).values(t).returning())[0]}async update(e,o){let n=this.getTable(),t=this._meta.model.primaryKeys[0],r=e[t];return (await this.getDb().update(n).set(o).where(eq(this.getColumn(t),r)).returning())[0]}};function Ht(l,e){return {Create:class extends S{_meta=e;db=l},Read:class extends _{_meta=e;db=l},Update:class extends I{_meta=e;db=l},Delete:class extends P{_meta=e;db=l},List:class extends U{_meta=e;db=l},Restore:class extends B{_meta=e;db=l},Upsert:class extends q{_meta=e;db=l},BatchCreate:class extends Q{_meta=e;db=l},BatchUpdate:class extends N{_meta=e;db=l},BatchDelete:class extends F{_meta=e;db=l},BatchRestore:class extends ${_meta=e;db=l},BatchUpsert:class extends W{_meta=e;db=l}}}var Jt={CreateEndpoint:S,ListEndpoint:U,ReadEndpoint:_,UpdateEndpoint:I,DeleteEndpoint:P};var X=null,Be=false,V=null;async function G(){if(Be){if(V)throw V;return X}Be=true;try{return X=await import('drizzle-zod'),X}catch{throw V=new Error("drizzle-zod is not installed. Please install it: npm install drizzle-zod"),V}}async function at(l,e){return (await G()).createSelectSchema(l,e)}async function it(l,e){return (await G()).createInsertSchema(l,e)}async function lt(l,e){let o=await G();return o.createUpdateSchema?o.createUpdateSchema(l,e):o.createInsertSchema(l,e).partial()}async function dt(l,e){let o=await G(),n=e?.coerceDates!==false,t=n?gt(l):new Set,r=o.createSelectSchema(l,e?.selectRefine),s=o.createInsertSchema(l,e?.insertRefine),a;return o.createUpdateSchema?a=o.createUpdateSchema(l,e?.updateRefine):a=o.createInsertSchema(l,e?.updateRefine).partial(),n&&t.size>0&&(s=Ze(s,t),a=Ze(a,t)),{select:r,insert:s,update:a}}function ct(){return X!==null}var ut=z.preprocess(l=>{if(l instanceof Date)return l;if(typeof l=="string"){let e=new Date(l);if(!isNaN(e.getTime()))return e}return l},z.date()),pt=z.preprocess(l=>{if(l==null)return null;if(l instanceof Date)return l;if(typeof l=="string"){let e=new Date(l);if(!isNaN(e.getTime()))return e}return l},z.date().nullable());function gt(l){let e=new Set,o=l;for(let[n,t]of Object.entries(o)){if(n==="_"||n==="$inferInsert"||n==="$inferSelect")continue;let r=t;if(!r||typeof r!="object")continue;let s=String(r.dataType??"").toLowerCase(),a=String(r.columnType??"").toLowerCase(),i=r.config,u=String(i?.dataType??"").toLowerCase();(s.includes("timestamp")||s.includes("date")||s.includes("datetime")||a.includes("pgtimestamp")||a.includes("pgdate")||a.includes("mysqltimestamp")||a.includes("mysqldate")||a.includes("sqlitetimestamp")||u.includes("timestamp")||u.includes("date"))&&e.add(n);}return e}function Ze(l,e){if(e.size===0)return l;let o=l.shape,n={};for(let[t,r]of Object.entries(o))if(e.has(t)){let s=r.isOptional?.()??false,a=r.isNullable?.()??false,i=ut;(a||s)&&(i=pt),s&&(i=i.optional()),n[t]=i;}else n[t]=r;return z.object(n)}export{Jt as DrizzleAdapters,Se as DrizzleAggregateEndpoint,Q as DrizzleBatchCreateEndpoint,F as DrizzleBatchDeleteEndpoint,$ as DrizzleBatchRestoreEndpoint,N as DrizzleBatchUpdateEndpoint,W as DrizzleBatchUpsertEndpoint,S as DrizzleCreateEndpoint,P as DrizzleDeleteEndpoint,Ie as DrizzleExportEndpoint,Pe as DrizzleImportEndpoint,U as DrizzleListEndpoint,_ as DrizzleReadEndpoint,B as DrizzleRestoreEndpoint,_e as DrizzleSearchEndpoint,I as DrizzleUpdateEndpoint,q as DrizzleUpsertEndpoint,ve as DrizzleVersionCompareEndpoint,ke as DrizzleVersionHistoryEndpoint,Oe as DrizzleVersionReadEndpoint,je as DrizzleVersionRollbackEndpoint,O as batchLoadDrizzleRelations,x as buildWhereCondition,L as cast,Ht as createDrizzleCrud,dt as createDrizzleSchemas,it as createInsertSchema,at as createSelectSchema,lt as createUpdateSchema,m as getColumn,f as getTable,ct as isDrizzleZodAvailable,Te as loadDrizzleRelation,ee as loadDrizzleRelations};
|
|
1
|
+
export{I as DrizzleAdapters,x as DrizzleAggregateEndpoint,n as DrizzleBatchCreateEndpoint,p as DrizzleBatchDeleteEndpoint,q as DrizzleBatchRestoreEndpoint,o as DrizzleBatchUpdateEndpoint,s as DrizzleBatchUpsertEndpoint,B as DrizzleCloneEndpoint,h as DrizzleCreateEndpoint,k as DrizzleDeleteEndpoint,z as DrizzleExportEndpoint,A as DrizzleImportEndpoint,l as DrizzleListEndpoint,i as DrizzleReadEndpoint,m as DrizzleRestoreEndpoint,y as DrizzleSearchEndpoint,j as DrizzleUpdateEndpoint,r as DrizzleUpsertEndpoint,v as DrizzleVersionCompareEndpoint,t as DrizzleVersionHistoryEndpoint,u as DrizzleVersionReadEndpoint,w as DrizzleVersionRollbackEndpoint,f as batchLoadDrizzleRelations,g as buildWhereCondition,a as cast,C as createDrizzleCrud,G as createDrizzleSchemas,E as createInsertSchema,D as createSelectSchema,F as createUpdateSchema,c as getColumn,b as getTable,H as isDrizzleZodAvailable,d as loadDrizzleRelation,e as loadDrizzleRelations}from'../../chunk-5UBOPX6O.js';import'../../chunk-TP6RZ5RR.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-3TIIYAKB.js';import'../../chunk-7NM6MBRL.js';import'../../chunk-FC56WWPB.js';import'../../chunk-ANWSQPCQ.js';import'../../chunk-Z575OBLV.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,7 +1,7 @@
|
|
|
1
1
|
import { Env } from 'hono';
|
|
2
|
-
import { a as CreateEndpoint, M as ModelObject, D as DeleteEndpoint, L as ListEndpoint, R as ReadEndpoint, b as RestoreEndpoint, U as UpdateEndpoint, B as BatchCreateEndpoint, c as BatchDeleteEndpoint, d as BatchRestoreEndpoint, e as BatchUpdateEndpoint, f as BatchUpdateItem, g as BatchUpsertEndpoint, A as AggregateEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint,
|
|
2
|
+
import { a as CreateEndpoint, M as ModelObject, D as DeleteEndpoint, L as ListEndpoint, R as ReadEndpoint, b as RestoreEndpoint, U as UpdateEndpoint, B as BatchCreateEndpoint, c as BatchDeleteEndpoint, d as BatchRestoreEndpoint, e as BatchUpdateEndpoint, f as BatchUpdateItem, g as BatchUpsertEndpoint, A as AggregateEndpoint, h as CloneEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint, i as UpsertEndpoint, V as VersionCompareEndpoint, j as VersionHistoryEndpoint, k as VersionReadEndpoint, l as VersionRollbackEndpoint } from '../../import-D8nboMpT.js';
|
|
3
3
|
import { M as MetaInput, f as RelationConfig, L as ListFilters, P as PaginatedResult, I as IncludeOptions, N as NestedUpdateInput, g as NestedWriteResult, h as AggregateOptions, i as AggregateResult, S as SearchOptions, j as SearchResult } from '../../types-tpG0M7Va.js';
|
|
4
|
-
import { B as BulkPatchEndpoint
|
|
4
|
+
import { B as BulkPatchEndpoint } from '../../bulk-patch-DG_5emFi.js';
|
|
5
5
|
import 'zod';
|
|
6
6
|
import '../../route-AzM3iPZP.js';
|
|
7
7
|
import 'hono/utils/http-status';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{
|
|
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-6P4Z6G35.js';import'../../chunk-TP6RZ5RR.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-3TIIYAKB.js';import'../../chunk-7NM6MBRL.js';import'../../chunk-FC56WWPB.js';import'../../chunk-ANWSQPCQ.js';import'../../chunk-Z575OBLV.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,6 +1,7 @@
|
|
|
1
1
|
import { Env } from 'hono';
|
|
2
|
-
import { a as CreateEndpoint, M as ModelObject, D as DeleteEndpoint, L as ListEndpoint, R as ReadEndpoint, U as UpdateEndpoint, B as BatchCreateEndpoint, c as BatchDeleteEndpoint, d as BatchRestoreEndpoint, e as BatchUpdateEndpoint, f as BatchUpdateItem, g as BatchUpsertEndpoint, b as RestoreEndpoint, A as AggregateEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint,
|
|
2
|
+
import { a as CreateEndpoint, M as ModelObject, D as DeleteEndpoint, L as ListEndpoint, R as ReadEndpoint, U as UpdateEndpoint, B as BatchCreateEndpoint, c as BatchDeleteEndpoint, d as BatchRestoreEndpoint, e as BatchUpdateEndpoint, f as BatchUpdateItem, g as BatchUpsertEndpoint, b as RestoreEndpoint, A as AggregateEndpoint, h as CloneEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint, i as UpsertEndpoint, V as VersionCompareEndpoint, j as VersionHistoryEndpoint, k as VersionReadEndpoint, l as VersionRollbackEndpoint } from '../../import-D8nboMpT.js';
|
|
3
3
|
import { M as MetaInput, L as ListFilters, P as PaginatedResult, I as IncludeOptions, h as AggregateOptions, i as AggregateResult, k as AggregateField, S as SearchOptions, j as SearchResult } from '../../types-tpG0M7Va.js';
|
|
4
|
+
import { A as AdapterBundle } from '../../index-EYmyKrzX.js';
|
|
4
5
|
import 'zod';
|
|
5
6
|
import '../../route-AzM3iPZP.js';
|
|
6
7
|
import 'hono/utils/http-status';
|
|
@@ -405,5 +406,43 @@ declare abstract class PrismaAggregateEndpoint<E extends Env = Env, M extends Me
|
|
|
405
406
|
*/
|
|
406
407
|
protected aggregateWithGroupBy(model: PrismaModelOperations, where: Record<string, unknown>, options: AggregateOptions): Promise<AggregateResult>;
|
|
407
408
|
}
|
|
409
|
+
/**
|
|
410
|
+
* Prisma Clone endpoint.
|
|
411
|
+
*
|
|
412
|
+
* Reads the source row by `lookupField`, lets the base `CloneEndpoint`
|
|
413
|
+
* strip primary keys + `excludeFromClone` fields and apply body overrides,
|
|
414
|
+
* then inserts the result with a freshly-generated primary key.
|
|
415
|
+
*
|
|
416
|
+
* Soft-deleted source rows are not cloneable — the WHERE clause adds a
|
|
417
|
+
* `<field>: null` predicate when the model has soft-delete configured.
|
|
418
|
+
*
|
|
419
|
+
* Composite-PK note: the base class strips ALL primary keys but this
|
|
420
|
+
* implementation only fills `primaryKeys[0]` via `generateId()`. Models with
|
|
421
|
+
* composite primary keys must subclass and override `createClone` to fill the
|
|
422
|
+
* remaining columns.
|
|
423
|
+
*
|
|
424
|
+
* Override `generateId()` to swap UUIDv4 for ULID/snowflake/etc.
|
|
425
|
+
*/
|
|
426
|
+
declare abstract class PrismaCloneEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends CloneEndpoint<E, M> {
|
|
427
|
+
abstract prisma: PrismaClient;
|
|
428
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
429
|
+
/** Generates the primary-key value for the cloned row. Defaults to UUIDv4. */
|
|
430
|
+
protected generateId(): string;
|
|
431
|
+
findSource(lookupValue: string, additionalFilters?: Record<string, string>): Promise<ModelObject<M['model']> | null>;
|
|
432
|
+
createClone(data: ModelObject<M['model']>): Promise<ModelObject<M['model']>>;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/**
|
|
436
|
+
* Prisma adapter bundle for use with `defineEndpoints`.
|
|
437
|
+
*
|
|
438
|
+
* Populates the 11 verbs Prisma implements natively plus a stub
|
|
439
|
+
* `CloneEndpoint` (throws on request — subclass to implement).
|
|
440
|
+
*
|
|
441
|
+
* @example
|
|
442
|
+
* ```ts
|
|
443
|
+
* const endpoints = defineEndpoints({ meta, create: {}, search: { fields: ['name'] } }, PrismaAdapters);
|
|
444
|
+
* ```
|
|
445
|
+
*/
|
|
446
|
+
declare const PrismaAdapters: AdapterBundle;
|
|
408
447
|
|
|
409
|
-
export { PrismaAggregateEndpoint, PrismaBatchCreateEndpoint, PrismaBatchDeleteEndpoint, PrismaBatchRestoreEndpoint, PrismaBatchUpdateEndpoint, PrismaBatchUpsertEndpoint, PrismaCreateEndpoint, PrismaDeleteEndpoint, PrismaExportEndpoint, PrismaImportEndpoint, PrismaListEndpoint, PrismaReadEndpoint, PrismaRestoreEndpoint, PrismaSearchEndpoint, PrismaUpdateEndpoint, PrismaUpsertEndpoint, PrismaVersionCompareEndpoint, PrismaVersionHistoryEndpoint, PrismaVersionReadEndpoint, PrismaVersionRollbackEndpoint, clearPrismaModelMappings, registerPrismaModelMapping, registerPrismaModelMappings };
|
|
448
|
+
export { PrismaAdapters, PrismaAggregateEndpoint, PrismaBatchCreateEndpoint, PrismaBatchDeleteEndpoint, PrismaBatchRestoreEndpoint, PrismaBatchUpdateEndpoint, PrismaBatchUpsertEndpoint, PrismaCloneEndpoint, PrismaCreateEndpoint, PrismaDeleteEndpoint, PrismaExportEndpoint, PrismaImportEndpoint, PrismaListEndpoint, PrismaReadEndpoint, PrismaRestoreEndpoint, PrismaSearchEndpoint, PrismaUpdateEndpoint, PrismaUpsertEndpoint, PrismaVersionCompareEndpoint, PrismaVersionHistoryEndpoint, PrismaVersionReadEndpoint, PrismaVersionRollbackEndpoint, clearPrismaModelMappings, registerPrismaModelMapping, registerPrismaModelMappings };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {k as k$1,l,m,n,o,p,r,s,t,u,v as v$1,J,K as K$1,T,U,q,w as w$1,x as x$1,y,z,A,B}from'../../chunk-2I6G2Q6U.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-3TIIYAKB.js';import'../../chunk-7NM6MBRL.js';import'../../chunk-ANWSQPCQ.js';import'../../chunk-Z575OBLV.js';import'../../chunk-FC56WWPB.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';var v,_;async function _e(){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 je(){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 C(a){return (await _e()).singular(a)}async function I(a,t){return (await je())(a,t)}function oe(a,t){return a[t]}function Ee(a){return typeof a=="object"&&a!==null&&"create"in a&&typeof a.create=="function"}function h(a,t){let e=oe(a,t);return Ee(e)?e:void 0}function F(a){if(typeof a.$transaction!="function")throw new Error("Prisma client does not support $transaction");return a.$transaction.bind(a)}function k(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 K(a){let t={};for(let e of a){let o=k(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(k)};break}case "nin":{let n=Array.isArray(e.value)?e.value:[e.value];t[e.field]={notIn:n.map(k)};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,r]=e.value;t[e.field]={gte:k(n),lte:k(r)};break}}}return t}var Ce=500,b=new Map;function ne(a,t){if(b.size>=Ce){let e=b.keys().next().value;e!==void 0&&b.delete(e);}b.set(a,t);}var D=new Map;function re(a,t){D.set(a.toLowerCase(),t),b.delete(a);}function Ie(a){for(let[t,e]of Object.entries(a))re(t,e);}function Fe(){D.clear(),b.clear();}async function w(a){let t=b.get(a);if(t)return t;let e=D.get(a.toLowerCase());if(e)return ne(a,e),e;let o=a.replace(/[-_](.)/g,(n,r)=>r.toUpperCase()).replace(/^./,n=>n.toLowerCase());return o=await C(o),ne(a,o),o}function Ke(a){let t=[];for(let e of Object.keys(a)){if(e.startsWith("$")||e.startsWith("_"))continue;let o=oe(a,e);o&&typeof o=="object"&&"create"in o&&t.push(e);}return t}async function De(a,t,e=3){if(t.length===0)return [];let o=a.toLowerCase();return (await Promise.all(t.map(async r=>({name:r,distance:await I(o,r.toLowerCase())})))).filter(r=>r.distance<=Math.max(3,a.length/2)).sort((r,s)=>r.distance-s.distance).slice(0,e).map(r=>r.name)}async function f(a,t){let e=await w(t),o=h(a,e);if(!o){let n=Ke(a),r=await De(e,n),s=`Model '${e}' not found in Prisma client. Table name: '${t}'. `;throw r.length>0&&(s+=`Did you mean: ${r.map(i=>`'${i}'`).join(", ")}? `),n.length>0&&n.length<=10&&(s+=`Available models: ${n.join(", ")}. `),s+=`You can register a custom mapping with: registerPrismaModelMapping('${t}', 'yourModelName')`,new Error(s)}return o}async function Ae(a,t,e,o){let n=await w(o.model),r=h(a,n);if(!r)return t;switch(o.type){case "hasOne":{let s=o.localKey||"id",i=t[s];if(i==null)return {...t,[e]:null};let l=await r.findFirst({where:{[o.foreignKey]:i}});return {...t,[e]:l||null}}case "hasMany":{let s=o.localKey||"id",i=t[s];if(i==null)return {...t,[e]:[]};let l=await r.findMany({where:{[o.foreignKey]:i}});return {...t,[e]:l}}case "belongsTo":{let s=t[o.foreignKey];if(s==null)return {...t,[e]:null};let i=o.localKey||"id",l=await r.findFirst({where:{[i]:s}});return {...t,[e]:l||null}}default:return t}}async function se(a,t,e,o){if(!o?.relations?.length||!e.model.relations)return t;let n={...t};for(let r of o.relations){let s=e.model.relations[r];s&&(n=await Ae(a,n,r,s));}return n}async function x(a,t,e,o){if(!t.length||!o?.relations?.length||!e.model.relations)return t;let n=t.map(r=>({...r}));for(let r of o.relations){let s=e.model.relations[r];if(!s)continue;let i=await w(s.model),l=h(a,i);if(l)switch(s.type){case "hasOne":case "hasMany":{let u=s.localKey||"id",c=[...new Set(n.map(m=>m[u]).filter(m=>m!=null))];if(c.length===0){n=n.map(m=>({...m,[r]:s.type==="hasMany"?[]:null}));continue}let d=await l.findMany({where:{[s.foreignKey]:{in:c}}}),p=new Map;for(let m of d){let g=m[s.foreignKey];p.has(g)||p.set(g,[]),p.get(g).push(m);}n=n.map(m=>{let g=m[u],M=p.get(g)||[];return {...m,[r]:s.type==="hasMany"?M:M[0]||null}});break}case "belongsTo":{let u=s.localKey||"id",c=[...new Set(n.map(m=>m[s.foreignKey]).filter(m=>m!=null))];if(c.length===0){n=n.map(m=>({...m,[r]:null}));continue}let d=await l.findMany({where:{[u]:{in:c}}}),p=new Map;for(let m of d){let g=m[u];p.set(g,m);}n=n.map(m=>{let g=m[s.foreignKey];return {...m,[r]:p.get(g)||null}});break}}}return n}async function j(a){let{model:t,filters:e,searchFields:o=[],softDeleteConfig:n,defaultPerPage:r=20,additionalWhere:s={}}=a,i={...K(e.filters),...s};if(n?.enabled){let{withDeleted:g,onlyDeleted:M}=e.options;M?i[n.field]={not:null}:g||(i[n.field]=null);}if(e.options.search&&o.length>0){let g=o.map(M=>({[M]:{contains:e.options.search,mode:"insensitive"}}));i={...i,OR:g};}let l=await t.count({where:i}),u;e.options.order_by&&(u={[e.options.order_by]:e.options.order_by_direction||"asc"});let c=e.options.page||1,d=e.options.per_page||r,p=await t.findMany({where:i,orderBy:u,skip:(c-1)*d,take:d}),m=Math.ceil(l/d);return {records:p,where:i,totalCount:l,page:c,perPage:d,totalPages:m}}function E(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 ae=class extends k$1{useTransaction=false;async getModel(){return f(this.prisma,this._meta.model.tableName)}async create(t){let e=await this.getModel(),o=this._meta.model.primaryKeys[0],n={...t,[o]:t[o]||crypto.randomUUID()};return await e.create({data:n})}},ie=class extends l{async getModel(){return f(this.prisma,this._meta.model.tableName)}async read(t,e,o){let n=await this.getModel(),r={[this.lookupField]:t,...e},s=await n.findFirst({where:r});return s?await se(this.prisma,s,this._meta,o):null}},le=class extends m{useTransaction=false;async getModel(){return f(this.prisma,this._meta.model.tableName)}async update(t,e,o){let n=await this.getModel(),r={[this.lookupField]:t,...o},s=await n.findFirst({where:r});if(!s)return null;let i=this._meta.model.primaryKeys[0];return await n.update({where:{[i]:s[i]},data:e})}},de=class extends n{useTransaction=false;async getModel(){return f(this.prisma,this._meta.model.tableName)}async findForDelete(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),r={[this.lookupField]:t,...e};return n.enabled&&(r[n.field]=null),await o.findFirst({where:r})}async delete(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),r={[this.lookupField]:t,...e};n.enabled&&(r[n.field]=null);let s=await o.findFirst({where:r});if(!s)return null;let i=this._meta.model.primaryKeys[0],l=s[i];return n.enabled?await o.update({where:{[i]:l},data:{[n.field]:new Date}}):await o.delete({where:{[i]:l}})}},ce=class extends o{async getModel(){return f(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 x(this.prisma,e.records,this._meta,o);return E(n,e)}};var ue=class extends p{useTransaction=false;async getModel(){return f(this.prisma,this._meta.model.tableName)}async restore(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),r={[this.lookupField]:t,[n.field]:{not:null},...e},s=await o.findFirst({where:r});if(!s)return null;let i=this._meta.model.primaryKeys[0];return await o.update({where:{[i]:s[i]},data:{[n.field]:null}})}},me=class extends r{async getModel(){return f(this.prisma,this._meta.model.tableName)}async batchCreate(t){let e=this._meta.model.primaryKeys[0],o=t.map(r=>({...r,[e]:r[e]||crypto.randomUUID()})),n=[];return await F(this.prisma)(async r=>{let s=h(r,await w(this._meta.model.tableName));if(!s)throw new Error(`Model '${this._meta.model.tableName}' not found in Prisma transaction client`);for(let i of o){let l=await s.create({data:i});n.push(l);}}),n}},ge=class extends s{async getModel(){return f(this.prisma,this._meta.model.tableName)}async batchUpdate(t){let e=await this.getModel(),o=this.getSoftDeleteConfig(),n=this._meta.model.primaryKeys[0],r=[],s=[],i=t.map(d=>d.id),l={[this.lookupField]:{in:i}};o.enabled&&(l[o.field]=null);let u=await e.findMany({where:l}),c=new Map;for(let d of u){let p=d[this.lookupField];c.set(p,d);}for(let d of t){let p=c.get(d.id);if(!p){s.push(d.id);continue}let m=await e.update({where:{[n]:p[n]},data:d.data});r.push(m);}return {updated:r,notFound:s}}},pe=class extends t{async getModel(){return f(this.prisma,this._meta.model.tableName)}async batchDelete(t){let e=await this.getModel(),o=this.getSoftDeleteConfig(),n=this._meta.model.primaryKeys[0],r=[],s=[],i={[this.lookupField]:{in:t}};o.enabled&&(i[o.field]=null);let l=await e.findMany({where:i}),u=new Map;for(let c of l){let d=c[this.lookupField];u.set(d,c);}for(let c of t)u.has(c)||s.push(c);for(let c of t){let d=u.get(c);if(d)if(o.enabled){let p=await e.update({where:{[n]:d[n]},data:{[o.field]:new Date}});r.push(p);}else {let p=await e.delete({where:{[n]:d[n]}});r.push(p);}}return {deleted:r,notFound:s}}},fe=class extends u{async getModel(){return f(this.prisma,this._meta.model.tableName)}async batchRestore(t){let e=await this.getModel(),o=this.getSoftDeleteConfig(),n=this._meta.model.primaryKeys[0],r=[],s=[],i={[this.lookupField]:{in:t},[o.field]:{not:null}},l=await e.findMany({where:i}),u=new Map;for(let c of l){let d=c[this.lookupField];u.set(d,c);}for(let c of t){let d=u.get(c);if(!d){s.push(c);continue}let p=await e.update({where:{[n]:d[n]},data:{[o.field]:null}});r.push(p);}return {restored:r,notFound:s}}},Me=class extends v$1{useTransaction=true;async getModel(){return f(this.prisma,this._meta.model.tableName)}async findExisting(t){let e=await this.getModel(),o=this.getUpsertKeys(),n={};for(let s of o){let i=t[s];i!==void 0&&(n[s]=i);}return Object.keys(n).length===0?null:await e.findFirst({where:n})||null}async create(t){let e=await this.getModel(),o=this._meta.model.primaryKeys[0],n={...t,[o]:t[o]||crypto.randomUUID()};return await e.create({data:n})}async update(t,e){let o=await this.getModel(),n=this._meta.model.primaryKeys[0];return await o.update({where:{[n]:t[n]},data: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],r=async l=>{let u=h(l,await w(this._meta.model.tableName));if(!u)throw new Error(`Model '${this._meta.model.tableName}' not found in Prisma client`);let c=[],d=[];for(let p=0;p<t.length;p++){let m=t[p];try{let g={};for(let y of o){let O=m[y];O!==void 0&&(g[y]=O);}let M={...m,[n]:m[n]||crypto.randomUUID()},P={};for(let[y,O]of Object.entries(m))!o.includes(y)&&y!==n&&(this.createOnlyFields?.includes(y)||(P[y]=O));let ve=await u.upsert({where:g,create:M,update:Object.keys(P).length>0?P:{}});c.push({data:ve,created:!1,index:p});}catch(g){if(this.continueOnError)d.push({index:p,error:g instanceof Error?g.message:String(g)});else throw g}}return {results:c,errors:d}},s;this.useTransaction?s=await F(this.prisma)(r):s=await r(this.prisma);let i={items:s.results,createdCount:0,updatedCount:s.results.length,totalCount:s.results.length};return s.errors.length>0&&(i.errors=s.errors),i}};var he=class extends J{async getModel(){return f(this.prisma,this._meta.model.tableName)}buildSearchWhere(t,e){let o=K(e.filters),n=this.getSoftDeleteConfig();if(n.enabled){let{withDeleted:l,onlyDeleted:u}=e.options;u?o[n.field]={not:null}:l||(o[n.field]=null);}let r=this.getSearchableFields(),i=(t.fields||Object.keys(r)).map(l=>({[l]:{contains:t.query,mode:"insensitive"}}));return i.length>0&&(t.mode==="all"?o={...o,AND:i}:o={...o,OR:i}),o}async search(t,e){let o=await this.getModel(),n=this.buildSearchWhere(t,e),r=await o.count({where:n}),s=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,u=await o.findMany({where:n,orderBy:s,skip:(i-1)*l,take:l}),c=K$1(u,t,this.getSearchableFields()),d={relations:e.options.include||[]},p=c.map(M=>M.item),m=await x(this.prisma,p,this._meta,d);return {items:c.map((M,P)=>({...M,item:m[P]})),totalCount:r}}},we=class extends T{async getModel(){return f(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 x(this.prisma,e.records,this._meta,o);return E(n,e)}},ye=class extends U{async getModel(){return f(this.prisma,this._meta.model.tableName)}async findExisting(t){let e=await this.getModel(),o=this.getUpsertKeys(),n={};for(let s of o){let i=t[s];i!==void 0&&(n[s]=i);}return Object.keys(n).length===0?null:await e.findFirst({where:n})||null}async create(t){let e=await this.getModel(),o=this._meta.model.primaryKeys[0],n={...t,[o]:t[o]||crypto.randomUUID()};return await e.create({data:n})}async update(t,e){let o=await this.getModel(),n=this._meta.model.primaryKeys[0];return await o.update({where:{[n]:t[n]},data:e})}},be=class extends q{useTransaction=false;async getModel(){return f(this.prisma,this._meta.model.tableName)}async findExisting(t){let e=await this.getModel(),o=this.getUpsertKeys(),n={};for(let s of o){let i=t[s];i!==void 0&&(n[s]=i);}return Object.keys(n).length===0?null:await e.findFirst({where:n})||null}async create(t){let e=await this.getModel(),o=this._meta.model.primaryKeys[0],n={...t,[o]:t[o]||crypto.randomUUID()};return await e.create({data:n})}async update(t,e){let o=await this.getModel(),n=this._meta.model.primaryKeys[0];return await o.update({where:{[n]:t[n]},data:e})}async nativeUpsert(t,e){let o=await this.getModel(),n=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s={};for(let c of n){let d=t[c];d!==void 0&&(s[c]=d);}let i={...t,[r]:t[r]||crypto.randomUUID()},l={};for(let[c,d]of Object.entries(t))!n.includes(c)&&c!==r&&(this.createOnlyFields?.includes(c)||(l[c]=d));return {data:await o.upsert({where:s,create:i,update:Object.keys(l).length>0?l:{}}),created:false}}},Pe=class extends w$1{async getModel(){return f(this.prisma,this._meta.model.tableName)}async recordExists(t){return await(await this.getModel()).count({where:{[this.lookupField]:t}})>0}},ke=class extends x$1{},xe=class extends y{},Oe=class extends z{async getModel(){return f(this.prisma,this._meta.model.tableName)}async rollback(t,e,o){let n=await this.getModel(),r=this.getVersioningConfig().field,s=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:{[s]:i[s]},data:{...e,[r]:o}})}},Re=class extends A{useNativeAggregation=true;async getModel(){return f(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,r]of Object.entries(t.filters))if(typeof r=="object"&&r!==null){let s={};for(let[i,l]of Object.entries(r))switch(i){case "eq":s.equals=l;break;case "ne":s.not=l;break;case "gt":s.gt=l;break;case "gte":s.gte=l;break;case "lt":s.lt=l;break;case "lte":s.lte=l;break;case "in":s.in=l;break;case "nin":s.notIn=l;break;default:s[i]=l;}e[n]=s;}else e[n]=r;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 B(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},r={},s=this.groupAggregationsByOperation(o.aggregations);if(n._count=true,s.sum.length){n._sum={};for(let u of s.sum)n._sum[u]=true;}if(s.avg.length){n._avg={};for(let u of s.avg)n._avg[u]=true;}if(s.min.length){n._min={};for(let u of s.min)n._min[u]=true;}if(s.max.length){n._max={};for(let u of s.max)n._max[u]=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 u=await l.aggregate(n);if(u._count!==void 0&&(r.count=typeof u._count=="object"?u._count._all??0:u._count),u._sum&&s.sum.length)for(let c of s.sum){let d=c.charAt(0).toUpperCase()+c.slice(1);r[`sum${d}`]=u._sum[c]??0;}if(u._avg&&s.avg.length)for(let c of s.avg){let d=c.charAt(0).toUpperCase()+c.slice(1);r[`avg${d}`]=u._avg[c]??0;}if(u._min&&s.min.length)for(let c of s.min){let d=c.charAt(0).toUpperCase()+c.slice(1);r[`min${d}`]=u._min[c];}if(u._max&&s.max.length)for(let c of s.max){let d=c.charAt(0).toUpperCase()+c.slice(1);r[`max${d}`]=u._max[c];}return {values:r,groups:[]}}catch{let c=await t.findMany({where:e});return B(c,o)}}async aggregateWithGroupBy(t,e,o){let n={by:o.groupBy,where:e},r=this.groupAggregationsByOperation(o.aggregations);if(n._count=true,r.sum.length){n._sum={};for(let l of r.sum)n._sum[l]=true;}if(r.avg.length){n._avg={};for(let l of r.avg)n._avg[l]=true;}if(r.min.length){n._min={};for(let l of r.min)n._min[l]=true;}if(r.max.length){n._max={};for(let l of r.max)n._max[l]=true;}let s=await w(this._meta.model.tableName),i=h(this.prisma,s);if(!i)throw new Error(`Model '${s}' not found in Prisma client`);try{let u=(await i.groupBy(n)).map(d=>{let p={},m={};for(let g of o.groupBy)p[g]=d[g];if(m.count=typeof d._count=="object"?d._count._all??0:d._count??0,d._sum&&r.sum.length)for(let g of r.sum){let M=g.charAt(0).toUpperCase()+g.slice(1);m[`sum${M}`]=d._sum[g]??0;}if(d._avg&&r.avg.length)for(let g of r.avg){let M=g.charAt(0).toUpperCase()+g.slice(1);m[`avg${M}`]=d._avg[g]??0;}if(d._min&&r.min.length)for(let g of r.min){let M=g.charAt(0).toUpperCase()+g.slice(1);m[`min${M}`]=d._min[g];}if(d._max&&r.max.length)for(let g of r.max){let M=g.charAt(0).toUpperCase()+g.slice(1);m[`max${M}`]=d._max[g];}return {key:p,values:m}});return {values:{count:u.reduce((d,p)=>d+(p.values.count||0),0)},groups:u}}catch{let u=await t.findMany({where:e});return B(u,o)}}};export{Re as PrismaAggregateEndpoint,me as PrismaBatchCreateEndpoint,pe as PrismaBatchDeleteEndpoint,fe as PrismaBatchRestoreEndpoint,ge as PrismaBatchUpdateEndpoint,Me as PrismaBatchUpsertEndpoint,ae as PrismaCreateEndpoint,de as PrismaDeleteEndpoint,we as PrismaExportEndpoint,ye as PrismaImportEndpoint,ce as PrismaListEndpoint,ie as PrismaReadEndpoint,ue as PrismaRestoreEndpoint,he as PrismaSearchEndpoint,le as PrismaUpdateEndpoint,be as PrismaUpsertEndpoint,xe as PrismaVersionCompareEndpoint,Pe as PrismaVersionHistoryEndpoint,ke as PrismaVersionReadEndpoint,Oe as PrismaVersionRollbackEndpoint,Fe as clearPrismaModelMappings,re as registerPrismaModelMapping,Ie as registerPrismaModelMappings};
|
|
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-DLD4TRHM.js';import'../../chunk-TP6RZ5RR.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-3TIIYAKB.js';import'../../chunk-7NM6MBRL.js';import'../../chunk-FC56WWPB.js';import'../../chunk-ANWSQPCQ.js';import'../../chunk-Z575OBLV.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';
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { ZodObject, ZodRawShape } from 'zod';
|
|
2
|
+
import { Env } from 'hono';
|
|
3
|
+
import { C as CrudEndpoint, M as ModelObject } from './import-D8nboMpT.js';
|
|
4
|
+
import { M as MetaInput, H as HookMode, L as ListFilters, O as OpenAPIRouteSchema } from './types-tpG0M7Va.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Result of a bulk patch operation.
|
|
8
|
+
*/
|
|
9
|
+
interface BulkPatchResult<T = unknown> {
|
|
10
|
+
/** Number of records that matched the filter */
|
|
11
|
+
matched: number;
|
|
12
|
+
/** Number of records actually updated */
|
|
13
|
+
updated: number;
|
|
14
|
+
/** Whether this was a dry run (no actual updates) */
|
|
15
|
+
dryRun: boolean;
|
|
16
|
+
/** Updated records (only if not dry run and returnRecords is true) */
|
|
17
|
+
records?: T[];
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Base endpoint for bulk patching resources matching a filter.
|
|
21
|
+
*
|
|
22
|
+
* `PATCH /resource?role=inactive` → update all matching records.
|
|
23
|
+
*
|
|
24
|
+
* Supports dry-run mode via `?dryRun=true` query parameter.
|
|
25
|
+
* Requires `X-Confirm-Bulk` header when affecting more than `confirmThreshold` records.
|
|
26
|
+
*/
|
|
27
|
+
declare abstract class BulkPatchEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends CrudEndpoint<E, M> {
|
|
28
|
+
/** Maximum number of records that can be updated in a single bulk operation */
|
|
29
|
+
protected maxBulkSize: number;
|
|
30
|
+
/** Require X-Confirm-Bulk header when this many or more records match */
|
|
31
|
+
protected confirmThreshold: number;
|
|
32
|
+
/** Whether to return updated records in the response */
|
|
33
|
+
protected returnRecords: boolean;
|
|
34
|
+
/** Hook execution mode */
|
|
35
|
+
protected hookMode: HookMode;
|
|
36
|
+
/** Filter fields allowed in query params */
|
|
37
|
+
protected filterFields?: string[];
|
|
38
|
+
/** Get the model schema */
|
|
39
|
+
protected abstract getModelSchema(): ZodObject<ZodRawShape>;
|
|
40
|
+
/** Get the update (partial) schema */
|
|
41
|
+
protected abstract getUpdateSchema(): ZodObject<ZodRawShape>;
|
|
42
|
+
/** Count records matching filters (for dry run and threshold check) */
|
|
43
|
+
protected abstract countMatching(filters: ListFilters): Promise<number>;
|
|
44
|
+
/** Apply patch to all matching records */
|
|
45
|
+
protected abstract applyPatch(data: Partial<ModelObject<M['model']>>, filters: ListFilters): Promise<{
|
|
46
|
+
updated: number;
|
|
47
|
+
records?: ModelObject<M['model']>[];
|
|
48
|
+
}>;
|
|
49
|
+
/** Before hook: called before the bulk patch is applied */
|
|
50
|
+
protected beforeBulkPatch?(data: Partial<ModelObject<M['model']>>, filters: ListFilters, matchedCount: number): Promise<Partial<ModelObject<M['model']>>>;
|
|
51
|
+
/** After hook: called after the bulk patch is applied */
|
|
52
|
+
protected afterBulkPatch?(result: BulkPatchResult<ModelObject<M['model']>>): Promise<void>;
|
|
53
|
+
getSchema(): OpenAPIRouteSchema;
|
|
54
|
+
handle(): Promise<Response>;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export { BulkPatchEndpoint as B, type BulkPatchResult as a };
|
package/dist/cache/index.js
CHANGED
|
@@ -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-
|
|
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-2U5ZQ7XQ.js';import'../chunk-7NM6MBRL.js';import'../chunk-GF2EC5G4.js';import'../chunk-2M5BM4VD.js';import'../chunk-FC56WWPB.js';import'../chunk-ANWSQPCQ.js';import'../chunk-Z575OBLV.js';import'../chunk-GBQQ3YQX.js';import'../chunk-DMGP7QDL.js';import'../chunk-MDHMZPXK.js';import'../chunk-VJRDAVID.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {b as b$4}from'./chunk-7NM6MBRL.js';import {a as a$3}from'./chunk-GF2EC5G4.js';import {b as b$3}from'./chunk-ANWSQPCQ.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
|
+
import {b as b$4}from'./chunk-7NM6MBRL.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-ANWSQPCQ.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};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import {k as k$1,l,m as m$1,n,o,q as q$1,s,t,u,v as v$1,r,w,x,y,z as z$1,A as A$1,B as B$1,C,K as K$1,L as L$1,U as U$1,V as V$1,p}from'./chunk-TP6RZ5RR.js';import {b}from'./chunk-DMGP7QDL.js';import {getTableColumns,eq,inArray,between,isNull,isNotNull,ilike,like,notInArray,lte,lt as lt$1,gte,gt as gt$1,ne,and,sql,or,desc,asc}from'drizzle-orm';import {z}from'zod';function q(l){return l}function h(l){if(!l.model.table)throw new Error(`Model ${l.model.tableName} does not have a table reference`);return l.model.table}function m(l,e){let o=getTableColumns(l),n=o[e];if(!n)throw new Error(`Column '${e}' not found in table. Available columns: ${Object.keys(o).join(", ")}`);return n}async function ve(l,e,o,n){if(!n.table)return e;let t=n.table;switch(n.type){case "hasOne":{let r=n.localKey||"id",s=e[r];if(s==null)return e;let i=m(t,n.foreignKey),a=await l.select().from(t).where(eq(i,s)).limit(1);return {...e,[o]:a[0]||null}}case "hasMany":{let r=n.localKey||"id",s=e[r];if(s==null)return {...e,[o]:[]};let i=m(t,n.foreignKey),a=await l.select().from(t).where(eq(i,s));return {...e,[o]:a}}case "belongsTo":{let r=e[n.foreignKey];if(r==null)return {...e,[o]:null};let s=m(t,n.localKey||"id"),i=await l.select().from(t).where(eq(s,r)).limit(1);return {...e,[o]:i[0]||null}}default:return e}}async function se(l,e,o,n){if(!n?.relations?.length||!o.model.relations)return e;let t={...e};for(let r of n.relations){let s=o.model.relations[r];s&&(t=await ve(l,t,r,s));}return t}async function v(l,e,o,n){if(!e.length||!n?.relations?.length||!o.model.relations)return e;let t=e.map(r=>({...r}));for(let r of n.relations){let s=o.model.relations[r];if(!s||!s.table)continue;let i=s.table;switch(s.type){case "hasOne":case "hasMany":{let a=s.localKey||"id",u=[...new Set(t.map(p=>p[a]).filter(p=>p!=null))];if(u.length===0){t=t.map(p=>({...p,[r]:s.type==="hasMany"?[]:null}));continue}let d=m(i,s.foreignKey),c=await l.select().from(i).where(inArray(d,u)),g=new Map;for(let p of c){let b=p[s.foreignKey];g.has(b)||g.set(b,[]),g.get(b).push(p);}t=t.map(p=>{let b=p[a],z=g.get(b)||[];return {...p,[r]:s.type==="hasMany"?z:z[0]||null}});break}case "belongsTo":{let a=s.localKey||"id",u=[...new Set(t.map(p=>p[s.foreignKey]).filter(p=>p!=null))];if(u.length===0){t=t.map(p=>({...p,[r]:null}));continue}let d=m(i,a),c=await l.select().from(i).where(inArray(d,u)),g=new Map;for(let p of c){let b=p[a];g.set(b,p);}t=t.map(p=>{let b=p[s.foreignKey];return {...p,[r]:g.get(b)||null}});break}}}return t}function k(l,e){let o=m(l,e.field);switch(e.operator){case "eq":return eq(o,e.value);case "ne":return ne(o,e.value);case "gt":return gt$1(o,e.value);case "gte":return gte(o,e.value);case "lt":return lt$1(o,e.value);case "lte":return lte(o,e.value);case "in":return inArray(o,e.value);case "nin":return notInArray(o,e.value);case "like":return like(o,e.value);case "ilike":return ilike(o,e.value);case "null":return e.value?isNull(o):isNotNull(o);case "between":{let[n,t]=e.value;return between(o,n,t)}default:return}}function D(l){let e=l;if(e._tx)return e._tx;if(e.db)return e.db;let o=e.context?.get?.("db");if(o)return o;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 S=class extends k$1{db;useTransaction=false;getDb(){return D(this)}getTable(){return h(this._meta)}getRelatedTable(e){return e.table}async create(e,o){let n=o??this.getDb(),t=this.getTable(),r=this._meta.model.primaryKeys[0],s={...e,[r]:e[r]||crypto.randomUUID()};return (await n.insert(t).values(s).returning())[0]}async createNested(e,o,n,t,r){let s=r??this.getDb(),i=this.getRelatedTable(n);if(!i)return b().warn(`Related table not found for ${o}. Add 'table' to the relation config.`),[];let a=Array.isArray(t)?t:[t],u=[];for(let d of a){if(typeof d!="object"||d===null)continue;let c={...d,id:crypto.randomUUID(),[n.foreignKey]:e},g=await s.insert(i).values(c).returning();g[0]&&u.push(g[0]);}return u}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()}},_=class extends l{db;getDb(){return D(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async read(e,o,n){let t=this.getTable(),r=this.getColumn(this.lookupField),s=this.getSoftDeleteConfig(),i=[eq(r,e)];if(o)for(let[d,c]of Object.entries(o))i.push(eq(this.getColumn(d),c));s.enabled&&i.push(isNull(this.getColumn(s.field)));let a=await this.getDb().select().from(t).where(and(...i)).limit(1);return a[0]?await se(this.getDb(),a[0],this._meta,n):null}},I=class extends m$1{db;useTransaction=false;getDb(){return D(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}getRelatedTable(e){return e.table}async findExisting(e,o,n){let t=n??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),a=[eq(s,e)];if(o)for(let[d,c]of Object.entries(o))a.push(eq(this.getColumn(d),c));return i.enabled&&a.push(isNull(this.getColumn(i.field))),(await t.select().from(r).where(and(...a)).limit(1))[0]||null}async update(e,o,n,t){let r=t??this.getDb(),s=this.getTable(),i=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),u=[eq(i,e)];if(n)for(let[c,g]of Object.entries(n))u.push(eq(this.getColumn(c),g));return a.enabled&&u.push(isNull(this.getColumn(a.field))),(await r.update(s).set(o).where(and(...u)).returning())[0]||null}async processNestedWrites(e,o,n,t,r){let s=r??this.getDb(),i=this.getRelatedTable(n);if(!i)return b().warn(`Related table not found for ${o}. Add 'table' to the relation config.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]};let a={created:[],updated:[],deleted:[],connected:[],disconnected:[]},u=m(i,n.foreignKey),d=m(i,"id");if(t.create){let c=Array.isArray(t.create)?t.create:[t.create];for(let g of c){if(typeof g!="object"||g===null)continue;let p={...g,id:crypto.randomUUID(),[n.foreignKey]:e},b=await s.insert(i).values(p).returning();b[0]&&a.created.push(b[0]);}}if(t.update)for(let c of t.update){if(!c.id||!(await s.select().from(i).where(and(eq(d,c.id),eq(u,e))).limit(1))[0])continue;let{id:p,...b}=c,z=await s.update(i).set(b).where(eq(d,p)).returning();z[0]&&a.updated.push(z[0]);}if(t.delete)for(let c of t.delete)(await s.delete(i).where(and(eq(d,c),eq(u,e))).returning())[0]&&a.deleted.push(c);if(t.connect)for(let c of t.connect)(await s.update(i).set({[n.foreignKey]:e}).where(eq(d,c)).returning())[0]&&a.connected.push(c);if(t.disconnect)for(let c of t.disconnect)(await s.update(i).set({[n.foreignKey]:null}).where(and(eq(d,c),eq(u,e))).returning())[0]&&a.disconnected.push(c);return a}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()}},P=class extends n{db;useTransaction=false;getDb(){return D(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}getRelatedTable(e){return e.table}async findForDelete(e,o,n){let t=n??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),a=[eq(s,e)];if(o)for(let[d,c]of Object.entries(o))a.push(eq(this.getColumn(d),c));return i.enabled&&a.push(isNull(this.getColumn(i.field))),(await t.select().from(r).where(and(...a)).limit(1))[0]||null}async delete(e,o,n){let t=n??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),a=[eq(s,e)];if(o)for(let[u,d]of Object.entries(o))a.push(eq(this.getColumn(u),d));return i.enabled&&a.push(isNull(this.getColumn(i.field))),i.enabled?(await t.update(r).set({[i.field]:new Date}).where(and(...a)).returning())[0]||null:(await t.delete(r).where(and(...a)).returning())[0]||null}async countRelated(e,o,n,t){let r=t??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let i=m(s,n.foreignKey),a=await r.select({count:sql`count(*)`}).from(s).where(eq(i,e));return Number(a[0]?.count)||0}async deleteRelated(e,o,n,t){let r=t??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let i=m(s,n.foreignKey);return (await r.delete(s).where(eq(i,e)).returning()).length}async nullifyRelated(e,o,n,t){let r=t??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let i=m(s,n.foreignKey);return (await r.update(s).set({[n.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()}},U=class extends o{db;getDb(){return D(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async list(e){let o=this.getTable(),n=[],t=this.getSoftDeleteConfig();if(t.enabled){let y=this.getColumn(t.field);e.options.onlyDeleted?n.push(isNotNull(y)):e.options.withDeleted||n.push(isNull(y));}for(let y of e.filters){let R=k(o,y);R&&n.push(R);}if(e.options.search&&this.searchFields.length>0){let y=this.searchFields.map(R=>{let ne=this.getColumn(R);return sql`LOWER(${ne}) LIKE LOWER(${`%${e.options.search}%`})`});n.push(or(...y));}let r=n.length>0?and(...n):void 0,s=this.getDb(),i=await s.select({count:sql`count(*)`}).from(o).where(r),a=Number(i[0]?.count)||0,u=s.select().from(o).where(r);if(e.options.order_by){let y=this.getColumn(e.options.order_by),R=e.options.order_by_direction==="desc"?desc:asc;u=u.orderBy(R(y));}let d=e.options.page||1,c=e.options.per_page||this.defaultPerPage;u=u.limit(c).offset((d-1)*c);let g=await u,p={relations:e.options.include||[]},b=await v(this.getDb(),g,this._meta,p),z=Math.ceil(a/c);return {result:b,result_info:{page:d,per_page:c,total_count:a,total_pages:z,has_next_page:d<z,has_prev_page:d>1}}}},K=class extends q$1{db;useTransaction=false;getDb(){return D(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async restore(e,o,n){let t=n??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),a=[eq(s,e)];if(o)for(let[d,c]of Object.entries(o))a.push(eq(this.getColumn(d),c));return a.push(isNotNull(this.getColumn(i.field))),(await t.update(r).set({[i.field]:null}).where(and(...a)).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 B=class extends s{db;getDb(){return D(this)}getTable(){return h(this._meta)}async batchCreate(e){let o=this.getTable(),n=this._meta.model.primaryKeys[0],t=e.map(s=>({...s,[n]:s[n]||crypto.randomUUID()}));return await this.getDb().insert(o).values(t).returning()}},A=class extends t{db;getDb(){return D(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async batchUpdate(e){let o=this.getTable(),n=this.getColumn(this.lookupField),t=this.getSoftDeleteConfig(),r=[],s=[];for(let i of e){let a=[eq(n,i.id)];t.enabled&&a.push(isNull(this.getColumn(t.field)));let u=await this.getDb().update(o).set(i.data).where(and(...a)).returning();u[0]?r.push(u[0]):s.push(i.id);}return {updated:r,notFound:s}}},L=class extends u{db;getDb(){return D(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async batchDelete(e){let o=this.getTable(),n=this.getColumn(this.lookupField),t=this.getSoftDeleteConfig(),r=[inArray(n,e)];t.enabled&&r.push(isNull(this.getColumn(t.field)));let s;t.enabled?s=await this.getDb().update(o).set({[t.field]:new Date}).where(and(...r)).returning():s=await this.getDb().delete(o).where(and(...r)).returning();let i=s,a=new Set(i.map(d=>String(d[this.lookupField]))),u=e.filter(d=>!a.has(d));return {deleted:i,notFound:u}}},Z=class extends v$1{db;getDb(){return D(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async batchRestore(e){let o=this.getTable(),n=this.getColumn(this.lookupField),t=this.getSoftDeleteConfig(),r=[inArray(n,e),isNotNull(this.getColumn(t.field))],i=await this.getDb().update(o).set({[t.field]:null}).where(and(...r)).returning(),a=new Set(i.map(d=>String(d[this.lookupField]))),u=e.filter(d=>!a.has(d));return {restored:i,notFound:u}}};var Q=class extends r{db;getDb(){return D(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async findExisting(e){let o=this.getTable(),n=this.getUpsertKeys(),t=this.getSoftDeleteConfig(),r=[];for(let i of n){let a=e[i];a!==void 0&&r.push(eq(this.getColumn(i),a));}return t.enabled&&r.push(isNull(this.getColumn(t.field))),r.length===0?null:(await this.getDb().select().from(o).where(and(...r)).limit(1))[0]||null}async create(e){let o=this.getTable(),n=this._meta.model.primaryKeys[0],t={...e,[n]:e[n]||crypto.randomUUID()};return (await this.getDb().insert(o).values(t).returning())[0]}async update(e,o){let n=this.getTable(),t=this._meta.model.primaryKeys[0],r=e[t];return (await this.getDb().update(n).set(o).where(eq(this.getColumn(t),r)).returning())[0]}async nativeUpsert(e,o){let n=this.getTable(),t=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s=this.getSoftDeleteConfig(),i={...e,[r]:e[r]||crypto.randomUUID()},a={};for(let[c,g]of Object.entries(e))!t.includes(c)&&c!==r&&(this.createOnlyFields?.includes(c)||(a[c]=g));let u=t.map(c=>this.getColumn(c)),d;s.enabled&&(d=isNull(this.getColumn(s.field)));try{return {data:(await this.getDb().insert(n).values(i).onConflictDoUpdate({target:u,set:Object.keys(a).length>0?a:{[r]:sql`${this.getColumn(r)}`},where:d}).returning())[0],created:!1}}catch(c){if(c instanceof Error&&c.message.includes("onConflictDoUpdate"))try{return {data:(await this.getDb().insert(n).values(i).onDuplicateKeyUpdate({set:Object.keys(a).length>0?a:{[r]:sql`${this.getColumn(r)}`}}).returning())[0],created:!1}}catch{return this.performStandardUpsert(e,o)}throw c}}},N=class extends w{db;getDb(){return D(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async findExisting(e){let o=this.getTable(),n=this.getUpsertKeys(),t=[];for(let s of n){let i=e[s];i!==void 0&&t.push(eq(this.getColumn(s),i));}return t.length===0?null:(await this.getDb().select().from(o).where(and(...t)).limit(1))[0]||null}async create(e){let o=this.getTable(),n=this._meta.model.primaryKeys[0],t={...e,[n]:e[n]||crypto.randomUUID()};return (await this.getDb().insert(o).values(t).returning())[0]}async update(e,o){let n=this.getTable(),t=this._meta.model.primaryKeys[0],r=e[t];return (await this.getDb().update(n).set(o).where(eq(this.getColumn(t),r)).returning())[0]}async nativeBatchUpsert(e,o){if(e.length===0)return {items:[],createdCount:0,updatedCount:0,totalCount:0};let n=this.getTable(),t=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s=e.map(d=>({...d,[r]:d[r]||crypto.randomUUID()})),i={},a=e[0];for(let d of Object.keys(a))!t.includes(d)&&d!==r&&(this.createOnlyFields?.includes(d)||(i[d]=sql`excluded.${sql.identifier(d)}`));let u=t.map(d=>this.getColumn(d));try{let c=await this.getDb().insert(n).values(s).onConflictDoUpdate({target:u,set:Object.keys(i).length>0?i:{[r]:sql`${this.getColumn(r)}`}}).returning();return {items:c.map((g,p)=>({data:g,created:!1,index:p})),createdCount:0,updatedCount:c.length,totalCount:c.length}}catch(d){if(d instanceof Error&&d.message.includes("onConflictDoUpdate"))try{let g=await this.getDb().insert(n).values(s).onDuplicateKeyUpdate({set:Object.keys(i).length>0?i:{[r]:sql`${this.getColumn(r)}`}}).returning();return {items:g.map((p,b)=>({data:p,created:!1,index:b})),createdCount:0,updatedCount:g.length,totalCount:g.length}}catch{return this.performStandardBatchUpsert(e,o)}throw d}}},Ie=class extends x{db;getDb(){return D(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async recordExists(e){let o=this.getTable(),n=await this.getDb().select({count:sql`count(*)`}).from(o).where(eq(this.getColumn("id"),e));return Number(n[0]?.count)>0}},Pe=class extends y{},Ue=class extends z$1{},Ke=class extends A$1{db;getDb(){return D(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async rollback(e,o,n){let t=this.getTable(),r=this.getVersioningConfig().field;return (await this.getDb().update(t).set({...o,[r]:n}).where(eq(this.getColumn("id"),e)).returning())[0]}},V=class extends B$1{db;getDb(){return D(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async aggregate(e){let o=this.getTable(),n=[],t=this.getSoftDeleteConfig();if(t.enabled){let{query:i}=await this.getValidatedData();i?.withDeleted===true||i?.withDeleted==="true"||n.push(isNull(this.getColumn(t.field)));}if(e.filters)for(let[i,a]of Object.entries(e.filters))if(typeof a=="object"&&a!==null)for(let[u,d]of Object.entries(a)){let c=k(o,{field:i,operator:u,value:d});c&&n.push(c);}else n.push(eq(this.getColumn(i),a));let r=n.length>0?and(...n):void 0,s=await this.getDb().select().from(o).where(r);return C(s,e)}},X=class extends K$1{db;getDb(){return D(this)}useNativeSearch=false;vectorColumn;vectorConfig="english";getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async search(e,o){let n=this.getTable(),t=[],r=this.getSoftDeleteConfig();r.enabled&&(o.options.onlyDeleted?t.push(isNotNull(this.getColumn(r.field))):o.options.withDeleted||t.push(isNull(this.getColumn(r.field))));for(let C of o.filters){let w=k(n,C);w&&t.push(w);}let s=this.getSearchableFields(),i=e.fields||Object.keys(s);if(this.useNativeSearch&&this.vectorColumn){let C=this.getColumn(this.vectorColumn),w=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(" | ")})`;t.push(sql`${C} @@ ${w}`);}else {let C=i.map(w=>{try{let Fe=this.getColumn(w);return sql`LOWER(CAST(${Fe} AS TEXT)) LIKE LOWER(${`%${e.query}%`})`}catch{return}}).filter(w=>w!==void 0);C.length>0&&(e.mode==="all"?t.push(and(...C)):t.push(or(...C)));}let a=t.length>0?and(...t):void 0,u=await this.getDb().select({count:sql`count(*)`}).from(n).where(a),d=Number(u[0]?.count)||0,c=this.getDb().select().from(n).where(a);if(o.options.order_by){let C=this.getColumn(o.options.order_by),w=o.options.order_by_direction==="desc"?desc:asc;c=c.orderBy(w(C));}let g=o.options.page||1,p=o.options.per_page||this.defaultPerPage;c=c.limit(p).offset((g-1)*p);let b=await c,z=L$1(b,e,s),y={relations:o.options.include||[]},R=z.map(C=>C.item),ne=await v(this.getDb(),R,this._meta,y);return {items:z.map((C,w)=>({...C,item:ne[w]})),totalCount:d}}},G=class extends U$1{db;getDb(){return D(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async list(e){let o=this.getTable(),n=[],t=this.getSoftDeleteConfig();if(t.enabled){let z=this.getColumn(t.field);e.options.onlyDeleted?n.push(isNotNull(z)):e.options.withDeleted||n.push(isNull(z));}for(let z of e.filters){let y=k(o,z);y&&n.push(y);}if(e.options.search&&this.searchFields.length>0){let z=this.searchFields.map(y=>{let R=this.getColumn(y);return sql`LOWER(${R}) LIKE LOWER(${`%${e.options.search}%`})`});n.push(or(...z));}let r=n.length>0?and(...n):void 0,s=await this.getDb().select({count:sql`count(*)`}).from(o).where(r),i=Number(s[0]?.count)||0,a=this.getDb().select().from(o).where(r);if(e.options.order_by){let z=this.getColumn(e.options.order_by),y=e.options.order_by_direction==="desc"?desc:asc;a=a.orderBy(y(z));}let u=e.options.page||1,d=e.options.per_page||this.defaultPerPage;a=a.limit(d).offset((u-1)*d);let c=await a,g={relations:e.options.include||[]},p=await v(this.getDb(),c,this._meta,g),b=Math.ceil(i/d);return {result:p,result_info:{page:u,per_page:d,total_count:i,total_pages:b,has_next_page:u<b,has_prev_page:u>1}}}},H=class extends V$1{db;getDb(){return D(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async findExisting(e){let o=this.getTable(),n=this.getUpsertKeys(),t=this.getSoftDeleteConfig(),r=[];for(let i of n){let a=e[i];a!==void 0&&r.push(eq(this.getColumn(i),a));}return t.enabled&&r.push(isNull(this.getColumn(t.field))),r.length===0?null:(await this.getDb().select().from(o).where(and(...r)).limit(1))[0]||null}async create(e){let o=this.getTable(),n=this._meta.model.primaryKeys[0],t={...e,[n]:e[n]||crypto.randomUUID()};return (await this.getDb().insert(o).values(t).returning())[0]}async update(e,o){let n=this.getTable(),t=this._meta.model.primaryKeys[0],r=e[t];return (await this.getDb().update(n).set(o).where(eq(this.getColumn(t),r)).returning())[0]}},J=class extends p{db;getDb(){return D(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}generateId(){return crypto.randomUUID()}async findSource(e,o){let n=this.getTable(),t=this.getColumn(this.lookupField),r=this.getSoftDeleteConfig(),s=[eq(t,e)];if(o)for(let[a,u]of Object.entries(o))s.push(eq(this.getColumn(a),u));r.enabled&&s.push(isNull(this.getColumn(r.field)));let i=await this.getDb().select().from(n).where(and(...s)).limit(1);return i[0]?i[0]:null}async createClone(e){let o=this.getTable(),n=this._meta.model.primaryKeys[0],t={...e,[n]:e[n]||this.generateId()};return (await this.getDb().insert(o).values(t).returning())[0]}};function en(l,e){return {Create:class extends S{_meta=e;db=l},Read:class extends _{_meta=e;db=l},Update:class extends I{_meta=e;db=l},Delete:class extends P{_meta=e;db=l},List:class extends U{_meta=e;db=l},Restore:class extends K{_meta=e;db=l},Upsert:class extends Q{_meta=e;db=l},BatchCreate:class extends B{_meta=e;db=l},BatchUpdate:class extends A{_meta=e;db=l},BatchDelete:class extends L{_meta=e;db=l},BatchRestore:class extends Z{_meta=e;db=l},BatchUpsert:class extends N{_meta=e;db=l}}}var ee=null,Qe=false,Y=null;async function te(){if(Qe){if(Y)throw Y;return ee}Qe=true;try{return ee=await import('drizzle-zod'),ee}catch{throw Y=new Error("drizzle-zod is not installed. Please install it: npm install drizzle-zod"),Y}}async function lt(l,e){return (await te()).createSelectSchema(l,e)}async function dt(l,e){return (await te()).createInsertSchema(l,e)}async function ct(l,e){let o=await te();return o.createUpdateSchema?o.createUpdateSchema(l,e):o.createInsertSchema(l,e).partial()}async function ut(l,e){let o=await te(),n=e?.coerceDates!==false,t=n?bt(l):new Set,r=o.createSelectSchema(l,e?.selectRefine),s=o.createInsertSchema(l,e?.insertRefine),i;return o.createUpdateSchema?i=o.createUpdateSchema(l,e?.updateRefine):i=o.createInsertSchema(l,e?.updateRefine).partial(),n&&t.size>0&&(s=Ne(s,t),i=Ne(i,t)),{select:r,insert:s,update:i}}function pt(){return ee!==null}var gt=z.preprocess(l=>{if(l instanceof Date)return l;if(typeof l=="string"){let e=new Date(l);if(!isNaN(e.getTime()))return e}return l},z.date()),mt=z.preprocess(l=>{if(l==null)return null;if(l instanceof Date)return l;if(typeof l=="string"){let e=new Date(l);if(!isNaN(e.getTime()))return e}return l},z.date().nullable());function bt(l){let e=new Set,o=l;for(let[n,t]of Object.entries(o)){if(n==="_"||n==="$inferInsert"||n==="$inferSelect")continue;let r=t;if(!r||typeof r!="object")continue;let s=String(r.dataType??"").toLowerCase(),i=String(r.columnType??"").toLowerCase(),a=r.config,u=String(a?.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")||u.includes("timestamp")||u.includes("date"))&&e.add(n);}return e}function Ne(l,e){if(e.size===0)return l;let o=l.shape,n={};for(let[t,r]of Object.entries(o))if(e.has(t)){let s=r.isOptional?.()??false,i=r.isNullable?.()??false,a=gt;(i||s)&&(a=mt),s&&(a=a.optional()),n[t]=a;}else n[t]=r;return z.object(n)}var yn={CreateEndpoint:S,ListEndpoint:U,ReadEndpoint:_,UpdateEndpoint:I,DeleteEndpoint:P,RestoreEndpoint:K,BatchCreateEndpoint:B,BatchUpdateEndpoint:A,BatchDeleteEndpoint:L,BatchRestoreEndpoint:Z,BatchUpsertEndpoint:N,SearchEndpoint:X,AggregateEndpoint:V,ExportEndpoint:G,ImportEndpoint:H,UpsertEndpoint:Q,CloneEndpoint:J};export{H as A,J as B,en as C,lt as D,dt as E,ct as F,ut as G,pt as H,yn as I,q as a,h as b,m as c,ve as d,se as e,v as f,k as g,S as h,_ as i,I as j,P as k,U as l,K as m,B as n,A as o,L as p,Z as q,Q as r,N as s,Ie as t,Pe as u,Ue as v,Ke as w,V as x,X as y,G as z};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {k,l,m as m$1,n,o,q,s,t,u,v as v$1,w as w$1,d,f,p,r,x as x$1,y,z as z$1,A,B,C,K,L,U,V}from'./chunk-TP6RZ5RR.js';import {b,a}from'./chunk-Z575OBLV.js';import {z}from'zod';var w=new Map;function m(u){return w.has(u)||w.set(u,new Map),w.get(u)}function Ee(u,n,a){let t=m(a.model),e=a.localKey||"id",o=u[e];if(o==null)return u;let r=Array.from(t.values()).filter(s=>s[a.foreignKey]===o);switch(a.type){case "hasOne":return {...u,[n]:r[0]||null};case "hasMany":return {...u,[n]:r};case "belongsTo":{let s=u[a.foreignKey];if(s==null)return {...u,[n]:null};let i=Array.from(t.values()).find(d=>d[a.localKey||"id"]===s);return {...u,[n]:i||null}}default:return u}}function S(u,n,a){if(!a?.relations?.length||!n.model.relations)return u;let t={...u};for(let e of a.relations){let o=n.model.relations[e];o&&(t=Ee(t,e,o));}return t}function _e(){w.clear();}function Ne(u){return m(u)}function x(u,n,a){if(u==null||typeof u!="object")return false;let t=u;if(n.enabled){let e=t[n.field];if(e!=null)return false}if(a){for(let[e,o]of Object.entries(a))if(String(t[e])!==o)return false}return true}var _=Object.freeze({__memoryNoopTx:true,rolledBack:false}),se=class extends k{_tx=_;generateId(){return crypto.randomUUID()}async create(n){let a=m(this._meta.model.tableName),t=this._meta.model.primaryKeys[0],e={...n,[t]:n[t]||this.generateId()},o=String(e[t]);return a.set(o,e),e}async createNested(n,a,t,e){let o=m(t.model),r=[],s=Array.isArray(e)?e:[e];for(let i of s){if(typeof i!="object"||i===null)continue;let d={...i,id:crypto.randomUUID(),[t.foreignKey]:n};o.set(d.id,d),r.push(d);}return r}},ie=class extends l{async read(n,a,t){let o=m(this._meta.model.tableName).get(n),r=this.getSoftDeleteConfig();return !o||!x(o,r,a)?null:S(o,this._meta,t)}},ae=class extends m$1{_tx=_;async findExisting(n,a){let e=m(this._meta.model.tableName).get(n),o=this.getSoftDeleteConfig();return !e||!x(e,o,a)?null:{...e}}async update(n,a,t){let e=m(this._meta.model.tableName),o=e.get(n),r=this.getSoftDeleteConfig();if(!o||!x(o,r,t))return null;let s={...o,...a};return e.set(n,s),s}async processNestedWrites(n,a,t,e){let o=m(t.model),r={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(),[t.foreignKey]:n};o.set(d.id,d),r.created.push(d);}}if(e.update)for(let s of e.update){if(!s.id)continue;let i=o.get(String(s.id));if(!i||i[t.foreignKey]!==n)continue;let d={...i,...s};o.set(String(s.id),d),r.updated.push(d);}if(e.delete)for(let s of e.delete){let i=o.get(String(s));i&&i[t.foreignKey]===n&&(o.delete(String(s)),r.deleted.push(s));}if(e.connect)for(let s of e.connect){let i=o.get(String(s));if(!i)continue;let d={...i,[t.foreignKey]:n};o.set(String(s),d),r.connected.push(s);}if(e.disconnect)for(let s of e.disconnect){let i=o.get(String(s));if(!i||i[t.foreignKey]!==n)continue;let d={...i,[t.foreignKey]:null};o.set(String(s),d),r.disconnected.push(s);}if(e.set!==void 0){let s=Array.from(o.values()).filter(i=>i[t.foreignKey]===n);for(let i of s)if(i.id){let d={...i,[t.foreignKey]:null};o.set(String(i.id),d),r.disconnected.push(i.id);}if(e.set!==null){let i={...e.set,id:crypto.randomUUID(),[t.foreignKey]:n};o.set(i.id,i),r.created.push(i);}}return r}},de=class extends n{_tx=_;async findForDelete(n,a){let e=m(this._meta.model.tableName).get(n),o=this.getSoftDeleteConfig();return !e||!x(e,o,a)?null:e}async countRelated(n,a,t){let e=m(t.model),o=0;for(let r of e.values())r[t.foreignKey]===n&&o++;return o}async deleteRelated(n,a,t){let e=m(t.model),o=0;for(let[r,s]of e.entries())s[t.foreignKey]===n&&(e.delete(r),o++);return o}async nullifyRelated(n,a,t){let e=m(t.model),o=0;for(let[r,s]of e.entries())if(s[t.foreignKey]===n){let i={...s,[t.foreignKey]:null};e.set(r,i),o++;}return o}async delete(n,a){let t=m(this._meta.model.tableName),e=t.get(n),o=this.getSoftDeleteConfig();if(!e||!x(e,o,a))return null;if(o.enabled){let r={...e,[o.field]:new Date};return t.set(n,r),r}else return t.delete(n),e}},le=class extends o{async list(n){let a$1=m(this._meta.model.tableName),t=Array.from(a$1.values()),e=this.getSoftDeleteConfig();e.enabled&&(n.options.onlyDeleted?t=t.filter(c=>{let f=c[e.field];return f!=null}):n.options.withDeleted||(t=t.filter(c=>{let f=c[e.field];return f==null})));for(let c of n.filters)t=t.filter(f=>{let l=f[c.field];switch(c.operator){case "eq":return String(l)===String(c.value);case "ne":return String(l)!==String(c.value);case "gt":return Number(l)>Number(c.value);case "gte":return Number(l)>=Number(c.value);case "lt":return Number(l)<Number(c.value);case "lte":return Number(l)<=Number(c.value);case "in":return c.value.map(String).includes(String(l));case "nin":return !c.value.map(String).includes(String(l));case "like":return String(l).includes(String(c.value).replace(/%/g,""));case "ilike":return String(l).toLowerCase().includes(String(c.value).replace(/%/g,"").toLowerCase());case "null":return c.value?l===null:l!==null;case "between":{let[p,M]=c.value;return Number(l)>=Number(p)&&Number(l)<=Number(M)}default:return true}});if(n.options.search&&this.searchFields.length>0){let c=n.options.search.toLowerCase();t=t.filter(f=>this.searchFields.some(l=>{let p=f[l];return String(p).toLowerCase().includes(c)}));}let o=t.length;if(n.options.order_by){let c=n.options.order_by,f=n.options.order_by_direction==="desc"?-1:1;t.sort((l,p)=>{let M=l[c],y=p[c];return M<y?-1*f:M>y?1*f:0});}if(this.cursorPaginationEnabled&&(n.options.cursor||n.options.limit)){let c=this.cursorField||"id",f=n.options.limit||n.options.per_page||this.defaultPerPage,l=0;if(n.options.cursor){let R=b(n.options.cursor);if(R!==null){let I=t.findIndex(ve=>String(ve[c])===R);I!==-1&&(l=I+1);}}let p=t.slice(l,l+f),M={relations:n.options.include||[]},y=p.map(R=>S(R,this._meta,M)),j=l+f<t.length,k=l>0,N,P;if(j&&p.length>0){let R=p[p.length-1];N=a(R[c]);}if(k&&l>0){let R=t[l-1];P=a(R[c]);}return {result:y,result_info:{page:0,per_page:f,total_count:o,has_next_page:j,has_prev_page:k,next_cursor:N,prev_cursor:P}}}let r=n.options.page||1,s=n.options.per_page||this.defaultPerPage,i=(r-1)*s,d=t.slice(i,i+s),g={relations:n.options.include||[]},b$1=d.map(c=>S(c,this._meta,g)),h=Math.ceil(o/s);return {result:b$1,result_info:{page:r,per_page:s,total_count:o,total_pages:h,has_next_page:r<h,has_prev_page:r>1}}}},ce=class extends q{async restore(n,a){let t=m(this._meta.model.tableName),e=t.get(n),o=this.getSoftDeleteConfig();if(!e)return null;let r=e[o.field];if(r==null)return null;if(a){for(let[i,d]of Object.entries(a))if(String(e[i])!==d)return null}let s={...e,[o.field]:null};return t.set(n,s),s}};var ue=class extends s{generateId(){return crypto.randomUUID()}async batchCreate(n){let a=m(this._meta.model.tableName),t=this._meta.model.primaryKeys[0],e=[];for(let o of n){let r={...o,[t]:o[t]||this.generateId()},s=String(r[t]);a.set(s,r),e.push(r);}return e}},me=class extends t{async batchUpdate(n){let a=m(this._meta.model.tableName),t=this.getSoftDeleteConfig(),e=[],o=[];for(let r of n){let s=a.get(r.id);if(!s){o.push(r.id);continue}if(!x(s,t)){o.push(r.id);continue}let i={...s,...r.data};a.set(r.id,i),e.push(i);}return {updated:e,notFound:o}}},ge=class extends u{async batchDelete(n){let a=m(this._meta.model.tableName),t=this.getSoftDeleteConfig(),e=[],o=[];for(let r of n){let s=a.get(r);if(!s){o.push(r);continue}if(!x(s,t)){o.push(r);continue}if(t.enabled){let i={...s,[t.field]:new Date};a.set(r,i),e.push(i);}else a.delete(r),e.push(s);}return {deleted:e,notFound:o}}},fe=class extends v$1{async batchRestore(n){let a=m(this._meta.model.tableName),t=this.getSoftDeleteConfig(),e=[],o=[];for(let r of n){let s=a.get(r);if(!s){o.push(r);continue}let i=s[t.field];if(i==null){o.push(r);continue}let d={...s,[t.field]:null};a.set(r,d),e.push(d);}return {restored:e,notFound:o}}},pe=class extends w$1{generateId(){return crypto.randomUUID()}async findExisting(n){let a=m(this._meta.model.tableName),t=this.getUpsertKeys();for(let e of a.values()){let o=true;for(let r of t){let s=n[r],i=e[r];if(s!==i){o=false;break}}if(o)return e}return null}async create(n){let a=m(this._meta.model.tableName),t=this._meta.model.primaryKeys[0],e={...n,[t]:n[t]||this.generateId()};return a.set(String(e[t]),e),e}async update(n,a){let t=m(this._meta.model.tableName),e=this._meta.model.primaryKeys[0],o=String(n[e]),r={...n,...a};return t.set(o,r),r}async nativeBatchUpsert(n,a){let t=m(this._meta.model.tableName),e=this.getUpsertKeys(),o=this._meta.model.primaryKeys[0],r=[],s=0,i=0;for(let d=0;d<n.length;d++){let g=n[d],b=null;for(let h of t.values()){let c=true;for(let f of e){let l=g[f],p=h[f];if(l!==p){c=false;break}}if(c){b=h;break}}if(b){let h={...g};if(this.createOnlyFields)for(let l of this.createOnlyFields)delete h[l];let c=String(b[o]),f={...b,...h};t.set(c,f),r.push({data:f,created:false,index:d}),i++;}else {let h={...g};if(this.updateOnlyFields)for(let l of this.updateOnlyFields)delete h[l];let c={...h,[o]:g[o]||this.generateId()},f=String(c[o]);t.set(f,c),r.push({data:c,created:true,index:d}),s++;}}return {items:r,createdCount:s,updatedCount:i,totalCount:r.length}}};var v=class extends d{maxBulkSize=1e3;confirmThreshold=100;returnRecords=false;hookMode="parallel";filterFields;getSchema(){return {request:{body:{content:{"application/json":{schema:this.getUpdateSchema().partial()}}},query:z.object({dryRun:z.string().optional()}).passthrough()},responses:{200:{description:"Bulk patch result",content:{"application/json":{schema:z.object({success:z.boolean(),matched:z.number(),updated:z.number(),dryRun:z.boolean()})}}},400:{description:"Bad request",content:{"application/json":{schema:z.object({success:z.boolean(),error:z.string()})}}}}}}async handle(){let n=this.getContext(),t=(await this.getValidatedData()).body;if(!t||Object.keys(t).length===0)return this.error("Request body is required with at least one field to update","EMPTY_BODY",400);let e=n.req.query("dryRun"),o=e==="true"||e==="1",r=f(n.req.query(),{filterFields:this.filterFields,defaultPerPage:this.maxBulkSize,maxPerPage:this.maxBulkSize}),s=await this.countMatching(r);if(s===0)return this.json({success:true,matched:0,updated:0,dryRun:o});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&&n.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(o)return this.json({success:true,matched:s,updated:0,dryRun:true});let i=t;this.beforeBulkPatch&&(i=await this.beforeBulkPatch(i,r,s));let d=await this.applyPatch(i,r),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 p{generateId(){return crypto.randomUUID()}async findSource(n,a){let e=m(this._meta.model.tableName).get(n),o=this.getSoftDeleteConfig();return !e||!x(e,o,a)?null:e}async createClone(n){let a=m(this._meta.model.tableName),t=this._meta.model.primaryKeys[0],e=this.generateId(),o={...n,[t]:e};return a.set(e,o),o}},be=class extends r{generateId(){return crypto.randomUUID()}async findExisting(n){let a=m(this._meta.model.tableName),t=this.getUpsertKeys(),e=this.getSoftDeleteConfig();for(let o of a.values()){if(e.enabled){let s=o[e.field];if(s!=null)continue}let r=true;for(let s of t){let i=n[s],d=o[s];if(i!==d){r=false;break}}if(r)return o}return null}async create(n){let a=m(this._meta.model.tableName),t=this._meta.model.primaryKeys[0],e={...n,[t]:n[t]||this.generateId()};return a.set(String(e[t]),e),e}async update(n,a){let t=m(this._meta.model.tableName),e=this._meta.model.primaryKeys[0],o=String(n[e]),r={...n,...a};return t.set(o,r),r}async nativeUpsert(n,a){let t=m(this._meta.model.tableName),e=this.getUpsertKeys(),o=this._meta.model.primaryKeys[0],r=this.getSoftDeleteConfig(),s=null;for(let i of t.values()){if(r.enabled){let g=i[r.field];if(g!=null)continue}let d=true;for(let g of e){let b=n[g],h=i[g];if(b!==h){d=false;break}}if(d){s=i;break}}if(s){let i={...n};if(this.createOnlyFields)for(let b of this.createOnlyFields)delete i[b];let d=String(s[o]),g={...s,...i};return t.set(d,g),{data:g,created:false}}else {let i={...n};if(this.updateOnlyFields)for(let b of this.updateOnlyFields)delete i[b];let d={...i,[o]:n[o]||this.generateId()},g=String(d[o]);return t.set(g,d),{data:d,created:true}}}async processNestedWrites(n,a,t,e){let o=m(t.model),r={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(),[t.foreignKey]:n};o.set(d.id,d),r.created.push(d);}}if(e.update)for(let s of e.update){let i=String(s.id),d=o.get(i);if(d&&d[t.foreignKey]===n){let g={...d,...s};o.set(i,g),r.updated.push(g);}}if(e.delete)for(let s of e.delete){let i=String(s),d=o.get(i);d&&d[t.foreignKey]===n&&(o.delete(i),r.deleted.push(s));}if(e.connect)for(let s of e.connect){let i=String(s),d=o.get(i);if(d){let g={...d,[t.foreignKey]:n};o.set(i,g),r.connected.push(s);}}if(e.disconnect)for(let s of e.disconnect){let i=String(s),d=o.get(i);if(d&&d[t.foreignKey]===n){let g={...d,[t.foreignKey]:null};o.set(i,g),r.disconnected.push(s);}}return r}},he=class extends x$1{async recordExists(n){return m(this._meta.model.tableName).has(n)}},ye=class extends y{},xe=class extends z$1{},Oe=class extends A{async rollback(n,a,t){let e=m(this._meta.model.tableName),o=this.getVersioningConfig().field,r={...a,[o]:t};return e.set(n,r),r}},Re=class extends B{async aggregate(n){let a=m(this._meta.model.tableName),t=Array.from(a.values()),e=this.getSoftDeleteConfig();if(e.enabled){let{query:o}=await this.getValidatedData();o?.withDeleted===true||o?.withDeleted==="true"||(t=t.filter(s=>{let i=s[e.field];return i==null}));}if(n.filters)for(let[o,r]of Object.entries(n.filters))t=t.filter(s=>{if(typeof r=="object"&&r!==null){for(let[i,d]of Object.entries(r)){let g=s[o];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[o])===String(r)});return C(t,n)}},je=class extends K{async search(n,a){let t=m(this._meta.model.tableName),e=Array.from(t.values()),o=this.getSoftDeleteConfig();o.enabled&&(a.options.onlyDeleted?e=e.filter(l=>{let p=l[o.field];return p!=null}):a.options.withDeleted||(e=e.filter(l=>{let p=l[o.field];return p==null})));for(let l of a.filters)e=e.filter(p=>{let M=p[l.field];switch(l.operator){case "eq":return String(M)===String(l.value);case "ne":return String(M)!==String(l.value);case "gt":return Number(M)>Number(l.value);case "gte":return Number(M)>=Number(l.value);case "lt":return Number(M)<Number(l.value);case "lte":return Number(M)<=Number(l.value);case "in":return l.value.map(String).includes(String(M));case "nin":return !l.value.map(String).includes(String(M));case "like":return String(M).includes(String(l.value).replace(/%/g,""));case "ilike":return String(M).toLowerCase().includes(String(l.value).replace(/%/g,"").toLowerCase());case "null":return l.value?M===null:M!==null;case "between":{let[y,j]=l.value;return Number(M)>=Number(y)&&Number(M)<=Number(j)}default:return true}});let r=this.getSearchableFields(),s=L(e,n,r),i=s.length;if(a.options.order_by){let l=a.options.order_by,p=a.options.order_by_direction==="desc"?-1:1;s.sort((M,y)=>{let j=M.item[l],k=y.item[l];return j<k?-1*p:j>k?1*p:0});}let d=a.options.page||1,g=a.options.per_page||this.defaultPerPage,b=(d-1)*g,h=s.slice(b,b+g),c={relations:a.options.include||[]};return {items:h.map(l=>({...l,item:S(l.item,this._meta,c)})),totalCount:i}}},Se=class extends U{async list(n){let a=m(this._meta.model.tableName),t=Array.from(a.values()),e=this.getSoftDeleteConfig();e.enabled&&(n.options.onlyDeleted?t=t.filter(c=>{let f=c[e.field];return f!=null}):n.options.withDeleted||(t=t.filter(c=>{let f=c[e.field];return f==null})));for(let c of n.filters)t=t.filter(f=>{let l=f[c.field];switch(c.operator){case "eq":return String(l)===String(c.value);case "ne":return String(l)!==String(c.value);case "gt":return Number(l)>Number(c.value);case "gte":return Number(l)>=Number(c.value);case "lt":return Number(l)<Number(c.value);case "lte":return Number(l)<=Number(c.value);case "in":return c.value.map(String).includes(String(l));case "nin":return !c.value.map(String).includes(String(l));case "like":return String(l).includes(String(c.value).replace(/%/g,""));case "ilike":return String(l).toLowerCase().includes(String(c.value).replace(/%/g,"").toLowerCase());case "null":return c.value?l===null:l!==null;case "between":{let[p,M]=c.value;return Number(l)>=Number(p)&&Number(l)<=Number(M)}default:return true}});if(n.options.search&&this.searchFields.length>0){let c=n.options.search.toLowerCase();t=t.filter(f=>this.searchFields.some(l=>{let p=f[l];return String(p).toLowerCase().includes(c)}));}let o=t.length;if(n.options.order_by){let c=n.options.order_by,f=n.options.order_by_direction==="desc"?-1:1;t.sort((l,p)=>{let M=l[c],y=p[c];return M<y?-1*f:M>y?1*f:0});}let r=n.options.page||1,s=n.options.per_page||this.defaultPerPage,i=(r-1)*s,d=t.slice(i,i+s),g={relations:n.options.include||[]},b=d.map(c=>S(c,this._meta,g)),h=Math.ceil(o/s);return {result:b,result_info:{page:r,per_page:s,total_count:o,total_pages:h,has_next_page:r<h,has_prev_page:r>1}}}},ke=class extends V{generateId(){return crypto.randomUUID()}async findExisting(n){let a=m(this._meta.model.tableName),t=this.getUpsertKeys(),e=this.getSoftDeleteConfig();for(let o of a.values()){if(e.enabled){let s=o[e.field];if(s!=null)continue}let r=true;for(let s of t){let i=n[s],d=o[s];if(i!==d){r=false;break}}if(r)return o}return null}async create(n){let a=m(this._meta.model.tableName),t=this._meta.model.primaryKeys[0],e={...n,[t]:n[t]||this.generateId()};return a.set(String(e[t]),e),e}async update(n,a){let t=m(this._meta.model.tableName),e=this._meta.model.primaryKeys[0],o=String(n[e]),r={...n,...a};return t.set(o,r),r}},we=class extends v{async countMatching(n){return this.getFilteredItems(n).length}async applyPatch(n,a){let t=m(this._meta.model.tableName),e=this._meta.model.primaryKeys[0],o=this.getFilteredItems(a),r=[];for(let s of o){let i=String(s[e]),d={...s,...n};t.set(i,d),r.push(d);}return {updated:r.length,records:r}}getFilteredItems(n){let a=m(this._meta.model.tableName),t=Array.from(a.values());for(let e of n.filters)t=t.filter(o=>{let r=o[e.field];switch(e.operator){case "eq":return String(r)===String(e.value);case "ne":return String(r)!==String(e.value);case "gt":return Number(r)>Number(e.value);case "gte":return Number(r)>=Number(e.value);case "lt":return Number(r)<Number(e.value);case "lte":return Number(r)<=Number(e.value);case "in":return e.value.map(String).includes(String(r));case "nin":return !e.value.map(String).includes(String(r));case "like":return String(r).includes(String(e.value).replace(/%/g,""));case "ilike":return String(r).toLowerCase().includes(String(e.value).replace(/%/g,"").toLowerCase());case "null":return e.value?r===null:r!==null;default:return true}});return t}};export{ke as A,we as B,v as a,w as b,m as c,_e as d,Ne as e,_ 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,fe as p,pe as q,Me as r,be as s,he as t,ye as u,xe as v,Oe as w,Re as x,je as y,Se as z};
|