hono-crud 0.12.3 → 0.12.4

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.
Files changed (38) hide show
  1. package/CHANGELOG.md +2 -0
  2. package/dist/adapters/drizzle/index.d.ts +4 -4
  3. package/dist/adapters/drizzle/index.js +1 -1
  4. package/dist/adapters/memory/index.d.ts +4 -4
  5. package/dist/adapters/memory/index.js +1 -1
  6. package/dist/adapters/prisma/index.d.ts +4 -4
  7. package/dist/adapters/prisma/index.js +1 -1
  8. package/dist/audit/index.d.ts +1 -1
  9. package/dist/audit/index.js +1 -1
  10. package/dist/auth/index.d.ts +3 -3
  11. package/dist/auth/index.js +1 -1
  12. package/dist/{bulk-patch-DcGhBJGk.d.ts → bulk-patch-DC4NS656.d.ts} +2 -2
  13. package/dist/cache/index.d.ts +2 -2
  14. package/dist/cache/index.js +1 -1
  15. package/dist/{chunk-FDRCY3XF.js → chunk-75XHZDBH.js} +1 -1
  16. package/dist/{chunk-4FZTIZFM.js → chunk-7ZUZICKI.js} +1 -1
  17. package/dist/{chunk-2RI4AYKP.js → chunk-CGVBR7MW.js} +1 -1
  18. package/dist/{chunk-KLBMVJX3.js → chunk-FJCWFB5L.js} +1 -1
  19. package/dist/{chunk-4CM6OCS3.js → chunk-IPMPKM4J.js} +1 -1
  20. package/dist/{chunk-FHABLABR.js → chunk-KUFOENSK.js} +1 -1
  21. package/dist/{chunk-3DE2MG3R.js → chunk-NGUMNUOP.js} +1 -1
  22. package/dist/{chunk-ESMN3MEH.js → chunk-PCPU5A2Q.js} +1 -1
  23. package/dist/{chunk-NYDPHOMU.js → chunk-S2C35QM7.js} +1 -1
  24. package/dist/{chunk-VIKT6QQG.js → chunk-V4YEHNEZ.js} +10 -10
  25. package/dist/{chunk-4PBGEU64.js → chunk-XI7HT5ZM.js} +1 -1
  26. package/dist/{import-BwvD7VLW.d.ts → import-Gx0ZUJjI.d.ts} +8 -2
  27. package/dist/{index-CdId8t4j.d.ts → index-B1QEfh5v.d.ts} +8 -8
  28. package/dist/index.d.ts +9 -9
  29. package/dist/index.js +1 -1
  30. package/dist/logging/index.js +1 -1
  31. package/dist/rate-limit/index.js +1 -1
  32. package/dist/{route-Ctv6vIW0.d.ts → route-UXFfftVm.d.ts} +1 -1
  33. package/dist/storage/index.d.ts +1 -1
  34. package/dist/storage/index.js +1 -1
  35. package/dist/{types-Bg1Mpdsl.d.ts → types-Dfi9RdjS.d.ts} +21 -1
  36. package/dist/versioning/index.d.ts +1 -1
  37. package/dist/versioning/index.js +1 -1
  38. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
12
12
  %b
13
13
  %b
14
14
  %b
15
+ %b
15
16
  ## [0.8.0] — 2026-05-03
16
17
 
17
18
  ### Added
@@ -89,3 +90,4 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
89
90
  [0.12.1]: https://github.com/kshdotdev/hono-crud/compare/v0.12.0...v0.12.1
90
91
  [0.12.2]: https://github.com/kshdotdev/hono-crud/compare/v0.12.1...v0.12.2
91
92
  [0.12.3]: https://github.com/kshdotdev/hono-crud/compare/v0.12.2...v0.12.3
93
+ [0.12.4]: https://github.com/kshdotdev/hono-crud/compare/v0.12.3...v0.12.4
@@ -1,13 +1,13 @@
1
1
  import { Table, SQL, Column } from 'drizzle-orm';
2
- import { M as MetaInput, I as IncludeOptions, n as FilterCondition, h as RelationConfig, N as NestedUpdateInput, i as NestedWriteResult, L as ListFilters, P as PaginatedResult, j as AggregateOptions, k as AggregateResult, S as SearchOptions, l as SearchResult } from '../../types-Bg1Mpdsl.js';
2
+ import { M as MetaInput, I as IncludeOptions, n as FilterCondition, h as RelationConfig, N as NestedUpdateInput, i as NestedWriteResult, L as ListFilters, P as PaginatedResult, j as AggregateOptions, k as AggregateResult, S as SearchOptions, l as SearchResult } from '../../types-Dfi9RdjS.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 CloneEndpoint, i as UpsertEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint, V as VersionCompareEndpoint, j as VersionHistoryEndpoint, k as VersionReadEndpoint, l as VersionRollbackEndpoint } from '../../import-BwvD7VLW.js';
4
+ import { a as CreateEndpoint, M as ModelObject, R as ReadEndpoint, U as UpdateEndpoint, D as DeleteEndpoint, L as ListEndpoint, b as RestoreEndpoint, B as BatchCreateEndpoint, c as BatchDeleteEndpoint, d as BatchRestoreEndpoint, e as BatchUpdateEndpoint, f as BatchUpdateItem, A as AggregateEndpoint, g as BatchUpsertEndpoint, h as CloneEndpoint, i as UpsertEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint, V as VersionCompareEndpoint, j as VersionHistoryEndpoint, k as VersionReadEndpoint, l as VersionRollbackEndpoint } from '../../import-Gx0ZUJjI.js';
5
5
  import { z } from 'zod';
6
- import { A as AdapterBundle } from '../../index-CdId8t4j.js';
6
+ import { A as AdapterBundle } from '../../index-B1QEfh5v.js';
7
7
  import '../../types-B5wq2iKZ.js';
8
8
  import '../../types-BAcN7U0B.js';
9
9
  import '@hono/zod-openapi';
10
- import '../../route-Ctv6vIW0.js';
10
+ import '../../route-UXFfftVm.js';
11
11
  import 'hono/utils/http-status';
12
12
  import '../../exceptions-BEvDdXFC.js';
13
13
  import 'hono/http-exception';
@@ -1 +1 @@
1
- export{I as DrizzleAdapters,x as DrizzleAggregateEndpoint,n as DrizzleBatchCreateEndpoint,p as DrizzleBatchDeleteEndpoint,q as DrizzleBatchRestoreEndpoint,o as DrizzleBatchUpdateEndpoint,s as DrizzleBatchUpsertEndpoint,B as DrizzleCloneEndpoint,h as DrizzleCreateEndpoint,k as DrizzleDeleteEndpoint,z as DrizzleExportEndpoint,A as DrizzleImportEndpoint,l as DrizzleListEndpoint,i as DrizzleReadEndpoint,m as DrizzleRestoreEndpoint,y as DrizzleSearchEndpoint,j as DrizzleUpdateEndpoint,r as DrizzleUpsertEndpoint,v as DrizzleVersionCompareEndpoint,t as DrizzleVersionHistoryEndpoint,u as DrizzleVersionReadEndpoint,w as DrizzleVersionRollbackEndpoint,f as batchLoadDrizzleRelations,g as buildWhereCondition,a as cast,C as createDrizzleCrud,G as createDrizzleSchemas,E as createInsertSchema,D as createSelectSchema,F as createUpdateSchema,c as getColumn,b as getTable,H as isDrizzleZodAvailable,d as loadDrizzleRelation,e as loadDrizzleRelations}from'../../chunk-FDRCY3XF.js';import'../../chunk-VIKT6QQG.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-4PBGEU64.js';import'../../chunk-3DE2MG3R.js';import'../../chunk-KLBMVJX3.js';import'../../chunk-FC56WWPB.js';import'../../chunk-FHABLABR.js';import'../../chunk-GBQQ3YQX.js';import'../../chunk-QRXEQTNE.js';import'../../chunk-QXFY6NYI.js';import'../../chunk-DMGP7QDL.js';import'../../chunk-MDHMZPXK.js';import'../../chunk-VJRDAVID.js';
1
+ export{I as DrizzleAdapters,x as DrizzleAggregateEndpoint,n as DrizzleBatchCreateEndpoint,p as DrizzleBatchDeleteEndpoint,q as DrizzleBatchRestoreEndpoint,o as DrizzleBatchUpdateEndpoint,s as DrizzleBatchUpsertEndpoint,B as DrizzleCloneEndpoint,h as DrizzleCreateEndpoint,k as DrizzleDeleteEndpoint,z as DrizzleExportEndpoint,A as DrizzleImportEndpoint,l as DrizzleListEndpoint,i as DrizzleReadEndpoint,m as DrizzleRestoreEndpoint,y as DrizzleSearchEndpoint,j as DrizzleUpdateEndpoint,r as DrizzleUpsertEndpoint,v as DrizzleVersionCompareEndpoint,t as DrizzleVersionHistoryEndpoint,u as DrizzleVersionReadEndpoint,w as DrizzleVersionRollbackEndpoint,f as batchLoadDrizzleRelations,g as buildWhereCondition,a as cast,C as createDrizzleCrud,G as createDrizzleSchemas,E as createInsertSchema,D as createSelectSchema,F as createUpdateSchema,c as getColumn,b as getTable,H as isDrizzleZodAvailable,d as loadDrizzleRelation,e as loadDrizzleRelations}from'../../chunk-75XHZDBH.js';import'../../chunk-V4YEHNEZ.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-XI7HT5ZM.js';import'../../chunk-NGUMNUOP.js';import'../../chunk-FJCWFB5L.js';import'../../chunk-FC56WWPB.js';import'../../chunk-KUFOENSK.js';import'../../chunk-GBQQ3YQX.js';import'../../chunk-QRXEQTNE.js';import'../../chunk-QXFY6NYI.js';import'../../chunk-DMGP7QDL.js';import'../../chunk-MDHMZPXK.js';import'../../chunk-VJRDAVID.js';
@@ -1,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, h as CloneEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint, i as UpsertEndpoint, V as VersionCompareEndpoint, j as VersionHistoryEndpoint, k as VersionReadEndpoint, l as VersionRollbackEndpoint } from '../../import-BwvD7VLW.js';
3
- import { M as MetaInput, h as RelationConfig, L as ListFilters, P as PaginatedResult, I as IncludeOptions, N as NestedUpdateInput, i as NestedWriteResult, j as AggregateOptions, k as AggregateResult, S as SearchOptions, l as SearchResult } from '../../types-Bg1Mpdsl.js';
4
- import { B as BulkPatchEndpoint } from '../../bulk-patch-DcGhBJGk.js';
2
+ import { a as CreateEndpoint, M as ModelObject, D as DeleteEndpoint, L as ListEndpoint, R as ReadEndpoint, b as RestoreEndpoint, U as UpdateEndpoint, B as BatchCreateEndpoint, c as BatchDeleteEndpoint, d as BatchRestoreEndpoint, e as BatchUpdateEndpoint, f as BatchUpdateItem, g as BatchUpsertEndpoint, A as AggregateEndpoint, h as CloneEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint, i as UpsertEndpoint, V as VersionCompareEndpoint, j as VersionHistoryEndpoint, k as VersionReadEndpoint, l as VersionRollbackEndpoint } from '../../import-Gx0ZUJjI.js';
3
+ import { M as MetaInput, h as RelationConfig, L as ListFilters, P as PaginatedResult, I as IncludeOptions, N as NestedUpdateInput, i as NestedWriteResult, j as AggregateOptions, k as AggregateResult, S as SearchOptions, l as SearchResult } from '../../types-Dfi9RdjS.js';
4
+ import { B as BulkPatchEndpoint } from '../../bulk-patch-DC4NS656.js';
5
5
  import 'zod';
6
- import '../../route-Ctv6vIW0.js';
6
+ import '../../route-UXFfftVm.js';
7
7
  import 'hono/utils/http-status';
8
8
  import '../../exceptions-BEvDdXFC.js';
9
9
  import 'hono/http-exception';
@@ -1 +1 @@
1
- export{f as MEMORY_NOOP_TX,x as MemoryAggregateEndpoint,m as MemoryBatchCreateEndpoint,o as MemoryBatchDeleteEndpoint,p as MemoryBatchRestoreEndpoint,n as MemoryBatchUpdateEndpoint,q as MemoryBatchUpsertEndpoint,B as MemoryBulkPatchEndpoint,r as MemoryCloneEndpoint,g as MemoryCreateEndpoint,j as MemoryDeleteEndpoint,z as MemoryExportEndpoint,A as MemoryImportEndpoint,k as MemoryListEndpoint,h as MemoryReadEndpoint,l as MemoryRestoreEndpoint,y as MemorySearchEndpoint,i as MemoryUpdateEndpoint,s as MemoryUpsertEndpoint,v as MemoryVersionCompareEndpoint,t as MemoryVersionHistoryEndpoint,u as MemoryVersionReadEndpoint,w as MemoryVersionRollbackEndpoint,d as clearStorage,e as getStorage,c as getStore,b as storage}from'../../chunk-NYDPHOMU.js';import'../../chunk-VIKT6QQG.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-4PBGEU64.js';import'../../chunk-3DE2MG3R.js';import'../../chunk-KLBMVJX3.js';import'../../chunk-FC56WWPB.js';import'../../chunk-FHABLABR.js';import'../../chunk-GBQQ3YQX.js';import'../../chunk-QRXEQTNE.js';import'../../chunk-QXFY6NYI.js';import'../../chunk-DMGP7QDL.js';import'../../chunk-MDHMZPXK.js';import'../../chunk-VJRDAVID.js';
1
+ export{f as MEMORY_NOOP_TX,x as MemoryAggregateEndpoint,m as MemoryBatchCreateEndpoint,o as MemoryBatchDeleteEndpoint,p as MemoryBatchRestoreEndpoint,n as MemoryBatchUpdateEndpoint,q as MemoryBatchUpsertEndpoint,B as MemoryBulkPatchEndpoint,r as MemoryCloneEndpoint,g as MemoryCreateEndpoint,j as MemoryDeleteEndpoint,z as MemoryExportEndpoint,A as MemoryImportEndpoint,k as MemoryListEndpoint,h as MemoryReadEndpoint,l as MemoryRestoreEndpoint,y as MemorySearchEndpoint,i as MemoryUpdateEndpoint,s as MemoryUpsertEndpoint,v as MemoryVersionCompareEndpoint,t as MemoryVersionHistoryEndpoint,u as MemoryVersionReadEndpoint,w as MemoryVersionRollbackEndpoint,d as clearStorage,e as getStorage,c as getStore,b as storage}from'../../chunk-S2C35QM7.js';import'../../chunk-V4YEHNEZ.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-XI7HT5ZM.js';import'../../chunk-NGUMNUOP.js';import'../../chunk-FJCWFB5L.js';import'../../chunk-FC56WWPB.js';import'../../chunk-KUFOENSK.js';import'../../chunk-GBQQ3YQX.js';import'../../chunk-QRXEQTNE.js';import'../../chunk-QXFY6NYI.js';import'../../chunk-DMGP7QDL.js';import'../../chunk-MDHMZPXK.js';import'../../chunk-VJRDAVID.js';
@@ -1,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, U as UpdateEndpoint, B as BatchCreateEndpoint, c as BatchDeleteEndpoint, d as BatchRestoreEndpoint, e as BatchUpdateEndpoint, f as BatchUpdateItem, g as BatchUpsertEndpoint, b as RestoreEndpoint, A as AggregateEndpoint, h as CloneEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint, i as UpsertEndpoint, V as VersionCompareEndpoint, j as VersionHistoryEndpoint, k as VersionReadEndpoint, l as VersionRollbackEndpoint } from '../../import-BwvD7VLW.js';
3
- import { M as MetaInput, L as ListFilters, P as PaginatedResult, I as IncludeOptions, j as AggregateOptions, k as AggregateResult, m as AggregateField, S as SearchOptions, l as SearchResult } from '../../types-Bg1Mpdsl.js';
4
- import { A as AdapterBundle } from '../../index-CdId8t4j.js';
2
+ import { a as CreateEndpoint, M as ModelObject, D as DeleteEndpoint, L as ListEndpoint, R as ReadEndpoint, U as UpdateEndpoint, B as BatchCreateEndpoint, c as BatchDeleteEndpoint, d as BatchRestoreEndpoint, e as BatchUpdateEndpoint, f as BatchUpdateItem, g as BatchUpsertEndpoint, b as RestoreEndpoint, A as AggregateEndpoint, h as CloneEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint, i as UpsertEndpoint, V as VersionCompareEndpoint, j as VersionHistoryEndpoint, k as VersionReadEndpoint, l as VersionRollbackEndpoint } from '../../import-Gx0ZUJjI.js';
3
+ import { M as MetaInput, L as ListFilters, P as PaginatedResult, I as IncludeOptions, j as AggregateOptions, k as AggregateResult, m as AggregateField, S as SearchOptions, l as SearchResult } from '../../types-Dfi9RdjS.js';
4
+ import { A as AdapterBundle } from '../../index-B1QEfh5v.js';
5
5
  import 'zod';
6
- import '../../route-Ctv6vIW0.js';
6
+ import '../../route-UXFfftVm.js';
7
7
  import 'hono/utils/http-status';
8
8
  import '../../exceptions-BEvDdXFC.js';
9
9
  import 'hono/http-exception';
@@ -1 +1 @@
1
- export{y as PrismaAdapters,w as PrismaAggregateEndpoint,j as PrismaBatchCreateEndpoint,l as PrismaBatchDeleteEndpoint,m as PrismaBatchRestoreEndpoint,k as PrismaBatchUpdateEndpoint,n as PrismaBatchUpsertEndpoint,x as PrismaCloneEndpoint,d as PrismaCreateEndpoint,g as PrismaDeleteEndpoint,p as PrismaExportEndpoint,q as PrismaImportEndpoint,h as PrismaListEndpoint,e as PrismaReadEndpoint,i as PrismaRestoreEndpoint,o as PrismaSearchEndpoint,f as PrismaUpdateEndpoint,r as PrismaUpsertEndpoint,u as PrismaVersionCompareEndpoint,s as PrismaVersionHistoryEndpoint,t as PrismaVersionReadEndpoint,v as PrismaVersionRollbackEndpoint,c as clearPrismaModelMappings,a as registerPrismaModelMapping,b as registerPrismaModelMappings}from'../../chunk-2RI4AYKP.js';import'../../chunk-VIKT6QQG.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-4PBGEU64.js';import'../../chunk-3DE2MG3R.js';import'../../chunk-KLBMVJX3.js';import'../../chunk-FC56WWPB.js';import'../../chunk-FHABLABR.js';import'../../chunk-GBQQ3YQX.js';import'../../chunk-QRXEQTNE.js';import'../../chunk-QXFY6NYI.js';import'../../chunk-DMGP7QDL.js';import'../../chunk-MDHMZPXK.js';import'../../chunk-VJRDAVID.js';
1
+ export{y as PrismaAdapters,w as PrismaAggregateEndpoint,j as PrismaBatchCreateEndpoint,l as PrismaBatchDeleteEndpoint,m as PrismaBatchRestoreEndpoint,k as PrismaBatchUpdateEndpoint,n as PrismaBatchUpsertEndpoint,x as PrismaCloneEndpoint,d as PrismaCreateEndpoint,g as PrismaDeleteEndpoint,p as PrismaExportEndpoint,q as PrismaImportEndpoint,h as PrismaListEndpoint,e as PrismaReadEndpoint,i as PrismaRestoreEndpoint,o as PrismaSearchEndpoint,f as PrismaUpdateEndpoint,r as PrismaUpsertEndpoint,u as PrismaVersionCompareEndpoint,s as PrismaVersionHistoryEndpoint,t as PrismaVersionReadEndpoint,v as PrismaVersionRollbackEndpoint,c as clearPrismaModelMappings,a as registerPrismaModelMapping,b as registerPrismaModelMappings}from'../../chunk-CGVBR7MW.js';import'../../chunk-V4YEHNEZ.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-XI7HT5ZM.js';import'../../chunk-NGUMNUOP.js';import'../../chunk-FJCWFB5L.js';import'../../chunk-FC56WWPB.js';import'../../chunk-KUFOENSK.js';import'../../chunk-GBQQ3YQX.js';import'../../chunk-QRXEQTNE.js';import'../../chunk-QXFY6NYI.js';import'../../chunk-DMGP7QDL.js';import'../../chunk-MDHMZPXK.js';import'../../chunk-VJRDAVID.js';
@@ -1,5 +1,5 @@
1
1
  import { Context, Env } from 'hono';
2
- import { A as AuditConfig, c as AuditLogEntry, d as AuditAction } from '../types-Bg1Mpdsl.js';
2
+ import { A as AuditConfig, c as AuditLogEntry, d as AuditAction } from '../types-Dfi9RdjS.js';
3
3
  import { S as StorageRegistry } from '../registry-PNJjvSvm.js';
4
4
  import 'zod';
5
5
  import '../types-B5wq2iKZ.js';
@@ -1 +1 @@
1
- export{e as AuditLogger,a as MemoryAuditLogStorage,b as auditStorageRegistry,f as createAuditLogger,d as getAuditStorage,c as setAuditStorage}from'../chunk-KLBMVJX3.js';import'../chunk-FHABLABR.js';import'../chunk-GBQQ3YQX.js';import'../chunk-MDHMZPXK.js';import'../chunk-VJRDAVID.js';
1
+ export{e as AuditLogger,a as MemoryAuditLogStorage,b as auditStorageRegistry,f as createAuditLogger,d as getAuditStorage,c as setAuditStorage}from'../chunk-FJCWFB5L.js';import'../chunk-KUFOENSK.js';import'../chunk-GBQQ3YQX.js';import'../chunk-MDHMZPXK.js';import'../chunk-VJRDAVID.js';
@@ -1,7 +1,7 @@
1
- import { r as AuthEnv, aa as JWTConfig, a8 as JWTClaims, s as APIKeyConfig, t as APIKeyEntry, D as AuthConfig, _ as Guard, B as ApprovalConfig, J as AuthorizationCheck, ao as OwnershipExtractor, ad as ModelPolicies, C as ApprovalStorage, ar as PendingAction, G as AuthUser, M as MetaInput, O as OpenAPIRouteSchema, aY as Constructor, X as EndpointAuthConfig, aZ as APIKeyStorage, u as APIKeyLookupResult } from '../types-Bg1Mpdsl.js';
2
- export { v as ActionSource, E as AuthType, a7 as JWTAlgorithm, a9 as JWTClaimsSchema, aq as PathPattern, as as PendingActionStatus, aE as ValidatedJWTClaims, aV as parseJWTClaims, aX as safeParseJWTClaims } from '../types-Bg1Mpdsl.js';
1
+ import { r as AuthEnv, aa as JWTConfig, a8 as JWTClaims, s as APIKeyConfig, t as APIKeyEntry, D as AuthConfig, _ as Guard, B as ApprovalConfig, J as AuthorizationCheck, ao as OwnershipExtractor, ad as ModelPolicies, C as ApprovalStorage, ar as PendingAction, G as AuthUser, M as MetaInput, O as OpenAPIRouteSchema, aY as Constructor, X as EndpointAuthConfig, aZ as APIKeyStorage, u as APIKeyLookupResult } from '../types-Dfi9RdjS.js';
2
+ export { v as ActionSource, E as AuthType, a7 as JWTAlgorithm, a9 as JWTClaimsSchema, aq as PathPattern, as as PendingActionStatus, aE as ValidatedJWTClaims, aV as parseJWTClaims, aX as safeParseJWTClaims } from '../types-Dfi9RdjS.js';
3
3
  import { MiddlewareHandler, Context } from 'hono';
4
- import { O as OpenAPIRoute } from '../route-Ctv6vIW0.js';
4
+ import { O as OpenAPIRoute } from '../route-UXFfftVm.js';
5
5
  import 'zod';
6
6
  import '../types-B5wq2iKZ.js';
7
7
  import '../types-BAcN7U0B.js';
@@ -1 +1 @@
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-4FZTIZFM.js';export{e as MemoryApprovalStorage,f as POLICIES_CONTEXT_KEY,n as allOf,q as allowAll,o as anyOf,p as denyAll,d as parseIso8601Duration,h as requireAllRoles,j as requireAnyPermission,t as requireApproval,k as requireAuth,r as requireAuthenticated,l as requireOwnership,m as requireOwnershipOrRole,i as requirePermissions,s as requirePolicy,g as requireRoles}from'../chunk-4PBGEU64.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-FHABLABR.js';import'../chunk-GBQQ3YQX.js';import'../chunk-DMGP7QDL.js';import'../chunk-MDHMZPXK.js';import'../chunk-VJRDAVID.js';
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-7ZUZICKI.js';export{e as MemoryApprovalStorage,f as POLICIES_CONTEXT_KEY,n as allOf,q as allowAll,o as anyOf,p as denyAll,d as parseIso8601Duration,h as requireAllRoles,j as requireAnyPermission,t as requireApproval,k as requireAuth,r as requireAuthenticated,l as requireOwnership,m as requireOwnershipOrRole,i as requirePermissions,s as requirePolicy,g as requireRoles}from'../chunk-XI7HT5ZM.js';export{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-KUFOENSK.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-BwvD7VLW.js';
4
- import { M as MetaInput, H as HookMode, L as ListFilters, O as OpenAPIRouteSchema } from './types-Bg1Mpdsl.js';
3
+ import { C as CrudEndpoint, M as ModelObject } from './import-Gx0ZUJjI.js';
4
+ import { M as MetaInput, H as HookMode, L as ListFilters, O as OpenAPIRouteSchema } from './types-Dfi9RdjS.js';
5
5
 
