hono-crud 0.4.4 → 0.5.1
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 +4 -0
- package/dist/adapters/drizzle/index.d.ts +14 -9
- package/dist/adapters/drizzle/index.js +2 -2
- package/dist/adapters/memory/index.d.ts +10 -5
- package/dist/adapters/memory/index.js +1 -1
- package/dist/adapters/prisma/index.d.ts +27 -22
- package/dist/adapters/prisma/index.js +1 -1
- package/dist/api-version/index.d.ts +114 -0
- package/dist/api-version/index.js +1 -0
- package/dist/audit/index.d.ts +152 -0
- package/dist/audit/index.js +1 -0
- package/dist/auth/index.d.ts +135 -8
- package/dist/auth/index.js +1 -1
- package/dist/{bulk-patch-f4TR8L-q.d.ts → bulk-patch-CoEduhTf.d.ts} +4 -13
- package/dist/cache/index.d.ts +76 -9
- package/dist/cache/index.js +1 -1
- package/dist/chunk-2M5BM4VD.js +1 -0
- package/dist/chunk-7DDNX2F2.js +1 -0
- package/dist/chunk-BJTWQHEV.js +0 -0
- package/dist/chunk-BSL6R76X.js +1 -0
- package/dist/chunk-CCGZ5UPB.js +0 -0
- package/dist/chunk-DMGP7QDL.js +1 -0
- package/dist/chunk-EWKQ6BPV.js +33 -0
- package/dist/chunk-FC56WWPB.js +1 -0
- package/dist/chunk-FXIMMYFV.js +1 -0
- package/dist/chunk-GASDSU4U.js +1 -0
- package/dist/chunk-GBQQ3YQX.js +1 -0
- package/dist/chunk-GF2EC5G4.js +1 -0
- package/dist/chunk-H3H65KZF.js +1 -0
- package/dist/chunk-HAUN4LQO.js +1 -0
- package/dist/chunk-KKLMXJY4.js +1 -0
- package/dist/chunk-L4X7KFWN.js +1 -0
- package/dist/chunk-MDHMZPXK.js +1 -0
- package/dist/chunk-NIWM7GOK.js +1 -0
- package/dist/{chunk-STVUWSWZ.js → chunk-OXBPASZN.js} +1 -1
- package/dist/chunk-Q2D5AUPJ.js +1 -0
- package/dist/chunk-Q4FF5JVS.js +11 -0
- package/dist/chunk-QRXEQTNE.js +1 -0
- package/dist/chunk-QXFY6NYI.js +1 -0
- package/dist/chunk-R3WESU6C.js +1 -0
- package/dist/chunk-RFT77JBK.js +1 -0
- package/dist/chunk-SDNXN7M5.js +1 -0
- package/dist/chunk-VJRDAVID.js +1 -0
- package/dist/chunk-W4FHI5YI.js +1 -0
- package/dist/chunk-XH7DEPW2.js +1 -0
- package/dist/cloudflare-kv-types-ByUEHhBc.d.ts +30 -0
- package/dist/emitter-Npan0uNZ.d.ts +104 -0
- package/dist/encryption/index.d.ts +42 -0
- package/dist/encryption/index.js +1 -0
- package/dist/events/index.d.ts +87 -0
- package/dist/events/index.js +1 -0
- package/dist/health/index.d.ts +103 -0
- package/dist/health/index.js +1 -0
- package/dist/idempotency/index.d.ts +80 -0
- package/dist/idempotency/index.js +1 -0
- package/dist/{import-BZ05PJMa.d.ts → import-BHD2B1u8.d.ts} +122 -211
- package/dist/{index-bSnRLgcs.d.ts → index-BNIzQvcO.d.ts} +25 -2
- package/dist/{index-431Ovi2o.d.ts → index-DhCIATbD.d.ts} +76 -47
- package/dist/index.d.ts +107 -1198
- package/dist/index.js +1 -1
- package/dist/logging/index.d.ts +3 -88
- package/dist/logging/index.js +1 -1
- package/dist/multi-tenant/index.d.ts +136 -0
- package/dist/multi-tenant/index.js +1 -0
- package/dist/rate-limit/index.d.ts +3 -2
- package/dist/rate-limit/index.js +1 -1
- package/dist/registry-PNJjvSvm.d.ts +147 -0
- package/dist/{route-DwSID3du.d.ts → route-BmtmmHSO.d.ts} +1 -9
- package/dist/serialization/index.d.ts +26 -0
- package/dist/serialization/index.js +1 -0
- package/dist/storage/index.d.ts +41 -147
- package/dist/storage/index.js +1 -1
- package/dist/types/cloudflare.d.ts +80 -0
- package/dist/types/cloudflare.js +1 -0
- package/dist/{types-CA784ZtV.d.ts → types-5BBVU0EY.d.ts} +28 -1
- package/dist/types-B5wq2iKZ.d.ts +30 -0
- package/dist/types-BAcN7U0B.d.ts +40 -0
- package/dist/types-BCsipBBX.d.ts +38 -0
- package/dist/types-BNui1SQl.d.ts +89 -0
- package/dist/{types-DlIkjpdK.d.ts → types-BdRvpp1z.d.ts} +5 -3
- package/dist/{types-BO3G_MZk.d.ts → types-Bjef1r9u.d.ts} +1 -1
- package/dist/{memory-B_NZbOQP.d.ts → types-Di38wHnA.d.ts} +21 -126
- package/dist/{types-DnQWCfXp.d.ts → types-SnlsH9UT.d.ts} +1 -1
- package/dist/{versioning-BG8-R7C0.d.ts → versioning/index.d.ts} +16 -138
- package/dist/versioning/index.js +1 -0
- package/package.json +53 -4
- package/dist/chunk-3UFSQECZ.js +0 -1
- package/dist/chunk-4O2JRCJE.js +0 -10
- package/dist/chunk-6UMKXMI6.js +0 -1
- package/dist/chunk-GPY4KIVI.js +0 -1
- package/dist/chunk-HFAUW4XN.js +0 -33
- package/dist/chunk-OF4XNWYW.js +0 -1
- package/dist/chunk-OG6VCZ64.js +0 -1
- package/dist/chunk-RRA3AHAE.js +0 -1
- package/dist/chunk-T7HH5Y3I.js +0 -1
- package/dist/chunk-TXBOO4S5.js +0 -1
- package/dist/chunk-UXKMF6AR.js +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -18,6 +18,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
18
18
|
%b
|
|
19
19
|
%b
|
|
20
20
|
%b
|
|
21
|
+
%b
|
|
22
|
+
%b
|
|
21
23
|
## [0.1.0] - 2025-01-29
|
|
22
24
|
|
|
23
25
|
### Added
|
|
@@ -52,3 +54,5 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
52
54
|
[0.4.2]: https://github.com/kshdotdev/hono-crud/compare/v0.4.1...v0.4.2
|
|
53
55
|
[0.4.3]: https://github.com/kshdotdev/hono-crud/compare/v0.4.2...v0.4.3
|
|
54
56
|
[0.4.4]: https://github.com/kshdotdev/hono-crud/compare/v0.4.3...v0.4.4
|
|
57
|
+
[0.5.0]: https://github.com/kshdotdev/hono-crud/compare/v0.4.4...v0.5.0
|
|
58
|
+
[0.5.1]: https://github.com/kshdotdev/hono-crud/compare/v0.5.0...v0.5.1
|
|
@@ -1,13 +1,18 @@
|
|
|
1
1
|
import { Table, SQL, Column } from 'drizzle-orm';
|
|
2
|
-
import { M as MetaInput, I as IncludeOptions, F as FilterCondition,
|
|
2
|
+
import { M as MetaInput, I as IncludeOptions, F 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-5BBVU0EY.js';
|
|
3
3
|
import { Env } from 'hono';
|
|
4
|
-
import {
|
|
5
|
-
import { A as AdapterBundle } from '../../index-
|
|
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, i as VersionHistoryEndpoint, j as VersionReadEndpoint, k as VersionRollbackEndpoint } from '../../import-BHD2B1u8.js';
|
|
5
|
+
import { A as AdapterBundle } from '../../index-BNIzQvcO.js';
|
|
6
6
|
import { z } from 'zod';
|
|
7
|
+
import '../../types-B5wq2iKZ.js';
|
|
8
|
+
import '../../types-BAcN7U0B.js';
|
|
7
9
|
import '@hono/zod-openapi';
|
|
8
|
-
import '../../route-
|
|
10
|
+
import '../../route-BmtmmHSO.js';
|
|
9
11
|
import 'hono/utils/http-status';
|
|
10
|
-
import '../../
|
|
12
|
+
import '../../audit/index.js';
|
|
13
|
+
import '../../registry-PNJjvSvm.js';
|
|
14
|
+
import '../../versioning/index.js';
|
|
15
|
+
import '../../types-BCsipBBX.js';
|
|
11
16
|
|
|
12
17
|
/**
|
|
13
18
|
* Internal query builder interface used for type-safe method calls.
|
|
@@ -188,7 +193,7 @@ declare abstract class DrizzleCreateEndpoint<E extends Env = Env, M extends Meta
|
|
|
188
193
|
*/
|
|
189
194
|
protected useTransaction: boolean;
|
|
190
195
|
/** Current transaction context (set during transaction execution) */
|
|
191
|
-
|
|
196
|
+
protected _tx?: DrizzleDatabase;
|
|
192
197
|
/**
|
|
193
198
|
* Gets the database instance to use. Checks in order:
|
|
194
199
|
* 1. Transaction context (if in transaction)
|
|
@@ -246,7 +251,7 @@ declare abstract class DrizzleUpdateEndpoint<E extends Env = Env, M extends Meta
|
|
|
246
251
|
*/
|
|
247
252
|
protected useTransaction: boolean;
|
|
248
253
|
/** Current transaction context (set during transaction execution) */
|
|
249
|
-
|
|
254
|
+
protected _tx?: DrizzleDatabase;
|
|
250
255
|
/** Gets the database instance from property, transaction, or context */
|
|
251
256
|
protected getDb(): DrizzleDatabase;
|
|
252
257
|
protected getTable(): Table;
|
|
@@ -286,7 +291,7 @@ declare abstract class DrizzleDeleteEndpoint<E extends Env = Env, M extends Meta
|
|
|
286
291
|
*/
|
|
287
292
|
protected useTransaction: boolean;
|
|
288
293
|
/** Current transaction context (set during transaction execution) */
|
|
289
|
-
|
|
294
|
+
protected _tx?: DrizzleDatabase;
|
|
290
295
|
/** Gets the database instance from property, transaction, or context */
|
|
291
296
|
protected getDb(): DrizzleDatabase;
|
|
292
297
|
protected getTable(): Table;
|
|
@@ -352,7 +357,7 @@ declare abstract class DrizzleRestoreEndpoint<E extends Env = Env, M extends Met
|
|
|
352
357
|
*/
|
|
353
358
|
protected useTransaction: boolean;
|
|
354
359
|
/** Current transaction context (set during transaction execution) */
|
|
355
|
-
|
|
360
|
+
protected _tx?: DrizzleDatabase;
|
|
356
361
|
/** Gets the database instance from property, transaction, or context */
|
|
357
362
|
protected getDb(): DrizzleDatabase;
|
|
358
363
|
protected getTable(): Table;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {k,l,m as m$1,n,o,p,r,s,t,u,q as q$1,v as v$1,w,x,y as y$1,z as z$1,A,B as B$1,J,K,T,U as U$1}from'../../chunk-Q4FF5JVS.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-W4FHI5YI.js';import'../../chunk-HAUN4LQO.js';import'../../chunk-NIWM7GOK.js';import'../../chunk-RFT77JBK.js';import'../../chunk-FC56WWPB.js';import'../../chunk-GBQQ3YQX.js';import'../../chunk-QRXEQTNE.js';import'../../chunk-QXFY6NYI.js';import {b}from'../../chunk-DMGP7QDL.js';import'../../chunk-MDHMZPXK.js';import'../../chunk-VJRDAVID.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 L(l){return l}function f(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 Te(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 a=m(t,n.foreignKey),i=await l.select().from(t).where(eq(a,s)).limit(1);return {...e,[o]:i[0]||null}}case "hasMany":{let r=n.localKey||"id",s=e[r];if(s==null)return {...e,[o]:[]};let a=m(t,n.foreignKey),i=await l.select().from(t).where(eq(a,s));return {...e,[o]:i}}case "belongsTo":{let r=e[n.foreignKey];if(r==null)return {...e,[o]:null};let s=m(t,n.localKey||"id"),a=await l.select().from(t).where(eq(s,r)).limit(1);return {...e,[o]:a[0]||null}}default:return e}}async function ee(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 Te(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 a=s.table;switch(s.type){case "hasOne":case "hasMany":{let i=s.localKey||"id",u=[...new Set(t.map(p=>p[i]).filter(p=>p!=null))];if(u.length===0){t=t.map(p=>({...p,[r]:s.type==="hasMany"?[]:null}));continue}let c=m(a,s.foreignKey),d=await l.select().from(a).where(inArray(c,u)),g=new Map;for(let p of d){let b=p[s.foreignKey];g.has(b)||g.set(b,[]),g.get(b).push(p);}t=t.map(p=>{let b=p[i],D=g.get(b)||[];return {...p,[r]:s.type==="hasMany"?D:D[0]||null}});break}case "belongsTo":{let i=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 c=m(a,i),d=await l.select().from(a).where(inArray(c,u)),g=new Map;for(let p of d){let b=p[i];g.set(b,p);}t=t.map(p=>{let b=p[s.foreignKey];return {...p,[r]:g.get(b)||null}});break}}}return t}function E(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 y(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
2
|
1. Set db property: db = myDb;
|
|
3
3
|
2. Use middleware: c.set("db", myDb);
|
|
4
|
-
3. Use factory: createDrizzleCrud(db, meta)`)}getTable(){return f(this._meta)}getRelatedTable(e){return e.table}async create(e,r){let n=r??this.getDb(),t=this.getTable(),o=this._meta.model.primaryKeys[0],s={...e,[o]:e[o]||crypto.randomUUID()};return (await n.insert(t).values(s).returning())[0]}async createNested(e,r,n,t,o){let s=o??this.getDb(),a=this.getRelatedTable(n);if(!a)return b().warn(`Related table not found for ${r}. 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},p=await s.insert(a).values(c).returning();p[0]&&u.push(p[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()}},j=class extends k{db;getDb(){if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error("Database not configured. Set db property or use middleware.")}getTable(){return f(this._meta)}getColumn(e){return g(this.getTable(),e)}async read(e,r,n){let t=this.getTable(),o=this.getColumn(this.lookupField),s=this.getSoftDeleteConfig(),a=[eq(o,e)];if(r)for(let[d,c]of Object.entries(r))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 Y(this.getDb(),i[0],this._meta,n):null}},_=class extends l{db;useTransaction=false;_tx;getDb(){if(this._tx)return this._tx;if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error("Database not configured. Set db property or use middleware.")}getTable(){return f(this._meta)}getColumn(e){return g(this.getTable(),e)}getRelatedTable(e){return e.table}async findExisting(e,r,n){let t=n??this.getDb(),o=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),i=[eq(s,e)];if(r)for(let[d,c]of Object.entries(r))i.push(eq(this.getColumn(d),c));return a.enabled&&i.push(isNull(this.getColumn(a.field))),(await t.select().from(o).where(and(...i)).limit(1))[0]||null}async update(e,r,n,t){let o=t??this.getDb(),s=this.getTable(),a=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),u=[eq(a,e)];if(n)for(let[c,p]of Object.entries(n))u.push(eq(this.getColumn(c),p));return i.enabled&&u.push(isNull(this.getColumn(i.field))),(await o.update(s).set(r).where(and(...u)).returning())[0]||null}async processNestedWrites(e,r,n,t,o){let s=o??this.getDb(),a=this.getRelatedTable(n);if(!a)return b().warn(`Related table not found for ${r}. Add 'table' to the relation config.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]};let i={created:[],updated:[],deleted:[],connected:[],disconnected:[]},u=g(a,n.foreignKey),d=g(a,"id");if(t.create){let c=Array.isArray(t.create)?t.create:[t.create];for(let p of c){if(typeof p!="object"||p===null)continue;let b={...p,id:crypto.randomUUID(),[n.foreignKey]:e},m=await s.insert(a).values(b).returning();m[0]&&i.created.push(m[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:b,...m}=c,D=await s.update(a).set(m).where(eq(d,b)).returning();D[0]&&i.updated.push(D[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()}},I=class extends m{db;useTransaction=false;_tx;getDb(){if(this._tx)return this._tx;if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error("Database not configured. Set db property or use middleware.")}getTable(){return f(this._meta)}getColumn(e){return g(this.getTable(),e)}getRelatedTable(e){return e.table}async findForDelete(e,r,n){let t=n??this.getDb(),o=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),i=[eq(s,e)];if(r)for(let[d,c]of Object.entries(r))i.push(eq(this.getColumn(d),c));return a.enabled&&i.push(isNull(this.getColumn(a.field))),(await t.select().from(o).where(and(...i)).limit(1))[0]||null}async delete(e,r,n){let t=n??this.getDb(),o=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),i=[eq(s,e)];if(r)for(let[u,d]of Object.entries(r))i.push(eq(this.getColumn(u),d));return a.enabled&&i.push(isNull(this.getColumn(a.field))),a.enabled?(await t.update(o).set({[a.field]:new Date}).where(and(...i)).returning())[0]||null:(await t.delete(o).where(and(...i)).returning())[0]||null}async countRelated(e,r,n,t){let o=t??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let a=g(s,n.foreignKey),i=await o.select({count:sql`count(*)`}).from(s).where(eq(a,e));return Number(i[0]?.count)||0}async deleteRelated(e,r,n,t){let o=t??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let a=g(s,n.foreignKey);return (await o.delete(s).where(eq(a,e)).returning()).length}async nullifyRelated(e,r,n,t){let o=t??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let a=g(s,n.foreignKey);return (await o.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()}},P=class extends n{db;getDb(){if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error("Database not configured. Set db property or use middleware.")}getTable(){return f(this._meta)}getColumn(e){return g(this.getTable(),e)}async list(e){let r=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 x=R(r,y);x&&n.push(x);}if(e.options.search&&this.searchFields.length>0){let y=this.searchFields.map(x=>{let G=this.getColumn(x);return sql`LOWER(${G}) LIKE LOWER(${`%${e.options.search}%`})`});n.push(or(...y));}let o=n.length>0?and(...n):void 0,s=this.getDb(),a=await s.select({count:sql`count(*)`}).from(r).where(o),i=Number(a[0]?.count)||0,u=s.select().from(r).where(o);if(e.options.order_by){let y=this.getColumn(e.options.order_by),x=e.options.order_by_direction==="desc"?desc:asc;u=u.orderBy(x(y));}let d=e.options.page||1,c=e.options.per_page||this.defaultPerPage;u=u.limit(c).offset((d-1)*c);let p=await u,b={relations:e.options.include||[]},m=await v(this.getDb(),p,this._meta,b),D=Math.ceil(i/c);return {result:m,result_info:{page:d,per_page:c,total_count:i,total_pages:D,has_next_page:d<D,has_prev_page:d>1}}}},L=class extends o{db;useTransaction=false;_tx;getDb(){if(this._tx)return this._tx;if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error("Database not configured. Set db property or use middleware.")}getTable(){return f(this._meta)}getColumn(e){return g(this.getTable(),e)}async restore(e,r,n){let t=n??this.getDb(),o=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),i=[eq(s,e)];if(r)for(let[d,c]of Object.entries(r))i.push(eq(this.getColumn(d),c));return i.push(isNotNull(this.getColumn(a.field))),(await t.update(o).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 Z=class extends q$1{db;getDb(){if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error("Database not configured. Set db property or use middleware.")}getTable(){return f(this._meta)}async batchCreate(e){let r=this.getTable(),n=this._meta.model.primaryKeys[0],t=e.map(s=>({...s,[n]:s[n]||crypto.randomUUID()}));return await this.getDb().insert(r).values(t).returning()}},Q=class extends r{db;getDb(){if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error("Database not configured. Set db property or use middleware.")}getTable(){return f(this._meta)}getColumn(e){return g(this.getTable(),e)}async batchUpdate(e){let r=this.getTable(),n=this.getColumn(this.lookupField),t=this.getSoftDeleteConfig(),o=[],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(r).set(a.data).where(and(...i)).returning();u[0]?o.push(u[0]):s.push(a.id);}return {updated:o,notFound:s}}},N=class extends s{db;getDb(){if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error("Database not configured. Set db property or use middleware.")}getTable(){return f(this._meta)}getColumn(e){return g(this.getTable(),e)}async batchDelete(e){let r=this.getTable(),n=this.getColumn(this.lookupField),t=this.getSoftDeleteConfig(),o=[inArray(n,e)];t.enabled&&o.push(isNull(this.getColumn(t.field)));let s;t.enabled?s=await this.getDb().update(r).set({[t.field]:new Date}).where(and(...o)).returning():s=await this.getDb().delete(r).where(and(...o)).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}}},F=class extends t{db;getDb(){if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error("Database not configured. Set db property or use middleware.")}getTable(){return f(this._meta)}getColumn(e){return g(this.getTable(),e)}async batchRestore(e){let r=this.getTable(),n=this.getColumn(this.lookupField),t=this.getSoftDeleteConfig(),o=[inArray(n,e),isNotNull(this.getColumn(t.field))],a=await this.getDb().update(r).set({[t.field]:null}).where(and(...o)).returning(),i=new Set(a.map(d=>String(d[this.lookupField]))),u=e.filter(d=>!i.has(d));return {restored:a,notFound:u}}};var $=class extends p{db;getDb(){if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error("Database not configured. Set db property or use middleware.")}getTable(){return f(this._meta)}getColumn(e){return g(this.getTable(),e)}async findExisting(e){let r=this.getTable(),n=this.getUpsertKeys(),t=this.getSoftDeleteConfig(),o=[];for(let a of n){let i=e[a];i!==void 0&&o.push(eq(this.getColumn(a),i));}return t.enabled&&o.push(isNull(this.getColumn(t.field))),o.length===0?null:(await this.getDb().select().from(r).where(and(...o)).limit(1))[0]||null}async create(e){let r=this.getTable(),n=this._meta.model.primaryKeys[0],t={...e,[n]:e[n]||crypto.randomUUID()};return (await this.getDb().insert(r).values(t).returning())[0]}async update(e,r){let n=this.getTable(),t=this._meta.model.primaryKeys[0],o=e[t];return (await this.getDb().update(n).set(r).where(eq(this.getColumn(t),o)).returning())[0]}async nativeUpsert(e,r){let n=this.getTable(),t=this.getUpsertKeys(),o=this._meta.model.primaryKeys[0],s=this.getSoftDeleteConfig(),a={...e,[o]:e[o]||crypto.randomUUID()},i={};for(let[c,p]of Object.entries(e))!t.includes(c)&&c!==o&&(this.createOnlyFields?.includes(c)||(i[c]=p));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:{[o]:sql`${this.getColumn(o)}`},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:{[o]:sql`${this.getColumn(o)}`}}).returning())[0],created:!1}}catch{return this.performStandardUpsert(e,r)}throw c}}},q=class extends u{db;getDb(){if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error("Database not configured. Set db property or use middleware.")}getTable(){return f(this._meta)}getColumn(e){return g(this.getTable(),e)}async findExisting(e){let r=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(r).where(and(...t)).limit(1))[0]||null}async create(e){let r=this.getTable(),n=this._meta.model.primaryKeys[0],t={...e,[n]:e[n]||crypto.randomUUID()};return (await this.getDb().insert(r).values(t).returning())[0]}async update(e,r){let n=this.getTable(),t=this._meta.model.primaryKeys[0],o=e[t];return (await this.getDb().update(n).set(r).where(eq(this.getColumn(t),o)).returning())[0]}async nativeBatchUpsert(e,r){if(e.length===0)return {items:[],createdCount:0,updatedCount:0,totalCount:0};let n=this.getTable(),t=this.getUpsertKeys(),o=this._meta.model.primaryKeys[0],s=e.map(d=>({...d,[o]:d[o]||crypto.randomUUID()})),a={},i=e[0];for(let d of Object.keys(i))!t.includes(d)&&d!==o&&(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:{[o]:sql`${this.getColumn(o)}`}}).returning();return {items:c.map((p,b)=>({data:p,created:!1,index:b})),createdCount:0,updatedCount:c.length,totalCount:c.length}}catch(d){if(d instanceof Error&&d.message.includes("onConflictDoUpdate"))try{let p=await this.getDb().insert(n).values(s).onDuplicateKeyUpdate({set:Object.keys(a).length>0?a:{[o]:sql`${this.getColumn(o)}`}}).returning();return {items:p.map((b,m)=>({data:b,created:!1,index:m})),createdCount:0,updatedCount:p.length,totalCount:p.length}}catch{return this.performStandardBatchUpsert(e,r)}throw d}}},Ee=class extends v$1{db;getDb(){if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error("Database not configured. Set db property or use middleware.")}getTable(){return f(this._meta)}getColumn(e){return g(this.getTable(),e)}async recordExists(e){let r=this.getTable(),n=await this.getDb().select({count:sql`count(*)`}).from(r).where(eq(this.getColumn("id"),e));return Number(n[0]?.count)>0}},ve=class extends w{},ke=class extends x{},Oe=class extends y{db;getDb(){if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error("Database not configured. Set db property or use middleware.")}getTable(){return f(this._meta)}getColumn(e){return g(this.getTable(),e)}async rollback(e,r,n){let t=this.getTable(),o=this.getVersioningConfig().field;return (await this.getDb().update(t).set({...r,[o]:n}).where(eq(this.getColumn("id"),e)).returning())[0]}},Se=class extends z$1{db;getDb(){if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error("Database not configured. Set db property or use middleware.")}getTable(){return f(this._meta)}getColumn(e){return g(this.getTable(),e)}async aggregate(e){let r=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=R(r,{field:a,operator:u,value:d});c&&n.push(c);}else n.push(eq(this.getColumn(a),i));let o=n.length>0?and(...n):void 0,s=await this.getDb().select().from(r).where(o);return A$1(s,e)}},je=class extends I$1{db;getDb(){if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error("Database not configured. Set db property or use middleware.")}useNativeSearch=false;vectorColumn;vectorConfig="english";getTable(){return f(this._meta)}getColumn(e){return g(this.getTable(),e)}async search(e,r){let n=this.getTable(),t=[],o=this.getSoftDeleteConfig();o.enabled&&(r.options.onlyDeleted?t.push(isNotNull(this.getColumn(o.field))):r.options.withDeleted||t.push(isNull(this.getColumn(o.field))));for(let w of r.filters){let M=R(n,w);M&&t.push(M);}let s=this.getSearchableFields(),a=e.fields||Object.keys(s);if(this.useNativeSearch&&this.vectorColumn){let w=this.getColumn(this.vectorColumn),M=e.mode==="phrase"?sql`phraseto_tsquery(${this.vectorConfig}, ${e.query})`:e.mode==="all"?sql`plainto_tsquery(${this.vectorConfig}, ${e.query})`:sql`to_tsquery(${this.vectorConfig}, ${e.query.split(/\s+/).join(" | ")})`;t.push(sql`${w} @@ ${M}`);}else {let w=a.map(M=>{try{let Ze=this.getColumn(M);return sql`LOWER(CAST(${Ze} AS TEXT)) LIKE LOWER(${`%${e.query}%`})`}catch{return}}).filter(M=>M!==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(r.options.order_by){let w=this.getColumn(r.options.order_by),M=r.options.order_by_direction==="desc"?desc:asc;c=c.orderBy(M(w));}let p=r.options.page||1,b=r.options.per_page||this.defaultPerPage;c=c.limit(b).offset((p-1)*b);let m=await c,D=J(m,e,s),y={relations:r.options.include||[]},x=D.map(w=>w.item),G=await v(this.getDb(),x,this._meta,y);return {items:D.map((w,M)=>({...w,item:G[M]})),totalCount:d}}},_e=class extends S$1{db;getDb(){if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error("Database not configured. Set db property or use middleware.")}getTable(){return f(this._meta)}getColumn(e){return g(this.getTable(),e)}async list(e){let r=this.getTable(),n=[],t=this.getSoftDeleteConfig();if(t.enabled){let D=this.getColumn(t.field);e.options.onlyDeleted?n.push(isNotNull(D)):e.options.withDeleted||n.push(isNull(D));}for(let D of e.filters){let y=R(r,D);y&&n.push(y);}if(e.options.search&&this.searchFields.length>0){let D=this.searchFields.map(y=>{let x=this.getColumn(y);return sql`LOWER(${x}) LIKE LOWER(${`%${e.options.search}%`})`});n.push(or(...D));}let o=n.length>0?and(...n):void 0,s=await this.getDb().select({count:sql`count(*)`}).from(r).where(o),a=Number(s[0]?.count)||0,i=this.getDb().select().from(r).where(o);if(e.options.order_by){let D=this.getColumn(e.options.order_by),y=e.options.order_by_direction==="desc"?desc:asc;i=i.orderBy(y(D));}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,p={relations:e.options.include||[]},b=await v(this.getDb(),c,this._meta,p),m=Math.ceil(a/d);return {result:b,result_info:{page:u,per_page:d,total_count:a,total_pages:m,has_next_page:u<m,has_prev_page:u>1}}}},Ie=class extends T{db;getDb(){if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error("Database not configured. Set db property or use middleware.")}getTable(){return f(this._meta)}getColumn(e){return g(this.getTable(),e)}async findExisting(e){let r=this.getTable(),n=this.getUpsertKeys(),t=this.getSoftDeleteConfig(),o=[];for(let a of n){let i=e[a];i!==void 0&&o.push(eq(this.getColumn(a),i));}return t.enabled&&o.push(isNull(this.getColumn(t.field))),o.length===0?null:(await this.getDb().select().from(r).where(and(...o)).limit(1))[0]||null}async create(e){let r=this.getTable(),n=this._meta.model.primaryKeys[0],t={...e,[n]:e[n]||crypto.randomUUID()};return (await this.getDb().insert(r).values(t).returning())[0]}async update(e,r){let n=this.getTable(),t=this._meta.model.primaryKeys[0],o=e[t];return (await this.getDb().update(n).set(r).where(eq(this.getColumn(t),o)).returning())[0]}};function qt(l,e){return {Create:class extends S{_meta=e;db=l},Read:class extends j{_meta=e;db=l},Update:class extends _{_meta=e;db=l},Delete:class extends I{_meta=e;db=l},List:class extends P{_meta=e;db=l},Restore:class extends L{_meta=e;db=l},Upsert:class extends ${_meta=e;db=l},BatchCreate:class extends Z{_meta=e;db=l},BatchUpdate:class extends Q{_meta=e;db=l},BatchDelete:class extends N{_meta=e;db=l},BatchRestore:class extends F{_meta=e;db=l},BatchUpsert:class extends q{_meta=e;db=l}}}var Wt={CreateEndpoint:S,ListEndpoint:P,ReadEndpoint:j,UpdateEndpoint:_,DeleteEndpoint:I};var V=null,Le=false,W=null;async function X(){if(Le){if(W)throw W;return V}Le=true;try{return V=await import('drizzle-zod'),V}catch{throw W=new Error("drizzle-zod is not installed. Please install it: npm install drizzle-zod"),W}}async function st(l,e){return (await X()).createSelectSchema(l,e)}async function at(l,e){return (await X()).createInsertSchema(l,e)}async function it(l,e){let r=await X();return r.createUpdateSchema?r.createUpdateSchema(l,e):r.createInsertSchema(l,e).partial()}async function lt(l,e){let r=await X(),n=e?.coerceDates!==false,t=n?bt(l):new Set,o=r.createSelectSchema(l,e?.selectRefine),s=r.createInsertSchema(l,e?.insertRefine),a;return r.createUpdateSchema?a=r.createUpdateSchema(l,e?.updateRefine):a=r.createInsertSchema(l,e?.updateRefine).partial(),n&&t.size>0&&(s=Be(s,t),a=Be(a,t)),{select:o,insert:s,update:a}}function dt(){return V!==null}var ct=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()),ut=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,r=l;for(let[n,t]of Object.entries(r)){if(n==="_"||n==="$inferInsert"||n==="$inferSelect")continue;let o=t;if(!o||typeof o!="object")continue;let s=String(o.dataType??"").toLowerCase(),a=String(o.columnType??"").toLowerCase(),i=o.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 Be(l,e){if(e.size===0)return l;let r=l.shape,n={};for(let[t,o]of Object.entries(r))if(e.has(t)){let s=o.isOptional?.()??false,a=o.isNullable?.()??false,i=ct;(a||s)&&(i=ut),s&&(i=i.optional()),n[t]=i;}else n[t]=o;return z.object(n)}export{Wt as DrizzleAdapters,Se as DrizzleAggregateEndpoint,Z as DrizzleBatchCreateEndpoint,N as DrizzleBatchDeleteEndpoint,F as DrizzleBatchRestoreEndpoint,Q as DrizzleBatchUpdateEndpoint,q as DrizzleBatchUpsertEndpoint,S as DrizzleCreateEndpoint,I as DrizzleDeleteEndpoint,_e as DrizzleExportEndpoint,Ie as DrizzleImportEndpoint,P as DrizzleListEndpoint,j as DrizzleReadEndpoint,L as DrizzleRestoreEndpoint,je as DrizzleSearchEndpoint,_ as DrizzleUpdateEndpoint,$ as DrizzleUpsertEndpoint,ke as DrizzleVersionCompareEndpoint,Ee as DrizzleVersionHistoryEndpoint,ve as DrizzleVersionReadEndpoint,Oe as DrizzleVersionRollbackEndpoint,v as batchLoadDrizzleRelations,R as buildWhereCondition,A as cast,qt as createDrizzleCrud,lt as createDrizzleSchemas,at as createInsertSchema,st as createSelectSchema,it as createUpdateSchema,g as getColumn,f as getTable,dt as isDrizzleZodAvailable,Ce as loadDrizzleRelation,Y as loadDrizzleRelations};
|
|
4
|
+
3. Use factory: createDrizzleCrud(db, meta)`)}var S=class extends k{db;useTransaction=false;_tx;getDb(){return y(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 c of i){if(typeof c!="object"||c===null)continue;let d={...c,id:crypto.randomUUID(),[n.foreignKey]:e},g=await s.insert(a).values(d).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 y(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[c,d]of Object.entries(o))a.push(eq(this.getColumn(c),d));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;_tx;getDb(){return y(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[c,d]of Object.entries(o))i.push(eq(this.getColumn(c),d));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[d,g]of Object.entries(n))u.push(eq(this.getColumn(d),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),c=m(a,"id");if(t.create){let d=Array.isArray(t.create)?t.create:[t.create];for(let g of d){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 d of t.update){if(!d.id||!(await s.select().from(a).where(and(eq(c,d.id),eq(u,e))).limit(1))[0])continue;let{id:p,...b}=d,D=await s.update(a).set(b).where(eq(c,p)).returning();D[0]&&i.updated.push(D[0]);}if(t.delete)for(let d of t.delete)(await s.delete(a).where(and(eq(c,d),eq(u,e))).returning())[0]&&i.deleted.push(d);if(t.connect)for(let d of t.connect)(await s.update(a).set({[n.foreignKey]:e}).where(eq(c,d)).returning())[0]&&i.connected.push(d);if(t.disconnect)for(let d of t.disconnect)(await s.update(a).set({[n.foreignKey]:null}).where(and(eq(c,d),eq(u,e))).returning())[0]&&i.disconnected.push(d);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;_tx;getDb(){return y(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[c,d]of Object.entries(o))i.push(eq(this.getColumn(c),d));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,c]of Object.entries(o))i.push(eq(this.getColumn(u),c));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 y(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=E(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 c=e.options.page||1,d=e.options.per_page||this.defaultPerPage;u=u.limit(d).offset((c-1)*d);let g=await u,p={relations:e.options.include||[]},b=await v(this.getDb(),g,this._meta,p),D=Math.ceil(i/d);return {result:b,result_info:{page:c,per_page:d,total_count:i,total_pages:D,has_next_page:c<D,has_prev_page:c>1}}}},B=class extends p{db;useTransaction=false;_tx;getDb(){return y(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[c,d]of Object.entries(o))i.push(eq(this.getColumn(c),d));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 y(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 y(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 y(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(c=>String(c[this.lookupField]))),u=e.filter(c=>!i.has(c));return {deleted:a,notFound:u}}},$=class extends u{db;getDb(){return y(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(c=>String(c[this.lookupField]))),u=e.filter(c=>!i.has(c));return {restored:a,notFound:u}}};var q=class extends q$1{db;getDb(){return y(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[d,g]of Object.entries(e))!t.includes(d)&&d!==r&&(this.createOnlyFields?.includes(d)||(i[d]=g));let u=t.map(d=>this.getColumn(d)),c;s.enabled&&(c=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:c}).returning())[0],created:!1}}catch(d){if(d instanceof Error&&d.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 d}}},W=class extends v$1{db;getDb(){return y(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(c=>({...c,[r]:c[r]||crypto.randomUUID()})),a={},i=e[0];for(let c of Object.keys(i))!t.includes(c)&&c!==r&&(this.createOnlyFields?.includes(c)||(a[c]=sql`excluded.${sql.identifier(c)}`));let u=t.map(c=>this.getColumn(c));try{let d=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:d.map((g,p)=>({data:g,created:!1,index:p})),createdCount:0,updatedCount:d.length,totalCount:d.length}}catch(c){if(c instanceof Error&&c.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 c}}},ke=class extends w{db;getDb(){return y(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}},ve=class extends x{},Oe=class extends y$1{},je=class extends z$1{db;getDb(){return y(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 y(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,c]of Object.entries(i)){let d=E(o,{field:a,operator:u,value:c});d&&n.push(d);}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 y(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=E(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),c=Number(u[0]?.count)||0,d=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;d=d.orderBy(C(w));}let g=o.options.page||1,p=o.options.per_page||this.defaultPerPage;d=d.limit(p).offset((g-1)*p);let b=await d,D=K(b,e,s),z={relations:o.options.include||[]},R=D.map(w=>w.item),H=await v(this.getDb(),R,this._meta,z);return {items:D.map((w,C)=>({...w,item:H[C]})),totalCount:c}}},Ie=class extends T{db;getDb(){return y(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 D=this.getColumn(t.field);e.options.onlyDeleted?n.push(isNotNull(D)):e.options.withDeleted||n.push(isNull(D));}for(let D of e.filters){let z=E(o,D);z&&n.push(z);}if(e.options.search&&this.searchFields.length>0){let D=this.searchFields.map(z=>{let R=this.getColumn(z);return sql`LOWER(${R}) LIKE LOWER(${`%${e.options.search}%`})`});n.push(or(...D));}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 D=this.getColumn(e.options.order_by),z=e.options.order_by_direction==="desc"?desc:asc;i=i.orderBy(z(D));}let u=e.options.page||1,c=e.options.per_page||this.defaultPerPage;i=i.limit(c).offset((u-1)*c);let d=await i,g={relations:e.options.include||[]},p=await v(this.getDb(),d,this._meta,g),b=Math.ceil(a/c);return {result:p,result_info:{page:u,per_page:c,total_count:a,total_pages:b,has_next_page:u<b,has_prev_page:u>1}}}},Pe=class extends U$1{db;getDb(){return y(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 ct(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 dt(){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,Oe as DrizzleVersionCompareEndpoint,ke as DrizzleVersionHistoryEndpoint,ve as DrizzleVersionReadEndpoint,je as DrizzleVersionRollbackEndpoint,v as batchLoadDrizzleRelations,E as buildWhereCondition,L as cast,Ht as createDrizzleCrud,ct as createDrizzleSchemas,it as createInsertSchema,at as createSelectSchema,lt as createUpdateSchema,m as getColumn,f as getTable,dt as isDrizzleZodAvailable,Te as loadDrizzleRelation,ee as loadDrizzleRelations};
|
|
@@ -1,12 +1,17 @@
|
|
|
1
1
|
import { Env } from 'hono';
|
|
2
|
-
import {
|
|
3
|
-
import { M as MetaInput,
|
|
4
|
-
import { B as BulkPatchEndpoint, C as CloneEndpoint } from '../../bulk-patch-
|
|
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, h as UpsertEndpoint, V as VersionCompareEndpoint, i as VersionHistoryEndpoint, j as VersionReadEndpoint, k as VersionRollbackEndpoint } from '../../import-BHD2B1u8.js';
|
|
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-5BBVU0EY.js';
|
|
4
|
+
import { B as BulkPatchEndpoint, C as CloneEndpoint } from '../../bulk-patch-CoEduhTf.js';
|
|
5
5
|
import 'zod';
|
|
6
|
-
import '../../route-
|
|
6
|
+
import '../../route-BmtmmHSO.js';
|
|
7
7
|
import 'hono/utils/http-status';
|
|
8
|
-
import '../../
|
|
8
|
+
import '../../audit/index.js';
|
|
9
|
+
import '../../registry-PNJjvSvm.js';
|
|
10
|
+
import '../../types-B5wq2iKZ.js';
|
|
11
|
+
import '../../types-BAcN7U0B.js';
|
|
9
12
|
import '@hono/zod-openapi';
|
|
13
|
+
import '../../versioning/index.js';
|
|
14
|
+
import '../../types-BCsipBBX.js';
|
|
10
15
|
|
|
11
16
|
/**
|
|
12
17
|
* Module-level in-memory storage.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{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,e as clearStorage,f as getStorage,d as getStore,c as storage}from'../../chunk-
|
|
1
|
+
export{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,e as clearStorage,f as getStorage,d as getStore,c as storage}from'../../chunk-Q2D5AUPJ.js';import'../../chunk-Q4FF5JVS.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-W4FHI5YI.js';import'../../chunk-HAUN4LQO.js';import'../../chunk-NIWM7GOK.js';import'../../chunk-RFT77JBK.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';
|
|
@@ -1,11 +1,16 @@
|
|
|
1
1
|
import { Env } from 'hono';
|
|
2
|
-
import {
|
|
3
|
-
import { M as MetaInput, L as ListFilters, P as PaginatedResult, I as IncludeOptions,
|
|
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, h as UpsertEndpoint, V as VersionCompareEndpoint, i as VersionHistoryEndpoint, j as VersionReadEndpoint, k as VersionRollbackEndpoint } from '../../import-BHD2B1u8.js';
|
|
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-5BBVU0EY.js';
|
|
4
4
|
import 'zod';
|
|
5
|
-
import '../../route-
|
|
5
|
+
import '../../route-BmtmmHSO.js';
|
|
6
6
|
import 'hono/utils/http-status';
|
|
7
|
-
import '../../
|
|
7
|
+
import '../../audit/index.js';
|
|
8
|
+
import '../../registry-PNJjvSvm.js';
|
|
9
|
+
import '../../types-B5wq2iKZ.js';
|
|
10
|
+
import '../../types-BAcN7U0B.js';
|
|
8
11
|
import '@hono/zod-openapi';
|
|
12
|
+
import '../../versioning/index.js';
|
|
13
|
+
import '../../types-BCsipBBX.js';
|
|
9
14
|
|
|
10
15
|
/**
|
|
11
16
|
* Prisma adapter helpers: types, model resolution, relation loading, query utils.
|
|
@@ -110,7 +115,7 @@ declare function clearPrismaModelMappings(): void;
|
|
|
110
115
|
declare abstract class PrismaCreateEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends CreateEndpoint<E, M> {
|
|
111
116
|
abstract prisma: PrismaClient;
|
|
112
117
|
protected useTransaction: boolean;
|
|
113
|
-
protected getModel(): PrismaModelOperations
|
|
118
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
114
119
|
create(data: ModelObject<M['model']>): Promise<ModelObject<M['model']>>;
|
|
115
120
|
}
|
|
116
121
|
/**
|
|
@@ -118,7 +123,7 @@ declare abstract class PrismaCreateEndpoint<E extends Env = Env, M extends MetaI
|
|
|
118
123
|
*/
|
|
119
124
|
declare abstract class PrismaReadEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends ReadEndpoint<E, M> {
|
|
120
125
|
abstract prisma: PrismaClient;
|
|
121
|
-
protected getModel(): PrismaModelOperations
|
|
126
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
122
127
|
read(lookupValue: string, additionalFilters?: Record<string, string>, includeOptions?: IncludeOptions): Promise<ModelObject<M['model']> | null>;
|
|
123
128
|
}
|
|
124
129
|
/**
|
|
@@ -127,7 +132,7 @@ declare abstract class PrismaReadEndpoint<E extends Env = Env, M extends MetaInp
|
|
|
127
132
|
declare abstract class PrismaUpdateEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends UpdateEndpoint<E, M> {
|
|
128
133
|
abstract prisma: PrismaClient;
|
|
129
134
|
protected useTransaction: boolean;
|
|
130
|
-
protected getModel(): PrismaModelOperations
|
|
135
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
131
136
|
update(lookupValue: string, data: Partial<ModelObject<M['model']>>, additionalFilters?: Record<string, string>): Promise<ModelObject<M['model']> | null>;
|
|
132
137
|
}
|
|
133
138
|
/**
|
|
@@ -136,7 +141,7 @@ declare abstract class PrismaUpdateEndpoint<E extends Env = Env, M extends MetaI
|
|
|
136
141
|
declare abstract class PrismaDeleteEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends DeleteEndpoint<E, M> {
|
|
137
142
|
abstract prisma: PrismaClient;
|
|
138
143
|
protected useTransaction: boolean;
|
|
139
|
-
protected getModel(): PrismaModelOperations
|
|
144
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
140
145
|
/**
|
|
141
146
|
* Finds a record without deleting it (for constraint checks).
|
|
142
147
|
*/
|
|
@@ -148,7 +153,7 @@ declare abstract class PrismaDeleteEndpoint<E extends Env = Env, M extends MetaI
|
|
|
148
153
|
*/
|
|
149
154
|
declare abstract class PrismaListEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends ListEndpoint<E, M> {
|
|
150
155
|
abstract prisma: PrismaClient;
|
|
151
|
-
protected getModel(): PrismaModelOperations
|
|
156
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
152
157
|
list(filters: ListFilters): Promise<PaginatedResult<ModelObject<M['model']>>>;
|
|
153
158
|
}
|
|
154
159
|
|
|
@@ -161,7 +166,7 @@ declare abstract class PrismaListEndpoint<E extends Env = Env, M extends MetaInp
|
|
|
161
166
|
declare abstract class PrismaRestoreEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends RestoreEndpoint<E, M> {
|
|
162
167
|
abstract prisma: PrismaClient;
|
|
163
168
|
protected useTransaction: boolean;
|
|
164
|
-
protected getModel(): PrismaModelOperations
|
|
169
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
165
170
|
restore(lookupValue: string, additionalFilters?: Record<string, string>): Promise<ModelObject<M['model']> | null>;
|
|
166
171
|
}
|
|
167
172
|
/**
|
|
@@ -170,7 +175,7 @@ declare abstract class PrismaRestoreEndpoint<E extends Env = Env, M extends Meta
|
|
|
170
175
|
*/
|
|
171
176
|
declare abstract class PrismaBatchCreateEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends BatchCreateEndpoint<E, M> {
|
|
172
177
|
abstract prisma: PrismaClient;
|
|
173
|
-
protected getModel(): PrismaModelOperations
|
|
178
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
174
179
|
batchCreate(items: Partial<ModelObject<M['model']>>[]): Promise<ModelObject<M['model']>[]>;
|
|
175
180
|
}
|
|
176
181
|
/**
|
|
@@ -181,7 +186,7 @@ declare abstract class PrismaBatchCreateEndpoint<E extends Env = Env, M extends
|
|
|
181
186
|
*/
|
|
182
187
|
declare abstract class PrismaBatchUpdateEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends BatchUpdateEndpoint<E, M> {
|
|
183
188
|
abstract prisma: PrismaClient;
|
|
184
|
-
protected getModel(): PrismaModelOperations
|
|
189
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
185
190
|
batchUpdate(items: BatchUpdateItem<ModelObject<M['model']>>[]): Promise<{
|
|
186
191
|
updated: ModelObject<M['model']>[];
|
|
187
192
|
notFound: string[];
|
|
@@ -195,7 +200,7 @@ declare abstract class PrismaBatchUpdateEndpoint<E extends Env = Env, M extends
|
|
|
195
200
|
*/
|
|
196
201
|
declare abstract class PrismaBatchDeleteEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends BatchDeleteEndpoint<E, M> {
|
|
197
202
|
abstract prisma: PrismaClient;
|
|
198
|
-
protected getModel(): PrismaModelOperations
|
|
203
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
199
204
|
batchDelete(ids: string[]): Promise<{
|
|
200
205
|
deleted: ModelObject<M['model']>[];
|
|
201
206
|
notFound: string[];
|
|
@@ -208,7 +213,7 @@ declare abstract class PrismaBatchDeleteEndpoint<E extends Env = Env, M extends
|
|
|
208
213
|
*/
|
|
209
214
|
declare abstract class PrismaBatchRestoreEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends BatchRestoreEndpoint<E, M> {
|
|
210
215
|
abstract prisma: PrismaClient;
|
|
211
|
-
protected getModel(): PrismaModelOperations
|
|
216
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
212
217
|
batchRestore(ids: string[]): Promise<{
|
|
213
218
|
restored: ModelObject<M['model']>[];
|
|
214
219
|
notFound: string[];
|
|
@@ -225,7 +230,7 @@ declare abstract class PrismaBatchRestoreEndpoint<E extends Env = Env, M extends
|
|
|
225
230
|
declare abstract class PrismaBatchUpsertEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends BatchUpsertEndpoint<E, M> {
|
|
226
231
|
abstract prisma: PrismaClient;
|
|
227
232
|
protected useTransaction: boolean;
|
|
228
|
-
protected getModel(): PrismaModelOperations
|
|
233
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
229
234
|
/**
|
|
230
235
|
* Finds an existing record by upsert keys.
|
|
231
236
|
*/
|
|
@@ -263,7 +268,7 @@ declare abstract class PrismaBatchUpsertEndpoint<E extends Env = Env, M extends
|
|
|
263
268
|
*/
|
|
264
269
|
declare abstract class PrismaSearchEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends SearchEndpoint<E, M> {
|
|
265
270
|
abstract prisma: PrismaClient;
|
|
266
|
-
protected getModel(): PrismaModelOperations
|
|
271
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
267
272
|
/**
|
|
268
273
|
* Builds search-specific WHERE clause with search conditions and filters.
|
|
269
274
|
*/
|
|
@@ -279,7 +284,7 @@ declare abstract class PrismaSearchEndpoint<E extends Env = Env, M extends MetaI
|
|
|
279
284
|
*/
|
|
280
285
|
declare abstract class PrismaExportEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends ExportEndpoint<E, M> {
|
|
281
286
|
abstract prisma: PrismaClient;
|
|
282
|
-
protected getModel(): PrismaModelOperations
|
|
287
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
283
288
|
list(filters: ListFilters): Promise<PaginatedResult<ModelObject<M['model']>>>;
|
|
284
289
|
}
|
|
285
290
|
/**
|
|
@@ -288,7 +293,7 @@ declare abstract class PrismaExportEndpoint<E extends Env = Env, M extends MetaI
|
|
|
288
293
|
*/
|
|
289
294
|
declare abstract class PrismaImportEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends ImportEndpoint<E, M> {
|
|
290
295
|
abstract prisma: PrismaClient;
|
|
291
|
-
protected getModel(): PrismaModelOperations
|
|
296
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
292
297
|
/**
|
|
293
298
|
* Finds an existing record by upsert keys.
|
|
294
299
|
*/
|
|
@@ -311,7 +316,7 @@ declare abstract class PrismaImportEndpoint<E extends Env = Env, M extends MetaI
|
|
|
311
316
|
declare abstract class PrismaUpsertEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends UpsertEndpoint<E, M> {
|
|
312
317
|
abstract prisma: PrismaClient;
|
|
313
318
|
protected useTransaction: boolean;
|
|
314
|
-
protected getModel(): PrismaModelOperations
|
|
319
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
315
320
|
/**
|
|
316
321
|
* Finds an existing record by upsert keys.
|
|
317
322
|
*/
|
|
@@ -338,7 +343,7 @@ declare abstract class PrismaUpsertEndpoint<E extends Env = Env, M extends MetaI
|
|
|
338
343
|
*/
|
|
339
344
|
declare abstract class PrismaVersionHistoryEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends VersionHistoryEndpoint<E, M> {
|
|
340
345
|
abstract prisma: PrismaClient;
|
|
341
|
-
protected getModel(): PrismaModelOperations
|
|
346
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
342
347
|
protected recordExists(lookupValue: string): Promise<boolean>;
|
|
343
348
|
}
|
|
344
349
|
/**
|
|
@@ -359,7 +364,7 @@ declare abstract class PrismaVersionCompareEndpoint<E extends Env = Env, M exten
|
|
|
359
364
|
*/
|
|
360
365
|
declare abstract class PrismaVersionRollbackEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends VersionRollbackEndpoint<E, M> {
|
|
361
366
|
abstract prisma: PrismaClient;
|
|
362
|
-
protected getModel(): PrismaModelOperations
|
|
367
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
363
368
|
rollback(lookupValue: string, versionData: Record<string, unknown>, newVersion: number): Promise<ModelObject<M['model']>>;
|
|
364
369
|
}
|
|
365
370
|
/**
|
|
@@ -374,7 +379,7 @@ declare abstract class PrismaAggregateEndpoint<E extends Env = Env, M extends Me
|
|
|
374
379
|
* Default: true
|
|
375
380
|
*/
|
|
376
381
|
protected useNativeAggregation: boolean;
|
|
377
|
-
protected getModel(): PrismaModelOperations
|
|
382
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
378
383
|
/**
|
|
379
384
|
* Builds the where clause for aggregation queries.
|
|
380
385
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {j as j$1,k as k$1,l,m,n,o,q,r,s,t,u,I,J as J$1,S,T,p,v as v$1,w,x as x$1,y as y$1,z,A}from'../../chunk-4O2JRCJE.js';import'../../chunk-TXBOO4S5.js';import'../../chunk-RRA3AHAE.js';import'../../chunk-OF4XNWYW.js';import xe from'pluralize';import {distance}from'fastest-levenshtein';function X(i){return xe.singular(i)}function Y(i,t){return distance(i,t)}function k(i){if(typeof i=="string"){if(/^-?\d+$/.test(i))return parseInt(i,10);if(/^-?\d+\.\d+$/.test(i))return parseFloat(i);if(i==="true")return true;if(i==="false")return false}return i}function _(i){let t={};for(let e of i){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 Oe=500,y=new Map;function J(i,t){if(y.size>=Oe){let e=y.keys().next().value;e!==void 0&&y.delete(e);}y.set(i,t);}var j=new Map;function Z(i,t){j.set(i.toLowerCase(),t),y.delete(i);}function Re(i){for(let[t,e]of Object.entries(i))Z(t,e);}function ve(){j.clear(),y.clear();}function _e(i){return X(i)}function h(i){let t=y.get(i);if(t)return t;let e=j.get(i.toLowerCase());if(e)return J(i,e),e;let o=i.replace(/[-_](.)/g,(n,r)=>r.toUpperCase()).replace(/^./,n=>n.toLowerCase());return o=_e(o),J(i,o),o}function je(i){let t=[];for(let e of Object.keys(i)){if(e.startsWith("$")||e.startsWith("_"))continue;let o=i[e];o&&typeof o=="object"&&"create"in o&&t.push(e);}return t}function Ee(i,t,e=3){if(t.length===0)return [];let o=i.toLowerCase();return t.map(r=>({name:r,distance:Y(o,r.toLowerCase())})).filter(r=>r.distance<=Math.max(3,i.length/2)).sort((r,s)=>r.distance-s.distance).slice(0,e).map(r=>r.name)}function f(i,t){let e=h(t),o=i[e];if(!o||typeof o.create!="function"){let n=je(i),r=Ee(e,n),s=`Model '${e}' not found in Prisma client. Table name: '${t}'. `;throw r.length>0&&(s+=`Did you mean: ${r.map(a=>`'${a}'`).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 Ce(i,t,e,o){let n=h(o.model),r=i[n];if(!r)return t;switch(o.type){case "hasOne":{let s=o.localKey||"id",a=t[s];if(a==null)return {...t,[e]:null};let l=await r.findFirst({where:{[o.foreignKey]:a}});return {...t,[e]:l||null}}case "hasMany":{let s=o.localKey||"id",a=t[s];if(a==null)return {...t,[e]:[]};let l=await r.findMany({where:{[o.foreignKey]:a}});return {...t,[e]:l}}case "belongsTo":{let s=t[o.foreignKey];if(s==null)return {...t,[e]:null};let a=o.localKey||"id",l=await r.findFirst({where:{[a]:s}});return {...t,[e]:l||null}}default:return t}}async function ee(i,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 Ce(i,n,r,s));}return n}async function x(i,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 a=h(s.model),l=i[a];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 R(i){let{model:t,filters:e,searchFields:o=[],softDeleteConfig:n,defaultPerPage:r=20,additionalWhere:s={}}=i,a={..._(e.filters),...s};if(n?.enabled){let{withDeleted:g,onlyDeleted:M}=e.options;M?a[n.field]={not:null}:g||(a[n.field]=null);}if(e.options.search&&o.length>0){let g=o.map(M=>({[M]:{contains:e.options.search,mode:"insensitive"}}));a={...a,OR:g};}let l=await t.count({where:a}),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:a,orderBy:u,skip:(c-1)*d,take:d}),m=Math.ceil(l/d);return {records:p,where:a,totalCount:l,page:c,perPage:d,totalPages:m}}function v(i,t){return {result:i,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 te=class extends j$1{useTransaction=false;getModel(){return f(this.prisma,this._meta.model.tableName)}async create(t){let e=this.getModel(),o=this._meta.model.primaryKeys[0],n={...t,[o]:t[o]||crypto.randomUUID()};return await e.create({data:n})}},ne=class extends k$1{getModel(){return f(this.prisma,this._meta.model.tableName)}async read(t,e,o){let n=this.getModel(),r={[this.lookupField]:t,...e},s=await n.findFirst({where:r});return s?await ee(this.prisma,s,this._meta,o):null}},oe=class extends l{useTransaction=false;getModel(){return f(this.prisma,this._meta.model.tableName)}async update(t,e,o){let n=this.getModel(),r={[this.lookupField]:t,...o},s=await n.findFirst({where:r});if(!s)return null;let a=this._meta.model.primaryKeys[0];return await n.update({where:{[a]:s[a]},data:e})}},re=class extends m{useTransaction=false;getModel(){return f(this.prisma,this._meta.model.tableName)}async findForDelete(t,e){let o=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=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 a=this._meta.model.primaryKeys[0],l=s[a];return n.enabled?await o.update({where:{[a]:l},data:{[n.field]:new Date}}):await o.delete({where:{[a]:l}})}},se=class extends n{getModel(){return f(this.prisma,this._meta.model.tableName)}async list(t){let e=await R({model: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 v(n,e)}};var ae=class extends o{useTransaction=false;getModel(){return f(this.prisma,this._meta.model.tableName)}async restore(t,e){let o=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 a=this._meta.model.primaryKeys[0];return await o.update({where:{[a]:s[a]},data:{[n.field]:null}})}},ie=class extends q{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 this.prisma.$transaction(async r=>{let s=r[h(this._meta.model.tableName)];for(let a of o){let l=await s.create({data:a});n.push(l);}}),n}},le=class extends r{getModel(){return f(this.prisma,this._meta.model.tableName)}async batchUpdate(t){let e=this.getModel(),o=this.getSoftDeleteConfig(),n=this._meta.model.primaryKeys[0],r=[],s=[],a=t.map(d=>d.id),l={[this.lookupField]:{in:a}};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}}},de=class extends s{getModel(){return f(this.prisma,this._meta.model.tableName)}async batchDelete(t){let e=this.getModel(),o=this.getSoftDeleteConfig(),n=this._meta.model.primaryKeys[0],r=[],s=[],a={[this.lookupField]:{in:t}};o.enabled&&(a[o.field]=null);let l=await e.findMany({where:a}),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}}},ce=class extends t{getModel(){return f(this.prisma,this._meta.model.tableName)}async batchRestore(t){let e=this.getModel(),o=this.getSoftDeleteConfig(),n=this._meta.model.primaryKeys[0],r=[],s=[],a={[this.lookupField]:{in:t},[o.field]:{not:null}},l=await e.findMany({where:a}),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}}},ue=class extends u{useTransaction=true;getModel(){return f(this.prisma,this._meta.model.tableName)}async findExisting(t){let e=this.getModel(),o=this.getUpsertKeys(),n={};for(let s of o){let a=t[s];a!==void 0&&(n[s]=a);}return Object.keys(n).length===0?null:await e.findFirst({where:n})||null}async create(t){let e=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=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=l[h(this._meta.model.tableName)],c=[],d=[];for(let p=0;p<t.length;p++){let m=t[p];try{let g={};for(let b of o){let P=m[b];P!==void 0&&(g[b]=P);}let M={...m,[n]:m[n]||crypto.randomUUID()},w={};for(let[b,P]of Object.entries(m))!o.includes(b)&&b!==n&&(this.createOnlyFields?.includes(b)||(w[b]=P));let ke=await u.upsert({where:g,create:M,update:Object.keys(w).length>0?w:{}});c.push({data:ke,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 this.prisma.$transaction(r):s=await r(this.prisma);let a={items:s.results,createdCount:0,updatedCount:s.results.length,totalCount:s.results.length};return s.errors.length>0&&(a.errors=s.errors),a}};var me=class extends I{getModel(){return f(this.prisma,this._meta.model.tableName)}buildSearchWhere(t,e){let o=_(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(),a=(t.fields||Object.keys(r)).map(l=>({[l]:{contains:t.query,mode:"insensitive"}}));return a.length>0&&(t.mode==="all"?o={...o,AND:a}:o={...o,OR:a}),o}async search(t,e){let o=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,a=e.options.page||1,l=e.options.per_page||this.defaultPerPage,u=await o.findMany({where:n,orderBy:s,skip:(a-1)*l,take:l}),c=J$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,w)=>({...M,item:m[w]})),totalCount:r}}},ge=class extends S{getModel(){return f(this.prisma,this._meta.model.tableName)}async list(t){let e=await R({model: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 v(n,e)}},pe=class extends T{getModel(){return f(this.prisma,this._meta.model.tableName)}async findExisting(t){let e=this.getModel(),o=this.getUpsertKeys(),n={};for(let s of o){let a=t[s];a!==void 0&&(n[s]=a);}return Object.keys(n).length===0?null:await e.findFirst({where:n})||null}async create(t){let e=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=this.getModel(),n=this._meta.model.primaryKeys[0];return await o.update({where:{[n]:t[n]},data:e})}},fe=class extends p{useTransaction=false;getModel(){return f(this.prisma,this._meta.model.tableName)}async findExisting(t){let e=this.getModel(),o=this.getUpsertKeys(),n={};for(let s of o){let a=t[s];a!==void 0&&(n[s]=a);}return Object.keys(n).length===0?null:await e.findFirst({where:n})||null}async create(t){let e=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=this.getModel(),n=this._meta.model.primaryKeys[0];return await o.update({where:{[n]:t[n]},data:e})}async nativeUpsert(t,e){let o=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 a={...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:a,update:Object.keys(l).length>0?l:{}}),created:false}}},Me=class extends v$1{getModel(){return f(this.prisma,this._meta.model.tableName)}async recordExists(t){return await this.getModel().count({where:{[this.lookupField]:t}})>0}},he=class extends w{},be=class extends x$1{},ye=class extends y$1{getModel(){return f(this.prisma,this._meta.model.tableName)}async rollback(t,e,o){let n=this.getModel(),r=this.getVersioningConfig().field,s=this._meta.model.primaryKeys[0],a=await n.findFirst({where:{[this.lookupField]:t}});if(!a)throw new Error(`Record not found: ${t}`);return await n.update({where:{[s]:a[s]},data:{...e,[r]:o}})}},we=class extends z{useNativeAggregation=true;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[a,l]of Object.entries(r))switch(a){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[a]=l;}e[n]=s;}else e[n]=r;return e}async aggregate(t){let e=this.getModel(),o=await this.buildAggregateWhere(t);if(!this.useNativeAggregation||t.having){let n=await e.findMany({where:o});return A(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 a=h(this._meta.model.tableName),l=this.prisma[a];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 A(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=h(this._meta.model.tableName),a=this.prisma[s];try{let u=(await a.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 A(u,o)}}};export{we as PrismaAggregateEndpoint,ie as PrismaBatchCreateEndpoint,de as PrismaBatchDeleteEndpoint,ce as PrismaBatchRestoreEndpoint,le as PrismaBatchUpdateEndpoint,ue as PrismaBatchUpsertEndpoint,te as PrismaCreateEndpoint,re as PrismaDeleteEndpoint,ge as PrismaExportEndpoint,pe as PrismaImportEndpoint,se as PrismaListEndpoint,ne as PrismaReadEndpoint,ae as PrismaRestoreEndpoint,me as PrismaSearchEndpoint,oe as PrismaUpdateEndpoint,fe as PrismaUpsertEndpoint,be as PrismaVersionCompareEndpoint,Me as PrismaVersionHistoryEndpoint,he as PrismaVersionReadEndpoint,ye as PrismaVersionRollbackEndpoint,ve as clearPrismaModelMappings,Z as registerPrismaModelMapping,Re as registerPrismaModelMappings};
|
|
1
|
+
import {k as k$1,l,m,n,o,p,r,s,t,u,v as v$1,J,K,T,U,q,w,x,y as y$1,z,A,B}from'../../chunk-Q4FF5JVS.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-W4FHI5YI.js';import'../../chunk-HAUN4LQO.js';import'../../chunk-NIWM7GOK.js';import'../../chunk-RFT77JBK.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 R,v;async function Oe(){if(R)return R;try{return R=(await import('pluralize')).default,R}catch{throw new Error('The "pluralize" package is required. Install it with: npm install pluralize')}}async function Re(){if(v)return v;try{return v=(await import('fastest-levenshtein')).distance,v}catch{throw new Error('The "fastest-levenshtein" package is required. Install it with: npm install fastest-levenshtein')}}async function E(i){return (await Oe()).singular(i)}async function C(i,t){return (await Re())(i,t)}function k(i){if(typeof i=="string"){if(/^-?\d+$/.test(i))return parseInt(i,10);if(/^-?\d+\.\d+$/.test(i))return parseFloat(i);if(i==="true")return true;if(i==="false")return false}return i}function I(i){let t={};for(let e of i){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 ve=500,y=new Map;function ee(i,t){if(y.size>=ve){let e=y.keys().next().value;e!==void 0&&y.delete(e);}y.set(i,t);}var F=new Map;function te(i,t){F.set(i.toLowerCase(),t),y.delete(i);}function _e(i){for(let[t,e]of Object.entries(i))te(t,e);}function je(){F.clear(),y.clear();}async function h(i){let t=y.get(i);if(t)return t;let e=F.get(i.toLowerCase());if(e)return ee(i,e),e;let o=i.replace(/[-_](.)/g,(n,r)=>r.toUpperCase()).replace(/^./,n=>n.toLowerCase());return o=await E(o),ee(i,o),o}function Ee(i){let t=[];for(let e of Object.keys(i)){if(e.startsWith("$")||e.startsWith("_"))continue;let o=i[e];o&&typeof o=="object"&&"create"in o&&t.push(e);}return t}async function Ce(i,t,e=3){if(t.length===0)return [];let o=i.toLowerCase();return (await Promise.all(t.map(async r=>({name:r,distance:await C(o,r.toLowerCase())})))).filter(r=>r.distance<=Math.max(3,i.length/2)).sort((r,s)=>r.distance-s.distance).slice(0,e).map(r=>r.name)}async function f(i,t){let e=await h(t),o=i[e];if(!o||typeof o.create!="function"){let n=Ee(i),r=await Ce(e,n),s=`Model '${e}' not found in Prisma client. Table name: '${t}'. `;throw r.length>0&&(s+=`Did you mean: ${r.map(a=>`'${a}'`).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 Ie(i,t,e,o){let n=await h(o.model),r=i[n];if(!r)return t;switch(o.type){case "hasOne":{let s=o.localKey||"id",a=t[s];if(a==null)return {...t,[e]:null};let l=await r.findFirst({where:{[o.foreignKey]:a}});return {...t,[e]:l||null}}case "hasMany":{let s=o.localKey||"id",a=t[s];if(a==null)return {...t,[e]:[]};let l=await r.findMany({where:{[o.foreignKey]:a}});return {...t,[e]:l}}case "belongsTo":{let s=t[o.foreignKey];if(s==null)return {...t,[e]:null};let a=o.localKey||"id",l=await r.findFirst({where:{[a]:s}});return {...t,[e]:l||null}}default:return t}}async function ne(i,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 Ie(i,n,r,s));}return n}async function P(i,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 a=await h(s.model),l=i[a];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 _(i){let{model:t,filters:e,searchFields:o=[],softDeleteConfig:n,defaultPerPage:r=20,additionalWhere:s={}}=i,a={...I(e.filters),...s};if(n?.enabled){let{withDeleted:g,onlyDeleted:M}=e.options;M?a[n.field]={not:null}:g||(a[n.field]=null);}if(e.options.search&&o.length>0){let g=o.map(M=>({[M]:{contains:e.options.search,mode:"insensitive"}}));a={...a,OR:g};}let l=await t.count({where:a}),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:a,orderBy:u,skip:(c-1)*d,take:d}),m=Math.ceil(l/d);return {records:p,where:a,totalCount:l,page:c,perPage:d,totalPages:m}}function j(i,t){return {result:i,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 oe=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})}},re=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 ne(this.prisma,s,this._meta,o):null}},se=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 a=this._meta.model.primaryKeys[0];return await n.update({where:{[a]:s[a]},data:e})}},ae=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 a=this._meta.model.primaryKeys[0],l=s[a];return n.enabled?await o.update({where:{[a]:l},data:{[n.field]:new Date}}):await o.delete({where:{[a]:l}})}},ie=class extends o{async getModel(){return f(this.prisma,this._meta.model.tableName)}async list(t){let e=await _({model:await this.getModel(),filters:t,searchFields:this.searchFields,softDeleteConfig:this.getSoftDeleteConfig(),defaultPerPage:this.defaultPerPage}),o={relations:t.options.include||[]},n=await P(this.prisma,e.records,this._meta,o);return j(n,e)}};var le=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 a=this._meta.model.primaryKeys[0];return await o.update({where:{[a]:s[a]},data:{[n.field]:null}})}},de=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 this.prisma.$transaction(async r=>{let s=r[await h(this._meta.model.tableName)];for(let a of o){let l=await s.create({data:a});n.push(l);}}),n}},ce=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=[],a=t.map(d=>d.id),l={[this.lookupField]:{in:a}};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}}},ue=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=[],a={[this.lookupField]:{in:t}};o.enabled&&(a[o.field]=null);let l=await e.findMany({where:a}),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}}},me=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=[],a={[this.lookupField]:{in:t},[o.field]:{not:null}},l=await e.findMany({where:a}),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}}},ge=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 a=t[s];a!==void 0&&(n[s]=a);}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=l[await h(this._meta.model.tableName)],c=[],d=[];for(let p=0;p<t.length;p++){let m=t[p];try{let g={};for(let w of o){let x=m[w];x!==void 0&&(g[w]=x);}let M={...m,[n]:m[n]||crypto.randomUUID()},b={};for(let[w,x]of Object.entries(m))!o.includes(w)&&w!==n&&(this.createOnlyFields?.includes(w)||(b[w]=x));let xe=await u.upsert({where:g,create:M,update:Object.keys(b).length>0?b:{}});c.push({data:xe,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 this.prisma.$transaction(r):s=await r(this.prisma);let a={items:s.results,createdCount:0,updatedCount:s.results.length,totalCount:s.results.length};return s.errors.length>0&&(a.errors=s.errors),a}};var pe=class extends J{async getModel(){return f(this.prisma,this._meta.model.tableName)}buildSearchWhere(t,e){let o=I(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(),a=(t.fields||Object.keys(r)).map(l=>({[l]:{contains:t.query,mode:"insensitive"}}));return a.length>0&&(t.mode==="all"?o={...o,AND:a}:o={...o,OR:a}),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,a=e.options.page||1,l=e.options.per_page||this.defaultPerPage,u=await o.findMany({where:n,orderBy:s,skip:(a-1)*l,take:l}),c=K(u,t,this.getSearchableFields()),d={relations:e.options.include||[]},p=c.map(M=>M.item),m=await P(this.prisma,p,this._meta,d);return {items:c.map((M,b)=>({...M,item:m[b]})),totalCount:r}}},fe=class extends T{async getModel(){return f(this.prisma,this._meta.model.tableName)}async list(t){let e=await _({model:await this.getModel(),filters:t,searchFields:this.searchFields,softDeleteConfig:this.getSoftDeleteConfig(),defaultPerPage:this.defaultPerPage}),o={relations:t.options.include||[]},n=await P(this.prisma,e.records,this._meta,o);return j(n,e)}},Me=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 a=t[s];a!==void 0&&(n[s]=a);}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})}},he=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 a=t[s];a!==void 0&&(n[s]=a);}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 a={...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:a,update:Object.keys(l).length>0?l:{}}),created:false}}},we=class extends w{async getModel(){return f(this.prisma,this._meta.model.tableName)}async recordExists(t){return await(await this.getModel()).count({where:{[this.lookupField]:t}})>0}},ye=class extends x{},be=class extends y$1{},ke=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],a=await n.findFirst({where:{[this.lookupField]:t}});if(!a)throw new Error(`Record not found: ${t}`);return await n.update({where:{[s]:a[s]},data:{...e,[r]:o}})}},Pe=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[a,l]of Object.entries(r))switch(a){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[a]=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 a=await h(this._meta.model.tableName),l=this.prisma[a];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 h(this._meta.model.tableName),a=this.prisma[s];try{let u=(await a.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{Pe as PrismaAggregateEndpoint,de as PrismaBatchCreateEndpoint,ue as PrismaBatchDeleteEndpoint,me as PrismaBatchRestoreEndpoint,ce as PrismaBatchUpdateEndpoint,ge as PrismaBatchUpsertEndpoint,oe as PrismaCreateEndpoint,ae as PrismaDeleteEndpoint,fe as PrismaExportEndpoint,Me as PrismaImportEndpoint,ie as PrismaListEndpoint,re as PrismaReadEndpoint,le as PrismaRestoreEndpoint,pe as PrismaSearchEndpoint,se as PrismaUpdateEndpoint,he as PrismaUpsertEndpoint,be as PrismaVersionCompareEndpoint,we as PrismaVersionHistoryEndpoint,ye as PrismaVersionReadEndpoint,ke as PrismaVersionRollbackEndpoint,je as clearPrismaModelMappings,te as registerPrismaModelMapping,_e as registerPrismaModelMappings};
|