hono-crud 0.13.9 → 0.13.11

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 (56) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/dist/api-version/index.js +1 -1
  3. package/dist/audit/index.d.ts +18 -14
  4. package/dist/audit/index.js +1 -1
  5. package/dist/auth/index.d.ts +4 -4
  6. package/dist/auth/index.js +1 -1
  7. package/dist/{chunk-B3II5FPG.js → chunk-4KMRJFCY.js} +1 -1
  8. package/dist/chunk-5HFTJZQX.js +11 -0
  9. package/dist/chunk-6GO5LUOZ.js +1 -0
  10. package/dist/chunk-DALXO46J.js +1 -0
  11. package/dist/chunk-JEOLCWK3.js +1 -0
  12. package/dist/chunk-JNRSTMFA.js +1 -0
  13. package/dist/chunk-MCXQ77DB.js +1 -0
  14. package/dist/{chunk-MKMMXMDX.js → chunk-NEBNG4DP.js} +1 -1
  15. package/dist/chunk-OCJC5XWY.js +1 -0
  16. package/dist/chunk-QFPEE4LH.js +1 -0
  17. package/dist/chunk-VESRPXGC.js +1 -0
  18. package/dist/{chunk-MGYAQGMG.js → chunk-WECW5WB3.js} +1 -1
  19. package/dist/config/index.d.ts +5 -5
  20. package/dist/{emitter-B7QIE5f9.d.ts → emitter-B6dLhiMF.d.ts} +8 -4
  21. package/dist/events/index.d.ts +2 -2
  22. package/dist/events/index.js +1 -1
  23. package/dist/functional/index.d.ts +3 -3
  24. package/dist/helpers-C3xy6C9u.d.ts +515 -0
  25. package/dist/{index-Coira0ZO.d.ts → index-BWwvlRfM.d.ts} +3 -3
  26. package/dist/{index-Rm1UKAWZ.d.ts → index-CZZ12W3j.d.ts} +5 -5
  27. package/dist/{index-DVizFuqF.d.ts → index-DHJ4DeUp.d.ts} +70 -49
  28. package/dist/index.d.ts +14 -14
  29. package/dist/index.js +1 -1
  30. package/dist/internal.d.ts +56 -16
  31. package/dist/internal.js +1 -1
  32. package/dist/logging/index.d.ts +4 -87
  33. package/dist/logging/index.js +1 -1
  34. package/dist/{types-CpinG1az.d.ts → middleware-DBIpdsJ1.d.ts} +89 -2
  35. package/dist/multi-tenant/index.js +1 -1
  36. package/dist/{registry-PNJjvSvm.d.ts → registry-3p4qTDGZ.d.ts} +7 -4
  37. package/dist/{route-BsBxrEW1.d.ts → route-BULuf1Xl.d.ts} +1 -1
  38. package/dist/serialization/index.d.ts +1 -1
  39. package/dist/storage/index.d.ts +66 -185
  40. package/dist/storage/index.js +1 -1
  41. package/dist/{types-DcRAcexC.d.ts → types-B5wq2iKZ.d.ts} +1 -1
  42. package/dist/{types-CmzJjItf.d.ts → types-C_OAPSsu.d.ts} +14 -3
  43. package/dist/{types-Bfdb_zwM.d.ts → types-DXVXRfuq.d.ts} +1 -1
  44. package/dist/versioning/index.d.ts +20 -17
  45. package/dist/versioning/index.js +1 -1
  46. package/package.json +1 -1
  47. package/dist/chunk-4NKDESHS.js +0 -1
  48. package/dist/chunk-FOJBZJRS.js +0 -1
  49. package/dist/chunk-GMP7FCND.js +0 -11
  50. package/dist/chunk-HIDT3P5C.js +0 -1
  51. package/dist/chunk-IJBJE4G2.js +0 -1
  52. package/dist/chunk-P5JQKX7Z.js +0 -1
  53. package/dist/chunk-UAVAEDVS.js +0 -1
  54. package/dist/chunk-WZFVYTTE.js +0 -1
  55. package/dist/chunk-XCDY63Q6.js +0 -1
  56. package/dist/chunk-ZJWDAVGG.js +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,34 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.13.11
4
+
5
+ ### Patch Changes
6
+
7
+ - 97e92f5: Dedup batch: the edge-safe in-memory TTL machinery, the cache entry wire format, and the relation-batching control flow each now live in exactly one place.
8
+
9
+ - New internal `MemoryTtlStore` in core (exported via `hono-crud/internal`) owns lazy cleanup-on-access, expiry-on-read, and insertion-order capacity eviction. The cache, rate-limit, and idempotency memory storages compose it, supplying only their entry shapes and domain indices (cache tag index via an eviction hook, idempotency locks as a second store). Public constructor options are unchanged. The logging memory storage intentionally stays standalone — its newest-first ordering is a different structure, not drift.
10
+ - New cache entry codec (`packages/cache/src/entry.ts`, internal): `buildCacheEntry` / `normalizeStoredEntry` / `isCacheEntryExpired` shared by the memory, Redis, and Cloudflare KV backends — including the single canonical legacy-Date migration guard, so already-persisted entries keep reading identically.
11
+ - New relation-batching orchestrator in core (exported via `hono-crud/internal`): the ORM-agnostic control flow (key collection, grouping, map-back, lookup-map dispatch over hasOne/hasMany/belongsTo) is shared; drizzle, prisma, and memory supply only their query adapters. N+1 batching fixes now land in one place.
12
+ - Two deliberate behavior fixes that the dedup surfaced: (1) single-item relation reads in the memory and drizzle adapters now always set the relation key (`null` / `[]` instead of absent), matching the batch path and prisma — this also fixes memory's belongsTo gating on the row's own `id` instead of the foreign key; (2) the rate-limit fixed window no longer slides its stored expiry on within-window increments — the window keeps its original `windowStart + windowMs` end.
13
+ - Internal-only removals (never publicly exported): memory's `loadRelation`, prisma's `loadPrismaRelation`.
14
+
15
+ ## 0.13.10
16
+
17
+ ### Patch Changes
18
+
19
+ - 8244828: Storage unification (breaking, patch): one injection story and one contract shape for all eight first-party storages.
20
+
21
+ - `createCrudMiddleware` / `CrudMiddlewareConfig` are removed. `createStorageMiddleware` is the single injection middleware and now accepts all eight slots (`loggingStorage`, `auditStorage`, `versioningStorage`, `apiKeyStorage`, `cacheStorage`, `rateLimitStorage`, `idempotencyStorage`, `eventEmitter`), each writing the matching `CONTEXT_KEYS` context var. New single-storage factories: `createCacheStorageMiddleware`, `createRateLimitStorageMiddleware`, `createIdempotencyStorageMiddleware`.
22
+ - `CONTEXT_KEYS` (now exported from `hono-crud` and `hono-crud/internal`) is the complete registry of context-var keys, adding `db`, `cacheStorage`, `rateLimitStorage`, `idempotencyStorage`, `rateLimit`, `rateLimitKey`, `responseEnvelope`, `policies`. All key strings are unchanged; cache/rate-limit/idempotency context resolution is now actually live (previously their context tier read keys no middleware wrote).
23
+ - Every storage feature exposes the same two-getter contract: `getXStorage(): T | null` (never throws) plus `getXStorageRequired(): T`. Consequences: `getAuditStorage` / `getVersioningStorage` / `getCacheStorage` return types are now nullable (`getCacheStorage` stays never-null at runtime via its lazy memory default); `getIdempotencyStorage` no longer throws — the old throwing behavior moved to `getIdempotencyStorageRequired`. New: `getLoggingStorageRequired`, `getAuditStorageRequired`, `getVersioningStorageRequired`, `getCacheStorageRequired`, `getRateLimitStorageRequired`, `getIdempotencyStorageRequired`.
24
+ - `VersioningStorage.save(entry)` is renamed to `store(tableName, entry)` — interface method rename; third-party implementations must update. The `entry.id.split(':')` table-name hack is gone and `VersionManager` no longer duck-types.
25
+ - `CacheStorage.set` option `ttl` (seconds) is now `ttlMs` (milliseconds); cache storage constructors take `defaultTtlMs` (default `300_000`) instead of `defaultTtl`. User-facing `CacheConfig.ttl` stays seconds and is converted once in the mixin.
26
+ - `IdempotencyStorage.destroy` is now optional and `cleanup?(): Promise<number>` is part of the optional contract (the memory implementation's cleanup returns the number of entries removed).
27
+ - `APIKeyConfig.lookupKey` is now optional and `APIKeyConfig.storage?: APIKeyStorage` was added; the API-key middleware resolves storage through the registry (explicit > context > global), so `setAPIKeyStorage` is no longer a silent no-op. Configs with neither `lookupKey` nor a resolvable storage throw `ConfigurationException`.
28
+ - The `CacheStorage` / `RateLimitStorage` / `IdempotencyStorage` contracts now live in core and are re-exported by their plugins via `hono-crud/internal` (type identity preserved).
29
+ - Endpoints now thread the request context into audit/versioning managers, so context-injected storage is honored (previously silently ignored).
30
+ - Non-breaking type tightening: `POLICIES_CONTEXT_KEY` narrows from `string` to its literal type.
31
+
3
32
  ## 0.13.9
4
33
 
5
34
  ### Patch Changes
@@ -1 +1 @@
1
- export{a as apiVersion,b as getApiVersion,c as getApiVersionConfig,d as versionedResponse}from'../chunk-MKMMXMDX.js';import'../chunk-A3O6KC4L.js';import'../chunk-IJBJE4G2.js';
1
+ export{a as apiVersion,b as getApiVersion,c as getApiVersionConfig,d as versionedResponse}from'../chunk-NEBNG4DP.js';import'../chunk-A3O6KC4L.js';import'../chunk-6GO5LUOZ.js';
@@ -1,8 +1,8 @@
1
- import { Context, Env } from 'hono';
2
- import { A as AuditConfig, f as AuditLogEntry, g as AuditAction } from '../types-CmzJjItf.js';
3
- import { S as StorageRegistry } from '../registry-PNJjvSvm.js';
1
+ import { Context } from 'hono';
2
+ import { A as AuditConfig, f as AuditLogEntry, g as AuditAction } from '../types-C_OAPSsu.js';
3
+ import { S as StorageRegistry } from '../registry-3p4qTDGZ.js';
4
4
  import 'zod';
5
- import '../types-DcRAcexC.js';
5
+ import '../types-B5wq2iKZ.js';
6
6
  import '../types-Drjma4gp.js';
7
7
  import '@hono/zod-openapi';
8
8
 
@@ -34,6 +34,8 @@ interface AuditLogStorage {
34
34
  limit?: number;
35
35
  offset?: number;
36
36
  }): Promise<AuditLogEntry[]>;
37
+ /** Release resources (timers, connections). Optional, edge-safe. */
38
+ destroy?(): void;
37
39
  }
38
40
  /**
39
41
  * In-memory audit log storage for testing.
@@ -64,27 +66,29 @@ declare class MemoryAuditLogStorage implements AuditLogStorage {
64
66
  clear(): void;
65
67
  }
66
68
  /**
67
- * Global audit log storage registry.
68
- * Compatibility getters can still create a MemoryAuditLogStorage lazily, but
69
- * request-time audit resolution requires explicit, context, or configured
70
- * global storage.
69
+ * Global audit log storage registry (exported for helpers/tests).
71
70
  */
72
71
  declare const auditStorageRegistry: StorageRegistry<AuditLogStorage>;
73
72
  /**
74
73
  * Set the global audit log storage.
75
74
  */
76
- declare function setAuditStorage(storage: AuditLogStorage): void;
75
+ declare const setAuditStorage: (storage: AuditLogStorage) => void;
77
76
  /**
78
- * Get the global audit log storage.
77
+ * Get the global audit log storage, or null when none was configured.
79
78
  */
80
- declare function getAuditStorage(): AuditLogStorage;
79
+ declare const getAuditStorage: () => AuditLogStorage | null;
80
+ /**
81
+ * Get the global audit log storage, lazily creating a MemoryAuditLogStorage
82
+ * default when none was configured.
83
+ */
84
+ declare const getAuditStorageRequired: () => AuditLogStorage;
81
85
  /**
82
86
  * Audit logger class for creating audit log entries.
83
87
  */
