hono-crud 0.4.3 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +4 -0
- package/dist/adapters/drizzle/index.d.ts +3 -3
- package/dist/adapters/drizzle/index.js +1 -1
- package/dist/adapters/memory/index.d.ts +3 -3
- package/dist/adapters/memory/index.js +1 -1
- package/dist/adapters/prisma/index.d.ts +20 -20
- package/dist/adapters/prisma/index.js +1 -1
- package/dist/auth/index.d.ts +3 -3
- package/dist/auth/index.js +1 -1
- package/dist/{bulk-patch-f4TR8L-q.d.ts → bulk-patch-D-Snxx42.d.ts} +1 -1
- package/dist/cache/index.d.ts +72 -7
- package/dist/cache/index.js +1 -1
- package/dist/chunk-CLNKDHBG.js +1 -0
- package/dist/chunk-EWKQ6BPV.js +33 -0
- package/dist/chunk-HX7QWSYF.js +1 -0
- package/dist/chunk-JFFTAQOR.js +1 -0
- package/dist/{chunk-OF4XNWYW.js → chunk-K3226EHO.js} +1 -1
- package/dist/{chunk-GPY4KIVI.js → chunk-LE4MKODL.js} +1 -1
- package/dist/chunk-R3WESU6C.js +1 -0
- package/dist/chunk-SFCD22UI.js +11 -0
- package/dist/{chunk-OG6VCZ64.js → chunk-TWBEVCH3.js} +1 -1
- package/dist/{chunk-T7HH5Y3I.js → chunk-UT3KYWDL.js} +1 -1
- package/dist/{chunk-STVUWSWZ.js → chunk-WCQ3LO6R.js} +1 -1
- package/dist/{chunk-TXBOO4S5.js → chunk-WRFHCN2W.js} +1 -1
- package/dist/{import-BZ05PJMa.d.ts → import-D5BPlFB5.d.ts} +12 -26
- package/dist/index-BgD-_6bM.d.ts +621 -0
- package/dist/{index-bSnRLgcs.d.ts → index-BlgcrFpZ.d.ts} +24 -1
- package/dist/{index-431Ovi2o.d.ts → index-C0ebqb3b.d.ts} +72 -5
- package/dist/index.d.ts +124 -275
- package/dist/index.js +1 -1
- package/dist/kv-types-ByUEHhBc.d.ts +30 -0
- package/dist/logging/index.d.ts +2 -2
- package/dist/logging/index.js +1 -1
- package/dist/rate-limit/index.d.ts +3 -2
- package/dist/rate-limit/index.js +1 -1
- package/dist/storage/index.d.ts +7 -365
- 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-DlIkjpdK.d.ts → types-BdRvpp1z.d.ts} +5 -3
- package/dist/{types-BO3G_MZk.d.ts → types-Bjef1r9u.d.ts} +1 -1
- package/dist/{types-DnQWCfXp.d.ts → types-SnlsH9UT.d.ts} +1 -1
- package/dist/{versioning-BG8-R7C0.d.ts → versioning-BG3T0q1q.d.ts} +5 -3
- package/package.json +17 -5
- package/dist/chunk-3UFSQECZ.js +0 -1
- package/dist/chunk-4O2JRCJE.js +0 -10
- package/dist/chunk-6UMKXMI6.js +0 -1
- package/dist/chunk-HFAUW4XN.js +0 -33
- package/dist/chunk-RRA3AHAE.js +0 -1
- package/dist/chunk-UXKMF6AR.js +0 -1
- package/docs/advanced-features.md +0 -881
- package/docs/alternative-api-patterns.md +0 -531
- package/docs/authentication.md +0 -285
- package/docs/caching.md +0 -175
- package/docs/database-adapters.md +0 -409
- package/docs/logging.md +0 -211
- package/docs/rate-limiting.md +0 -183
package/CHANGELOG.md
CHANGED
|
@@ -17,6 +17,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
17
17
|
%b
|
|
18
18
|
%b
|
|
19
19
|
%b
|
|
20
|
+
%b
|
|
21
|
+
%b
|
|
20
22
|
## [0.1.0] - 2025-01-29
|
|
21
23
|
|
|
22
24
|
### Added
|
|
@@ -50,3 +52,5 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
50
52
|
[0.4.1]: https://github.com/kshdotdev/hono-crud/compare/v0.4.0...v0.4.1
|
|
51
53
|
[0.4.2]: https://github.com/kshdotdev/hono-crud/compare/v0.4.1...v0.4.2
|
|
52
54
|
[0.4.3]: https://github.com/kshdotdev/hono-crud/compare/v0.4.2...v0.4.3
|
|
55
|
+
[0.4.4]: https://github.com/kshdotdev/hono-crud/compare/v0.4.3...v0.4.4
|
|
56
|
+
[0.5.0]: https://github.com/kshdotdev/hono-crud/compare/v0.4.4...v0.5.0
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { Table, SQL, Column } from 'drizzle-orm';
|
|
2
2
|
import { M as MetaInput, I as IncludeOptions, F as FilterCondition, g as RelationConfig, h as NestedUpdateInput, i as NestedWriteResult, L as ListFilters, P as PaginatedResult, j as AggregateOptions, k as AggregateResult, S as SearchOptions, l as SearchResult } from '../../types-CA784ZtV.js';
|
|
3
3
|
import { Env } from 'hono';
|
|
4
|
-
import { C as CreateEndpoint, M as ModelObject, R as ReadEndpoint, U as UpdateEndpoint, D as DeleteEndpoint, L as ListEndpoint, a as RestoreEndpoint, B as BatchCreateEndpoint, b as BatchDeleteEndpoint, c as BatchRestoreEndpoint, d as BatchUpdateEndpoint, e as BatchUpdateItem, A as AggregateEndpoint, f as BatchUpsertEndpoint, g as UpsertEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint, V as VersionCompareEndpoint, h as VersionHistoryEndpoint, i as VersionReadEndpoint, j as VersionRollbackEndpoint } from '../../import-
|
|
5
|
-
import { A as AdapterBundle } from '../../index-
|
|
4
|
+
import { C as CreateEndpoint, M as ModelObject, R as ReadEndpoint, U as UpdateEndpoint, D as DeleteEndpoint, L as ListEndpoint, a as RestoreEndpoint, B as BatchCreateEndpoint, b as BatchDeleteEndpoint, c as BatchRestoreEndpoint, d as BatchUpdateEndpoint, e as BatchUpdateItem, A as AggregateEndpoint, f as BatchUpsertEndpoint, g as UpsertEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint, V as VersionCompareEndpoint, h as VersionHistoryEndpoint, i as VersionReadEndpoint, j as VersionRollbackEndpoint } from '../../import-D5BPlFB5.js';
|
|
5
|
+
import { A as AdapterBundle } from '../../index-BlgcrFpZ.js';
|
|
6
6
|
import { z } from 'zod';
|
|
7
7
|
import '@hono/zod-openapi';
|
|
8
8
|
import '../../route-DwSID3du.js';
|
|
9
9
|
import 'hono/utils/http-status';
|
|
10
|
-
import '../../versioning-
|
|
10
|
+
import '../../versioning-BG3T0q1q.js';
|
|
11
11
|
|
|
12
12
|
/**
|
|
13
13
|
* Internal query builder interface used for type-safe method calls.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {j as j$1,k,l,m,n,o,q as q$1,r,s,t,p,u,v as v$1,w,x,y,z as z$1,A as A$1,I as I$1,J,S as S$1,T}from'../../chunk-
|
|
1
|
+
import {j as j$1,k,l,m,n,o,q as q$1,r,s,t,p,u,v as v$1,w,x,y,z as z$1,A as A$1,I as I$1,J,S as S$1,T}from'../../chunk-SFCD22UI.js';import'../../chunk-WRFHCN2W.js';import'../../chunk-HX7QWSYF.js';import {b}from'../../chunk-K3226EHO.js';import {getTableColumns,eq,inArray,between,isNull,isNotNull,ilike,like,notInArray,lte,lt as lt$1,gte,gt,ne,and,sql,or,desc,asc}from'drizzle-orm';import {z}from'zod';function A(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 g(l,e){let r=getTableColumns(l),n=r[e];if(!n)throw new Error(`Column '${e}' not found in table. Available columns: ${Object.keys(r).join(", ")}`);return n}async function Ce(l,e,r,n){if(!n.table)return e;let t=n.table;switch(n.type){case "hasOne":{let o=n.localKey||"id",s=e[o];if(s==null)return e;let a=g(t,n.foreignKey),i=await l.select().from(t).where(eq(a,s)).limit(1);return {...e,[r]:i[0]||null}}case "hasMany":{let o=n.localKey||"id",s=e[o];if(s==null)return {...e,[r]:[]};let a=g(t,n.foreignKey),i=await l.select().from(t).where(eq(a,s));return {...e,[r]:i}}case "belongsTo":{let o=e[n.foreignKey];if(o==null)return {...e,[r]:null};let s=g(t,n.localKey||"id"),a=await l.select().from(t).where(eq(s,o)).limit(1);return {...e,[r]:a[0]||null}}default:return e}}async function Y(l,e,r,n){if(!n?.relations?.length||!r.model.relations)return e;let t={...e};for(let o of n.relations){let s=r.model.relations[o];s&&(t=await Ce(l,t,o,s));}return t}async function v(l,e,r,n){if(!e.length||!n?.relations?.length||!r.model.relations)return e;let t=e.map(o=>({...o}));for(let o of n.relations){let s=r.model.relations[o];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(b=>b[i]).filter(b=>b!=null))];if(u.length===0){t=t.map(b=>({...b,[o]:s.type==="hasMany"?[]:null}));continue}let d=g(a,s.foreignKey),c=await l.select().from(a).where(inArray(d,u)),p=new Map;for(let b of c){let m=b[s.foreignKey];p.has(m)||p.set(m,[]),p.get(m).push(b);}t=t.map(b=>{let m=b[i],D=p.get(m)||[];return {...b,[o]:s.type==="hasMany"?D:D[0]||null}});break}case "belongsTo":{let i=s.localKey||"id",u=[...new Set(t.map(b=>b[s.foreignKey]).filter(b=>b!=null))];if(u.length===0){t=t.map(b=>({...b,[o]:null}));continue}let d=g(a,i),c=await l.select().from(a).where(inArray(d,u)),p=new Map;for(let b of c){let m=b[i];p.set(m,b);}t=t.map(b=>{let m=b[s.foreignKey];return {...b,[o]:p.get(m)||null}});break}}}return t}function R(l,e){let r=g(l,e.field);switch(e.operator){case "eq":return eq(r,e.value);case "ne":return ne(r,e.value);case "gt":return gt(r,e.value);case "gte":return gte(r,e.value);case "lt":return lt$1(r,e.value);case "lte":return lte(r,e.value);case "in":return inArray(r,e.value);case "nin":return notInArray(r,e.value);case "like":return like(r,e.value);case "ilike":return ilike(r,e.value);case "null":return e.value?isNull(r):isNotNull(r);case "between":{let[n,t]=e.value;return between(r,n,t)}default:return}}var S=class extends j$1{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. Either:
|
|
2
2
|
1. Set db property: db = myDb;
|
|
3
3
|
2. Use middleware: c.set("db", myDb);
|
|
4
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};
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { Env } from 'hono';
|
|
2
|
-
import { C as CreateEndpoint, M as ModelObject, D as DeleteEndpoint, L as ListEndpoint, R as ReadEndpoint, a as RestoreEndpoint, U as UpdateEndpoint, B as BatchCreateEndpoint, b as BatchDeleteEndpoint, c as BatchRestoreEndpoint, d as BatchUpdateEndpoint, e as BatchUpdateItem, f as BatchUpsertEndpoint, A as AggregateEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint, g as UpsertEndpoint, V as VersionCompareEndpoint, h as VersionHistoryEndpoint, i as VersionReadEndpoint, j as VersionRollbackEndpoint } from '../../import-
|
|
2
|
+
import { C as CreateEndpoint, M as ModelObject, D as DeleteEndpoint, L as ListEndpoint, R as ReadEndpoint, a as RestoreEndpoint, U as UpdateEndpoint, B as BatchCreateEndpoint, b as BatchDeleteEndpoint, c as BatchRestoreEndpoint, d as BatchUpdateEndpoint, e as BatchUpdateItem, f as BatchUpsertEndpoint, A as AggregateEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint, g as UpsertEndpoint, V as VersionCompareEndpoint, h as VersionHistoryEndpoint, i as VersionReadEndpoint, j as VersionRollbackEndpoint } from '../../import-D5BPlFB5.js';
|
|
3
3
|
import { M as MetaInput, g as RelationConfig, L as ListFilters, P as PaginatedResult, I as IncludeOptions, h as NestedUpdateInput, i as NestedWriteResult, j as AggregateOptions, k as AggregateResult, S as SearchOptions, l as SearchResult } from '../../types-CA784ZtV.js';
|
|
4
|
-
import { B as BulkPatchEndpoint, C as CloneEndpoint } from '../../bulk-patch-
|
|
4
|
+
import { B as BulkPatchEndpoint, C as CloneEndpoint } from '../../bulk-patch-D-Snxx42.js';
|
|
5
5
|
import 'zod';
|
|
6
6
|
import '../../route-DwSID3du.js';
|
|
7
7
|
import 'hono/utils/http-status';
|
|
8
|
-
import '../../versioning-
|
|
8
|
+
import '../../versioning-BG3T0q1q.js';
|
|
9
9
|
import '@hono/zod-openapi';
|
|
10
10
|
|
|
11
11
|
/**
|
|
@@ -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-LE4MKODL.js';import'../../chunk-SFCD22UI.js';import'../../chunk-WRFHCN2W.js';import'../../chunk-HX7QWSYF.js';import'../../chunk-K3226EHO.js';
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { Env } from 'hono';
|
|
2
|
-
import { C as CreateEndpoint, M as ModelObject, D as DeleteEndpoint, L as ListEndpoint, R as ReadEndpoint, U as UpdateEndpoint, B as BatchCreateEndpoint, b as BatchDeleteEndpoint, c as BatchRestoreEndpoint, d as BatchUpdateEndpoint, e as BatchUpdateItem, f as BatchUpsertEndpoint, a as RestoreEndpoint, A as AggregateEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint, g as UpsertEndpoint, V as VersionCompareEndpoint, h as VersionHistoryEndpoint, i as VersionReadEndpoint, j as VersionRollbackEndpoint } from '../../import-
|
|
2
|
+
import { C as CreateEndpoint, M as ModelObject, D as DeleteEndpoint, L as ListEndpoint, R as ReadEndpoint, U as UpdateEndpoint, B as BatchCreateEndpoint, b as BatchDeleteEndpoint, c as BatchRestoreEndpoint, d as BatchUpdateEndpoint, e as BatchUpdateItem, f as BatchUpsertEndpoint, a as RestoreEndpoint, A as AggregateEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint, g as UpsertEndpoint, V as VersionCompareEndpoint, h as VersionHistoryEndpoint, i as VersionReadEndpoint, j as VersionRollbackEndpoint } from '../../import-D5BPlFB5.js';
|
|
3
3
|
import { M as MetaInput, L as ListFilters, P as PaginatedResult, I as IncludeOptions, j as AggregateOptions, k as AggregateResult, m as AggregateField, S as SearchOptions, l as SearchResult } from '../../types-CA784ZtV.js';
|
|
4
4
|
import 'zod';
|
|
5
5
|
import '../../route-DwSID3du.js';
|
|
6
6
|
import 'hono/utils/http-status';
|
|
7
|
-
import '../../versioning-
|
|
7
|
+
import '../../versioning-BG3T0q1q.js';
|
|
8
8
|
import '@hono/zod-openapi';
|
|
9
9
|
|
|
10
10
|
/**
|
|
@@ -110,7 +110,7 @@ declare function clearPrismaModelMappings(): void;
|
|
|
110
110
|
declare abstract class PrismaCreateEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends CreateEndpoint<E, M> {
|
|
111
111
|
abstract prisma: PrismaClient;
|
|
112
112
|
protected useTransaction: boolean;
|
|
113
|
-
protected getModel(): PrismaModelOperations
|
|
113
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
114
114
|
create(data: ModelObject<M['model']>): Promise<ModelObject<M['model']>>;
|
|
115
115
|
}
|
|
116
116
|
/**
|
|
@@ -118,7 +118,7 @@ declare abstract class PrismaCreateEndpoint<E extends Env = Env, M extends MetaI
|
|
|
118
118
|
*/
|
|
119
119
|
declare abstract class PrismaReadEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends ReadEndpoint<E, M> {
|
|
120
120
|
abstract prisma: PrismaClient;
|
|
121
|
-
protected getModel(): PrismaModelOperations
|
|
121
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
122
122
|
read(lookupValue: string, additionalFilters?: Record<string, string>, includeOptions?: IncludeOptions): Promise<ModelObject<M['model']> | null>;
|
|
123
123
|
}
|
|
124
124
|
/**
|
|
@@ -127,7 +127,7 @@ declare abstract class PrismaReadEndpoint<E extends Env = Env, M extends MetaInp
|
|
|
127
127
|
declare abstract class PrismaUpdateEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends UpdateEndpoint<E, M> {
|
|
128
128
|
abstract prisma: PrismaClient;
|
|
129
129
|
protected useTransaction: boolean;
|
|
130
|
-
protected getModel(): PrismaModelOperations
|
|
130
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
131
131
|
update(lookupValue: string, data: Partial<ModelObject<M['model']>>, additionalFilters?: Record<string, string>): Promise<ModelObject<M['model']> | null>;
|
|
132
132
|
}
|
|
133
133
|
/**
|
|
@@ -136,7 +136,7 @@ declare abstract class PrismaUpdateEndpoint<E extends Env = Env, M extends MetaI
|
|
|
136
136
|
declare abstract class PrismaDeleteEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends DeleteEndpoint<E, M> {
|
|
137
137
|
abstract prisma: PrismaClient;
|
|
138
138
|
protected useTransaction: boolean;
|
|
139
|
-
protected getModel(): PrismaModelOperations
|
|
139
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
140
140
|
/**
|
|
141
141
|
* Finds a record without deleting it (for constraint checks).
|
|
142
142
|
*/
|
|
@@ -148,7 +148,7 @@ declare abstract class PrismaDeleteEndpoint<E extends Env = Env, M extends MetaI
|
|
|
148
148
|
*/
|
|
149
149
|
declare abstract class PrismaListEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends ListEndpoint<E, M> {
|
|
150
150
|
abstract prisma: PrismaClient;
|
|
151
|
-
protected getModel(): PrismaModelOperations
|
|
151
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
152
152
|
list(filters: ListFilters): Promise<PaginatedResult<ModelObject<M['model']>>>;
|
|
153
153
|
}
|
|
154
154
|
|
|
@@ -161,7 +161,7 @@ declare abstract class PrismaListEndpoint<E extends Env = Env, M extends MetaInp
|
|
|
161
161
|
declare abstract class PrismaRestoreEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends RestoreEndpoint<E, M> {
|
|
162
162
|
abstract prisma: PrismaClient;
|
|
163
163
|
protected useTransaction: boolean;
|
|
164
|
-
protected getModel(): PrismaModelOperations
|
|
164
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
165
165
|
restore(lookupValue: string, additionalFilters?: Record<string, string>): Promise<ModelObject<M['model']> | null>;
|
|
166
166
|
}
|
|
167
167
|
/**
|
|
@@ -170,7 +170,7 @@ declare abstract class PrismaRestoreEndpoint<E extends Env = Env, M extends Meta
|
|
|
170
170
|
*/
|
|
171
171
|
declare abstract class PrismaBatchCreateEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends BatchCreateEndpoint<E, M> {
|
|
172
172
|
abstract prisma: PrismaClient;
|
|
173
|
-
protected getModel(): PrismaModelOperations
|
|
173
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
174
174
|
batchCreate(items: Partial<ModelObject<M['model']>>[]): Promise<ModelObject<M['model']>[]>;
|
|
175
175
|
}
|
|
176
176
|
/**
|
|
@@ -181,7 +181,7 @@ declare abstract class PrismaBatchCreateEndpoint<E extends Env = Env, M extends
|
|
|
181
181
|
*/
|
|
182
182
|
declare abstract class PrismaBatchUpdateEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends BatchUpdateEndpoint<E, M> {
|
|
183
183
|
abstract prisma: PrismaClient;
|
|
184
|
-
protected getModel(): PrismaModelOperations
|
|
184
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
185
185
|
batchUpdate(items: BatchUpdateItem<ModelObject<M['model']>>[]): Promise<{
|
|
186
186
|
updated: ModelObject<M['model']>[];
|
|
187
187
|
notFound: string[];
|
|
@@ -195,7 +195,7 @@ declare abstract class PrismaBatchUpdateEndpoint<E extends Env = Env, M extends
|
|
|
195
195
|
*/
|
|
196
196
|
declare abstract class PrismaBatchDeleteEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends BatchDeleteEndpoint<E, M> {
|
|
197
197
|
abstract prisma: PrismaClient;
|
|
198
|
-
protected getModel(): PrismaModelOperations
|
|
198
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
199
199
|
batchDelete(ids: string[]): Promise<{
|
|
200
200
|
deleted: ModelObject<M['model']>[];
|
|
201
201
|
notFound: string[];
|
|
@@ -208,7 +208,7 @@ declare abstract class PrismaBatchDeleteEndpoint<E extends Env = Env, M extends
|
|
|
208
208
|
*/
|
|
209
209
|
declare abstract class PrismaBatchRestoreEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends BatchRestoreEndpoint<E, M> {
|
|
210
210
|
abstract prisma: PrismaClient;
|
|
211
|
-
protected getModel(): PrismaModelOperations
|
|
211
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
212
212
|
batchRestore(ids: string[]): Promise<{
|
|
213
213
|
restored: ModelObject<M['model']>[];
|
|
214
214
|
notFound: string[];
|
|
@@ -225,7 +225,7 @@ declare abstract class PrismaBatchRestoreEndpoint<E extends Env = Env, M extends
|
|
|
225
225
|
declare abstract class PrismaBatchUpsertEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends BatchUpsertEndpoint<E, M> {
|
|
226
226
|
abstract prisma: PrismaClient;
|
|
227
227
|
protected useTransaction: boolean;
|
|
228
|
-
protected getModel(): PrismaModelOperations
|
|
228
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
229
229
|
/**
|
|
230
230
|
* Finds an existing record by upsert keys.
|
|
231
231
|
*/
|
|
@@ -263,7 +263,7 @@ declare abstract class PrismaBatchUpsertEndpoint<E extends Env = Env, M extends
|
|
|
263
263
|
*/
|
|
264
264
|
declare abstract class PrismaSearchEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends SearchEndpoint<E, M> {
|
|
265
265
|
abstract prisma: PrismaClient;
|
|
266
|
-
protected getModel(): PrismaModelOperations
|
|
266
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
267
267
|
/**
|
|
268
268
|
* Builds search-specific WHERE clause with search conditions and filters.
|
|
269
269
|
*/
|
|
@@ -279,7 +279,7 @@ declare abstract class PrismaSearchEndpoint<E extends Env = Env, M extends MetaI
|
|
|
279
279
|
*/
|
|
280
280
|
declare abstract class PrismaExportEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends ExportEndpoint<E, M> {
|
|
281
281
|
abstract prisma: PrismaClient;
|
|
282
|
-
protected getModel(): PrismaModelOperations
|
|
282
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
283
283
|
list(filters: ListFilters): Promise<PaginatedResult<ModelObject<M['model']>>>;
|
|
284
284
|
}
|
|
285
285
|
/**
|
|
@@ -288,7 +288,7 @@ declare abstract class PrismaExportEndpoint<E extends Env = Env, M extends MetaI
|
|
|
288
288
|
*/
|
|
289
289
|
declare abstract class PrismaImportEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends ImportEndpoint<E, M> {
|
|
290
290
|
abstract prisma: PrismaClient;
|
|
291
|
-
protected getModel(): PrismaModelOperations
|
|
291
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
292
292
|
/**
|
|
293
293
|
* Finds an existing record by upsert keys.
|
|
294
294
|
*/
|
|
@@ -311,7 +311,7 @@ declare abstract class PrismaImportEndpoint<E extends Env = Env, M extends MetaI
|
|
|
311
311
|
declare abstract class PrismaUpsertEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends UpsertEndpoint<E, M> {
|
|
312
312
|
abstract prisma: PrismaClient;
|
|
313
313
|
protected useTransaction: boolean;
|
|
314
|
-
protected getModel(): PrismaModelOperations
|
|
314
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
315
315
|
/**
|
|
316
316
|
* Finds an existing record by upsert keys.
|
|
317
317
|
*/
|
|
@@ -338,7 +338,7 @@ declare abstract class PrismaUpsertEndpoint<E extends Env = Env, M extends MetaI
|
|
|
338
338
|
*/
|
|
339
339
|
declare abstract class PrismaVersionHistoryEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends VersionHistoryEndpoint<E, M> {
|
|
340
340
|
abstract prisma: PrismaClient;
|
|
341
|
-
protected getModel(): PrismaModelOperations
|
|
341
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
342
342
|
protected recordExists(lookupValue: string): Promise<boolean>;
|
|
343
343
|
}
|
|
344
344
|
/**
|
|
@@ -359,7 +359,7 @@ declare abstract class PrismaVersionCompareEndpoint<E extends Env = Env, M exten
|
|
|
359
359
|
*/
|
|
360
360
|
declare abstract class PrismaVersionRollbackEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends VersionRollbackEndpoint<E, M> {
|
|
361
361
|
abstract prisma: PrismaClient;
|
|
362
|
-
protected getModel(): PrismaModelOperations
|
|
362
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
363
363
|
rollback(lookupValue: string, versionData: Record<string, unknown>, newVersion: number): Promise<ModelObject<M['model']>>;
|
|
364
364
|
}
|
|
365
365
|
/**
|
|
@@ -374,7 +374,7 @@ declare abstract class PrismaAggregateEndpoint<E extends Env = Env, M extends Me
|
|
|
374
374
|
* Default: true
|
|
375
375
|
*/
|
|
376
376
|
protected useNativeAggregation: boolean;
|
|
377
|
-
protected getModel(): PrismaModelOperations
|
|
377
|
+
protected getModel(): Promise<PrismaModelOperations>;
|
|
378
378
|
/**
|
|
379
379
|
* Builds the where clause for aggregation queries.
|
|
380
380
|
*/
|
|
@@ -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 {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,y as y$1,z,A}from'../../chunk-SFCD22UI.js';import'../../chunk-WRFHCN2W.js';import'../../chunk-HX7QWSYF.js';import'../../chunk-K3226EHO.js';var _,j;async function Oe(){if(!_)try{_=(await import('pluralize')).default;}catch{throw new Error('The "pluralize" package is required by the Prisma adapter. Install it with: npm install pluralize')}return _}async function Re(){if(!j)try{j=(await import('fastest-levenshtein')).distance;}catch{throw new Error('The "fastest-levenshtein" package is required by the Prisma adapter. Install it with: npm install fastest-levenshtein')}return j}async function J(i){return (await Oe()).singular(i)}async function Z(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 E(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 C=new Map;function te(i,t){C.set(i.toLowerCase(),t),y.delete(i);}function _e(i){for(let[t,e]of Object.entries(i))te(t,e);}function je(){C.clear(),y.clear();}async function h(i){let t=y.get(i);if(t)return t;let e=C.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 J(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 Z(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 R(i){let{model:t,filters:e,searchFields:o=[],softDeleteConfig:n,defaultPerPage:r=20,additionalWhere:s={}}=i,a={...E(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 oe=class extends j$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 k$1{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 l{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 m{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 n{async getModel(){return f(this.prisma,this._meta.model.tableName)}async list(t){let e=await R({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 v(n,e)}};var le=class extends o{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 q{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 r{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 s{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 t{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 u{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 I{async getModel(){return f(this.prisma,this._meta.model.tableName)}buildSearchWhere(t,e){let o=E(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=J$1(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 S{async getModel(){return f(this.prisma,this._meta.model.tableName)}async list(t){let e=await R({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 v(n,e)}},Me=class extends T{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 p{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 v$1{async getModel(){return f(this.prisma,this._meta.model.tableName)}async recordExists(t){return await(await this.getModel()).count({where:{[this.lookupField]:t}})>0}},ye=class extends w{},be=class extends x{},ke=class extends y$1{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 z{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 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=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 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=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 A(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};
|
package/dist/auth/index.d.ts
CHANGED
|
@@ -15,7 +15,7 @@ import 'hono/utils/http-status';
|
|
|
15
15
|
* const app = new Hono<AuthEnv>();
|
|
16
16
|
*
|
|
17
17
|
* app.use('*', createJWTMiddleware({
|
|
18
|
-
* secret:
|
|
18
|
+
* secret: c.env.JWT_SECRET,
|
|
19
19
|
* issuer: 'my-app',
|
|
20
20
|
* }));
|
|
21
21
|
*
|
|
@@ -87,7 +87,7 @@ declare function validateAPIKey(apiKey: string, config: APIKeyConfig): Promise<A
|
|
|
87
87
|
* const app = new Hono<AuthEnv>();
|
|
88
88
|
*
|
|
89
89
|
* app.use('*', createAuthMiddleware({
|
|
90
|
-
* jwt: { secret:
|
|
90
|
+
* jwt: { secret: c.env.JWT_SECRET },
|
|
91
91
|
* apiKey: {
|
|
92
92
|
* lookupKey: async (hash) => await db.apiKeys.findByHash(hash),
|
|
93
93
|
* },
|
|
@@ -110,7 +110,7 @@ declare function createAuthMiddleware<E extends AuthEnv = AuthEnv>(config: AuthC
|
|
|
110
110
|
* @example
|
|
111
111
|
* ```ts
|
|
112
112
|
* app.use('*', optionalAuth({
|
|
113
|
-
* jwt: { secret:
|
|
113
|
+
* jwt: { secret: c.env.JWT_SECRET },
|
|
114
114
|
* }));
|
|
115
115
|
*
|
|
116
116
|
* app.get('/public', (c) => {
|
package/dist/auth/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{A as AuthenticatedEndpoint,a as JWTClaimsSchema,v as allOf,y as allowAll,w as anyOf,j as createAPIKeyMiddleware,l as createAuthMiddleware,e as createJWTMiddleware,g as decodeJWT,i as defaultHashAPIKey,x as denyAll,m as optionalAuth,b as parseJWTClaims,p as requireAllRoles,r as requireAnyPermission,s as requireAuth,z as requireAuthenticated,n as requireAuthentication,t as requireOwnership,u as requireOwnershipOrRole,q as requirePermissions,o as requireRoles,c as safeParseJWTClaims,k as validateAPIKey,h as validateAPIKeyEntry,d as validateJWTClaims,f as verifyJWT,B as withAuth}from'../chunk-
|
|
1
|
+
export{A as AuthenticatedEndpoint,a as JWTClaimsSchema,v as allOf,y as allowAll,w as anyOf,j as createAPIKeyMiddleware,l as createAuthMiddleware,e as createJWTMiddleware,g as decodeJWT,i as defaultHashAPIKey,x as denyAll,m as optionalAuth,b as parseJWTClaims,p as requireAllRoles,r as requireAnyPermission,s as requireAuth,z as requireAuthenticated,n as requireAuthentication,t as requireOwnership,u as requireOwnershipOrRole,q as requirePermissions,o as requireRoles,c as safeParseJWTClaims,k as validateAPIKey,h as validateAPIKeyEntry,d as validateJWTClaims,f as verifyJWT,B as withAuth}from'../chunk-TWBEVCH3.js';import'../chunk-WRFHCN2W.js';export{a as MemoryAPIKeyStorage,b as generateAPIKey,f as getAPIKeyStorage,c as hashAPIKey,d as isValidAPIKeyFormat,g as setAPIKeyStorage}from'../chunk-UT3KYWDL.js';import'../chunk-K3226EHO.js';
|
|
@@ -2,7 +2,7 @@ import { ZodObject, ZodRawShape } from 'zod';
|
|
|
2
2
|
import { Env } from 'hono';
|
|
3
3
|
import { O as OpenAPIRoute } from './route-DwSID3du.js';
|
|
4
4
|
import { M as MetaInput, N as NormalizedSoftDeleteConfig, a as NormalizedMultiTenantConfig, O as OpenAPIRouteSchema, H as HookMode, L as ListFilters } from './types-CA784ZtV.js';
|
|
5
|
-
import { M as ModelObject } from './import-
|
|
5
|
+
import { M as ModelObject } from './import-D5BPlFB5.js';
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
8
|
* Base endpoint for cloning/duplicating a resource.
|
package/dist/cache/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { I as InvalidationPatternOptions,
|
|
2
|
-
export { g as InvalidationStrategy } from '../types-
|
|
1
|
+
import { I as InvalidationPatternOptions, d as CacheKeyOptions, C as CacheStorage, b as CacheEntry, e as CacheSetOptions, f as CacheStats, a as CacheConfig, c as CacheInvalidationConfig } from '../types-BdRvpp1z.js';
|
|
2
|
+
export { g as InvalidationStrategy } from '../types-BdRvpp1z.js';
|
|
3
|
+
import { K as KVNamespace } from '../kv-types-ByUEHhBc.js';
|
|
3
4
|
import { ap as Constructor } from '../types-CA784ZtV.js';
|
|
4
5
|
import { O as OpenAPIRoute } from '../route-DwSID3du.js';
|
|
5
6
|
import 'zod';
|
|
@@ -181,6 +182,7 @@ declare class MemoryCacheStorage implements CacheStorage {
|
|
|
181
182
|
getTags(): string[];
|
|
182
183
|
/**
|
|
183
184
|
* Evict oldest entry when at capacity.
|
|
185
|
+
* Uses Map insertion order for O(1) lookup instead of scanning all entries.
|
|
184
186
|
*/
|
|
185
187
|
private evictOldest;
|
|
186
188
|
/**
|
|
@@ -209,6 +211,16 @@ interface RedisClient {
|
|
|
209
211
|
smembers?(key: string): Promise<string[]>;
|
|
210
212
|
srem?(key: string, ...members: string[]): Promise<number>;
|
|
211
213
|
flushdb?(): Promise<string>;
|
|
214
|
+
/** Pipeline support for batching commands (supported by @upstash/redis and ioredis). */
|
|
215
|
+
pipeline?(): {
|
|
216
|
+
set(key: string, value: string, options?: {
|
|
217
|
+
ex?: number;
|
|
218
|
+
}): unknown;
|
|
219
|
+
del(...keys: string[]): unknown;
|
|
220
|
+
sadd(key: string, ...members: string[]): unknown;
|
|
221
|
+
srem(key: string, ...members: string[]): unknown;
|
|
222
|
+
exec(): Promise<unknown[]>;
|
|
223
|
+
};
|
|
212
224
|
}
|
|
213
225
|
/**
|
|
214
226
|
* Options for Redis cache storage.
|
|
@@ -242,8 +254,8 @@ interface RedisCacheStorageOptions {
|
|
|
242
254
|
*
|
|
243
255
|
* const cache = new RedisCacheStorage({
|
|
244
256
|
* client: new Redis({
|
|
245
|
-
* url:
|
|
246
|
-
* token:
|
|
257
|
+
* url: c.env.REDIS_URL,
|
|
258
|
+
* token: c.env.REDIS_TOKEN,
|
|
247
259
|
* }),
|
|
248
260
|
* });
|
|
249
261
|
* setCacheStorage(cache);
|
|
@@ -255,7 +267,7 @@ interface RedisCacheStorageOptions {
|
|
|
255
267
|
* import { RedisCacheStorage, setCacheStorage } from 'hono-crud/cache';
|
|
256
268
|
*
|
|
257
269
|
* const cache = new RedisCacheStorage({
|
|
258
|
-
* client: new Redis(
|
|
270
|
+
* client: new Redis(c.env.REDIS_URL),
|
|
259
271
|
* });
|
|
260
272
|
* setCacheStorage(cache);
|
|
261
273
|
* ```
|
|
@@ -320,6 +332,59 @@ declare class RedisCacheStorage implements CacheStorage {
|
|
|
320
332
|
private scanKeys;
|
|
321
333
|
}
|
|
322
334
|
|
|
335
|
+
/**
|
|
336
|
+
* Options for Cloudflare KV cache storage.
|
|
337
|
+
*/
|
|
338
|
+
interface KVCacheStorageOptions {
|
|
339
|
+
/** KV namespace binding. */
|
|
340
|
+
kv: KVNamespace;
|
|
341
|
+
/** Key prefix for all cache entries. @default 'cache:' */
|
|
342
|
+
prefix?: string;
|
|
343
|
+
/** Default TTL in seconds. @default 300 */
|
|
344
|
+
defaultTtl?: number;
|
|
345
|
+
}
|
|
346
|
+
/**
|
|
347
|
+
* Cloudflare KV cache storage implementation.
|
|
348
|
+
*
|
|
349
|
+
* Uses KV's native TTL for expiration and stores tag indices as JSON arrays.
|
|
350
|
+
* Best used with the `createCrudMiddleware` since KV bindings are only
|
|
351
|
+
* available inside request handlers.
|
|
352
|
+
*
|
|
353
|
+
* **Caveats:**
|
|
354
|
+
* - Tag indices use read-modify-write (not atomic) — concurrent writes to
|
|
355
|
+
* the same tag may lose entries. Acceptable for cache invalidation.
|
|
356
|
+
* - KV is eventually consistent (~60s stale reads possible).
|
|
357
|
+
* - `deletePattern()` uses KV `list()` which may be slow for large keyspaces.
|
|
358
|
+
*
|
|
359
|
+
* @example
|
|
360
|
+
* ```ts
|
|
361
|
+
* import { KVCacheStorage, createCrudMiddleware } from 'hono-crud';
|
|
362
|
+
*
|
|
363
|
+
* app.use('*', async (c, next) => {
|
|
364
|
+
* const cache = new KVCacheStorage({ kv: c.env.CACHE_KV });
|
|
365
|
+
* return createCrudMiddleware({ cache })(c, next);
|
|
366
|
+
* });
|
|
367
|
+
* ```
|
|
368
|
+
*/
|
|
369
|
+
declare class KVCacheStorage implements CacheStorage {
|
|
370
|
+
private kv;
|
|
371
|
+
private prefix;
|
|
372
|
+
private defaultTtl;
|
|
373
|
+
private stats;
|
|
374
|
+
constructor(options: KVCacheStorageOptions);
|
|
375
|
+
private getKey;
|
|
376
|
+
private getTagKey;
|
|
377
|
+
private getExpirationTtl;
|
|
378
|
+
get<T>(key: string): Promise<CacheEntry<T> | null>;
|
|
379
|
+
set<T>(key: string, data: T, options?: CacheSetOptions): Promise<void>;
|
|
380
|
+
delete(key: string): Promise<boolean>;
|
|
381
|
+
deletePattern(pattern: string): Promise<number>;
|
|
382
|
+
deleteByTag(tag: string): Promise<number>;
|
|
383
|
+
has(key: string): Promise<boolean>;
|
|
384
|
+
clear(): Promise<void>;
|
|
385
|
+
getStats(): CacheStats;
|
|
386
|
+
}
|
|
387
|
+
|
|
323
388
|
/**
|
|
324
389
|
* Set the global cache storage instance.
|
|
325
390
|
*
|
|
@@ -329,7 +394,7 @@ declare class RedisCacheStorage implements CacheStorage {
|
|
|
329
394
|
* import { RedisCacheStorage, setCacheStorage } from 'hono-crud/cache';
|
|
330
395
|
*
|
|
331
396
|
* setCacheStorage(new RedisCacheStorage({
|
|
332
|
-
* client: new Redis({ url:
|
|
397
|
+
* client: new Redis({ url: c.env.REDIS_URL }),
|
|
333
398
|
* }));
|
|
334
399
|
* ```
|
|
335
400
|
*/
|
|
@@ -418,4 +483,4 @@ declare function withCache<TBase extends Constructor<OpenAPIRoute>>(Base: TBase)
|
|
|
418
483
|
*/
|
|
419
484
|
declare function withCacheInvalidation<TBase extends Constructor<OpenAPIRoute>>(Base: TBase): TBase & Constructor<CacheInvalidationMethods>;
|
|
420
485
|
|
|
421
|
-
export { CacheConfig, type CacheEndpointMethods, CacheEntry, CacheInvalidationConfig, type CacheInvalidationMethods, CacheKeyOptions, CacheSetOptions, CacheStats, CacheStorage, InvalidationPatternOptions, MemoryCacheStorage, RedisCacheStorage, type RedisCacheStorageOptions, type RedisClient, createInvalidationPattern, createRelatedPatterns, generateCacheKey, getCacheStorage, matchesPattern, parseCacheKey, setCacheStorage, withCache, withCacheInvalidation };
|
|
486
|
+
export { CacheConfig, type CacheEndpointMethods, CacheEntry, CacheInvalidationConfig, type CacheInvalidationMethods, CacheKeyOptions, CacheSetOptions, CacheStats, CacheStorage, InvalidationPatternOptions, KVCacheStorage, type KVCacheStorageOptions, MemoryCacheStorage, RedisCacheStorage, type RedisCacheStorageOptions, type RedisClient, createInvalidationPattern, createRelatedPatterns, generateCacheKey, getCacheStorage, matchesPattern, parseCacheKey, setCacheStorage, withCache, withCacheInvalidation };
|
package/dist/cache/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{a as RedisCacheStorage}from'../chunk-
|
|
1
|
+
export{b as KVCacheStorage,a as RedisCacheStorage}from'../chunk-CLNKDHBG.js';export{C as MemoryCacheStorage,y as createInvalidationPattern,z as createRelatedPatterns,x as generateCacheKey,E as getCacheStorage,A as matchesPattern,B as parseCacheKey,D as setCacheStorage,F as withCache,G as withCacheInvalidation}from'../chunk-JFFTAQOR.js';import'../chunk-HX7QWSYF.js';import'../chunk-UT3KYWDL.js';import'../chunk-K3226EHO.js';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {b}from'./chunk-K3226EHO.js';var y=class{client;prefix;defaultTtl;useScan;scanCount;stats={hits:0,misses:0,size:0};constructor(t){this.client=t.client,this.prefix=t.prefix??"cache:",this.defaultTtl=t.defaultTtl??300,this.useScan=t.useScan??true,this.scanCount=t.scanCount??100;}getKey(t){return `${this.prefix}${t}`}getTagKey(t){return `${this.prefix}tag:${t}`}async get(t){let i=this.getKey(t),e=await this.client.get(i);if(!e)return this.stats.misses++,null;try{let n=JSON.parse(e),s=n.createdAt;if(typeof s=="string"){let a=Date.parse(s);n.createdAt=Number.isNaN(a)?Date.now():a;}let r=n.expiresAt;if(typeof r=="string"){let a=Date.parse(r);n.expiresAt=Number.isNaN(a)?null:a;}return n.expiresAt&&n.expiresAt<Date.now()?(this.stats.misses++,null):(this.stats.hits++,n)}catch{return this.stats.misses++,null}}async set(t,i,e){let n=this.getKey(t),s=e?.ttl??this.defaultTtl,r=e?.tags,a=Date.now(),o={data:i,createdAt:a,expiresAt:s>0?a+s*1e3:null,tags:r},l=JSON.stringify(o);if(r&&r.length>0&&this.client.pipeline){let c=this.client.pipeline();s>0?c.set(n,l,{ex:s}):c.set(n,l);for(let g of r)c.sadd(this.getTagKey(g),t);await c.exec();}else if(s>0?await this.client.set(n,l,{ex:s}):await this.client.set(n,l),r&&this.client.sadd)for(let c of r)await this.client.sadd(this.getTagKey(c),t);}async delete(t){let i=this.getKey(t),e=await this.client.get(i);if(e&&this.client.srem)try{let s=JSON.parse(e);if(s.tags)for(let r of s.tags)await this.client.srem(this.getTagKey(r),t);}catch{}return await this.client.del(i)>0}async deletePattern(t){let i=this.getKey(t),e=await this.getKeysByPattern(i);if(e.length===0)return 0;let n=e.map(a=>a.substring(this.prefix.length));for(let a of n){let o=await this.client.get(this.getKey(a));if(o&&this.client.srem)try{let l=JSON.parse(o);if(l.tags)for(let c of l.tags)await this.client.srem(this.getTagKey(c),a);}catch{}}let s=100,r=0;for(let a=0;a<e.length;a+=s){let o=e.slice(a,a+s);r+=await this.client.del(...o);}return r}async deleteByTag(t){if(!this.client.smembers)return this.deletePattern(`*:tag=${t}*`);let i=this.getTagKey(t),e=await this.client.smembers(i);if(e.length===0)return 0;if(this.client.pipeline){let s=this.client.pipeline();for(let r of e)s.del(this.getKey(r));return s.del(i),await s.exec(),e.length}let n=0;for(let s of e)await this.delete(s)&&n++;return await this.client.del(i),n}async has(t){let i=this.getKey(t);return await this.client.exists(i)>0}async clear(){await this.deletePattern("*"),this.stats.hits=0,this.stats.misses=0,this.stats.size=0;}getStats(){return {...this.stats}}async getKeysByPattern(t){return this.useScan&&this.client.scan?this.scanKeys(t):this.client.keys?this.client.keys(t):(b().warn("Redis client does not support SCAN or KEYS. Pattern deletion not available."),[])}async scanKeys(t){if(!this.client.scan)return [];let i=[],e="0";do{let[n,s]=await this.client.scan(e,{match:t,count:this.scanCount});e=String(n),i.push(...s);}while(e!=="0");return i}};async function u(h,t){for(let i=0;i<h.length;i+=50)await Promise.all(h.slice(i,i+50).map(t));}var m=class{kv;prefix;defaultTtl;stats={hits:0,misses:0,size:0};constructor(t){this.kv=t.kv,this.prefix=t.prefix??"cache:",this.defaultTtl=t.defaultTtl??300;}getKey(t){return `${this.prefix}${t}`}getTagKey(t){return `${this.prefix}_tag:${t}`}getExpirationTtl(t){return Math.max(60,t)}async get(t){let i=await this.kv.get(this.getKey(t));if(!i)return this.stats.misses++,null;try{let e=JSON.parse(i),n=e.createdAt;if(typeof n=="string"){let r=Date.parse(n);e.createdAt=Number.isNaN(r)?Date.now():r;}let s=e.expiresAt;if(typeof s=="string"){let r=Date.parse(s);e.expiresAt=Number.isNaN(r)?null:r;}return e.expiresAt&&e.expiresAt<Date.now()?(this.stats.misses++,null):(this.stats.hits++,e)}catch{return this.stats.misses++,null}}async set(t,i,e){let n=e?.ttl??this.defaultTtl,s=e?.tags,r=Date.now(),a={data:i,createdAt:r,expiresAt:n>0?r+n*1e3:null,tags:s},o=n>0?{expirationTtl:this.getExpirationTtl(n)}:void 0;await this.kv.put(this.getKey(t),JSON.stringify(a),o),s&&await u(s,async l=>{let c=this.getTagKey(l),g=await this.kv.get(c),p=g?JSON.parse(g):[];p.includes(t)||(p.push(t),await this.kv.put(c,JSON.stringify(p),{expirationTtl:86400}));});}async delete(t){let i=this.getKey(t),e=await this.kv.get(i);if(e)try{let n=JSON.parse(e);n.tags&&await u(n.tags,async s=>{let r=this.getTagKey(s),a=await this.kv.get(r);if(!a)return;let l=JSON.parse(a).filter(c=>c!==t);l.length>0?await this.kv.put(r,JSON.stringify(l),{expirationTtl:86400}):await this.kv.delete(r);});}catch{}return await this.kv.delete(i),e!==null}async deletePattern(t){let i=t.indexOf("*"),e=i>=0?this.getKey(t.substring(0,i)):this.getKey(t),n=0,s;do{let r=await this.kv.list({prefix:e,limit:100,cursor:s}),a=r.keys.map(({name:o})=>o.substring(this.prefix.length));await u(a,o=>this.delete(o)),n+=a.length,s=r.list_complete?void 0:r.cursor;}while(s);return n}async deleteByTag(t){let i=this.getTagKey(t),e=await this.kv.get(i);if(!e)return 0;let n=JSON.parse(e);return await u(n,s=>this.kv.delete(this.getKey(s))),await this.kv.delete(i),n.length}async has(t){return await this.kv.get(this.getKey(t))!==null}async clear(){await this.deletePattern("*"),this.stats={hits:0,misses:0,size:0};}getStats(){return {...this.stats}}};export{y as a,m as b};
|