6
6
  /**
7
7
  * Result of a bulk patch operation.
@@ -1,8 +1,8 @@
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 { aY as Constructor } from '../types-Bg1Mpdsl.js';
5
- import { O as OpenAPIRoute } from '../route-Ctv6vIW0.js';
4
+ import { aY as Constructor } from '../types-Dfi9RdjS.js';
5
+ import { O as OpenAPIRoute } from '../route-UXFfftVm.js';
6
6
  import 'hono';
7
7
  import 'zod';
8
8
  import '../types-B5wq2iKZ.js';
@@ -1 +1 @@
1
- export{b as KVCacheStorage,a as RedisCacheStorage}from'../chunk-H3H65KZF.js';export{C as MemoryCacheStorage,y as createInvalidationPattern,z as createRelatedPatterns,x as generateCacheKey,E as getCacheStorage,A as matchesPattern,B as parseCacheKey,D as setCacheStorage,F as withCache,G as withCacheInvalidation}from'../chunk-4CM6OCS3.js';import'../chunk-3DE2MG3R.js';import'../chunk-GF2EC5G4.js';import'../chunk-KLBMVJX3.js';import'../chunk-2M5BM4VD.js';import'../chunk-FC56WWPB.js';import'../chunk-FHABLABR.js';import'../chunk-GBQQ3YQX.js';import'../chunk-DMGP7QDL.js';import'../chunk-MDHMZPXK.js';import'../chunk-VJRDAVID.js';
1
+ export{b as KVCacheStorage,a as RedisCacheStorage}from'../chunk-H3H65KZF.js';export{C as MemoryCacheStorage,y as createInvalidationPattern,z as createRelatedPatterns,x as generateCacheKey,E as getCacheStorage,A as matchesPattern,B as parseCacheKey,D as setCacheStorage,F as withCache,G as withCacheInvalidation}from'../chunk-IPMPKM4J.js';import'../chunk-NGUMNUOP.js';import'../chunk-GF2EC5G4.js';import'../chunk-FJCWFB5L.js';import'../chunk-2M5BM4VD.js';import'../chunk-FC56WWPB.js';import'../chunk-KUFOENSK.js';import'../chunk-GBQQ3YQX.js';import'../chunk-DMGP7QDL.js';import'../chunk-MDHMZPXK.js';import'../chunk-VJRDAVID.js';
@@ -1,4 +1,4 @@
1
- import {t,u,v as v$1,w,x,z as z$2,B as B$1,C,D,E,A as A$1,F as F$1,G as G$1,H as H$1,I as I$1,J as J$1,K as K$1,L as L$1,T,U as U$1,ba,ca,y}from'./chunk-VIKT6QQG.js';import {b}from'./chunk-DMGP7QDL.js';import {getTableColumns,eq,inArray,between,isNull,isNotNull,ilike,like,notInArray,lte,lt as lt$1,gte,gt as gt$1,ne,and,sql,or,desc,asc}from'drizzle-orm';import {z as z$1}from'zod';function q(l){return l}function h(l){if(!l.model.table)throw new Error(`Model ${l.model.tableName} does not have a table reference`);return l.model.table}function m(l,e){let n=getTableColumns(l),o=n[e];if(!o)throw new Error(`Column '${e}' not found in table. Available columns: ${Object.keys(n).join(", ")}`);return o}async function ve(l,e,n,o){if(!o.table)return e;let t=o.table;switch(o.type){case "hasOne":{let r=o.localKey||"id",s=e[r];if(s==null)return e;let i=m(t,o.foreignKey),a=await l.select().from(t).where(eq(i,s)).limit(1);return {...e,[n]:a[0]||null}}case "hasMany":{let r=o.localKey||"id",s=e[r];if(s==null)return {...e,[n]:[]};let i=m(t,o.foreignKey),a=await l.select().from(t).where(eq(i,s));return {...e,[n]:a}}case "belongsTo":{let r=e[o.foreignKey];if(r==null)return {...e,[n]:null};let s=m(t,o.localKey||"id"),i=await l.select().from(t).where(eq(s,r)).limit(1);return {...e,[n]:i[0]||null}}default:return e}}async function se(l,e,n,o){if(!o?.relations?.length||!n.model.relations)return e;let t={...e};for(let r of o.relations){let s=n.model.relations[r];s&&(t=await ve(l,t,r,s));}return t}async function v(l,e,n,o){if(!e.length||!o?.relations?.length||!n.model.relations)return e;let t=e.map(r=>({...r}));for(let r of o.relations){let s=n.model.relations[r];if(!s||!s.table)continue;let i=s.table;switch(s.type){case "hasOne":case "hasMany":{let a=s.localKey||"id",c=[...new Set(t.map(p=>p[a]).filter(p=>p!=null))];if(c.length===0){t=t.map(p=>({...p,[r]:s.type==="hasMany"?[]:null}));continue}let u=m(i,s.foreignKey),d=await l.select().from(i).where(inArray(u,c)),g=new Map;for(let p of d){let b=p[s.foreignKey];g.has(b)||g.set(b,[]),g.get(b).push(p);}t=t.map(p=>{let b=p[a],D=g.get(b)||[];return {...p,[r]:s.type==="hasMany"?D:D[0]||null}});break}case "belongsTo":{let a=s.localKey||"id",c=[...new Set(t.map(p=>p[s.foreignKey]).filter(p=>p!=null))];if(c.length===0){t=t.map(p=>({...p,[r]:null}));continue}let u=m(i,a),d=await l.select().from(i).where(inArray(u,c)),g=new Map;for(let p of d){let b=p[a];g.set(b,p);}t=t.map(p=>{let b=p[s.foreignKey];return {...p,[r]:g.get(b)||null}});break}}}return t}function k(l,e){let n=m(l,e.field);switch(e.operator){case "eq":return eq(n,e.value);case "ne":return ne(n,e.value);case "gt":return gt$1(n,e.value);case "gte":return gte(n,e.value);case "lt":return lt$1(n,e.value);case "lte":return lte(n,e.value);case "in":return inArray(n,e.value);case "nin":return notInArray(n,e.value);case "like":return like(n,e.value);case "ilike":return ilike(n,e.value);case "null":return e.value?isNull(n):isNotNull(n);case "between":{let[o,t]=e.value;return between(n,o,t)}default:return}}function z(l){let e=l;if(e._tx)return e._tx;if(e.db)return e.db;let n=e.context?.get?.("db");if(n)return n;throw new Error(`Database not configured. Either:
1
+ import {t,u,v as v$1,w,x,z as z$2,B as B$1,C,D,E,A as A$1,F as F$1,G as G$1,H as H$1,I as I$1,J as J$1,K as K$1,L as L$1,T,U as U$1,ba,ca,y}from'./chunk-V4YEHNEZ.js';import {b}from'./chunk-DMGP7QDL.js';import {getTableColumns,eq,inArray,between,isNull,isNotNull,ilike,like,notInArray,lte,lt as lt$1,gte,gt as gt$1,ne,and,sql,or,desc,asc}from'drizzle-orm';import {z as z$1}from'zod';function q(l){return l}function h(l){if(!l.model.table)throw new Error(`Model ${l.model.tableName} does not have a table reference`);return l.model.table}function m(l,e){let n=getTableColumns(l),o=n[e];if(!o)throw new Error(`Column '${e}' not found in table. Available columns: ${Object.keys(n).join(", ")}`);return o}async function ve(l,e,n,o){if(!o.table)return e;let t=o.table;switch(o.type){case "hasOne":{let r=o.localKey||"id",s=e[r];if(s==null)return e;let i=m(t,o.foreignKey),a=await l.select().from(t).where(eq(i,s)).limit(1);return {...e,[n]:a[0]||null}}case "hasMany":{let r=o.localKey||"id",s=e[r];if(s==null)return {...e,[n]:[]};let i=m(t,o.foreignKey),a=await l.select().from(t).where(eq(i,s));return {...e,[n]:a}}case "belongsTo":{let r=e[o.foreignKey];if(r==null)return {...e,[n]:null};let s=m(t,o.localKey||"id"),i=await l.select().from(t).where(eq(s,r)).limit(1);return {...e,[n]:i[0]||null}}default:return e}}async function se(l,e,n,o){if(!o?.relations?.length||!n.model.relations)return e;let t={...e};for(let r of o.relations){let s=n.model.relations[r];s&&(t=await ve(l,t,r,s));}return t}async function v(l,e,n,o){if(!e.length||!o?.relations?.length||!n.model.relations)return e;let t=e.map(r=>({...r}));for(let r of o.relations){let s=n.model.relations[r];if(!s||!s.table)continue;let i=s.table;switch(s.type){case "hasOne":case "hasMany":{let a=s.localKey||"id",c=[...new Set(t.map(p=>p[a]).filter(p=>p!=null))];if(c.length===0){t=t.map(p=>({...p,[r]:s.type==="hasMany"?[]:null}));continue}let u=m(i,s.foreignKey),d=await l.select().from(i).where(inArray(u,c)),g=new Map;for(let p of d){let b=p[s.foreignKey];g.has(b)||g.set(b,[]),g.get(b).push(p);}t=t.map(p=>{let b=p[a],D=g.get(b)||[];return {...p,[r]:s.type==="hasMany"?D:D[0]||null}});break}case "belongsTo":{let a=s.localKey||"id",c=[...new Set(t.map(p=>p[s.foreignKey]).filter(p=>p!=null))];if(c.length===0){t=t.map(p=>({...p,[r]:null}));continue}let u=m(i,a),d=await l.select().from(i).where(inArray(u,c)),g=new Map;for(let p of d){let b=p[a];g.set(b,p);}t=t.map(p=>{let b=p[s.foreignKey];return {...p,[r]:g.get(b)||null}});break}}}return t}function k(l,e){let n=m(l,e.field);switch(e.operator){case "eq":return eq(n,e.value);case "ne":return ne(n,e.value);case "gt":return gt$1(n,e.value);case "gte":return gte(n,e.value);case "lt":return lt$1(n,e.value);case "lte":return lte(n,e.value);case "in":return inArray(n,e.value);case "nin":return notInArray(n,e.value);case "like":return like(n,e.value);case "ilike":return ilike(n,e.value);case "null":return e.value?isNull(n):isNotNull(n);case "between":{let[o,t]=e.value;return between(n,o,t)}default:return}}function z(l){let e=l;if(e._tx)return e._tx;if(e.db)return e.db;let n=e.context?.get?.("db");if(n)return n;throw new Error(`Database not configured. Either:
2
2
  1. Set db property: db = myDb;
3
3
  2. Use middleware: c.set("db", myDb);
4
4
  3. Use factory: createDrizzleCrud(db, meta)`)}var S=class extends t{db;useTransaction=false;getDb(){return z(this)}getTable(){return h(this._meta)}getRelatedTable(e){return e.table}async create(e,n){let o=n??this.getDb(),t=this.getTable(),r=this.applyManagedInsertFields(e,"drizzle");return (await o.insert(t).values(r).returning())[0]}async createNested(e,n,o,t,r){let s=r??this.getDb(),i=this.getRelatedTable(o);if(!i)return b().warn(`Related table not found for ${n}. Add 'table' to the relation config.`),[];let a=Array.isArray(t)?t:[t],c=[];for(let u of a){if(typeof u!="object"||u===null)continue;let d={...u,id:crypto.randomUUID(),[o.foreignKey]:e},g=await s.insert(i).values(d).returning();g[0]&&c.push(g[0]);}return c}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 u{db;getDb(){return z(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async read(e,n,o){let t=this.getTable(),r=this.getColumn(this.lookupField),s=this.getSoftDeleteConfig(),i=[eq(r,e)];if(n)for(let[u,d]of Object.entries(n))i.push(eq(this.getColumn(u),d));s.enabled&&i.push(isNull(this.getColumn(s.field)));let a=await this.getDb().select().from(t).where(and(...i)).limit(1);return a[0]?await se(this.getDb(),a[0],this._meta,o):null}},I=class extends v$1{db;useTransaction=false;getDb(){return z(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}getRelatedTable(e){return e.table}async findExisting(e,n,o){let t=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),a=[eq(s,e)];if(n)for(let[u,d]of Object.entries(n))a.push(eq(this.getColumn(u),d));return i.enabled&&a.push(isNull(this.getColumn(i.field))),(await t.select().from(r).where(and(...a)).limit(1))[0]||null}async update(e,n,o,t){let r=t??this.getDb(),s=this.getTable(),i=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),c=[eq(i,e)];if(o)for(let[d,g]of Object.entries(o))c.push(eq(this.getColumn(d),g));return a.enabled&&c.push(isNull(this.getColumn(a.field))),(await r.update(s).set(this.applyManagedUpdateFields(n)).where(and(...c)).returning())[0]||null}async processNestedWrites(e,n,o,t,r){let s=r??this.getDb(),i=this.getRelatedTable(o);if(!i)return b().warn(`Related table not found for ${n}. Add 'table' to the relation config.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]};let a={created:[],updated:[],deleted:[],connected:[],disconnected:[]},c=m(i,o.foreignKey),u=m(i,"id");if(t.create){let d=Array.isArray(t.create)?t.create:[t.create];for(let g of d){if(typeof g!="object"||g===null)continue;let p={...g,id:crypto.randomUUID(),[o.foreignKey]:e},b=await s.insert(i).values(p).returning();b[0]&&a.created.push(b[0]);}}if(t.update)for(let d of t.update){if(!d.id||!(await s.select().from(i).where(and(eq(u,d.id),eq(c,e))).limit(1))[0])continue;let{id:p,...b}=d,D=await s.update(i).set(b).where(eq(u,p)).returning();D[0]&&a.updated.push(D[0]);}if(t.delete)for(let d of t.delete)(await s.delete(i).where(and(eq(u,d),eq(c,e))).returning())[0]&&a.deleted.push(d);if(t.connect)for(let d of t.connect)(await s.update(i).set({[o.foreignKey]:e}).where(eq(u,d)).returning())[0]&&a.connected.push(d);if(t.disconnect)for(let d of t.disconnect)(await s.update(i).set({[o.foreignKey]:null}).where(and(eq(u,d),eq(c,e))).returning())[0]&&a.disconnected.push(d);return a}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},P=class extends w{db;useTransaction=false;getDb(){return z(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}getRelatedTable(e){return e.table}async findForDelete(e,n,o){let t=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),a=[eq(s,e)];if(n)for(let[u,d]of Object.entries(n))a.push(eq(this.getColumn(u),d));return i.enabled&&a.push(isNull(this.getColumn(i.field))),(await t.select().from(r).where(and(...a)).limit(1))[0]||null}async delete(e,n,o){let t=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),a=[eq(s,e)];if(n)for(let[c,u]of Object.entries(n))a.push(eq(this.getColumn(c),u));return i.enabled&&a.push(isNull(this.getColumn(i.field))),i.enabled?(await t.update(r).set({[i.field]:new Date}).where(and(...a)).returning())[0]||null:(await t.delete(r).where(and(...a)).returning())[0]||null}async countRelated(e,n,o,t){let r=t??this.getDb(),s=this.getRelatedTable(o);if(!s)return 0;let i=m(s,o.foreignKey),a=await r.select({count:sql`count(*)`}).from(s).where(eq(i,e));return Number(a[0]?.count)||0}async deleteRelated(e,n,o,t){let r=t??this.getDb(),s=this.getRelatedTable(o);if(!s)return 0;let i=m(s,o.foreignKey);return (await r.delete(s).where(eq(i,e)).returning()).length}async nullifyRelated(e,n,o,t){let r=t??this.getDb(),s=this.getRelatedTable(o);if(!s)return 0;let i=m(s,o.foreignKey);return (await r.update(s).set({[o.foreignKey]:null}).where(eq(i,e)).returning()).length}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},U=class extends x{db;getDb(){return z(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async list(e){let n=this.getTable(),o=[],t=this.getSoftDeleteConfig();if(t.enabled){let y=this.getColumn(t.field);e.options.onlyDeleted?o.push(isNotNull(y)):e.options.withDeleted||o.push(isNull(y));}for(let y of e.filters){let R=k(n,y);R&&o.push(R);}if(e.options.search&&this.searchFields.length>0){let y=this.searchFields.map(R=>{let ne=this.getColumn(R);return sql`LOWER(${ne}) LIKE LOWER(${`%${e.options.search}%`})`});o.push(or(...y));}let r=o.length>0?and(...o):void 0,s=this.getDb(),i=await s.select({count:sql`count(*)`}).from(n).where(r),a=Number(i[0]?.count)||0,c=s.select().from(n).where(r);if(e.options.order_by){let y=this.getColumn(e.options.order_by),R=e.options.order_by_direction==="desc"?desc:asc;c=c.orderBy(R(y));}let u=e.options.page||1,d=e.options.per_page||this.defaultPerPage;c=c.limit(d).offset((u-1)*d);let g=await c,p={relations:e.options.include||[]},b=await v(this.getDb(),g,this._meta,p),D=Math.ceil(a/d);return {result:b,result_info:{page:u,per_page:d,total_count:a,total_pages:D,has_next_page:u<D,has_prev_page:u>1}}}},B=class extends z$2{db;useTransaction=false;getDb(){return z(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async restore(e,n,o){let t=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),a=[eq(s,e)];if(n)for(let[u,d]of Object.entries(n))a.push(eq(this.getColumn(u),d));return a.push(isNotNull(this.getColumn(i.field))),(await t.update(r).set({[i.field]:null}).where(and(...a)).returning())[0]||null}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}};var A=class extends B$1{db;getDb(){return z(this)}getTable(){return h(this._meta)}async batchCreate(e){let n=this.getTable(),o=e.map(r=>this.applyManagedInsertFields(r,"drizzle"));return await this.getDb().insert(n).values(o).returning()}},L=class extends C{db;getDb(){return z(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async batchUpdate(e){let n=this.getTable(),o=this.getColumn(this.lookupField),t=this.getSoftDeleteConfig(),r=[],s=[];for(let i of e){let a=[eq(o,i.id)];t.enabled&&a.push(isNull(this.getColumn(t.field)));let c=await this.getDb().update(n).set(this.applyManagedUpdateFields(i.data)).where(and(...a)).returning();c[0]?r.push(c[0]):s.push(i.id);}return {updated:r,notFound:s}}},K=class extends D{db;getDb(){return z(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async batchDelete(e){let n=this.getTable(),o=this.getColumn(this.lookupField),t=this.getSoftDeleteConfig(),r=[inArray(o,e)];t.enabled&&r.push(isNull(this.getColumn(t.field)));let s;t.enabled?s=await this.getDb().update(n).set({[t.field]:new Date}).where(and(...r)).returning():s=await this.getDb().delete(n).where(and(...r)).returning();let i=s,a=new Set(i.map(u=>String(u[this.lookupField]))),c=e.filter(u=>!a.has(u));return {deleted:i,notFound:c}}},Z=class extends E{db;getDb(){return z(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async batchRestore(e){let n=this.getTable(),o=this.getColumn(this.lookupField),t=this.getSoftDeleteConfig(),r=[inArray(o,e),isNotNull(this.getColumn(t.field))],i=await this.getDb().update(n).set({[t.field]:null}).where(and(...r)).returning(),a=new Set(i.map(u=>String(u[this.lookupField]))),c=e.filter(u=>!a.has(u));return {restored:i,notFound:c}}};var Q=class extends A$1{db;getDb(){return z(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async findExisting(e){let n=this.getTable(),o=this.getUpsertKeys(),t=this.getSoftDeleteConfig(),r=[];for(let i of o){let a=e[i];a!==void 0&&r.push(eq(this.getColumn(i),a));}return t.enabled&&r.push(isNull(this.getColumn(t.field))),r.length===0?null:(await this.getDb().select().from(n).where(and(...r)).limit(1))[0]||null}async create(e){let n=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(n).values(o).returning())[0]}async update(e,n){let o=this.getTable(),t=this._meta.model.primaryKeys[0],r=e[t];return (await this.getDb().update(o).set(this.applyManagedUpdateFields(n)).where(eq(this.getColumn(t),r)).returning())[0]}async nativeUpsert(e,n){let o=this.getTable(),t=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s=this.getSoftDeleteConfig(),i=this.getTimestampsConfig(),a=this.applyManagedInsertFields(e,"drizzle"),c={};for(let[g,p]of Object.entries(e))!t.includes(g)&&g!==r&&(this.createOnlyFields?.includes(g)||(c[g]=p));i.enabled&&(c[i.updatedAt]=Date.now());let u=t.map(g=>this.getColumn(g)),d;s.enabled&&(d=isNull(this.getColumn(s.field)));try{return {data:(await this.getDb().insert(o).values(a).onConflictDoUpdate({target:u,set:Object.keys(c).length>0?c:{[r]:sql`${this.getColumn(r)}`},where:d}).returning())[0],created:!1}}catch(g){if(g instanceof Error&&g.message.includes("onConflictDoUpdate"))try{return {data:(await this.getDb().insert(o).values(a).onDuplicateKeyUpdate({set:Object.keys(c).length>0?c:{[r]:sql`${this.getColumn(r)}`}}).returning())[0],created:!1}}catch{return this.performStandardUpsert(e,n)}throw g}}},F=class extends F$1{db;getDb(){return z(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async findExisting(e){let n=this.getTable(),o=this.getUpsertKeys(),t=[];for(let s of o){let i=e[s];i!==void 0&&t.push(eq(this.getColumn(s),i));}return t.length===0?null:(await this.getDb().select().from(n).where(and(...t)).limit(1))[0]||null}async create(e){let n=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(n).values(o).returning())[0]}async update(e,n){let o=this.getTable(),t=this._meta.model.primaryKeys[0],r=e[t];return (await this.getDb().update(o).set(this.applyManagedUpdateFields(n)).where(eq(this.getColumn(t),r)).returning())[0]}async nativeBatchUpsert(e,n){if(e.length===0)return {items:[],createdCount:0,updatedCount:0,totalCount:0};let o=this.getTable(),t=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s=this.getTimestampsConfig(),i=e.map(d=>this.applyManagedInsertFields(d,"drizzle")),a={},c=e[0];for(let d of Object.keys(c))!t.includes(d)&&d!==r&&(this.createOnlyFields?.includes(d)||(a[d]=sql`excluded.${sql.identifier(d)}`));s.enabled&&(a[s.updatedAt]=Date.now());let u=t.map(d=>this.getColumn(d));try{let g=await this.getDb().insert(o).values(i).onConflictDoUpdate({target:u,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(d){if(d instanceof Error&&d.message.includes("onConflictDoUpdate"))try{let p=await this.getDb().insert(o).values(i).onDuplicateKeyUpdate({set:Object.keys(a).length>0?a:{[r]:sql`${this.getColumn(r)}`}}).returning();return {items:p.map((b,D)=>({data:b,created:!1,index:D})),createdCount:0,updatedCount:p.length,totalCount:p.length}}catch{return this.performStandardBatchUpsert(e,n)}throw d}}},Ie=class extends G$1{db;getDb(){return z(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async recordExists(e){let n=this.getTable(),o=await this.getDb().select({count:sql`count(*)`}).from(n).where(eq(this.getColumn("id"),e));return Number(o[0]?.count)>0}},Pe=class extends H$1{},Ue=class extends I$1{},Be=class extends J$1{db;getDb(){return z(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async rollback(e,n,o){let t=this.getTable(),r=this.getVersioningConfig().field;return (await this.getDb().update(t).set({...n,[r]:o}).where(eq(this.getColumn("id"),e)).returning())[0]}},V=class extends K$1{db;getDb(){return z(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async aggregate(e){let n=this.getTable(),o=[],t=this.getSoftDeleteConfig();if(t.enabled){let{query:i}=await this.getValidatedData();i?.withDeleted===true||i?.withDeleted==="true"||o.push(isNull(this.getColumn(t.field)));}if(e.filters)for(let[i,a]of Object.entries(e.filters))if(typeof a=="object"&&a!==null)for(let[c,u]of Object.entries(a)){let d=k(n,{field:i,operator:c,value:u});d&&o.push(d);}else o.push(eq(this.getColumn(i),a));let r=o.length>0?and(...o):void 0,s=await this.getDb().select().from(n).where(r);return L$1(s,e)}},X=class extends T{db;getDb(){return z(this)}useNativeSearch=false;vectorColumn;vectorConfig="english";getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async search(e,n){let o=this.getTable(),t=[],r=this.getSoftDeleteConfig();r.enabled&&(n.options.onlyDeleted?t.push(isNotNull(this.getColumn(r.field))):n.options.withDeleted||t.push(isNull(this.getColumn(r.field))));for(let C of n.filters){let w=k(o,C);w&&t.push(w);}let s=this.getSearchableFields(),i=e.fields||Object.keys(s);if(this.useNativeSearch&&this.vectorColumn){let C=this.getColumn(this.vectorColumn),w=e.mode==="phrase"?sql`phraseto_tsquery(${this.vectorConfig}, ${e.query})`:e.mode==="all"?sql`plainto_tsquery(${this.vectorConfig}, ${e.query})`:sql`to_tsquery(${this.vectorConfig}, ${e.query.split(/\s+/).join(" | ")})`;t.push(sql`${C} @@ ${w}`);}else {let C=i.map(w=>{try{let Ne=this.getColumn(w);return sql`LOWER(CAST(${Ne} AS TEXT)) LIKE LOWER(${`%${e.query}%`})`}catch{return}}).filter(w=>w!==void 0);C.length>0&&(e.mode==="all"?t.push(and(...C)):t.push(or(...C)));}let a=t.length>0?and(...t):void 0,c=await this.getDb().select({count:sql`count(*)`}).from(o).where(a),u=Number(c[0]?.count)||0,d=this.getDb().select().from(o).where(a);if(n.options.order_by){let C=this.getColumn(n.options.order_by),w=n.options.order_by_direction==="desc"?desc:asc;d=d.orderBy(w(C));}let g=n.options.page||1,p=n.options.per_page||this.defaultPerPage;d=d.limit(p).offset((g-1)*p);let b=await d,D=U$1(b,e,s),y={relations:n.options.include||[]},R=D.map(C=>C.item),ne=await v(this.getDb(),R,this._meta,y);return {items:D.map((C,w)=>({...C,item:ne[w]})),totalCount:u}}},G=class extends ba{db;getDb(){return z(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async list(e){let n=this.getTable(),o=[],t=this.getSoftDeleteConfig();if(t.enabled){let D=this.getColumn(t.field);e.options.onlyDeleted?o.push(isNotNull(D)):e.options.withDeleted||o.push(isNull(D));}for(let D of e.filters){let y=k(n,D);y&&o.push(y);}if(e.options.search&&this.searchFields.length>0){let D=this.searchFields.map(y=>{let R=this.getColumn(y);return sql`LOWER(${R}) LIKE LOWER(${`%${e.options.search}%`})`});o.push(or(...D));}let r=o.length>0?and(...o):void 0,s=await this.getDb().select({count:sql`count(*)`}).from(n).where(r),i=Number(s[0]?.count)||0,a=this.getDb().select().from(n).where(r);if(e.options.order_by){let D=this.getColumn(e.options.order_by),y=e.options.order_by_direction==="desc"?desc:asc;a=a.orderBy(y(D));}let c=e.options.page||1,u=e.options.per_page||this.defaultPerPage;a=a.limit(u).offset((c-1)*u);let d=await a,g={relations:e.options.include||[]},p=await v(this.getDb(),d,this._meta,g),b=Math.ceil(i/u);return {result:p,result_info:{page:c,per_page:u,total_count:i,total_pages:b,has_next_page:c<b,has_prev_page:c>1}}}},H=class extends ca{db;getDb(){return z(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async findExisting(e){let n=this.getTable(),o=this.getUpsertKeys(),t=this.getSoftDeleteConfig(),r=[];for(let i of o){let a=e[i];a!==void 0&&r.push(eq(this.getColumn(i),a));}return t.enabled&&r.push(isNull(this.getColumn(t.field))),r.length===0?null:(await this.getDb().select().from(n).where(and(...r)).limit(1))[0]||null}async create(e){let n=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(n).values(o).returning())[0]}async update(e,n){let o=this.getTable(),t=this._meta.model.primaryKeys[0],r=e[t];return (await this.getDb().update(o).set(this.applyManagedUpdateFields(n)).where(eq(this.getColumn(t),r)).returning())[0]}},J=class extends y{db;getDb(){return z(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}generateId(){return crypto.randomUUID()}async findSource(e,n){let o=this.getTable(),t=this.getColumn(this.lookupField),r=this.getSoftDeleteConfig(),s=[eq(t,e)];if(n)for(let[a,c]of Object.entries(n))s.push(eq(this.getColumn(a),c));r.enabled&&s.push(isNull(this.getColumn(r.field)));let i=await this.getDb().select().from(o).where(and(...s)).limit(1);return i[0]?i[0]:null}async createClone(e){let n=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle",()=>this.generateId());return (await this.getDb().insert(n).values(o).returning())[0]}};function en(l,e){return {Create:class extends S{_meta=e;db=l},Read:class extends _{_meta=e;db=l},Update:class extends I{_meta=e;db=l},Delete:class extends P{_meta=e;db=l},List:class extends U{_meta=e;db=l},Restore:class extends B{_meta=e;db=l},Upsert:class extends Q{_meta=e;db=l},BatchCreate:class extends A{_meta=e;db=l},BatchUpdate:class extends L{_meta=e;db=l},BatchDelete:class extends K{_meta=e;db=l},BatchRestore:class extends Z{_meta=e;db=l},BatchUpsert:class extends F{_meta=e;db=l}}}var ee=null,Qe=false,Y=null;async function te(){if(Qe){if(Y)throw Y;return ee}Qe=true;try{return ee=await import('drizzle-zod'),ee}catch{throw Y=new Error("drizzle-zod is not installed. Please install it: npm install drizzle-zod"),Y}}async function lt(l,e){return (await te()).createSelectSchema(l,e)}async function dt(l,e){return (await te()).createInsertSchema(l,e)}async function ct(l,e){let n=await te();return n.createUpdateSchema?n.createUpdateSchema(l,e):n.createInsertSchema(l,e).partial()}async function ut(l,e){let n=await te(),o=e?.coerceDates!==false,t=o?bt(l):new Set,r=n.createSelectSchema(l,e?.selectRefine),s=n.createInsertSchema(l,e?.insertRefine),i;return n.createUpdateSchema?i=n.createUpdateSchema(l,e?.updateRefine):i=n.createInsertSchema(l,e?.updateRefine).partial(),o&&t.size>0&&(s=Fe(s,t),i=Fe(i,t)),{select:r,insert:s,update:i}}function pt(){return ee!==null}var gt=z$1.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$1.date()),mt=z$1.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$1.date().nullable());function bt(l){let e=new Set,n=l;for(let[o,t]of Object.entries(n)){if(o==="_"||o==="$inferInsert"||o==="$inferSelect")continue;let r=t;if(!r||typeof r!="object")continue;let s=String(r.dataType??"").toLowerCase(),i=String(r.columnType??"").toLowerCase(),a=r.config,c=String(a?.dataType??"").toLowerCase();(s.includes("timestamp")||s.includes("date")||s.includes("datetime")||i.includes("pgtimestamp")||i.includes("pgdate")||i.includes("mysqltimestamp")||i.includes("mysqldate")||i.includes("sqlitetimestamp")||c.includes("timestamp")||c.includes("date"))&&e.add(o);}return e}function Fe(l,e){if(e.size===0)return l;let n=l.shape,o={};for(let[t,r]of Object.entries(n))if(e.has(t)){let s=r.isOptional?.()??false,i=r.isNullable?.()??false,a=gt;(i||s)&&(a=mt),s&&(a=a.optional()),o[t]=a;}else o[t]=r;return z$1.object(o)}var yn={CreateEndpoint:S,ListEndpoint:U,ReadEndpoint:_,UpdateEndpoint:I,DeleteEndpoint:P,RestoreEndpoint:B,BatchCreateEndpoint:A,BatchUpdateEndpoint:L,BatchDeleteEndpoint:K,BatchRestoreEndpoint:Z,BatchUpsertEndpoint:F,SearchEndpoint:X,AggregateEndpoint:V,ExportEndpoint:G,ImportEndpoint:H,UpsertEndpoint:Q,CloneEndpoint:J};export{H as A,J as B,en as C,lt as D,dt as E,ct as F,ut as G,pt as H,yn as I,q as a,h as b,m as c,ve as d,se as e,v as f,k as g,S as h,_ as i,I as j,P as k,U as l,B as m,A as n,L as o,K as p,Z as q,Q as r,F as s,Ie as t,Pe as u,Ue as v,Be as w,V as x,X as y,G as z};
@@ -1 +1 @@
1
- import {b as b$2}from'./chunk-4PBGEU64.js';import {b as b$1}from'./chunk-2M5BM4VD.js';import {e,f as f$1}from'./chunk-FC56WWPB.js';import {z as z$1}from'zod';import {decode,verify}from'hono/jwt';var P=z$1.object({sub:z$1.string().optional(),iss:z$1.string().optional(),aud:z$1.union([z$1.string(),z$1.array(z$1.string())]).optional(),exp:z$1.number().int().optional(),nbf:z$1.number().int().optional(),iat:z$1.number().int().optional(),jti:z$1.string().optional()}).passthrough();function K(e){return P.parse(e)}function S(e){return P.safeParse(e)}z$1.object({id:z$1.string(),tenantId:z$1.string().optional(),organizationId:z$1.string().optional(),userId:z$1.string().optional(),actorUserId:z$1.string().optional(),onBehalfOfUserId:z$1.string().optional(),agentId:z$1.string().optional(),agentRunId:z$1.string().optional(),toolCallId:z$1.string().optional(),source:z$1.enum(["http","agent-mcp","agent-code-mode","workflow","job","system"]),toolName:z$1.string(),input:z$1.unknown(),status:z$1.enum(["pending","approved","rejected","expired"]),createdAt:z$1.iso.datetime(),expiresAt:z$1.iso.datetime(),reason:z$1.string(),approvedBy:z$1.string().optional(),approvedAt:z$1.iso.datetime().optional(),rejectedBy:z$1.string().optional(),rejectedReason:z$1.string().optional()});function f(e$1,t={}){let{clockTolerance:n=0,issuer:s,audience:r,skipTimeValidation:o=false}=t;if(!o){let l=Math.floor(Date.now()/1e3);if(e$1.exp!==void 0&&l>e$1.exp+n)throw new e("Token has expired");if(e$1.nbf!==void 0&&l<e$1.nbf-n)throw new e("Token not yet valid")}if(s!==void 0&&e$1.iss!==s)throw new e("Invalid token issuer");if(r!==void 0){let l=Array.isArray(r)?r:[r],u=Array.isArray(e$1.aud)?e$1.aud:[e$1.aud];if(!l.some(A=>u.includes(A)))throw new e("Invalid token audience")}}function b(e){if(!["HS256","HS384","HS512","RS256","RS384","RS512","ES256","ES384","ES512"].includes(e))throw new Error(`Unsupported algorithm: ${e}`);return e}function J(e){let t=e.req.header("Authorization");if(!t)return null;let n=t.split(" ");return n.length!==2||n[0].toLowerCase()!=="bearer"?null:n[1]}function W(e){return {id:String(e.sub||e.id||""),email:e.email,roles:e.roles||e.role,permissions:e.permissions,metadata:e.metadata}}function E(e$1){let t=b(e$1.algorithm||"HS256"),n=e$1.clockTolerance||0,s=e$1.extractToken||J,r=e$1.extractUser||W;return async(o,l)=>{let u=s(o);if(!u)throw new e("Missing authentication token");let h=decode(u);if(!h||!h.header)throw new e("Invalid token format");if(h.header.alg!==t)throw new e("Invalid token algorithm");let A;try{A=await verify(u,e$1.secret,t);}catch(c){if(c instanceof Error){if(c.message.includes("expired")||c.name==="JwtTokenExpired")throw new e("Token has expired");if(c.message.includes("signature")||c.name==="JwtTokenSignatureMismatched")throw new e("Invalid token signature");if(c.message.includes("not valid yet")||c.name==="JwtTokenNotYetValid")throw new e("Token not yet valid")}throw new e("Invalid token")}let m=A;f(m,{clockTolerance:n,issuer:e$1.issuer,audience:e$1.audience});let p=r(m);o.set("userId",p.id),o.set("user",p),o.set("roles",p.roles||[]),o.set("permissions",p.permissions||[]),o.set("authType","jwt"),await l();}}async function O(e$1,t){let n=b(t.algorithm||"HS256"),s=t.clockTolerance||0,r=decode(e$1);if(!r||!r.header)throw new e("Invalid token format");if(r.header.alg!==n)throw new e("Invalid token algorithm");let o;try{o=await verify(e$1,t.secret,n);}catch(u){if(u instanceof Error){if(u.message.includes("expired")||u.name==="JwtTokenExpired")throw new e("Token has expired");if(u.message.includes("signature")||u.name==="JwtTokenSignatureMismatched")throw new e("Invalid token signature");if(u.message.includes("not valid yet")||u.name==="JwtTokenNotYetValid")throw new e("Token not yet valid")}throw new e("Invalid token")}let l=o;return f(l,{clockTolerance:s,issuer:t.issuer,audience:t.audience}),l}function j(e){try{let t=decode(e);return !t||!t.header||!t.payload?null:{header:t.header,payload:t.payload}}catch{return null}}function w(e$1){if(!e$1)throw new e("Invalid API key");if(!e$1.active)throw new e("API key has been revoked");if(e$1.expiresAt&&new Date>e$1.expiresAt)throw new e("API key has expired");return e$1}async function v(e){let n=new TextEncoder().encode(e),s=await crypto.subtle.digest("SHA-256",n),r=new Uint8Array(s);return Array.from(r).map(o=>o.toString(16).padStart(2,"0")).join("")}function H(e){return {id:e.userId,roles:e.roles,permissions:e.permissions,metadata:{...e.metadata,apiKeyId:e.id,apiKeyName:e.name}}}function M(e,t){return e.req.header(t)||null}function z(e,t){return e.req.query(t)||null}function I(e$1){let t=e$1.headerName||"X-API-Key",n=e$1.queryParam??null,s=e$1.hashKey||v,r=e$1.extractUser||H;return async(o,l)=>{let u=M(o,t);if(!u&&n&&(u=z(o,n)),!u)throw new e("Missing API key");let h=await s(u),A=await e$1.lookupKey(h),m=w(A),p=r(m);o.set("userId",p.id),o.set("user",p),o.set("roles",p.roles||[]),o.set("permissions",p.permissions||[]),o.set("authType","api-key"),e$1.updateLastUsed&&Promise.resolve(e$1.updateLastUsed(m.id)).catch(()=>{}),await l();}}async function N(e,t){let s=await(t.hashKey||v)(e),r=await t.lookupKey(s);return w(r)}function C(e$1){let t=e$1.requireAuth??true,n=e$1.skipPaths||[],s=e$1.unauthorizedMessage||"Unauthorized",r=e$1.authOrder||["jwt","api-key"],o=e$1.jwt?E(e$1.jwt):null,l=e$1.apiKey?I(e$1.apiKey):null;return async(u,h)=>{let A=u.req.path;if(b$1(A,n))return u.set("authType","none"),h();let m=false,p=null;for(let c of r)try{if(c==="jwt"&&o&&u.req.header("Authorization")?.toLowerCase().startsWith("bearer ")){await o(u,async()=>{}),m=!0;break}if(c==="api-key"&&l){let y=e$1.apiKey?.headerName||"X-API-Key",R=e$1.apiKey?.queryParam;if(u.req.header(y)||R&&u.req.query(R)){await l(u,async()=>{}),m=!0;break}}}catch(y){p=y instanceof Error?y:new Error(String(y));}if(!m){if(t)throw p instanceof e?p:new e(s);u.set("authType","none");}await h();}}function V(e){return C({...e,requireAuth:false})}function L(e){return C({...e,requireAuth:true})}var T=class extends b$2{requiresAuth=true;requiredRoles;requiredPermissions;requireAllRoles=false;async authorize(t,n){return true}getUser(){let n=this.getContext().var.user;if(!n)throw new e("Authentication required");return n}getUserOrNull(){return this.getContext().var.user}getUserId(){return this.getUser().id}getUserIdOrNull(){return this.getUserOrNull()?.id}getUserRoles(){return this.getUser().roles||[]}getUserPermissions(){return this.getUser().permissions||[]}hasRole(t){return this.getUserRoles().includes(t)}hasAnyRole(...t){let n=this.getUserRoles();return t.some(s=>n.includes(s))}hasAllRoles(...t){let n=this.getUserRoles();return t.every(s=>n.includes(s))}hasPermission(t){return this.getUserPermissions().includes(t)}hasAllPermissions(...t){let n=this.getUserPermissions();return t.every(s=>n.includes(s))}hasAnyPermission(...t){let n=this.getUserPermissions();return t.some(s=>n.includes(s))}async enforceAuth(){let t=this.getContext();if(this.requiresAuth&&!t.var.user)throw new e("Authentication required");let n=t.var.user;if(!n)return;if(this.requiredRoles&&this.requiredRoles.length>0){let r=n.roles||[];if(this.requireAllRoles){if(!this.requiredRoles.every(l=>r.includes(l)))throw new f$1(`Required roles: ${this.requiredRoles.join(" and ")}`)}else if(!this.requiredRoles.some(l=>r.includes(l)))throw new f$1(`Required role: ${this.requiredRoles.join(" or ")}`)}if(this.requiredPermissions&&this.requiredPermissions.length>0){let r=n.permissions||[];if(!this.requiredPermissions.every(l=>r.includes(l)))throw new f$1(`Required permissions: ${this.requiredPermissions.join(", ")}`)}if(!await this.authorize(n,t))throw new f$1("Access denied")}getSchema(){let t=super.getSchema(),n=this.requiresAuth?[{bearerAuth:[]}]:void 0,s={401:{description:"Unauthorized - Authentication required",content:{"application/json":{schema:z$1.object({success:z$1.literal(false),error:z$1.object({code:z$1.literal("UNAUTHORIZED"),message:z$1.string()})})}}},403:{description:"Forbidden - Insufficient permissions",content:{"application/json":{schema:z$1.object({success:z$1.literal(false),error:z$1.object({code:z$1.literal("FORBIDDEN"),message:z$1.string()})})}}}};return {...t,security:n,responses:{...t.responses,...this.requiresAuth?s:{}}}}};function B(e$1){class t extends e$1{requiresAuth=true;requiredRoles;requiredPermissions;requireAllRoles=false;async authorize(s,r){return true}getUser(){let r=this.getContext().var.user;if(!r)throw new e("Authentication required");return r}getUserOrNull(){return this.getContext().var.user}getUserId(){return this.getUser().id}getUserIdOrNull(){return this.getUserOrNull()?.id}getUserRoles(){return this.getUser().roles||[]}getUserPermissions(){return this.getUser().permissions||[]}hasRole(s){let r=this.getUserOrNull();return r?(r.roles||[]).includes(s):false}hasAnyRole(...s){let r=this.getUserOrNull()?.roles||[];return s.some(o=>r.includes(o))}hasAllRoles(...s){let r=this.getUserOrNull()?.roles||[];return s.every(o=>r.includes(o))}hasPermission(s){let r=this.getUserOrNull();return r?(r.permissions||[]).includes(s):false}hasAllPermissions(...s){let r=this.getUserOrNull()?.permissions||[];return s.every(o=>r.includes(o))}hasAnyPermission(...s){let r=this.getUserOrNull()?.permissions||[];return s.some(o=>r.includes(o))}async enforceAuth(){let s=this.getContext();if(this.requiresAuth&&!s.var.user)throw new e("Authentication required");let r=s.var.user;if(!r)return;if(this.requiredRoles&&this.requiredRoles.length>0){let l=r.roles||[];if(this.requireAllRoles){if(!this.requiredRoles.every(h=>l.includes(h)))throw new f$1(`Required roles: ${this.requiredRoles.join(" and ")}`)}else if(!this.requiredRoles.some(h=>l.includes(h)))throw new f$1(`Required role: ${this.requiredRoles.join(" or ")}`)}if(this.requiredPermissions&&this.requiredPermissions.length>0){let l=r.permissions||[];if(!this.requiredPermissions.every(h=>l.includes(h)))throw new f$1(`Required permissions: ${this.requiredPermissions.join(", ")}`)}if(!await this.authorize(r,s))throw new f$1("Access denied")}getSchema(){let s=super.getSchema(),r=this.requiresAuth?[{bearerAuth:[]}]:void 0,o={401:{description:"Unauthorized - Authentication required",content:{"application/json":{schema:z$1.object({success:z$1.literal(false),error:z$1.object({code:z$1.literal("UNAUTHORIZED"),message:z$1.string()})})}}},403:{description:"Forbidden - Insufficient permissions",content:{"application/json":{schema:z$1.object({success:z$1.literal(false),error:z$1.object({code:z$1.literal("FORBIDDEN"),message:z$1.string()})})}}}};return {...s,security:r,responses:{...s.responses,...this.requiresAuth?o:{}}}}}return t}export{P as a,K as b,S as c,f as d,E as e,O as f,j as g,w as h,v as i,I as j,N as k,C as l,V as m,L as n,T as o,B as p};
1
+ import {b as b$2}from'./chunk-XI7HT5ZM.js';import {b as b$1}from'./chunk-2M5BM4VD.js';import {e,f as f$1}from'./chunk-FC56WWPB.js';import {z as z$1}from'zod';import {decode,verify}from'hono/jwt';var P=z$1.object({sub:z$1.string().optional(),iss:z$1.string().optional(),aud:z$1.union([z$1.string(),z$1.array(z$1.string())]).optional(),exp:z$1.number().int().optional(),nbf:z$1.number().int().optional(),iat:z$1.number().int().optional(),jti:z$1.string().optional()}).passthrough();function K(e){return P.parse(e)}function S(e){return P.safeParse(e)}z$1.object({id:z$1.string(),tenantId:z$1.string().optional(),organizationId:z$1.string().optional(),userId:z$1.string().optional(),actorUserId:z$1.string().optional(),onBehalfOfUserId:z$1.string().optional(),agentId:z$1.string().optional(),agentRunId:z$1.string().optional(),toolCallId:z$1.string().optional(),source:z$1.enum(["http","agent-mcp","agent-code-mode","workflow","job","system"]),toolName:z$1.string(),input:z$1.unknown(),status:z$1.enum(["pending","approved","rejected","expired"]),createdAt:z$1.iso.datetime(),expiresAt:z$1.iso.datetime(),reason:z$1.string(),approvedBy:z$1.string().optional(),approvedAt:z$1.iso.datetime().optional(),rejectedBy:z$1.string().optional(),rejectedReason:z$1.string().optional()});function f(e$1,t={}){let{clockTolerance:n=0,issuer:s,audience:r,skipTimeValidation:o=false}=t;if(!o){let l=Math.floor(Date.now()/1e3);if(e$1.exp!==void 0&&l>e$1.exp+n)throw new e("Token has expired");if(e$1.nbf!==void 0&&l<e$1.nbf-n)throw new e("Token not yet valid")}if(s!==void 0&&e$1.iss!==s)throw new e("Invalid token issuer");if(r!==void 0){let l=Array.isArray(r)?r:[r],u=Array.isArray(e$1.aud)?e$1.aud:[e$1.aud];if(!l.some(A=>u.includes(A)))throw new e("Invalid token audience")}}function b(e){if(!["HS256","HS384","HS512","RS256","RS384","RS512","ES256","ES384","ES512"].includes(e))throw new Error(`Unsupported algorithm: ${e}`);return e}function J(e){let t=e.req.header("Authorization");if(!t)return null;let n=t.split(" ");return n.length!==2||n[0].toLowerCase()!=="bearer"?null:n[1]}function W(e){return {id:String(e.sub||e.id||""),email:e.email,roles:e.roles||e.role,permissions:e.permissions,metadata:e.metadata}}function E(e$1){let t=b(e$1.algorithm||"HS256"),n=e$1.clockTolerance||0,s=e$1.extractToken||J,r=e$1.extractUser||W;return async(o,l)=>{let u=s(o);if(!u)throw new e("Missing authentication token");let h=decode(u);if(!h||!h.header)throw new e("Invalid token format");if(h.header.alg!==t)throw new e("Invalid token algorithm");let A;try{A=await verify(u,e$1.secret,t);}catch(c){if(c instanceof Error){if(c.message.includes("expired")||c.name==="JwtTokenExpired")throw new e("Token has expired");if(c.message.includes("signature")||c.name==="JwtTokenSignatureMismatched")throw new e("Invalid token signature");if(c.message.includes("not valid yet")||c.name==="JwtTokenNotYetValid")throw new e("Token not yet valid")}throw new e("Invalid token")}let m=A;f(m,{clockTolerance:n,issuer:e$1.issuer,audience:e$1.audience});let p=r(m);o.set("userId",p.id),o.set("user",p),o.set("roles",p.roles||[]),o.set("permissions",p.permissions||[]),o.set("authType","jwt"),await l();}}async function O(e$1,t){let n=b(t.algorithm||"HS256"),s=t.clockTolerance||0,r=decode(e$1);if(!r||!r.header)throw new e("Invalid token format");if(r.header.alg!==n)throw new e("Invalid token algorithm");let o;try{o=await verify(e$1,t.secret,n);}catch(u){if(u instanceof Error){if(u.message.includes("expired")||u.name==="JwtTokenExpired")throw new e("Token has expired");if(u.message.includes("signature")||u.name==="JwtTokenSignatureMismatched")throw new e("Invalid token signature");if(u.message.includes("not valid yet")||u.name==="JwtTokenNotYetValid")throw new e("Token not yet valid")}throw new e("Invalid token")}let l=o;return f(l,{clockTolerance:s,issuer:t.issuer,audience:t.audience}),l}function j(e){try{let t=decode(e);return !t||!t.header||!t.payload?null:{header:t.header,payload:t.payload}}catch{return null}}function w(e$1){if(!e$1)throw new e("Invalid API key");if(!e$1.active)throw new e("API key has been revoked");if(e$1.expiresAt&&new Date>e$1.expiresAt)throw new e("API key has expired");return e$1}async function v(e){let n=new TextEncoder().encode(e),s=await crypto.subtle.digest("SHA-256",n),r=new Uint8Array(s);return Array.from(r).map(o=>o.toString(16).padStart(2,"0")).join("")}function H(e){return {id:e.userId,roles:e.roles,permissions:e.permissions,metadata:{...e.metadata,apiKeyId:e.id,apiKeyName:e.name}}}function M(e,t){return e.req.header(t)||null}function z(e,t){return e.req.query(t)||null}function I(e$1){let t=e$1.headerName||"X-API-Key",n=e$1.queryParam??null,s=e$1.hashKey||v,r=e$1.extractUser||H;return async(o,l)=>{let u=M(o,t);if(!u&&n&&(u=z(o,n)),!u)throw new e("Missing API key");let h=await s(u),A=await e$1.lookupKey(h),m=w(A),p=r(m);o.set("userId",p.id),o.set("user",p),o.set("roles",p.roles||[]),o.set("permissions",p.permissions||[]),o.set("authType","api-key"),e$1.updateLastUsed&&Promise.resolve(e$1.updateLastUsed(m.id)).catch(()=>{}),await l();}}async function N(e,t){let s=await(t.hashKey||v)(e),r=await t.lookupKey(s);return w(r)}function C(e$1){let t=e$1.requireAuth??true,n=e$1.skipPaths||[],s=e$1.unauthorizedMessage||"Unauthorized",r=e$1.authOrder||["jwt","api-key"],o=e$1.jwt?E(e$1.jwt):null,l=e$1.apiKey?I(e$1.apiKey):null;return async(u,h)=>{let A=u.req.path;if(b$1(A,n))return u.set("authType","none"),h();let m=false,p=null;for(let c of r)try{if(c==="jwt"&&o&&u.req.header("Authorization")?.toLowerCase().startsWith("bearer ")){await o(u,async()=>{}),m=!0;break}if(c==="api-key"&&l){let y=e$1.apiKey?.headerName||"X-API-Key",R=e$1.apiKey?.queryParam;if(u.req.header(y)||R&&u.req.query(R)){await l(u,async()=>{}),m=!0;break}}}catch(y){p=y instanceof Error?y:new Error(String(y));}if(!m){if(t)throw p instanceof e?p:new e(s);u.set("authType","none");}await h();}}function V(e){return C({...e,requireAuth:false})}function L(e){return C({...e,requireAuth:true})}var T=class extends b$2{requiresAuth=true;requiredRoles;requiredPermissions;requireAllRoles=false;async authorize(t,n){return true}getUser(){let n=this.getContext().var.user;if(!n)throw new e("Authentication required");return n}getUserOrNull(){return this.getContext().var.user}getUserId(){return this.getUser().id}getUserIdOrNull(){return this.getUserOrNull()?.id}getUserRoles(){return this.getUser().roles||[]}getUserPermissions(){return this.getUser().permissions||[]}hasRole(t){return this.getUserRoles().includes(t)}hasAnyRole(...t){let n=this.getUserRoles();return t.some(s=>n.includes(s))}hasAllRoles(...t){let n=this.getUserRoles();return t.every(s=>n.includes(s))}hasPermission(t){return this.getUserPermissions().includes(t)}hasAllPermissions(...t){let n=this.getUserPermissions();return t.every(s=>n.includes(s))}hasAnyPermission(...t){let n=this.getUserPermissions();return t.some(s=>n.includes(s))}async enforceAuth(){let t=this.getContext();if(this.requiresAuth&&!t.var.user)throw new e("Authentication required");let n=t.var.user;if(!n)return;if(this.requiredRoles&&this.requiredRoles.length>0){let r=n.roles||[];if(this.requireAllRoles){if(!this.requiredRoles.every(l=>r.includes(l)))throw new f$1(`Required roles: ${this.requiredRoles.join(" and ")}`)}else if(!this.requiredRoles.some(l=>r.includes(l)))throw new f$1(`Required role: ${this.requiredRoles.join(" or ")}`)}if(this.requiredPermissions&&this.requiredPermissions.length>0){let r=n.permissions||[];if(!this.requiredPermissions.every(l=>r.includes(l)))throw new f$1(`Required permissions: ${this.requiredPermissions.join(", ")}`)}if(!await this.authorize(n,t))throw new f$1("Access denied")}getSchema(){let t=super.getSchema(),n=this.requiresAuth?[{bearerAuth:[]}]:void 0,s={401:{description:"Unauthorized - Authentication required",content:{"application/json":{schema:z$1.object({success:z$1.literal(false),error:z$1.object({code:z$1.literal("UNAUTHORIZED"),message:z$1.string()})})}}},403:{description:"Forbidden - Insufficient permissions",content:{"application/json":{schema:z$1.object({success:z$1.literal(false),error:z$1.object({code:z$1.literal("FORBIDDEN"),message:z$1.string()})})}}}};return {...t,security:n,responses:{...t.responses,...this.requiresAuth?s:{}}}}};function B(e$1){class t extends e$1{requiresAuth=true;requiredRoles;requiredPermissions;requireAllRoles=false;async authorize(s,r){return true}getUser(){let r=this.getContext().var.user;if(!r)throw new e("Authentication required");return r}getUserOrNull(){return this.getContext().var.user}getUserId(){return this.getUser().id}getUserIdOrNull(){return this.getUserOrNull()?.id}getUserRoles(){return this.getUser().roles||[]}getUserPermissions(){return this.getUser().permissions||[]}hasRole(s){let r=this.getUserOrNull();return r?(r.roles||[]).includes(s):false}hasAnyRole(...s){let r=this.getUserOrNull()?.roles||[];return s.some(o=>r.includes(o))}hasAllRoles(...s){let r=this.getUserOrNull()?.roles||[];return s.every(o=>r.includes(o))}hasPermission(s){let r=this.getUserOrNull();return r?(r.permissions||[]).includes(s):false}hasAllPermissions(...s){let r=this.getUserOrNull()?.permissions||[];return s.every(o=>r.includes(o))}hasAnyPermission(...s){let r=this.getUserOrNull()?.permissions||[];return s.some(o=>r.includes(o))}async enforceAuth(){let s=this.getContext();if(this.requiresAuth&&!s.var.user)throw new e("Authentication required");let r=s.var.user;if(!r)return;if(this.requiredRoles&&this.requiredRoles.length>0){let l=r.roles||[];if(this.requireAllRoles){if(!this.requiredRoles.every(h=>l.includes(h)))throw new f$1(`Required roles: ${this.requiredRoles.join(" and ")}`)}else if(!this.requiredRoles.some(h=>l.includes(h)))throw new f$1(`Required role: ${this.requiredRoles.join(" or ")}`)}if(this.requiredPermissions&&this.requiredPermissions.length>0){let l=r.permissions||[];if(!this.requiredPermissions.every(h=>l.includes(h)))throw new f$1(`Required permissions: ${this.requiredPermissions.join(", ")}`)}if(!await this.authorize(r,s))throw new f$1("Access denied")}getSchema(){let s=super.getSchema(),r=this.requiresAuth?[{bearerAuth:[]}]:void 0,o={401:{description:"Unauthorized - Authentication required",content:{"application/json":{schema:z$1.object({success:z$1.literal(false),error:z$1.object({code:z$1.literal("UNAUTHORIZED"),message:z$1.string()})})}}},403:{description:"Forbidden - Insufficient permissions",content:{"application/json":{schema:z$1.object({success:z$1.literal(false),error:z$1.object({code:z$1.literal("FORBIDDEN"),message:z$1.string()})})}}}};return {...s,security:r,responses:{...s.responses,...this.requiresAuth?o:{}}}}}return t}export{P as a,K as b,S as c,f as d,E as e,O as f,j as g,w as h,v as i,I as j,N as k,C as l,V as m,L as n,T as o,B as p};
@@ -1 +1 @@
1
- import {t,u,v as v$1,w as w$1,x,z as z$1,B as B$1,C as C$1,D as D$1,E as E$1,F as F$1,T as T$1,U as U$1,ba,ca,A as A$1,G as G$1,H as H$1,I as I$1,J as J$1,K as K$1,L as L$1,y as y$1}from'./chunk-VIKT6QQG.js';var E,v;async function Ce(){if(E)return E;try{return E=(await import('pluralize')).default,E}catch{throw new Error('The "pluralize" package is required. Install it with: npm install pluralize')}}async function Fe(){if(v)return v;try{return v=(await import('fastest-levenshtein')).distance,v}catch{throw new Error('The "fastest-levenshtein" package is required. Install it with: npm install fastest-levenshtein')}}async function G(a){return (await Ce()).singular(a)}async function H(a,t){return (await Fe())(a,t)}function ke(a,t){return a[t]}function Ie(a){return typeof a=="object"&&a!==null&&"create"in a&&typeof a.create=="function"}function h(a,t){let e=ke(a,t);return Ie(e)?e:void 0}function X(a){if(typeof a.$transaction!="function")throw new Error("Prisma client does not support $transaction");return a.$transaction.bind(a)}function P(a){if(typeof a=="string"){if(/^-?\d+$/.test(a))return parseInt(a,10);if(/^-?\d+\.\d+$/.test(a))return parseFloat(a);if(a==="true")return true;if(a==="false")return false}return a}function Y(a){let t={};for(let e of a){let o=P(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(P)};break}case "nin":{let n=Array.isArray(e.value)?e.value:[e.value];t[e.field]={notIn:n.map(P)};break}case "like":t[e.field]={contains:String(e.value).replace(/%/g,"")};break;case "ilike":t[e.field]={contains:String(e.value).replace(/%/g,""),mode:"insensitive"};break;case "null":t[e.field]=e.value?null:{not:null};break;case "between":{let[n,s]=e.value;t[e.field]={gte:P(n),lte:P(s)};break}}}return t}var De=500,y=new Map;function Pe(a,t){if(y.size>=De){let e=y.keys().next().value;e!==void 0&&y.delete(e);}y.set(a,t);}var J=new Map;function xe(a,t){J.set(a.toLowerCase(),t),y.delete(a);}function Ae(a){for(let[t,e]of Object.entries(a))xe(t,e);}function Ke(){J.clear(),y.clear();}async function w(a){let t=y.get(a);if(t)return t;let e=J.get(a.toLowerCase());if(e)return Pe(a,e),e;let o=a.replace(/[-_](.)/g,(n,s)=>s.toUpperCase()).replace(/^./,n=>n.toLowerCase());return o=await G(o),Pe(a,o),o}function Ne(a){let t=[];for(let e of Object.keys(a)){if(e.startsWith("$")||e.startsWith("_"))continue;let o=ke(a,e);o&&typeof o=="object"&&"create"in o&&t.push(e);}return t}async function Se(a,t,e=3){if(t.length===0)return [];let o=a.toLowerCase();return (await Promise.all(t.map(async s=>({name:s,distance:await H(o,s.toLowerCase())})))).filter(s=>s.distance<=Math.max(3,a.length/2)).sort((s,r)=>s.distance-r.distance).slice(0,e).map(s=>s.name)}async function M(a,t){let e=await w(t),o=h(a,e);if(!o){let n=Ne(a),s=await Se(e,n),r=`Model '${e}' not found in Prisma client. Table name: '${t}'. `;throw s.length>0&&(r+=`Did you mean: ${s.map(i=>`'${i}'`).join(", ")}? `),n.length>0&&n.length<=10&&(r+=`Available models: ${n.join(", ")}. `),r+=`You can register a custom mapping with: registerPrismaModelMapping('${t}', 'yourModelName')`,new Error(r)}return o}async function Ue(a,t,e,o){let n=await w(o.model),s=h(a,n);if(!s)return t;switch(o.type){case "hasOne":{let r=o.localKey||"id",i=t[r];if(i==null)return {...t,[e]:null};let d=await s.findFirst({where:{[o.foreignKey]:i}});return {...t,[e]:d||null}}case "hasMany":{let r=o.localKey||"id",i=t[r];if(i==null)return {...t,[e]:[]};let d=await s.findMany({where:{[o.foreignKey]:i}});return {...t,[e]:d}}case "belongsTo":{let r=t[o.foreignKey];if(r==null)return {...t,[e]:null};let i=o.localKey||"id",d=await s.findFirst({where:{[i]:r}});return {...t,[e]:d||null}}default:return t}}async function Oe(a,t,e,o){if(!o?.relations?.length||!e.model.relations)return t;let n={...t};for(let s of o.relations){let r=e.model.relations[s];r&&(n=await Ue(a,n,s,r));}return n}async function k(a,t,e,o){if(!t.length||!o?.relations?.length||!e.model.relations)return t;let n=t.map(s=>({...s}));for(let s of o.relations){let r=e.model.relations[s];if(!r)continue;let i=await w(r.model),d=h(a,i);if(d)switch(r.type){case "hasOne":case "hasMany":{let c=r.localKey||"id",u=[...new Set(n.map(m=>m[c]).filter(m=>m!=null))];if(u.length===0){n=n.map(m=>({...m,[s]:r.type==="hasMany"?[]:null}));continue}let l=await d.findMany({where:{[r.foreignKey]:{in:u}}}),g=new Map;for(let m of l){let p=m[r.foreignKey];g.has(p)||g.set(p,[]),g.get(p).push(m);}n=n.map(m=>{let p=m[c],f=g.get(p)||[];return {...m,[s]:r.type==="hasMany"?f:f[0]||null}});break}case "belongsTo":{let c=r.localKey||"id",u=[...new Set(n.map(m=>m[r.foreignKey]).filter(m=>m!=null))];if(u.length===0){n=n.map(m=>({...m,[s]:null}));continue}let l=await d.findMany({where:{[c]:{in:u}}}),g=new Map;for(let m of l){let p=m[c];g.set(p,m);}n=n.map(m=>{let p=m[r.foreignKey];return {...m,[s]:g.get(p)||null}});break}}}return n}async function _(a){let{model:t,filters:e,searchFields:o=[],softDeleteConfig:n,defaultPerPage:s=20,additionalWhere:r={}}=a,i={...Y(e.filters),...r};if(n?.enabled){let{withDeleted:p,onlyDeleted:f}=e.options;f?i[n.field]={not:null}:p||(i[n.field]=null);}if(e.options.search&&o.length>0){let p=o.map(f=>({[f]:{contains:e.options.search,mode:"insensitive"}}));i={...i,OR:p};}let d=await t.count({where:i}),c;e.options.order_by&&(c={[e.options.order_by]:e.options.order_by_direction||"asc"});let u=e.options.page||1,l=e.options.per_page||s,g=await t.findMany({where:i,orderBy:c,skip:(u-1)*l,take:l}),m=Math.ceil(d/l);return {records:g,where:i,totalCount:d,page:u,perPage:l,totalPages:m}}function j(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 C=class extends t{useTransaction=false;async getModel(){return M(this.prisma,this._meta.model.tableName)}async create(t){let e=await this.getModel(),o=this.applyManagedInsertFields(t,"prisma");return await e.create({data:o})}},F=class extends u{async getModel(){return M(this.prisma,this._meta.model.tableName)}async read(t,e,o){let n=await this.getModel(),s={[this.lookupField]:t,...e},r=await n.findFirst({where:s});return r?await Oe(this.prisma,r,this._meta,o):null}},I=class extends v$1{useTransaction=false;async getModel(){return M(this.prisma,this._meta.model.tableName)}async update(t,e,o){let n=await this.getModel(),s={[this.lookupField]:t,...o},r=await n.findFirst({where:s});if(!r)return null;let i=this._meta.model.primaryKeys[0];return await n.update({where:{[i]:r[i]},data:this.applyManagedUpdateFields(e)})}},D=class extends w$1{useTransaction=false;async getModel(){return M(this.prisma,this._meta.model.tableName)}async findForDelete(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),s={[this.lookupField]:t,...e};return n.enabled&&(s[n.field]=null),await o.findFirst({where:s})}async delete(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),s={[this.lookupField]:t,...e};n.enabled&&(s[n.field]=null);let r=await o.findFirst({where:s});if(!r)return null;let i=this._meta.model.primaryKeys[0],d=r[i];return n.enabled?await o.update({where:{[i]:d},data:{[n.field]:new Date}}):await o.delete({where:{[i]:d}})}},A=class extends x{async getModel(){return M(this.prisma,this._meta.model.tableName)}async list(t){let e=await _({model:await this.getModel(),filters:t,searchFields:this.searchFields,softDeleteConfig:this.getSoftDeleteConfig(),defaultPerPage:this.defaultPerPage}),o={relations:t.options.include||[]},n=await k(this.prisma,e.records,this._meta,o);return j(n,e)}};var K=class extends z$1{useTransaction=false;async getModel(){return M(this.prisma,this._meta.model.tableName)}async restore(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),s={[this.lookupField]:t,[n.field]:{not:null},...e},r=await o.findFirst({where:s});if(!r)return null;let i=this._meta.model.primaryKeys[0];return await o.update({where:{[i]:r[i]},data:{[n.field]:null}})}},N=class extends B$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}async batchCreate(t){let e=t.map(n=>this.applyManagedInsertFields(n,"prisma")),o=[];return await X(this.prisma)(async n=>{let s=h(n,await w(this._meta.model.tableName));if(!s)throw new Error(`Model '${this._meta.model.tableName}' not found in Prisma transaction client`);for(let r of e){let i=await s.create({data:r});o.push(i);}}),o}},S=class extends C$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}async batchUpdate(t){let e=await this.getModel(),o=this.getSoftDeleteConfig(),n=this._meta.model.primaryKeys[0],s=[],r=[],i=t.map(l=>l.id),d={[this.lookupField]:{in:i}};o.enabled&&(d[o.field]=null);let c=await e.findMany({where:d}),u=new Map;for(let l of c){let g=l[this.lookupField];u.set(g,l);}for(let l of t){let g=u.get(l.id);if(!g){r.push(l.id);continue}let m=await e.update({where:{[n]:g[n]},data:this.applyManagedUpdateFields(l.data)});s.push(m);}return {updated:s,notFound:r}}},U=class extends D$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}async batchDelete(t){let e=await this.getModel(),o=this.getSoftDeleteConfig(),n=this._meta.model.primaryKeys[0],s=[],r=[],i={[this.lookupField]:{in:t}};o.enabled&&(i[o.field]=null);let d=await e.findMany({where:i}),c=new Map;for(let u of d){let l=u[this.lookupField];c.set(l,u);}for(let u of t)c.has(u)||r.push(u);for(let u of t){let l=c.get(u);if(l)if(o.enabled){let g=await e.update({where:{[n]:l[n]},data:{[o.field]:new Date}});s.push(g);}else {let g=await e.delete({where:{[n]:l[n]}});s.push(g);}}return {deleted:s,notFound:r}}},T=class extends E$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}async batchRestore(t){let e=await this.getModel(),o=this.getSoftDeleteConfig(),n=this._meta.model.primaryKeys[0],s=[],r=[],i={[this.lookupField]:{in:t},[o.field]:{not:null}},d=await e.findMany({where:i}),c=new Map;for(let u of d){let l=u[this.lookupField];c.set(l,u);}for(let u of t){let l=c.get(u);if(!l){r.push(u);continue}let g=await e.update({where:{[n]:l[n]},data:{[o.field]:null}});s.push(g);}return {restored:s,notFound:r}}},B=class extends F$1{useTransaction=true;async getModel(){return M(this.prisma,this._meta.model.tableName)}async findExisting(t){let e=await this.getModel(),o=this.getUpsertKeys(),n={};for(let r of o){let i=t[r];i!==void 0&&(n[r]=i);}return Object.keys(n).length===0?null:await e.findFirst({where:n})||null}async create(t){let e=await this.getModel(),o=this.applyManagedInsertFields(t,"prisma");return await e.create({data:o})}async update(t,e){let o=await this.getModel(),n=this._meta.model.primaryKeys[0];return await o.update({where:{[n]:t[n]},data:this.applyManagedUpdateFields(e)})}async nativeBatchUpsert(t,e){if(t.length===0)return {items:[],createdCount:0,updatedCount:0,totalCount:0};let o=this.getUpsertKeys(),n=this._meta.model.primaryKeys[0],s=this.getTimestampsConfig(),r=async c=>{let u=h(c,await w(this._meta.model.tableName));if(!u)throw new Error(`Model '${this._meta.model.tableName}' not found in Prisma client`);let l=[],g=[];for(let m=0;m<t.length;m++){let p=t[m];try{let f={};for(let b of o){let O=p[b];O!==void 0&&(f[b]=O);}let q=this.applyManagedInsertFields(p,"prisma"),x={};for(let[b,O]of Object.entries(p))!o.includes(b)&&b!==n&&(this.createOnlyFields?.includes(b)||(x[b]=O));s.enabled&&(x[s.updatedAt]=Date.now());let je=await u.upsert({where:f,create:q,update:Object.keys(x).length>0?x:{}});l.push({data:je,created:!1,index:m});}catch(f){if(this.continueOnError)g.push({index:m,error:f instanceof Error?f.message:String(f)});else throw f}}return {results:l,errors:g}},i;this.useTransaction?i=await X(this.prisma)(r):i=await r(this.prisma);let d={items:i.results,createdCount:0,updatedCount:i.results.length,totalCount:i.results.length};return i.errors.length>0&&(d.errors=i.errors),d}};var $=class extends T$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}buildSearchWhere(t,e){let o=Y(e.filters),n=this.getSoftDeleteConfig();if(n.enabled){let{withDeleted:d,onlyDeleted:c}=e.options;c?o[n.field]={not:null}:d||(o[n.field]=null);}let s=this.getSearchableFields(),i=(t.fields||Object.keys(s)).map(d=>({[d]:{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),s=await o.count({where:n}),r=e.options.order_by?{[e.options.order_by]:e.options.order_by_direction||"asc"}:void 0,i=e.options.page||1,d=e.options.per_page||this.defaultPerPage,c=await o.findMany({where:n,orderBy:r,skip:(i-1)*d,take:d}),u=U$1(c,t,this.getSearchableFields()),l={relations:e.options.include||[]},g=u.map(f=>f.item),m=await k(this.prisma,g,this._meta,l);return {items:u.map((f,q)=>({...f,item:m[q]})),totalCount:s}}},L=class extends ba{async getModel(){return M(this.prisma,this._meta.model.tableName)}async list(t){let e=await _({model:await this.getModel(),filters:t,searchFields:this.searchFields,softDeleteConfig:this.getSoftDeleteConfig(),defaultPerPage:this.defaultPerPage}),o={relations:t.options.include||[]},n=await k(this.prisma,e.records,this._meta,o);return j(n,e)}},W=class extends ca{async getModel(){return M(this.prisma,this._meta.model.tableName)}async findExisting(t){let e=await this.getModel(),o=this.getUpsertKeys(),n={};for(let r of o){let i=t[r];i!==void 0&&(n[r]=i);}return Object.keys(n).length===0?null:await e.findFirst({where:n})||null}async create(t){let e=await this.getModel(),o=this.applyManagedInsertFields(t,"prisma");return await e.create({data:o})}async update(t,e){let o=await this.getModel(),n=this._meta.model.primaryKeys[0];return await o.update({where:{[n]:t[n]},data:this.applyManagedUpdateFields(e)})}},V=class extends A$1{useTransaction=false;async getModel(){return M(this.prisma,this._meta.model.tableName)}async findExisting(t){let e=await this.getModel(),o=this.getUpsertKeys(),n={};for(let r of o){let i=t[r];i!==void 0&&(n[r]=i);}return Object.keys(n).length===0?null:await e.findFirst({where:n})||null}async create(t){let e=await this.getModel(),o=this.applyManagedInsertFields(t,"prisma");return await e.create({data:o})}async update(t,e){let o=await this.getModel(),n=this._meta.model.primaryKeys[0];return await o.update({where:{[n]:t[n]},data:this.applyManagedUpdateFields(e)})}async nativeUpsert(t,e){let o=await this.getModel(),n=this.getUpsertKeys(),s=this._meta.model.primaryKeys[0],r=this.getTimestampsConfig(),i={};for(let l of n){let g=t[l];g!==void 0&&(i[l]=g);}let d=this.applyManagedInsertFields(t,"prisma"),c={};for(let[l,g]of Object.entries(t))!n.includes(l)&&l!==s&&(this.createOnlyFields?.includes(l)||(c[l]=g));return r.enabled&&(c[r.updatedAt]=Date.now()),{data:await o.upsert({where:i,create:d,update:Object.keys(c).length>0?c:{}}),created:false}}},Re=class extends G$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}async recordExists(t){return await(await this.getModel()).count({where:{[this.lookupField]:t}})>0}},Ee=class extends H$1{},ve=class extends I$1{},_e=class extends J$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}async rollback(t,e,o){let n=await this.getModel(),s=this.getVersioningConfig().field,r=this._meta.model.primaryKeys[0],i=await n.findFirst({where:{[this.lookupField]:t}});if(!i)throw new Error(`Record not found: ${t}`);return await n.update({where:{[r]:i[r]},data:{...e,[s]:o}})}},Q=class extends K$1{useNativeAggregation=true;async getModel(){return M(this.prisma,this._meta.model.tableName)}async buildAggregateWhere(t){let e={},o=this.getSoftDeleteConfig();if(o.enabled){let{query:n}=await this.getValidatedData();n?.withDeleted===true||n?.withDeleted==="true"||(e[o.field]=null);}if(t.filters)for(let[n,s]of Object.entries(t.filters))if(typeof s=="object"&&s!==null){let r={};for(let[i,d]of Object.entries(s))switch(i){case "eq":r.equals=d;break;case "ne":r.not=d;break;case "gt":r.gt=d;break;case "gte":r.gte=d;break;case "lt":r.lt=d;break;case "lte":r.lte=d;break;case "in":r.in=d;break;case "nin":r.notIn=d;break;default:r[i]=d;}e[n]=r;}else e[n]=s;return e}async aggregate(t){let e=await this.getModel(),o=await this.buildAggregateWhere(t);if(!this.useNativeAggregation||t.having){let n=await e.findMany({where:o});return L$1(n,t)}return t.groupBy?.length?this.aggregateWithGroupBy(e,o,t):this.aggregateSimple(e,o,t)}groupAggregationsByOperation(t){let e={sum:[],avg:[],min:[],max:[],count:[],countDistinct:[]};for(let o of t)switch(o.operation){case "sum":e.sum.push(o.field);break;case "avg":e.avg.push(o.field);break;case "min":e.min.push(o.field);break;case "max":e.max.push(o.field);break;case "count":e.count.push(o.field);break;case "countDistinct":e.countDistinct.push(o.field);break}return e}async aggregateSimple(t,e,o){let n={where:e},s={},r=this.groupAggregationsByOperation(o.aggregations);if(n._count=true,r.sum.length){n._sum={};for(let c of r.sum)n._sum[c]=true;}if(r.avg.length){n._avg={};for(let c of r.avg)n._avg[c]=true;}if(r.min.length){n._min={};for(let c of r.min)n._min[c]=true;}if(r.max.length){n._max={};for(let c of r.max)n._max[c]=true;}let i=await w(this._meta.model.tableName),d=h(this.prisma,i);if(!d)throw new Error(`Model '${i}' not found in Prisma client`);try{let c=await d.aggregate(n);if(c._count!==void 0&&(s.count=typeof c._count=="object"?c._count._all??0:c._count),c._sum&&r.sum.length)for(let u of r.sum){let l=u.charAt(0).toUpperCase()+u.slice(1);s[`sum${l}`]=c._sum[u]??0;}if(c._avg&&r.avg.length)for(let u of r.avg){let l=u.charAt(0).toUpperCase()+u.slice(1);s[`avg${l}`]=c._avg[u]??0;}if(c._min&&r.min.length)for(let u of r.min){let l=u.charAt(0).toUpperCase()+u.slice(1);s[`min${l}`]=c._min[u];}if(c._max&&r.max.length)for(let u of r.max){let l=u.charAt(0).toUpperCase()+u.slice(1);s[`max${l}`]=c._max[u];}return {values:s,groups:[]}}catch{let u=await t.findMany({where:e});return L$1(u,o)}}async aggregateWithGroupBy(t,e,o){let n={by:o.groupBy,where:e},s=this.groupAggregationsByOperation(o.aggregations);if(n._count=true,s.sum.length){n._sum={};for(let d of s.sum)n._sum[d]=true;}if(s.avg.length){n._avg={};for(let d of s.avg)n._avg[d]=true;}if(s.min.length){n._min={};for(let d of s.min)n._min[d]=true;}if(s.max.length){n._max={};for(let d of s.max)n._max[d]=true;}let r=await w(this._meta.model.tableName),i=h(this.prisma,r);if(!i)throw new Error(`Model '${r}' not found in Prisma client`);try{let c=(await i.groupBy(n)).map(l=>{let g={},m={};for(let p of o.groupBy)g[p]=l[p];if(m.count=typeof l._count=="object"?l._count._all??0:l._count??0,l._sum&&s.sum.length)for(let p of s.sum){let f=p.charAt(0).toUpperCase()+p.slice(1);m[`sum${f}`]=l._sum[p]??0;}if(l._avg&&s.avg.length)for(let p of s.avg){let f=p.charAt(0).toUpperCase()+p.slice(1);m[`avg${f}`]=l._avg[p]??0;}if(l._min&&s.min.length)for(let p of s.min){let f=p.charAt(0).toUpperCase()+p.slice(1);m[`min${f}`]=l._min[p];}if(l._max&&s.max.length)for(let p of s.max){let f=p.charAt(0).toUpperCase()+p.slice(1);m[`max${f}`]=l._max[p];}return {key:g,values:m}});return {values:{count:c.reduce((l,g)=>l+(g.values.count||0),0)},groups:c}}catch{let c=await t.findMany({where:e});return L$1(c,o)}}},z=class extends y$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}generateId(){return crypto.randomUUID()}async findSource(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),s={[this.lookupField]:t,...e};n.enabled&&(s[n.field]=null);let r=await o.findFirst({where:s});return r||null}async createClone(t){let e=await this.getModel(),o=this.applyManagedInsertFields(t,"prisma",()=>this.generateId());return await e.create({data:o})}};var ht={CreateEndpoint:C,ListEndpoint:A,ReadEndpoint:F,UpdateEndpoint:I,DeleteEndpoint:D,RestoreEndpoint:K,BatchCreateEndpoint:N,BatchUpdateEndpoint:S,BatchDeleteEndpoint:U,BatchRestoreEndpoint:T,BatchUpsertEndpoint:B,SearchEndpoint:$,AggregateEndpoint:Q,ExportEndpoint:L,ImportEndpoint:W,UpsertEndpoint:V,CloneEndpoint:z};export{xe as a,Ae as b,Ke as c,C as d,F as e,I as f,D as g,A as h,K as i,N as j,S as k,U as l,T as m,B as n,$ as o,L as p,W as q,V as r,Re as s,Ee as t,ve as u,_e as v,Q as w,z as x,ht as y};
1
+ import {t,u,v as v$1,w as w$1,x,z as z$1,B as B$1,C as C$1,D as D$1,E as E$1,F as F$1,T as T$1,U as U$1,ba,ca,A as A$1,G as G$1,H as H$1,I as I$1,J as J$1,K as K$1,L as L$1,y as y$1}from'./chunk-V4YEHNEZ.js';var E,v;async function Ce(){if(E)return E;try{return E=(await import('pluralize')).default,E}catch{throw new Error('The "pluralize" package is required. Install it with: npm install pluralize')}}async function Fe(){if(v)return v;try{return v=(await import('fastest-levenshtein')).distance,v}catch{throw new Error('The "fastest-levenshtein" package is required. Install it with: npm install fastest-levenshtein')}}async function G(a){return (await Ce()).singular(a)}async function H(a,t){return (await Fe())(a,t)}function ke(a,t){return a[t]}function Ie(a){return typeof a=="object"&&a!==null&&"create"in a&&typeof a.create=="function"}function h(a,t){let e=ke(a,t);return Ie(e)?e:void 0}function X(a){if(typeof a.$transaction!="function")throw new Error("Prisma client does not support $transaction");return a.$transaction.bind(a)}function P(a){if(typeof a=="string"){if(/^-?\d+$/.test(a))return parseInt(a,10);if(/^-?\d+\.\d+$/.test(a))return parseFloat(a);if(a==="true")return true;if(a==="false")return false}return a}function Y(a){let t={};for(let e of a){let o=P(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(P)};break}case "nin":{let n=Array.isArray(e.value)?e.value:[e.value];t[e.field]={notIn:n.map(P)};break}case "like":t[e.field]={contains:String(e.value).replace(/%/g,"")};break;case "ilike":t[e.field]={contains:String(e.value).replace(/%/g,""),mode:"insensitive"};break;case "null":t[e.field]=e.value?null:{not:null};break;case "between":{let[n,s]=e.value;t[e.field]={gte:P(n),lte:P(s)};break}}}return t}var De=500,y=new Map;function Pe(a,t){if(y.size>=De){let e=y.keys().next().value;e!==void 0&&y.delete(e);}y.set(a,t);}var J=new Map;function xe(a,t){J.set(a.toLowerCase(),t),y.delete(a);}function Ae(a){for(let[t,e]of Object.entries(a))xe(t,e);}function Ke(){J.clear(),y.clear();}async function w(a){let t=y.get(a);if(t)return t;let e=J.get(a.toLowerCase());if(e)return Pe(a,e),e;let o=a.replace(/[-_](.)/g,(n,s)=>s.toUpperCase()).replace(/^./,n=>n.toLowerCase());return o=await G(o),Pe(a,o),o}function Ne(a){let t=[];for(let e of Object.keys(a)){if(e.startsWith("$")||e.startsWith("_"))continue;let o=ke(a,e);o&&typeof o=="object"&&"create"in o&&t.push(e);}return t}async function Se(a,t,e=3){if(t.length===0)return [];let o=a.toLowerCase();return (await Promise.all(t.map(async s=>({name:s,distance:await H(o,s.toLowerCase())})))).filter(s=>s.distance<=Math.max(3,a.length/2)).sort((s,r)=>s.distance-r.distance).slice(0,e).map(s=>s.name)}async function M(a,t){let e=await w(t),o=h(a,e);if(!o){let n=Ne(a),s=await Se(e,n),r=`Model '${e}' not found in Prisma client. Table name: '${t}'. `;throw s.length>0&&(r+=`Did you mean: ${s.map(i=>`'${i}'`).join(", ")}? `),n.length>0&&n.length<=10&&(r+=`Available models: ${n.join(", ")}. `),r+=`You can register a custom mapping with: registerPrismaModelMapping('${t}', 'yourModelName')`,new Error(r)}return o}async function Ue(a,t,e,o){let n=await w(o.model),s=h(a,n);if(!s)return t;switch(o.type){case "hasOne":{let r=o.localKey||"id",i=t[r];if(i==null)return {...t,[e]:null};let d=await s.findFirst({where:{[o.foreignKey]:i}});return {...t,[e]:d||null}}case "hasMany":{let r=o.localKey||"id",i=t[r];if(i==null)return {...t,[e]:[]};let d=await s.findMany({where:{[o.foreignKey]:i}});return {...t,[e]:d}}case "belongsTo":{let r=t[o.foreignKey];if(r==null)return {...t,[e]:null};let i=o.localKey||"id",d=await s.findFirst({where:{[i]:r}});return {...t,[e]:d||null}}default:return t}}async function Oe(a,t,e,o){if(!o?.relations?.length||!e.model.relations)return t;let n={...t};for(let s of o.relations){let r=e.model.relations[s];r&&(n=await Ue(a,n,s,r));}return n}async function k(a,t,e,o){if(!t.length||!o?.relations?.length||!e.model.relations)return t;let n=t.map(s=>({...s}));for(let s of o.relations){let r=e.model.relations[s];if(!r)continue;let i=await w(r.model),d=h(a,i);if(d)switch(r.type){case "hasOne":case "hasMany":{let c=r.localKey||"id",u=[...new Set(n.map(m=>m[c]).filter(m=>m!=null))];if(u.length===0){n=n.map(m=>({...m,[s]:r.type==="hasMany"?[]:null}));continue}let l=await d.findMany({where:{[r.foreignKey]:{in:u}}}),g=new Map;for(let m of l){let p=m[r.foreignKey];g.has(p)||g.set(p,[]),g.get(p).push(m);}n=n.map(m=>{let p=m[c],f=g.get(p)||[];return {...m,[s]:r.type==="hasMany"?f:f[0]||null}});break}case "belongsTo":{let c=r.localKey||"id",u=[...new Set(n.map(m=>m[r.foreignKey]).filter(m=>m!=null))];if(u.length===0){n=n.map(m=>({...m,[s]:null}));continue}let l=await d.findMany({where:{[c]:{in:u}}}),g=new Map;for(let m of l){let p=m[c];g.set(p,m);}n=n.map(m=>{let p=m[r.foreignKey];return {...m,[s]:g.get(p)||null}});break}}}return n}async function _(a){let{model:t,filters:e,searchFields:o=[],softDeleteConfig:n,defaultPerPage:s=20,additionalWhere:r={}}=a,i={...Y(e.filters),...r};if(n?.enabled){let{withDeleted:p,onlyDeleted:f}=e.options;f?i[n.field]={not:null}:p||(i[n.field]=null);}if(e.options.search&&o.length>0){let p=o.map(f=>({[f]:{contains:e.options.search,mode:"insensitive"}}));i={...i,OR:p};}let d=await t.count({where:i}),c;e.options.order_by&&(c={[e.options.order_by]:e.options.order_by_direction||"asc"});let u=e.options.page||1,l=e.options.per_page||s,g=await t.findMany({where:i,orderBy:c,skip:(u-1)*l,take:l}),m=Math.ceil(d/l);return {records:g,where:i,totalCount:d,page:u,perPage:l,totalPages:m}}function j(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 C=class extends t{useTransaction=false;async getModel(){return M(this.prisma,this._meta.model.tableName)}async create(t){let e=await this.getModel(),o=this.applyManagedInsertFields(t,"prisma");return await e.create({data:o})}},F=class extends u{async getModel(){return M(this.prisma,this._meta.model.tableName)}async read(t,e,o){let n=await this.getModel(),s={[this.lookupField]:t,...e},r=await n.findFirst({where:s});return r?await Oe(this.prisma,r,this._meta,o):null}},I=class extends v$1{useTransaction=false;async getModel(){return M(this.prisma,this._meta.model.tableName)}async update(t,e,o){let n=await this.getModel(),s={[this.lookupField]:t,...o},r=await n.findFirst({where:s});if(!r)return null;let i=this._meta.model.primaryKeys[0];return await n.update({where:{[i]:r[i]},data:this.applyManagedUpdateFields(e)})}},D=class extends w$1{useTransaction=false;async getModel(){return M(this.prisma,this._meta.model.tableName)}async findForDelete(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),s={[this.lookupField]:t,...e};return n.enabled&&(s[n.field]=null),await o.findFirst({where:s})}async delete(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),s={[this.lookupField]:t,...e};n.enabled&&(s[n.field]=null);let r=await o.findFirst({where:s});if(!r)return null;let i=this._meta.model.primaryKeys[0],d=r[i];return n.enabled?await o.update({where:{[i]:d},data:{[n.field]:new Date}}):await o.delete({where:{[i]:d}})}},A=class extends x{async getModel(){return M(this.prisma,this._meta.model.tableName)}async list(t){let e=await _({model:await this.getModel(),filters:t,searchFields:this.searchFields,softDeleteConfig:this.getSoftDeleteConfig(),defaultPerPage:this.defaultPerPage}),o={relations:t.options.include||[]},n=await k(this.prisma,e.records,this._meta,o);return j(n,e)}};var K=class extends z$1{useTransaction=false;async getModel(){return M(this.prisma,this._meta.model.tableName)}async restore(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),s={[this.lookupField]:t,[n.field]:{not:null},...e},r=await o.findFirst({where:s});if(!r)return null;let i=this._meta.model.primaryKeys[0];return await o.update({where:{[i]:r[i]},data:{[n.field]:null}})}},N=class extends B$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}async batchCreate(t){let e=t.map(n=>this.applyManagedInsertFields(n,"prisma")),o=[];return await X(this.prisma)(async n=>{let s=h(n,await w(this._meta.model.tableName));if(!s)throw new Error(`Model '${this._meta.model.tableName}' not found in Prisma transaction client`);for(let r of e){let i=await s.create({data:r});o.push(i);}}),o}},S=class extends C$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}async batchUpdate(t){let e=await this.getModel(),o=this.getSoftDeleteConfig(),n=this._meta.model.primaryKeys[0],s=[],r=[],i=t.map(l=>l.id),d={[this.lookupField]:{in:i}};o.enabled&&(d[o.field]=null);let c=await e.findMany({where:d}),u=new Map;for(let l of c){let g=l[this.lookupField];u.set(g,l);}for(let l of t){let g=u.get(l.id);if(!g){r.push(l.id);continue}let m=await e.update({where:{[n]:g[n]},data:this.applyManagedUpdateFields(l.data)});s.push(m);}return {updated:s,notFound:r}}},U=class extends D$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}async batchDelete(t){let e=await this.getModel(),o=this.getSoftDeleteConfig(),n=this._meta.model.primaryKeys[0],s=[],r=[],i={[this.lookupField]:{in:t}};o.enabled&&(i[o.field]=null);let d=await e.findMany({where:i}),c=new Map;for(let u of d){let l=u[this.lookupField];c.set(l,u);}for(let u of t)c.has(u)||r.push(u);for(let u of t){let l=c.get(u);if(l)if(o.enabled){let g=await e.update({where:{[n]:l[n]},data:{[o.field]:new Date}});s.push(g);}else {let g=await e.delete({where:{[n]:l[n]}});s.push(g);}}return {deleted:s,notFound:r}}},T=class extends E$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}async batchRestore(t){let e=await this.getModel(),o=this.getSoftDeleteConfig(),n=this._meta.model.primaryKeys[0],s=[],r=[],i={[this.lookupField]:{in:t},[o.field]:{not:null}},d=await e.findMany({where:i}),c=new Map;for(let u of d){let l=u[this.lookupField];c.set(l,u);}for(let u of t){let l=c.get(u);if(!l){r.push(u);continue}let g=await e.update({where:{[n]:l[n]},data:{[o.field]:null}});s.push(g);}return {restored:s,notFound:r}}},B=class extends F$1{useTransaction=true;async getModel(){return M(this.prisma,this._meta.model.tableName)}async findExisting(t){let e=await this.getModel(),o=this.getUpsertKeys(),n={};for(let r of o){let i=t[r];i!==void 0&&(n[r]=i);}return Object.keys(n).length===0?null:await e.findFirst({where:n})||null}async create(t){let e=await this.getModel(),o=this.applyManagedInsertFields(t,"prisma");return await e.create({data:o})}async update(t,e){let o=await this.getModel(),n=this._meta.model.primaryKeys[0];return await o.update({where:{[n]:t[n]},data:this.applyManagedUpdateFields(e)})}async nativeBatchUpsert(t,e){if(t.length===0)return {items:[],createdCount:0,updatedCount:0,totalCount:0};let o=this.getUpsertKeys(),n=this._meta.model.primaryKeys[0],s=this.getTimestampsConfig(),r=async c=>{let u=h(c,await w(this._meta.model.tableName));if(!u)throw new Error(`Model '${this._meta.model.tableName}' not found in Prisma client`);let l=[],g=[];for(let m=0;m<t.length;m++){let p=t[m];try{let f={};for(let b of o){let O=p[b];O!==void 0&&(f[b]=O);}let q=this.applyManagedInsertFields(p,"prisma"),x={};for(let[b,O]of Object.entries(p))!o.includes(b)&&b!==n&&(this.createOnlyFields?.includes(b)||(x[b]=O));s.enabled&&(x[s.updatedAt]=Date.now());let je=await u.upsert({where:f,create:q,update:Object.keys(x).length>0?x:{}});l.push({data:je,created:!1,index:m});}catch(f){if(this.continueOnError)g.push({index:m,error:f instanceof Error?f.message:String(f)});else throw f}}return {results:l,errors:g}},i;this.useTransaction?i=await X(this.prisma)(r):i=await r(this.prisma);let d={items:i.results,createdCount:0,updatedCount:i.results.length,totalCount:i.results.length};return i.errors.length>0&&(d.errors=i.errors),d}};var $=class extends T$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}buildSearchWhere(t,e){let o=Y(e.filters),n=this.getSoftDeleteConfig();if(n.enabled){let{withDeleted:d,onlyDeleted:c}=e.options;c?o[n.field]={not:null}:d||(o[n.field]=null);}let s=this.getSearchableFields(),i=(t.fields||Object.keys(s)).map(d=>({[d]:{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),s=await o.count({where:n}),r=e.options.order_by?{[e.options.order_by]:e.options.order_by_direction||"asc"}:void 0,i=e.options.page||1,d=e.options.per_page||this.defaultPerPage,c=await o.findMany({where:n,orderBy:r,skip:(i-1)*d,take:d}),u=U$1(c,t,this.getSearchableFields()),l={relations:e.options.include||[]},g=u.map(f=>f.item),m=await k(this.prisma,g,this._meta,l);return {items:u.map((f,q)=>({...f,item:m[q]})),totalCount:s}}},L=class extends ba{async getModel(){return M(this.prisma,this._meta.model.tableName)}async list(t){let e=await _({model:await this.getModel(),filters:t,searchFields:this.searchFields,softDeleteConfig:this.getSoftDeleteConfig(),defaultPerPage:this.defaultPerPage}),o={relations:t.options.include||[]},n=await k(this.prisma,e.records,this._meta,o);return j(n,e)}},W=class extends ca{async getModel(){return M(this.prisma,this._meta.model.tableName)}async findExisting(t){let e=await this.getModel(),o=this.getUpsertKeys(),n={};for(let r of o){let i=t[r];i!==void 0&&(n[r]=i);}return Object.keys(n).length===0?null:await e.findFirst({where:n})||null}async create(t){let e=await this.getModel(),o=this.applyManagedInsertFields(t,"prisma");return await e.create({data:o})}async update(t,e){let o=await this.getModel(),n=this._meta.model.primaryKeys[0];return await o.update({where:{[n]:t[n]},data:this.applyManagedUpdateFields(e)})}},V=class extends A$1{useTransaction=false;async getModel(){return M(this.prisma,this._meta.model.tableName)}async findExisting(t){let e=await this.getModel(),o=this.getUpsertKeys(),n={};for(let r of o){let i=t[r];i!==void 0&&(n[r]=i);}return Object.keys(n).length===0?null:await e.findFirst({where:n})||null}async create(t){let e=await this.getModel(),o=this.applyManagedInsertFields(t,"prisma");return await e.create({data:o})}async update(t,e){let o=await this.getModel(),n=this._meta.model.primaryKeys[0];return await o.update({where:{[n]:t[n]},data:this.applyManagedUpdateFields(e)})}async nativeUpsert(t,e){let o=await this.getModel(),n=this.getUpsertKeys(),s=this._meta.model.primaryKeys[0],r=this.getTimestampsConfig(),i={};for(let l of n){let g=t[l];g!==void 0&&(i[l]=g);}let d=this.applyManagedInsertFields(t,"prisma"),c={};for(let[l,g]of Object.entries(t))!n.includes(l)&&l!==s&&(this.createOnlyFields?.includes(l)||(c[l]=g));return r.enabled&&(c[r.updatedAt]=Date.now()),{data:await o.upsert({where:i,create:d,update:Object.keys(c).length>0?c:{}}),created:false}}},Re=class extends G$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}async recordExists(t){return await(await this.getModel()).count({where:{[this.lookupField]:t}})>0}},Ee=class extends H$1{},ve=class extends I$1{},_e=class extends J$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}async rollback(t,e,o){let n=await this.getModel(),s=this.getVersioningConfig().field,r=this._meta.model.primaryKeys[0],i=await n.findFirst({where:{[this.lookupField]:t}});if(!i)throw new Error(`Record not found: ${t}`);return await n.update({where:{[r]:i[r]},data:{...e,[s]:o}})}},Q=class extends K$1{useNativeAggregation=true;async getModel(){return M(this.prisma,this._meta.model.tableName)}async buildAggregateWhere(t){let e={},o=this.getSoftDeleteConfig();if(o.enabled){let{query:n}=await this.getValidatedData();n?.withDeleted===true||n?.withDeleted==="true"||(e[o.field]=null);}if(t.filters)for(let[n,s]of Object.entries(t.filters))if(typeof s=="object"&&s!==null){let r={};for(let[i,d]of Object.entries(s))switch(i){case "eq":r.equals=d;break;case "ne":r.not=d;break;case "gt":r.gt=d;break;case "gte":r.gte=d;break;case "lt":r.lt=d;break;case "lte":r.lte=d;break;case "in":r.in=d;break;case "nin":r.notIn=d;break;default:r[i]=d;}e[n]=r;}else e[n]=s;return e}async aggregate(t){let e=await this.getModel(),o=await this.buildAggregateWhere(t);if(!this.useNativeAggregation||t.having){let n=await e.findMany({where:o});return L$1(n,t)}return t.groupBy?.length?this.aggregateWithGroupBy(e,o,t):this.aggregateSimple(e,o,t)}groupAggregationsByOperation(t){let e={sum:[],avg:[],min:[],max:[],count:[],countDistinct:[]};for(let o of t)switch(o.operation){case "sum":e.sum.push(o.field);break;case "avg":e.avg.push(o.field);break;case "min":e.min.push(o.field);break;case "max":e.max.push(o.field);break;case "count":e.count.push(o.field);break;case "countDistinct":e.countDistinct.push(o.field);break}return e}async aggregateSimple(t,e,o){let n={where:e},s={},r=this.groupAggregationsByOperation(o.aggregations);if(n._count=true,r.sum.length){n._sum={};for(let c of r.sum)n._sum[c]=true;}if(r.avg.length){n._avg={};for(let c of r.avg)n._avg[c]=true;}if(r.min.length){n._min={};for(let c of r.min)n._min[c]=true;}if(r.max.length){n._max={};for(let c of r.max)n._max[c]=true;}let i=await w(this._meta.model.tableName),d=h(this.prisma,i);if(!d)throw new Error(`Model '${i}' not found in Prisma client`);try{let c=await d.aggregate(n);if(c._count!==void 0&&(s.count=typeof c._count=="object"?c._count._all??0:c._count),c._sum&&r.sum.length)for(let u of r.sum){let l=u.charAt(0).toUpperCase()+u.slice(1);s[`sum${l}`]=c._sum[u]??0;}if(c._avg&&r.avg.length)for(let u of r.avg){let l=u.charAt(0).toUpperCase()+u.slice(1);s[`avg${l}`]=c._avg[u]??0;}if(c._min&&r.min.length)for(let u of r.min){let l=u.charAt(0).toUpperCase()+u.slice(1);s[`min${l}`]=c._min[u];}if(c._max&&r.max.length)for(let u of r.max){let l=u.charAt(0).toUpperCase()+u.slice(1);s[`max${l}`]=c._max[u];}return {values:s,groups:[]}}catch{let u=await t.findMany({where:e});return L$1(u,o)}}async aggregateWithGroupBy(t,e,o){let n={by:o.groupBy,where:e},s=this.groupAggregationsByOperation(o.aggregations);if(n._count=true,s.sum.length){n._sum={};for(let d of s.sum)n._sum[d]=true;}if(s.avg.length){n._avg={};for(let d of s.avg)n._avg[d]=true;}if(s.min.length){n._min={};for(let d of s.min)n._min[d]=true;}if(s.max.length){n._max={};for(let d of s.max)n._max[d]=true;}let r=await w(this._meta.model.tableName),i=h(this.prisma,r);if(!i)throw new Error(`Model '${r}' not found in Prisma client`);try{let c=(await i.groupBy(n)).map(l=>{let g={},m={};for(let p of o.groupBy)g[p]=l[p];if(m.count=typeof l._count=="object"?l._count._all??0:l._count??0,l._sum&&s.sum.length)for(let p of s.sum){let f=p.charAt(0).toUpperCase()+p.slice(1);m[`sum${f}`]=l._sum[p]??0;}if(l._avg&&s.avg.length)for(let p of s.avg){let f=p.charAt(0).toUpperCase()+p.slice(1);m[`avg${f}`]=l._avg[p]??0;}if(l._min&&s.min.length)for(let p of s.min){let f=p.charAt(0).toUpperCase()+p.slice(1);m[`min${f}`]=l._min[p];}if(l._max&&s.max.length)for(let p of s.max){let f=p.charAt(0).toUpperCase()+p.slice(1);m[`max${f}`]=l._max[p];}return {key:g,values:m}});return {values:{count:c.reduce((l,g)=>l+(g.values.count||0),0)},groups:c}}catch{let c=await t.findMany({where:e});return L$1(c,o)}}},z=class extends y$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}generateId(){return crypto.randomUUID()}async findSource(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),s={[this.lookupField]:t,...e};n.enabled&&(s[n.field]=null);let r=await o.findFirst({where:s});return r||null}async createClone(t){let e=await this.getModel(),o=this.applyManagedInsertFields(t,"prisma",()=>this.generateId());return await e.create({data:o})}};var ht={CreateEndpoint:C,ListEndpoint:A,ReadEndpoint:F,UpdateEndpoint:I,DeleteEndpoint:D,RestoreEndpoint:K,BatchCreateEndpoint:N,BatchUpdateEndpoint:S,BatchDeleteEndpoint:U,BatchRestoreEndpoint:T,BatchUpsertEndpoint:B,SearchEndpoint:$,AggregateEndpoint:Q,ExportEndpoint:L,ImportEndpoint:W,UpsertEndpoint:V,CloneEndpoint:z};export{xe as a,Ae as b,Ke as c,C as d,F as e,I as f,D as g,A as h,K as i,N as j,S as k,U as l,T as m,B as n,$ as o,L as p,W as q,V as r,Re as s,Ee as t,ve as u,_e as v,Q as w,z as x,ht as y};
@@ -1 +1 @@
1
- import {e,f}from'./chunk-FHABLABR.js';import {c}from'./chunk-GBQQ3YQX.js';var a=class{logs=[];async store(t){this.logs.push(t);}async getByRecordId(t,e,r){let n=this.logs.filter(s=>s.tableName===t&&s.recordId===e),i=r?.offset||0,o=r?.limit||n.length;return n.slice(i,i+o)}async getAll(t){let e=[...this.logs];t?.tableName&&(e=e.filter(i=>i.tableName===t.tableName)),t?.action&&(e=e.filter(i=>i.action===t.action)),t?.userId&&(e=e.filter(i=>i.userId===t.userId)),t?.startDate&&(e=e.filter(i=>i.timestamp>=t.startDate)),t?.endDate&&(e=e.filter(i=>i.timestamp<=t.endDate));let r=t?.offset||0,n=t?.limit||e.length;return e.slice(r,r+n)}getAllLogs(){return [...this.logs]}clear(){this.logs=[];}},l=c("auditStorage",()=>new a);function A(d){l.set(d);}function R(){return l.getRequired()}var u=class{config;storage;constructor(t,e$1,r){this.config=e(t),this.storage=l.resolve(r,e$1);}getStorage(){if(!this.storage)throw new Error("Audit storage not configured. Pass storage explicitly or inject auditStorage with createCrudMiddleware().");return this.storage}isEnabled(t){return this.config.enabled&&this.config.actions.includes(t)}async logCreate(t,e,r,n,i){if(!this.isEnabled("create"))return;let o=this.createEntry("create",t,e,n,i);this.config.storeRecord&&(o.record=this.filterFields(r)),await this.getStorage().store(o);}async logUpdate(t,e,r,n,i,o){if(!this.isEnabled("update"))return;let s=this.createEntry("update",t,e,i,o);this.config.storeRecord&&(s.record=this.filterFields(n)),this.config.storePreviousRecord&&(s.previousRecord=this.filterFields(r)),this.config.trackChanges&&(s.changes=f(r,n,this.config.excludeFields)),await this.getStorage().store(s);}async logDelete(t,e,r,n,i){if(!this.isEnabled("delete"))return;let o=this.createEntry("delete",t,e,n,i);this.config.storePreviousRecord&&(o.previousRecord=this.filterFields(r)),await this.getStorage().store(o);}async logRestore(t,e,r,n,i){if(!this.isEnabled("restore"))return;let o=this.createEntry("restore",t,e,n,i);this.config.storeRecord&&(o.record=this.filterFields(r)),await this.getStorage().store(o);}async logUpsert(t,e,r,n,i,o,s){if(!this.isEnabled("upsert"))return;let g=this.createEntry("upsert",t,e,o,{...s,created:i});this.config.storeRecord&&(g.record=this.filterFields(r)),this.config.storePreviousRecord&&n&&(g.previousRecord=this.filterFields(n)),this.config.trackChanges&&n&&(g.changes=f(n,r,this.config.excludeFields)),await this.getStorage().store(g);}async logBatch(t,e,r,n,i){if(this.isEnabled(t))for(let o of r){let s=this.createEntry(t,e,o.recordId,n,i);this.config.storeRecord&&o.record&&(s.record=this.filterFields(o.record)),this.config.storePreviousRecord&&o.previousRecord&&(s.previousRecord=this.filterFields(o.previousRecord)),this.config.trackChanges&&o.previousRecord&&o.record&&(s.changes=f(o.previousRecord,o.record,this.config.excludeFields)),await this.getStorage().store(s);}}createEntry(t,e,r,n,i){return {id:crypto.randomUUID(),timestamp:new Date,action:t,tableName:e,recordId:r,userId:n,metadata:i}}filterFields(t){if(this.config.excludeFields.length===0)return t;let e={};for(let[r,n]of Object.entries(t))this.config.excludeFields.includes(r)||(e[r]=n);return e}};function b(d,t,e){return new u(d,t,e)}export{a,l as b,A as c,R as d,u as e,b as f};
1
+ import {e,f}from'./chunk-KUFOENSK.js';import {c}from'./chunk-GBQQ3YQX.js';var a=class{logs=[];async store(t){this.logs.push(t);}async getByRecordId(t,e,r){let n=this.logs.filter(s=>s.tableName===t&&s.recordId===e),i=r?.offset||0,o=r?.limit||n.length;return n.slice(i,i+o)}async getAll(t){let e=[...this.logs];t?.tableName&&(e=e.filter(i=>i.tableName===t.tableName)),t?.action&&(e=e.filter(i=>i.action===t.action)),t?.userId&&(e=e.filter(i=>i.userId===t.userId)),t?.startDate&&(e=e.filter(i=>i.timestamp>=t.startDate)),t?.endDate&&(e=e.filter(i=>i.timestamp<=t.endDate));let r=t?.offset||0,n=t?.limit||e.length;return e.slice(r,r+n)}getAllLogs(){return [...this.logs]}clear(){this.logs=[];}},l=c("auditStorage",()=>new a);function A(d){l.set(d);}function R(){return l.getRequired()}var u=class{config;storage;constructor(t,e$1,r){this.config=e(t),this.storage=l.resolve(r,e$1);}getStorage(){if(!this.storage)throw new Error("Audit storage not configured. Pass storage explicitly or inject auditStorage with createCrudMiddleware().");return this.storage}isEnabled(t){return this.config.enabled&&this.config.actions.includes(t)}async logCreate(t,e,r,n,i){if(!this.isEnabled("create"))return;let o=this.createEntry("create",t,e,n,i);this.config.storeRecord&&(o.record=this.filterFields(r)),await this.getStorage().store(o);}async logUpdate(t,e,r,n,i,o){if(!this.isEnabled("update"))return;let s=this.createEntry("update",t,e,i,o);this.config.storeRecord&&(s.record=this.filterFields(n)),this.config.storePreviousRecord&&(s.previousRecord=this.filterFields(r)),this.config.trackChanges&&(s.changes=f(r,n,this.config.excludeFields)),await this.getStorage().store(s);}async logDelete(t,e,r,n,i){if(!this.isEnabled("delete"))return;let o=this.createEntry("delete",t,e,n,i);this.config.storePreviousRecord&&(o.previousRecord=this.filterFields(r)),await this.getStorage().store(o);}async logRestore(t,e,r,n,i){if(!this.isEnabled("restore"))return;let o=this.createEntry("restore",t,e,n,i);this.config.storeRecord&&(o.record=this.filterFields(r)),await this.getStorage().store(o);}async logUpsert(t,e,r,n,i,o,s){if(!this.isEnabled("upsert"))return;let g=this.createEntry("upsert",t,e,o,{...s,created:i});this.config.storeRecord&&(g.record=this.filterFields(r)),this.config.storePreviousRecord&&n&&(g.previousRecord=this.filterFields(n)),this.config.trackChanges&&n&&(g.changes=f(n,r,this.config.excludeFields)),await this.getStorage().store(g);}async logBatch(t,e,r,n,i){if(this.isEnabled(t))for(let o of r){let s=this.createEntry(t,e,o.recordId,n,i);this.config.storeRecord&&o.record&&(s.record=this.filterFields(o.record)),this.config.storePreviousRecord&&o.previousRecord&&(s.previousRecord=this.filterFields(o.previousRecord)),this.config.trackChanges&&o.previousRecord&&o.record&&(s.changes=f(o.previousRecord,o.record,this.config.excludeFields)),await this.getStorage().store(s);}}createEntry(t,e,r,n,i){return {id:crypto.randomUUID(),timestamp:new Date,action:t,tableName:e,recordId:r,userId:n,metadata:i}}filterFields(t){if(this.config.excludeFields.length===0)return t;let e={};for(let[r,n]of Object.entries(t))this.config.excludeFields.includes(r)||(e[r]=n);return e}};function b(d,t,e){return new u(d,t,e)}export{a,l as b,A as c,R as d,u as e,b as f};
@@ -1 +1 @@
1
- import {b as b$4}from'./chunk-3DE2MG3R.js';import {a as a$3}from'./chunk-GF2EC5G4.js';import {b as b$3}from'./chunk-KLBMVJX3.js';import {a,g}from'./chunk-2M5BM4VD.js';import {a as a$1,i}from'./chunk-FC56WWPB.js';import {b,c}from'./chunk-GBQQ3YQX.js';import {b as b$2}from'./chunk-DMGP7QDL.js';import {e,a as a$2,b as b$1}from'./chunk-VJRDAVID.js';function B(e,t={}){let{ipHeader:n="X-Forwarded-For",trustProxy:r=true}=t;if(r){let s=e.req.header(n);if(s){let c=s.split(",")[0]?.trim();if(c)return c}let a=e.req.header("X-Real-IP")?.trim();if(a)return a;let i=e.req.header("CF-Connecting-IP")?.trim();if(i)return i}let o=e.req.raw;if(o&&typeof o.socket=="object"&&o.socket?.remoteAddress)return o.socket.remoteAddress;if(o?.cf?.ip)return o.cf.ip}function $(e){return a$2(e,"userId")}function z(e,t){let n=e.toLowerCase();for(let r of t){if(r instanceof RegExp){if(r.test(e))return true;continue}let o=r.toLowerCase();if(o.includes("*")){let s=o.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");if(new RegExp(`^${s}$`).test(n))return true}else if(n===o)return true}return false}function j(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(r=>j(r,t));if(typeof e!="object")return e;let n={};for(let[r,o]of Object.entries(e))z(r,t)?n[r]="[REDACTED]":typeof o=="object"&&o!==null?n[r]=j(o,t):n[r]=o;return n}function he(e,t){let n={};for(let[r,o]of Object.entries(e))n[r]=z(r,t)?"[REDACTED]":o;return n}function Ye(e,t){return z(e,t)}function ee(e,t){return j(e,t)}function te(e,t){return he(e,t)}function Ze(e,t){return a(e,t)}function ye(e,t,n){for(let r of n)if(a(e,r))return true;if(t.length===0)return false;for(let r of t)if(a(e,r))return false;return true}function xe(e,t="X-Forwarded-For",n=false){return B(e,{ipHeader:t,trustProxy:n||true})}function re(e){let t={};return e.forEach((n,r)=>{t[r.toLowerCase()]=n;}),t}function Ce(e){let t={};return new URL(e.req.url).searchParams.forEach((r,o)=>{t[o]=r;}),t}function D(e,t){if(typeof e=="string")return e.length>t?e.substring(0,t)+"... [TRUNCATED]":e;let n=JSON.stringify(e);return n.length>t?{_truncated:true,_originalSize:n.length,_maxSize:t}:e}function Ee(e,t){if(!e)return false;if(t.length===0)return true;let n=e.toLowerCase();for(let r of t)if(n.includes(r.toLowerCase()))return true;return false}function Se(e){return $(e)}function Re(){return e()}var U=class extends a$1{constructor(t="Too many requests",n=60){super(t,429,"RATE_LIMIT_EXCEEDED",{retryAfter:n}),this.name="RateLimitExceededException";}};function q(e,t="X-Forwarded-For",n=false){return B(e,{ipHeader:t,trustProxy:n})??"unknown"}function ne(e){return $(e)??null}function we(e,t="X-API-Key"){return e.req.header(t)||null}function st(e,t){return a(e,t)}function ve(e,t){return t.some(n=>a(e,n))}function Ie(e,...t){let n=t.filter(r=>r!==void 0&&r!=="");return `${e}:${n.join(":")}`}function V(e){return e instanceof Error?e:new Error(String(e))}function Me(e,t){let n=V(e),r=new Error(`${t}: ${n.message}`);return r.cause=n,r}function Oe(e){return e instanceof Error?e.message:String(e)}var X=b("loggingStorage");function ht(e){X.set(e);}function yt(){return X.get()}var De=["authorization","cookie","x-api-key","x-auth-token"],Fe=["password","token","secret","apiKey","api_key","accessToken","access_token","refreshToken","refresh_token","creditCard","credit_card","ssn","socialSecurityNumber"],_e=["/health","/healthz","/ready","/readyz","/live","/livez","/metrics","/favicon.ico"];function xt(e){return a$2(e,"requestId")}function Ct(e){return a$2(e,"requestStartTime")}function Et(e={}){let t=e.enabled??true,n=e.level??"info",r=e.includePaths??[],o=e.excludePaths??_e,s=e.redactHeaders??De,a=e.redactBodyFields??Fe,i=e.requestBody??{enabled:false},c=e.responseBody??{enabled:false},u=e.includeHeaders??true,d=e.includeQuery??true,g=e.includeClientIp??true,C=e.ipHeader??"X-Forwarded-For",m=e.trustProxy??false,h=e.minResponseTimeMs??0,R=e.generateRequestId??Re;return async(l,P)=>{if(!t)return P();let w=l.req.path;if(ye(w,r,o))return P();let f=R(),T=Date.now();b$1(l,"requestId",f),b$1(l,"requestStartTime",T),l.header("X-Request-ID",f);let Ae=l.req.method,qe=l.req.url,oe;if(u){let E=re(l.req.raw.headers);oe=te(E,s);}let se;d&&(se=Ce(l));let ae;g&&(ae=xe(l,C,m));let Ke=Se(l),Q;if(i.enabled){let E=l.req.header("content-type"),H=i.contentTypes??[];if(Ee(E,H))try{let L=await l.req.raw.clone().text();if(L)try{let x=JSON.parse(L);x=ee(x,a);let y=i.maxSize??10240;Q=D(x,y);}catch{let x=i.maxSize??10240;Q=D(L,x);}}catch{}}let S,Y;try{await P();}catch(E){throw S=E instanceof Error?E:new Error(String(E)),E}finally{let H=Date.now()-T;if(H<h)return;let b=l.res.status,L;if(u){let p=re(l.res.headers);L=te(p,s);}if(c.enabled&&!S){let p=c.statusCodes??[];if(p.length===0||p.includes(b))try{let Z=await l.res.clone().text();if(Z)try{let M=JSON.parse(Z);M=ee(M,a);let He=c.maxSize??10240;Y=D(M,He);}catch{let M=c.maxSize??10240;Y=D(Z,M);}}catch{}}let x=n;e.levelResolver?x=e.levelResolver(l,H,b,S):S||b>=500?x="error":b>=400&&(x="warn");let y={id:f,timestamp:new Date(T).toISOString(),level:x,request:{method:Ae,path:w,url:qe,headers:oe,query:se,body:Q,clientIp:ae,userId:Ke},response:{statusCode:b,headers:L,body:Y,responseTimeMs:H}};if(S&&(y.error={message:S.message,name:S.name,stack:S.stack}),e.metadata){let p=typeof e.metadata=="function"?e.metadata(l):e.metadata;y.metadata=p;}e.formatter&&(y=e.formatter(y));let ie=Pe(l,e.storage);(async()=>{if(ie)try{await ie.store(y);}catch(p){e.onError&&e.onError(p instanceof Error?p:new Error(String(p)),y);}if(e.handlers)for(let p of e.handlers)try{await p(y);}catch(v){e.onError&&e.onError(v instanceof Error?v:new Error(String(v)),y);}})().catch(p=>{let v=V(p);e.onError?e.onError(v,y):b$2().error("Failed to process log entry",{error:v.message});});}}}function Te(e){let{tableName:t,method:n,params:r,query:o,keyFields:s,userId:a,prefix:i}=e,c=[];if(i&&c.push(i),c.push(t),c.push(n),r&&Object.keys(r).length>0){let u=Object.keys(r).sort().map(d=>`${d}=${r[d]}`).join("&");c.push(u);}if(o&&Object.keys(o).length>0){let u=Object.keys(o).filter(d=>o[d]!==void 0&&o[d]!==null&&o[d]!=="");if(s&&s.length>0&&(u=u.filter(d=>s.includes(d))),u.length>0){let d=u.sort().map(g=>`${g}=${String(o[g])}`).join("&");c.push(d);}}return a&&c.push(`user=${a}`),c.join(":")}function K(e,t,n){let r=[];if(n&&r.push(n),r.push(e),!t)return r.push("*"),r.join(":");let{method:o,id:s,userId:a}=t;return o?(r.push(o),r.join(":")+"*"):(s!==void 0?(r.push("*"),r.push(`id=${s}*`)):a?(r.push("*"),r.push(`user=${a}`)):r.push("*"),r.join(":"))}function be(e,t,n){return t.map(r=>K(r,void 0,n))}function Le(e,t){let n=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${n}$`).test(e)}function Rt(e){let t=e.split(":"),n=t.length>2&&!["GET","LIST"].includes(t[1]),r=0,o=n?t[r++]:void 0,s=t[r++],a=t[r++],i={tableName:s,method:a};o&&(i.prefix=o);for(let c=r;c<t.length;c++){let u=t[c];if(u.startsWith("user="))i.userId=u.substring(5);else if(u.includes("=")){let d=u.split("&"),g={};for(let C of d){let[m,h]=C.split("=");m&&h!==void 0&&(g[m]=h);}a==="GET"&&!i.params?i.params=g:a==="LIST"&&!i.query||i.params?i.query=g:i.params=g;}}return i}var W=class{storage=new Map;tagIndex=new Map;stats={hits:0,misses:0,size:0};defaultTtl;maxEntries;constructor(t){this.defaultTtl=t?.defaultTtl??300,this.maxEntries=t?.maxEntries??1e4;}async get(t){let n=this.storage.get(t);return n?n.expiresAt&&n.expiresAt<Date.now()?(await this.delete(t),this.stats.misses++,null):(this.stats.hits++,n):(this.stats.misses++,null)}async set(t,n,r){let o=r?.ttl??this.defaultTtl,s=r?.tags;this.maxEntries>0&&this.storage.size>=this.maxEntries&&!this.storage.has(t)&&this.evictOldest();let a=Date.now(),i={data:n,createdAt:a,expiresAt:o>0?a+o*1e3:null,tags:s},c=this.storage.get(t);if(c?.tags)for(let u of c.tags)this.tagIndex.get(u)?.delete(t);if(c&&this.storage.delete(t),this.storage.set(t,i),this.stats.size=this.storage.size,s)for(let u of s)this.tagIndex.has(u)||this.tagIndex.set(u,new Set),this.tagIndex.get(u).add(t);}async delete(t){let n=this.storage.get(t);if(!n)return false;if(n.tags)for(let r of n.tags)this.tagIndex.get(r)?.delete(t);return this.storage.delete(t),this.stats.size=this.storage.size,true}async deletePattern(t){let n=0,r=[];for(let o of this.storage.keys())Le(o,t)&&r.push(o);for(let o of r)await this.delete(o)&&n++;return n}async deleteByTag(t){let n=this.tagIndex.get(t);if(!n||n.size===0)return 0;let r=0,o=Array.from(n);for(let s of o)await this.delete(s)&&r++;return this.tagIndex.delete(t),r}async has(t){let n=this.storage.get(t);return n?n.expiresAt&&n.expiresAt<Date.now()?(await this.delete(t),false):true:false}async clear(){this.storage.clear(),this.tagIndex.clear(),this.stats.size=0;}getStats(){return {...this.stats}}resetStats(){this.stats.hits=0,this.stats.misses=0;}getKeys(){return Array.from(this.storage.keys())}getTags(){return Array.from(this.tagIndex.keys())}evictOldest(){let t=this.storage.keys().next().value;t!==void 0&&this.delete(t).catch(()=>{});}async cleanup(){let t=Date.now(),n=0,r=[];for(let[o,s]of this.storage.entries())s.expiresAt&&s.expiresAt<t&&r.push(o);for(let o of r)await this.delete(o),n++;return n}};function G(e){let n=e._meta?.model?.tableName;if(!n)throw new i("Cache mixin requires `_meta.model.tableName`. Declare `_meta` on the endpoint or remove the cache mixin.");return n}var J=c("cacheStorage",()=>new W);function qt(e){J.set(e);}function Kt(){return J.getRequired()}function Ht(e){class t extends e{cacheConfig;getCacheConfig(){return {enabled:true,ttl:300,perUser:false,...this.cacheConfig}}async generateCacheKey(){let r=this.getCacheConfig(),o=this.getContext(),s=G(this),a=await this.getValidatedData(),i=a.params,c=a.query,u=i&&Object.keys(i).length>0?"GET":"LIST",d;return r.perUser&&(d=o.var?.userId),Te({tableName:s,method:u,params:i,query:c,keyFields:r.keyFields,userId:d,prefix:r.prefix})}_cacheHit=false;async getCachedResponse(){if(!this.getCacheConfig().enabled)return this._cacheHit=false,null;let o=await this.generateCacheKey(),s=this.getContext(),a=F(s);if(!a)return this._cacheHit=false,null;let i=await a.get(o);return this._cacheHit=i!==null,i?.data??null}getCacheStatus(){return this._cacheHit?"HIT":"MISS"}successWithCache(r,o=200){return new Response(JSON.stringify({success:true,result:r}),{status:o,headers:{"Content-Type":"application/json","X-Cache":this.getCacheStatus()}})}jsonWithCache(r,o=200){return new Response(JSON.stringify(r),{status:o,headers:{"Content-Type":"application/json","X-Cache":this.getCacheStatus()}})}async setCachedResponse(r){let o=this.getCacheConfig();if(!o.enabled)return;let s=await this.generateCacheKey(),a=this.getContext(),i=F(a);if(!i)return;let c=o.tags?[...o.tags]:[],u=this._meta;u?.model?.tableName&&c.push(u.model.tableName),await i.set(s,r,{ttl:o.ttl,tags:c.length>0?c:void 0});}async invalidateCache(r){let o=this.getContext(),s=F(o);if(!s)return;let a=this.getCacheConfig();if(r?.pattern)await s.deletePattern(r.pattern);else if(r?.tags&&s.deleteByTag)for(let i of r.tags)await s.deleteByTag(i);else {let i=G(this),c=K(i,void 0,a.prefix);await s.deletePattern(c);}}}return t}function Mt(e){class t extends e{cacheInvalidation;getCacheInvalidationConfig(){return {strategy:"all",...this.cacheInvalidation}}async performCacheInvalidation(r){let o=this.getCacheInvalidationConfig(),s=this.getContext(),a=F(s);if(!a)return;let i=G(this);switch(o.strategy??"all"){case "single":if(r!==void 0){let g=K(i,{id:r});await a.deletePattern(g);}break;case "list":let u=K(i,{method:"LIST"});await a.deletePattern(u);break;case "all":let d=K(i);await a.deletePattern(d);break;case "pattern":o.pattern&&await a.deletePattern(o.pattern);break;case "tags":if(o.tags&&a.deleteByTag)for(let g of o.tags)await a.deleteByTag(g);break}if(o.relatedModels&&o.relatedModels.length>0){let u=be(i,o.relatedModels);for(let d of u)await a.deletePattern(d);}}async handle(){let r=await super.handle();if(r.status>=200&&r.status<300){let o;try{o=(await r.clone().json())?.result?.id;}catch{}let s=G(this);this.performCacheInvalidation(o).catch(a=>{b$2().error("Cache invalidation failed",{error:a instanceof Error?a.message:String(a),tableName:s,recordId:o});});}return r}}return t}function ke(e,t){return _.resolve(e,t)}function Pe(e,t){return X.resolve(e,t)}function F(e,t){return J.resolve(e,t)}function zt(e,t){return b$3.resolve(e,t)}function Ut(e,t){return b$4.resolve(e,t)}function Vt(e,t){return g.resolve(e,t)}function Xt(e,t){return a$3.resolve(e,t)}var _=b("rateLimitStorage");function tr(e){_.set(e);}function rr(){return _.get()}function Ne(){return {ip:e=>t=>q(t,e.ipHeader,e.trustProxy),user:e=>t=>{let n=ne(t);return n?`user:${n}`:q(t,e.ipHeader,e.trustProxy)},"api-key":e=>t=>{let n=we(t,e.apiKeyHeader);return n?`apikey:${n.substring(0,8)}`:q(t,e.ipHeader,e.trustProxy)},combined:e=>t=>{let n=q(t,e.ipHeader,e.trustProxy),r=ne(t);return r?`${n}:user:${r}`:n}}}function Be(e,t){if(typeof e=="function")return e;let r=Ne()[e];return r?r(t):o=>q(o,t.ipHeader,t.trustProxy)}async function $e(e,t,n,r){let o=await e.increment(t,r),s=Math.ceil((o.windowStart+r)/1e3),a=Math.max(0,n-o.count),i=o.count<=n;return {allowed:i,limit:n,remaining:a,resetAt:s,retryAfter:i?void 0:Math.ceil((o.windowStart+r-Date.now())/1e3)}}async function je(e,t,n,r){let o=Date.now(),s=await e.addTimestamp(t,r,o),a=s.timestamps.length,i=Math.max(0,n-a),c=a<=n,u=s.timestamps.length>0?Math.min(...s.timestamps):o,d=Math.ceil((u+r)/1e3),g;if(!c&&s.timestamps.length>0){let C=[...s.timestamps].sort((h,R)=>h-R),m=a-n;if(m>0&&C.length>=m){let h=C[m-1];g=Math.max(1,Math.ceil((h+r-o)/1e3));}}return {allowed:c,limit:n,remaining:i,resetAt:d,retryAfter:g}}function nr(e={}){let t=e.limit??100,n=e.windowSeconds??60,r=e.algorithm??"sliding-window",o=e.keyStrategy??"ip",s=e.keyPrefix??"rl",a=e.skipPaths??[],i=e.includeHeaders??true,c=e.errorMessage??"Too many requests",u=Be(o,e);return async(d,g)=>{let C=d.req.path;if(a.length>0&&ve(C,a))return g();let m=ke(d,e.storage);if(!m)return b$2().warn("Rate limit storage not configured. Skipping rate limiting."),g();let h=u(d);if(!h)return g();let R=t,l=n;if(e.getTier){let T=await e.getTier(d);R=T.limit,l=T.windowSeconds??n;}let P=l*1e3,w=Ie(s,C,h),f;if(r==="fixed-window"?f=await $e(m,w,R,P):f=await je(m,w,R,P),b$1(d,"rateLimit",f),b$1(d,"rateLimitKey",w),i&&(d.header("X-RateLimit-Limit",String(f.limit)),d.header("X-RateLimit-Remaining",String(f.remaining)),d.header("X-RateLimit-Reset",String(f.resetAt))),!f.allowed)throw f.retryAfter&&d.header("Retry-After",String(f.retryAfter)),e.onRateLimitExceeded&&await e.onRateLimitExceeded(d,f,w),new U(c,f.retryAfter??60);await g();}}async function or(e,t){let n=t??_.get();if(!n)throw new Error("Rate limit storage not configured");await n.reset(e);}export{Le as A,Rt as B,W as C,qt as D,Kt as E,Ht as F,Mt as G,ke as H,Pe as I,F as J,zt as K,Ut as L,Vt as M,Xt as N,V as O,Me as P,Oe as Q,ht as R,yt as S,xt as T,Ct as U,Et as V,Ye as a,ee as b,te as c,Ze as d,ye as e,xe as f,re as g,Ce as h,D as i,Ee as j,Se as k,Re as l,U as m,q as n,ne as o,we as p,st as q,ve as r,Ie as s,tr as t,rr as u,nr as v,or as w,Te as x,K as y,be as z};
1
+ import {b as b$4}from'./chunk-NGUMNUOP.js';import {a as a$3}from'./chunk-GF2EC5G4.js';import {b as b$3}from'./chunk-FJCWFB5L.js';import {a,g}from'./chunk-2M5BM4VD.js';import {a as a$1,i}from'./chunk-FC56WWPB.js';import {b,c}from'./chunk-GBQQ3YQX.js';import {b as b$2}from'./chunk-DMGP7QDL.js';import {e,a as a$2,b as b$1}from'./chunk-VJRDAVID.js';function B(e,t={}){let{ipHeader:n="X-Forwarded-For",trustProxy:r=true}=t;if(r){let s=e.req.header(n);if(s){let c=s.split(",")[0]?.trim();if(c)return c}let a=e.req.header("X-Real-IP")?.trim();if(a)return a;let i=e.req.header("CF-Connecting-IP")?.trim();if(i)return i}let o=e.req.raw;if(o&&typeof o.socket=="object"&&o.socket?.remoteAddress)return o.socket.remoteAddress;if(o?.cf?.ip)return o.cf.ip}function $(e){return a$2(e,"userId")}function z(e,t){let n=e.toLowerCase();for(let r of t){if(r instanceof RegExp){if(r.test(e))return true;continue}let o=r.toLowerCase();if(o.includes("*")){let s=o.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");if(new RegExp(`^${s}$`).test(n))return true}else if(n===o)return true}return false}function j(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(r=>j(r,t));if(typeof e!="object")return e;let n={};for(let[r,o]of Object.entries(e))z(r,t)?n[r]="[REDACTED]":typeof o=="object"&&o!==null?n[r]=j(o,t):n[r]=o;return n}function he(e,t){let n={};for(let[r,o]of Object.entries(e))n[r]=z(r,t)?"[REDACTED]":o;return n}function Ye(e,t){return z(e,t)}function ee(e,t){return j(e,t)}function te(e,t){return he(e,t)}function Ze(e,t){return a(e,t)}function ye(e,t,n){for(let r of n)if(a(e,r))return true;if(t.length===0)return false;for(let r of t)if(a(e,r))return false;return true}function xe(e,t="X-Forwarded-For",n=false){return B(e,{ipHeader:t,trustProxy:n||true})}function re(e){let t={};return e.forEach((n,r)=>{t[r.toLowerCase()]=n;}),t}function Ce(e){let t={};return new URL(e.req.url).searchParams.forEach((r,o)=>{t[o]=r;}),t}function D(e,t){if(typeof e=="string")return e.length>t?e.substring(0,t)+"... [TRUNCATED]":e;let n=JSON.stringify(e);return n.length>t?{_truncated:true,_originalSize:n.length,_maxSize:t}:e}function Ee(e,t){if(!e)return false;if(t.length===0)return true;let n=e.toLowerCase();for(let r of t)if(n.includes(r.toLowerCase()))return true;return false}function Se(e){return $(e)}function Re(){return e()}var U=class extends a$1{constructor(t="Too many requests",n=60){super(t,429,"RATE_LIMIT_EXCEEDED",{retryAfter:n}),this.name="RateLimitExceededException";}};function q(e,t="X-Forwarded-For",n=false){return B(e,{ipHeader:t,trustProxy:n})??"unknown"}function ne(e){return $(e)??null}function we(e,t="X-API-Key"){return e.req.header(t)||null}function st(e,t){return a(e,t)}function ve(e,t){return t.some(n=>a(e,n))}function Ie(e,...t){let n=t.filter(r=>r!==void 0&&r!=="");return `${e}:${n.join(":")}`}function V(e){return e instanceof Error?e:new Error(String(e))}function Me(e,t){let n=V(e),r=new Error(`${t}: ${n.message}`);return r.cause=n,r}function Oe(e){return e instanceof Error?e.message:String(e)}var X=b("loggingStorage");function ht(e){X.set(e);}function yt(){return X.get()}var De=["authorization","cookie","x-api-key","x-auth-token"],Fe=["password","token","secret","apiKey","api_key","accessToken","access_token","refreshToken","refresh_token","creditCard","credit_card","ssn","socialSecurityNumber"],_e=["/health","/healthz","/ready","/readyz","/live","/livez","/metrics","/favicon.ico"];function xt(e){return a$2(e,"requestId")}function Ct(e){return a$2(e,"requestStartTime")}function Et(e={}){let t=e.enabled??true,n=e.level??"info",r=e.includePaths??[],o=e.excludePaths??_e,s=e.redactHeaders??De,a=e.redactBodyFields??Fe,i=e.requestBody??{enabled:false},c=e.responseBody??{enabled:false},u=e.includeHeaders??true,d=e.includeQuery??true,g=e.includeClientIp??true,C=e.ipHeader??"X-Forwarded-For",m=e.trustProxy??false,h=e.minResponseTimeMs??0,R=e.generateRequestId??Re;return async(l,P)=>{if(!t)return P();let w=l.req.path;if(ye(w,r,o))return P();let f=R(),T=Date.now();b$1(l,"requestId",f),b$1(l,"requestStartTime",T),l.header("X-Request-ID",f);let Ae=l.req.method,qe=l.req.url,oe;if(u){let E=re(l.req.raw.headers);oe=te(E,s);}let se;d&&(se=Ce(l));let ae;g&&(ae=xe(l,C,m));let Ke=Se(l),Q;if(i.enabled){let E=l.req.header("content-type"),H=i.contentTypes??[];if(Ee(E,H))try{let L=await l.req.raw.clone().text();if(L)try{let x=JSON.parse(L);x=ee(x,a);let y=i.maxSize??10240;Q=D(x,y);}catch{let x=i.maxSize??10240;Q=D(L,x);}}catch{}}let S,Y;try{await P();}catch(E){throw S=E instanceof Error?E:new Error(String(E)),E}finally{let H=Date.now()-T;if(H<h)return;let b=l.res.status,L;if(u){let p=re(l.res.headers);L=te(p,s);}if(c.enabled&&!S){let p=c.statusCodes??[];if(p.length===0||p.includes(b))try{let Z=await l.res.clone().text();if(Z)try{let M=JSON.parse(Z);M=ee(M,a);let He=c.maxSize??10240;Y=D(M,He);}catch{let M=c.maxSize??10240;Y=D(Z,M);}}catch{}}let x=n;e.levelResolver?x=e.levelResolver(l,H,b,S):S||b>=500?x="error":b>=400&&(x="warn");let y={id:f,timestamp:new Date(T).toISOString(),level:x,request:{method:Ae,path:w,url:qe,headers:oe,query:se,body:Q,clientIp:ae,userId:Ke},response:{statusCode:b,headers:L,body:Y,responseTimeMs:H}};if(S&&(y.error={message:S.message,name:S.name,stack:S.stack}),e.metadata){let p=typeof e.metadata=="function"?e.metadata(l):e.metadata;y.metadata=p;}e.formatter&&(y=e.formatter(y));let ie=Pe(l,e.storage);(async()=>{if(ie)try{await ie.store(y);}catch(p){e.onError&&e.onError(p instanceof Error?p:new Error(String(p)),y);}if(e.handlers)for(let p of e.handlers)try{await p(y);}catch(v){e.onError&&e.onError(v instanceof Error?v:new Error(String(v)),y);}})().catch(p=>{let v=V(p);e.onError?e.onError(v,y):b$2().error("Failed to process log entry",{error:v.message});});}}}function Te(e){let{tableName:t,method:n,params:r,query:o,keyFields:s,userId:a,prefix:i}=e,c=[];if(i&&c.push(i),c.push(t),c.push(n),r&&Object.keys(r).length>0){let u=Object.keys(r).sort().map(d=>`${d}=${r[d]}`).join("&");c.push(u);}if(o&&Object.keys(o).length>0){let u=Object.keys(o).filter(d=>o[d]!==void 0&&o[d]!==null&&o[d]!=="");if(s&&s.length>0&&(u=u.filter(d=>s.includes(d))),u.length>0){let d=u.sort().map(g=>`${g}=${String(o[g])}`).join("&");c.push(d);}}return a&&c.push(`user=${a}`),c.join(":")}function K(e,t,n){let r=[];if(n&&r.push(n),r.push(e),!t)return r.push("*"),r.join(":");let{method:o,id:s,userId:a}=t;return o?(r.push(o),r.join(":")+"*"):(s!==void 0?(r.push("*"),r.push(`id=${s}*`)):a?(r.push("*"),r.push(`user=${a}`)):r.push("*"),r.join(":"))}function be(e,t,n){return t.map(r=>K(r,void 0,n))}function Le(e,t){let n=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${n}$`).test(e)}function Rt(e){let t=e.split(":"),n=t.length>2&&!["GET","LIST"].includes(t[1]),r=0,o=n?t[r++]:void 0,s=t[r++],a=t[r++],i={tableName:s,method:a};o&&(i.prefix=o);for(let c=r;c<t.length;c++){let u=t[c];if(u.startsWith("user="))i.userId=u.substring(5);else if(u.includes("=")){let d=u.split("&"),g={};for(let C of d){let[m,h]=C.split("=");m&&h!==void 0&&(g[m]=h);}a==="GET"&&!i.params?i.params=g:a==="LIST"&&!i.query||i.params?i.query=g:i.params=g;}}return i}var W=class{storage=new Map;tagIndex=new Map;stats={hits:0,misses:0,size:0};defaultTtl;maxEntries;constructor(t){this.defaultTtl=t?.defaultTtl??300,this.maxEntries=t?.maxEntries??1e4;}async get(t){let n=this.storage.get(t);return n?n.expiresAt&&n.expiresAt<Date.now()?(await this.delete(t),this.stats.misses++,null):(this.stats.hits++,n):(this.stats.misses++,null)}async set(t,n,r){let o=r?.ttl??this.defaultTtl,s=r?.tags;this.maxEntries>0&&this.storage.size>=this.maxEntries&&!this.storage.has(t)&&this.evictOldest();let a=Date.now(),i={data:n,createdAt:a,expiresAt:o>0?a+o*1e3:null,tags:s},c=this.storage.get(t);if(c?.tags)for(let u of c.tags)this.tagIndex.get(u)?.delete(t);if(c&&this.storage.delete(t),this.storage.set(t,i),this.stats.size=this.storage.size,s)for(let u of s)this.tagIndex.has(u)||this.tagIndex.set(u,new Set),this.tagIndex.get(u).add(t);}async delete(t){let n=this.storage.get(t);if(!n)return false;if(n.tags)for(let r of n.tags)this.tagIndex.get(r)?.delete(t);return this.storage.delete(t),this.stats.size=this.storage.size,true}async deletePattern(t){let n=0,r=[];for(let o of this.storage.keys())Le(o,t)&&r.push(o);for(let o of r)await this.delete(o)&&n++;return n}async deleteByTag(t){let n=this.tagIndex.get(t);if(!n||n.size===0)return 0;let r=0,o=Array.from(n);for(let s of o)await this.delete(s)&&r++;return this.tagIndex.delete(t),r}async has(t){let n=this.storage.get(t);return n?n.expiresAt&&n.expiresAt<Date.now()?(await this.delete(t),false):true:false}async clear(){this.storage.clear(),this.tagIndex.clear(),this.stats.size=0;}getStats(){return {...this.stats}}resetStats(){this.stats.hits=0,this.stats.misses=0;}getKeys(){return Array.from(this.storage.keys())}getTags(){return Array.from(this.tagIndex.keys())}evictOldest(){let t=this.storage.keys().next().value;t!==void 0&&this.delete(t).catch(()=>{});}async cleanup(){let t=Date.now(),n=0,r=[];for(let[o,s]of this.storage.entries())s.expiresAt&&s.expiresAt<t&&r.push(o);for(let o of r)await this.delete(o),n++;return n}};function G(e){let n=e._meta?.model?.tableName;if(!n)throw new i("Cache mixin requires `_meta.model.tableName`. Declare `_meta` on the endpoint or remove the cache mixin.");return n}var J=c("cacheStorage",()=>new W);function qt(e){J.set(e);}function Kt(){return J.getRequired()}function Ht(e){class t extends e{cacheConfig;getCacheConfig(){return {enabled:true,ttl:300,perUser:false,...this.cacheConfig}}async generateCacheKey(){let r=this.getCacheConfig(),o=this.getContext(),s=G(this),a=await this.getValidatedData(),i=a.params,c=a.query,u=i&&Object.keys(i).length>0?"GET":"LIST",d;return r.perUser&&(d=o.var?.userId),Te({tableName:s,method:u,params:i,query:c,keyFields:r.keyFields,userId:d,prefix:r.prefix})}_cacheHit=false;async getCachedResponse(){if(!this.getCacheConfig().enabled)return this._cacheHit=false,null;let o=await this.generateCacheKey(),s=this.getContext(),a=F(s);if(!a)return this._cacheHit=false,null;let i=await a.get(o);return this._cacheHit=i!==null,i?.data??null}getCacheStatus(){return this._cacheHit?"HIT":"MISS"}successWithCache(r,o=200){return new Response(JSON.stringify({success:true,result:r}),{status:o,headers:{"Content-Type":"application/json","X-Cache":this.getCacheStatus()}})}jsonWithCache(r,o=200){return new Response(JSON.stringify(r),{status:o,headers:{"Content-Type":"application/json","X-Cache":this.getCacheStatus()}})}async setCachedResponse(r){let o=this.getCacheConfig();if(!o.enabled)return;let s=await this.generateCacheKey(),a=this.getContext(),i=F(a);if(!i)return;let c=o.tags?[...o.tags]:[],u=this._meta;u?.model?.tableName&&c.push(u.model.tableName),await i.set(s,r,{ttl:o.ttl,tags:c.length>0?c:void 0});}async invalidateCache(r){let o=this.getContext(),s=F(o);if(!s)return;let a=this.getCacheConfig();if(r?.pattern)await s.deletePattern(r.pattern);else if(r?.tags&&s.deleteByTag)for(let i of r.tags)await s.deleteByTag(i);else {let i=G(this),c=K(i,void 0,a.prefix);await s.deletePattern(c);}}}return t}function Mt(e){class t extends e{cacheInvalidation;getCacheInvalidationConfig(){return {strategy:"all",...this.cacheInvalidation}}async performCacheInvalidation(r){let o=this.getCacheInvalidationConfig(),s=this.getContext(),a=F(s);if(!a)return;let i=G(this);switch(o.strategy??"all"){case "single":if(r!==void 0){let g=K(i,{id:r});await a.deletePattern(g);}break;case "list":let u=K(i,{method:"LIST"});await a.deletePattern(u);break;case "all":let d=K(i);await a.deletePattern(d);break;case "pattern":o.pattern&&await a.deletePattern(o.pattern);break;case "tags":if(o.tags&&a.deleteByTag)for(let g of o.tags)await a.deleteByTag(g);break}if(o.relatedModels&&o.relatedModels.length>0){let u=be(i,o.relatedModels);for(let d of u)await a.deletePattern(d);}}async handle(){let r=await super.handle();if(r.status>=200&&r.status<300){let o;try{o=(await r.clone().json())?.result?.id;}catch{}let s=G(this);this.performCacheInvalidation(o).catch(a=>{b$2().error("Cache invalidation failed",{error:a instanceof Error?a.message:String(a),tableName:s,recordId:o});});}return r}}return t}function ke(e,t){return _.resolve(e,t)}function Pe(e,t){return X.resolve(e,t)}function F(e,t){return J.resolve(e,t)}function zt(e,t){return b$3.resolve(e,t)}function Ut(e,t){return b$4.resolve(e,t)}function Vt(e,t){return g.resolve(e,t)}function Xt(e,t){return a$3.resolve(e,t)}var _=b("rateLimitStorage");function tr(e){_.set(e);}function rr(){return _.get()}function Ne(){return {ip:e=>t=>q(t,e.ipHeader,e.trustProxy),user:e=>t=>{let n=ne(t);return n?`user:${n}`:q(t,e.ipHeader,e.trustProxy)},"api-key":e=>t=>{let n=we(t,e.apiKeyHeader);return n?`apikey:${n.substring(0,8)}`:q(t,e.ipHeader,e.trustProxy)},combined:e=>t=>{let n=q(t,e.ipHeader,e.trustProxy),r=ne(t);return r?`${n}:user:${r}`:n}}}function Be(e,t){if(typeof e=="function")return e;let r=Ne()[e];return r?r(t):o=>q(o,t.ipHeader,t.trustProxy)}async function $e(e,t,n,r){let o=await e.increment(t,r),s=Math.ceil((o.windowStart+r)/1e3),a=Math.max(0,n-o.count),i=o.count<=n;return {allowed:i,limit:n,remaining:a,resetAt:s,retryAfter:i?void 0:Math.ceil((o.windowStart+r-Date.now())/1e3)}}async function je(e,t,n,r){let o=Date.now(),s=await e.addTimestamp(t,r,o),a=s.timestamps.length,i=Math.max(0,n-a),c=a<=n,u=s.timestamps.length>0?Math.min(...s.timestamps):o,d=Math.ceil((u+r)/1e3),g;if(!c&&s.timestamps.length>0){let C=[...s.timestamps].sort((h,R)=>h-R),m=a-n;if(m>0&&C.length>=m){let h=C[m-1];g=Math.max(1,Math.ceil((h+r-o)/1e3));}}return {allowed:c,limit:n,remaining:i,resetAt:d,retryAfter:g}}function nr(e={}){let t=e.limit??100,n=e.windowSeconds??60,r=e.algorithm??"sliding-window",o=e.keyStrategy??"ip",s=e.keyPrefix??"rl",a=e.skipPaths??[],i=e.includeHeaders??true,c=e.errorMessage??"Too many requests",u=Be(o,e);return async(d,g)=>{let C=d.req.path;if(a.length>0&&ve(C,a))return g();let m=ke(d,e.storage);if(!m)return b$2().warn("Rate limit storage not configured. Skipping rate limiting."),g();let h=u(d);if(!h)return g();let R=t,l=n;if(e.getTier){let T=await e.getTier(d);R=T.limit,l=T.windowSeconds??n;}let P=l*1e3,w=Ie(s,C,h),f;if(r==="fixed-window"?f=await $e(m,w,R,P):f=await je(m,w,R,P),b$1(d,"rateLimit",f),b$1(d,"rateLimitKey",w),i&&(d.header("X-RateLimit-Limit",String(f.limit)),d.header("X-RateLimit-Remaining",String(f.remaining)),d.header("X-RateLimit-Reset",String(f.resetAt))),!f.allowed)throw f.retryAfter&&d.header("Retry-After",String(f.retryAfter)),e.onRateLimitExceeded&&await e.onRateLimitExceeded(d,f,w),new U(c,f.retryAfter??60);await g();}}async function or(e,t){let n=t??_.get();if(!n)throw new Error("Rate limit storage not configured");await n.reset(e);}export{Le as A,Rt as B,W as C,qt as D,Kt as E,Ht as F,Mt as G,ke as H,Pe as I,F as J,zt as K,Ut as L,Vt as M,Xt as N,V as O,Me as P,Oe as Q,ht as R,yt as S,xt as T,Ct as U,Et as V,Ye as a,ee as b,te as c,Ze as d,ye as e,xe as f,re as g,Ce as h,D as i,Ee as j,Se as k,Re as l,U as m,q as n,ne as o,we as p,st as q,ve as r,Ie as s,tr as t,rr as u,nr as v,or as w,Te as x,K as y,be as z};
@@ -1 +1 @@
1
- import {a}from'./chunk-VJRDAVID.js';function T(e){return btoa(String(e))}function h(e){try{return atob(e)}catch{return null}}function C(e,t){let n={},o={};for(let[a,r]of Object.entries(e))t.includes(a)&&r!==void 0?o[a]=r:n[a]=r;return {mainData:n,nestedData:o}}function k(e){if(Array.isArray(e))return true;if(typeof e=="object"&&e!==null){let t=Object.keys(e),n=["create","update","delete","connect","disconnect","set"];return !t.some(o=>n.includes(o))}return false}function w(e){return !e||!e.enabled?{enabled:false,tableName:"audit_logs",actions:[],excludeFields:[],storeRecord:true,storePreviousRecord:true,trackChanges:true}:{enabled:true,tableName:e.tableName||"audit_logs",actions:e.actions||["create","update","delete"],excludeFields:e.excludeFields||[],storeRecord:e.storeRecord??true,storePreviousRecord:e.storePreviousRecord??true,trackChanges:e.trackChanges??true,getUserId:e.getUserId}}function R(e,t,n=[]){let o=[];if(!e&&!t)return o;let a=new Set([...Object.keys(e||{}),...Object.keys(t||{})]);for(let r of a){if(n.includes(r))continue;let l=e?.[r],u=t?.[r],g=JSON.stringify(l),p=JSON.stringify(u);g!==p&&o.push({field:r,oldValue:l,newValue:u});}return o}function A(e,t){return !e||!e.enabled?{enabled:false,field:"version",historyTable:`${t}_history`,maxVersions:null,trackChangedBy:false,excludeFields:[]}:{enabled:true,field:e.field||"version",historyTable:e.historyTable||`${t}_history`,maxVersions:e.maxVersions??null,trackChangedBy:e.trackChangedBy??false,excludeFields:e.excludeFields||[],getUserId:e.getUserId}}function I(e){let t=e.split(":");if(t.length<2)return null;let n=t[0].toLowerCase();return ["count","sum","avg","min","max","countdistinct"].includes(n)?{operation:n==="countdistinct"?"countDistinct":n,field:t[1],alias:t[2]}:null}function P(e){let t=[],n={},o=["count","sum","avg","min","max","countDistinct"];for(let i of o){let s=e[i];if(s){let c=Array.isArray(s)?s:[s];for(let d of c)typeof d=="string"&&t.push({operation:i,field:d==="true"||d===""?"*":d});}}let a;if(e.groupBy){let i=e.groupBy;typeof i=="string"?a=i.split(",").map(s=>s.trim()):Array.isArray(i)&&(a=i.filter(s=>typeof s=="string"));}let r;for(let[i,s]of Object.entries(e)){let c=i.match(/^having\[(\w+)\]\[(\w+)\]$/);if(c){let[,d,m]=c;r||(r={}),r[d]||(r[d]={}),r[d][m]=s;}}let l=typeof e.orderBy=="string"?e.orderBy:void 0,u=e.orderDirection==="desc"?"desc":"asc",g=typeof e.limit=="string"?parseInt(e.limit,10):void 0,p=typeof e.offset=="string"?parseInt(e.offset,10):void 0,x=[...o,"groupBy","orderBy","orderDirection","limit","offset"];for(let[i,s]of Object.entries(e))!x.includes(i)&&!i.startsWith("having[")&&(n[i]=s);return {aggregations:t,groupBy:a,filters:Object.keys(n).length>0?n:void 0,having:r,orderBy:l,orderDirection:u,limit:g,offset:p}}async function y(e,t){if(!t||Object.keys(t).length===0)return e;let n={...e};for(let[o,a]of Object.entries(t))try{let r=await a.compute(e);n[o]=r;}catch{n[o]=void 0;}return n}async function O(e,t){return !t||Object.keys(t).length===0?e:Promise.all(e.map(n=>y(n,t)))}function F(e){return e}function S(e){return e}function v(e){return e?e===true?{enabled:true,field:"deletedAt",allowQueryDeleted:true,queryParam:"withDeleted"}:{enabled:true,field:e.field??"deletedAt",allowQueryDeleted:e.allowQueryDeleted??true,queryParam:e.queryParam??"withDeleted"}:{enabled:false,field:"deletedAt",allowQueryDeleted:true,queryParam:"withDeleted"}}function M(e){let t={enabled:false,field:"tenantId",source:"context",headerName:"X-Tenant-ID",contextKey:"tenantId",pathParam:"tenantId",required:true,errorMessage:"Tenant ID is required"};return e?e===true?{...t,enabled:true}:{enabled:true,field:e.field??t.field,source:e.source??t.source,headerName:e.headerName??t.headerName,contextKey:e.contextKey??t.contextKey,pathParam:e.pathParam??t.pathParam,getTenantId:e.getTenantId,required:e.required??t.required,errorMessage:e.errorMessage??t.errorMessage}:t}function N(e,t){if(t.enabled)switch(t.source){case "header":return e.req.header(t.headerName);case "context":return a(e,t.contextKey);case "path":return e.req.param(t.pathParam);case "custom":return t.getTenantId?t.getTenantId(e):void 0;default:return}}var D="__honoCrudResponseEnvelope__";function _(e){return e==="all"||e==="phrase"?e:"any"}export{T as a,h as b,C as c,k as d,w as e,R as f,A as g,I as h,P as i,y as j,O as k,F as l,S as m,v as n,M as o,N as p,D as q,_ as r};
1
+ import {a}from'./chunk-VJRDAVID.js';function T(e){return btoa(String(e))}function h(e){try{return atob(e)}catch{return null}}function C(e,t){let n={},o={};for(let[a,r]of Object.entries(e))t.includes(a)&&r!==void 0?o[a]=r:n[a]=r;return {mainData:n,nestedData:o}}function k(e){if(Array.isArray(e))return true;if(typeof e=="object"&&e!==null){let t=Object.keys(e),n=["create","update","delete","connect","disconnect","set"];return !t.some(o=>n.includes(o))}return false}function w(e){return !e||!e.enabled?{enabled:false,tableName:"audit_logs",actions:[],excludeFields:[],storeRecord:true,storePreviousRecord:true,trackChanges:true}:{enabled:true,tableName:e.tableName||"audit_logs",actions:e.actions||["create","update","delete"],excludeFields:e.excludeFields||[],storeRecord:e.storeRecord??true,storePreviousRecord:e.storePreviousRecord??true,trackChanges:e.trackChanges??true,getUserId:e.getUserId}}function R(e,t,n=[]){let o=[];if(!e&&!t)return o;let a=new Set([...Object.keys(e||{}),...Object.keys(t||{})]);for(let r of a){if(n.includes(r))continue;let l=e?.[r],u=t?.[r],g=JSON.stringify(l),p=JSON.stringify(u);g!==p&&o.push({field:r,oldValue:l,newValue:u});}return o}function A(e,t){return !e||!e.enabled?{enabled:false,field:"version",historyTable:`${t}_history`,maxVersions:null,trackChangedBy:false,excludeFields:[]}:{enabled:true,field:e.field||"version",historyTable:e.historyTable||`${t}_history`,maxVersions:e.maxVersions??null,trackChangedBy:e.trackChangedBy??false,excludeFields:e.excludeFields||[],getUserId:e.getUserId}}function I(e){let t=e.split(":");if(t.length<2)return null;let n=t[0].toLowerCase();return ["count","sum","avg","min","max","countdistinct"].includes(n)?{operation:n==="countdistinct"?"countDistinct":n,field:t[1],alias:t[2]}:null}function P(e){let t=[],n={},o=["count","sum","avg","min","max","countDistinct"];for(let i of o){let s=e[i];if(s){let c=Array.isArray(s)?s:[s];for(let d of c)typeof d=="string"&&t.push({operation:i,field:d==="true"||d===""?"*":d});}}let a;if(e.groupBy){let i=e.groupBy;typeof i=="string"?a=i.split(",").map(s=>s.trim()):Array.isArray(i)&&(a=i.filter(s=>typeof s=="string"));}let r;for(let[i,s]of Object.entries(e)){let c=i.match(/^having\[(\w+)\]\[(\w+)\]$/);if(c){let[,d,m]=c;r||(r={}),r[d]||(r[d]={}),r[d][m]=s;}}let l=typeof e.orderBy=="string"?e.orderBy:void 0,u=e.orderDirection==="desc"?"desc":"asc",g=typeof e.limit=="string"?parseInt(e.limit,10):void 0,p=typeof e.offset=="string"?parseInt(e.offset,10):void 0,x=[...o,"groupBy","orderBy","orderDirection","limit","offset"];for(let[i,s]of Object.entries(e))!x.includes(i)&&!i.startsWith("having[")&&(n[i]=s);return {aggregations:t,groupBy:a,filters:Object.keys(n).length>0?n:void 0,having:r,orderBy:l,orderDirection:u,limit:g,offset:p}}async function y(e,t){if(!t||Object.keys(t).length===0)return e;let n={...e};for(let[o,a]of Object.entries(t))try{let r=await a.compute(e);n[o]=r;}catch{n[o]=void 0;}return n}async function F(e,t){return !t||Object.keys(t).length===0?e:Promise.all(e.map(n=>y(n,t)))}function O(e){return e}function S(e){return e}function v(e){return e?e===true?{enabled:true,field:"deletedAt",allowQueryDeleted:true,queryParam:"withDeleted"}:{enabled:true,field:e.field??"deletedAt",allowQueryDeleted:e.allowQueryDeleted??true,queryParam:e.queryParam??"withDeleted"}:{enabled:false,field:"deletedAt",allowQueryDeleted:true,queryParam:"withDeleted"}}function M(e){let t={enabled:false,field:"tenantId",source:"context",headerName:"X-Tenant-ID",contextKey:"tenantId",pathParam:"tenantId",required:true,errorMessage:"Tenant ID is required"};return e?e===true?{...t,enabled:true}:{enabled:true,field:e.field??t.field,source:e.source??t.source,headerName:e.headerName??t.headerName,contextKey:e.contextKey??t.contextKey,pathParam:e.pathParam??t.pathParam,getTenantId:e.getTenantId,required:e.required??t.required,errorMessage:e.errorMessage??t.errorMessage}:t}function N(e,t){if(t.enabled)switch(t.source){case "header":return e.req.header(t.headerName);case "context":return a(e,t.contextKey);case "path":return e.req.param(t.pathParam);case "custom":return t.getTenantId?t.getTenantId(e):void 0;default:return}}var D="__honoCrudResponseEnvelope__";function _(e){return e==="all"||e==="phrase"?e:"any"}export{T as a,h as b,C as c,k as d,w as e,R as f,A as g,I as h,P as i,y as j,F as k,O as l,S as m,v as n,M as o,N as p,D as q,_ as r};
@@ -1 +1 @@
1
- import {g,f}from'./chunk-FHABLABR.js';import {c}from'./chunk-GBQQ3YQX.js';var d=class{versions=new Map;getKey(e,n){return `${e}:${n}`}async save(e){let n=this.getKey(e.tableName||e.id.split(":")[0]||"unknown",e.recordId),r={...e,tableName:n.split(":")[0]},t=this.versions.get(n)||[];t.push(r),this.versions.set(n,t);}async store(e,n){let r=this.getKey(e,n.recordId),t=this.versions.get(r)||[];t.push({...n,tableName:e}),this.versions.set(r,t);}async getByRecordId(e,n,r){let t=this.getKey(e,n),i=[...this.versions.get(t)||[]].sort((c,o)=>o.version-c.version),g=r?.offset||0,a=r?.limit||i.length;return i.slice(g,g+a)}async getVersion(e,n,r){let t=this.getKey(e,n);return (this.versions.get(t)||[]).find(i=>i.version===r)||null}async getLatestVersion(e,n){let r=this.getKey(e,n),t=this.versions.get(r)||[];return t.length===0?0:Math.max(...t.map(s=>s.version))}async pruneVersions(e,n,r){let t=this.getKey(e,n),s=this.versions.get(t)||[];if(s.length<=r)return 0;let i=[...s].sort((c,o)=>o.version-c.version),g=i.slice(0,r),a=i.length-g.length;return this.versions.set(t,g),a}async deleteAllVersions(e,n){let r=this.getKey(e,n),s=(this.versions.get(r)||[]).length;return this.versions.delete(r),s}getAllVersions(){let e=[];for(let n of this.versions.values())e.push(...n);return e}clear(){this.versions.clear();}},h=c("versioningStorage",()=>new d);function p(u){h.set(u);}function E(){return h.getRequired()}var y=class{config;storage;tableName;constructor(e,n,r,t){this.config=g(e,n),this.tableName=n,this.storage=h.resolve(t,r);}getStorage(){if(!this.storage)throw new Error("Versioning storage not configured. Pass storage explicitly or inject versioningStorage with createCrudMiddleware().");return this.storage}isEnabled(){return this.config.enabled}getVersionField(){return this.config.field}getHistoryTable(){return this.config.historyTable}async saveVersion(e,n,r,t,s){if(!this.isEnabled())return n[this.config.field]||1;let i=n[this.config.field]||0,g=i+1,a;r&&(a=f(r,n,this.config.excludeFields));let c=this.filterFields(n),o={id:crypto.randomUUID(),recordId:e,version:i,data:c,createdAt:new Date,changes:a};this.config.trackChangedBy&&t&&(o.changedBy=t),s&&(o.changeReason=s);let l=this.getStorage();return "store"in l&&typeof l.store=="function"?await l.store(this.tableName,o):await l.save(o),this.config.maxVersions&&l.pruneVersions&&await l.pruneVersions(this.tableName,e,this.config.maxVersions),g}async getVersions(e,n){return this.getStorage().getByRecordId(this.tableName,e,n)}async getVersion(e,n){return this.getStorage().getVersion(this.tableName,e,n)}async getVersionData(e,n){let r=await this.getVersion(e,n);return r?r.data:null}async getLatestVersion(e){return this.getStorage().getLatestVersion(this.tableName,e)}async compareVersions(e,n,r){let[t,s]=await Promise.all([this.getVersion(e,n),this.getVersion(e,r)]);return !t||!s?[]:f(t.data,s.data,this.config.excludeFields)}async deleteAllVersions(e){let n=this.getStorage();return n.deleteAllVersions?n.deleteAllVersions(this.tableName,e):0}filterFields(e){if(this.config.excludeFields.length===0)return e;let n={};for(let[r,t]of Object.entries(e))this.config.excludeFields.includes(r)||(n[r]=t);return n}};function P(u,e,n,r){return new y(u,e,n,r)}export{d as a,h as b,p as c,E as d,y as e,P as f};
1
+ import {g,f}from'./chunk-KUFOENSK.js';import {c}from'./chunk-GBQQ3YQX.js';var d=class{versions=new Map;getKey(e,n){return `${e}:${n}`}async save(e){let n=this.getKey(e.tableName||e.id.split(":")[0]||"unknown",e.recordId),r={...e,tableName:n.split(":")[0]},t=this.versions.get(n)||[];t.push(r),this.versions.set(n,t);}async store(e,n){let r=this.getKey(e,n.recordId),t=this.versions.get(r)||[];t.push({...n,tableName:e}),this.versions.set(r,t);}async getByRecordId(e,n,r){let t=this.getKey(e,n),i=[...this.versions.get(t)||[]].sort((c,o)=>o.version-c.version),g=r?.offset||0,a=r?.limit||i.length;return i.slice(g,g+a)}async getVersion(e,n,r){let t=this.getKey(e,n);return (this.versions.get(t)||[]).find(i=>i.version===r)||null}async getLatestVersion(e,n){let r=this.getKey(e,n),t=this.versions.get(r)||[];return t.length===0?0:Math.max(...t.map(s=>s.version))}async pruneVersions(e,n,r){let t=this.getKey(e,n),s=this.versions.get(t)||[];if(s.length<=r)return 0;let i=[...s].sort((c,o)=>o.version-c.version),g=i.slice(0,r),a=i.length-g.length;return this.versions.set(t,g),a}async deleteAllVersions(e,n){let r=this.getKey(e,n),s=(this.versions.get(r)||[]).length;return this.versions.delete(r),s}getAllVersions(){let e=[];for(let n of this.versions.values())e.push(...n);return e}clear(){this.versions.clear();}},h=c("versioningStorage",()=>new d);function p(u){h.set(u);}function E(){return h.getRequired()}var y=class{config;storage;tableName;constructor(e,n,r,t){this.config=g(e,n),this.tableName=n,this.storage=h.resolve(t,r);}getStorage(){if(!this.storage)throw new Error("Versioning storage not configured. Pass storage explicitly or inject versioningStorage with createCrudMiddleware().");return this.storage}isEnabled(){return this.config.enabled}getVersionField(){return this.config.field}getHistoryTable(){return this.config.historyTable}async saveVersion(e,n,r,t,s){if(!this.isEnabled())return n[this.config.field]||1;let i=n[this.config.field]||0,g=i+1,a;r&&(a=f(r,n,this.config.excludeFields));let c=this.filterFields(n),o={id:crypto.randomUUID(),recordId:e,version:i,data:c,createdAt:new Date,changes:a};this.config.trackChangedBy&&t&&(o.changedBy=t),s&&(o.changeReason=s);let l=this.getStorage();return "store"in l&&typeof l.store=="function"?await l.store(this.tableName,o):await l.save(o),this.config.maxVersions&&l.pruneVersions&&await l.pruneVersions(this.tableName,e,this.config.maxVersions),g}async getVersions(e,n){return this.getStorage().getByRecordId(this.tableName,e,n)}async getVersion(e,n){return this.getStorage().getVersion(this.tableName,e,n)}async getVersionData(e,n){let r=await this.getVersion(e,n);return r?r.data:null}async getLatestVersion(e){return this.getStorage().getLatestVersion(this.tableName,e)}async compareVersions(e,n,r){let[t,s]=await Promise.all([this.getVersion(e,n),this.getVersion(e,r)]);return !t||!s?[]:f(t.data,s.data,this.config.excludeFields)}async deleteAllVersions(e){let n=this.getStorage();return n.deleteAllVersions?n.deleteAllVersions(this.tableName,e):0}filterFields(e){if(this.config.excludeFields.length===0)return e;let n={};for(let[r,t]of Object.entries(e))this.config.excludeFields.includes(r)||(n[r]=t);return n}};function P(u,e,n,r){return new y(u,e,n,r)}export{d as a,h as b,p as c,E as d,y as e,P as f};
@@ -1 +1 @@
1
- import {d}from'./chunk-4CM6OCS3.js';var m=class{entriesById=new Map;entryIds=[];maxEntries;maxAge;cleanupInterval;lastCleanup=0;constructor(e){this.maxEntries=e?.maxEntries??1e4,this.maxAge=e?.maxAge??864e5,this.cleanupInterval=e?.cleanupInterval??3e5;}maybeCleanup(){if(this.cleanupInterval<=0||this.maxAge<=0)return;let e=Date.now();e-this.lastCleanup>=this.cleanupInterval&&(this.lastCleanup=e,this.deleteOlderThanSync(this.maxAge));}deleteOlderThanSync(e){let n=Date.now()-e,a=0;for(let t=this.entryIds.length-1;t>=0;t--){let s=this.entryIds[t],r=this.entriesById.get(s);if(r)if(new Date(r.timestamp).getTime()<n)this.entriesById.delete(s),this.entryIds.splice(t,1),a++;else break}return a}async store(e){for(this.maybeCleanup();this.entryIds.length>=this.maxEntries;){let n=this.entryIds.pop();n&&this.entriesById.delete(n);}this.entriesById.set(e.id,e),this.entryIds.unshift(e.id);}async query(e){this.maybeCleanup();let n=this.getFilteredEntries(e);if(e?.sort){let{field:s,direction:r}=e.sort;n=n.sort((i,o)=>{let g,u;switch(s){case "timestamp":g=new Date(i.timestamp).getTime(),u=new Date(o.timestamp).getTime();break;case "responseTimeMs":g=i.response.responseTimeMs,u=o.response.responseTimeMs;break;case "statusCode":g=i.response.statusCode,u=o.response.statusCode;break;default:return 0}return r==="asc"?g-u:u-g});}let a=e?.offset??0,t=e?.limit??n.length;return n.slice(a,a+t)}async getById(e){return this.entriesById.get(e)??null}async count(e){return this.getFilteredEntries(e).length}async deleteOlderThan(e){return this.deleteOlderThanSync(e)}async clear(){let e=this.entriesById.size;return this.entriesById.clear(),this.entryIds=[],e}destroy(){this.entriesById.clear(),this.entryIds=[];}getSize(){return this.entriesById.size}getFilteredEntries(e){if(!e)return Array.from(this.entriesById.values());let n=[];for(let a of this.entryIds){let t=this.entriesById.get(a);if(t&&!(e.level&&!(Array.isArray(e.level)?e.level:[e.level]).includes(t.level))&&!(e.method&&!(Array.isArray(e.method)?e.method:[e.method]).map(r=>r.toUpperCase()).includes(t.request.method.toUpperCase()))&&!(e.path&&!d(t.request.path,e.path))){if(e.statusCode){let{min:s,max:r}=e.statusCode,i=t.response.statusCode;if(s!==void 0&&i<s||r!==void 0&&i>r)continue}if(e.timeRange){let s=new Date(t.timestamp).getTime(),{start:r,end:i}=e.timeRange;if(r){let o=typeof r=="string"?new Date(r).getTime():r.getTime();if(s<o)continue}if(i){let o=typeof i=="string"?new Date(i).getTime():i.getTime();if(s>o)continue}}e.userId&&t.request.userId!==e.userId||e.clientIp&&t.request.clientIp!==e.clientIp||e.requestId&&t.id!==e.requestId||e.errorMessage&&(!t.error?.message||!t.error.message.toLowerCase().includes(e.errorMessage.toLowerCase()))||n.push(t);}}return n}};export{m as a};
1
+ import {d}from'./chunk-IPMPKM4J.js';var m=class{entriesById=new Map;entryIds=[];maxEntries;maxAge;cleanupInterval;lastCleanup=0;constructor(e){this.maxEntries=e?.maxEntries??1e4,this.maxAge=e?.maxAge??864e5,this.cleanupInterval=e?.cleanupInterval??3e5;}maybeCleanup(){if(this.cleanupInterval<=0||this.maxAge<=0)return;let e=Date.now();e-this.lastCleanup>=this.cleanupInterval&&(this.lastCleanup=e,this.deleteOlderThanSync(this.maxAge));}deleteOlderThanSync(e){let n=Date.now()-e,a=0;for(let t=this.entryIds.length-1;t>=0;t--){let s=this.entryIds[t],r=this.entriesById.get(s);if(r)if(new Date(r.timestamp).getTime()<n)this.entriesById.delete(s),this.entryIds.splice(t,1),a++;else break}return a}async store(e){for(this.maybeCleanup();this.entryIds.length>=this.maxEntries;){let n=this.entryIds.pop();n&&this.entriesById.delete(n);}this.entriesById.set(e.id,e),this.entryIds.unshift(e.id);}async query(e){this.maybeCleanup();let n=this.getFilteredEntries(e);if(e?.sort){let{field:s,direction:r}=e.sort;n=n.sort((i,o)=>{let g,u;switch(s){case "timestamp":g=new Date(i.timestamp).getTime(),u=new Date(o.timestamp).getTime();break;case "responseTimeMs":g=i.response.responseTimeMs,u=o.response.responseTimeMs;break;case "statusCode":g=i.response.statusCode,u=o.response.statusCode;break;default:return 0}return r==="asc"?g-u:u-g});}let a=e?.offset??0,t=e?.limit??n.length;return n.slice(a,a+t)}async getById(e){return this.entriesById.get(e)??null}async count(e){return this.getFilteredEntries(e).length}async deleteOlderThan(e){return this.deleteOlderThanSync(e)}async clear(){let e=this.entriesById.size;return this.entriesById.clear(),this.entryIds=[],e}destroy(){this.entriesById.clear(),this.entryIds=[];}getSize(){return this.entriesById.size}getFilteredEntries(e){if(!e)return Array.from(this.entriesById.values());let n=[];for(let a of this.entryIds){let t=this.entriesById.get(a);if(t&&!(e.level&&!(Array.isArray(e.level)?e.level:[e.level]).includes(t.level))&&!(e.method&&!(Array.isArray(e.method)?e.method:[e.method]).map(r=>r.toUpperCase()).includes(t.request.method.toUpperCase()))&&!(e.path&&!d(t.request.path,e.path))){if(e.statusCode){let{min:s,max:r}=e.statusCode,i=t.response.statusCode;if(s!==void 0&&i<s||r!==void 0&&i>r)continue}if(e.timeRange){let s=new Date(t.timestamp).getTime(),{start:r,end:i}=e.timeRange;if(r){let o=typeof r=="string"?new Date(r).getTime():r.getTime();if(s<o)continue}if(i){let o=typeof i=="string"?new Date(i).getTime():i.getTime();if(s>o)continue}}e.userId&&t.request.userId!==e.userId||e.clientIp&&t.request.clientIp!==e.clientIp||e.requestId&&t.id!==e.requestId||e.errorMessage&&(!t.error?.message||!t.error.message.toLowerCase().includes(e.errorMessage.toLowerCase()))||n.push(t);}}return n}};export{m as a};