hono-crud 0.5.3 → 0.6.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 +1 -0
- package/dist/adapters/drizzle/index.d.ts +5 -5
- package/dist/adapters/drizzle/index.js +2 -2
- package/dist/adapters/memory/index.d.ts +19 -6
- package/dist/adapters/memory/index.js +1 -1
- package/dist/adapters/prisma/index.d.ts +4 -4
- package/dist/adapters/prisma/index.js +1 -1
- package/dist/audit/index.d.ts +2 -2
- package/dist/audit/index.js +1 -1
- package/dist/auth/index.d.ts +85 -5
- package/dist/auth/index.js +1 -1
- package/dist/{bulk-patch-Kg8XagOd.d.ts → bulk-patch-C9PIpw4R.d.ts} +2 -2
- package/dist/cache/index.d.ts +4 -4
- package/dist/cache/index.js +1 -1
- package/dist/chunk-2I6G2Q6U.js +11 -0
- package/dist/{chunk-GASDSU4U.js → chunk-3PFSX6M2.js} +1 -1
- package/dist/chunk-3TIIYAKB.js +1 -0
- package/dist/{chunk-HAUN4LQO.js → chunk-7NM6MBRL.js} +1 -1
- package/dist/{chunk-NIWM7GOK.js → chunk-ANWSQPCQ.js} +1 -1
- package/dist/chunk-HCFP7RM6.js +1 -0
- package/dist/{chunk-OXBPASZN.js → chunk-K3XR44EH.js} +1 -1
- package/dist/chunk-KLZMYDYG.js +1 -0
- package/dist/{chunk-RFT77JBK.js → chunk-Z575OBLV.js} +1 -1
- package/dist/{emitter-Npan0uNZ.d.ts → emitter-vW4MflrJ.d.ts} +1 -1
- package/dist/events/index.d.ts +4 -4
- package/dist/{import-Co7vvjkO.d.ts → import-JN0uu97B.d.ts} +138 -18
- package/dist/{index-COXyTPal.d.ts → index-KkWX8bsI.d.ts} +3 -3
- package/dist/index.d.ts +133 -18
- package/dist/index.js +2 -1
- package/dist/logging/index.js +1 -1
- package/dist/rate-limit/index.js +1 -1
- package/dist/{route-CSScNXhr.d.ts → route-AzM3iPZP.d.ts} +1 -1
- package/dist/storage/index.d.ts +4 -5
- package/dist/storage/index.js +1 -1
- package/dist/{types-BCsipBBX.d.ts → types-rJSyOxkJ.d.ts} +12 -0
- package/dist/{types-T4ThpPOK.d.ts → types-tpG0M7Va.d.ts} +569 -3
- package/dist/versioning/index.d.ts +2 -2
- package/dist/versioning/index.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-BSL6R76X.js +0 -1
- package/dist/chunk-Q2D5AUPJ.js +0 -1
- package/dist/chunk-Q4FF5JVS.js +0 -11
- package/dist/chunk-W4FHI5YI.js +0 -1
- package/dist/types-Di38wHnA.d.ts +0 -357
package/CHANGELOG.md
CHANGED
|
@@ -60,3 +60,4 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
60
60
|
[0.5.1]: https://github.com/kshdotdev/hono-crud/compare/v0.5.0...v0.5.1
|
|
61
61
|
[0.5.2]: https://github.com/kshdotdev/hono-crud/compare/v0.5.1...v0.5.2
|
|
62
62
|
[0.5.3]: https://github.com/kshdotdev/hono-crud/compare/v0.5.2...v0.5.3
|
|
63
|
+
[0.6.0]: https://github.com/kshdotdev/hono-crud/compare/v0.5.3...v0.6.0
|
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
import { Table, SQL, Column } from 'drizzle-orm';
|
|
2
|
-
import { M as MetaInput, I as IncludeOptions, l as FilterCondition, f as RelationConfig, N as NestedUpdateInput, g as NestedWriteResult, L as ListFilters, P as PaginatedResult, h as AggregateOptions, i as AggregateResult, S as SearchOptions, j as SearchResult } from '../../types-
|
|
2
|
+
import { M as MetaInput, I as IncludeOptions, l as FilterCondition, f as RelationConfig, N as NestedUpdateInput, g as NestedWriteResult, L as ListFilters, P as PaginatedResult, h as AggregateOptions, i as AggregateResult, S as SearchOptions, j as SearchResult } from '../../types-tpG0M7Va.js';
|
|
3
3
|
import { Env } from 'hono';
|
|
4
|
-
import { a as CreateEndpoint, M as ModelObject, R as ReadEndpoint, U as UpdateEndpoint, D as DeleteEndpoint, L as ListEndpoint, b as RestoreEndpoint, B as BatchCreateEndpoint, c as BatchDeleteEndpoint, d as BatchRestoreEndpoint, e as BatchUpdateEndpoint, f as BatchUpdateItem, A as AggregateEndpoint, g as BatchUpsertEndpoint, h as UpsertEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint, V as VersionCompareEndpoint, i as VersionHistoryEndpoint, j as VersionReadEndpoint, k as VersionRollbackEndpoint } from '../../import-
|
|
5
|
-
import { A as AdapterBundle } from '../../index-
|
|
4
|
+
import { a as CreateEndpoint, M as ModelObject, R as ReadEndpoint, U as UpdateEndpoint, D as DeleteEndpoint, L as ListEndpoint, b as RestoreEndpoint, B as BatchCreateEndpoint, c as BatchDeleteEndpoint, d as BatchRestoreEndpoint, e as BatchUpdateEndpoint, f as BatchUpdateItem, A as AggregateEndpoint, g as BatchUpsertEndpoint, h as UpsertEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint, V as VersionCompareEndpoint, i as VersionHistoryEndpoint, j as VersionReadEndpoint, k as VersionRollbackEndpoint } from '../../import-JN0uu97B.js';
|
|
5
|
+
import { A as AdapterBundle } from '../../index-KkWX8bsI.js';
|
|
6
6
|
import { z } from 'zod';
|
|
7
7
|
import '../../types-B5wq2iKZ.js';
|
|
8
8
|
import '../../types-BAcN7U0B.js';
|
|
9
9
|
import '@hono/zod-openapi';
|
|
10
|
-
import '../../route-
|
|
10
|
+
import '../../route-AzM3iPZP.js';
|
|
11
11
|
import 'hono/utils/http-status';
|
|
12
12
|
import '../../audit/index.js';
|
|
13
13
|
import '../../registry-PNJjvSvm.js';
|
|
14
14
|
import '../../versioning/index.js';
|
|
15
|
-
import '../../types-
|
|
15
|
+
import '../../types-rJSyOxkJ.js';
|
|
16
16
|
|
|
17
17
|
/**
|
|
18
18
|
* Internal query builder interface used for type-safe method calls.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {k,l,m as m$1,n,o,p,r,s,t,u,q as q$1,v,w,x as x$1,y,z as z$1,A,B as B$1,J,K,T,U as U$1}from'../../chunk-
|
|
1
|
+
import {k,l,m as m$1,n,o,p,r,s,t,u,q as q$1,v,w,x as x$1,y,z as z$1,A,B as B$1,J,K,T,U as U$1}from'../../chunk-2I6G2Q6U.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-3TIIYAKB.js';import'../../chunk-7NM6MBRL.js';import'../../chunk-ANWSQPCQ.js';import'../../chunk-Z575OBLV.js';import'../../chunk-FC56WWPB.js';import'../../chunk-GBQQ3YQX.js';import'../../chunk-QRXEQTNE.js';import'../../chunk-QXFY6NYI.js';import {b}from'../../chunk-DMGP7QDL.js';import'../../chunk-MDHMZPXK.js';import'../../chunk-VJRDAVID.js';import {getTableColumns,eq,inArray,between,isNull,isNotNull,ilike,like,notInArray,lte,lt as lt$1,gte,gt as gt$1,ne,and,sql,or,desc,asc}from'drizzle-orm';import {z}from'zod';function L(l){return l}function f(l){if(!l.model.table)throw new Error(`Model ${l.model.tableName} does not have a table reference`);return l.model.table}function m(l,e){let o=getTableColumns(l),n=o[e];if(!n)throw new Error(`Column '${e}' not found in table. Available columns: ${Object.keys(o).join(", ")}`);return n}async function Te(l,e,o,n){if(!n.table)return e;let t=n.table;switch(n.type){case "hasOne":{let r=n.localKey||"id",s=e[r];if(s==null)return e;let a=m(t,n.foreignKey),i=await l.select().from(t).where(eq(a,s)).limit(1);return {...e,[o]:i[0]||null}}case "hasMany":{let r=n.localKey||"id",s=e[r];if(s==null)return {...e,[o]:[]};let a=m(t,n.foreignKey),i=await l.select().from(t).where(eq(a,s));return {...e,[o]:i}}case "belongsTo":{let r=e[n.foreignKey];if(r==null)return {...e,[o]:null};let s=m(t,n.localKey||"id"),a=await l.select().from(t).where(eq(s,r)).limit(1);return {...e,[o]:a[0]||null}}default:return e}}async function ee(l,e,o,n){if(!n?.relations?.length||!o.model.relations)return e;let t={...e};for(let r of n.relations){let s=o.model.relations[r];s&&(t=await Te(l,t,r,s));}return t}async function O(l,e,o,n){if(!e.length||!n?.relations?.length||!o.model.relations)return e;let t=e.map(r=>({...r}));for(let r of n.relations){let s=o.model.relations[r];if(!s||!s.table)continue;let a=s.table;switch(s.type){case "hasOne":case "hasMany":{let i=s.localKey||"id",u=[...new Set(t.map(p=>p[i]).filter(p=>p!=null))];if(u.length===0){t=t.map(p=>({...p,[r]:s.type==="hasMany"?[]:null}));continue}let d=m(a,s.foreignKey),c=await l.select().from(a).where(inArray(d,u)),g=new Map;for(let p of c){let b=p[s.foreignKey];g.has(b)||g.set(b,[]),g.get(b).push(p);}t=t.map(p=>{let b=p[i],y=g.get(b)||[];return {...p,[r]:s.type==="hasMany"?y:y[0]||null}});break}case "belongsTo":{let i=s.localKey||"id",u=[...new Set(t.map(p=>p[s.foreignKey]).filter(p=>p!=null))];if(u.length===0){t=t.map(p=>({...p,[r]:null}));continue}let d=m(a,i),c=await l.select().from(a).where(inArray(d,u)),g=new Map;for(let p of c){let b=p[i];g.set(b,p);}t=t.map(p=>{let b=p[s.foreignKey];return {...p,[r]:g.get(b)||null}});break}}}return t}function x(l,e){let o=m(l,e.field);switch(e.operator){case "eq":return eq(o,e.value);case "ne":return ne(o,e.value);case "gt":return gt$1(o,e.value);case "gte":return gte(o,e.value);case "lt":return lt$1(o,e.value);case "lte":return lte(o,e.value);case "in":return inArray(o,e.value);case "nin":return notInArray(o,e.value);case "like":return like(o,e.value);case "ilike":return ilike(o,e.value);case "null":return e.value?isNull(o):isNotNull(o);case "between":{let[n,t]=e.value;return between(o,n,t)}default:return}}function D(l){let e=l;if(e._tx)return e._tx;if(e.db)return e.db;let o=e.context?.get?.("db");if(o)return o;throw new Error(`Database not configured. Either:
|
|
2
2
|
1. Set db property: db = myDb;
|
|
3
3
|
2. Use middleware: c.set("db", myDb);
|
|
4
|
-
3. Use factory: createDrizzleCrud(db, meta)`)}var S=class extends k{db;useTransaction=false;_tx;getDb(){return D(this)}getTable(){return f(this._meta)}getRelatedTable(e){return e.table}async create(e,o){let n=o??this.getDb(),t=this.getTable(),r=this._meta.model.primaryKeys[0],s={...e,[r]:e[r]||crypto.randomUUID()};return (await n.insert(t).values(s).returning())[0]}async createNested(e,o,n,t,r){let s=r??this.getDb(),a=this.getRelatedTable(n);if(!a)return b().warn(`Related table not found for ${o}. Add 'table' to the relation config.`),[];let i=Array.isArray(t)?t:[t],u=[];for(let d of i){if(typeof d!="object"||d===null)continue;let c={...d,id:crypto.randomUUID(),[n.foreignKey]:e},g=await s.insert(a).values(c).returning();g[0]&&u.push(g[0]);}return u}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},_=class extends l{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async read(e,o,n){let t=this.getTable(),r=this.getColumn(this.lookupField),s=this.getSoftDeleteConfig(),a=[eq(r,e)];if(o)for(let[d,c]of Object.entries(o))a.push(eq(this.getColumn(d),c));s.enabled&&a.push(isNull(this.getColumn(s.field)));let i=await this.getDb().select().from(t).where(and(...a)).limit(1);return i[0]?await ee(this.getDb(),i[0],this._meta,n):null}},I=class extends m$1{db;useTransaction=false;_tx;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}getRelatedTable(e){return e.table}async findExisting(e,o,n){let t=n??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),i=[eq(s,e)];if(o)for(let[d,c]of Object.entries(o))i.push(eq(this.getColumn(d),c));return a.enabled&&i.push(isNull(this.getColumn(a.field))),(await t.select().from(r).where(and(...i)).limit(1))[0]||null}async update(e,o,n,t){let r=t??this.getDb(),s=this.getTable(),a=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),u=[eq(a,e)];if(n)for(let[c,g]of Object.entries(n))u.push(eq(this.getColumn(c),g));return i.enabled&&u.push(isNull(this.getColumn(i.field))),(await r.update(s).set(o).where(and(...u)).returning())[0]||null}async processNestedWrites(e,o,n,t,r){let s=r??this.getDb(),a=this.getRelatedTable(n);if(!a)return b().warn(`Related table not found for ${o}. Add 'table' to the relation config.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]};let i={created:[],updated:[],deleted:[],connected:[],disconnected:[]},u=m(a,n.foreignKey),d=m(a,"id");if(t.create){let c=Array.isArray(t.create)?t.create:[t.create];for(let g of c){if(typeof g!="object"||g===null)continue;let p={...g,id:crypto.randomUUID(),[n.foreignKey]:e},b=await s.insert(a).values(p).returning();b[0]&&i.created.push(b[0]);}}if(t.update)for(let c of t.update){if(!c.id||!(await s.select().from(a).where(and(eq(d,c.id),eq(u,e))).limit(1))[0])continue;let{id:p,...b}=c,y=await s.update(a).set(b).where(eq(d,p)).returning();y[0]&&i.updated.push(y[0]);}if(t.delete)for(let c of t.delete)(await s.delete(a).where(and(eq(d,c),eq(u,e))).returning())[0]&&i.deleted.push(c);if(t.connect)for(let c of t.connect)(await s.update(a).set({[n.foreignKey]:e}).where(eq(d,c)).returning())[0]&&i.connected.push(c);if(t.disconnect)for(let c of t.disconnect)(await s.update(a).set({[n.foreignKey]:null}).where(and(eq(d,c),eq(u,e))).returning())[0]&&i.disconnected.push(c);return i}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},P=class extends n{db;useTransaction=false;_tx;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}getRelatedTable(e){return e.table}async findForDelete(e,o,n){let t=n??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),i=[eq(s,e)];if(o)for(let[d,c]of Object.entries(o))i.push(eq(this.getColumn(d),c));return a.enabled&&i.push(isNull(this.getColumn(a.field))),(await t.select().from(r).where(and(...i)).limit(1))[0]||null}async delete(e,o,n){let t=n??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),i=[eq(s,e)];if(o)for(let[u,d]of Object.entries(o))i.push(eq(this.getColumn(u),d));return a.enabled&&i.push(isNull(this.getColumn(a.field))),a.enabled?(await t.update(r).set({[a.field]:new Date}).where(and(...i)).returning())[0]||null:(await t.delete(r).where(and(...i)).returning())[0]||null}async countRelated(e,o,n,t){let r=t??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let a=m(s,n.foreignKey),i=await r.select({count:sql`count(*)`}).from(s).where(eq(a,e));return Number(i[0]?.count)||0}async deleteRelated(e,o,n,t){let r=t??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let a=m(s,n.foreignKey);return (await r.delete(s).where(eq(a,e)).returning()).length}async nullifyRelated(e,o,n,t){let r=t??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let a=m(s,n.foreignKey);return (await r.update(s).set({[n.foreignKey]:null}).where(eq(a,e)).returning()).length}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},U=class extends o{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async list(e){let o=this.getTable(),n=[],t=this.getSoftDeleteConfig();if(t.enabled){let z=this.getColumn(t.field);e.options.onlyDeleted?n.push(isNotNull(z)):e.options.withDeleted||n.push(isNull(z));}for(let z of e.filters){let R=x(o,z);R&&n.push(R);}if(e.options.search&&this.searchFields.length>0){let z=this.searchFields.map(R=>{let H=this.getColumn(R);return sql`LOWER(${H}) LIKE LOWER(${`%${e.options.search}%`})`});n.push(or(...z));}let r=n.length>0?and(...n):void 0,s=this.getDb(),a=await s.select({count:sql`count(*)`}).from(o).where(r),i=Number(a[0]?.count)||0,u=s.select().from(o).where(r);if(e.options.order_by){let z=this.getColumn(e.options.order_by),R=e.options.order_by_direction==="desc"?desc:asc;u=u.orderBy(R(z));}let d=e.options.page||1,c=e.options.per_page||this.defaultPerPage;u=u.limit(c).offset((d-1)*c);let g=await u,p={relations:e.options.include||[]},b=await O(this.getDb(),g,this._meta,p),y=Math.ceil(i/c);return {result:b,result_info:{page:d,per_page:c,total_count:i,total_pages:y,has_next_page:d<y,has_prev_page:d>1}}}},B=class extends p{db;useTransaction=false;_tx;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async restore(e,o,n){let t=n??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),i=[eq(s,e)];if(o)for(let[d,c]of Object.entries(o))i.push(eq(this.getColumn(d),c));return i.push(isNotNull(this.getColumn(a.field))),(await t.update(r).set({[a.field]:null}).where(and(...i)).returning())[0]||null}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}};var Q=class extends r{db;getDb(){return D(this)}getTable(){return f(this._meta)}async batchCreate(e){let o=this.getTable(),n=this._meta.model.primaryKeys[0],t=e.map(s=>({...s,[n]:s[n]||crypto.randomUUID()}));return await this.getDb().insert(o).values(t).returning()}},N=class extends s{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async batchUpdate(e){let o=this.getTable(),n=this.getColumn(this.lookupField),t=this.getSoftDeleteConfig(),r=[],s=[];for(let a of e){let i=[eq(n,a.id)];t.enabled&&i.push(isNull(this.getColumn(t.field)));let u=await this.getDb().update(o).set(a.data).where(and(...i)).returning();u[0]?r.push(u[0]):s.push(a.id);}return {updated:r,notFound:s}}},F=class extends t{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async batchDelete(e){let o=this.getTable(),n=this.getColumn(this.lookupField),t=this.getSoftDeleteConfig(),r=[inArray(n,e)];t.enabled&&r.push(isNull(this.getColumn(t.field)));let s;t.enabled?s=await this.getDb().update(o).set({[t.field]:new Date}).where(and(...r)).returning():s=await this.getDb().delete(o).where(and(...r)).returning();let a=s,i=new Set(a.map(d=>String(d[this.lookupField]))),u=e.filter(d=>!i.has(d));return {deleted:a,notFound:u}}},$=class extends u{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async batchRestore(e){let o=this.getTable(),n=this.getColumn(this.lookupField),t=this.getSoftDeleteConfig(),r=[inArray(n,e),isNotNull(this.getColumn(t.field))],a=await this.getDb().update(o).set({[t.field]:null}).where(and(...r)).returning(),i=new Set(a.map(d=>String(d[this.lookupField]))),u=e.filter(d=>!i.has(d));return {restored:a,notFound:u}}};var q=class extends q$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async findExisting(e){let o=this.getTable(),n=this.getUpsertKeys(),t=this.getSoftDeleteConfig(),r=[];for(let a of n){let i=e[a];i!==void 0&&r.push(eq(this.getColumn(a),i));}return t.enabled&&r.push(isNull(this.getColumn(t.field))),r.length===0?null:(await this.getDb().select().from(o).where(and(...r)).limit(1))[0]||null}async create(e){let o=this.getTable(),n=this._meta.model.primaryKeys[0],t={...e,[n]:e[n]||crypto.randomUUID()};return (await this.getDb().insert(o).values(t).returning())[0]}async update(e,o){let n=this.getTable(),t=this._meta.model.primaryKeys[0],r=e[t];return (await this.getDb().update(n).set(o).where(eq(this.getColumn(t),r)).returning())[0]}async nativeUpsert(e,o){let n=this.getTable(),t=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s=this.getSoftDeleteConfig(),a={...e,[r]:e[r]||crypto.randomUUID()},i={};for(let[c,g]of Object.entries(e))!t.includes(c)&&c!==r&&(this.createOnlyFields?.includes(c)||(i[c]=g));let u=t.map(c=>this.getColumn(c)),d;s.enabled&&(d=isNull(this.getColumn(s.field)));try{return {data:(await this.getDb().insert(n).values(a).onConflictDoUpdate({target:u,set:Object.keys(i).length>0?i:{[r]:sql`${this.getColumn(r)}`},where:d}).returning())[0],created:!1}}catch(c){if(c instanceof Error&&c.message.includes("onConflictDoUpdate"))try{return {data:(await this.getDb().insert(n).values(a).onDuplicateKeyUpdate({set:Object.keys(i).length>0?i:{[r]:sql`${this.getColumn(r)}`}}).returning())[0],created:!1}}catch{return this.performStandardUpsert(e,o)}throw c}}},W=class extends v{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async findExisting(e){let o=this.getTable(),n=this.getUpsertKeys(),t=[];for(let s of n){let a=e[s];a!==void 0&&t.push(eq(this.getColumn(s),a));}return t.length===0?null:(await this.getDb().select().from(o).where(and(...t)).limit(1))[0]||null}async create(e){let o=this.getTable(),n=this._meta.model.primaryKeys[0],t={...e,[n]:e[n]||crypto.randomUUID()};return (await this.getDb().insert(o).values(t).returning())[0]}async update(e,o){let n=this.getTable(),t=this._meta.model.primaryKeys[0],r=e[t];return (await this.getDb().update(n).set(o).where(eq(this.getColumn(t),r)).returning())[0]}async nativeBatchUpsert(e,o){if(e.length===0)return {items:[],createdCount:0,updatedCount:0,totalCount:0};let n=this.getTable(),t=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s=e.map(d=>({...d,[r]:d[r]||crypto.randomUUID()})),a={},i=e[0];for(let d of Object.keys(i))!t.includes(d)&&d!==r&&(this.createOnlyFields?.includes(d)||(a[d]=sql`excluded.${sql.identifier(d)}`));let u=t.map(d=>this.getColumn(d));try{let c=await this.getDb().insert(n).values(s).onConflictDoUpdate({target:u,set:Object.keys(a).length>0?a:{[r]:sql`${this.getColumn(r)}`}}).returning();return {items:c.map((g,p)=>({data:g,created:!1,index:p})),createdCount:0,updatedCount:c.length,totalCount:c.length}}catch(d){if(d instanceof Error&&d.message.includes("onConflictDoUpdate"))try{let g=await this.getDb().insert(n).values(s).onDuplicateKeyUpdate({set:Object.keys(a).length>0?a:{[r]:sql`${this.getColumn(r)}`}}).returning();return {items:g.map((p,b)=>({data:p,created:!1,index:b})),createdCount:0,updatedCount:g.length,totalCount:g.length}}catch{return this.performStandardBatchUpsert(e,o)}throw d}}},ke=class extends w{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async recordExists(e){let o=this.getTable(),n=await this.getDb().select({count:sql`count(*)`}).from(o).where(eq(this.getColumn("id"),e));return Number(n[0]?.count)>0}},Oe=class extends x$1{},ve=class extends y{},je=class extends z$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async rollback(e,o,n){let t=this.getTable(),r=this.getVersioningConfig().field;return (await this.getDb().update(t).set({...o,[r]:n}).where(eq(this.getColumn("id"),e)).returning())[0]}},Se=class extends A{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async aggregate(e){let o=this.getTable(),n=[],t=this.getSoftDeleteConfig();if(t.enabled){let{query:a}=await this.getValidatedData();a?.withDeleted===true||a?.withDeleted==="true"||n.push(isNull(this.getColumn(t.field)));}if(e.filters)for(let[a,i]of Object.entries(e.filters))if(typeof i=="object"&&i!==null)for(let[u,d]of Object.entries(i)){let c=x(o,{field:a,operator:u,value:d});c&&n.push(c);}else n.push(eq(this.getColumn(a),i));let r=n.length>0?and(...n):void 0,s=await this.getDb().select().from(o).where(r);return B$1(s,e)}},_e=class extends J{db;getDb(){return D(this)}useNativeSearch=false;vectorColumn;vectorConfig="english";getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async search(e,o){let n=this.getTable(),t=[],r=this.getSoftDeleteConfig();r.enabled&&(o.options.onlyDeleted?t.push(isNotNull(this.getColumn(r.field))):o.options.withDeleted||t.push(isNull(this.getColumn(r.field))));for(let w of o.filters){let C=x(n,w);C&&t.push(C);}let s=this.getSearchableFields(),a=e.fields||Object.keys(s);if(this.useNativeSearch&&this.vectorColumn){let w=this.getColumn(this.vectorColumn),C=e.mode==="phrase"?sql`phraseto_tsquery(${this.vectorConfig}, ${e.query})`:e.mode==="all"?sql`plainto_tsquery(${this.vectorConfig}, ${e.query})`:sql`to_tsquery(${this.vectorConfig}, ${e.query.split(/\s+/).join(" | ")})`;t.push(sql`${w} @@ ${C}`);}else {let w=a.map(C=>{try{let Qe=this.getColumn(C);return sql`LOWER(CAST(${Qe} AS TEXT)) LIKE LOWER(${`%${e.query}%`})`}catch{return}}).filter(C=>C!==void 0);w.length>0&&(e.mode==="all"?t.push(and(...w)):t.push(or(...w)));}let i=t.length>0?and(...t):void 0,u=await this.getDb().select({count:sql`count(*)`}).from(n).where(i),d=Number(u[0]?.count)||0,c=this.getDb().select().from(n).where(i);if(o.options.order_by){let w=this.getColumn(o.options.order_by),C=o.options.order_by_direction==="desc"?desc:asc;c=c.orderBy(C(w));}let g=o.options.page||1,p=o.options.per_page||this.defaultPerPage;c=c.limit(p).offset((g-1)*p);let b=await c,y=K(b,e,s),z={relations:o.options.include||[]},R=y.map(w=>w.item),H=await O(this.getDb(),R,this._meta,z);return {items:y.map((w,C)=>({...w,item:H[C]})),totalCount:d}}},Ie=class extends T{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async list(e){let o=this.getTable(),n=[],t=this.getSoftDeleteConfig();if(t.enabled){let y=this.getColumn(t.field);e.options.onlyDeleted?n.push(isNotNull(y)):e.options.withDeleted||n.push(isNull(y));}for(let y of e.filters){let z=x(o,y);z&&n.push(z);}if(e.options.search&&this.searchFields.length>0){let y=this.searchFields.map(z=>{let R=this.getColumn(z);return sql`LOWER(${R}) LIKE LOWER(${`%${e.options.search}%`})`});n.push(or(...y));}let r=n.length>0?and(...n):void 0,s=await this.getDb().select({count:sql`count(*)`}).from(o).where(r),a=Number(s[0]?.count)||0,i=this.getDb().select().from(o).where(r);if(e.options.order_by){let y=this.getColumn(e.options.order_by),z=e.options.order_by_direction==="desc"?desc:asc;i=i.orderBy(z(y));}let u=e.options.page||1,d=e.options.per_page||this.defaultPerPage;i=i.limit(d).offset((u-1)*d);let c=await i,g={relations:e.options.include||[]},p=await O(this.getDb(),c,this._meta,g),b=Math.ceil(a/d);return {result:p,result_info:{page:u,per_page:d,total_count:a,total_pages:b,has_next_page:u<b,has_prev_page:u>1}}}},Pe=class extends U$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async findExisting(e){let o=this.getTable(),n=this.getUpsertKeys(),t=this.getSoftDeleteConfig(),r=[];for(let a of n){let i=e[a];i!==void 0&&r.push(eq(this.getColumn(a),i));}return t.enabled&&r.push(isNull(this.getColumn(t.field))),r.length===0?null:(await this.getDb().select().from(o).where(and(...r)).limit(1))[0]||null}async create(e){let o=this.getTable(),n=this._meta.model.primaryKeys[0],t={...e,[n]:e[n]||crypto.randomUUID()};return (await this.getDb().insert(o).values(t).returning())[0]}async update(e,o){let n=this.getTable(),t=this._meta.model.primaryKeys[0],r=e[t];return (await this.getDb().update(n).set(o).where(eq(this.getColumn(t),r)).returning())[0]}};function Ht(l,e){return {Create:class extends S{_meta=e;db=l},Read:class extends _{_meta=e;db=l},Update:class extends I{_meta=e;db=l},Delete:class extends P{_meta=e;db=l},List:class extends U{_meta=e;db=l},Restore:class extends B{_meta=e;db=l},Upsert:class extends q{_meta=e;db=l},BatchCreate:class extends Q{_meta=e;db=l},BatchUpdate:class extends N{_meta=e;db=l},BatchDelete:class extends F{_meta=e;db=l},BatchRestore:class extends ${_meta=e;db=l},BatchUpsert:class extends W{_meta=e;db=l}}}var Jt={CreateEndpoint:S,ListEndpoint:U,ReadEndpoint:_,UpdateEndpoint:I,DeleteEndpoint:P};var X=null,Be=false,V=null;async function G(){if(Be){if(V)throw V;return X}Be=true;try{return X=await import('drizzle-zod'),X}catch{throw V=new Error("drizzle-zod is not installed. Please install it: npm install drizzle-zod"),V}}async function at(l,e){return (await G()).createSelectSchema(l,e)}async function it(l,e){return (await G()).createInsertSchema(l,e)}async function lt(l,e){let o=await G();return o.createUpdateSchema?o.createUpdateSchema(l,e):o.createInsertSchema(l,e).partial()}async function dt(l,e){let o=await G(),n=e?.coerceDates!==false,t=n?gt(l):new Set,r=o.createSelectSchema(l,e?.selectRefine),s=o.createInsertSchema(l,e?.insertRefine),a;return o.createUpdateSchema?a=o.createUpdateSchema(l,e?.updateRefine):a=o.createInsertSchema(l,e?.updateRefine).partial(),n&&t.size>0&&(s=Ze(s,t),a=Ze(a,t)),{select:r,insert:s,update:a}}function ct(){return X!==null}var ut=z.preprocess(l=>{if(l instanceof Date)return l;if(typeof l=="string"){let e=new Date(l);if(!isNaN(e.getTime()))return e}return l},z.date()),pt=z.preprocess(l=>{if(l==null)return null;if(l instanceof Date)return l;if(typeof l=="string"){let e=new Date(l);if(!isNaN(e.getTime()))return e}return l},z.date().nullable());function gt(l){let e=new Set,o=l;for(let[n,t]of Object.entries(o)){if(n==="_"||n==="$inferInsert"||n==="$inferSelect")continue;let r=t;if(!r||typeof r!="object")continue;let s=String(r.dataType??"").toLowerCase(),a=String(r.columnType??"").toLowerCase(),i=r.config,u=String(i?.dataType??"").toLowerCase();(s.includes("timestamp")||s.includes("date")||s.includes("datetime")||a.includes("pgtimestamp")||a.includes("pgdate")||a.includes("mysqltimestamp")||a.includes("mysqldate")||a.includes("sqlitetimestamp")||u.includes("timestamp")||u.includes("date"))&&e.add(n);}return e}function Ze(l,e){if(e.size===0)return l;let o=l.shape,n={};for(let[t,r]of Object.entries(o))if(e.has(t)){let s=r.isOptional?.()??false,a=r.isNullable?.()??false,i=ut;(a||s)&&(i=pt),s&&(i=i.optional()),n[t]=i;}else n[t]=r;return z.object(n)}export{Jt as DrizzleAdapters,Se as DrizzleAggregateEndpoint,Q as DrizzleBatchCreateEndpoint,F as DrizzleBatchDeleteEndpoint,$ as DrizzleBatchRestoreEndpoint,N as DrizzleBatchUpdateEndpoint,W as DrizzleBatchUpsertEndpoint,S as DrizzleCreateEndpoint,P as DrizzleDeleteEndpoint,Ie as DrizzleExportEndpoint,Pe as DrizzleImportEndpoint,U as DrizzleListEndpoint,_ as DrizzleReadEndpoint,B as DrizzleRestoreEndpoint,_e as DrizzleSearchEndpoint,I as DrizzleUpdateEndpoint,q as DrizzleUpsertEndpoint,ve as DrizzleVersionCompareEndpoint,ke as DrizzleVersionHistoryEndpoint,Oe as DrizzleVersionReadEndpoint,je as DrizzleVersionRollbackEndpoint,O as batchLoadDrizzleRelations,x as buildWhereCondition,L as cast,Ht as createDrizzleCrud,dt as createDrizzleSchemas,it as createInsertSchema,at as createSelectSchema,lt as createUpdateSchema,m as getColumn,f as getTable,ct as isDrizzleZodAvailable,Te as loadDrizzleRelation,ee as loadDrizzleRelations};
|
|
4
|
+
3. Use factory: createDrizzleCrud(db, meta)`)}var S=class extends k{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getRelatedTable(e){return e.table}async create(e,o){let n=o??this.getDb(),t=this.getTable(),r=this._meta.model.primaryKeys[0],s={...e,[r]:e[r]||crypto.randomUUID()};return (await n.insert(t).values(s).returning())[0]}async createNested(e,o,n,t,r){let s=r??this.getDb(),a=this.getRelatedTable(n);if(!a)return b().warn(`Related table not found for ${o}. Add 'table' to the relation config.`),[];let i=Array.isArray(t)?t:[t],u=[];for(let d of i){if(typeof d!="object"||d===null)continue;let c={...d,id:crypto.randomUUID(),[n.foreignKey]:e},g=await s.insert(a).values(c).returning();g[0]&&u.push(g[0]);}return u}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},_=class extends l{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async read(e,o,n){let t=this.getTable(),r=this.getColumn(this.lookupField),s=this.getSoftDeleteConfig(),a=[eq(r,e)];if(o)for(let[d,c]of Object.entries(o))a.push(eq(this.getColumn(d),c));s.enabled&&a.push(isNull(this.getColumn(s.field)));let i=await this.getDb().select().from(t).where(and(...a)).limit(1);return i[0]?await ee(this.getDb(),i[0],this._meta,n):null}},I=class extends m$1{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}getRelatedTable(e){return e.table}async findExisting(e,o,n){let t=n??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),i=[eq(s,e)];if(o)for(let[d,c]of Object.entries(o))i.push(eq(this.getColumn(d),c));return a.enabled&&i.push(isNull(this.getColumn(a.field))),(await t.select().from(r).where(and(...i)).limit(1))[0]||null}async update(e,o,n,t){let r=t??this.getDb(),s=this.getTable(),a=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),u=[eq(a,e)];if(n)for(let[c,g]of Object.entries(n))u.push(eq(this.getColumn(c),g));return i.enabled&&u.push(isNull(this.getColumn(i.field))),(await r.update(s).set(o).where(and(...u)).returning())[0]||null}async processNestedWrites(e,o,n,t,r){let s=r??this.getDb(),a=this.getRelatedTable(n);if(!a)return b().warn(`Related table not found for ${o}. Add 'table' to the relation config.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]};let i={created:[],updated:[],deleted:[],connected:[],disconnected:[]},u=m(a,n.foreignKey),d=m(a,"id");if(t.create){let c=Array.isArray(t.create)?t.create:[t.create];for(let g of c){if(typeof g!="object"||g===null)continue;let p={...g,id:crypto.randomUUID(),[n.foreignKey]:e},b=await s.insert(a).values(p).returning();b[0]&&i.created.push(b[0]);}}if(t.update)for(let c of t.update){if(!c.id||!(await s.select().from(a).where(and(eq(d,c.id),eq(u,e))).limit(1))[0])continue;let{id:p,...b}=c,y=await s.update(a).set(b).where(eq(d,p)).returning();y[0]&&i.updated.push(y[0]);}if(t.delete)for(let c of t.delete)(await s.delete(a).where(and(eq(d,c),eq(u,e))).returning())[0]&&i.deleted.push(c);if(t.connect)for(let c of t.connect)(await s.update(a).set({[n.foreignKey]:e}).where(eq(d,c)).returning())[0]&&i.connected.push(c);if(t.disconnect)for(let c of t.disconnect)(await s.update(a).set({[n.foreignKey]:null}).where(and(eq(d,c),eq(u,e))).returning())[0]&&i.disconnected.push(c);return i}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},P=class extends n{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}getRelatedTable(e){return e.table}async findForDelete(e,o,n){let t=n??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),i=[eq(s,e)];if(o)for(let[d,c]of Object.entries(o))i.push(eq(this.getColumn(d),c));return a.enabled&&i.push(isNull(this.getColumn(a.field))),(await t.select().from(r).where(and(...i)).limit(1))[0]||null}async delete(e,o,n){let t=n??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),i=[eq(s,e)];if(o)for(let[u,d]of Object.entries(o))i.push(eq(this.getColumn(u),d));return a.enabled&&i.push(isNull(this.getColumn(a.field))),a.enabled?(await t.update(r).set({[a.field]:new Date}).where(and(...i)).returning())[0]||null:(await t.delete(r).where(and(...i)).returning())[0]||null}async countRelated(e,o,n,t){let r=t??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let a=m(s,n.foreignKey),i=await r.select({count:sql`count(*)`}).from(s).where(eq(a,e));return Number(i[0]?.count)||0}async deleteRelated(e,o,n,t){let r=t??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let a=m(s,n.foreignKey);return (await r.delete(s).where(eq(a,e)).returning()).length}async nullifyRelated(e,o,n,t){let r=t??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let a=m(s,n.foreignKey);return (await r.update(s).set({[n.foreignKey]:null}).where(eq(a,e)).returning()).length}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},U=class extends o{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async list(e){let o=this.getTable(),n=[],t=this.getSoftDeleteConfig();if(t.enabled){let z=this.getColumn(t.field);e.options.onlyDeleted?n.push(isNotNull(z)):e.options.withDeleted||n.push(isNull(z));}for(let z of e.filters){let R=x(o,z);R&&n.push(R);}if(e.options.search&&this.searchFields.length>0){let z=this.searchFields.map(R=>{let H=this.getColumn(R);return sql`LOWER(${H}) LIKE LOWER(${`%${e.options.search}%`})`});n.push(or(...z));}let r=n.length>0?and(...n):void 0,s=this.getDb(),a=await s.select({count:sql`count(*)`}).from(o).where(r),i=Number(a[0]?.count)||0,u=s.select().from(o).where(r);if(e.options.order_by){let z=this.getColumn(e.options.order_by),R=e.options.order_by_direction==="desc"?desc:asc;u=u.orderBy(R(z));}let d=e.options.page||1,c=e.options.per_page||this.defaultPerPage;u=u.limit(c).offset((d-1)*c);let g=await u,p={relations:e.options.include||[]},b=await O(this.getDb(),g,this._meta,p),y=Math.ceil(i/c);return {result:b,result_info:{page:d,per_page:c,total_count:i,total_pages:y,has_next_page:d<y,has_prev_page:d>1}}}},B=class extends p{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async restore(e,o,n){let t=n??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),i=[eq(s,e)];if(o)for(let[d,c]of Object.entries(o))i.push(eq(this.getColumn(d),c));return i.push(isNotNull(this.getColumn(a.field))),(await t.update(r).set({[a.field]:null}).where(and(...i)).returning())[0]||null}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}};var Q=class extends r{db;getDb(){return D(this)}getTable(){return f(this._meta)}async batchCreate(e){let o=this.getTable(),n=this._meta.model.primaryKeys[0],t=e.map(s=>({...s,[n]:s[n]||crypto.randomUUID()}));return await this.getDb().insert(o).values(t).returning()}},N=class extends s{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async batchUpdate(e){let o=this.getTable(),n=this.getColumn(this.lookupField),t=this.getSoftDeleteConfig(),r=[],s=[];for(let a of e){let i=[eq(n,a.id)];t.enabled&&i.push(isNull(this.getColumn(t.field)));let u=await this.getDb().update(o).set(a.data).where(and(...i)).returning();u[0]?r.push(u[0]):s.push(a.id);}return {updated:r,notFound:s}}},F=class extends t{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async batchDelete(e){let o=this.getTable(),n=this.getColumn(this.lookupField),t=this.getSoftDeleteConfig(),r=[inArray(n,e)];t.enabled&&r.push(isNull(this.getColumn(t.field)));let s;t.enabled?s=await this.getDb().update(o).set({[t.field]:new Date}).where(and(...r)).returning():s=await this.getDb().delete(o).where(and(...r)).returning();let a=s,i=new Set(a.map(d=>String(d[this.lookupField]))),u=e.filter(d=>!i.has(d));return {deleted:a,notFound:u}}},$=class extends u{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async batchRestore(e){let o=this.getTable(),n=this.getColumn(this.lookupField),t=this.getSoftDeleteConfig(),r=[inArray(n,e),isNotNull(this.getColumn(t.field))],a=await this.getDb().update(o).set({[t.field]:null}).where(and(...r)).returning(),i=new Set(a.map(d=>String(d[this.lookupField]))),u=e.filter(d=>!i.has(d));return {restored:a,notFound:u}}};var q=class extends q$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async findExisting(e){let o=this.getTable(),n=this.getUpsertKeys(),t=this.getSoftDeleteConfig(),r=[];for(let a of n){let i=e[a];i!==void 0&&r.push(eq(this.getColumn(a),i));}return t.enabled&&r.push(isNull(this.getColumn(t.field))),r.length===0?null:(await this.getDb().select().from(o).where(and(...r)).limit(1))[0]||null}async create(e){let o=this.getTable(),n=this._meta.model.primaryKeys[0],t={...e,[n]:e[n]||crypto.randomUUID()};return (await this.getDb().insert(o).values(t).returning())[0]}async update(e,o){let n=this.getTable(),t=this._meta.model.primaryKeys[0],r=e[t];return (await this.getDb().update(n).set(o).where(eq(this.getColumn(t),r)).returning())[0]}async nativeUpsert(e,o){let n=this.getTable(),t=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s=this.getSoftDeleteConfig(),a={...e,[r]:e[r]||crypto.randomUUID()},i={};for(let[c,g]of Object.entries(e))!t.includes(c)&&c!==r&&(this.createOnlyFields?.includes(c)||(i[c]=g));let u=t.map(c=>this.getColumn(c)),d;s.enabled&&(d=isNull(this.getColumn(s.field)));try{return {data:(await this.getDb().insert(n).values(a).onConflictDoUpdate({target:u,set:Object.keys(i).length>0?i:{[r]:sql`${this.getColumn(r)}`},where:d}).returning())[0],created:!1}}catch(c){if(c instanceof Error&&c.message.includes("onConflictDoUpdate"))try{return {data:(await this.getDb().insert(n).values(a).onDuplicateKeyUpdate({set:Object.keys(i).length>0?i:{[r]:sql`${this.getColumn(r)}`}}).returning())[0],created:!1}}catch{return this.performStandardUpsert(e,o)}throw c}}},W=class extends v{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async findExisting(e){let o=this.getTable(),n=this.getUpsertKeys(),t=[];for(let s of n){let a=e[s];a!==void 0&&t.push(eq(this.getColumn(s),a));}return t.length===0?null:(await this.getDb().select().from(o).where(and(...t)).limit(1))[0]||null}async create(e){let o=this.getTable(),n=this._meta.model.primaryKeys[0],t={...e,[n]:e[n]||crypto.randomUUID()};return (await this.getDb().insert(o).values(t).returning())[0]}async update(e,o){let n=this.getTable(),t=this._meta.model.primaryKeys[0],r=e[t];return (await this.getDb().update(n).set(o).where(eq(this.getColumn(t),r)).returning())[0]}async nativeBatchUpsert(e,o){if(e.length===0)return {items:[],createdCount:0,updatedCount:0,totalCount:0};let n=this.getTable(),t=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s=e.map(d=>({...d,[r]:d[r]||crypto.randomUUID()})),a={},i=e[0];for(let d of Object.keys(i))!t.includes(d)&&d!==r&&(this.createOnlyFields?.includes(d)||(a[d]=sql`excluded.${sql.identifier(d)}`));let u=t.map(d=>this.getColumn(d));try{let c=await this.getDb().insert(n).values(s).onConflictDoUpdate({target:u,set:Object.keys(a).length>0?a:{[r]:sql`${this.getColumn(r)}`}}).returning();return {items:c.map((g,p)=>({data:g,created:!1,index:p})),createdCount:0,updatedCount:c.length,totalCount:c.length}}catch(d){if(d instanceof Error&&d.message.includes("onConflictDoUpdate"))try{let g=await this.getDb().insert(n).values(s).onDuplicateKeyUpdate({set:Object.keys(a).length>0?a:{[r]:sql`${this.getColumn(r)}`}}).returning();return {items:g.map((p,b)=>({data:p,created:!1,index:b})),createdCount:0,updatedCount:g.length,totalCount:g.length}}catch{return this.performStandardBatchUpsert(e,o)}throw d}}},ke=class extends w{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async recordExists(e){let o=this.getTable(),n=await this.getDb().select({count:sql`count(*)`}).from(o).where(eq(this.getColumn("id"),e));return Number(n[0]?.count)>0}},Oe=class extends x$1{},ve=class extends y{},je=class extends z$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async rollback(e,o,n){let t=this.getTable(),r=this.getVersioningConfig().field;return (await this.getDb().update(t).set({...o,[r]:n}).where(eq(this.getColumn("id"),e)).returning())[0]}},Se=class extends A{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async aggregate(e){let o=this.getTable(),n=[],t=this.getSoftDeleteConfig();if(t.enabled){let{query:a}=await this.getValidatedData();a?.withDeleted===true||a?.withDeleted==="true"||n.push(isNull(this.getColumn(t.field)));}if(e.filters)for(let[a,i]of Object.entries(e.filters))if(typeof i=="object"&&i!==null)for(let[u,d]of Object.entries(i)){let c=x(o,{field:a,operator:u,value:d});c&&n.push(c);}else n.push(eq(this.getColumn(a),i));let r=n.length>0?and(...n):void 0,s=await this.getDb().select().from(o).where(r);return B$1(s,e)}},_e=class extends J{db;getDb(){return D(this)}useNativeSearch=false;vectorColumn;vectorConfig="english";getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async search(e,o){let n=this.getTable(),t=[],r=this.getSoftDeleteConfig();r.enabled&&(o.options.onlyDeleted?t.push(isNotNull(this.getColumn(r.field))):o.options.withDeleted||t.push(isNull(this.getColumn(r.field))));for(let w of o.filters){let C=x(n,w);C&&t.push(C);}let s=this.getSearchableFields(),a=e.fields||Object.keys(s);if(this.useNativeSearch&&this.vectorColumn){let w=this.getColumn(this.vectorColumn),C=e.mode==="phrase"?sql`phraseto_tsquery(${this.vectorConfig}, ${e.query})`:e.mode==="all"?sql`plainto_tsquery(${this.vectorConfig}, ${e.query})`:sql`to_tsquery(${this.vectorConfig}, ${e.query.split(/\s+/).join(" | ")})`;t.push(sql`${w} @@ ${C}`);}else {let w=a.map(C=>{try{let Qe=this.getColumn(C);return sql`LOWER(CAST(${Qe} AS TEXT)) LIKE LOWER(${`%${e.query}%`})`}catch{return}}).filter(C=>C!==void 0);w.length>0&&(e.mode==="all"?t.push(and(...w)):t.push(or(...w)));}let i=t.length>0?and(...t):void 0,u=await this.getDb().select({count:sql`count(*)`}).from(n).where(i),d=Number(u[0]?.count)||0,c=this.getDb().select().from(n).where(i);if(o.options.order_by){let w=this.getColumn(o.options.order_by),C=o.options.order_by_direction==="desc"?desc:asc;c=c.orderBy(C(w));}let g=o.options.page||1,p=o.options.per_page||this.defaultPerPage;c=c.limit(p).offset((g-1)*p);let b=await c,y=K(b,e,s),z={relations:o.options.include||[]},R=y.map(w=>w.item),H=await O(this.getDb(),R,this._meta,z);return {items:y.map((w,C)=>({...w,item:H[C]})),totalCount:d}}},Ie=class extends T{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async list(e){let o=this.getTable(),n=[],t=this.getSoftDeleteConfig();if(t.enabled){let y=this.getColumn(t.field);e.options.onlyDeleted?n.push(isNotNull(y)):e.options.withDeleted||n.push(isNull(y));}for(let y of e.filters){let z=x(o,y);z&&n.push(z);}if(e.options.search&&this.searchFields.length>0){let y=this.searchFields.map(z=>{let R=this.getColumn(z);return sql`LOWER(${R}) LIKE LOWER(${`%${e.options.search}%`})`});n.push(or(...y));}let r=n.length>0?and(...n):void 0,s=await this.getDb().select({count:sql`count(*)`}).from(o).where(r),a=Number(s[0]?.count)||0,i=this.getDb().select().from(o).where(r);if(e.options.order_by){let y=this.getColumn(e.options.order_by),z=e.options.order_by_direction==="desc"?desc:asc;i=i.orderBy(z(y));}let u=e.options.page||1,d=e.options.per_page||this.defaultPerPage;i=i.limit(d).offset((u-1)*d);let c=await i,g={relations:e.options.include||[]},p=await O(this.getDb(),c,this._meta,g),b=Math.ceil(a/d);return {result:p,result_info:{page:u,per_page:d,total_count:a,total_pages:b,has_next_page:u<b,has_prev_page:u>1}}}},Pe=class extends U$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async findExisting(e){let o=this.getTable(),n=this.getUpsertKeys(),t=this.getSoftDeleteConfig(),r=[];for(let a of n){let i=e[a];i!==void 0&&r.push(eq(this.getColumn(a),i));}return t.enabled&&r.push(isNull(this.getColumn(t.field))),r.length===0?null:(await this.getDb().select().from(o).where(and(...r)).limit(1))[0]||null}async create(e){let o=this.getTable(),n=this._meta.model.primaryKeys[0],t={...e,[n]:e[n]||crypto.randomUUID()};return (await this.getDb().insert(o).values(t).returning())[0]}async update(e,o){let n=this.getTable(),t=this._meta.model.primaryKeys[0],r=e[t];return (await this.getDb().update(n).set(o).where(eq(this.getColumn(t),r)).returning())[0]}};function Ht(l,e){return {Create:class extends S{_meta=e;db=l},Read:class extends _{_meta=e;db=l},Update:class extends I{_meta=e;db=l},Delete:class extends P{_meta=e;db=l},List:class extends U{_meta=e;db=l},Restore:class extends B{_meta=e;db=l},Upsert:class extends q{_meta=e;db=l},BatchCreate:class extends Q{_meta=e;db=l},BatchUpdate:class extends N{_meta=e;db=l},BatchDelete:class extends F{_meta=e;db=l},BatchRestore:class extends ${_meta=e;db=l},BatchUpsert:class extends W{_meta=e;db=l}}}var Jt={CreateEndpoint:S,ListEndpoint:U,ReadEndpoint:_,UpdateEndpoint:I,DeleteEndpoint:P};var X=null,Be=false,V=null;async function G(){if(Be){if(V)throw V;return X}Be=true;try{return X=await import('drizzle-zod'),X}catch{throw V=new Error("drizzle-zod is not installed. Please install it: npm install drizzle-zod"),V}}async function at(l,e){return (await G()).createSelectSchema(l,e)}async function it(l,e){return (await G()).createInsertSchema(l,e)}async function lt(l,e){let o=await G();return o.createUpdateSchema?o.createUpdateSchema(l,e):o.createInsertSchema(l,e).partial()}async function dt(l,e){let o=await G(),n=e?.coerceDates!==false,t=n?gt(l):new Set,r=o.createSelectSchema(l,e?.selectRefine),s=o.createInsertSchema(l,e?.insertRefine),a;return o.createUpdateSchema?a=o.createUpdateSchema(l,e?.updateRefine):a=o.createInsertSchema(l,e?.updateRefine).partial(),n&&t.size>0&&(s=Ze(s,t),a=Ze(a,t)),{select:r,insert:s,update:a}}function ct(){return X!==null}var ut=z.preprocess(l=>{if(l instanceof Date)return l;if(typeof l=="string"){let e=new Date(l);if(!isNaN(e.getTime()))return e}return l},z.date()),pt=z.preprocess(l=>{if(l==null)return null;if(l instanceof Date)return l;if(typeof l=="string"){let e=new Date(l);if(!isNaN(e.getTime()))return e}return l},z.date().nullable());function gt(l){let e=new Set,o=l;for(let[n,t]of Object.entries(o)){if(n==="_"||n==="$inferInsert"||n==="$inferSelect")continue;let r=t;if(!r||typeof r!="object")continue;let s=String(r.dataType??"").toLowerCase(),a=String(r.columnType??"").toLowerCase(),i=r.config,u=String(i?.dataType??"").toLowerCase();(s.includes("timestamp")||s.includes("date")||s.includes("datetime")||a.includes("pgtimestamp")||a.includes("pgdate")||a.includes("mysqltimestamp")||a.includes("mysqldate")||a.includes("sqlitetimestamp")||u.includes("timestamp")||u.includes("date"))&&e.add(n);}return e}function Ze(l,e){if(e.size===0)return l;let o=l.shape,n={};for(let[t,r]of Object.entries(o))if(e.has(t)){let s=r.isOptional?.()??false,a=r.isNullable?.()??false,i=ut;(a||s)&&(i=pt),s&&(i=i.optional()),n[t]=i;}else n[t]=r;return z.object(n)}export{Jt as DrizzleAdapters,Se as DrizzleAggregateEndpoint,Q as DrizzleBatchCreateEndpoint,F as DrizzleBatchDeleteEndpoint,$ as DrizzleBatchRestoreEndpoint,N as DrizzleBatchUpdateEndpoint,W as DrizzleBatchUpsertEndpoint,S as DrizzleCreateEndpoint,P as DrizzleDeleteEndpoint,Ie as DrizzleExportEndpoint,Pe as DrizzleImportEndpoint,U as DrizzleListEndpoint,_ as DrizzleReadEndpoint,B as DrizzleRestoreEndpoint,_e as DrizzleSearchEndpoint,I as DrizzleUpdateEndpoint,q as DrizzleUpsertEndpoint,ve as DrizzleVersionCompareEndpoint,ke as DrizzleVersionHistoryEndpoint,Oe as DrizzleVersionReadEndpoint,je as DrizzleVersionRollbackEndpoint,O as batchLoadDrizzleRelations,x as buildWhereCondition,L as cast,Ht as createDrizzleCrud,dt as createDrizzleSchemas,it as createInsertSchema,at as createSelectSchema,lt as createUpdateSchema,m as getColumn,f as getTable,ct as isDrizzleZodAvailable,Te as loadDrizzleRelation,ee as loadDrizzleRelations};
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { Env } from 'hono';
|
|
2
|
-
import { a as CreateEndpoint, M as ModelObject, D as DeleteEndpoint, L as ListEndpoint, R as ReadEndpoint, b as RestoreEndpoint, U as UpdateEndpoint, B as BatchCreateEndpoint, c as BatchDeleteEndpoint, d as BatchRestoreEndpoint, e as BatchUpdateEndpoint, f as BatchUpdateItem, g as BatchUpsertEndpoint, A as AggregateEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint, h as UpsertEndpoint, V as VersionCompareEndpoint, i as VersionHistoryEndpoint, j as VersionReadEndpoint, k as VersionRollbackEndpoint } from '../../import-
|
|
3
|
-
import { M as MetaInput, f as RelationConfig, L as ListFilters, P as PaginatedResult, I as IncludeOptions, N as NestedUpdateInput, g as NestedWriteResult, h as AggregateOptions, i as AggregateResult, S as SearchOptions, j as SearchResult } from '../../types-
|
|
4
|
-
import { B as BulkPatchEndpoint, C as CloneEndpoint } from '../../bulk-patch-
|
|
2
|
+
import { a as CreateEndpoint, M as ModelObject, D as DeleteEndpoint, L as ListEndpoint, R as ReadEndpoint, b as RestoreEndpoint, U as UpdateEndpoint, B as BatchCreateEndpoint, c as BatchDeleteEndpoint, d as BatchRestoreEndpoint, e as BatchUpdateEndpoint, f as BatchUpdateItem, g as BatchUpsertEndpoint, A as AggregateEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint, h as UpsertEndpoint, V as VersionCompareEndpoint, i as VersionHistoryEndpoint, j as VersionReadEndpoint, k as VersionRollbackEndpoint } from '../../import-JN0uu97B.js';
|
|
3
|
+
import { M as MetaInput, f as RelationConfig, L as ListFilters, P as PaginatedResult, I as IncludeOptions, N as NestedUpdateInput, g as NestedWriteResult, h as AggregateOptions, i as AggregateResult, S as SearchOptions, j as SearchResult } from '../../types-tpG0M7Va.js';
|
|
4
|
+
import { B as BulkPatchEndpoint, C as CloneEndpoint } from '../../bulk-patch-C9PIpw4R.js';
|
|
5
5
|
import 'zod';
|
|
6
|
-
import '../../route-
|
|
6
|
+
import '../../route-AzM3iPZP.js';
|
|
7
7
|
import 'hono/utils/http-status';
|
|
8
8
|
import '../../audit/index.js';
|
|
9
9
|
import '../../registry-PNJjvSvm.js';
|
|
@@ -11,7 +11,7 @@ import '../../types-B5wq2iKZ.js';
|
|
|
11
11
|
import '../../types-BAcN7U0B.js';
|
|
12
12
|
import '@hono/zod-openapi';
|
|
13
13
|
import '../../versioning/index.js';
|
|
14
|
-
import '../../types-
|
|
14
|
+
import '../../types-rJSyOxkJ.js';
|
|
15
15
|
|
|
16
16
|
/**
|
|
17
17
|
* Module-level in-memory storage.
|
|
@@ -38,11 +38,22 @@ declare function clearStorage(): void;
|
|
|
38
38
|
*/
|
|
39
39
|
declare function getStorage<T>(tableName: string): Map<string, T>;
|
|
40
40
|
|
|
41
|
+
/**
|
|
42
|
+
* Sentinel placed on `HookContext.db.tx` for memory-adapter writes. The
|
|
43
|
+
* memory adapter has no real transaction machinery, so throwing inside an
|
|
44
|
+
* `after*` hook does NOT roll back the parent write — the sentinel makes
|
|
45
|
+
* that explicit so downstream code can feature-detect.
|
|
46
|
+
*/
|
|
47
|
+
declare const MEMORY_NOOP_TX: Readonly<{
|
|
48
|
+
__memoryNoopTx: true;
|
|
49
|
+
rolledBack: false;
|
|
50
|
+
}>;
|
|
41
51
|
/**
|
|
42
52
|
* Memory-based Create endpoint for testing.
|
|
43
53
|
* Supports nested writes for creating related records.
|
|
44
54
|
*/
|
|
45
55
|
declare abstract class MemoryCreateEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends CreateEndpoint<E, M> {
|
|
56
|
+
protected _tx: unknown;
|
|
46
57
|
/**
|
|
47
58
|
* Generates a unique ID for new records.
|
|
48
59
|
* Override to customize ID generation.
|
|
@@ -67,6 +78,7 @@ declare abstract class MemoryReadEndpoint<E extends Env = Env, M extends MetaInp
|
|
|
67
78
|
* Supports nested writes for creating/updating/deleting related records.
|
|
68
79
|
*/
|
|
69
80
|
declare abstract class MemoryUpdateEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends UpdateEndpoint<E, M> {
|
|
81
|
+
protected _tx: unknown;
|
|
70
82
|
/**
|
|
71
83
|
* Finds an existing record for audit logging (before update).
|
|
72
84
|
*/
|
|
@@ -83,6 +95,7 @@ declare abstract class MemoryUpdateEndpoint<E extends Env = Env, M extends MetaI
|
|
|
83
95
|
* Supports cascade operations (cascade, setNull, restrict).
|
|
84
96
|
*/
|
|
85
97
|
declare abstract class MemoryDeleteEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends DeleteEndpoint<E, M> {
|
|
98
|
+
protected _tx: unknown;
|
|
86
99
|
/**
|
|
87
100
|
* Finds a record without deleting it.
|
|
88
101
|
*/
|
|
@@ -355,4 +368,4 @@ declare abstract class MemoryBulkPatchEndpoint<E extends Env = Env, M extends Me
|
|
|
355
368
|
private getFilteredItems;
|
|
356
369
|
}
|
|
357
370
|
|
|
358
|
-
export { MemoryAggregateEndpoint, MemoryBatchCreateEndpoint, MemoryBatchDeleteEndpoint, MemoryBatchRestoreEndpoint, MemoryBatchUpdateEndpoint, MemoryBatchUpsertEndpoint, MemoryBulkPatchEndpoint, MemoryCloneEndpoint, MemoryCreateEndpoint, MemoryDeleteEndpoint, MemoryExportEndpoint, MemoryImportEndpoint, MemoryListEndpoint, MemoryReadEndpoint, MemoryRestoreEndpoint, MemorySearchEndpoint, MemoryUpdateEndpoint, MemoryUpsertEndpoint, MemoryVersionCompareEndpoint, MemoryVersionHistoryEndpoint, MemoryVersionReadEndpoint, MemoryVersionRollbackEndpoint, clearStorage, getStorage, getStore, storage };
|
|
371
|
+
export { MEMORY_NOOP_TX, MemoryAggregateEndpoint, MemoryBatchCreateEndpoint, MemoryBatchDeleteEndpoint, MemoryBatchRestoreEndpoint, MemoryBatchUpdateEndpoint, MemoryBatchUpsertEndpoint, MemoryBulkPatchEndpoint, MemoryCloneEndpoint, MemoryCreateEndpoint, MemoryDeleteEndpoint, MemoryExportEndpoint, MemoryImportEndpoint, MemoryListEndpoint, MemoryReadEndpoint, MemoryRestoreEndpoint, MemorySearchEndpoint, MemoryUpdateEndpoint, MemoryUpsertEndpoint, MemoryVersionCompareEndpoint, MemoryVersionHistoryEndpoint, MemoryVersionReadEndpoint, MemoryVersionRollbackEndpoint, clearStorage, getStorage, getStore, storage };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{
|
|
1
|
+
export{g as MEMORY_NOOP_TX,y as MemoryAggregateEndpoint,n as MemoryBatchCreateEndpoint,p as MemoryBatchDeleteEndpoint,q as MemoryBatchRestoreEndpoint,o as MemoryBatchUpdateEndpoint,r as MemoryBatchUpsertEndpoint,C as MemoryBulkPatchEndpoint,s as MemoryCloneEndpoint,h as MemoryCreateEndpoint,k as MemoryDeleteEndpoint,A as MemoryExportEndpoint,B as MemoryImportEndpoint,l as MemoryListEndpoint,i as MemoryReadEndpoint,m as MemoryRestoreEndpoint,z as MemorySearchEndpoint,j as MemoryUpdateEndpoint,t as MemoryUpsertEndpoint,w as MemoryVersionCompareEndpoint,u as MemoryVersionHistoryEndpoint,v as MemoryVersionReadEndpoint,x as MemoryVersionRollbackEndpoint,e as clearStorage,f as getStorage,d as getStore,c as storage}from'../../chunk-HCFP7RM6.js';import'../../chunk-2I6G2Q6U.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-3TIIYAKB.js';import'../../chunk-7NM6MBRL.js';import'../../chunk-ANWSQPCQ.js';import'../../chunk-Z575OBLV.js';import'../../chunk-FC56WWPB.js';import'../../chunk-GBQQ3YQX.js';import'../../chunk-QRXEQTNE.js';import'../../chunk-QXFY6NYI.js';import'../../chunk-DMGP7QDL.js';import'../../chunk-MDHMZPXK.js';import'../../chunk-VJRDAVID.js';
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { Env } from 'hono';
|
|
2
|
-
import { a as CreateEndpoint, M as ModelObject, D as DeleteEndpoint, L as ListEndpoint, R as ReadEndpoint, U as UpdateEndpoint, B as BatchCreateEndpoint, c as BatchDeleteEndpoint, d as BatchRestoreEndpoint, e as BatchUpdateEndpoint, f as BatchUpdateItem, g as BatchUpsertEndpoint, b as RestoreEndpoint, A as AggregateEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint, h as UpsertEndpoint, V as VersionCompareEndpoint, i as VersionHistoryEndpoint, j as VersionReadEndpoint, k as VersionRollbackEndpoint } from '../../import-
|
|
3
|
-
import { M as MetaInput, L as ListFilters, P as PaginatedResult, I as IncludeOptions, h as AggregateOptions, i as AggregateResult, k as AggregateField, S as SearchOptions, j as SearchResult } from '../../types-
|
|
2
|
+
import { a as CreateEndpoint, M as ModelObject, D as DeleteEndpoint, L as ListEndpoint, R as ReadEndpoint, U as UpdateEndpoint, B as BatchCreateEndpoint, c as BatchDeleteEndpoint, d as BatchRestoreEndpoint, e as BatchUpdateEndpoint, f as BatchUpdateItem, g as BatchUpsertEndpoint, b as RestoreEndpoint, A as AggregateEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint, h as UpsertEndpoint, V as VersionCompareEndpoint, i as VersionHistoryEndpoint, j as VersionReadEndpoint, k as VersionRollbackEndpoint } from '../../import-JN0uu97B.js';
|
|
3
|
+
import { M as MetaInput, L as ListFilters, P as PaginatedResult, I as IncludeOptions, h as AggregateOptions, i as AggregateResult, k as AggregateField, S as SearchOptions, j as SearchResult } from '../../types-tpG0M7Va.js';
|
|
4
4
|
import 'zod';
|
|
5
|
-
import '../../route-
|
|
5
|
+
import '../../route-AzM3iPZP.js';
|
|
6
6
|
import 'hono/utils/http-status';
|
|
7
7
|
import '../../audit/index.js';
|
|
8
8
|
import '../../registry-PNJjvSvm.js';
|
|
@@ -10,7 +10,7 @@ import '../../types-B5wq2iKZ.js';
|
|
|
10
10
|
import '../../types-BAcN7U0B.js';
|
|
11
11
|
import '@hono/zod-openapi';
|
|
12
12
|
import '../../versioning/index.js';
|
|
13
|
-
import '../../types-
|
|
13
|
+
import '../../types-rJSyOxkJ.js';
|
|
14
14
|
|
|
15
15
|
/**
|
|
16
16
|
* Prisma adapter helpers: types, model resolution, relation loading, query utils.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {k as k$1,l,m,n,o,p,r,s,t,u,v as v$1,J,K as K$1,T,U,q,w as w$1,x as x$1,y,z,A,B}from'../../chunk-Q4FF5JVS.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-W4FHI5YI.js';import'../../chunk-HAUN4LQO.js';import'../../chunk-NIWM7GOK.js';import'../../chunk-RFT77JBK.js';import'../../chunk-FC56WWPB.js';import'../../chunk-GBQQ3YQX.js';import'../../chunk-QRXEQTNE.js';import'../../chunk-QXFY6NYI.js';import'../../chunk-DMGP7QDL.js';import'../../chunk-MDHMZPXK.js';import'../../chunk-VJRDAVID.js';var v,_;async function _e(){if(v)return v;try{return v=(await import('pluralize')).default,v}catch{throw new Error('The "pluralize" package is required. Install it with: npm install pluralize')}}async function je(){if(_)return _;try{return _=(await import('fastest-levenshtein')).distance,_}catch{throw new Error('The "fastest-levenshtein" package is required. Install it with: npm install fastest-levenshtein')}}async function C(a){return (await _e()).singular(a)}async function I(a,t){return (await je())(a,t)}function oe(a,t){return a[t]}function Ee(a){return typeof a=="object"&&a!==null&&"create"in a&&typeof a.create=="function"}function h(a,t){let e=oe(a,t);return Ee(e)?e:void 0}function F(a){if(typeof a.$transaction!="function")throw new Error("Prisma client does not support $transaction");return a.$transaction.bind(a)}function k(a){if(typeof a=="string"){if(/^-?\d+$/.test(a))return parseInt(a,10);if(/^-?\d+\.\d+$/.test(a))return parseFloat(a);if(a==="true")return true;if(a==="false")return false}return a}function K(a){let t={};for(let e of a){let o=k(e.value);switch(e.operator){case "eq":t[e.field]=o;break;case "ne":t[e.field]={not:o};break;case "gt":t[e.field]={gt:o};break;case "gte":t[e.field]={gte:o};break;case "lt":t[e.field]={lt:o};break;case "lte":t[e.field]={lte:o};break;case "in":{let n=Array.isArray(e.value)?e.value:[e.value];t[e.field]={in:n.map(k)};break}case "nin":{let n=Array.isArray(e.value)?e.value:[e.value];t[e.field]={notIn:n.map(k)};break}case "like":t[e.field]={contains:String(e.value).replace(/%/g,"")};break;case "ilike":t[e.field]={contains:String(e.value).replace(/%/g,""),mode:"insensitive"};break;case "null":t[e.field]=e.value?null:{not:null};break;case "between":{let[n,r]=e.value;t[e.field]={gte:k(n),lte:k(r)};break}}}return t}var Ce=500,b=new Map;function ne(a,t){if(b.size>=Ce){let e=b.keys().next().value;e!==void 0&&b.delete(e);}b.set(a,t);}var D=new Map;function re(a,t){D.set(a.toLowerCase(),t),b.delete(a);}function Ie(a){for(let[t,e]of Object.entries(a))re(t,e);}function Fe(){D.clear(),b.clear();}async function w(a){let t=b.get(a);if(t)return t;let e=D.get(a.toLowerCase());if(e)return ne(a,e),e;let o=a.replace(/[-_](.)/g,(n,r)=>r.toUpperCase()).replace(/^./,n=>n.toLowerCase());return o=await C(o),ne(a,o),o}function Ke(a){let t=[];for(let e of Object.keys(a)){if(e.startsWith("$")||e.startsWith("_"))continue;let o=oe(a,e);o&&typeof o=="object"&&"create"in o&&t.push(e);}return t}async function De(a,t,e=3){if(t.length===0)return [];let o=a.toLowerCase();return (await Promise.all(t.map(async r=>({name:r,distance:await I(o,r.toLowerCase())})))).filter(r=>r.distance<=Math.max(3,a.length/2)).sort((r,s)=>r.distance-s.distance).slice(0,e).map(r=>r.name)}async function f(a,t){let e=await w(t),o=h(a,e);if(!o){let n=Ke(a),r=await De(e,n),s=`Model '${e}' not found in Prisma client. Table name: '${t}'. `;throw r.length>0&&(s+=`Did you mean: ${r.map(i=>`'${i}'`).join(", ")}? `),n.length>0&&n.length<=10&&(s+=`Available models: ${n.join(", ")}. `),s+=`You can register a custom mapping with: registerPrismaModelMapping('${t}', 'yourModelName')`,new Error(s)}return o}async function Ae(a,t,e,o){let n=await w(o.model),r=h(a,n);if(!r)return t;switch(o.type){case "hasOne":{let s=o.localKey||"id",i=t[s];if(i==null)return {...t,[e]:null};let l=await r.findFirst({where:{[o.foreignKey]:i}});return {...t,[e]:l||null}}case "hasMany":{let s=o.localKey||"id",i=t[s];if(i==null)return {...t,[e]:[]};let l=await r.findMany({where:{[o.foreignKey]:i}});return {...t,[e]:l}}case "belongsTo":{let s=t[o.foreignKey];if(s==null)return {...t,[e]:null};let i=o.localKey||"id",l=await r.findFirst({where:{[i]:s}});return {...t,[e]:l||null}}default:return t}}async function se(a,t,e,o){if(!o?.relations?.length||!e.model.relations)return t;let n={...t};for(let r of o.relations){let s=e.model.relations[r];s&&(n=await Ae(a,n,r,s));}return n}async function x(a,t,e,o){if(!t.length||!o?.relations?.length||!e.model.relations)return t;let n=t.map(r=>({...r}));for(let r of o.relations){let s=e.model.relations[r];if(!s)continue;let i=await w(s.model),l=h(a,i);if(l)switch(s.type){case "hasOne":case "hasMany":{let u=s.localKey||"id",c=[...new Set(n.map(m=>m[u]).filter(m=>m!=null))];if(c.length===0){n=n.map(m=>({...m,[r]:s.type==="hasMany"?[]:null}));continue}let d=await l.findMany({where:{[s.foreignKey]:{in:c}}}),p=new Map;for(let m of d){let g=m[s.foreignKey];p.has(g)||p.set(g,[]),p.get(g).push(m);}n=n.map(m=>{let g=m[u],M=p.get(g)||[];return {...m,[r]:s.type==="hasMany"?M:M[0]||null}});break}case "belongsTo":{let u=s.localKey||"id",c=[...new Set(n.map(m=>m[s.foreignKey]).filter(m=>m!=null))];if(c.length===0){n=n.map(m=>({...m,[r]:null}));continue}let d=await l.findMany({where:{[u]:{in:c}}}),p=new Map;for(let m of d){let g=m[u];p.set(g,m);}n=n.map(m=>{let g=m[s.foreignKey];return {...m,[r]:p.get(g)||null}});break}}}return n}async function j(a){let{model:t,filters:e,searchFields:o=[],softDeleteConfig:n,defaultPerPage:r=20,additionalWhere:s={}}=a,i={...K(e.filters),...s};if(n?.enabled){let{withDeleted:g,onlyDeleted:M}=e.options;M?i[n.field]={not:null}:g||(i[n.field]=null);}if(e.options.search&&o.length>0){let g=o.map(M=>({[M]:{contains:e.options.search,mode:"insensitive"}}));i={...i,OR:g};}let l=await t.count({where:i}),u;e.options.order_by&&(u={[e.options.order_by]:e.options.order_by_direction||"asc"});let c=e.options.page||1,d=e.options.per_page||r,p=await t.findMany({where:i,orderBy:u,skip:(c-1)*d,take:d}),m=Math.ceil(l/d);return {records:p,where:i,totalCount:l,page:c,perPage:d,totalPages:m}}function E(a,t){return {result:a,result_info:{page:t.page,per_page:t.perPage,total_count:t.totalCount,total_pages:t.totalPages,has_next_page:t.page<t.totalPages,has_prev_page:t.page>1}}}var ae=class extends k$1{useTransaction=false;async getModel(){return f(this.prisma,this._meta.model.tableName)}async create(t){let e=await this.getModel(),o=this._meta.model.primaryKeys[0],n={...t,[o]:t[o]||crypto.randomUUID()};return await e.create({data:n})}},ie=class extends l{async getModel(){return f(this.prisma,this._meta.model.tableName)}async read(t,e,o){let n=await this.getModel(),r={[this.lookupField]:t,...e},s=await n.findFirst({where:r});return s?await se(this.prisma,s,this._meta,o):null}},le=class extends m{useTransaction=false;async getModel(){return f(this.prisma,this._meta.model.tableName)}async update(t,e,o){let n=await this.getModel(),r={[this.lookupField]:t,...o},s=await n.findFirst({where:r});if(!s)return null;let i=this._meta.model.primaryKeys[0];return await n.update({where:{[i]:s[i]},data:e})}},de=class extends n{useTransaction=false;async getModel(){return f(this.prisma,this._meta.model.tableName)}async findForDelete(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),r={[this.lookupField]:t,...e};return n.enabled&&(r[n.field]=null),await o.findFirst({where:r})}async delete(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),r={[this.lookupField]:t,...e};n.enabled&&(r[n.field]=null);let s=await o.findFirst({where:r});if(!s)return null;let i=this._meta.model.primaryKeys[0],l=s[i];return n.enabled?await o.update({where:{[i]:l},data:{[n.field]:new Date}}):await o.delete({where:{[i]:l}})}},ce=class extends o{async getModel(){return f(this.prisma,this._meta.model.tableName)}async list(t){let e=await j({model:await this.getModel(),filters:t,searchFields:this.searchFields,softDeleteConfig:this.getSoftDeleteConfig(),defaultPerPage:this.defaultPerPage}),o={relations:t.options.include||[]},n=await x(this.prisma,e.records,this._meta,o);return E(n,e)}};var ue=class extends p{useTransaction=false;async getModel(){return f(this.prisma,this._meta.model.tableName)}async restore(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),r={[this.lookupField]:t,[n.field]:{not:null},...e},s=await o.findFirst({where:r});if(!s)return null;let i=this._meta.model.primaryKeys[0];return await o.update({where:{[i]:s[i]},data:{[n.field]:null}})}},me=class extends r{async getModel(){return f(this.prisma,this._meta.model.tableName)}async batchCreate(t){let e=this._meta.model.primaryKeys[0],o=t.map(r=>({...r,[e]:r[e]||crypto.randomUUID()})),n=[];return await F(this.prisma)(async r=>{let s=h(r,await w(this._meta.model.tableName));if(!s)throw new Error(`Model '${this._meta.model.tableName}' not found in Prisma transaction client`);for(let i of o){let l=await s.create({data:i});n.push(l);}}),n}},ge=class extends s{async getModel(){return f(this.prisma,this._meta.model.tableName)}async batchUpdate(t){let e=await this.getModel(),o=this.getSoftDeleteConfig(),n=this._meta.model.primaryKeys[0],r=[],s=[],i=t.map(d=>d.id),l={[this.lookupField]:{in:i}};o.enabled&&(l[o.field]=null);let u=await e.findMany({where:l}),c=new Map;for(let d of u){let p=d[this.lookupField];c.set(p,d);}for(let d of t){let p=c.get(d.id);if(!p){s.push(d.id);continue}let m=await e.update({where:{[n]:p[n]},data:d.data});r.push(m);}return {updated:r,notFound:s}}},pe=class extends t{async getModel(){return f(this.prisma,this._meta.model.tableName)}async batchDelete(t){let e=await this.getModel(),o=this.getSoftDeleteConfig(),n=this._meta.model.primaryKeys[0],r=[],s=[],i={[this.lookupField]:{in:t}};o.enabled&&(i[o.field]=null);let l=await e.findMany({where:i}),u=new Map;for(let c of l){let d=c[this.lookupField];u.set(d,c);}for(let c of t)u.has(c)||s.push(c);for(let c of t){let d=u.get(c);if(d)if(o.enabled){let p=await e.update({where:{[n]:d[n]},data:{[o.field]:new Date}});r.push(p);}else {let p=await e.delete({where:{[n]:d[n]}});r.push(p);}}return {deleted:r,notFound:s}}},fe=class extends u{async getModel(){return f(this.prisma,this._meta.model.tableName)}async batchRestore(t){let e=await this.getModel(),o=this.getSoftDeleteConfig(),n=this._meta.model.primaryKeys[0],r=[],s=[],i={[this.lookupField]:{in:t},[o.field]:{not:null}},l=await e.findMany({where:i}),u=new Map;for(let c of l){let d=c[this.lookupField];u.set(d,c);}for(let c of t){let d=u.get(c);if(!d){s.push(c);continue}let p=await e.update({where:{[n]:d[n]},data:{[o.field]:null}});r.push(p);}return {restored:r,notFound:s}}},Me=class extends v$1{useTransaction=true;async getModel(){return f(this.prisma,this._meta.model.tableName)}async findExisting(t){let e=await this.getModel(),o=this.getUpsertKeys(),n={};for(let s of o){let i=t[s];i!==void 0&&(n[s]=i);}return Object.keys(n).length===0?null:await e.findFirst({where:n})||null}async create(t){let e=await this.getModel(),o=this._meta.model.primaryKeys[0],n={...t,[o]:t[o]||crypto.randomUUID()};return await e.create({data:n})}async update(t,e){let o=await this.getModel(),n=this._meta.model.primaryKeys[0];return await o.update({where:{[n]:t[n]},data:e})}async nativeBatchUpsert(t,e){if(t.length===0)return {items:[],createdCount:0,updatedCount:0,totalCount:0};let o=this.getUpsertKeys(),n=this._meta.model.primaryKeys[0],r=async l=>{let u=h(l,await w(this._meta.model.tableName));if(!u)throw new Error(`Model '${this._meta.model.tableName}' not found in Prisma client`);let c=[],d=[];for(let p=0;p<t.length;p++){let m=t[p];try{let g={};for(let y of o){let O=m[y];O!==void 0&&(g[y]=O);}let M={...m,[n]:m[n]||crypto.randomUUID()},P={};for(let[y,O]of Object.entries(m))!o.includes(y)&&y!==n&&(this.createOnlyFields?.includes(y)||(P[y]=O));let ve=await u.upsert({where:g,create:M,update:Object.keys(P).length>0?P:{}});c.push({data:ve,created:!1,index:p});}catch(g){if(this.continueOnError)d.push({index:p,error:g instanceof Error?g.message:String(g)});else throw g}}return {results:c,errors:d}},s;this.useTransaction?s=await F(this.prisma)(r):s=await r(this.prisma);let i={items:s.results,createdCount:0,updatedCount:s.results.length,totalCount:s.results.length};return s.errors.length>0&&(i.errors=s.errors),i}};var he=class extends J{async getModel(){return f(this.prisma,this._meta.model.tableName)}buildSearchWhere(t,e){let o=K(e.filters),n=this.getSoftDeleteConfig();if(n.enabled){let{withDeleted:l,onlyDeleted:u}=e.options;u?o[n.field]={not:null}:l||(o[n.field]=null);}let r=this.getSearchableFields(),i=(t.fields||Object.keys(r)).map(l=>({[l]:{contains:t.query,mode:"insensitive"}}));return i.length>0&&(t.mode==="all"?o={...o,AND:i}:o={...o,OR:i}),o}async search(t,e){let o=await this.getModel(),n=this.buildSearchWhere(t,e),r=await o.count({where:n}),s=e.options.order_by?{[e.options.order_by]:e.options.order_by_direction||"asc"}:void 0,i=e.options.page||1,l=e.options.per_page||this.defaultPerPage,u=await o.findMany({where:n,orderBy:s,skip:(i-1)*l,take:l}),c=K$1(u,t,this.getSearchableFields()),d={relations:e.options.include||[]},p=c.map(M=>M.item),m=await x(this.prisma,p,this._meta,d);return {items:c.map((M,P)=>({...M,item:m[P]})),totalCount:r}}},we=class extends T{async getModel(){return f(this.prisma,this._meta.model.tableName)}async list(t){let e=await j({model:await this.getModel(),filters:t,searchFields:this.searchFields,softDeleteConfig:this.getSoftDeleteConfig(),defaultPerPage:this.defaultPerPage}),o={relations:t.options.include||[]},n=await x(this.prisma,e.records,this._meta,o);return E(n,e)}},ye=class extends U{async getModel(){return f(this.prisma,this._meta.model.tableName)}async findExisting(t){let e=await this.getModel(),o=this.getUpsertKeys(),n={};for(let s of o){let i=t[s];i!==void 0&&(n[s]=i);}return Object.keys(n).length===0?null:await e.findFirst({where:n})||null}async create(t){let e=await this.getModel(),o=this._meta.model.primaryKeys[0],n={...t,[o]:t[o]||crypto.randomUUID()};return await e.create({data:n})}async update(t,e){let o=await this.getModel(),n=this._meta.model.primaryKeys[0];return await o.update({where:{[n]:t[n]},data:e})}},be=class extends q{useTransaction=false;async getModel(){return f(this.prisma,this._meta.model.tableName)}async findExisting(t){let e=await this.getModel(),o=this.getUpsertKeys(),n={};for(let s of o){let i=t[s];i!==void 0&&(n[s]=i);}return Object.keys(n).length===0?null:await e.findFirst({where:n})||null}async create(t){let e=await this.getModel(),o=this._meta.model.primaryKeys[0],n={...t,[o]:t[o]||crypto.randomUUID()};return await e.create({data:n})}async update(t,e){let o=await this.getModel(),n=this._meta.model.primaryKeys[0];return await o.update({where:{[n]:t[n]},data:e})}async nativeUpsert(t,e){let o=await this.getModel(),n=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s={};for(let c of n){let d=t[c];d!==void 0&&(s[c]=d);}let i={...t,[r]:t[r]||crypto.randomUUID()},l={};for(let[c,d]of Object.entries(t))!n.includes(c)&&c!==r&&(this.createOnlyFields?.includes(c)||(l[c]=d));return {data:await o.upsert({where:s,create:i,update:Object.keys(l).length>0?l:{}}),created:false}}},Pe=class extends w$1{async getModel(){return f(this.prisma,this._meta.model.tableName)}async recordExists(t){return await(await this.getModel()).count({where:{[this.lookupField]:t}})>0}},ke=class extends x$1{},xe=class extends y{},Oe=class extends z{async getModel(){return f(this.prisma,this._meta.model.tableName)}async rollback(t,e,o){let n=await this.getModel(),r=this.getVersioningConfig().field,s=this._meta.model.primaryKeys[0],i=await n.findFirst({where:{[this.lookupField]:t}});if(!i)throw new Error(`Record not found: ${t}`);return await n.update({where:{[s]:i[s]},data:{...e,[r]:o}})}},Re=class extends A{useNativeAggregation=true;async getModel(){return f(this.prisma,this._meta.model.tableName)}async buildAggregateWhere(t){let e={},o=this.getSoftDeleteConfig();if(o.enabled){let{query:n}=await this.getValidatedData();n?.withDeleted===true||n?.withDeleted==="true"||(e[o.field]=null);}if(t.filters)for(let[n,r]of Object.entries(t.filters))if(typeof r=="object"&&r!==null){let s={};for(let[i,l]of Object.entries(r))switch(i){case "eq":s.equals=l;break;case "ne":s.not=l;break;case "gt":s.gt=l;break;case "gte":s.gte=l;break;case "lt":s.lt=l;break;case "lte":s.lte=l;break;case "in":s.in=l;break;case "nin":s.notIn=l;break;default:s[i]=l;}e[n]=s;}else e[n]=r;return e}async aggregate(t){let e=await this.getModel(),o=await this.buildAggregateWhere(t);if(!this.useNativeAggregation||t.having){let n=await e.findMany({where:o});return B(n,t)}return t.groupBy?.length?this.aggregateWithGroupBy(e,o,t):this.aggregateSimple(e,o,t)}groupAggregationsByOperation(t){let e={sum:[],avg:[],min:[],max:[],count:[],countDistinct:[]};for(let o of t)switch(o.operation){case "sum":e.sum.push(o.field);break;case "avg":e.avg.push(o.field);break;case "min":e.min.push(o.field);break;case "max":e.max.push(o.field);break;case "count":e.count.push(o.field);break;case "countDistinct":e.countDistinct.push(o.field);break}return e}async aggregateSimple(t,e,o){let n={where:e},r={},s=this.groupAggregationsByOperation(o.aggregations);if(n._count=true,s.sum.length){n._sum={};for(let u of s.sum)n._sum[u]=true;}if(s.avg.length){n._avg={};for(let u of s.avg)n._avg[u]=true;}if(s.min.length){n._min={};for(let u of s.min)n._min[u]=true;}if(s.max.length){n._max={};for(let u of s.max)n._max[u]=true;}let i=await w(this._meta.model.tableName),l=h(this.prisma,i);if(!l)throw new Error(`Model '${i}' not found in Prisma client`);try{let u=await l.aggregate(n);if(u._count!==void 0&&(r.count=typeof u._count=="object"?u._count._all??0:u._count),u._sum&&s.sum.length)for(let c of s.sum){let d=c.charAt(0).toUpperCase()+c.slice(1);r[`sum${d}`]=u._sum[c]??0;}if(u._avg&&s.avg.length)for(let c of s.avg){let d=c.charAt(0).toUpperCase()+c.slice(1);r[`avg${d}`]=u._avg[c]??0;}if(u._min&&s.min.length)for(let c of s.min){let d=c.charAt(0).toUpperCase()+c.slice(1);r[`min${d}`]=u._min[c];}if(u._max&&s.max.length)for(let c of s.max){let d=c.charAt(0).toUpperCase()+c.slice(1);r[`max${d}`]=u._max[c];}return {values:r,groups:[]}}catch{let c=await t.findMany({where:e});return B(c,o)}}async aggregateWithGroupBy(t,e,o){let n={by:o.groupBy,where:e},r=this.groupAggregationsByOperation(o.aggregations);if(n._count=true,r.sum.length){n._sum={};for(let l of r.sum)n._sum[l]=true;}if(r.avg.length){n._avg={};for(let l of r.avg)n._avg[l]=true;}if(r.min.length){n._min={};for(let l of r.min)n._min[l]=true;}if(r.max.length){n._max={};for(let l of r.max)n._max[l]=true;}let s=await w(this._meta.model.tableName),i=h(this.prisma,s);if(!i)throw new Error(`Model '${s}' not found in Prisma client`);try{let u=(await i.groupBy(n)).map(d=>{let p={},m={};for(let g of o.groupBy)p[g]=d[g];if(m.count=typeof d._count=="object"?d._count._all??0:d._count??0,d._sum&&r.sum.length)for(let g of r.sum){let M=g.charAt(0).toUpperCase()+g.slice(1);m[`sum${M}`]=d._sum[g]??0;}if(d._avg&&r.avg.length)for(let g of r.avg){let M=g.charAt(0).toUpperCase()+g.slice(1);m[`avg${M}`]=d._avg[g]??0;}if(d._min&&r.min.length)for(let g of r.min){let M=g.charAt(0).toUpperCase()+g.slice(1);m[`min${M}`]=d._min[g];}if(d._max&&r.max.length)for(let g of r.max){let M=g.charAt(0).toUpperCase()+g.slice(1);m[`max${M}`]=d._max[g];}return {key:p,values:m}});return {values:{count:u.reduce((d,p)=>d+(p.values.count||0),0)},groups:u}}catch{let u=await t.findMany({where:e});return B(u,o)}}};export{Re as PrismaAggregateEndpoint,me as PrismaBatchCreateEndpoint,pe as PrismaBatchDeleteEndpoint,fe as PrismaBatchRestoreEndpoint,ge as PrismaBatchUpdateEndpoint,Me as PrismaBatchUpsertEndpoint,ae as PrismaCreateEndpoint,de as PrismaDeleteEndpoint,we as PrismaExportEndpoint,ye as PrismaImportEndpoint,ce as PrismaListEndpoint,ie as PrismaReadEndpoint,ue as PrismaRestoreEndpoint,he as PrismaSearchEndpoint,le as PrismaUpdateEndpoint,be as PrismaUpsertEndpoint,xe as PrismaVersionCompareEndpoint,Pe as PrismaVersionHistoryEndpoint,ke as PrismaVersionReadEndpoint,Oe as PrismaVersionRollbackEndpoint,Fe as clearPrismaModelMappings,re as registerPrismaModelMapping,Ie as registerPrismaModelMappings};
|
|
1
|
+
import {k as k$1,l,m,n,o,p,r,s,t,u,v as v$1,J,K as K$1,T,U,q,w as w$1,x as x$1,y,z,A,B}from'../../chunk-2I6G2Q6U.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-3TIIYAKB.js';import'../../chunk-7NM6MBRL.js';import'../../chunk-ANWSQPCQ.js';import'../../chunk-Z575OBLV.js';import'../../chunk-FC56WWPB.js';import'../../chunk-GBQQ3YQX.js';import'../../chunk-QRXEQTNE.js';import'../../chunk-QXFY6NYI.js';import'../../chunk-DMGP7QDL.js';import'../../chunk-MDHMZPXK.js';import'../../chunk-VJRDAVID.js';var v,_;async function _e(){if(v)return v;try{return v=(await import('pluralize')).default,v}catch{throw new Error('The "pluralize" package is required. Install it with: npm install pluralize')}}async function je(){if(_)return _;try{return _=(await import('fastest-levenshtein')).distance,_}catch{throw new Error('The "fastest-levenshtein" package is required. Install it with: npm install fastest-levenshtein')}}async function C(a){return (await _e()).singular(a)}async function I(a,t){return (await je())(a,t)}function oe(a,t){return a[t]}function Ee(a){return typeof a=="object"&&a!==null&&"create"in a&&typeof a.create=="function"}function h(a,t){let e=oe(a,t);return Ee(e)?e:void 0}function F(a){if(typeof a.$transaction!="function")throw new Error("Prisma client does not support $transaction");return a.$transaction.bind(a)}function k(a){if(typeof a=="string"){if(/^-?\d+$/.test(a))return parseInt(a,10);if(/^-?\d+\.\d+$/.test(a))return parseFloat(a);if(a==="true")return true;if(a==="false")return false}return a}function K(a){let t={};for(let e of a){let o=k(e.value);switch(e.operator){case "eq":t[e.field]=o;break;case "ne":t[e.field]={not:o};break;case "gt":t[e.field]={gt:o};break;case "gte":t[e.field]={gte:o};break;case "lt":t[e.field]={lt:o};break;case "lte":t[e.field]={lte:o};break;case "in":{let n=Array.isArray(e.value)?e.value:[e.value];t[e.field]={in:n.map(k)};break}case "nin":{let n=Array.isArray(e.value)?e.value:[e.value];t[e.field]={notIn:n.map(k)};break}case "like":t[e.field]={contains:String(e.value).replace(/%/g,"")};break;case "ilike":t[e.field]={contains:String(e.value).replace(/%/g,""),mode:"insensitive"};break;case "null":t[e.field]=e.value?null:{not:null};break;case "between":{let[n,r]=e.value;t[e.field]={gte:k(n),lte:k(r)};break}}}return t}var Ce=500,b=new Map;function ne(a,t){if(b.size>=Ce){let e=b.keys().next().value;e!==void 0&&b.delete(e);}b.set(a,t);}var D=new Map;function re(a,t){D.set(a.toLowerCase(),t),b.delete(a);}function Ie(a){for(let[t,e]of Object.entries(a))re(t,e);}function Fe(){D.clear(),b.clear();}async function w(a){let t=b.get(a);if(t)return t;let e=D.get(a.toLowerCase());if(e)return ne(a,e),e;let o=a.replace(/[-_](.)/g,(n,r)=>r.toUpperCase()).replace(/^./,n=>n.toLowerCase());return o=await C(o),ne(a,o),o}function Ke(a){let t=[];for(let e of Object.keys(a)){if(e.startsWith("$")||e.startsWith("_"))continue;let o=oe(a,e);o&&typeof o=="object"&&"create"in o&&t.push(e);}return t}async function De(a,t,e=3){if(t.length===0)return [];let o=a.toLowerCase();return (await Promise.all(t.map(async r=>({name:r,distance:await I(o,r.toLowerCase())})))).filter(r=>r.distance<=Math.max(3,a.length/2)).sort((r,s)=>r.distance-s.distance).slice(0,e).map(r=>r.name)}async function f(a,t){let e=await w(t),o=h(a,e);if(!o){let n=Ke(a),r=await De(e,n),s=`Model '${e}' not found in Prisma client. Table name: '${t}'. `;throw r.length>0&&(s+=`Did you mean: ${r.map(i=>`'${i}'`).join(", ")}? `),n.length>0&&n.length<=10&&(s+=`Available models: ${n.join(", ")}. `),s+=`You can register a custom mapping with: registerPrismaModelMapping('${t}', 'yourModelName')`,new Error(s)}return o}async function Ae(a,t,e,o){let n=await w(o.model),r=h(a,n);if(!r)return t;switch(o.type){case "hasOne":{let s=o.localKey||"id",i=t[s];if(i==null)return {...t,[e]:null};let l=await r.findFirst({where:{[o.foreignKey]:i}});return {...t,[e]:l||null}}case "hasMany":{let s=o.localKey||"id",i=t[s];if(i==null)return {...t,[e]:[]};let l=await r.findMany({where:{[o.foreignKey]:i}});return {...t,[e]:l}}case "belongsTo":{let s=t[o.foreignKey];if(s==null)return {...t,[e]:null};let i=o.localKey||"id",l=await r.findFirst({where:{[i]:s}});return {...t,[e]:l||null}}default:return t}}async function se(a,t,e,o){if(!o?.relations?.length||!e.model.relations)return t;let n={...t};for(let r of o.relations){let s=e.model.relations[r];s&&(n=await Ae(a,n,r,s));}return n}async function x(a,t,e,o){if(!t.length||!o?.relations?.length||!e.model.relations)return t;let n=t.map(r=>({...r}));for(let r of o.relations){let s=e.model.relations[r];if(!s)continue;let i=await w(s.model),l=h(a,i);if(l)switch(s.type){case "hasOne":case "hasMany":{let u=s.localKey||"id",c=[...new Set(n.map(m=>m[u]).filter(m=>m!=null))];if(c.length===0){n=n.map(m=>({...m,[r]:s.type==="hasMany"?[]:null}));continue}let d=await l.findMany({where:{[s.foreignKey]:{in:c}}}),p=new Map;for(let m of d){let g=m[s.foreignKey];p.has(g)||p.set(g,[]),p.get(g).push(m);}n=n.map(m=>{let g=m[u],M=p.get(g)||[];return {...m,[r]:s.type==="hasMany"?M:M[0]||null}});break}case "belongsTo":{let u=s.localKey||"id",c=[...new Set(n.map(m=>m[s.foreignKey]).filter(m=>m!=null))];if(c.length===0){n=n.map(m=>({...m,[r]:null}));continue}let d=await l.findMany({where:{[u]:{in:c}}}),p=new Map;for(let m of d){let g=m[u];p.set(g,m);}n=n.map(m=>{let g=m[s.foreignKey];return {...m,[r]:p.get(g)||null}});break}}}return n}async function j(a){let{model:t,filters:e,searchFields:o=[],softDeleteConfig:n,defaultPerPage:r=20,additionalWhere:s={}}=a,i={...K(e.filters),...s};if(n?.enabled){let{withDeleted:g,onlyDeleted:M}=e.options;M?i[n.field]={not:null}:g||(i[n.field]=null);}if(e.options.search&&o.length>0){let g=o.map(M=>({[M]:{contains:e.options.search,mode:"insensitive"}}));i={...i,OR:g};}let l=await t.count({where:i}),u;e.options.order_by&&(u={[e.options.order_by]:e.options.order_by_direction||"asc"});let c=e.options.page||1,d=e.options.per_page||r,p=await t.findMany({where:i,orderBy:u,skip:(c-1)*d,take:d}),m=Math.ceil(l/d);return {records:p,where:i,totalCount:l,page:c,perPage:d,totalPages:m}}function E(a,t){return {result:a,result_info:{page:t.page,per_page:t.perPage,total_count:t.totalCount,total_pages:t.totalPages,has_next_page:t.page<t.totalPages,has_prev_page:t.page>1}}}var ae=class extends k$1{useTransaction=false;async getModel(){return f(this.prisma,this._meta.model.tableName)}async create(t){let e=await this.getModel(),o=this._meta.model.primaryKeys[0],n={...t,[o]:t[o]||crypto.randomUUID()};return await e.create({data:n})}},ie=class extends l{async getModel(){return f(this.prisma,this._meta.model.tableName)}async read(t,e,o){let n=await this.getModel(),r={[this.lookupField]:t,...e},s=await n.findFirst({where:r});return s?await se(this.prisma,s,this._meta,o):null}},le=class extends m{useTransaction=false;async getModel(){return f(this.prisma,this._meta.model.tableName)}async update(t,e,o){let n=await this.getModel(),r={[this.lookupField]:t,...o},s=await n.findFirst({where:r});if(!s)return null;let i=this._meta.model.primaryKeys[0];return await n.update({where:{[i]:s[i]},data:e})}},de=class extends n{useTransaction=false;async getModel(){return f(this.prisma,this._meta.model.tableName)}async findForDelete(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),r={[this.lookupField]:t,...e};return n.enabled&&(r[n.field]=null),await o.findFirst({where:r})}async delete(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),r={[this.lookupField]:t,...e};n.enabled&&(r[n.field]=null);let s=await o.findFirst({where:r});if(!s)return null;let i=this._meta.model.primaryKeys[0],l=s[i];return n.enabled?await o.update({where:{[i]:l},data:{[n.field]:new Date}}):await o.delete({where:{[i]:l}})}},ce=class extends o{async getModel(){return f(this.prisma,this._meta.model.tableName)}async list(t){let e=await j({model:await this.getModel(),filters:t,searchFields:this.searchFields,softDeleteConfig:this.getSoftDeleteConfig(),defaultPerPage:this.defaultPerPage}),o={relations:t.options.include||[]},n=await x(this.prisma,e.records,this._meta,o);return E(n,e)}};var ue=class extends p{useTransaction=false;async getModel(){return f(this.prisma,this._meta.model.tableName)}async restore(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),r={[this.lookupField]:t,[n.field]:{not:null},...e},s=await o.findFirst({where:r});if(!s)return null;let i=this._meta.model.primaryKeys[0];return await o.update({where:{[i]:s[i]},data:{[n.field]:null}})}},me=class extends r{async getModel(){return f(this.prisma,this._meta.model.tableName)}async batchCreate(t){let e=this._meta.model.primaryKeys[0],o=t.map(r=>({...r,[e]:r[e]||crypto.randomUUID()})),n=[];return await F(this.prisma)(async r=>{let s=h(r,await w(this._meta.model.tableName));if(!s)throw new Error(`Model '${this._meta.model.tableName}' not found in Prisma transaction client`);for(let i of o){let l=await s.create({data:i});n.push(l);}}),n}},ge=class extends s{async getModel(){return f(this.prisma,this._meta.model.tableName)}async batchUpdate(t){let e=await this.getModel(),o=this.getSoftDeleteConfig(),n=this._meta.model.primaryKeys[0],r=[],s=[],i=t.map(d=>d.id),l={[this.lookupField]:{in:i}};o.enabled&&(l[o.field]=null);let u=await e.findMany({where:l}),c=new Map;for(let d of u){let p=d[this.lookupField];c.set(p,d);}for(let d of t){let p=c.get(d.id);if(!p){s.push(d.id);continue}let m=await e.update({where:{[n]:p[n]},data:d.data});r.push(m);}return {updated:r,notFound:s}}},pe=class extends t{async getModel(){return f(this.prisma,this._meta.model.tableName)}async batchDelete(t){let e=await this.getModel(),o=this.getSoftDeleteConfig(),n=this._meta.model.primaryKeys[0],r=[],s=[],i={[this.lookupField]:{in:t}};o.enabled&&(i[o.field]=null);let l=await e.findMany({where:i}),u=new Map;for(let c of l){let d=c[this.lookupField];u.set(d,c);}for(let c of t)u.has(c)||s.push(c);for(let c of t){let d=u.get(c);if(d)if(o.enabled){let p=await e.update({where:{[n]:d[n]},data:{[o.field]:new Date}});r.push(p);}else {let p=await e.delete({where:{[n]:d[n]}});r.push(p);}}return {deleted:r,notFound:s}}},fe=class extends u{async getModel(){return f(this.prisma,this._meta.model.tableName)}async batchRestore(t){let e=await this.getModel(),o=this.getSoftDeleteConfig(),n=this._meta.model.primaryKeys[0],r=[],s=[],i={[this.lookupField]:{in:t},[o.field]:{not:null}},l=await e.findMany({where:i}),u=new Map;for(let c of l){let d=c[this.lookupField];u.set(d,c);}for(let c of t){let d=u.get(c);if(!d){s.push(c);continue}let p=await e.update({where:{[n]:d[n]},data:{[o.field]:null}});r.push(p);}return {restored:r,notFound:s}}},Me=class extends v$1{useTransaction=true;async getModel(){return f(this.prisma,this._meta.model.tableName)}async findExisting(t){let e=await this.getModel(),o=this.getUpsertKeys(),n={};for(let s of o){let i=t[s];i!==void 0&&(n[s]=i);}return Object.keys(n).length===0?null:await e.findFirst({where:n})||null}async create(t){let e=await this.getModel(),o=this._meta.model.primaryKeys[0],n={...t,[o]:t[o]||crypto.randomUUID()};return await e.create({data:n})}async update(t,e){let o=await this.getModel(),n=this._meta.model.primaryKeys[0];return await o.update({where:{[n]:t[n]},data:e})}async nativeBatchUpsert(t,e){if(t.length===0)return {items:[],createdCount:0,updatedCount:0,totalCount:0};let o=this.getUpsertKeys(),n=this._meta.model.primaryKeys[0],r=async l=>{let u=h(l,await w(this._meta.model.tableName));if(!u)throw new Error(`Model '${this._meta.model.tableName}' not found in Prisma client`);let c=[],d=[];for(let p=0;p<t.length;p++){let m=t[p];try{let g={};for(let y of o){let O=m[y];O!==void 0&&(g[y]=O);}let M={...m,[n]:m[n]||crypto.randomUUID()},P={};for(let[y,O]of Object.entries(m))!o.includes(y)&&y!==n&&(this.createOnlyFields?.includes(y)||(P[y]=O));let ve=await u.upsert({where:g,create:M,update:Object.keys(P).length>0?P:{}});c.push({data:ve,created:!1,index:p});}catch(g){if(this.continueOnError)d.push({index:p,error:g instanceof Error?g.message:String(g)});else throw g}}return {results:c,errors:d}},s;this.useTransaction?s=await F(this.prisma)(r):s=await r(this.prisma);let i={items:s.results,createdCount:0,updatedCount:s.results.length,totalCount:s.results.length};return s.errors.length>0&&(i.errors=s.errors),i}};var he=class extends J{async getModel(){return f(this.prisma,this._meta.model.tableName)}buildSearchWhere(t,e){let o=K(e.filters),n=this.getSoftDeleteConfig();if(n.enabled){let{withDeleted:l,onlyDeleted:u}=e.options;u?o[n.field]={not:null}:l||(o[n.field]=null);}let r=this.getSearchableFields(),i=(t.fields||Object.keys(r)).map(l=>({[l]:{contains:t.query,mode:"insensitive"}}));return i.length>0&&(t.mode==="all"?o={...o,AND:i}:o={...o,OR:i}),o}async search(t,e){let o=await this.getModel(),n=this.buildSearchWhere(t,e),r=await o.count({where:n}),s=e.options.order_by?{[e.options.order_by]:e.options.order_by_direction||"asc"}:void 0,i=e.options.page||1,l=e.options.per_page||this.defaultPerPage,u=await o.findMany({where:n,orderBy:s,skip:(i-1)*l,take:l}),c=K$1(u,t,this.getSearchableFields()),d={relations:e.options.include||[]},p=c.map(M=>M.item),m=await x(this.prisma,p,this._meta,d);return {items:c.map((M,P)=>({...M,item:m[P]})),totalCount:r}}},we=class extends T{async getModel(){return f(this.prisma,this._meta.model.tableName)}async list(t){let e=await j({model:await this.getModel(),filters:t,searchFields:this.searchFields,softDeleteConfig:this.getSoftDeleteConfig(),defaultPerPage:this.defaultPerPage}),o={relations:t.options.include||[]},n=await x(this.prisma,e.records,this._meta,o);return E(n,e)}},ye=class extends U{async getModel(){return f(this.prisma,this._meta.model.tableName)}async findExisting(t){let e=await this.getModel(),o=this.getUpsertKeys(),n={};for(let s of o){let i=t[s];i!==void 0&&(n[s]=i);}return Object.keys(n).length===0?null:await e.findFirst({where:n})||null}async create(t){let e=await this.getModel(),o=this._meta.model.primaryKeys[0],n={...t,[o]:t[o]||crypto.randomUUID()};return await e.create({data:n})}async update(t,e){let o=await this.getModel(),n=this._meta.model.primaryKeys[0];return await o.update({where:{[n]:t[n]},data:e})}},be=class extends q{useTransaction=false;async getModel(){return f(this.prisma,this._meta.model.tableName)}async findExisting(t){let e=await this.getModel(),o=this.getUpsertKeys(),n={};for(let s of o){let i=t[s];i!==void 0&&(n[s]=i);}return Object.keys(n).length===0?null:await e.findFirst({where:n})||null}async create(t){let e=await this.getModel(),o=this._meta.model.primaryKeys[0],n={...t,[o]:t[o]||crypto.randomUUID()};return await e.create({data:n})}async update(t,e){let o=await this.getModel(),n=this._meta.model.primaryKeys[0];return await o.update({where:{[n]:t[n]},data:e})}async nativeUpsert(t,e){let o=await this.getModel(),n=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s={};for(let c of n){let d=t[c];d!==void 0&&(s[c]=d);}let i={...t,[r]:t[r]||crypto.randomUUID()},l={};for(let[c,d]of Object.entries(t))!n.includes(c)&&c!==r&&(this.createOnlyFields?.includes(c)||(l[c]=d));return {data:await o.upsert({where:s,create:i,update:Object.keys(l).length>0?l:{}}),created:false}}},Pe=class extends w$1{async getModel(){return f(this.prisma,this._meta.model.tableName)}async recordExists(t){return await(await this.getModel()).count({where:{[this.lookupField]:t}})>0}},ke=class extends x$1{},xe=class extends y{},Oe=class extends z{async getModel(){return f(this.prisma,this._meta.model.tableName)}async rollback(t,e,o){let n=await this.getModel(),r=this.getVersioningConfig().field,s=this._meta.model.primaryKeys[0],i=await n.findFirst({where:{[this.lookupField]:t}});if(!i)throw new Error(`Record not found: ${t}`);return await n.update({where:{[s]:i[s]},data:{...e,[r]:o}})}},Re=class extends A{useNativeAggregation=true;async getModel(){return f(this.prisma,this._meta.model.tableName)}async buildAggregateWhere(t){let e={},o=this.getSoftDeleteConfig();if(o.enabled){let{query:n}=await this.getValidatedData();n?.withDeleted===true||n?.withDeleted==="true"||(e[o.field]=null);}if(t.filters)for(let[n,r]of Object.entries(t.filters))if(typeof r=="object"&&r!==null){let s={};for(let[i,l]of Object.entries(r))switch(i){case "eq":s.equals=l;break;case "ne":s.not=l;break;case "gt":s.gt=l;break;case "gte":s.gte=l;break;case "lt":s.lt=l;break;case "lte":s.lte=l;break;case "in":s.in=l;break;case "nin":s.notIn=l;break;default:s[i]=l;}e[n]=s;}else e[n]=r;return e}async aggregate(t){let e=await this.getModel(),o=await this.buildAggregateWhere(t);if(!this.useNativeAggregation||t.having){let n=await e.findMany({where:o});return B(n,t)}return t.groupBy?.length?this.aggregateWithGroupBy(e,o,t):this.aggregateSimple(e,o,t)}groupAggregationsByOperation(t){let e={sum:[],avg:[],min:[],max:[],count:[],countDistinct:[]};for(let o of t)switch(o.operation){case "sum":e.sum.push(o.field);break;case "avg":e.avg.push(o.field);break;case "min":e.min.push(o.field);break;case "max":e.max.push(o.field);break;case "count":e.count.push(o.field);break;case "countDistinct":e.countDistinct.push(o.field);break}return e}async aggregateSimple(t,e,o){let n={where:e},r={},s=this.groupAggregationsByOperation(o.aggregations);if(n._count=true,s.sum.length){n._sum={};for(let u of s.sum)n._sum[u]=true;}if(s.avg.length){n._avg={};for(let u of s.avg)n._avg[u]=true;}if(s.min.length){n._min={};for(let u of s.min)n._min[u]=true;}if(s.max.length){n._max={};for(let u of s.max)n._max[u]=true;}let i=await w(this._meta.model.tableName),l=h(this.prisma,i);if(!l)throw new Error(`Model '${i}' not found in Prisma client`);try{let u=await l.aggregate(n);if(u._count!==void 0&&(r.count=typeof u._count=="object"?u._count._all??0:u._count),u._sum&&s.sum.length)for(let c of s.sum){let d=c.charAt(0).toUpperCase()+c.slice(1);r[`sum${d}`]=u._sum[c]??0;}if(u._avg&&s.avg.length)for(let c of s.avg){let d=c.charAt(0).toUpperCase()+c.slice(1);r[`avg${d}`]=u._avg[c]??0;}if(u._min&&s.min.length)for(let c of s.min){let d=c.charAt(0).toUpperCase()+c.slice(1);r[`min${d}`]=u._min[c];}if(u._max&&s.max.length)for(let c of s.max){let d=c.charAt(0).toUpperCase()+c.slice(1);r[`max${d}`]=u._max[c];}return {values:r,groups:[]}}catch{let c=await t.findMany({where:e});return B(c,o)}}async aggregateWithGroupBy(t,e,o){let n={by:o.groupBy,where:e},r=this.groupAggregationsByOperation(o.aggregations);if(n._count=true,r.sum.length){n._sum={};for(let l of r.sum)n._sum[l]=true;}if(r.avg.length){n._avg={};for(let l of r.avg)n._avg[l]=true;}if(r.min.length){n._min={};for(let l of r.min)n._min[l]=true;}if(r.max.length){n._max={};for(let l of r.max)n._max[l]=true;}let s=await w(this._meta.model.tableName),i=h(this.prisma,s);if(!i)throw new Error(`Model '${s}' not found in Prisma client`);try{let u=(await i.groupBy(n)).map(d=>{let p={},m={};for(let g of o.groupBy)p[g]=d[g];if(m.count=typeof d._count=="object"?d._count._all??0:d._count??0,d._sum&&r.sum.length)for(let g of r.sum){let M=g.charAt(0).toUpperCase()+g.slice(1);m[`sum${M}`]=d._sum[g]??0;}if(d._avg&&r.avg.length)for(let g of r.avg){let M=g.charAt(0).toUpperCase()+g.slice(1);m[`avg${M}`]=d._avg[g]??0;}if(d._min&&r.min.length)for(let g of r.min){let M=g.charAt(0).toUpperCase()+g.slice(1);m[`min${M}`]=d._min[g];}if(d._max&&r.max.length)for(let g of r.max){let M=g.charAt(0).toUpperCase()+g.slice(1);m[`max${M}`]=d._max[g];}return {key:p,values:m}});return {values:{count:u.reduce((d,p)=>d+(p.values.count||0),0)},groups:u}}catch{let u=await t.findMany({where:e});return B(u,o)}}};export{Re as PrismaAggregateEndpoint,me as PrismaBatchCreateEndpoint,pe as PrismaBatchDeleteEndpoint,fe as PrismaBatchRestoreEndpoint,ge as PrismaBatchUpdateEndpoint,Me as PrismaBatchUpsertEndpoint,ae as PrismaCreateEndpoint,de as PrismaDeleteEndpoint,we as PrismaExportEndpoint,ye as PrismaImportEndpoint,ce as PrismaListEndpoint,ie as PrismaReadEndpoint,ue as PrismaRestoreEndpoint,he as PrismaSearchEndpoint,le as PrismaUpdateEndpoint,be as PrismaUpsertEndpoint,xe as PrismaVersionCompareEndpoint,Pe as PrismaVersionHistoryEndpoint,ke as PrismaVersionReadEndpoint,Oe as PrismaVersionRollbackEndpoint,Fe as clearPrismaModelMappings,re as registerPrismaModelMapping,Ie as registerPrismaModelMappings};
|
package/dist/audit/index.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { Context, Env } from 'hono';
|
|
2
|
-
import { A as AuditConfig, a as AuditLogEntry, b as AuditAction } from '../types-
|
|
2
|
+
import { A as AuditConfig, a as AuditLogEntry, b as AuditAction } from '../types-tpG0M7Va.js';
|
|
3
3
|
import { S as StorageRegistry } from '../registry-PNJjvSvm.js';
|
|
4
|
+
import 'zod';
|
|
4
5
|
import '../types-B5wq2iKZ.js';
|
|
5
6
|
import '../types-BAcN7U0B.js';
|
|
6
|
-
import 'zod';
|
|
7
7
|
import '@hono/zod-openapi';
|
|
8
8
|
|
|
9
9
|
/**
|
package/dist/audit/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{e as AuditLogger,a as MemoryAuditLogStorage,b as auditStorageRegistry,f as createAuditLogger,d as getAuditStorage,c as setAuditStorage}from'../chunk-
|
|
1
|
+
export{e as AuditLogger,a as MemoryAuditLogStorage,b as auditStorageRegistry,f as createAuditLogger,d as getAuditStorage,c as setAuditStorage}from'../chunk-ANWSQPCQ.js';import'../chunk-Z575OBLV.js';import'../chunk-GBQQ3YQX.js';import'../chunk-MDHMZPXK.js';import'../chunk-VJRDAVID.js';
|
package/dist/auth/index.d.ts
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export {
|
|
1
|
+
import { p as AuthEnv, a5 as JWTConfig, a3 as JWTClaims, q as APIKeyConfig, r as APIKeyEntry, y as AuthConfig, W as Guard, w as ApprovalConfig, C as AuthorizationCheck, aj as OwnershipExtractor, a8 as ModelPolicies, x as ApprovalStorage, am as PendingAction, B as AuthUser, M as MetaInput, O as OpenAPIRouteSchema, aR as Constructor, Q as EndpointAuthConfig, aS as APIKeyStorage, s as APIKeyLookupResult } from '../types-tpG0M7Va.js';
|
|
2
|
+
export { t as ActionSource, z as AuthType, a2 as JWTAlgorithm, a4 as JWTClaimsSchema, al as PathPattern, an as PendingActionStatus, ax as ValidatedJWTClaims, aO as parseJWTClaims, aQ as safeParseJWTClaims } from '../types-tpG0M7Va.js';
|
|
3
3
|
import { MiddlewareHandler, Context } from 'hono';
|
|
4
|
-
import {
|
|
5
|
-
import { O as OpenAPIRoute } from '../route-CSScNXhr.js';
|
|
4
|
+
import { O as OpenAPIRoute } from '../route-AzM3iPZP.js';
|
|
6
5
|
import 'zod';
|
|
7
6
|
import '../types-B5wq2iKZ.js';
|
|
8
7
|
import '../types-BAcN7U0B.js';
|
|
@@ -130,6 +129,12 @@ declare function optionalAuth<E extends AuthEnv = AuthEnv>(config: Omit<AuthConf
|
|
|
130
129
|
*/
|
|
131
130
|
declare function requireAuthentication<E extends AuthEnv = AuthEnv>(config: Omit<AuthConfig, 'requireAuth'>): MiddlewareHandler<E>;
|
|
132
131
|
|
|
132
|
+
/**
|
|
133
|
+
* Storage key under `c.var` for the policies object set by `requirePolicy`.
|
|
134
|
+
* Endpoints prefer this over `Model.policies` when present so route-scoped
|
|
135
|
+
* policies override the model-level defaults.
|
|
136
|
+
*/
|
|
137
|
+
declare const POLICIES_CONTEXT_KEY = "__honoCrudPolicies";
|
|
133
138
|
/**
|
|
134
139
|
* Creates a guard that requires the user to have at least one of the specified roles.
|
|
135
140
|
*
|
|
@@ -261,6 +266,81 @@ declare function allowAll<E extends AuthEnv = AuthEnv>(): MiddlewareHandler<E>;
|
|
|
261
266
|
* ```
|
|
262
267
|
*/
|
|
263
268
|
declare function requireAuthenticated<E extends AuthEnv = AuthEnv>(): MiddlewareHandler<E>;
|
|
269
|
+
/**
|
|
270
|
+
* Attach a `ModelPolicies<T>` object to the current request so the
|
|
271
|
+
* downstream List / Read / Update / Delete endpoints apply it on top of
|
|
272
|
+
* (or in place of) any `Model.policies` defaults.
|
|
273
|
+
*
|
|
274
|
+
* Mutating: writes to `ctx.var[POLICIES_CONTEXT_KEY]`. Does not enforce
|
|
275
|
+
* by itself — enforcement happens in the endpoint handlers (post-fetch
|
|
276
|
+
* filtering for `read`, pre-write rejection for `write`, optional
|
|
277
|
+
* `readPushdown` translated to `FilterCondition[]` for List).
|
|
278
|
+
*
|
|
279
|
+
* @example
|
|
280
|
+
* ```ts
|
|
281
|
+
* app.get('/posts', requirePolicy<Post>({
|
|
282
|
+
* read: (ctx, post) => post.authorId === ctx.userId || ctx.user?.roles?.includes('admin'),
|
|
283
|
+
* }), PostList);
|
|
284
|
+
* ```
|
|
285
|
+
*/
|
|
286
|
+
declare function requirePolicy<T = unknown, E extends AuthEnv = AuthEnv>(policies: ModelPolicies<T>): MiddlewareHandler<E>;
|
|
287
|
+
/**
|
|
288
|
+
* Build a `requireApproval(...)` middleware for human-in-the-loop deferred
|
|
289
|
+
* execution.
|
|
290
|
+
*
|
|
291
|
+
* On the first call (no resume marker in body):
|
|
292
|
+
* 1. Parse the request body.
|
|
293
|
+
* 2. Persist a `PendingAction` carrying the body, full actor identity
|
|
294
|
+
* from `c.var` (user, agent, etc.), and a deadline.
|
|
295
|
+
* 3. Return `202 { status: 'pending', actionId, expiresAt }` to the
|
|
296
|
+
* caller. The handler does not run.
|
|
297
|
+
*
|
|
298
|
+
* On the resume call (`body[resumeMarker] = actionId`):
|
|
299
|
+
* 1. Look up the action; reject if missing, expired, or not approved.
|
|
300
|
+
* 2. Replay the original input as the request body (downstream
|
|
301
|
+
* `getValidatedData` reads it).
|
|
302
|
+
* 3. Continue to the handler.
|
|
303
|
+
*
|
|
304
|
+
* The middleware does not authenticate — combine with `requireRoles` /
|
|
305
|
+
* `requireAuth` upstream when the approval semantics need an authenticated
|
|
306
|
+
* caller.
|
|
307
|
+
*
|
|
308
|
+
* @example
|
|
309
|
+
* ```ts
|
|
310
|
+
* app.post('/transfers',
|
|
311
|
+
* requireApproval({ reason: 'Funds transfer over $1k' }),
|
|
312
|
+
* TransferCreate,
|
|
313
|
+
* );
|
|
314
|
+
* ```
|
|
315
|
+
*/
|
|
316
|
+
declare function requireApproval<E extends AuthEnv = AuthEnv>(config: ApprovalConfig): MiddlewareHandler<E>;
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* In-memory `ApprovalStorage` reference implementation.
|
|
320
|
+
*
|
|
321
|
+
* Stores pending actions in a `Map<actionId, PendingAction>`. Lazy expiry
|
|
322
|
+
* on `get(...)` (no `setInterval` — banned in edge runtimes; see
|
|
323
|
+
* `tests/edge-safety.test.ts`).
|
|
324
|
+
*
|
|
325
|
+
* Suitable for:
|
|
326
|
+
* - Local development / tests
|
|
327
|
+
* - Edge isolates that don't outlive a single-tenant request flight
|
|
328
|
+
*
|
|
329
|
+
* Not suitable for production cross-isolate state — wire a Postgres /
|
|
330
|
+
* Durable Object backed `ApprovalStorage` in those scenarios.
|
|
331
|
+
*/
|
|
332
|
+
|
|
333
|
+
declare class MemoryApprovalStorage implements ApprovalStorage {
|
|
334
|
+
private readonly store;
|
|
335
|
+
create(action: PendingAction): Promise<void>;
|
|
336
|
+
get(actionId: string): Promise<PendingAction | null>;
|
|
337
|
+
approve(actionId: string, by: string): Promise<void>;
|
|
338
|
+
reject(actionId: string, by: string, reason: string): Promise<void>;
|
|
339
|
+
/** Test helper: clear all stored actions. Not part of the interface. */
|
|
340
|
+
clear(): void;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
declare function parseIso8601Duration(input: string): number;
|
|
264
344
|
|
|
265
345
|
/**
|
|
266
346
|
* Interface for auth endpoint methods added by withAuth mixin.
|
|
@@ -598,4 +678,4 @@ declare function validateJWTClaims(claims: JWTClaims, options?: JWTClaimsValidat
|
|
|
598
678
|
*/
|
|
599
679
|
declare function validateAPIKeyEntry(entry: APIKeyEntry | null): APIKeyEntry;
|
|
600
680
|
|
|
601
|
-
export { APIKeyConfig, APIKeyEntry, APIKeyLookupResult, AuthConfig, type AuthEndpointMethods, AuthEnv, AuthUser, AuthenticatedEndpoint, AuthorizationCheck, EndpointAuthConfig, Guard, JWTClaims, type JWTClaimsValidationOptions, JWTConfig, MemoryAPIKeyStorage, OwnershipExtractor, allOf, allowAll, anyOf, createAPIKeyMiddleware, createAuthMiddleware, createJWTMiddleware, decodeJWT, defaultHashAPIKey, denyAll, generateAPIKey, getAPIKeyStorage, hashAPIKey, isValidAPIKeyFormat, optionalAuth, requireAllRoles, requireAnyPermission, requireAuth, requireAuthenticated, requireAuthentication, requireOwnership, requireOwnershipOrRole, requirePermissions, requireRoles, setAPIKeyStorage, validateAPIKey, validateAPIKeyEntry, validateJWTClaims, verifyJWT, withAuth };
|
|
681
|
+
export { APIKeyConfig, APIKeyEntry, APIKeyLookupResult, ApprovalConfig, ApprovalStorage, AuthConfig, type AuthEndpointMethods, AuthEnv, AuthUser, AuthenticatedEndpoint, AuthorizationCheck, EndpointAuthConfig, Guard, JWTClaims, type JWTClaimsValidationOptions, JWTConfig, MemoryAPIKeyStorage, MemoryApprovalStorage, OwnershipExtractor, POLICIES_CONTEXT_KEY, PendingAction, allOf, allowAll, anyOf, createAPIKeyMiddleware, createAuthMiddleware, createJWTMiddleware, decodeJWT, defaultHashAPIKey, denyAll, generateAPIKey, getAPIKeyStorage, hashAPIKey, isValidAPIKeyFormat, optionalAuth, parseIso8601Duration, requireAllRoles, requireAnyPermission, requireApproval, requireAuth, requireAuthenticated, requireAuthentication, requireOwnership, requireOwnershipOrRole, requirePermissions, requirePolicy, requireRoles, setAPIKeyStorage, validateAPIKey, validateAPIKeyEntry, validateJWTClaims, verifyJWT, withAuth };
|
package/dist/auth/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{
|
|
1
|
+
export{o as AuthenticatedEndpoint,a as JWTClaimsSchema,j as createAPIKeyMiddleware,l as createAuthMiddleware,e as createJWTMiddleware,g as decodeJWT,i as defaultHashAPIKey,m as optionalAuth,b as parseJWTClaims,n as requireAuthentication,c as safeParseJWTClaims,k as validateAPIKey,h as validateAPIKeyEntry,d as validateJWTClaims,f as verifyJWT,p as withAuth}from'../chunk-KLZMYDYG.js';export{d as MemoryApprovalStorage,e as POLICIES_CONTEXT_KEY,m as allOf,p as allowAll,n as anyOf,o as denyAll,c as parseIso8601Duration,g as requireAllRoles,i as requireAnyPermission,s as requireApproval,j as requireAuth,q as requireAuthenticated,k as requireOwnership,l as requireOwnershipOrRole,h as requirePermissions,r as requirePolicy,f as requireRoles}from'../chunk-3TIIYAKB.js';export{c as MemoryAPIKeyStorage,d as generateAPIKey,h as getAPIKeyStorage,e as hashAPIKey,f as isValidAPIKeyFormat,i as setAPIKeyStorage}from'../chunk-2M5BM4VD.js';import'../chunk-FC56WWPB.js';import'../chunk-GBQQ3YQX.js';import'../chunk-DMGP7QDL.js';import'../chunk-MDHMZPXK.js';import'../chunk-VJRDAVID.js';
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { ZodObject, ZodRawShape } from 'zod';
|
|
2
2
|
import { Env } from 'hono';
|
|
3
|
-
import { C as CrudEndpoint, M as ModelObject } from './import-
|
|
4
|
-
import { M as MetaInput, O as OpenAPIRouteSchema, H as HookMode, L as ListFilters } from './types-
|
|
3
|
+
import { C as CrudEndpoint, M as ModelObject } from './import-JN0uu97B.js';
|
|
4
|
+
import { M as MetaInput, O as OpenAPIRouteSchema, H as HookMode, L as ListFilters } from './types-tpG0M7Va.js';
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* Base endpoint for cloning/duplicating a resource.
|
package/dist/cache/index.d.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
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
2
|
export { g as InvalidationStrategy } from '../types-BdRvpp1z.js';
|
|
3
3
|
import { K as KVNamespace } from '../cloudflare-kv-types-ByUEHhBc.js';
|
|
4
|
-
import {
|
|
5
|
-
import { O as OpenAPIRoute } from '../route-
|
|
4
|
+
import { aR as Constructor } from '../types-tpG0M7Va.js';
|
|
5
|
+
import { O as OpenAPIRoute } from '../route-AzM3iPZP.js';
|
|
6
|
+
import 'hono';
|
|
7
|
+
import 'zod';
|
|
6
8
|
import '../types-B5wq2iKZ.js';
|
|
7
9
|
import '../types-BAcN7U0B.js';
|
|
8
|
-
import 'zod';
|
|
9
|
-
import 'hono';
|
|
10
10
|
import '@hono/zod-openapi';
|
|
11
11
|
import 'hono/utils/http-status';
|
|
12
12
|
|
package/dist/cache/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{b as KVCacheStorage,a as RedisCacheStorage}from'../chunk-H3H65KZF.js';export{C as MemoryCacheStorage,y as createInvalidationPattern,z as createRelatedPatterns,x as generateCacheKey,E as getCacheStorage,A as matchesPattern,B as parseCacheKey,D as setCacheStorage,F as withCache,G as withCacheInvalidation}from'../chunk-
|
|
1
|
+
export{b as KVCacheStorage,a as RedisCacheStorage}from'../chunk-H3H65KZF.js';export{C as MemoryCacheStorage,y as createInvalidationPattern,z as createRelatedPatterns,x as generateCacheKey,E as getCacheStorage,A as matchesPattern,B as parseCacheKey,D as setCacheStorage,F as withCache,G as withCacheInvalidation}from'../chunk-3PFSX6M2.js';import'../chunk-7NM6MBRL.js';import'../chunk-GF2EC5G4.js';import'../chunk-ANWSQPCQ.js';import'../chunk-Z575OBLV.js';import'../chunk-2M5BM4VD.js';import'../chunk-FC56WWPB.js';import'../chunk-GBQQ3YQX.js';import'../chunk-DMGP7QDL.js';import'../chunk-MDHMZPXK.js';import'../chunk-VJRDAVID.js';
|