84
88
  declare class AuditLogger {
85
89
  private config;
86
90
  private storage;
87
- constructor(config: AuditConfig | undefined, storage?: AuditLogStorage, ctx?: Context<Env>);
91
+ constructor(config: AuditConfig | undefined, storage?: AuditLogStorage, ctx?: Context);
88
92
  private getStorage;
89
93
  /**
90
94
  * Check if audit logging is enabled for an action.
@@ -147,6 +151,6 @@ declare class AuditLogger {
147
151
  * const logger = createAuditLogger(config, myStorage);
148
152
  * ```
149
153
  */
150
- declare function createAuditLogger(config: AuditConfig | undefined, storage?: AuditLogStorage, ctx?: Context<Env>): AuditLogger;
154
+ declare function createAuditLogger(config: AuditConfig | undefined, storage?: AuditLogStorage, ctx?: Context): AuditLogger;
151
155
 
152
- export { type AuditLogStorage, AuditLogger, MemoryAuditLogStorage, auditStorageRegistry, createAuditLogger, getAuditStorage, setAuditStorage };
156
+ export { type AuditLogStorage, AuditLogger, MemoryAuditLogStorage, auditStorageRegistry, createAuditLogger, getAuditStorage, getAuditStorageRequired, setAuditStorage };
@@ -1 +1 @@
1
- export{e as AuditLogger,a as MemoryAuditLogStorage,b as auditStorageRegistry,f as createAuditLogger,d as getAuditStorage,c as setAuditStorage}from'../chunk-UAVAEDVS.js';import'../chunk-EX4S3Q4M.js';import'../chunk-ZJWDAVGG.js';import'../chunk-VJRDAVID.js';import'../chunk-IJBJE4G2.js';
1
+ export{f as AuditLogger,a as MemoryAuditLogStorage,b as auditStorageRegistry,g as createAuditLogger,d as getAuditStorage,e as getAuditStorageRequired,c as setAuditStorage}from'../chunk-MCXQ77DB.js';import'../chunk-EX4S3Q4M.js';import'../chunk-OCJC5XWY.js';import'../chunk-VJRDAVID.js';import'../chunk-6GO5LUOZ.js';
@@ -1,9 +1,9 @@
1
- export { l as APIKeyConfig, m as APIKeyEntry, n as APIKeyLookupResult, o as ActionSource, w as ApprovalConfig, x as ApprovalStorage, y as AuthConfig, z as AuthEnv, B as AuthType, C as AuthUser, D as AuthorizationCheck, Q as EndpointAuthConfig, X as Guard, a4 as JWTAlgorithm, a5 as JWTClaims, a6 as JWTClaimsSchema, a7 as JWTConfig, a8 as JWT_ALGORITHMS, an as OwnershipExtractor, aV as PathPattern, aq as PendingAction, ar as PendingActionStatus, aL as ValidatedJWTClaims, aR as parseJWTClaims, aS as safeParseJWTClaims } from '../types-CmzJjItf.js';
2
- export { A as AuthEndpointMethods, a as AuthenticatedEndpoint, J as JWTClaimsValidationOptions, M as MemoryAPIKeyStorage, b as MemoryApprovalStorage, P as POLICIES_CONTEXT_KEY, c as allOf, d as allowAll, e as anyOf, f as createAPIKeyMiddleware, g as createAuthMiddleware, h as createJWTMiddleware, i as decodeJWT, j as defaultHashAPIKey, k as denyAll, m as generateAPIKey, n as getAPIKeyStorage, o as hashAPIKey, p as isValidAPIKeyFormat, q as optionalAuth, r as parseIso8601Duration, s as requireAllRoles, t as requireAnyPermission, u as requireApproval, v as requireAuth, w as requireAuthenticated, x as requireAuthentication, y as requireOwnership, z as requireOwnershipOrRole, B as requirePermissions, C as requirePolicy, D as requireRoles, E as setAPIKeyStorage, F as validateAPIKey, G as validateAPIKeyEntry, H as validateJWTClaims, I as verifyJWT, K as withAuth } from '../index-Rm1UKAWZ.js';
1
+ export { n as APIKeyConfig, o as APIKeyEntry, p as APIKeyLookupResult, q as ActionSource, y as ApprovalConfig, z as ApprovalStorage, B as AuthConfig, C as AuthEnv, D as AuthType, E as AuthUser, G as AuthorizationCheck, U as EndpointAuthConfig, Z as Guard, a5 as JWTAlgorithm, a6 as JWTClaims, a7 as JWTClaimsSchema, a8 as JWTConfig, a9 as JWT_ALGORITHMS, ao as OwnershipExtractor, aW as PathPattern, ar as PendingAction, as as PendingActionStatus, aL as ValidatedJWTClaims, aR as parseJWTClaims, aS as safeParseJWTClaims } from '../types-C_OAPSsu.js';
2
+ export { A as AuthEndpointMethods, a as AuthenticatedEndpoint, J as JWTClaimsValidationOptions, M as MemoryAPIKeyStorage, b as MemoryApprovalStorage, P as POLICIES_CONTEXT_KEY, c as allOf, d as allowAll, e as anyOf, f as createAPIKeyMiddleware, g as createAuthMiddleware, h as createJWTMiddleware, i as decodeJWT, j as defaultHashAPIKey, k as denyAll, m as generateAPIKey, n as getAPIKeyStorage, o as hashAPIKey, p as isValidAPIKeyFormat, q as optionalAuth, r as parseIso8601Duration, s as requireAllRoles, t as requireAnyPermission, u as requireApproval, v as requireAuth, w as requireAuthenticated, x as requireAuthentication, y as requireOwnership, z as requireOwnershipOrRole, B as requirePermissions, C as requirePolicy, D as requireRoles, E as setAPIKeyStorage, F as validateAPIKey, G as validateAPIKeyEntry, H as validateJWTClaims, I as verifyJWT, K as withAuth } from '../index-CZZ12W3j.js';
3
3
  import 'hono';
4
4
  import 'zod';
5
- import '../types-DcRAcexC.js';
5
+ import '../types-B5wq2iKZ.js';
6
6
  import '../types-Drjma4gp.js';
7
7
  import '@hono/zod-openapi';
8
- import '../route-BsBxrEW1.js';
8
+ import '../route-BULuf1Xl.js';
9
9
  import 'hono/utils/http-status';
@@ -1 +1 @@
1
- export{X as AuthenticatedEndpoint,I as JWTClaimsSchema,H as JWT_ALGORITHMS,q as MemoryApprovalStorage,s as POLICIES_CONTEXT_KEY,A as allOf,D as allowAll,B as anyOf,S as createAPIKeyMiddleware,U as createAuthMiddleware,N as createJWTMiddleware,P as decodeJWT,R as defaultHashAPIKey,C as denyAll,V as optionalAuth,r as parseIso8601Duration,J as parseJWTClaims,u as requireAllRoles,w as requireAnyPermission,G as requireApproval,x as requireAuth,E as requireAuthenticated,W as requireAuthentication,y as requireOwnership,z as requireOwnershipOrRole,v as requirePermissions,F as requirePolicy,t as requireRoles,K as safeParseJWTClaims,T as validateAPIKey,Q as validateAPIKeyEntry,L as validateJWTClaims,O as verifyJWT,Y as withAuth}from'../chunk-WZFVYTTE.js';export{a as MemoryAPIKeyStorage,b as generateAPIKey,f as getAPIKeyStorage,c as hashAPIKey,d as isValidAPIKeyFormat,g as setAPIKeyStorage}from'../chunk-4NKDESHS.js';import'../chunk-NWOJZP4P.js';import'../chunk-A3O6KC4L.js';import'../chunk-DMGP7QDL.js';import'../chunk-ZJWDAVGG.js';import'../chunk-VJRDAVID.js';import'../chunk-IJBJE4G2.js';
1
+ export{X as AuthenticatedEndpoint,I as JWTClaimsSchema,H as JWT_ALGORITHMS,q as MemoryApprovalStorage,s as POLICIES_CONTEXT_KEY,A as allOf,D as allowAll,B as anyOf,S as createAPIKeyMiddleware,U as createAuthMiddleware,N as createJWTMiddleware,P as decodeJWT,R as defaultHashAPIKey,C as denyAll,V as optionalAuth,r as parseIso8601Duration,J as parseJWTClaims,u as requireAllRoles,w as requireAnyPermission,G as requireApproval,x as requireAuth,E as requireAuthenticated,W as requireAuthentication,y as requireOwnership,z as requireOwnershipOrRole,v as requirePermissions,F as requirePolicy,t as requireRoles,K as safeParseJWTClaims,T as validateAPIKey,Q as validateAPIKeyEntry,L as validateJWTClaims,O as verifyJWT,Y as withAuth}from'../chunk-QFPEE4LH.js';export{a as MemoryAPIKeyStorage,b as generateAPIKey,e as getAPIKeyStorage,c as hashAPIKey,d as isValidAPIKeyFormat,f as setAPIKeyStorage}from'../chunk-DALXO46J.js';import'../chunk-NWOJZP4P.js';import'../chunk-VESRPXGC.js';import'../chunk-A3O6KC4L.js';import'../chunk-MCXQ77DB.js';import'../chunk-EX4S3Q4M.js';import'../chunk-DMGP7QDL.js';import'../chunk-OCJC5XWY.js';import'../chunk-VJRDAVID.js';import'../chunk-6GO5LUOZ.js';
@@ -1 +1 @@
1
- import {k}from'./chunk-P5JQKX7Z.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 s=Date.now()-e,a=0;for(let t=this.entryIds.length-1;t>=0;t--){let n=this.entryIds[t],r=this.entriesById.get(n);if(r)if(new Date(r.timestamp).getTime()<s)this.entriesById.delete(n),this.entryIds.splice(t,1),a++;else break}return a}async store(e){for(this.maybeCleanup();this.entryIds.length>=this.maxEntries;){let s=this.entryIds.pop();s&&this.entriesById.delete(s);}this.entriesById.set(e.id,e),this.entryIds.unshift(e.id);}async query(e){this.maybeCleanup();let s=this.getFilteredEntries(e);if(e?.sort){let{field:n,direction:r}=e.sort;s=s.sort((i,o)=>{let g,d;switch(n){case "timestamp":g=new Date(i.timestamp).getTime(),d=new Date(o.timestamp).getTime();break;case "responseTimeMs":g=i.response.responseTimeMs,d=o.response.responseTimeMs;break;case "statusCode":g=i.response.statusCode,d=o.response.statusCode;break;default:return 0}return r==="asc"?g-d:d-g});}let a=e?.offset??0,t=e?.limit??s.length;return s.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 s=[];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&&!k(t.request.path,e.path))){if(e.statusCode){let{min:n,max:r}=e.statusCode,i=t.response.statusCode;if(n!==void 0&&i<n||r!==void 0&&i>r)continue}if(e.timeRange){let n=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(n<o)continue}if(i){let o=typeof i=="string"?new Date(i).getTime():i.getTime();if(n>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()))||s.push(t);}}return s}};export{m as a};
1
+ import {u}from'./chunk-DALXO46J.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 s=Date.now()-e,a=0;for(let t=this.entryIds.length-1;t>=0;t--){let n=this.entryIds[t],r=this.entriesById.get(n);if(r)if(new Date(r.timestamp).getTime()<s)this.entriesById.delete(n),this.entryIds.splice(t,1),a++;else break}return a}async store(e){for(this.maybeCleanup();this.entryIds.length>=this.maxEntries;){let s=this.entryIds.pop();s&&this.entriesById.delete(s);}this.entriesById.set(e.id,e),this.entryIds.unshift(e.id);}async query(e){this.maybeCleanup();let s=this.getFilteredEntries(e);if(e?.sort){let{field:n,direction:r}=e.sort;s=s.sort((i,o)=>{let g,d;switch(n){case "timestamp":g=new Date(i.timestamp).getTime(),d=new Date(o.timestamp).getTime();break;case "responseTimeMs":g=i.response.responseTimeMs,d=o.response.responseTimeMs;break;case "statusCode":g=i.response.statusCode,d=o.response.statusCode;break;default:return 0}return r==="asc"?g-d:d-g});}let a=e?.offset??0,t=e?.limit??s.length;return s.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 s=[];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&&!u(t.request.path,e.path))){if(e.statusCode){let{min:n,max:r}=e.statusCode,i=t.response.statusCode;if(n!==void 0&&i<n||r!==void 0&&i>r)continue}if(e.timeRange){let n=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(n<o)continue}if(i){let o=typeof i=="string"?new Date(i).getTime():i.getTime();if(n>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()))||s.push(t);}}return s}};export{m as a};
@@ -0,0 +1,11 @@
1
+ import {a as a$6,b as b$3}from'./chunk-PDHKGPGZ.js';import {m,n,p,f,b as b$2,d as d$1,c as c$1,e,o,s,l}from'./chunk-QFPEE4LH.js';import {G as G$1}from'./chunk-DALXO46J.js';import {h,a as a$5}from'./chunk-VESRPXGC.js';import {a,b,i,d,c}from'./chunk-A3O6KC4L.js';import {g}from'./chunk-MCXQ77DB.js';import {a as a$3}from'./chunk-EX4S3Q4M.js';import {a as a$2}from'./chunk-STAO4FWC.js';import {e as e$1,f as f$1}from'./chunk-6MS7YXSZ.js';import {d as d$2}from'./chunk-JNRSTMFA.js';import {b as b$1}from'./chunk-DMGP7QDL.js';import {a as a$1,b as b$4}from'./chunk-VJRDAVID.js';import {a as a$4}from'./chunk-6GO5LUOZ.js';import {OpenAPIHono,createRoute}from'@hono/zod-openapi';import {z,ZodError}from'zod';import {HTTPException}from'hono/http-exception';import {streamSSE,stream}from'hono/streaming';var Qt=new WeakMap;function tt(n){return Qt.get(n)}var Me=class{app;options;routes=new Map;constructor(e,t={}){this.app=e,this.options={docs_url:"/docs",redoc_url:"/redoc",openapi_url:"/openapi.json",...t};}registerRoute(e,t,o,r=[]){let s=`${e.toUpperCase()} ${t}`,i=o,l=new i().getSchema();this.routes.set(s,{method:e,path:t,schema:l,routeClass:o});let c=createRoute({method:e,path:this.convertPath(t),...l,responses:l.responses||{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}});if(r.length>0)for(let a of r)this.app.use(t,async(d,p)=>{if(d.req.method.toLowerCase()===e)return a(d,p);await p();});this.app.openapi(c,async a$1=>{let d=new i;d.setContext(a$1);try{return await d.handle()}catch(p){if(p instanceof a){let m$1=p.toJSON(),h=m(a$1);return h?n(a$1,h.error(m$1.error),p.status):n(a$1,m$1,p.status)}throw p}});}convertPath(e){return e.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,"{$1}")}setupDocs(e,t){let o=e??this.options.openapi_url??"/openapi.json";this.app.doc(o,{openapi:t.openapi||"3.1.0",info:t.info,servers:t.servers,security:t.security});}getApp(){return this.app}getRegisteredRoutes(){return this.routes}toOpenApiPath(e){return this.convertPath(e)}};function ho(n=new OpenAPIHono,e={}){let t="openAPIRegistry"in n?n:new OpenAPIHono,o=new Me(t,e),r=["get","post","put","patch","delete","options","head"],s=new Proxy(t,{get(i,u){if(r.includes(u))return (c,...a)=>{let d=a[a.length-1];if(p(d)){let p=a.slice(0,-1);return o.registerRoute(u,c,d,p),s}return i[u](c,...a)};if(u==="doc")return (c,a)=>{o.setupDocs(c,a);};if(u==="use")return (...c)=>(i[u](...c),s);let l=i[u];return typeof l=="function"?l.bind(i):l}});return Qt.set(s,o),s}var yo=6e4,wo={openapi:"3.1.0",info:{title:"API",version:"1.0.0"}};async function Mo(n,e,t={}){let o=tt(n);if(!o)throw new Error("buildPerTenantOpenApi: app was not produced by fromHono(...). Cannot find route registry.");let r=t.config??wo,s=`openapi:${e.tenantId??"global"}:${r.info.version}`;if(t.cache){let c=await t.cache.get(s);if(c!=null)return c}let i=new OpenAPIHono;for(let c of o.getRegisteredRoutes().values()){let a=c.routeClass,d=new a,p=Eo(e);d.setContext(p),typeof d.resolveModelSchema=="function"&&await d.resolveModelSchema();let m=d.getSchema(),h=createRoute({...m,method:c.method,path:o.toOpenApiPath(c.path),responses:m.responses??{200:{description:"Success",content:{"application/json":{schema:z.unknown()}}}}});i.openapi(h,()=>new Response);}let u={openapi:r.openapi??"3.1.0",info:r.info,servers:r.servers,security:r.security},l=t.spec==="3.0"?i.getOpenAPIDocument(u):i.getOpenAPI31Document(u);return t.cache&&await t.cache.set(s,l,t.cacheTtlMs??yo),l}function Eo(n){let e={};n.tenantId!==void 0&&(e.tenantId=n.tenantId),n.organizationId!==void 0&&(e.organizationId=n.organizationId);let t=n.request??new Request("http://localhost/");return {var:e,env:n.env,req:{raw:t,header:()=>{},query:()=>{},param:()=>{}},set(o,r){e[o]=r;},get(o){return e[o]},executionCtx:void 0}}function Ro(n){return {async get(e){let t=await n.get(e);return t?t.data:void 0},async set(e,t,o){await n.set(e,t,o!=null?{ttlMs:o}:void 0);}}}var ko=[["create","post",""],["list","get",""],["batchCreate","post","/batch"],["batchUpdate","patch","/batch"],["batchDelete","delete","/batch"],["batchRestore","post","/batch/restore"],["batchUpsert","post","/batch/upsert"],["search","get","/search"],["aggregate","get","/aggregate"],["export","get","/export"],["import","post","/import"],["upsert","post","/upsert"],["read","get","/:id"],["update","patch","/:id"],["delete","delete","/:id"],["restore","post","/:id/restore"],["clone","post","/:id/clone"]];function Co(n){return n.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,"{$1}")}function Po(n,e){let o=`/${n}/${e}`.replace(/\/{2,}/g,"/");return o.length>1&&o.endsWith("/")?o.slice(0,-1):o}function jo(n,e={}){let t=e.basePath??"",o=e.tag,r=new OpenAPIHono,s=0;for(let[l,c,a]of ko){let d=n[l];if(!d)continue;let m=new d().getSchema(),h=o!==void 0?{...m,tags:[o]}:m,f=Po(t,Co(a)),y=createRoute({...h,method:c,path:f,responses:h.responses??{200:{description:"Success",content:{"application/json":{schema:z.unknown()}}}}});r.openapi(y,()=>new Response),s+=1;}return s===0?{}:r.getOpenAPI31Document({openapi:"3.1.0",info:{title:"hono-crud",version:"1.0.0"}}).paths??{}}var Jt=n=>{if(n instanceof ZodError)return b.fromZodError(n)};function Io(n$1={}){let{mappers:e=[],hooks:t=[],includeRequestId:o=true,includeStackTrace:r=false,defaultErrorCode:s="INTERNAL_ERROR",defaultErrorMessage:i="An internal error occurred",logUnmappedErrors:u=true,onHookError:l,responseEnvelope:c}=n$1,a$1=[...e,Jt];return async(d,p)=>{let m,h=false;if(d instanceof a)m=d,h=true;else if(d instanceof HTTPException)m=new a(d.message,d.status,"HTTP_ERROR"),h=true;else {for(let g of a$1)try{let S=await g(d,p);if(S){m=S,h=!0;break}}catch{}h||(u&&b$1().error("Unmapped error",{error:d instanceof Error?d.message:String(d)}),m=new a(i,500,s));}for(let g of t)try{let S=g(d,p,m);S instanceof Promise&&S.catch(F=>{l&&l(F,d,p);});}catch(S){l&&l(S,d,p);}let f=m.toJSON();if(o){let g=G$1(p);g&&(f.error.requestId=g);}r&&d.stack&&(f.error.stack=d.stack);let y=Yt(p,c),b=y?y.error(f.error):f;return n(p,b,m.status)}}function Yt(n,e){return m(n)??e}var ot="createdAt",rt="updatedAt";function ie(n){return n?n===true?{enabled:true,createdAt:ot,updatedAt:rt}:{enabled:true,createdAt:n.createdAt??ot,updatedAt:n.updatedAt??rt}:{enabled:false,createdAt:ot,updatedAt:rt}}function D(n,e={}){let{includePrimaryKeys:t=true}=e,o=new Set;if(t)for(let s of n.primaryKeys)o.add(s);let r=ie(n.timestamps);return r.enabled&&(o.add(r.createdAt),o.add(r.updatedAt)),[...o]}function Ao(n){return n!=null&&n!==""}function nt(n,e,t,o){let r={...n},s=e.primaryKeys[0];if(!Ao(r[s])){let u=e.id;if(typeof u=="function")r[s]=u();else if(u==="database"){if(t==="memory")throw new i("MemoryAdapter does not support id:'database' (no database to generate the key)");delete r[s];}else r[s]=o?o():crypto.randomUUID();}let i$1=ie(e.timestamps);if(i$1.enabled){let u=Date.now();i$1.createdAt in n||(r[i$1.createdAt]=u),i$1.updatedAt in n||(r[i$1.updatedAt]=u);}return r}function st(n,e){let t=ie(e.timestamps);return t.enabled?{...n,[t.updatedAt]:Date.now()}:{...n}}function it(n,e){if(e==="memory"&&n.id==="database")throw new i("MemoryAdapter does not support id:'database' (no database to generate the key)")}function at(n,e){let t={...n};for(let o of D(e))delete t[o];return t}var _o=new Set(["P2002","SQLITE_CONSTRAINT_UNIQUE","SQLITE_CONSTRAINT","23505","ER_DUP_ENTRY",1062,"1062"]),To=/UNIQUE constraint failed|duplicate key value violates unique constraint|Duplicate entry/i;function No(n){if(!n||typeof n!="object")return false;let{code:e,message:t}=n;return (typeof e=="string"||typeof e=="number")&&_o.has(e)?true:typeof t=="string"&&To.test(t)}function*Xt(n,e=8){for(let t=n,o=0;o<e&&t!=null&&typeof t=="object";o++)yield t,t=t.cause;}function Ee(n){for(let e of Xt(n))if(No(e))return new d("Unique constraint violation");return null}function W(n){throw Ee(n)??n}function Do(n){return btoa(String(n))}function Ho(n){try{return atob(n)}catch{return null}}async function ae(n,e){if(!e||Object.keys(e).length===0)return n;let t={...n};for(let[o,r]of Object.entries(e))try{let s=await r.compute(n);t[o]=s;}catch{t[o]=void 0;}return t}async function dt(n,e){return !e||Object.keys(e).length===0?n:Promise.all(n.map(t=>ae(t,e)))}function ee(n,e){let t={},o={};for(let[r,s]of Object.entries(n))e.includes(r)&&s!==void 0?o[r]=s:t[r]=s;return {mainData:t,nestedData:o}}function ge(n){if(Array.isArray(n))return true;if(typeof n=="object"&&n!==null){let e=Object.keys(n),t=["create","update","delete","connect","disconnect","set"];return !e.some(o=>t.includes(o))}return false}function Vo(n){let e=n.split(":");if(e.length<2)return null;let t=e[0].toLowerCase();return f.map(s=>s.toLowerCase()).includes(t)?{operation:t==="countdistinct"?"countDistinct":t,field:e[1],alias:e[2]}:null}function lt(n){let e=[],t={};for(let a of f){let d=n[a];if(d){let p=Array.isArray(d)?d:[d];for(let m of p)typeof m=="string"&&e.push({operation:a,field:m==="true"||m===""?"*":m});}}let o;if(n.groupBy){let a=n.groupBy;typeof a=="string"?o=a.split(",").map(d=>d.trim()):Array.isArray(a)&&(o=a.filter(d=>typeof d=="string"));}let r;for(let[a,d]of Object.entries(n)){let p=a.match(/^having\[(\w+)\]\[(\w+)\]$/);if(p){let[,m,h]=p;r||(r={}),r[m]||(r[m]={}),r[m][h]=d;}}let s=typeof n.orderBy=="string"?n.orderBy:void 0,i=n.orderDirection==="desc"?"desc":"asc",u=typeof n.limit=="string"?Number.parseInt(n.limit,10):void 0,l=typeof n.offset=="string"?Number.parseInt(n.offset,10):void 0,c=[...f,"groupBy","orderBy","orderDirection","limit","offset"];for(let[a,d]of Object.entries(n))!c.includes(a)&&!a.startsWith("having[")&&(t[a]=d);return {aggregations:e,groupBy:o,filters:Object.keys(t).length>0?t:void 0,having:r,orderBy:s,orderDirection:i,limit:u,offset:l}}function ct(n){return n?n===true?{enabled:true,field:"deletedAt",allowQueryDeleted:true,queryParam:"withDeleted"}:{enabled:true,field:n.field??"deletedAt",allowQueryDeleted:n.allowQueryDeleted??true,queryParam:n.queryParam??"withDeleted"}:{enabled:false,field:"deletedAt",allowQueryDeleted:true,queryParam:"withDeleted"}}function pt(n){let e={enabled:false,field:"tenantId",source:"context",headerName:"X-Tenant-ID",contextKey:"tenantId",pathParam:"tenantId",required:true,errorMessage:"Tenant ID is required"};return n?n===true?{...e,enabled:true}:{enabled:true,field:n.field??e.field,source:n.source??e.source,headerName:n.headerName??e.headerName,contextKey:n.contextKey??e.contextKey,pathParam:n.pathParam??e.pathParam,getTenantId:n.getTenantId,required:n.required??e.required,errorMessage:n.errorMessage??e.errorMessage}:e}function ut(n,e){return e.enabled?{header:()=>n.req.header(e.headerName),context:()=>a$1(n,e.contextKey),path:()=>n.req.param(e.pathParam),custom:()=>e.getTenantId?.(n)}[e.source]?.():void 0}var Zo=new Set(["a","an","and","are","as","at","be","by","for","from","has","he","in","is","it","its","of","on","or","that","the","to","was","were","will","with"]);function mt(n,e=true){if(!n||typeof n!="string")return [];let t=n.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter(Boolean);return e?t.filter(o=>!Zo.has(o)&&o.length>1):t}function ht(n,e){return e==="phrase"?[n.toLowerCase().trim()]:mt(n)}function to(n,e){return e.length===0?0:e.filter(o=>o===n||o.includes(n)).length/e.length}function ft(n,e,t,o){if(e.length===0)return {score:0,matchedFields:[]};let r=0,s=0,i=[];for(let[l,c]of Object.entries(t)){let a=n[l];if(a==null)continue;let d=c.weight??1;s+=d;let p;c.type==="array"&&Array.isArray(a)?p=a.join(" "):p=String(a);let m=mt(p,false),h=p.toLowerCase(),f=0,y=0;if(o==="phrase"){let b=e[0];h.includes(b)&&(f=1,y=1);}else {for(let b of e){let g=to(b,m);g>0?(y++,f+=g):h.includes(b)&&(y++,f+=.5/e.length);}e.length>0&&(f=f/e.length);}o==="all"&&y<e.length&&(f=0),f>0&&(i.push(l),r+=f*d);}return {score:s>0?Math.min(1,r/s):0,matchedFields:i}}function gt(n,e,t,o="mark",r=150){if(n==null)return [];let s;if(Array.isArray(n)?s=n.join(" "):s=String(n),!s||e.length===0)return [];let i=[],u=s.toLowerCase();if(t==="phrase"){let l=e[0],c=u.indexOf(l);if(c!==-1){let a=eo(s,c,l.length,r,o);a&&i.push(a);}}else {let l=[];for(let a of e){let d=0;for(;d<u.length;){let p=u.indexOf(a,d);if(p===-1)break;l.push({start:p,length:a.length}),d=p+1;}}l.sort((a,d)=>a.start-d.start);let c=new Set;for(let a of l){if(Array.from(c).some(m=>Math.abs(m-a.start)<r))continue;let p=eo(s,a.start,a.length,r,o);if(p&&(i.push(p),c.add(a.start)),i.length>=3)break}}return i}function eo(n,e,t,o,r){let s=Math.floor(o/2),i=Math.max(0,e-s),u=Math.min(n.length,e+t+s);if(i>0){let a=n.indexOf(" ",i);a!==-1&&a<e&&(i=a+1);}if(u<n.length){let a=n.lastIndexOf(" ",u);a!==-1&&a>e+t&&(u=a);}let l=n.slice(i,u);return i>0&&(l="..."+l),u<n.length&&(l=l+"..."),Lo(l,[n.slice(e,e+t)],r)}function Lo(n,e,t){let o=n,r=n.toLowerCase(),s=[...e].sort((i,u)=>u.length-i.length);for(let i of s){let u=i.toLowerCase(),l=0,c="",a=0;for(;a<r.length;){let d=r.indexOf(u,a);if(d===-1)break;c+=o.slice(l,d),c+=`<${t}>${o.slice(d,d+i.length)}</${t}>`,l=d+i.length,a=l;}c&&(c+=o.slice(l),o=c);}return o}function bt(n,e){if(!n)return Object.keys(e);let t=n.split(",").map(r=>r.trim()).filter(Boolean),o=Object.keys(e);return t.filter(r=>o.includes(r))}function yt(n,e){let t={};for(let o of n)t[o]={weight:e?.[o]??1};return t}function wt(n){return n==="all"||n==="phrase"?n:"any"}function Mt(n){if(n===null||typeof n!="object")return n;if(Array.isArray(n))return n.map(Mt);let e={};for(let t of Object.keys(n).sort())e[t]=Mt(n[t]);return e}async function de(n){let e=JSON.stringify(Mt(n)),t=new TextEncoder().encode(e),o=await crypto.subtle.digest("SHA-256",t);return `"${Array.from(new Uint8Array(o)).map(i=>i.toString(16).padStart(2,"0")).join("").substring(0,32)}"`}function Et(n,e){return n?n==="*"?true:n.split(",").map(t=>t.trim()).includes(e):false}function Rt(n,e){return !n||n==="*"?true:n.split(",").map(t=>t.trim()).includes(e)}function oo(n,e){return n==="in"||n==="nin"||n==="between"?e.split(",").map(t=>t.trim()):n==="null"?e.toLowerCase()==="true":e}function Uo(n){let e=n.match(/^\[([a-z]+)\](.*)$/);if(e&&b$2(e[1])){let t=e[1];return {operator:t,value:oo(t,e[2])}}return {operator:"eq",value:n}}function te(n,e){let t=[],o={},{filterFields:r=[],filterConfig:s={},searchFields:i=[],searchFieldName:u="search",sortFields:l=[],defaultSort:c,defaultPerPage:a=20,maxPerPage:d=100,cursorPaginationEnabled:p=false,softDeleteQueryParam:m="withDeleted",allowedIncludes:h=[],fieldSelectionEnabled:f=false,allowedSelectFields:y=[],blockedSelectFields:b=[],alwaysIncludeFields:g=[],defaultSelectFields:S=[]}=e,F={};for(let I of r)F[I]=["eq"];Object.assign(F,s);for(let[I,De]of Object.entries(n)){if(De==null)continue;let U=String(De);if(p&&I==="cursor"){o.cursor=U;continue}if(p&&I==="limit"){o.limit=Math.min(d,Math.max(1,Number.parseInt(U,10)||a));continue}if(I==="page"){o.page=Math.max(1,Number.parseInt(U,10)||1);continue}if(I==="per_page"){o.per_page=Math.min(d,Math.max(1,Number.parseInt(U,10)||a));continue}if(I==="sort"){(l.length===0||l.includes(U))&&(o.order_by=U);continue}if(I==="order"){(U==="asc"||U==="desc")&&(o.order_by_direction=U);continue}if(I===u&&i.length>0){o.search=U;continue}if(I===m){o.withDeleted=U.toLowerCase()==="true";continue}if(I==="onlyDeleted"){o.onlyDeleted=U.toLowerCase()==="true";continue}if(I==="include"){let re=U.split(",").map($=>$.trim()).filter(Boolean);h&&h.length>0?o.include=re.filter($=>h.includes($)):o.include=re;continue}if(I==="fields"&&f){let $=U.split(",").map(ce=>ce.trim()).filter(Boolean);y.length>0&&($=$.filter(ce=>y.includes(ce))),b.length>0&&($=$.filter(ce=>!b.includes(ce))),g.length>0&&($=[...new Set([...g,...$])]),o.fields=$;continue}let He=I.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([a-z]+)\]$/);if(He){let re=He[1],$=He[2];F[re]?.includes($)&&t.push({field:re,operator:$,value:oo($,U)});continue}F[I]&&t.push({field:I,operator:"eq",value:U});}if(o.page||(o.page=1),o.per_page||(o.per_page=a),!o.order_by&&c?.field&&(o.order_by=c.field),o.order_by_direction||(o.order_by_direction=c?.order??"asc"),f&&!o.fields&&S.length>0){let I=[...S];g.length>0&&(I=[...new Set([...g,...I])]),o.fields=I;}return {filters:t,options:o}}function V(n,e=[]){if(e.length===0)return n;let t=new Set(Object.keys(n.shape)),o=e.filter(s=>t.has(s));if(o.length===0)return n;let r=Object.fromEntries(o.map(s=>[s,true]));return n.omit(r)}function Bo(n,e={},t=[],o=[],r=[]){let{allowedFields:s=[],blockedFields:i=[],alwaysIncludeFields:u=[],defaultFields:l=[],allowComputedFields:c=true,allowRelationFields:a=true}=e;if(!n||typeof n!="string"||n.trim()==="")return l.length>0?{fields:[...new Set([...u,...l])],isActive:false}:{fields:[],isActive:false};let d=n.split(",").map(f=>f.trim()).filter(Boolean),p=new Set;for(let f of t)(s.length===0||s.includes(f))&&(i.includes(f)||p.add(f));if(c)for(let f of o)(s.length===0||s.includes(f))&&(i.includes(f)||p.add(f));if(a)for(let f of r)(s.length===0||s.includes(f))&&(i.includes(f)||p.add(f));let m=d.filter(f=>p.has(f));return {fields:[...new Set([...u,...m])],isActive:true}}function Re(n,e){if(!e.isActive||e.fields.length===0)return n;let t={};for(let o of e.fields)o in n&&(t[o]=n[o]);return t}function St(n,e){return !e.isActive||e.fields.length===0?n:n.map(t=>Re(t,e))}var no="__honoCrudResolvedSchema:";function qo(n){return typeof n.getBodySchema=="function"}var x=class extends o{_auditLogger;_versionManager;_tx;getAuditLogger(){return this._auditLogger||(this._auditLogger=g(this._meta.model.audit,void 0,this.context??void 0)),this._auditLogger}getAuditConfig(){return a$3(this._meta.model.audit)}isAuditEnabled(){return this.getAuditConfig().enabled}getAuditUserId(){let e=this.getAuditConfig();return e.getUserId&&this.context?e.getUserId(this.context):this.context?a$1(this.context,a$4.userId):void 0}getVersionManager(){return this._versionManager||(this._versionManager=h(this._meta.model.versioning,this._meta.model.tableName,void 0,this.context??void 0)),this._versionManager}getVersioningConfig(){return a$5(this._meta.model.versioning,this._meta.model.tableName)}isVersioningEnabled(){return this.getVersioningConfig().enabled}getVersioningUserId(){let e=this.getVersioningConfig();return e.getUserId&&this.context?e.getUserId(this.context):this.context?a$1(this.context,a$4.userId):void 0}getSoftDeleteConfig(){return ct(this._meta.model.softDelete)}isSoftDeleteEnabled(){return this.getSoftDeleteConfig().enabled}getMultiTenantConfig(){return pt(this._meta.model.multiTenant)}isMultiTenantEnabled(){return this.getMultiTenantConfig().enabled}applyManagedInsertFields(e,t,o){return nt(e,this._meta.model,t,o)}applyManagedUpdateFields(e){return st(e,this._meta.model)}assertIdStrategySupported(e){it(this._meta.model,e);}getTimestampsConfig(){return ie(this._meta.model.timestamps)}getTenantId(){if(!this.context)return;let e=this.getMultiTenantConfig();return ut(this.context,e)}validateTenantId(){let e=this.getMultiTenantConfig();if(!e.enabled)return;let t=this.getTenantId();if(!t&&e.required)throw new HTTPException(400,{message:e.errorMessage});return t}injectTenantId(e){let t=this.getMultiTenantConfig();if(!t.enabled)return e;let o=this.getTenantId();return o?{...e,[t.field]:o}:e}async emitEvent(e,t){let o=d$2(this.context??void 0);o&&await o.emit({type:e,table:this._meta.model.tableName,recordId:t.recordId,data:t.data??null,previousData:t.previousData,userId:this.getAuditUserId(),tenantId:this.context?this.getTenantId():void 0,organizationId:this.context?a$1(this.context,a$4.organizationId):void 0,timestamp:new Date().toISOString(),metadata:t.metadata});}async encryptOnWrite(e){let t=this._meta.model.fieldEncryption;return t?await e$1(e,t.fields,t.keyProvider):e}async decryptOnRead(e){let t=this._meta.model.fieldEncryption;return t?await f$1(e,t.fields,t.keyProvider):e}applyProfile(e){let t=this._meta.model.serializationProfile;return t?a$6(e,t):e}applyProfileToArray(e){let t=this._meta.model.serializationProfile;return t?b$3(e,t):e}transform(e){return e}async finalizeRecord(e,t){let o=this._meta.model,r=e;o.computedFields&&(r=await ae(r,o.computedFields));let s=o.serializer?o.serializer(r):r,i=this.applyProfile(s),u=this.transform(i);return t?.isActive&&t.fields.length>0?Re(u,t):u}async finalizeArray(e,t){let o=this._meta.model,r=e;o.computedFields&&(r=await dt(r,o.computedFields));let s=o.serializer?r.map(l=>o.serializer(l)):r,u=this.applyProfileToArray(s).map(l=>this.transform(l));return t?.isActive&&t.fields.length>0?St(u,t):u}getRecordId(e){if(e===null||typeof e!="object")return null;let t=this._meta.model.primaryKeys[0],o=e[t];return typeof o=="string"||typeof o=="number"?o:null}getParentId(e){return this.getRecordId(e)}getPolicies(){if(this.context){let e=a$1(this.context,s);if(e)return e}return this._meta.model.policies}buildPolicyContext(){let e=this.context;return {user:e?a$1(e,a$4.user):void 0,userId:e?a$1(e,a$4.userId):void 0,tenantId:e?a$1(e,a$4.tenantId):void 0,organizationId:e?a$1(e,a$4.organizationId):void 0,request:e?.req?.raw??new Request("http://localhost/")}}async applyReadPolicy(e){let t=this.getPolicies();if(!t)return e;let o=this.buildPolicyContext();if(t.read&&!await t.read(o,e))return null;if(t.fields){let r=t.fields(o,e);return {...e,...r}}return e}async applyReadPolicyToArray(e){if(!this.getPolicies())return e;let o=[];for(let r of e){let s=await this.applyReadPolicy(r);s!==null&&o.push(s);}return o}async applyWritePolicy(e){let t=this.getPolicies();if(!t?.write)return;if(!await t.write(this.buildPolicyContext(),e))throw new HTTPException(403,{message:"Forbidden by policy"})}applyReadPushdown(e){let t=this.getPolicies();if(!t?.readPushdown)return;let o=t.readPushdown(this.buildPolicyContext());o&&o.length>0&&e.filters.push(...o);}buildHookContext(){let e=this.context;return {db:{tx:this._tx},request:e?.req?.raw,tenantId:e?this.getTenantId():void 0,organizationId:e?a$1(e,a$4.organizationId):void 0,userId:e?a$1(e,a$4.userId):void 0,agentId:e?a$1(e,a$4.agentId):void 0,agentRunId:e?a$1(e,a$4.agentRunId):void 0}}getModelSchema(){if(this.context&&this._meta.model.resolveSchema){let e=a$1(this.context,no+this._meta.model.tableName);if(e)return e}return this._meta.model.schema}async resolveModelSchema(){let e=this._meta.model.resolveSchema;if(!e||!this.context)return this._meta.model.schema;let t=no+this._meta.model.tableName,o=a$1(this.context,t);if(o)return o;let r={tenantId:a$1(this.context,a$4.tenantId),organizationId:a$1(this.context,a$4.organizationId),request:this.context.req?.raw,env:this.context.env},s;try{s=await e(r);}catch(i){throw new a(i instanceof Error?i.message:"Schema resolution failed",500,"SCHEMA_RESOLVE_ERROR",i instanceof Error?{cause:i.message}:void 0)}return b$4(this.context,t,s),s}async getValidatedData(){await this.resolveModelSchema();let e=await super.getValidatedData();if(this.context&&e.body!==void 0&&qo(this)){let t=e.body;try{t=await this.context.req.json();}catch{}let r=this.getBodySchema().safeParse(t);if(!r.success)throw b.fromZodError(r.error);e.body=r.data;}return e}};function zo(){return z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.unknown().optional()})})}function R(n){return {description:n??"Error",content:{"application/json":{schema:zo()}}}}var xt=class extends x{beforeHookMode="sequential";afterHookMode="sequential";allowNestedCreate=[];getBodySchema(){let e,t=D(this._meta.model),o=this.getMultiTenantConfig();o.enabled&&t.push(o.field),this._meta.fields?e=this._meta.fields:e=V(this.getModelSchema(),t);let r=this.getNestedWritableRelations();if(r.length===0)return e;let s={...e.shape};for(let i of r){let u=this._meta.model.relations?.[i];if(!u?.schema)continue;let l=["id",u.foreignKey],c=V(u.schema,l);u.type==="hasMany"?s[i]=z.array(c).optional():s[i]=c.optional();}return z.object(s)}getNestedWritableRelations(){if(this.allowNestedCreate.length>0)return this.allowNestedCreate;let e=this._meta.model.relations;return e?Object.entries(e).filter(([t,o])=>o.nestedWrites?.allowCreate===true).map(([t])=>t):[]}extractNestedData(e){let t=this.getNestedWritableRelations();return ee(e,t)}getSchema(){let e=this.getBodySchema();return {...this.schema,request:{body:{content:{"application/json":{schema:e}},required:true}},responses:{201:{description:"Resource created successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:R("Validation error")}}}async getObject(){let{body:e}=await this.getValidatedData();return e}async before(e,t){return e}async after(e,t){return e}transform(e){return e}async createNested(e,t,o,r,s){return b$1().warn(`Nested writes not implemented for ${t}. Override createNested() in your adapter.`),[]}async handle(){this.validateTenantId();let e=await this.getObject(),{mainData:t,nestedData:o}=this.extractNestedData(e),r=t;r=this.injectTenantId(r);let s=this.buildHookContext();r=await this.before(r,s),r=await this.encryptOnWrite(r),r=await this.create(r,s.db.tx).catch(W),r=await this.decryptOnRead(r);let i=this.getParentId(r),u={};if(Object.keys(o).length>0&&i!==null)for(let[c,a]of Object.entries(o)){if(a==null)continue;let d=this._meta.model.relations?.[c];if(!d)continue;let p=await this.createNested(i,c,d,a);u[c]=p;}if(Object.keys(u).length>0){let c={};for(let[a,d]of Object.entries(u)){let p=this._meta.model.relations?.[a];p&&(p.type==="hasMany"?c[a]=d:c[a]=d[0]||null);}r={...r,...c};}if(this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(r,s))):r=await this.after(r,s),this.isAuditEnabled()&&i!==null){let c=this.getAuditLogger();this.runAfterResponse(c.logCreate(this._meta.model.tableName,i,r,this.getAuditUserId()));}i!==null&&this.runAfterResponse(this.emitEvent("created",{recordId:i,data:r}));let l=await this.finalizeRecord(r);return this.success(l,201)}};var Ot=class extends x{lookupField="id";lookupFields;additionalFilters;etagEnabled=false;allowedIncludes=[];fieldSelectionEnabled=false;allowedSelectFields=[];blockedSelectFields=[];alwaysIncludeFields=[];defaultSelectFields=[];getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getQuerySchema(){let e={};if(this.additionalFilters?.length)for(let t of this.additionalFilters)e[t]=z.string().optional();if(this.allowedIncludes.length>0&&(e.include=z.string().optional().meta({description:`Comma-separated list of relations to include. Allowed: ${this.allowedIncludes.join(", ")}`})),this.fieldSelectionEnabled){let t=this.getAvailableSelectFields();e.fields=z.string().optional().meta({description:`Comma-separated list of fields to return. Available: ${t.join(", ")}`});}if(Object.keys(e).length!==0)return z.object(e)}getAvailableSelectFields(){let e=Object.keys(this.getModelSchema().shape),t=this._meta.model.computedFields?Object.keys(this._meta.model.computedFields):[],o=this._meta.model.relations?Object.keys(this._meta.model.relations):[],r=[...e,...t,...o];return this.allowedSelectFields.length>0&&(r=r.filter(s=>this.allowedSelectFields.includes(s))),this.blockedSelectFields.length>0&&(r=r.filter(s=>!this.blockedSelectFields.includes(s))),r}getSchema(){let e=this.getQuerySchema();return {...this.schema,request:{params:this.getParamsSchema(),...e&&{query:e}},responses:{200:{description:"Resource retrieved successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},404:R("Resource not found")}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async getIncludeOptions(){let{query:e}=await this.getValidatedData(),t=e?.include;if(!t||typeof t!="string")return {relations:[]};let o=t.split(",").map(r=>r.trim()).filter(Boolean);return this.allowedIncludes.length>0?{relations:o.filter(r=>this.allowedIncludes.includes(r))}:{relations:o}}async getFieldSelection(){if(!this.fieldSelectionEnabled)return {fields:[],isActive:false};let{query:e}=await this.getValidatedData(),t=e?.fields;if(!t||typeof t!="string"||t.trim()==="")return this.defaultSelectFields.length>0?{fields:[...new Set([...this.alwaysIncludeFields,...this.defaultSelectFields])],isActive:true}:{fields:[],isActive:false};let o=t.split(",").map(i=>i.trim()).filter(Boolean),r=new Set(this.getAvailableSelectFields()),s=o.filter(i=>r.has(i));return this.alwaysIncludeFields.length>0&&(s=[...new Set([...this.alwaysIncludeFields,...s])]),{fields:s,isActive:true}}async after(e){return e}transform(e){return e}async handle(){let e=this.validateTenantId(),t=await this.getLookupValue(),o=await this.getAdditionalFilters(),r=await this.getIncludeOptions(),s=await this.getFieldSelection();if(e){let c=this.getMultiTenantConfig();o[c.field]=e;}let i=await this.read(t,o,r);if(!i)throw new c(this._meta.model.tableName,t);i=await this.decryptOnRead(i);let u=await this.applyReadPolicy(i);if(u===null)throw new c(this._meta.model.tableName,t);i=u,i=await this.after(i);let l=await this.finalizeRecord(i,s);if(this.etagEnabled){let c=await de(l),a=this.getContext(),d=a.req.header("If-None-Match");if(Et(d,c))return new Response(null,{status:304,headers:{ETag:c}});a.header("ETag",c);}return this.success(l)}};var kt=class extends x{lookupField="id";lookupFields;additionalFilters;allowedUpdateFields;blockedUpdateFields;beforeHookMode="sequential";afterHookMode="sequential";allowNestedWrites=[];etagEnabled=false;getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getBodySchema(){let e;if(this._meta.fields)e=this._meta.fields.partial();else {let r=D(this._meta.model);this.blockedUpdateFields&&(r=[...r,...this.blockedUpdateFields]);let s=V(this.getModelSchema(),r);if(this.allowedUpdateFields){let i={};for(let u of this.allowedUpdateFields)i[u]=true;s=s.pick(i);}e=s.partial();}let t=this.getNestedWritableRelations();if(t.length===0)return e;let o={...e.shape};for(let r of t){let s=this._meta.model.relations?.[r];if(!s?.schema)continue;let i=s.schema,u=z.object({create:z.union([i.partial(),z.array(i.partial())]).optional(),update:z.array(i.partial().extend({id:z.union([z.string(),z.number()])})).optional(),delete:z.array(z.union([z.string(),z.number()])).optional(),connect:z.array(z.union([z.string(),z.number()])).optional(),disconnect:z.array(z.union([z.string(),z.number()])).optional(),set:i.partial().nullable().optional()}).optional();o[r]=u;}return z.object(o)}getNestedWritableRelations(){if(this.allowNestedWrites.length>0)return this.allowNestedWrites;let e=this._meta.model.relations;return e?Object.entries(e).filter(([t,o])=>{let r=o.nestedWrites;return r&&(r.allowCreate||r.allowUpdate||r.allowDelete||r.allowConnect||r.allowDisconnect)}).map(([t])=>t):[]}extractNestedData(e){let t=this.getNestedWritableRelations();return ee(e,t)}getSchema(){return {...this.schema,request:{params:this.getParamsSchema(),body:{content:{"application/json":{schema:this.getBodySchema()}},required:true}},responses:{200:{description:"Resource updated successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:R("Validation error"),404:R("Resource not found")}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getObject(){let{body:e}=await this.getValidatedData();return e}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async before(e,t){return e}async after(e,t,o){return t}transform(e){return e}async findExisting(e,t,o){return null}async processNestedWrites(e,t,o,r,s){return b$1().warn(`Nested writes not implemented for ${t}. Override processNestedWrites() in your adapter.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]}}async handle(){let e=this.validateTenantId(),t=await this.getLookupValue(),o=await this.getAdditionalFilters();if(e){let b=this.getMultiTenantConfig();o[b.field]=e;}let r=await this.getObject(),{mainData:s,nestedData:i}=this.extractNestedData(r),u=this.getPolicies(),l=await this.findExisting(t,o,this._tx);if(l&&u?.write&&await this.applyWritePolicy(l),this.etagEnabled&&l){let b=this.getContext().req.header("If-Match");if(b){let g=await de(l);if(!Rt(b,g))return this.error("Resource has been modified by another request","CONFLICT",409)}}let c$1;if(this.isVersioningEnabled()&&l){let b=this.getVersionManager(),g=this.getParentId(l);g!==null&&(c$1=await b.saveVersion(g,l,void 0,this.getVersioningUserId()));}let a=s;if(this.isVersioningEnabled()&&c$1!==void 0){let b=this.getVersioningConfig().field;a[b]=c$1;}let d=this.buildHookContext();a=await this.before(a,d),a=await this.encryptOnWrite(a);let p=await this.update(t,a,o,d.db.tx);if(!p)throw new c(this._meta.model.tableName,t);p=await this.decryptOnRead(p);let m=this.getParentId(p),h={};if(Object.keys(i).length>0&&m!==null)for(let[b,g]of Object.entries(i)){if(g==null)continue;let S=this._meta.model.relations?.[b];if(!S)continue;let F;ge(g)?F={create:g}:F=g;let I=await this.processNestedWrites(m,b,S,F);h[b]=I;}if(Object.keys(h).length>0)for(let[b,g]of Object.entries(h)){let S=this._meta.model.relations?.[b];S&&(S.type==="hasMany"?p[b]=[...g.created,...g.updated]:p[b]=g.created[0]||g.updated[0]||null);}let f=l??p;if(this.afterHookMode==="fire-and-forget")this.runAfterResponse(Promise.resolve(this.after(f,p,d)));else {let b=await this.after(f,p,d);b!=null&&(p=b);}if(this.isAuditEnabled()&&m!==null&&l){let b=this.getAuditLogger();this.runAfterResponse(b.logUpdate(this._meta.model.tableName,m,l,p,this.getAuditUserId()));}m!==null&&this.runAfterResponse(this.emitEvent("updated",{recordId:m,data:p,previousData:l??void 0}));let y=await this.finalizeRecord(p);if(this.etagEnabled){let b=await de(y);this.getContext().header("ETag",b);}return this.success(y)}};var Ct=class extends x{lookupField="id";lookupFields;additionalFilters;beforeHookMode="sequential";afterHookMode="sequential";includeCascadeResults=false;getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getCascadeRelations(e){let t=this._meta.model.relations;return t?Object.entries(t).filter(([o,r])=>{let s=r.cascade?.[e];return s&&s!=="noAction"}).map(([o,r])=>({name:o,config:r,action:r.cascade[e]})):[]}getSchema(){let e=this.includeCascadeResults?z.object({deleted:z.literal(true),cascade:z.object({deleted:z.record(z.string(),z.number()),nullified:z.record(z.string(),z.number())}).optional()}):z.object({deleted:z.literal(true)});return {...this.schema,request:{params:this.getParamsSchema()},responses:{200:{description:"Resource deleted successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:e})}}},404:R("Resource not found"),409:{description:"Cannot delete - related records exist (restrict)",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.object({relation:z.string(),count:z.number()}).optional()})})}}}}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async before(e,t){}async after(e,t){}async countRelated(e,t,o,r){return b$1().warn(`countRelated not implemented for ${t}. Override in your adapter for restrict cascade to work.`),0}async deleteRelated(e,t,o,r){return b$1().warn(`deleteRelated not implemented for ${t}. Override in your adapter for cascade delete to work.`),0}async nullifyRelated(e,t,o,r){return b$1().warn(`nullifyRelated not implemented for ${t}. Override in your adapter for setNull cascade to work.`),0}async processCascade(e,t,o){let r=t?"onSoftDelete":"onDelete",s=this.getCascadeRelations(r),i={deleted:{},nullified:{}};for(let{name:u,config:l,action:c}of s)if(c==="cascade"){let a=await this.deleteRelated(e,u,l,o);a>0&&(i.deleted[u]=a);}else if(c==="setNull"){let a=await this.nullifyRelated(e,u,l,o);a>0&&(i.nullified[u]=a);}return i}async checkRestrictConstraints(e,t,o){let r=t?"onSoftDelete":"onDelete",s=this.getCascadeRelations(r);for(let{name:i,config:u,action:l}of s)if(l==="restrict"){let c=await this.countRelated(e,i,u,o);if(c>0)throw new d(`Cannot delete: ${c} related ${i} record(s) exist. Remove them first or change the cascade configuration.`,{relation:i,count:c})}}async handle(){let e=this.validateTenantId(),t=await this.getLookupValue(),o=await this.getAdditionalFilters();if(e){let d=this.getMultiTenantConfig();o[d.field]=e;}let r=this.isSoftDeleteEnabled(),s=await this.findForDelete(t,o,this._tx);if(!s)throw new c(this._meta.model.tableName,t);let i=this.getParentId(s);i!==null&&await this.checkRestrictConstraints(i,r),await this.applyWritePolicy(s);let u=this.buildHookContext();if(await this.before(t,u),!await this.delete(t,o,u.db.tx))throw new c(this._meta.model.tableName,t);let c$1;if(i!==null&&(c$1=await this.processCascade(i,r)),this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(s,u))):await this.after(s,u),this.isAuditEnabled()&&i!==null){let d=this.getAuditLogger();this.runAfterResponse(d.logDelete(this._meta.model.tableName,i,s,this.getAuditUserId()));}i!==null&&this.runAfterResponse(this.emitEvent("deleted",{recordId:i,previousData:s}));let a={deleted:true};if(this.includeCascadeResults&&c$1){let d=Object.keys(c$1.deleted).length>0,p=Object.keys(c$1.nullified).length>0;(d||p)&&(a.cascade=c$1);}return this.success(a)}};var be=class extends x{filterFields=[];filterConfig;searchFields=[];searchFieldName="search";sortFields=[];defaultSort;defaultPerPage=20;maxPerPage=100;cursorPaginationEnabled=false;cursorField;allowedIncludes=[];fieldSelectionEnabled=false;allowedSelectFields=[];blockedSelectFields=[];alwaysIncludeFields=[];defaultSelectFields=[];getQuerySchema(){let e={page:z.string().optional(),per_page:z.string().optional()};this.sortFields.length>0&&(e.sort=z.enum(this.sortFields).optional().meta({description:"Field to sort by"}),e.order=z.enum(d$1).optional().meta({description:"Sort direction (asc or desc)"})),this.searchFields.length>0&&(e[this.searchFieldName]=z.string().optional());for(let o of this.filterFields)e[o]=z.string().optional();if(this.filterConfig)for(let[o,r]of Object.entries(this.filterConfig)){for(let s of r)e[`${o}[${s}]`]=z.string().optional();e[o]=z.string().optional();}let t=this.getSoftDeleteConfig();if(t.enabled&&t.allowQueryDeleted&&(e[t.queryParam]=z.enum(["true","false"]).optional(),e.onlyDeleted=z.enum(["true","false"]).optional()),this.allowedIncludes.length>0&&(e.include=z.string().optional().meta({description:`Comma-separated list of relations to include. Allowed: ${this.allowedIncludes.join(", ")}`})),this.fieldSelectionEnabled){let o=this.getAvailableSelectFields();e.fields=z.string().optional().meta({description:`Comma-separated list of fields to return. Available: ${o.join(", ")}`});}return this.cursorPaginationEnabled&&(e.cursor=z.string().optional().meta({description:"Opaque cursor for fetching the next page"}),e.limit=z.string().optional().meta({description:"Number of items to return (cursor pagination)"})),z.object(e)}getAvailableSelectFields(){let e=Object.keys(this.getModelSchema().shape),t=this._meta.model.computedFields?Object.keys(this._meta.model.computedFields):[],o=this._meta.model.relations?Object.keys(this._meta.model.relations):[],r=[...e,...t,...o];return this.allowedSelectFields.length>0&&(r=r.filter(s=>this.allowedSelectFields.includes(s))),this.blockedSelectFields.length>0&&(r=r.filter(s=>!this.blockedSelectFields.includes(s))),r}getSchema(){return {...this.schema,request:{query:this.getQuerySchema()},responses:{200:{description:"List of resources",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.array(this.getModelSchema()),result_info:z.object({page:z.number(),per_page:z.number(),total_count:z.number().optional(),total_pages:z.number().optional(),has_next_page:z.boolean(),has_prev_page:z.boolean(),next_cursor:z.string().optional(),prev_cursor:z.string().optional()})})}}}}}}async getFilters(){let{query:e}=await this.getValidatedData(),t=this.getSoftDeleteConfig(),o={filterFields:this.filterFields,filterConfig:this.filterConfig,searchFields:this.searchFields,searchFieldName:this.searchFieldName,sortFields:this.sortFields,defaultSort:this.defaultSort,defaultPerPage:this.defaultPerPage,maxPerPage:this.maxPerPage,cursorPaginationEnabled:this.cursorPaginationEnabled,cursorField:this.cursorField,softDeleteQueryParam:t.queryParam,allowedIncludes:this.allowedIncludes,fieldSelectionEnabled:this.fieldSelectionEnabled,allowedSelectFields:this.allowedSelectFields,blockedSelectFields:this.blockedSelectFields,alwaysIncludeFields:this.alwaysIncludeFields,defaultSelectFields:this.defaultSelectFields};return te(e||{},o)}async after(e){return e}transform(e){return e}async handle(){let e=this.validateTenantId(),t=await this.getFilters();if(e){let c=this.getMultiTenantConfig();t.filters.push({field:c.field,operator:"eq",value:e});}this.applyReadPushdown(t);let o=await this.list(t),r=await Promise.all(o.result.map(c=>this.decryptOnRead(c))),s=await this.applyReadPolicyToArray(r),i=await this.after(s),u=this.fieldSelectionEnabled&&t.options.fields&&t.options.fields.length>0?{fields:t.options.fields,isActive:true}:void 0,l=await this.finalizeArray(i,u);return this.successPaginated(l,o.result_info)}};var Pt=class extends x{lookupField="id";excludeFromClone=[];getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getBodySchema(){let e=[...D(this._meta.model),...this.excludeFromClone];return V(this.getModelSchema(),e).partial()}getSchema(){return {...this.schema,request:{params:this.getParamsSchema(),body:{content:{"application/json":{schema:this.getBodySchema()}},required:false}},responses:{201:{description:"Resource cloned successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},404:R("Source resource not found"),409:R("Unique-constraint violation (e.g. natural-key collision)")}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getOverrides(){let{body:e}=await this.getValidatedData();return e||{}}async before(e){return e}async after(e){return e}async handle(){let e=this.validateTenantId(),t=await this.getLookupValue(),o=await this.getOverrides(),r={};if(e){let a=this.getMultiTenantConfig();r[a.field]=e;}let s=await this.findSource(t,r);if(!s)throw new c(this._meta.model.tableName,t);let i=at(s,this._meta.model);for(let a of this.excludeFromClone)delete i[a];Object.assign(i,o);let u=await this.before(i),l=await this.createClone(u).catch(W);l=await this.after(l);let c$1=await this.finalizeRecord(l);return this.success(c$1,201)}};var ye=new Map,Ko=["password","token","secret","apiKey","creditCard","ssn"];function Oe(n,e){if(n==null||typeof n!="object")return n;if(Array.isArray(n))return n.map(o=>Oe(o,e));let t={};for(let[o,r]of Object.entries(n))e.includes(o)||(t[o]=typeof r=="object"&&r!==null?Oe(r,e):r);return t}function Wo(n){let{table:e,events:t,emitter:o,filter:r,heartbeatInterval:s=3e4,maxConnections:i=1e3,connectionTimeout:u=3e5,excludeFields:l=Ko}=n;return c=>{let a=d$2(c,o);if(!a)return c.json({success:false,error:{code:"EVENT_EMITTER_NOT_CONFIGURED",message:"Event emitter not configured"}},500);let d=ye.get(e)||0;return d>=i?c.json({success:false,error:{code:"TOO_MANY_CONNECTIONS",message:"Too many SSE connections"}},503):(ye.set(e,d+1),streamSSE(c,async p=>{let m,h=async g=>{if(t&&t.length>0&&!t.includes(g.type)||r&&!r(g,c))return;let S=l.length>0?Oe(g.data,l):g.data,F=g.previousData&&l.length>0?Oe(g.previousData,l):g.previousData;try{await p.writeSSE({event:`${g.table}.${g.type}`,data:JSON.stringify({type:g.type,table:g.table,recordId:g.recordId,data:S,previousData:F,timestamp:g.timestamp}),id:`${g.table}-${g.recordId}-${Date.now()}`});}catch{}};m=a.onTable(e,h);let f=()=>{m.unsubscribe();let g=ye.get(e)||1;g<=1?ye.delete(e):ye.set(e,g-1);};p.onAbort(()=>{f();});let y=Date.now(),b=y;for(;!p.closed;){await p.sleep(1e3);let g=Date.now();if(g-y>=u){p.abort();break}if(g-b>=s){b=g;try{await p.writeSSE({event:"heartbeat",data:JSON.stringify({timestamp:new Date().toISOString()})});}catch{break}}}}))}}var jt=class extends x{lookupField="id";lookupFields;additionalFilters;beforeHookMode="sequential";afterHookMode="sequential";getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema()},responses:{200:{description:"Resource restored successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:R("Soft delete not enabled or record not deleted"),404:R("Resource not found")}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async before(e,t){}async after(e,t){return e}async handle(){if(!this.isSoftDeleteEnabled())throw new a("Soft delete is not enabled for this model",400,"SOFT_DELETE_NOT_ENABLED");let e=await this.getLookupValue(),t=await this.getAdditionalFilters();await this.before(e);let o=await this.restore(e,t);if(!o)throw new c(this._meta.model.tableName,e);this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(o))):o=await this.after(o);let r=this.getRecordId(o);if(this.isAuditEnabled()&&r!==null){let i=this.getAuditLogger();this.runAfterResponse(i.logRestore(this._meta.model.tableName,r,o,this.getAuditUserId()));}r!==null&&this.runAfterResponse(this.emitEvent("restored",{recordId:r,data:o}));let s=await this.finalizeRecord(o);return this.success(s)}};var vt=class extends x{upsertKeys;useNativeUpsert=false;createOnlyFields;updateOnlyFields;beforeHookMode="sequential";afterHookMode="sequential";allowNestedWrites=[];getUpsertKeys(){return this.upsertKeys||this._meta.model.primaryKeys}getBodySchema(){let e;if(this._meta.fields)e=this._meta.fields;else {let r=this.getUpsertKeys(),s=D(this._meta.model,{includePrimaryKeys:false});for(let l of this._meta.model.primaryKeys)r.includes(l)||s.push(l);let i=V(this.getModelSchema(),s),u={};for(let[l,c]of Object.entries(i.shape))r.includes(l)?u[l]=c:u[l]=c.optional();e=z.object(u);}let t=this.getNestedWritableRelations();if(t.length===0)return e;let o={...e.shape};for(let r of t){let s=this._meta.model.relations?.[r];if(!s?.schema)continue;let i=s.schema,u=z.union([s.type==="hasMany"?z.array(i.partial()):i.partial(),z.object({create:z.union([i.partial(),z.array(i.partial())]).optional(),update:z.array(i.partial().extend({id:z.union([z.string(),z.number()])})).optional(),upsert:z.union([i.partial(),z.array(i.partial())]).optional(),delete:z.array(z.union([z.string(),z.number()])).optional(),connect:z.array(z.union([z.string(),z.number()])).optional(),disconnect:z.array(z.union([z.string(),z.number()])).optional(),set:i.partial().nullable().optional()})]).optional();o[r]=u;}return z.object(o)}getNestedWritableRelations(){if(this.allowNestedWrites.length>0)return this.allowNestedWrites;let e=this._meta.model.relations;return e?Object.entries(e).filter(([t,o])=>{let r=o.nestedWrites;return r&&(r.allowCreate||r.allowUpdate||r.allowDelete||r.allowConnect||r.allowDisconnect)}).map(([t])=>t):[]}extractNestedData(e){let t=this.getNestedWritableRelations();return ee(e,t)}getSchema(){return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}},required:true}},responses:{200:{description:"Resource updated (upsert)",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema(),created:z.literal(false)})}}},201:{description:"Resource created (upsert)",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema(),created:z.literal(true)})}}},400:R("Validation error")}}}async getObject(){let{body:e}=await this.getValidatedData();return e}async before(e,t,o){return e}async beforeCreate(e,t){return e}async beforeUpdate(e,t,o){return e}async after(e,t,o){return e}async nativeUpsert(e,t){return b$1().warn("Native upsert not implemented for this adapter. Falling back to find-then-insert/update pattern."),this.performStandardUpsert(e,t)}async performStandardUpsert(e,t){let o=await this.findExisting(e,t);if(o){let r={...e};if(this.createOnlyFields)for(let i of this.createOnlyFields)delete r[i];return r=await this.beforeUpdate(r,o,t),{data:await this.update(o,r,t),created:false}}else {let r={...e};if(this.updateOnlyFields)for(let i of this.updateOnlyFields)delete r[i];return r=await this.beforeCreate(r,t),{data:await this.create(r,t),created:true}}}async upsert(e,t){return this.useNativeUpsert?this.nativeUpsert(e,t):this.performStandardUpsert(e,t)}async processNestedWrites(e,t,o,r,s){return b$1().warn(`Nested writes not implemented for ${t}. Override processNestedWrites() in your adapter.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]}}async handle(){this.validateTenantId();let e=await this.getObject(),{mainData:t,nestedData:o}=this.extractNestedData(e),r=t;r=this.injectTenantId(r);let s=await this.findExisting(r),i=!s;r=await this.before(r,i);let u=await this.upsert(r).catch(W),l=u.data,c=this.getParentId(l),a={};if(Object.keys(o).length>0&&c!==null)for(let[p,m]of Object.entries(o)){if(m==null)continue;let h=this._meta.model.relations?.[p];if(!h)continue;let f;ge(m)?f={create:m}:f=m;let y=await this.processNestedWrites(c,p,h,f);a[p]=y;}if(Object.keys(a).length>0)for(let[p,m]of Object.entries(a)){let h=this._meta.model.relations?.[p];h&&(h.type==="hasMany"?l[p]=[...m.created,...m.updated]:l[p]=m.created[0]||m.updated[0]||null);}if(this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(l,u.created))):l=await this.after(l,u.created),this.isAuditEnabled()&&c!==null){let p=this.getAuditLogger();this.runAfterResponse(p.logUpsert(this._meta.model.tableName,c,l,s,u.created,this.getAuditUserId()));}let d=await this.finalizeRecord(l);return this.json({success:true,result:d,created:u.created},u.created?201:200)}};var Ft=class extends x{maxBatchSize=100;stopOnError=true;beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){let e=this._meta.fields?this._meta.fields:V(this.getModelSchema(),D(this._meta.model));return z.object({items:z.array(e).min(1).max(this.maxBatchSize)})}getSchema(){return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{201:{description:"Resources created successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({created:z.array(this.getModelSchema()),count:z.number()})})}}},207:{description:"Partial success (some items failed)",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({created:z.array(this.getModelSchema()),count:z.number(),errors:z.array(z.object({index:z.number(),error:z.string()})).optional()})})}}},400:R("Validation error")}}}async getItems(){let{body:e}=await this.getValidatedData();return e?.items||[]}async before(e,t,o){return e}async after(e,t,o){return e}transform(e){return e}async handle(){let e=await this.getItems(),t=[],o=[];for(let c=0;c<e.length;c++)try{let a=await this.before(e[c],c);o.push(a);}catch(a){if(this.stopOnError)throw a;t.push({index:c,error:a instanceof Error?a.message:String(a)});}let r=await this.batchCreate(o).catch(W),s=[];for(let c=0;c<r.length;c++)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(r[c],c))),s.push(r[c])):s.push(await this.after(r[c],c));}catch(a){if(this.stopOnError)throw a;t.push({index:c,error:a instanceof Error?a.message:String(a)}),s.push(r[c]);}if(this.isAuditEnabled()){let c=this.getAuditLogger(),a=s.map(d=>{let p=this.getRecordId(d);return p===null?null:{recordId:p,record:d}}).filter(d=>d!==null);a.length>0&&this.runAfterResponse(c.logBatch("batch_create",this._meta.model.tableName,a,this.getAuditUserId()));}let i=await this.finalizeArray(s),u={success:true,result:{created:i,count:i.length,...t.length>0&&{errors:t}}},l=t.length>0?207:201;return this.json(u,l)}};var It=class extends x{maxBatchSize=100;stopOnError=false;lookupField="id";allowedUpdateFields;blockedUpdateFields;beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){let e=this._meta.fields?this._meta.fields:V(this.getModelSchema(),D(this._meta.model));return z.object({items:z.array(z.object({id:z.string(),data:e.partial()})).min(1).max(this.maxBatchSize)})}getSchema(){return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{200:{description:"Resources updated successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({updated:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional()})})}}},207:{description:"Partial success (some items failed or not found)",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({updated:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional(),errors:z.array(z.object({id:z.string(),error:z.string()})).optional()})})}}},400:R("Validation error")}}}async getItems(){let{body:e}=await this.getValidatedData();return e?.items||[]}filterUpdateData(e){let t={...e};if(this.allowedUpdateFields){let o=new Set(this.allowedUpdateFields);t=Object.fromEntries(Object.entries(t).filter(([r])=>o.has(r)));}if(this.blockedUpdateFields)for(let o of this.blockedUpdateFields)delete t[o];for(let o of this._meta.model.primaryKeys)delete t[o];return t}async before(e,t,o){return t}async after(e,t){return e}async handle(){let e=await this.getItems(),t=[],o=[];for(let a of e)try{let d=this.filterUpdateData(a.data),p=await this.before(a.id,d);o.push({id:a.id,data:p});}catch(d){if(this.stopOnError)throw d;t.push({id:a.id,error:d instanceof Error?d.message:String(d)});}let{updated:r,notFound:s}=await this.batchUpdate(o),i=[];for(let a of r)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(a))),i.push(a)):i.push(await this.after(a));}catch(d){let p=String(a[this.lookupField]);if(this.stopOnError)throw d;t.push({id:p,error:d instanceof Error?d.message:String(d)}),i.push(a);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),d=i.map(p=>{let m=this.getRecordId(p);return m===null?null:{recordId:m,record:p}}).filter(p=>p!==null);d.length>0&&this.runAfterResponse(a.logBatch("batch_update",this._meta.model.tableName,d,this.getAuditUserId()));}let u=await this.finalizeArray(i),l={success:true,result:{updated:u,count:u.length,...s.length>0&&{notFound:s},...t.length>0&&{errors:t}}},c=t.length>0||s.length>0?207:200;return this.json(l,c)}};var At=class extends x{maxBatchSize=100;stopOnError=false;lookupField="id";beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){return z.object({ids:z.array(z.string()).min(1).max(this.maxBatchSize)})}getSchema(){let e=this.isSoftDeleteEnabled();return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{200:{description:e?"Resources soft-deleted successfully":"Resources deleted successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({deleted:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional()})})}}},207:{description:"Partial success (some items failed or not found)",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({deleted:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional(),errors:z.array(z.object({id:z.string(),error:z.string()})).optional()})})}}},400:R("Validation error")}}}async getIds(){let{body:e}=await this.getValidatedData();return e?.ids||[]}async before(e,t){}async after(e,t){return e}async handle(){let e=await this.getIds(),t=[],o=[];for(let a of e)try{await this.before(a),o.push(a);}catch(d){if(this.stopOnError)throw d;t.push({id:a,error:d instanceof Error?d.message:String(d)});}let{deleted:r,notFound:s}=await this.batchDelete(o),i=[];for(let a of r)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(a))),i.push(a)):i.push(await this.after(a));}catch(d){let p=String(a[this.lookupField]);if(this.stopOnError)throw d;t.push({id:p,error:d instanceof Error?d.message:String(d)}),i.push(a);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),d=i.map(p=>{let m=this.getRecordId(p);return m===null?null:{recordId:m,previousRecord:p}}).filter(p=>p!==null);d.length>0&&this.runAfterResponse(a.logBatch("batch_delete",this._meta.model.tableName,d,this.getAuditUserId()));}let u=this._meta.model.serializer?i.map(a=>this._meta.model.serializer(a)):i,l={success:true,result:{deleted:u,count:u.length,...s.length>0&&{notFound:s},...t.length>0&&{errors:t}}},c=t.length>0||s.length>0?207:200;return this.json(l,c)}};var _t=class extends x{maxBatchSize=100;stopOnError=false;lookupField="id";beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){return z.object({ids:z.array(z.string()).min(1).max(this.maxBatchSize)})}getSchema(){return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{200:{description:"Resources restored successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({restored:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional()})})}}},207:{description:"Partial success (some items failed or not found)",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({restored:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional(),errors:z.array(z.object({id:z.string(),error:z.string()})).optional()})})}}},400:R("Soft delete not enabled or validation error")}}}async getIds(){let{body:e}=await this.getValidatedData();return e?.ids||[]}async before(e,t){}async after(e,t){return e}async handle(){if(!this.isSoftDeleteEnabled())throw new a("Soft delete is not enabled for this model",400,"SOFT_DELETE_NOT_ENABLED");let e=await this.getIds(),t=[],o=[];for(let a of e)try{await this.before(a),o.push(a);}catch(d){if(this.stopOnError)throw d;t.push({id:a,error:d instanceof Error?d.message:String(d)});}let{restored:r,notFound:s}=await this.batchRestore(o),i=[];for(let a of r)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(a))),i.push(a)):i.push(await this.after(a));}catch(d){let p=String(a[this.lookupField]);if(this.stopOnError)throw d;t.push({id:p,error:d instanceof Error?d.message:String(d)}),i.push(a);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),d=i.map(p=>{let m=this.getRecordId(p);return m===null?null:{recordId:m,record:p}}).filter(p=>p!==null);d.length>0&&this.runAfterResponse(a.logBatch("batch_restore",this._meta.model.tableName,d,this.getAuditUserId()));}let u=await this.finalizeArray(i),l={success:true,result:{restored:u,count:u.length,...s.length>0&&{notFound:s},...t.length>0&&{errors:t}}},c=t.length>0||s.length>0?207:200;return this.json(l,c)}};var Tt=class extends x{upsertKeys;createOnlyFields;updateOnlyFields;maxBatchSize=100;continueOnError=false;useNativeUpsert=false;beforeHookMode="sequential";afterHookMode="sequential";getUpsertKeys(){return this.upsertKeys||this._meta.model.primaryKeys}getItemSchema(){if(this._meta.fields)return this._meta.fields;let e=this.getUpsertKeys(),t=D(this._meta.model,{includePrimaryKeys:false});for(let s of this._meta.model.primaryKeys)e.includes(s)||t.push(s);let o=V(this.getModelSchema(),t),r={};for(let[s,i]of Object.entries(o.shape))e.includes(s)?r[s]=i:r[s]=i.optional();return z.object(r)}getBodySchema(){return z.array(this.getItemSchema()).max(this.maxBatchSize)}getSchema(){let e=z.object({data:this.getModelSchema(),created:z.boolean(),index:z.number()});return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}},required:true}},responses:{200:{description:"Batch upsert completed",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({items:z.array(e),createdCount:z.number(),updatedCount:z.number(),totalCount:z.number(),errors:z.array(z.object({index:z.number(),error:z.string()})).optional()})})}}},400:R("Validation error")}}}async getItems(){let{body:e}=await this.getValidatedData();return e}async beforeItem(e,t,o,r){return e}async afterItem(e,t,o,r){return e}async beforeBatch(e,t){return e}async afterBatch(e,t){return e}async upsertOne(e,t,o){let r=await this.findExisting(e,o),s=!r,i=await this.beforeItem(e,t,s,o),u;if(r){if(this.createOnlyFields)for(let l of this.createOnlyFields)delete i[l];u=await this.update(r,i,o);}else {if(this.updateOnlyFields)for(let l of this.updateOnlyFields)delete i[l];u=await this.create(i,o);}return u=await this.afterItem(u,t,s,o),{data:u,created:s,index:t}}async nativeBatchUpsert(e,t){return b$1().warn("Native batch upsert not implemented for this adapter. Falling back to item-by-item pattern."),this.performStandardBatchUpsert(e,t)}async performStandardBatchUpsert(e,t){let o=[],r=[],s=0,i=0;for(let l=0;l<e.length;l++)try{let c=await this.upsertOne(e[l],l,t);o.push(c),c.created?s++:i++;}catch(c){if(this.continueOnError)r.push({index:l,error:c instanceof Error?c.message:String(c)});else throw c}let u={items:o,createdCount:s,updatedCount:i,totalCount:o.length};return r.length>0&&(u.errors=r),u}async batchUpsert(e,t){return this.useNativeUpsert?this.nativeBatchUpsert(e,t):this.performStandardBatchUpsert(e,t)}async handle(){let e=await this.getItems();e=await this.beforeBatch(e);let t=await this.batchUpsert(e).catch(W);if(t=await this.afterBatch(t),this._meta.model.computedFields&&(t.items=await Promise.all(t.items.map(async o=>({...o,data:await ae(o.data,this._meta.model.computedFields)})))),this.isAuditEnabled()){let o=this.getAuditLogger(),r=t.items.map(s=>{let i=this.getRecordId(s.data);return i===null?null:{recordId:i,record:s.data}}).filter(s=>s!==null);r.length>0&&this.runAfterResponse(o.logBatch("batch_upsert",this._meta.model.tableName,r,this.getAuditUserId()));}return t.items=t.items.map(o=>{let r=this._meta.model.serializer?this._meta.model.serializer(o.data):o.data,s=this.applyProfile(r);return {...o,data:this.transform(s)}}),this.success(t)}};var Nt=class extends x{maxBulkSize=1e3;confirmThreshold=100;returnRecords=false;hookMode="parallel";filterFields;getSchema(){return {request:{body:{content:{"application/json":{schema:this.getUpdateSchema().partial()}}},query:z.object({dryRun:z.string().optional()}).passthrough()},responses:{200:{description:"Bulk patch result",content:{"application/json":{schema:z.object({success:z.boolean(),matched:z.number(),updated:z.number(),dryRun:z.boolean()})}}},400:{description:"Bad request",content:{"application/json":{schema:z.object({success:z.boolean(),error:z.string()})}}}}}}async handle(){let e=this.getContext(),o=(await this.getValidatedData()).body;if(!o||Object.keys(o).length===0)return this.error("Request body is required with at least one field to update","EMPTY_BODY",400);let r=e.req.query("dryRun"),s=r==="true"||r==="1",i=te(e.req.query(),{filterFields:this.filterFields,defaultPerPage:this.maxBulkSize,maxPerPage:this.maxBulkSize}),u=await this.countMatching(i);if(u===0)return this.json({success:true,matched:0,updated:0,dryRun:s});if(u>this.maxBulkSize)return this.error(`Bulk patch affects ${u} records, exceeding the maximum of ${this.maxBulkSize}. Use more specific filters.`,"BULK_TOO_LARGE",400);if(u>=this.confirmThreshold&&e.req.header("X-Confirm-Bulk")!=="true")return this.error(`This operation will affect ${u} records. Set X-Confirm-Bulk: true header to confirm.`,"CONFIRMATION_REQUIRED",400);if(s)return this.json({success:true,matched:u,updated:0,dryRun:true});let l=o;this.beforeBulkPatch&&(l=await this.beforeBulkPatch(l,i,u));let c=await this.applyPatch(l,i),a={matched:u,updated:c.updated,dryRun:false,records:this.returnRecords?c.records:void 0};return this.afterBulkPatch&&await this.afterBulkPatch(a),this.json({success:true,matched:a.matched,updated:a.updated,dryRun:false,...this.returnRecords&&a.records?{records:a.records}:{}})}};var so=z.object({id:z.string(),recordId:z.union([z.string(),z.number()]),version:z.number(),data:z.record(z.string(),z.unknown()),createdAt:z.date(),changedBy:z.string().optional(),changeReason:z.string().optional(),changes:z.array(z.object({field:z.string(),oldValue:z.unknown().optional(),newValue:z.unknown().optional()})).optional()}),Dt=class extends x{lookupField="id";defaultLimit=20;maxLimit=100;getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getQuerySchema(){return z.object({limit:z.coerce.number().min(1).max(this.maxLimit).optional(),offset:z.coerce.number().min(0).optional()})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema(),query:this.getQuerySchema()},responses:{200:{description:"Version history retrieved successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({versions:z.array(so),totalVersions:z.number()})})}}},400:R("Versioning not enabled"),404:R("Record not found")}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getPaginationOptions(){let{query:e}=await this.getValidatedData();return {limit:e?.limit?Number(e.limit):this.defaultLimit,offset:e?.offset?Number(e.offset):0}}async recordExists(e){return true}async handle(){if(!this.isVersioningEnabled())throw new a("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),{limit:t,offset:o}=await this.getPaginationOptions();if(!await this.recordExists(e))throw new c(this._meta.model.tableName,e);let s=this.getVersionManager(),i=await s.getVersions(e,{limit:t,offset:o}),u=await s.getLatestVersion(e);return this.success({versions:i,totalVersions:u})}},Ht=class extends x{lookupField="id";getParamsSchema(){return z.object({[this.lookupField]:z.string(),version:z.coerce.number().min(1)})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema()},responses:{200:{description:"Version retrieved successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:so})}}},400:R("Versioning not enabled"),404:R("Version not found")}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getVersionNumber(){let{params:e}=await this.getValidatedData();return e?.version?Number(e.version):0}async handle(){if(!this.isVersioningEnabled())throw new a("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),t=await this.getVersionNumber(),r=await this.getVersionManager().getVersion(e,t);if(!r)throw new c(`version ${t}`,e);return this.success(r)}},Vt=class extends x{lookupField="id";getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getQuerySchema(){return z.object({from:z.coerce.number().min(1),to:z.coerce.number().min(1)})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema(),query:this.getQuerySchema()},responses:{200:{description:"Version comparison completed",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({from:z.number(),to:z.number(),changes:z.array(z.object({field:z.string(),oldValue:z.unknown().optional(),newValue:z.unknown().optional()}))})})}}},400:R("Versioning not enabled or invalid parameters"),404:R("Version not found")}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getVersionNumbers(){let{query:e}=await this.getValidatedData();return {from:e?.from?Number(e.from):0,to:e?.to?Number(e.to):0}}async handle(){if(!this.isVersioningEnabled())throw new a("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),{from:t,to:o}=await this.getVersionNumbers(),s=await this.getVersionManager().compareVersions(e,t,o);return this.success({from:t,to:o,changes:s})}},Zt=class extends x{lookupField="id";getParamsSchema(){return z.object({[this.lookupField]:z.string(),version:z.coerce.number().min(1)})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema()},responses:{200:{description:"Record rolled back successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:R("Versioning not enabled"),404:R("Version not found")}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getVersionNumber(){let{params:e}=await this.getValidatedData();return e?.version?Number(e.version):0}async handle(){if(!this.isVersioningEnabled())throw new a("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),t=await this.getVersionNumber(),o=this.getVersionManager(),r=await o.getVersion(e,t);if(!r)throw new c(`version ${t}`,e);let i=await o.getLatestVersion(e)+1,u=await this.rollback(e,r.data,i),l=this._meta.model.serializer?this._meta.model.serializer(u):u;return this.success(l)}};var Go={sumFields:[],avgFields:[],minMaxFields:[],countDistinctFields:[],groupByFields:[],defaultLimit:100,maxLimit:1e3},Ut=class extends x{aggregateConfig={};maxGroupByFields=5;filterFields=[];getAggregateConfig(){return {...Go,...this.aggregateConfig}}getQuerySchema(){return z.object({count:z.union([z.string(),z.array(z.string())]).optional(),sum:z.union([z.string(),z.array(z.string())]).optional(),avg:z.union([z.string(),z.array(z.string())]).optional(),min:z.union([z.string(),z.array(z.string())]).optional(),max:z.union([z.string(),z.array(z.string())]).optional(),countDistinct:z.union([z.string(),z.array(z.string())]).optional(),groupBy:z.string().optional(),orderBy:z.string().optional(),orderDirection:z.enum(d$1).optional(),limit:z.coerce.number().optional(),offset:z.coerce.number().optional(),withDeleted:z.coerce.boolean().optional()}).passthrough()}getSchema(){let e=z.object({key:z.record(z.string(),z.unknown()),values:z.record(z.string(),z.number().nullable())});return {...this.schema,request:{query:this.getQuerySchema()},responses:{200:{description:"Aggregation result",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({values:z.record(z.string(),z.number().nullable()).optional(),groups:z.array(e).optional(),totalGroups:z.number().optional()})})}}},400:R("Invalid aggregation request")}}}async getAggregateOptions(){let{query:e}=await this.getValidatedData();return lt(e||{})}validateAggregations(e){let t=this.getAggregateConfig();for(let o of e.aggregations)if(!(o.operation==="count"&&o.field==="*"))switch(o.operation){case "count":break;case "sum":if(t.sumFields.length>0&&!t.sumFields.includes(o.field))throw new Error(`Field '${o.field}' is not allowed for SUM aggregation`);break;case "avg":if(t.avgFields.length>0&&!t.avgFields.includes(o.field))throw new Error(`Field '${o.field}' is not allowed for AVG aggregation`);break;case "min":case "max":if(t.minMaxFields.length>0&&!t.minMaxFields.includes(o.field))throw new Error(`Field '${o.field}' is not allowed for MIN/MAX aggregation`);break;case "countDistinct":if(t.countDistinctFields.length>0&&!t.countDistinctFields.includes(o.field))throw new Error(`Field '${o.field}' is not allowed for COUNT DISTINCT aggregation`);break;default:c$1(o.operation);}if(e.groupBy){if(e.groupBy.length>this.maxGroupByFields)throw new b(`Maximum ${this.maxGroupByFields} GROUP BY fields allowed`);for(let o of e.groupBy)if(t.groupByFields.length>0&&!t.groupByFields.includes(o))throw new Error(`Field '${o}' is not allowed for GROUP BY`)}if(e.limit!==void 0&&e.limit>t.maxLimit)throw new Error(`Limit cannot exceed ${t.maxLimit}`)}getAggregateAlias(e){return e.alias?e.alias:e.field==="*"?e.operation:`${e.operation}${e.field.charAt(0).toUpperCase()}${e.field.slice(1)}`}async handle(){let e=await this.getAggregateOptions();e.aggregations.length===0&&e.aggregations.push({operation:"count",field:"*"}),this.validateAggregations(e);let t=this.getAggregateConfig();e.groupBy&&e.groupBy.length>0&&e.limit===void 0&&(e.limit=t.defaultLimit);let o=await this.aggregate(e);return this.success(o)}},Qo={eq:(n,e)=>n===e,ne:(n,e)=>n!==e,gt:(n,e)=>n>e,gte:(n,e)=>n>=e,lt:(n,e)=>n<e,lte:(n,e)=>n<=e};function Jo(n,e){let t=n.get(e);if(t)return t;let o=[];return n.set(e,o),o}function Yo(n,e){let{aggregations:t,groupBy:o,having:r,orderBy:s,orderDirection:i,limit:u,offset:l}=e;if(!o||o.length===0){let p={};for(let m of t){let h=ao(m);p[h]=io(n,m);}return {values:p}}let c=new Map;for(let p of n){let h=o.map(f=>String(p[f]??"null")).join("|");Jo(c,h).push(p);}let a=[];for(let[p,m]of c){let h=p.split("|"),f={};o.forEach((b,g)=>{f[b]=h[g]==="null"?null:h[g];});let y={};for(let b of t){let g=ao(b);y[g]=io(m,b);}a.push({key:f,values:y});}r&&(a=a.filter(p=>{for(let[m,h]of Object.entries(r)){let f=p.values[m];if(f!==null)for(let[y,b]of Object.entries(h)){let g=Qo[y];if(g&&!g(f,Number(b)))return false}}return true}));let d=a.length;if(s){let p=i==="desc"?-1:1;a.sort((m,h)=>{if(s in m.values){let f=m.values[s]??0,y=h.values[s]??0;return (f-y)*p}if(s in m.key){let f=String(m.key[s]??""),y=String(h.key[s]??"");return f.localeCompare(y)*p}return 0});}if(l!==void 0||u!==void 0){let p=l||0,m=u?p+u:void 0;a=a.slice(p,m);}return {groups:a,totalGroups:d}}function Lt(n,e){return n.map(t=>t[e]).filter(t=>typeof t=="number")}var Xo={count:(n,e)=>e==="*"?n.length:n.filter(t=>t[e]!==null&&t[e]!==void 0).length,countDistinct:(n,e)=>new Set(n.map(o=>o[e]).filter(o=>o!=null).map(o=>String(o))).size,sum:(n,e)=>{let t=0;for(let o of n){let r=o[e];typeof r=="number"&&(t+=r);}return t},avg:(n,e)=>{let t=Lt(n,e);return t.length===0?null:t.reduce((r,s)=>r+s,0)/t.length},min:(n,e)=>{let t=Lt(n,e);return t.length===0?null:Math.min(...t)},max:(n,e)=>{let t=Lt(n,e);return t.length===0?null:Math.max(...t)}};function io(n,e){if(n.length===0)return e.operation==="count"?0:null;let t=Xo[e.operation];return t?t(n,e.field):null}function ao(n){return n.alias?n.alias:n.field==="*"?n.operation:`${n.operation}${n.field.charAt(0).toUpperCase()}${n.field.slice(1)}`}function er(n){if(n instanceof z.ZodString)return true;let e=n;return e?e._def?.type==="string"||e._def?.typeName==="ZodString"||e.def?.type==="string":false}var Bt=class extends x{searchableFields={};searchFields=[];fieldWeights={};defaultMode="any";minQueryLength=2;maxQueryLength=500;highlightTag="mark";snippetLength=150;defaultMinScore=0;searchParamName="q";filterFields=[];filterConfig;sortFields=[];defaultSort;defaultPerPage=20;maxPerPage=100;allowedIncludes=[];fieldSelectionEnabled=false;allowedSelectFields=[];blockedSelectFields=[];alwaysIncludeFields=[];defaultSelectFields=[];getSearchableFields(){if(Object.keys(this.searchableFields).length>0)return this.searchableFields;if(this.searchFields.length>0)return yt(this.searchFields,this.fieldWeights);let e=this.getModelSchema().shape,t={};for(let[o,r]of Object.entries(e))er(r)&&(t[o]={weight:1});return t}getQuerySchema(){let t={[this.searchParamName||"q"]:z.string().min(this.minQueryLength).max(this.maxQueryLength).meta({description:"Search query"}),fields:z.string().optional().meta({description:`Comma-separated fields to search. Available: ${Object.keys(this.getSearchableFields()).join(", ")}`}),mode:z.enum(e).optional().meta({description:"Search mode: any (OR), all (AND), phrase (exact)"}),highlight:z.enum(["true","false"]).optional().meta({description:"Include highlighted snippets"}),minScore:z.string().optional().meta({description:"Minimum relevance score threshold (0-1)"}),page:z.string().optional(),per_page:z.string().optional()};this.sortFields.length>0&&(t.sort=z.enum(this.sortFields).optional().meta({description:"Field to sort by"}),t.order=z.enum(d$1).optional().meta({description:"Sort direction (asc or desc)"}));for(let r of this.filterFields)t[r]=z.string().optional();if(this.filterConfig)for(let[r,s]of Object.entries(this.filterConfig)){for(let i of s)t[`${r}[${i}]`]=z.string().optional();t[r]=z.string().optional();}let o=this.getSoftDeleteConfig();if(o.enabled&&o.allowQueryDeleted&&(t[o.queryParam]=z.enum(["true","false"]).optional(),t.onlyDeleted=z.enum(["true","false"]).optional()),this.allowedIncludes.length>0&&(t.include=z.string().optional().meta({description:`Comma-separated list of relations to include. Allowed: ${this.allowedIncludes.join(", ")}`})),this.fieldSelectionEnabled){let r=this.getAvailableSelectFields();t.fields=z.string().optional().meta({description:`Comma-separated list of fields to return. Available: ${r.join(", ")}`});}return z.object(t)}getAvailableSelectFields(){let e=Object.keys(this.getModelSchema().shape),t=this._meta.model.computedFields?Object.keys(this._meta.model.computedFields):[],o=this._meta.model.relations?Object.keys(this._meta.model.relations):[],r=[...e,...t,...o];return this.allowedSelectFields.length>0&&(r=r.filter(s=>this.allowedSelectFields.includes(s))),this.blockedSelectFields.length>0&&(r=r.filter(s=>!this.blockedSelectFields.includes(s))),r}getSchema(){let e=z.object({item:this.getModelSchema(),score:z.number().min(0).max(1),highlights:z.record(z.string(),z.array(z.string())).optional(),matchedFields:z.array(z.string())});return {...this.schema,request:{query:this.getQuerySchema()},responses:{200:{description:"Search results",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.array(e),result_info:z.object({page:z.number(),per_page:z.number(),total_count:z.number().optional(),total_pages:z.number().optional(),query:z.string(),searchedFields:z.array(z.string())})})}}},400:R("Invalid search request")}}}async getSearchOptions(){let{query:e}=await this.getValidatedData(),t=this.searchParamName||"q",o=e?.[t],r=e?.fields,s=wt(e?.mode),i=e?.highlight==="true",u=e?.minScore?Math.max(0,Math.min(1,Number.parseFloat(e.minScore)||0)):this.defaultMinScore,l=this.getSearchableFields(),c=bt(r,l);return {query:o,fields:c.length>0?c:Object.keys(l),mode:s??this.defaultMode,highlight:i,minScore:u}}async getFilters(){let{query:e}=await this.getValidatedData(),t=this.getSoftDeleteConfig(),o={filterFields:this.filterFields,filterConfig:this.filterConfig,searchFields:[],searchFieldName:"q",sortFields:this.sortFields,defaultSort:this.defaultSort,defaultPerPage:this.defaultPerPage,maxPerPage:this.maxPerPage,softDeleteQueryParam:t.queryParam,allowedIncludes:this.allowedIncludes,fieldSelectionEnabled:this.fieldSelectionEnabled,allowedSelectFields:this.allowedSelectFields,blockedSelectFields:this.blockedSelectFields,alwaysIncludeFields:this.alwaysIncludeFields,defaultSelectFields:this.defaultSelectFields};return te(e||{},o)}async beforeSearch(e){return e}async afterSearch(e){return e}async handle(){let e=await this.getSearchOptions(),t=await this.getFilters();if(!e.query||e.query.length<this.minQueryLength)return this.json({success:false,error:{code:"INVALID_QUERY",message:`Search query must be at least ${this.minQueryLength} characters`}},400);e=await this.beforeSearch(e);let o=await this.search(e,t),r=await this.afterSearch(o.items),s=this.fieldSelectionEnabled&&t.options.fields&&t.options.fields.length>0?{fields:t.options.fields,isActive:true}:void 0,i=await this.finalizeArray(r.map(p=>p.item),s),u=r.map((p,m)=>({...p,item:i[m]})),l=o.postFilteredCount??o.totalCount,c=t.options.page||1,a=t.options.per_page||this.defaultPerPage,d=Math.ceil(l/a);return this.successPaginated(u,{page:c,per_page:a,total_count:l,total_pages:d,query:e.query,searchedFields:e.fields||Object.keys(this.getSearchableFields())})}};function tr(n,e,t){let o=ht(e.query,e.mode),r={},s=e.fields||Object.keys(t);for(let u of s)t[u]&&(r[u]=t[u]);let i=[];for(let u of n){let{score:l,matchedFields:c}=ft(u,o,r,e.mode);if(l<e.minScore||c.length===0)continue;let a;if(e.highlight){a={};for(let d of c){let p=gt(u[d],o,e.mode);p.length>0&&(a[d]=p);}}i.push({item:u,score:l,highlights:a&&Object.keys(a).length>0?a:void 0,matchedFields:c});}return i.sort((u,l)=>l.score-u.score),i}function G(n,e={}){let{delimiter:t=",",nullValue:o="",dateFormat:r="iso"}=e;if(n==null)return o;if(n instanceof Date)switch(r){case "timestamp":return String(n.getTime());case "locale":return n.toLocaleString();default:return n.toISOString()}if(typeof n=="object")return G(JSON.stringify(n),e);if(typeof n=="boolean")return n?"true":"false";let s=String(n),i=s.charAt(0);return i==="="||i==="+"||i==="-"||i==="@"||i===" "||i==="\r"?`" ${s.replace(/"/g,'""')}"`:s.includes(t)||s.includes('"')||s.includes(`
2
+ `)||s.includes("\r")?`"${s.replace(/"/g,'""')}"`:s}function Ce(n,e={}){let{delimiter:t=",",rowDelimiter:o=`\r
3
+ `,includeHeader:r=true,formatters:s={},excludeFields:i=[],headerLabels:u={},nullValue:l="",dateFormat:c="iso"}=e;if(n.length===0)return "";let a=e.headers;a?a=a.filter(p=>!i.includes(p)):a=Object.keys(n[0]).filter(p=>!i.includes(p));let d=[];if(r){let p=a.map(m=>{let h=u[m]||m;return G(h,{delimiter:t,nullValue:l,dateFormat:c})});d.push(p.join(t));}for(let p of n){let m=a.map(h=>{let f=p[h];return s[h]&&(f=s[h](f)),G(f,{delimiter:t,nullValue:l,dateFormat:c})});d.push(m.join(t));}return d.join(o)}function or(n,e={}){let{delimiter:t=",",rowDelimiter:o=`\r
4
+ `,includeHeader:r=true,formatters:s={},excludeFields:i=[],headerLabels:u={},nullValue:l="",dateFormat:c="iso"}=e,a=new TextEncoder,d=0,p=false,m=e.headers;return !m&&n.length>0?m=Object.keys(n[0]).filter(h=>!i.includes(h)):m?m=m.filter(h=>!i.includes(h)):m=[],new ReadableStream({pull(h){if(r&&!p&&m.length>0){let b=m.map(g=>{let S=u[g]||g;return G(S,{delimiter:t,nullValue:l,dateFormat:c})});h.enqueue(a.encode(b.join(t)+o)),p=true;return}let f=100,y=[];for(;d<n.length&&y.length<f;){let b=n[d],g=m.map(S=>{let F=b[S];return s[S]&&(F=s[S](F)),G(F,{delimiter:t,nullValue:l,dateFormat:c})});y.push(g.join(t)),d++;}y.length>0&&h.enqueue(a.encode(y.join(o)+o)),d>=n.length&&h.close();}})}function lo(n,e){let t=[],o="",r=false,s=0;for(;s<n.length;){let i=n[s];if(r){if(i==='"'){if(s+1<n.length&&n[s+1]==='"'){o+='"',s+=2;continue}r=false,s++;continue}o+=i,s++;}else {if(i==='"'){r=true,s++;continue}if(i===e){t.push(o),o="",s++;continue}o+=i,s++;}}return t.push(o),t}function rr(n){let e=[],t="",o=false;for(let r=0;r<n.length;r++){let s=n[r];if(s==='"'){if(o&&r+1<n.length&&n[r+1]==='"'){t+='""',r++;continue}o=!o,t+=s;continue}if(!o&&(s===`
5
+ `||s==="\r")){s==="\r"&&r+1<n.length&&n[r+1]===`
6
+ `&&r++,t.length>0&&(e.push(t),t="");continue}t+=s;}return t.length>0&&e.push(t),e}function Pe(n,e={}){let{delimiter:t=",",hasHeader:o=true,trimValues:r=true,skipEmptyRows:s=true,parsers:i={},emptyValue:u="empty"}=e,l={data:[],headers:[],errors:[]},c=rr(n);if(c.length===0)return l;let a=0;if(o){let p=c[0];l.headers=lo(p,t).map(m=>r?m.trim():m),a=1;}else e.headers&&(l.headers=e.headers);let d=e.headers||l.headers;for(let p=a;p<c.length;p++){let m=c[p],h=p+1;if(!(s&&m.trim()===""))try{let f=lo(m,t),y={};for(let b=0;b<d.length;b++){let g=d[b],S=b<f.length?f[b]:"";if(r&&typeof S=="string"&&(S=S.trim()),S==="")switch(u){case "null":S=null;break;case "undefined":S=void 0;break}if(i[g]&&typeof S=="string")try{S=i[g](S);}catch(F){l.errors.push({row:h,message:`Failed to parse field "${g}": ${F instanceof Error?F.message:String(F)}`,content:m});}y[g]=S;}l.data.push(y);}catch(f){l.errors.push({row:h,message:`Failed to parse row: ${f instanceof Error?f.message:String(f)}`,content:m});}}return l}function qt(n,e,t={}){let{allowUnknownFields:o=false,optionalFields:r=[]}=t,s=e.shape,i=Object.keys(s),l=i.filter(p=>r.includes(p)?false:!s[p].isOptional()).filter(p=>!n.includes(p)),c=n.filter(p=>!i.includes(p)),a=n.filter(p=>i.includes(p));return {valid:l.length===0&&(o||c.length===0),missingFields:l,unknownFields:c,validFields:a}}function nr(n,e){if(n){let t=n.toLowerCase().split(".").pop();if(t==="csv")return "csv";if(t==="json")return "json"}if(e){let t=e.trim();if(t.startsWith("[")||t.startsWith("{"))return "json";if(t.includes(",")||t.includes(`
7
+ `))return "csv"}return "unknown"}function sr(n,e={}){return Ce(n,e)}function ir(n,e={}){return Pe(n,e).data}var zt=class extends be{maxExportRecords=1e4;enableStreaming=true;streamPageSize=500;excludedExportFields=[];defaultFormat="json";csvOptions={};exportFilename;getExportQuerySchema(){return this.getQuerySchema().extend({format:z.enum(["json","csv"]).optional().meta({description:"Export format"}),stream:z.enum(["true","false"]).optional().meta({description:"Enable streaming for large exports"})})}getSchema(){return {...this.schema,request:{query:this.getExportQuerySchema()},responses:{200:{description:"Export successful",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({data:z.array(this.getModelSchema()),count:z.number(),format:z.enum(["json","csv"]),exportedAt:z.string()})})},"text/csv":{schema:z.string()}}}}}}async getExportOptions(){let{query:e}=await this.getValidatedData(),t=e?.format||this.defaultFormat,o=e?.stream==="true"&&this.enableStreaming;return {format:t,stream:o,fields:e?.fields?String(e.fields).split(","):void 0}}getExportFilename(e){let o=(this.exportFilename||this._meta.model.tableName).replace(/[^a-zA-Z0-9_-]/g,"_"),r=new Date().toISOString().replace(/[:.]/g,"-");return `${o}-export-${r}.${e}`}prepareRecordsForExport(e){return this.excludedExportFields.length===0?e:e.map(t=>{let o={};for(let[r,s]of Object.entries(t))this.excludedExportFields.includes(r)||(o[r]=s);return o})}exportAsJson(e,t){let o={data:e,count:e.length,format:t,exportedAt:new Date().toISOString()};return new Response(JSON.stringify({success:true,result:o},null,2),{status:200,headers:{"Content-Type":"application/json","Content-Disposition":`attachment; filename="${this.getExportFilename(t)}"`}})}exportAsCsv(e,t){let o=Ce(e,{...this.csvOptions,excludeFields:this.excludedExportFields});return new Response(o,{status:200,headers:{"Content-Type":"text/csv; charset=utf-8","Content-Disposition":`attachment; filename="${this.getExportFilename(t)}"`}})}exportAsCsvStream(e,t){let o=this.getContext(),r=this.getExportFilename(t),s=this.csvOptions,i=this.excludedExportFields;return stream(o,async u=>{if(o.header("Content-Type","text/csv; charset=utf-8"),o.header("Content-Disposition",`attachment; filename="${r}"`),e.length===0)return;let l=Object.keys(e[0]).filter(d=>!i.includes(d)),c=l.map(d=>G(d,s)).join(",")+`
8
+ `;await u.write(c);let a=100;for(let d=0;d<e.length;d+=a)for(let p of e.slice(d,d+a)){let m=l.map(h=>G(p[h],s)).join(",")+`
9
+ `;await u.write(m);}})}exportAsCsvStreamPaginated(e,t){let o=this.getExportFilename(t),r=this.streamPageSize,s=Math.min(this.maxExportRecords,1e5),i=this.excludedExportFields,u=this.csvOptions,l=null,c=new ReadableStream({start:async a=>{let d=new TextEncoder,p=1,m=0;try{for(;m<s;){let h={...e,options:{...e.options,page:p,per_page:r}},y=(await this.list(h)).result;if(y.length===0)break;y.length>s-m&&(y=y.slice(0,s-m)),y=await this.after(y),y=await this.beforeExport(y);let b=this.prepareRecordsForExport(y);if(!l&&b.length>0){l=Object.keys(b[0]).filter(S=>!i.includes(S));let g=l.map(S=>G(S,u)).join(",")+`
10
+ `;a.enqueue(d.encode(g));}if(l)for(let g of b){let S=l.map(F=>G(g[F],u)).join(",")+`
11
+ `;a.enqueue(d.encode(S));}if(m+=y.length,p++,y.length<r)break}}catch(h){a.error(h);return}a.close();}});return new Response(c,{status:200,headers:{"Content-Type":"text/csv; charset=utf-8","Content-Disposition":`attachment; filename="${o}"`}})}async beforeExport(e){return e}async fetchAllForExport(e){let t=Math.min(this.maxExportRecords,1e5),o={...e,options:{...e.options,page:1,per_page:t}};return (await this.list(o)).result}async handle(){let e=await this.getExportOptions(),t=await this.getFilters();if(e.format==="csv"&&e.stream)return this.exportAsCsvStreamPaginated(t,e.format);let o=await this.fetchAllForExport(t);o=await this.after(o),o=await this.beforeExport(o);let r=this.prepareRecordsForExport(o);return e.format==="csv"?this.exportAsCsv(r,e.format):this.exportAsJson(r,e.format)}};var $t=class extends x{maxBatchSize=1e3;importBatchSize=100;stopOnError=false;skipInvalidRows=true;defaultMode="create";upsertKeys;immutableFields=[];csvOptions={};maxBodySize=10*1024*1024;optionalImportFields=[];getUpsertKeys(){return this.upsertKeys||this._meta.model.primaryKeys}getImportSchema(){let e=this._meta.fields?this._meta.fields:V(this.getModelSchema(),D(this._meta.model));return z.object({items:z.array(e.partial()).min(1).max(this.maxBatchSize)})}getSchema(){return {...this.schema,request:{query:z.object({mode:z.enum(["create","upsert"]).optional().meta({description:"Import mode"}),skipInvalid:z.enum(["true","false"]).optional().meta({description:"Skip invalid rows"}),stopOnError:z.enum(["true","false"]).optional().meta({description:"Stop on first error"})})},responses:{200:{description:"Import completed successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({summary:z.object({total:z.number(),created:z.number(),updated:z.number(),skipped:z.number(),failed:z.number()}),results:z.array(z.object({rowNumber:z.number(),status:z.enum(["created","updated","skipped","failed"]),data:z.unknown().optional(),error:z.string().optional(),code:z.string().optional(),validationErrors:z.array(z.object({path:z.string(),message:z.string()})).optional()}))})})}}},207:{description:"Import completed with partial failures",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({summary:z.object({total:z.number(),created:z.number(),updated:z.number(),skipped:z.number(),failed:z.number()}),results:z.array(z.object({rowNumber:z.number(),status:z.enum(["created","updated","skipped","failed"]),data:z.unknown().optional(),error:z.string().optional(),code:z.string().optional(),validationErrors:z.array(z.object({path:z.string(),message:z.string()})).optional()}))})})}}},400:R("Validation error")}}}async getImportOptions(){let{query:e}=await this.getValidatedData(),t=e?.skipInvalid==="true"?true:e?.skipInvalid==="false"?false:this.skipInvalidRows,o=e?.stopOnError==="true"?true:e?.stopOnError==="false"?false:this.stopOnError;return {mode:e?.mode||this.defaultMode,skipInvalidRows:t,stopOnError:o}}async parseImportData(){let e=this.context;if(!e)throw new b("No request available");let t=e.req.header("content-type")||"";if(t.includes("application/json")){let o=await e.req.json();if(!o)throw new b("Request body is empty");if(!o.items||!Array.isArray(o.items))throw new b('Request body must contain an "items" array');if(o.items.length>this.maxBatchSize)throw new b(`Maximum ${this.maxBatchSize} items allowed per import`);return o.items}if(t.includes("text/csv")){let o=await e.req.text();if(o.length>this.maxBodySize)throw new b(`Request body exceeds maximum size of ${this.maxBodySize} bytes`);return this.parseCsvData(o)}if(t.includes("multipart/form-data")){let r=(await e.req.formData()).get("file");if(!r)throw new b("No file provided in form data");let s=await r.text();if(s.length>this.maxBodySize)throw new b(`Uploaded file exceeds maximum size of ${this.maxBodySize} bytes`);let i=r.name.toLowerCase();if(i.endsWith(".json")){let l;try{l=JSON.parse(s);}catch{throw new b("Invalid JSON content in uploaded file")}let c=Array.isArray(l)?l:l.items;if(!c||!Array.isArray(c))throw new b('JSON file must contain an array or an object with "items" array');if(c.length>this.maxBatchSize)throw new b(`Maximum ${this.maxBatchSize} items allowed per import`);return c}if(i.endsWith(".csv"))return this.parseCsvData(s);let u=s.trim();if(u.startsWith("[")||u.startsWith("{")){let l;try{l=JSON.parse(s);}catch{throw new b("Invalid JSON content in uploaded file")}let c=Array.isArray(l)?l:l.items;if(!c||!Array.isArray(c))throw new b('JSON file must contain an array or an object with "items" array');return c}return this.parseCsvData(s)}throw new b("Unsupported content type. Use application/json, text/csv, or multipart/form-data")}parseCsvData(e){let t=Pe(e,this.csvOptions);if(t.errors.length>0)throw new b(`CSV parsing errors: ${t.errors.map(s=>`Row ${s.row}: ${s.message}`).join("; ")}`);if(t.data.length===0)throw new b("CSV file is empty");if(t.data.length>this.maxBatchSize)throw new b(`Maximum ${this.maxBatchSize} items allowed per import`);let o=this._meta.fields||this.getModelSchema(),r=qt(t.headers,o,{allowUnknownFields:true,optionalFields:this.optionalImportFields});if(!r.valid&&r.missingFields.length>0)throw new b(`Missing required fields in CSV: ${r.missingFields.join(", ")}`);return t.data}validateRow(e,t){let o=this._meta.fields||this.getModelSchema(),r={};for(let i of D(this._meta.model))r[i]=true;for(let i of this.optionalImportFields)r[i]=true;let s=o.partial(r);try{return s.parse(e),{valid:!0}}catch(i){return i instanceof z.ZodError?{valid:false,errors:i.issues.map(l=>({path:l.path.join("."),message:l.message}))}:{valid:false,errors:[{path:"",message:i instanceof Error?i.message:String(i)}]}}}removeImmutableFields(e){if(this.immutableFields.length===0)return e;let t={};for(let[o,r]of Object.entries(e))this.immutableFields.includes(o)||(t[o]=r);return t}async before(e,t,o,r){return e}async after(e,t,o,r){return e}async processRow(e,t,o,r){let s=this.validateRow(e,t);if(!s.valid)return o.skipInvalidRows?{rowNumber:t,status:"skipped",error:"Validation failed",validationErrors:s.errors}:{rowNumber:t,status:"failed",error:"Validation failed",validationErrors:s.errors};try{let i=await this.before(e,t,o.mode,r);if(o.mode==="upsert"){let l=await this.findExisting(i,r);if(l){let c=this.removeImmutableFields(i),a=await this.update(l,c,r);return {rowNumber:t,status:"updated",data:a}}}else if(await this.findExisting(i,r))return o.skipInvalidRows?{rowNumber:t,status:"skipped",error:"Record already exists"}:{rowNumber:t,status:"failed",error:"Record already exists (duplicate key)"};let u=await this.create(i,r);return {rowNumber:t,status:"created",data:u}}catch(i){let u=Ee(i);return u?{rowNumber:t,status:"failed",code:"CONFLICT",error:u.message}:{rowNumber:t,status:"failed",error:i instanceof Error?i.message:String(i)}}}async handle(){let e=await this.getImportOptions(),t=await this.parseImportData();if(!Number.isInteger(this.importBatchSize)||this.importBatchSize<1)throw new i("importBatchSize must be a positive integer");let o={total:t.length,created:0,updated:0,skipped:0,failed:0},r=[],s=false,i$1=e.stopOnError?1:this.importBatchSize;for(let c=0;c<t.length&&!s;c+=i$1){let a=t.slice(c,c+i$1),d=await Promise.all(a.map(async(p,m)=>{let h=c+m+1,f=await this.processRow(p,h,e);return f=await this.after(f,h,e.mode),f}));for(let p of d){switch(r.push(p),p.status){case "created":o.created++;break;case "updated":o.updated++;break;case "skipped":o.skipped++;break;case "failed":o.failed++;break}if(e.stopOnError&&p.status==="failed"){s=true;break}}}if(this.isAuditEnabled()){let c=this.getAuditLogger(),a=r.filter(d=>d.status==="created"||d.status==="updated");if(a.length>0){let d=a.map(p=>{if(!p.data)return null;let m=this.getRecordId(p.data);return m===null?null:{recordId:m,record:p.data}}).filter(p=>p!==null);d.length>0&&this.runAfterResponse(c.logBatch(e.mode==="upsert"?"batch_upsert":"batch_create",this._meta.model.tableName,d,this.getAuditUserId()));}}let u={summary:o,results:r},l=o.failed>0&&o.failed<o.total?207:200;return this.json({success:true,result:u},l)}};var je=Symbol.for("hono-crud.resource-registry");function co(n,e,t){let o=n;o[je]||(o[je]=[]),o[je].push({path:e,endpoints:t});}function Ni(n){return n[je]??[]}function dr(n,e,t,o={}){let r=e.endsWith("/")?e.slice(0,-1):e,s=n,{middlewares:i=[],endpointMiddlewares:u={},responseEnvelope:l$1}=o,c=l$1?async(p,m)=>{b$4(p,l,l$1),await m();}:void 0,a=p=>{let m=t[p],h=m&&"_middlewares"in m?m._middlewares||[]:[];return [...c?[c]:[],...i,...u[p]||[],...h]},d=(p,m,h,f)=>{let y=a(h),b=s[p];y.length>0?b(m,...y,f):b(m,f);};t.create&&d("post",r,"create",t.create),t.list&&d("get",r,"list",t.list),t.batchCreate&&d("post",`${r}/batch`,"batchCreate",t.batchCreate),t.batchUpdate&&d("patch",`${r}/batch`,"batchUpdate",t.batchUpdate),t.batchDelete&&d("delete",`${r}/batch`,"batchDelete",t.batchDelete),t.batchRestore&&d("post",`${r}/batch/restore`,"batchRestore",t.batchRestore),t.batchUpsert&&d("post",`${r}/batch/upsert`,"batchUpsert",t.batchUpsert),t.search&&d("get",`${r}/search`,"search",t.search),t.aggregate&&d("get",`${r}/aggregate`,"aggregate",t.aggregate),t.export&&d("get",`${r}/export`,"export",t.export),t.import&&d("post",`${r}/import`,"import",t.import),t.upsert&&d("post",`${r}/upsert`,"upsert",t.upsert),t.bulkPatch&&d("patch",`${r}/bulk`,"bulkPatch",t.bulkPatch),t.read&&d("get",`${r}/:id`,"read",t.read),t.update&&d("patch",`${r}/:id`,"update",t.update),t.delete&&d("delete",`${r}/:id`,"delete",t.delete),t.restore&&d("post",`${r}/:id/restore`,"restore",t.restore),t.clone&&d("post",`${r}/:id/clone`,"clone",t.clone),t.versionHistory&&d("get",`${r}/:id/versions`,"versionHistory",t.versionHistory),t.versionCompare&&d("get",`${r}/:id/versions/compare`,"versionCompare",t.versionCompare),t.versionRead&&d("get",`${r}/:id/versions/:version`,"versionRead",t.versionRead),t.versionRollback&&d("post",`${r}/:id/versions/:version/rollback`,"versionRollback",t.versionRollback),co(n,r,t);}function Kt(n){return {content:{"application/json":{schema:n}}}}function lr(n){return {description:"Success",...Kt({type:"object",properties:{success:{type:"boolean",enum:[true]},result:n},required:["success","result"]})}}function cr(n="Error"){return {description:n,...Kt({type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"object",properties:{code:{type:"string"},message:{type:"string"},details:{}},required:["code","message"]}},required:["success","error"]})}}function Wt(n,e){return {content:{"application/json":{schema:n}},description:e}}function pr(n,e){return {content:{"application/json":{schema:n}},description:e,required:true}}var po=z.object({code:z.string(),path:z.array(z.union([z.string(),z.number()])),message:z.string()}),ve=z.object({success:z.literal(false),error:z.object({name:z.literal("ZodError"),issues:z.array(po)})});function ur(n){return ve}function mr(...n){return ve}var hr=(n,e)=>{if(!n.success)return e.json({success:false,error:{name:"ZodError",issues:n.error.issues}},422)};function fr(n,e=422){return (t,o)=>{if(!t.success)return o.json(n(t.error),e)}}var uo=z.object({success:z.literal(false),error:z.object({message:z.string(),code:z.string().optional()})});function oe(n){return Wt(uo,n)}var gr={badRequest:oe("Bad request"),unauthorized:oe("Unauthorized"),forbidden:oe("Forbidden"),notFound:oe("Resource not found"),conflict:oe("Resource conflict"),validationError:Wt(ve,"Validation error"),internalError:oe("Internal server error")};var Fe=class{constructor(e){this.meta=e;}_schema={};_before;_after;_beforeHookMode="sequential";_afterHookMode="sequential";_allowNestedCreate=[];_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}before(e){return this._before=e,this}after(e){return this._after=e,this}beforeMode(e){return this._beforeHookMode=e,this}afterMode(e){return this._afterHookMode=e,this}nestedCreate(...e){return this._allowNestedCreate=e,this}build(e){return a$2(e,{meta:this.meta,schema:this._schema,before:this._before,after:this._after,beforeHookMode:this._beforeHookMode,afterHookMode:this._afterHookMode,allowNestedCreate:this._allowNestedCreate,middlewares:this._middlewares})}},Ie=class{constructor(e){this.meta=e;}_schema={};_filterFields=[];_filterConfig;_searchFields=[];_searchFieldName="search";_sortFields=[];_defaultSort;_defaultPerPage=20;_maxPerPage=100;_allowedIncludes=[];_fieldSelectionEnabled=false;_allowedSelectFields=[];_blockedSelectFields=[];_alwaysIncludeFields=[];_defaultSelectFields=[];_after;_transform;_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}filter(...e){return this._filterFields=e,this}filterWith(e){return this._filterConfig=e,this}search(...e){return this._searchFields=e,this}searchParam(e){return this._searchFieldName=e,this}sortable(...e){return this._sortFields=e,this}orderBy(...e){return this.sortable(...e)}defaultSort(e,t="asc"){return this._defaultSort={field:e,order:t},this}defaultOrder(e,t="asc"){return this.defaultSort(e,t)}pagination(e,t){return this._defaultPerPage=e,t!==void 0&&(this._maxPerPage=t),this}include(...e){return this._allowedIncludes=e,this}fieldSelection(e){return this._fieldSelectionEnabled=true,e?.allowed&&(this._allowedSelectFields=e.allowed),e?.blocked&&(this._blockedSelectFields=e.blocked),e?.alwaysInclude&&(this._alwaysIncludeFields=e.alwaysInclude),e?.defaults&&(this._defaultSelectFields=e.defaults),this}after(e){return this._after=e,this}transform(e){return this._transform=e,this}build(e){return a$2(e,{meta:this.meta,schema:this._schema,filterFields:this._filterFields,filterConfig:this._filterConfig,searchFields:this._searchFields,searchFieldName:this._searchFieldName,sortFields:this._sortFields,defaultSort:this._defaultSort,defaultPerPage:this._defaultPerPage,maxPerPage:this._maxPerPage,allowedIncludes:this._allowedIncludes,fieldSelectionEnabled:this._fieldSelectionEnabled,allowedSelectFields:this._allowedSelectFields,blockedSelectFields:this._blockedSelectFields,alwaysIncludeFields:this._alwaysIncludeFields,defaultSelectFields:this._defaultSelectFields,after:this._after,transform:this._transform,middlewares:this._middlewares})}},Ae=class{constructor(e){this.meta=e;}_schema={};_lookupField="id";_additionalFilters;_allowedIncludes=[];_fieldSelectionEnabled=false;_allowedSelectFields=[];_blockedSelectFields=[];_alwaysIncludeFields=[];_defaultSelectFields=[];_after;_transform;_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}lookupField(e){return this._lookupField=e,this}additionalFilters(...e){return this._additionalFilters=e,this}include(...e){return this._allowedIncludes=e,this}fieldSelection(e){return this._fieldSelectionEnabled=true,e?.allowed&&(this._allowedSelectFields=e.allowed),e?.blocked&&(this._blockedSelectFields=e.blocked),e?.alwaysInclude&&(this._alwaysIncludeFields=e.alwaysInclude),e?.defaults&&(this._defaultSelectFields=e.defaults),this}after(e){return this._after=e,this}transform(e){return this._transform=e,this}build(e){return a$2(e,{meta:this.meta,schema:this._schema,lookupField:this._lookupField,additionalFilters:this._additionalFilters,allowedIncludes:this._allowedIncludes,fieldSelectionEnabled:this._fieldSelectionEnabled,allowedSelectFields:this._allowedSelectFields,blockedSelectFields:this._blockedSelectFields,alwaysIncludeFields:this._alwaysIncludeFields,defaultSelectFields:this._defaultSelectFields,after:this._after,transform:this._transform,middlewares:this._middlewares})}},_e=class{constructor(e){this.meta=e;}_schema={};_lookupField="id";_additionalFilters;_allowedUpdateFields;_blockedUpdateFields;_allowNestedWrites=[];_before;_after;_beforeHookMode="sequential";_afterHookMode="sequential";_transform;_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}lookupField(e){return this._lookupField=e,this}additionalFilters(...e){return this._additionalFilters=e,this}allowedFields(...e){return this._allowedUpdateFields=e,this}blockedFields(...e){return this._blockedUpdateFields=e,this}nestedWrites(...e){return this._allowNestedWrites=e,this}before(e){return this._before=e,this}after(e){return this._after=e,this}beforeMode(e){return this._beforeHookMode=e,this}afterMode(e){return this._afterHookMode=e,this}transform(e){return this._transform=e,this}build(e){return a$2(e,{meta:this.meta,schema:this._schema,lookupField:this._lookupField,additionalFilters:this._additionalFilters,allowedUpdateFields:this._allowedUpdateFields,blockedUpdateFields:this._blockedUpdateFields,allowNestedWrites:this._allowNestedWrites,before:this._before,after:this._after,beforeHookMode:this._beforeHookMode,afterHookMode:this._afterHookMode,transform:this._transform,middlewares:this._middlewares})}},Te=class{constructor(e){this.meta=e;}_schema={};_lookupField="id";_additionalFilters;_includeCascadeResults=false;_before;_after;_beforeHookMode="sequential";_afterHookMode="sequential";_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}lookupField(e){return this._lookupField=e,this}additionalFilters(...e){return this._additionalFilters=e,this}includeCascade(e=true){return this._includeCascadeResults=e,this}before(e){return this._before=e,this}after(e){return this._after=e,this}beforeMode(e){return this._beforeHookMode=e,this}afterMode(e){return this._afterHookMode=e,this}build(e){return a$2(e,{meta:this.meta,schema:this._schema,lookupField:this._lookupField,additionalFilters:this._additionalFilters,includeCascadeResults:this._includeCascadeResults,before:this._before,after:this._after,beforeHookMode:this._beforeHookMode,afterHookMode:this._afterHookMode,middlewares:this._middlewares})}},Ne=class{constructor(e){this.meta=e;}create(){return new Fe(this.meta)}list(){return new Ie(this.meta)}read(){return new Ae(this.meta)}update(){return new _e(this.meta)}delete(){return new Te(this.meta)}};function br(n){return new Ne(n)}export{jt as $,ct as A,dr as Aa,pt as B,Kt as Ba,ut as C,lr as Ca,mt as D,cr as Da,ht as E,Wt as Ea,to as F,pr as Fa,ft as G,po as Ga,gt as H,ve as Ha,bt as I,ur as Ia,yt as J,mr as Ja,wt as K,hr as Ka,de as L,fr as La,Et as M,uo as Ma,Rt as N,oe as Na,Uo as O,gr as Oa,te as P,Fe as Pa,V as Q,Ie as Qa,Bo as R,Ae as Ra,Re as S,_e as Sa,St as T,Te as Ta,xt as U,Ne as Ua,Ot as V,br as Va,kt as W,Ct as X,be as Y,Pt as Z,Wo as _,tt as a,vt as aa,Me as b,Ft as ba,ho as c,It as ca,Mo as d,At as da,Ro as e,_t as ea,jo as f,Tt as fa,Jt as g,Nt as ga,Io as h,Dt as ha,Yt as i,Ht as ia,ie as j,Vt as ja,D as k,Zt as ka,nt as l,Ut as la,st as m,Yo as ma,it as n,Bt as na,at as o,tr as oa,Xt as p,G as pa,Ee as q,Ce as qa,W as r,or as ra,Do as s,Pe as sa,Ho as t,qt as ta,ae as u,nr as ua,dt as v,sr as va,ee as w,ir as wa,ge as x,zt as xa,Vo as y,$t as ya,lt as z,Ni as za};
@@ -0,0 +1 @@
1
+ var e={userId:"userId",user:"user",roles:"roles",permissions:"permissions",authType:"authType",jwtPayload:"jwtPayload",organizationId:"organizationId",agentId:"agentId",agentRunId:"agentRunId",onBehalfOfUserId:"onBehalfOfUserId",toolCallId:"toolCallId",actionSource:"actionSource",tenantId:"tenantId",requestId:"requestId",requestStartTime:"requestStartTime",apiVersion:"apiVersion",apiVersionConfig:"apiVersionConfig",db:"db",loggingStorage:"loggingStorage",auditStorage:"auditStorage",versioningStorage:"versioningStorage",apiKeyStorage:"apiKeyStorage",cacheStorage:"cacheStorage",rateLimitStorage:"rateLimitStorage",idempotencyStorage:"idempotencyStorage",eventEmitter:"eventEmitter",rateLimit:"rateLimit",rateLimitKey:"rateLimitKey",responseEnvelope:"__honoCrudResponseEnvelope__",policies:"__honoCrudPolicies"};export{e as a};
@@ -0,0 +1 @@
1
+ import {c}from'./chunk-VESRPXGC.js';import {b as b$3}from'./chunk-MCXQ77DB.js';import {b as b$2}from'./chunk-DMGP7QDL.js';import {o,a as a$1,b}from'./chunk-OCJC5XWY.js';import {e,a as a$2,b as b$1}from'./chunk-VJRDAVID.js';import {a}from'./chunk-6GO5LUOZ.js';var Z=class{keys=new Map;hashToId=new Map;async store(t){this.keys.set(t.id,t),this.hashToId.set(t.keyHash,t.id);}async lookup(t){let r=this.hashToId.get(t);return r&&this.keys.get(r)||null}async getById(t){return this.keys.get(t)||null}async getByUserId(t){let r=[];for(let n of this.keys.values())n.userId===t&&r.push(n);return r}async revoke(t){let r=this.keys.get(t);return r?(r.active=false,true):false}async delete(t){let r=this.keys.get(t);return r?(this.hashToId.delete(r.keyHash),this.keys.delete(t),true):false}async updateLastUsed(t){let r=this.keys.get(t);r&&(r.lastUsedAt=new Date);}async generateKey(t){let r=t.prefix||"sk",n=Pe(r),o=await we(n),i={id:crypto.randomUUID(),keyHash:o,userId:t.userId,name:t.name,roles:t.roles,permissions:t.permissions,expiresAt:t.expiresAt??null,active:true,createdAt:new Date,metadata:t.metadata};return await this.store(i),{key:n,entry:i}}getAllKeys(){return Array.from(this.keys.values())}clear(){this.keys.clear(),this.hashToId.clear();}};function Pe(e="sk",t=32){let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=new Uint8Array(t);crypto.getRandomValues(n);let o="";for(let i=0;i<t;i++)o+=r[n[i]%r.length];return `${e}_${o}`}async function we(e){let r=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",r),o=new Uint8Array(n);return Array.from(o).map(i=>i.toString(16).padStart(2,"0")).join("")}function qe(e,t){if(!e||typeof e!="string")return false;let r=e.split("_");if(r.length!==2)return false;let[n,o]=r;return !(t&&n!==t||!/^[A-Za-z0-9]{16,}$/.test(o))}var w=o({contextKey:a.apiKeyStorage}),W=w.registry,be=w.get;w.getRequired;var De=w.set;function D(e){return e instanceof Error?e:new Error(String(e))}function _e(e,t){let r=D(e),n=new Error(`${t}: ${r.message}`);return n.cause=r,n}function Ue(e){return e instanceof Error?e.message:String(e)}var ee="\0DOUBLE_STAR\0",te="\0SINGLE_STAR\0";function E(e,t){if(t instanceof RegExp)return t.test(e);if(!t.includes("*"))return e===t;let r=t.replace(/\*\*/g,ee).replace(/\*/g,te).replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(new RegExp(ee,"g"),".*").replace(new RegExp(te,"g"),"[^/]*");return new RegExp(`^${r}$`).test(e)}function re(e,t){for(let r of t)if(E(e,r))return true;return false}function Oe(e,t,r){return re(e,r)?false:t.length===0?true:re(e,t)}function A(e,t){let r=e.toLowerCase();for(let n of t){if(n instanceof RegExp){if(n.test(e))return true;continue}let o=n.toLowerCase();if(o.includes("*")){let i=o.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");if(new RegExp(`^${i}$`).test(r))return true}else if(r===o)return true}return false}function I(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(n=>I(n,t));if(typeof e!="object")return e;let r={};for(let[n,o]of Object.entries(e))A(n,t)?r[n]="[REDACTED]":typeof o=="object"&&o!==null?r[n]=I(o,t):r[n]=o;return r}function ne(e,t){let r={};for(let[n,o]of Object.entries(e))r[n]=A(n,t)?"[REDACTED]":o;return r}function Ge(e,t){return A(e,t)}function F(e,t){return I(e,t)}function _(e,t){return ne(e,t)}function Qe(e,t){return E(e,t)}function oe(e,t,r){for(let n of r)if(E(e,n))return true;if(t.length===0)return false;for(let n of t)if(E(e,n))return false;return true}function se(e,t="X-Forwarded-For",r=false){return a$1(e,{ipHeader:t,trustProxy:r||true})}function U(e){let t={};return e.forEach((r,n)=>{t[n.toLowerCase()]=r;}),t}function ae(e){let t={};return new URL(e.req.url).searchParams.forEach((n,o)=>{t[o]=n;}),t}function x(e,t){if(typeof e=="string")return e.length>t?e.substring(0,t)+"... [TRUNCATED]":e;let r=JSON.stringify(e);return r.length>t?{_truncated:true,_originalSize:r.length,_maxSize:t}:e}function ie(e,t){if(!e)return false;if(t.length===0)return true;let r=e.toLowerCase();for(let n of t)if(r.includes(n.toLowerCase()))return true;return false}function ue(e){return b(e)}function de(){return e()}var v=o({contextKey:a.loggingStorage}),ce=v.registry,nt=v.set,Ie=v.get,Ae=v.getRequired,ve=["authorization","cookie","x-api-key","x-auth-token"],ke=["password","token","secret","apiKey","api_key","accessToken","access_token","refreshToken","refresh_token","creditCard","credit_card","ssn","socialSecurityNumber"],Le=["/health","/healthz","/ready","/readyz","/live","/livez","/metrics","/favicon.ico"];function ot(e){return a$2(e,a.requestId)}function st(e){return a$2(e,a.requestStartTime)}function at(e={}){let t=e.enabled??true,r=e.level??"info",n=e.includePaths??[],o=e.excludePaths??Le,i=e.redactHeaders??ve,B=e.redactBodyFields??ke,S=e.requestBody??{enabled:false},R=e.responseBody??{enabled:false},O=e.includeHeaders??true,le=e.includeQuery??true,fe=e.includeClientIp??true,pe=e.ipHeader??"X-Forwarded-For",ye=e.trustProxy??false,me=e.minResponseTimeMs??0,he=e.generateRequestId??de;return async(s,k)=>{if(!t)return k();let z=s.req.path;if(oe(z,n,o))return k();let L=he(),C=Date.now();b$1(s,a.requestId,L),b$1(s,a.requestStartTime,C),s.header("X-Request-ID",L);let Ee=s.req.method,xe=s.req.url,V;if(O){let g=U(s.req.raw.headers);V=_(g,i);}let $;le&&($=ae(s));let M;fe&&(M=se(s,pe,ye));let Se=ue(s),K;if(S.enabled){let g=s.req.header("content-type"),m=S.contentTypes??[];if(ie(g,m))try{let y=await s.req.raw.clone().text();if(y)try{let d=JSON.parse(y);d=F(d,B);let u=S.maxSize??10240;K=x(d,u);}catch{let d=S.maxSize??10240;K=x(y,d);}}catch{}}let c,T;try{await k();}catch(g){throw c=g instanceof Error?g:new Error(String(g)),g}finally{let m=Date.now()-C;if(m<me)return;let p=s.res.status,y;if(O){let a=U(s.res.headers);y=_(a,i);}if(R.enabled&&!c){let a=R.statusCodes??[];if(a.length===0||a.includes(p))try{let q=await s.res.clone().text();if(q)try{let h=JSON.parse(q);h=F(h,B);let Re=R.maxSize??10240;T=x(h,Re);}catch{let h=R.maxSize??10240;T=x(q,h);}}catch{}}let d=r;e.levelResolver?d=e.levelResolver(s,m,p,c):c||p>=500?d="error":p>=400&&(d="warn");let u={id:L,timestamp:new Date(C).toISOString(),level:d,request:{method:Ee,path:z,url:xe,headers:V,query:$,body:K,clientIp:M,userId:Se},response:{statusCode:p,headers:y,body:T,responseTimeMs:m}};if(c&&(u.error={message:c.message,name:c.name,stack:c.stack}),e.metadata){let a=typeof e.metadata=="function"?e.metadata(s):e.metadata;u.metadata=a;}e.formatter&&(u=e.formatter(u));let N=ge(s,e.storage);(async()=>{if(N)try{await N.store(u);}catch(a){e.onError&&e.onError(a instanceof Error?a:new Error(String(a)),u);}if(e.handlers)for(let a of e.handlers)try{await a(u);}catch(f){e.onError&&e.onError(f instanceof Error?f:new Error(String(f)),u);}})().catch(a=>{let f=D(a);e.onError?e.onError(f,u):b$2().error("Failed to process log entry",{error:f.message});});}}}function mt(e,t){return e.var[t]}function ge(e,t){return ce.resolve(e,t)}function ht(e,t){return b$3.resolve(e,t)}function Et(e,t){return c.resolve(e,t)}function xt(e,t){return W.resolve(e,t)}export{ie as A,ue as B,de as C,nt as D,Ie as E,Ae as F,ot as G,st as H,at as I,Z as a,Pe as b,we as c,qe as d,be as e,De as f,mt as g,ge as h,ht as i,Et as j,xt as k,D as l,_e as m,Ue as n,E as o,re as p,Oe as q,Ge as r,F as s,_ as t,Qe as u,oe as v,se as w,U as x,ae as y,x as z};
@@ -0,0 +1 @@
1
+ import {a}from'./chunk-6GO5LUOZ.js';var l={loggingStorage:a.loggingStorage,auditStorage:a.auditStorage,versioningStorage:a.versioningStorage,apiKeyStorage:a.apiKeyStorage,cacheStorage:a.cacheStorage,rateLimitStorage:a.rateLimitStorage,idempotencyStorage:a.idempotencyStorage,eventEmitter:a.eventEmitter};function o(t){return async(e,r)=>{for(let[a,i]of Object.entries(l)){let d=t[a];d&&e.set(i,d);}await r();}}function s(t){return o({loggingStorage:t})}function u(t){return o({auditStorage:t})}function S(t){return o({versioningStorage:t})}function p(t){return o({apiKeyStorage:t})}function c(t){return o({cacheStorage:t})}function v(t){return o({rateLimitStorage:t})}function m(t){return o({idempotencyStorage:t})}var g=class{map=new Map;isExpired;cleanupInterval;maxEntries;onEvict;lastCleanup=0;constructor(e){this.isExpired=e.isExpired,this.cleanupInterval=e.cleanupInterval??0,this.maxEntries=e.maxEntries??0,this.onEvict=e.onEvict;}maybeCleanup(e=Date.now()){this.cleanupInterval<=0||e-this.lastCleanup>=this.cleanupInterval&&(this.lastCleanup=e,this.cleanup(e));}get(e,r=Date.now()){let a=this.map.get(e);if(a!==void 0){if(this.isExpired(a,r)){this.delete(e);return}return a}}peek(e){return this.map.get(e)}has(e,r=Date.now()){return this.get(e,r)!==void 0}set(e,r,a=false){let i=this.map.has(e);if(this.maxEntries>0&&this.map.size>=this.maxEntries&&!i&&this.evictOldest(),i&&a){let d=this.map.get(e);this.map.delete(e),this.onEvict?.(e,d);}this.map.set(e,r);}delete(e){let r=this.map.get(e);return r===void 0?false:(this.map.delete(e),this.onEvict?.(e,r),true)}evictOldest(){let e=this.map.keys().next().value;e!==void 0&&this.delete(e);}cleanup(e=Date.now()){let r=0,a=[];for(let[i,d]of this.map.entries())this.isExpired(d,e)&&a.push(i);for(let i of a)this.delete(i)&&r++;return r}clear(){this.map.clear();}get size(){return this.map.size}getKeys(){return Array.from(this.map.keys())}entries(){return this.map.entries()}};export{o as a,s as b,u as c,S as d,p as e,c as f,v as g,m as h,g as i};
@@ -0,0 +1 @@
1
+ import {b as b$1}from'./chunk-DMGP7QDL.js';import {o}from'./chunk-OCJC5XWY.js';import {a}from'./chunk-6GO5LUOZ.js';var c=class{listeners=new Map;tableListeners=new Map;globalListeners=new Set;maxListeners;constructor(e){this.maxListeners=e?.maxListeners??100;}on(e,t,s){let n=`${e}:${t}`;this.listeners.has(n)||this.listeners.set(n,new Set);let i=this.listeners.get(n);return this.maxListeners>0&&i.size>=this.maxListeners?(b$1().warn(`Max listeners (${this.maxListeners}) reached for event "${n}". Listener not added.`),{unsubscribe:()=>{}}):(i.add(s),{unsubscribe:()=>{this.listeners.get(n)?.delete(s);}})}onTable(e,t){this.tableListeners.has(e)||this.tableListeners.set(e,new Set);let s=this.tableListeners.get(e);return this.maxListeners>0&&s.size>=this.maxListeners?(b$1().warn(`Max listeners (${this.maxListeners}) reached for table "${e}". Listener not added.`),{unsubscribe:()=>{}}):(s.add(t),{unsubscribe:()=>{this.tableListeners.get(e)?.delete(t);}})}onAny(e){return this.maxListeners>0&&this.globalListeners.size>=this.maxListeners?(b$1().warn(`Max global listeners (${this.maxListeners}) reached. Listener not added.`),{unsubscribe:()=>{}}):(this.globalListeners.add(e),{unsubscribe:()=>{this.globalListeners.delete(e);}})}off(e,t){this.listeners.delete(`${e}:${t}`);}removeAll(){this.listeners.clear(),this.tableListeners.clear(),this.globalListeners.clear();}async emit(e){let t=[],s=`${e.table}:${e.type}`,n=this.listeners.get(s);if(n)for(let a of n)t.push(this.safeCall(a,e));let i=this.tableListeners.get(e.table);if(i)for(let a of i)t.push(this.safeCall(a,e));for(let a of this.globalListeners)t.push(this.safeCall(a,e));await Promise.all(t);}emitAsync(e){this.emit(e).catch(t=>{b$1().error("Event emission error",{error:t instanceof Error?t.message:String(t)});});}listenerCount(){let e=this.globalListeners.size;for(let t of this.listeners.values())e+=t.size;for(let t of this.tableListeners.values())e+=t.size;return e}async safeCall(e,t){try{await e(t);}catch(s){b$1().error("Event listener error",{error:s instanceof Error?s.message:String(s)});}}},m=o({contextKey:a.eventEmitter,defaultFactory:()=>new c,lazyDefaultOnGet:true});m.registry;var b=m.getRequired,y=m.set,E=m.resolve;async function f(r,e){let t=new TextEncoder,s=await crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:"SHA-256"},false,["sign"]),n=await crypto.subtle.sign("HMAC",s,t.encode(r));return Array.from(new Uint8Array(n)).map(a=>a.toString(16).padStart(2,"0")).join("")}function g(r,e){if(!e||e.length===0)return true;let t=`${r.table}:${r.type}`;return e.some(s=>s==="*"||s===t)}async function C(r,e){let t=r.timeout??1e4,s=r.retries??2,n=JSON.stringify(e),i={"Content-Type":"application/json","X-Webhook-Event":`${e.table}.${e.type}`,"X-Webhook-Timestamp":e.timestamp,...r.headers??{}};if(r.secret){let o=await f(n,r.secret);i["X-Webhook-Signature"]=`sha256=${o}`;}let a;for(let o=0;o<=s;o++){try{let u=new AbortController,v=setTimeout(()=>u.abort(),t),d=await fetch(r.url,{method:"POST",headers:i,body:n,signal:u.signal});if(clearTimeout(v),d.ok)return {url:r.url,success:!0,statusCode:d.status,attempts:o+1};a=new Error(`HTTP ${d.status}: ${d.statusText}`);}catch(u){a=u instanceof Error?u:new Error(String(u));}o<s&&await new Promise(u=>setTimeout(u,1e3*Math.pow(2,o)));}return {url:r.url,success:false,error:a?.message,attempts:s+1}}function L(r){let e=E(void 0,r.emitter);if(!e)throw new Error("Event emitter not configured. Pass emitter explicitly or call setEventEmitter() first.");let t=n=>{for(let i of r.endpoints){if(!g(n,i.events))continue;let a=C(i,n).then(o=>{!o.success&&r.onError&&r.onError(i,n,new Error(o.error??"Unknown delivery error"));}).catch(o=>{r.onError&&r.onError(i,n,o instanceof Error?o:new Error(String(o)));});r.waitUntil&&r.waitUntil(a);}},s=e.onAny(t);return ()=>s.unsubscribe()}var x=["created","updated","deleted","restored"];export{c as a,b,y as c,E as d,L as e,x as f};
@@ -0,0 +1 @@
1
+ import {a as a$1,b as b$1}from'./chunk-EX4S3Q4M.js';import {o}from'./chunk-OCJC5XWY.js';import {a}from'./chunk-6GO5LUOZ.js';var u=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=[];}},d=o({contextKey:a.auditStorage,defaultFactory:()=>new u}),b=d.registry,w=d.set,p=d.get,v=d.getRequired,l=class{config;storage;constructor(t,e,r){this.config=a$1(t),this.storage=d.resolve(r,e);}getStorage(){if(!this.storage)throw new Error("Audit storage not configured. Pass storage explicitly or inject auditStorage with createStorageMiddleware().");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=b$1(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=b$1(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=b$1(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 E(c,t,e){return new l(c,t,e)}export{u as a,b,w as c,p as d,v as e,l as f,E as g};
@@ -1 +1 @@
1
- import {a}from'./chunk-A3O6KC4L.js';import {a as a$1}from'./chunk-IJBJE4G2.js';function l(e,n){return e.req.header(n)??void 0}function w(e,n){return e.req.query(n)??void 0}function C(e,n){let i=e.req.path,a=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace("\\{version\\}","([^/]+)"),d=new RegExp(`^${a}`);return i.match(d)?.[1]}function h(e){let{versions:n,strategy:i="header",headerName:p="Accept-Version",queryParam:a$2="version",urlPattern:d="/v{version}",extractVersion:f,addHeaders:c=true}=e,V=e.defaultVersion??n[0]?.version,u=new Map;for(let r of n)u.set(r.version,r);return async(r,m)=>{let t=f?f(r):{header:()=>l(r,p),query:()=>w(r,a$2),url:()=>C(r,d)}[i]();if(t=t??V,!t)throw new a("API version is required",400,"VERSION_REQUIRED");let o=u.get(t);if(!o)throw new a(`Unsupported API version: ${t}`,400,"UNSUPPORTED_VERSION");if(r.set(a$1.apiVersion,t),r.set(a$1.apiVersionConfig,o),c&&(r.header("X-API-Version",t),o.deprecated&&r.header("Deprecation",o.deprecated),o.sunset&&r.header("Sunset",o.sunset)),o.middleware&&o.middleware.length>0)for(let y of o.middleware)await y(r,async()=>{});await m();}}function v(e){return e.get(a$1.apiVersion)}function A(e){return e.get(a$1.apiVersionConfig)}function E(){return async(e,n)=>{await n();let i=e.get(a$1.apiVersionConfig);if(!(!i?.responseTransformer||!e.res.headers.get("content-type")?.includes("application/json")))try{let a=await e.res.json(),d=i.responseTransformer(a);e.res=new Response(JSON.stringify(d),{status:e.res.status,headers:e.res.headers});}catch{}}}export{h as a,v as b,A as c,E as d};
1
+ import {a}from'./chunk-A3O6KC4L.js';import {a as a$1}from'./chunk-6GO5LUOZ.js';function l(e,n){return e.req.header(n)??void 0}function w(e,n){return e.req.query(n)??void 0}function C(e,n){let i=e.req.path,a=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace("\\{version\\}","([^/]+)"),d=new RegExp(`^${a}`);return i.match(d)?.[1]}function h(e){let{versions:n,strategy:i="header",headerName:p="Accept-Version",queryParam:a$2="version",urlPattern:d="/v{version}",extractVersion:f,addHeaders:c=true}=e,V=e.defaultVersion??n[0]?.version,u=new Map;for(let r of n)u.set(r.version,r);return async(r,m)=>{let t=f?f(r):{header:()=>l(r,p),query:()=>w(r,a$2),url:()=>C(r,d)}[i]();if(t=t??V,!t)throw new a("API version is required",400,"VERSION_REQUIRED");let o=u.get(t);if(!o)throw new a(`Unsupported API version: ${t}`,400,"UNSUPPORTED_VERSION");if(r.set(a$1.apiVersion,t),r.set(a$1.apiVersionConfig,o),c&&(r.header("X-API-Version",t),o.deprecated&&r.header("Deprecation",o.deprecated),o.sunset&&r.header("Sunset",o.sunset)),o.middleware&&o.middleware.length>0)for(let y of o.middleware)await y(r,async()=>{});await m();}}function v(e){return e.get(a$1.apiVersion)}function A(e){return e.get(a$1.apiVersionConfig)}function E(){return async(e,n)=>{await n();let i=e.get(a$1.apiVersionConfig);if(!(!i?.responseTransformer||!e.res.headers.get("content-type")?.includes("application/json")))try{let a=await e.res.json(),d=i.responseTransformer(a);e.res=new Response(JSON.stringify(d),{status:e.res.status,headers:e.res.headers});}catch{}}}export{h as a,v as b,A as c,E as d};
@@ -0,0 +1 @@
1
+ import {a as a$1}from'./chunk-VJRDAVID.js';import {a as a$2}from'./chunk-6GO5LUOZ.js';function E(e,t={}){let{ipHeader:r="X-Forwarded-For",trustProxy:n=true}=t;if(n){let u=e.req.header(r);if(u){let d=u.split(",")[0]?.trim();if(d)return d}let g=e.req.header("X-Real-IP")?.trim();if(g)return g;let f=e.req.header("CF-Connecting-IP")?.trim();if(f)return f}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 x(e){return a$1(e,"userId")}function S(e){return a$1(e,a$2.user)}function a(e){return a$1(e,a$2.roles)}function c(e){return a$1(e,a$2.permissions)}function R(e){return a$1(e,a$2.authType)}function b(e,t){return a(e)?.includes(t)??false}function q(e,t){return c(e)?.includes(t)??false}function F(e,t){let r=a(e);return r?t.every(n=>r.includes(n)):false}function I(e,t){let r=a(e);return r?t.some(n=>r.includes(n)):false}function w(e,t){let r=c(e);return r?t.every(n=>r.includes(n)):false}var i=class{globalStorage=null;contextKey;defaultFactory;defaultInitialized=false;constructor(t,r){this.contextKey=t,this.defaultFactory=r??null;}ensureDefault(){!this.defaultInitialized&&this.defaultFactory&&this.globalStorage===null&&(this.globalStorage=this.defaultFactory(),this.defaultInitialized=true);}set(t){this.globalStorage=t;}get(){return this.ensureDefault(),this.globalStorage}getConfigured(){return this.globalStorage}getRequired(){if(this.ensureDefault(),this.globalStorage===null)throw new Error(`Storage not configured for '${this.contextKey}'`);return this.globalStorage}resolve(t,r){if(r)return r;if(t){let n=a$1(t,this.contextKey);if(n)return n}return this.globalStorage}resolveRequired(t,r){let n=this.resolve(t,r);if(n===null)throw new Error(`Storage not configured for '${this.contextKey}'`);return n}reset(){this.defaultInitialized=false,this.globalStorage=null;}getContextKey(){return this.contextKey}isConfigured(){return this.globalStorage!==null}};function A(e){return new i(e)}function P(e,t){return new i(e,t)}function V(e){let t=new i(e.contextKey,e.defaultFactory),r=e.lazyDefaultOnGet===true&&e.defaultFactory!=null;return {registry:t,set:n=>t.set(n),get:()=>r?t.get():t.getConfigured(),getRequired:()=>t.getRequired(),resolve:(n,o)=>t.resolve(n,o),resolveRequired:(n,o)=>t.resolveRequired(n,o)}}export{E as a,x as b,S as c,a as d,c as e,R as f,b as g,q as h,F as i,I as j,w as k,i as l,A as m,P as n,V as o};
@@ -0,0 +1 @@
1
+ import {k as k$1,p}from'./chunk-DALXO46J.js';import {a as a$2}from'./chunk-NWOJZP4P.js';import {e,i,f}from'./chunk-A3O6KC4L.js';import {b as b$2}from'./chunk-DMGP7QDL.js';import {b as b$1,a as a$1}from'./chunk-VJRDAVID.js';import {a}from'./chunk-6GO5LUOZ.js';import {z as z$1}from'zod';import {decode,verify}from'hono/jwt';var O=["HS256","HS384","HS512","RS256","RS384","RS512","ES256","ES384","ES512"],U=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(),email:z$1.string().optional(),role:z$1.string().optional(),roles:z$1.union([z$1.array(z$1.string()),z$1.string()]).optional(),permissions:z$1.union([z$1.array(z$1.string()),z$1.string()]).optional(),metadata:z$1.record(z$1.string(),z$1.unknown()).optional()}).passthrough();function ne(e){return U.parse(e)}function M(e){return U.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 C(e$1,t={}){let{clockTolerance:n=0,issuer:r,audience:o,skipTimeValidation:s=false}=t;if(!s){let u=Math.floor(Date.now()/1e3);if(e$1.exp!==void 0&&u>e$1.exp+n)throw new e("Token has expired");if(e$1.nbf!==void 0&&u<e$1.nbf-n)throw new e("Token not yet valid")}if(r!==void 0&&e$1.iss!==r)throw new e("Invalid token issuer");if(o!==void 0){let u=Array.isArray(o)?o:[o],d=Array.isArray(e$1.aud)?e$1.aud:[e$1.aud];if(!u.some(y=>d.includes(y)))throw new e("Invalid token audience")}}function X(e){if(!O.includes(e))throw new Error(`Unsupported algorithm: ${e}`);return e}function oe(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 $(e){if(e!==void 0)return Array.isArray(e)?e:[e]}function se(e){return {id:String(e.sub||e.id||""),email:e.email,roles:$(e.roles??e.role),permissions:$(e.permissions),metadata:e.metadata}}function j(e$1){let t=X(e$1.algorithm||"HS256"),n=e$1.clockTolerance||0,r=e$1.extractToken||oe,o=e$1.extractUser||se;return async(s,u)=>{let d=r(s);if(!d)throw new e("Missing authentication token");let c=decode(d);if(!c||!c.header)throw new e("Invalid token format");if(c.header.alg!==t)throw new e("Invalid token algorithm");let y;try{y=await verify(d,e$1.secret,t);}catch(g){if(g instanceof Error){if(g.message.includes("expired")||g.name==="JwtTokenExpired")throw new e("Token has expired");if(g.message.includes("signature")||g.name==="JwtTokenSignatureMismatched")throw new e("Invalid token signature");if(g.message.includes("not valid yet")||g.name==="JwtTokenNotYetValid")throw new e("Token not yet valid")}throw new e("Invalid token")}let m=M(y);if(!m.success)throw new e("Invalid token claims");let A=m.data;C(A,{clockTolerance:n,issuer:e$1.issuer,audience:e$1.audience});let f=o(A);s.set(a.userId,f.id),s.set(a.user,f),s.set(a.roles,f.roles||[]),s.set(a.permissions,f.permissions||[]),s.set(a.authType,"jwt"),await u();}}async function ie(e$1,t){let n=X(t.algorithm||"HS256"),r=t.clockTolerance||0,o=decode(e$1);if(!o||!o.header)throw new e("Invalid token format");if(o.header.alg!==n)throw new e("Invalid token algorithm");let s;try{s=await verify(e$1,t.secret,n);}catch(d){if(d instanceof Error){if(d.message.includes("expired")||d.name==="JwtTokenExpired")throw new e("Token has expired");if(d.message.includes("signature")||d.name==="JwtTokenSignatureMismatched")throw new e("Invalid token signature");if(d.message.includes("not valid yet")||d.name==="JwtTokenNotYetValid")throw new e("Token not yet valid")}throw new e("Invalid token")}let u=s;return C(u,{clockTolerance:r,issuer:t.issuer,audience:t.audience}),u}function ae(e){try{let t=decode(e);return !t||!t.header||!t.payload?null:{header:t.header,payload:t.payload}}catch{return null}}function b(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 N(e){let n=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",n),o=new Uint8Array(r);return Array.from(o).map(s=>s.toString(16).padStart(2,"0")).join("")}function ue(e){return {id:e.userId,roles:e.roles,permissions:e.permissions,metadata:{...e.metadata,apiKeyId:e.id,apiKeyName:e.name}}}function de(e,t){return e.req.header(t)||null}function le(e,t){return e.req.query(t)||null}function W(e$1){let t=e$1.headerName||"X-API-Key",n=e$1.queryParam??null,r=e$1.hashKey||N,o=e$1.extractUser||ue;return async(s,u)=>{let d=de(s,t);if(!d&&n&&(d=le(s,n)),!d)throw new e("Missing API key");let c=await r(d),y,m=e$1.lookupKey?null:k$1(s,e$1.storage);if(e$1.lookupKey)y=await e$1.lookupKey(c);else if(m)y=await m.lookup(c);else throw new i("API key auth requires lookupKey, storage, or a configured apiKeyStorage");let A=b(y),f=o(A);s.set(a.userId,f.id),s.set(a.user,f),s.set(a.roles,f.roles||[]),s.set(a.permissions,f.permissions||[]),s.set(a.authType,"api-key"),e$1.updateLastUsed?Promise.resolve(e$1.updateLastUsed(A.id)).catch(()=>{}):m&&Promise.resolve(m.updateLastUsed(A.id)).catch(()=>{}),await u();}}async function ce(e,t){let r=await(t.hashKey||N)(e),o;if(t.lookupKey)o=await t.lookupKey(r);else {let s=k$1(void 0,t.storage);if(s)o=await s.lookup(r);else throw new i("API key auth requires lookupKey, storage, or a configured apiKeyStorage")}return b(o)}function z(e$1){let t=e$1.requireAuth??true,n=e$1.skipPaths||[],r=e$1.unauthorizedMessage||"Unauthorized",o=e$1.authOrder||["jwt","api-key"],s=e$1.jwt?j(e$1.jwt):null,u=e$1.apiKey?W(e$1.apiKey):null;return async(d,c)=>{let y=d.req.path;if(p(y,n))return d.set(a.authType,"none"),c();let m=false,A=null;for(let f of o)try{if(f==="jwt"&&s&&d.req.header("Authorization")?.toLowerCase().startsWith("bearer ")){await s(d,async()=>{}),m=!0;break}if(f==="api-key"&&u){let g=e$1.apiKey?.headerName||"X-API-Key",R=e$1.apiKey?.queryParam;if(d.req.header(g)||R&&d.req.query(R)){await u(d,async()=>{}),m=!0;break}}}catch(g){A=g instanceof Error?g:new Error(String(g));}if(!m){if(t)throw A instanceof e?A:new e(r);d.set(a.authType,"none");}await c();}}function pe(e){return z({...e,requireAuth:false})}function he(e){return z({...e,requireAuth:true})}var E=class{store=new Map;async create(t){this.store.set(t.id,{...t});}async get(t){let n=this.store.get(t);if(!n)return null;if(n.status==="pending"&&Date.parse(n.expiresAt)<=Date.now()){let r={...n,status:"expired"};return this.store.set(t,r),r}return {...n}}async approve(t,n){let r=await this.get(t);if(!r)throw new Error(`Pending action ${t} not found`);if(r.status!=="pending")throw new Error(`Pending action ${t} cannot be approved from status '${r.status}'`);this.store.set(t,{...r,status:"approved",approvedBy:n,approvedAt:new Date().toISOString()});}async reject(t,n,r){let o=await this.get(t);if(!o)throw new Error(`Pending action ${t} not found`);if(o.status!=="pending")throw new Error(`Pending action ${t} cannot be rejected from status '${o.status}'`);this.store.set(t,{...o,status:"rejected",rejectedBy:n,rejectedReason:r});}clear(){this.store.clear();}};var ge=/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/;function J(e){let t=ge.exec(e);if(!t)throw new Error(`Invalid ISO 8601 duration: ${e}. Use P[nD][T[nH][nM][nS]] (years and months unsupported).`);let[,n,r,o,s]=t,u=(n?Number(n)*864e5:0)+(r?Number(r)*36e5:0)+(o?Number(o)*6e4:0)+(s?Number(s)*1e3:0);if(u===0&&e!=="PT0S"&&e!=="P0D")throw new Error(`ISO 8601 duration ${e} parsed to zero milliseconds \u2014 verify the format.`);return u}function me(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var H,Q=false;function fe(){return H||(H=new E),Q||(Q=true,b$2().warn("requireApproval: no approvalStorage configured \u2014 using process-local in-memory storage. NOT safe for multi-instance / serverless / edge-isolate deployments where phase 1 and phase 2 may hit different processes. Pass an explicit approvalStorage (e.g. PostgresApprovalStorage) for production. This warning is logged once per process.")),H}var ee=a.policies;function ye(...e$1){return async(t,n)=>{let r=t.var.user;if(!r)throw new e("Authentication required");let o=r.roles||[];if(!e$1.some(u=>o.includes(u)))throw new f("Insufficient permissions");await n();}}function Ae(...e$1){return async(t,n)=>{let r=t.var.user;if(!r)throw new e("Authentication required");let o=r.roles||[];if(!e$1.every(u=>o.includes(u)))throw new f("Insufficient permissions");await n();}}function we(...e$1){return async(t,n)=>{let r=t.var.user;if(!r)throw new e("Authentication required");let o=r.permissions||[];if(!e$1.every(u=>o.includes(u)))throw new f("Insufficient permissions");await n();}}function xe(...e$1){return async(t,n)=>{let r=t.var.user;if(!r)throw new e("Authentication required");let o=r.permissions||[];if(!e$1.some(u=>o.includes(u)))throw new f("Insufficient permissions");await n();}}function Te(e$1){return async(t,n)=>{let r=t.var.user;if(!r)throw new e("Authentication required");if(!await e$1(r,t))throw new f("Access denied");await n();}}function Ee(e$1){return async(t,n)=>{let r=t.var.user;if(!r)throw new e("Authentication required");let o=await e$1(t);if(r.id!==o)throw new f("Access denied: not resource owner");await n();}}function Re(e$1,...t){return async(n,r)=>{let o=n.var.user;if(!o)throw new e("Authentication required");let s=o.roles||[];if(t.some(c=>s.includes(c))){await r();return}let d=await e$1(n);if(o.id===d){await r();return}throw new f("Access denied")}}function ve(...e){return async(t,n)=>{for(let r of e)await r(t,async()=>{});await n();}}function Pe(...e){return async(t,n)=>{let r=null;for(let o of e)try{await o(t,async()=>{}),await n();return}catch(s){r=s instanceof Error?s:new Error(String(s));}throw r||new f("Access denied")}}function Ce(e="Access denied"){return async()=>{throw new f(e)}}function be(){return async(e,t)=>{await t();}}function ke(){return async(e$1,t)=>{if(!e$1.var.user)throw new e("Authentication required");await t();}}function Ie(e){return async(t,n)=>{b$1(t,ee,e),await n();}}function Se(e){let t=e.approvalStorage??fe(),n=e.resumeMarker??"_resume_",r=J(e.expiresAfter??"P1D"),o=z$1.object({[n]:z$1.string()}).loose();return async(s,u)=>{let d={};try{let T=await s.req.json();me(T)&&(d=T);}catch{}let c=o.safeParse(d).data?.[n];if(c){let T=await t.get(c);if(!T)throw new f(`Pending action ${c} not found`);if(T.status==="expired")throw new f(`Pending action ${c} has expired`);if(T.status!=="approved")throw new f(`Pending action ${c} is ${T.status}, cannot resume`);qe(s,T.input),await u();return}let y=a$1(s,a.userId),m=a$1(s,a.agentId),A=a$1(s,a.agentRunId),f$1=a$1(s,a.onBehalfOfUserId),g=a$1(s,a.toolCallId),R=a$1(s,a.tenantId),F=a$1(s,a.organizationId),re=a$1(s,a.actionSource)??(m?"agent-mcp":"http"),Z=Date.now(),v={id:crypto.randomUUID(),tenantId:R,organizationId:F,userId:y,actorUserId:y,onBehalfOfUserId:f$1,agentId:m,agentRunId:A,toolCallId:g,source:re,toolName:e.toolName??`${s.req.method} ${s.req.path}`,input:d,status:"pending",createdAt:new Date(Z).toISOString(),expiresAt:new Date(Z+r).toISOString(),reason:e.reason};return await t.create(v),s.json({status:"pending",actionId:v.id,expiresAt:v.expiresAt,reason:v.reason},202)}}function qe(e,t){let n=e.req,r=Promise.resolve(JSON.stringify(t));n.bodyCache?(n.bodyCache.text=r,delete n.bodyCache.parsedBody,delete n.bodyCache.json):n.bodyCache={text:r};}var Oe=["eq","ne","gt","gte","lt","lte","in","nin","like","ilike","null","between"];function wt(e){return Oe.includes(e)}function xt(e){throw new Error(`Unhandled discriminated union member: ${String(e)}`)}var Tt=["asc","desc"],Et=["any","all","phrase"],Rt=["count","sum","avg","min","max","countDistinct"];function vt(e){return e}function Pt(e){return e}var Ue=z$1.object({code:z$1.string(),message:z$1.string(),details:z$1.unknown().optional(),requestId:z$1.string().optional(),stack:z$1.string().optional()}).passthrough(),Ct=z$1.object({success:z$1.literal(false),error:Ue});function bt(e){return z$1.object({success:z$1.literal(true),result:e})}var Me=a.responseEnvelope;function te(e){return e?.var?.[Me]}function _(e,t){try{return e.req.valid(t)}catch{return}}function k(e,t,n){return e.json(t,n)}var I=class{static isRoute=true;schema={};params={};context=null;getSchema(){return this.schema}async getValidatedData(){if(!this.context)throw new Error("Context not set. Call setContext() first.");let t=this.context,n=this.getSchema(),r={};if(n.request?.body){let o=_(t,"json");if(o===void 0)try{o=await t.req.json();}catch{}o!==void 0&&(r.body=o);}if(n.request?.query){let o=_(t,"query");o===void 0&&(o=t.req.query()),o!==void 0&&(r.query=o);}if(n.request?.params){let o=_(t,"param");o===void 0&&(o=t.req.param()),o!==void 0&&(r.params=o);}return r}setContext(t){this.context=t;}getContext(){if(!this.context)throw new Error("Context not set");return this.context}json(t,n=200){return k(this.getContext(),t,n)}getResponseEnvelope(){return te(this.context)}success(t,n=200){let r=this.getResponseEnvelope(),o=r?r.success(t):{success:true,result:t};return k(this.getContext(),o,n)}successPaginated(t,n,r=200){let o=this.getResponseEnvelope(),s=o?o.success(t,n):{success:true,result:t,result_info:n};return k(this.getContext(),s,r)}runAfterResponse(t){let n=a$2(this.getContext());n?n(t):t.catch(r=>{b$2().error("Background task failed",{error:r instanceof Error?r.message:String(r)});});}error(t,n="ERROR",r=400,o){let s={code:n,message:t};o&&(s.details=o);let u=this.getResponseEnvelope(),d=u?u.error(s):{success:false,error:s};return k(this.getContext(),d,r)}};function Ot(e){return typeof e=="function"&&"isRoute"in e&&e.isRoute===true}var D=class extends I{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(r=>n.includes(r))}hasAllRoles(...t){let n=this.getUserRoles();return t.every(r=>n.includes(r))}hasPermission(t){return this.getUserPermissions().includes(t)}hasAllPermissions(...t){let n=this.getUserPermissions();return t.every(r=>n.includes(r))}hasAnyPermission(...t){let n=this.getUserPermissions();return t.some(r=>n.includes(r))}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 o=n.roles||[];if(this.requireAllRoles){if(!this.requiredRoles.every(u=>o.includes(u)))throw new f(`Required roles: ${this.requiredRoles.join(" and ")}`)}else if(!this.requiredRoles.some(u=>o.includes(u)))throw new f(`Required role: ${this.requiredRoles.join(" or ")}`)}if(this.requiredPermissions&&this.requiredPermissions.length>0){let o=n.permissions||[];if(!this.requiredPermissions.every(u=>o.includes(u)))throw new f(`Required permissions: ${this.requiredPermissions.join(", ")}`)}if(!await this.authorize(n,t))throw new f("Access denied")}getSchema(){let t=super.getSchema(),n=this.requiresAuth?[{bearerAuth:[]}]:void 0,r={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?r:{}}}}};function Ke(e$1){class t extends e$1{requiresAuth=true;requiredRoles;requiredPermissions;requireAllRoles=false;async authorize(r,o){return true}getUser(){let o=this.getContext().var.user;if(!o)throw new e("Authentication required");return o}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(r){let o=this.getUserOrNull();return o?(o.roles||[]).includes(r):false}hasAnyRole(...r){let o=this.getUserOrNull()?.roles||[];return r.some(s=>o.includes(s))}hasAllRoles(...r){let o=this.getUserOrNull()?.roles||[];return r.every(s=>o.includes(s))}hasPermission(r){let o=this.getUserOrNull();return o?(o.permissions||[]).includes(r):false}hasAllPermissions(...r){let o=this.getUserOrNull()?.permissions||[];return r.every(s=>o.includes(s))}hasAnyPermission(...r){let o=this.getUserOrNull()?.permissions||[];return r.some(s=>o.includes(s))}async enforceAuth(){let r=this.getContext();if(this.requiresAuth&&!r.var.user)throw new e("Authentication required");let o=r.var.user;if(!o)return;if(this.requiredRoles&&this.requiredRoles.length>0){let u=o.roles||[];if(this.requireAllRoles){if(!this.requiredRoles.every(c=>u.includes(c)))throw new f(`Required roles: ${this.requiredRoles.join(" and ")}`)}else if(!this.requiredRoles.some(c=>u.includes(c)))throw new f(`Required role: ${this.requiredRoles.join(" or ")}`)}if(this.requiredPermissions&&this.requiredPermissions.length>0){let u=o.permissions||[];if(!this.requiredPermissions.every(c=>u.includes(c)))throw new f(`Required permissions: ${this.requiredPermissions.join(", ")}`)}if(!await this.authorize(o,r))throw new f("Access denied")}getSchema(){let r=super.getSchema(),o=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 {...r,security:o,responses:{...r.responses,...this.requiresAuth?s:{}}}}}return t}export{ve as A,Pe as B,Ce as C,be as D,ke as E,Ie as F,Se as G,O as H,U as I,ne as J,M as K,C as L,oe as M,j as N,ie as O,ae as P,b as Q,N as R,W as S,ce as T,z as U,pe as V,he as W,D as X,Ke as Y,Oe as a,wt as b,xt as c,Tt as d,Et as e,Rt as f,vt as g,Pt as h,Ue as i,Ct as j,bt as k,Me as l,te as m,k as n,I as o,Ot as p,E as q,J as r,ee as s,ye as t,Ae as u,we as v,xe as w,Te as x,Ee as y,Re as z};
@@ -0,0 +1 @@
1
+ import {b as b$1}from'./chunk-EX4S3Q4M.js';import {o}from'./chunk-OCJC5XWY.js';import {a}from'./chunk-6GO5LUOZ.js';function b(i,e){return !i||!i.enabled?{enabled:false,field:"version",historyTable:`${e}_history`,maxVersions:null,trackChangedBy:false,excludeFields:[]}:{enabled:true,field:i.field||"version",historyTable:i.historyTable||`${e}_history`,maxVersions:i.maxVersions??null,trackChangedBy:i.trackChangedBy??false,excludeFields:i.excludeFields||[],getUserId:i.getUserId}}var y=class{versions=new Map;getKey(e,r){return `${e}:${r}`}async store(e,r){let n=this.getKey(e,r.recordId),t=this.versions.get(n)||[];t.push({...r,tableName:e}),this.versions.set(n,t);}async getByRecordId(e,r,n){let t=this.getKey(e,r),o=[...this.versions.get(t)||[]].sort((u,a)=>a.version-u.version),g=n?.offset||0,l=n?.limit||o.length;return o.slice(g,g+l)}async getVersion(e,r,n){let t=this.getKey(e,r);return (this.versions.get(t)||[]).find(o=>o.version===n)||null}async getLatestVersion(e,r){let n=this.getKey(e,r),t=this.versions.get(n)||[];return t.length===0?0:Math.max(...t.map(s=>s.version))}async pruneVersions(e,r,n){let t=this.getKey(e,r),s=this.versions.get(t)||[];if(s.length<=n)return 0;let o=[...s].sort((u,a)=>a.version-u.version),g=o.slice(0,n),l=o.length-g.length;return this.versions.set(t,g),l}async deleteAllVersions(e,r){let n=this.getKey(e,r),s=(this.versions.get(n)||[]).length;return this.versions.delete(n),s}getAllVersions(){let e=[];for(let r of this.versions.values())e.push(...r);return e}clear(){this.versions.clear();}},m=o({contextKey:a.versioningStorage,defaultFactory:()=>new y}),P=m.registry,w=m.set,E=m.get,k=m.getRequired,h=class{config;storage;tableName;constructor(e,r,n,t){this.config=b(e,r),this.tableName=r,this.storage=m.resolve(t,n);}getStorage(){if(!this.storage)throw new Error("Versioning storage not configured. Pass storage explicitly or inject versioningStorage with createStorageMiddleware().");return this.storage}isEnabled(){return this.config.enabled}getVersionField(){return this.config.field}getHistoryTable(){return this.config.historyTable}async saveVersion(e,r,n,t,s){if(!this.isEnabled())return r[this.config.field]||1;let o=r[this.config.field]||0,g=o+1,l;n&&(l=b$1(n,r,this.config.excludeFields));let u=this.filterFields(r),a={id:crypto.randomUUID(),recordId:e,version:o,data:u,createdAt:new Date,changes:l};this.config.trackChangedBy&&t&&(a.changedBy=t),s&&(a.changeReason=s);let c=this.getStorage();return await c.store(this.tableName,a),this.config.maxVersions&&c.pruneVersions&&await c.pruneVersions(this.tableName,e,this.config.maxVersions),g}async getVersions(e,r){return this.getStorage().getByRecordId(this.tableName,e,r)}async getVersion(e,r){return this.getStorage().getVersion(this.tableName,e,r)}async getVersionData(e,r){let n=await this.getVersion(e,r);return n?n.data:null}async getLatestVersion(e){return this.getStorage().getLatestVersion(this.tableName,e)}async compareVersions(e,r,n){let[t,s]=await Promise.all([this.getVersion(e,r),this.getVersion(e,n)]);return !t||!s?[]:b$1(t.data,s.data,this.config.excludeFields)}async deleteAllVersions(e){let r=this.getStorage();return r.deleteAllVersions?r.deleteAllVersions(this.tableName,e):0}filterFields(e){if(this.config.excludeFields.length===0)return e;let r={};for(let[n,t]of Object.entries(e))this.config.excludeFields.includes(n)||(r[n]=t);return r}};function N(i,e,r,n){return new h(i,e,r,n)}export{b as a,y as b,P as c,w as d,E as e,k as f,h as g,N as h};